title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
Fetch random rows from a table with MySQL
For this, you can use a PREPARE statement. Let us first create a table − mysql> create table DemoTable( FirstName varchar(100), CountryName varchar(100) ); Query OK, 0 rows affected (0.53 sec) Insert some records in the table using insert command − mysql> insert into DemoTable values('Adam','US'); Query OK, 1 row affected (0.15 sec) mysql> insert into DemoTable values('Chris','AUS'); Query OK, 1 row affected (0.15 sec) mysql> insert into DemoTable values('Robert','UK'); Query OK, 1 row affected (0.32 sec) Display all records from the table using select statement − mysql> select *from DemoTable; This will produce the following output − +-----------+-------------+ | FirstName | CountryName | +-----------+-------------+ | Adam | US | | Chris | AUS | | Robert | UK | +-----------+-------------+ 3 rows in set (0.00 sec) Following is the query to fetch random rows in a single query − mysql> set @value := ROUND((select count(*) from DemoTable) * rand()); Query OK, 0 rows affected (0.00 sec) mysql> set @query := CONCAT('select *from DemoTable LIMIT ', @value , ', 1'); Query OK, 0 rows affected (0.00 sec) mysql> prepare myStatement from @query ; Query OK, 0 rows affected (0.00 sec) Statement prepared mysql> execute myStatement; +-----------+-------------+ | FirstName | CountryName | +-----------+-------------+ | Chris | AUS | +-----------+-------------+ 1 row in set (0.00 sec) mysql> deallocate prepare myStatement; Query OK, 0 rows affected (0.00 sec)
[ { "code": null, "e": 1135, "s": 1062, "text": "For this, you can use a PREPARE statement. Let us first create a table −" }, { "code": null, "e": 1261, "s": 1135, "text": "mysql> create table DemoTable(\n FirstName varchar(100),\n CountryName varchar(100)\n);\nQuery OK, 0 rows affected (0.53 sec)" }, { "code": null, "e": 1317, "s": 1261, "text": "Insert some records in the table using insert command −" }, { "code": null, "e": 1579, "s": 1317, "text": "mysql> insert into DemoTable values('Adam','US');\nQuery OK, 1 row affected (0.15 sec)\nmysql> insert into DemoTable values('Chris','AUS');\nQuery OK, 1 row affected (0.15 sec)\nmysql> insert into DemoTable values('Robert','UK');\nQuery OK, 1 row affected (0.32 sec)" }, { "code": null, "e": 1639, "s": 1579, "text": "Display all records from the table using select statement −" }, { "code": null, "e": 1670, "s": 1639, "text": "mysql> select *from DemoTable;" }, { "code": null, "e": 1711, "s": 1670, "text": "This will produce the following output −" }, { "code": null, "e": 1933, "s": 1711, "text": "+-----------+-------------+\n| FirstName | CountryName |\n+-----------+-------------+\n| Adam | US |\n| Chris | AUS |\n| Robert | UK | \n+-----------+-------------+\n3 rows in set (0.00 sec)" }, { "code": null, "e": 1997, "s": 1933, "text": "Following is the query to fetch random rows in a single query −" }, { "code": null, "e": 2585, "s": 1997, "text": "mysql> set @value := ROUND((select count(*) from DemoTable) * rand());\nQuery OK, 0 rows affected (0.00 sec)\nmysql> set @query := CONCAT('select *from DemoTable LIMIT ', @value , ', 1');\nQuery OK, 0 rows affected (0.00 sec)\nmysql> prepare myStatement from @query ;\nQuery OK, 0 rows affected (0.00 sec)\nStatement prepared\nmysql> execute myStatement;\n+-----------+-------------+\n| FirstName | CountryName |\n+-----------+-------------+\n| Chris | AUS |\n+-----------+-------------+\n1 row in set (0.00 sec)\nmysql> deallocate prepare myStatement;\nQuery OK, 0 rows affected (0.00 sec)" } ]
Working with Numpy Arrays: Indexing | by Kurtis Pykes | Towards Data Science
PyTrix will now be a weekly series where I present cool things that can be done in Python that are useful for Data Scientist. The last PyTrix tutorial can be found in the link below... towardsdatascience.com Link for the Github Repository below: github.com First, let’s start by explaining Numpy. Numpy is the de-facto library for scientific programming and is so commonly used amongst practitioners that it has its own standard when we import it — import numpy as np . The Numpy framework provides us with a high-performance multidimensional array object, as well as useful tools to manipulate the arrays. On that note, we can describe numpy arrays as a grid of the same type values that is indexed via a tuple of non-negative integers. We distinguish the number dimensions by the rank of the array. Additionally, the shape of the array is a tuple of integers that represent the size of the array along each of its dimensions. Note: If you aren’t familiar with the rank terminology, in the link below Steven Steinke has an fantastic explanation. medium.com However, today’s series of PyTrix is about indexing arrays, therefore without further ado, let’s get into it! The process of extracting individual elements, rows, columns or planes from multi-dimensional arrays is referred to as indexing. There are multiple occasions in which we may wish to obtain some value(s) from an array during our Data Science projects. Depending on the dimension (or rank) of the matrix, we’d have to adopt various strategies to effectively perform this task. For those that would like to read more about the np.array() class, the Documentation can be found here! In the first example I will initialize a 1-D numpy array and print it: Note: Assume the import for numpy from the previous section has been done numbers= [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]a= np.array(numbers)print(a)>>>> [ 1 2 3 4 5 6 7 8 9 10] To access the elements within the array, we follow the exact same conventions for indexing into a normal python list or tuple data type: print(f"Index 0: {a[0]}\nIndex 5: {a[5]}\nIndex 7: {a[7]}")>>>> Index 0: 1 Index 5: 6 Index 7: 8 Next, we will instantiate a 2 dimensional numpy array from a list of list. We already have one list initialized as numbers, we would have to create one more. big_numbers= [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]b= np.array([numbers, big_numbers])print(b)>>>> [[ 1 2 3 4 5 6 7 8 9 10] [ 10 20 30 40 50 60 70 80 90 100]] If we’d like to extract a single element from the 2-D array, we must first select the index, i, which is a pointer to the row of the matrix, then index, j, to select the column. print(b[1, 4]) >>>> 50 This denotes that we selected row 1 and column 4 from our array. I know my readers are very curious people. Therefore, you may be wondering what happens when you just pass the i index to our list... print(b[0]) >>>> [ 1 2 3 4 5 6 7 8 9 10] This returned the row vector at index 0. A Rank 1 array. What if we want to access a column vector? print(b[:, 8])>>>> [ 9 90] The : tells python that we we should take every row and we have broken it up with a “,” and 8 to tell python to take the rows only from column 8. However, we are getting slightly ahead of ourselves as this ties into slicing, which we will be discussing in next weeks PyTrix :). Note: When we index or slice a numpy array, the same data is returned as a view of the original array, however accessed in the order that we have declared from the index or slice. If a 2-D array can be instantiated with a list of list, then... you guessed it. A 3-D array is instantiated with a list of list of list — take a moment to let that sink in. c= np.array([[[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]]])print(c)>>>> [[[ 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]]] We may think of a 3-D array as a stack of matrices where the first index, i, selects the matrix. The second index, j, selects the row and the third index, k, selects the column. For example we will select the first matrix: print(c[0])>>>> [[1 2 3] [4 5 6] [7 8 9]] and if we want to select an individual element in the array, it is done as follows: print(c[2, 1, 1])>>>> 23 To explain the above code, we printed from our 3-D array from matrix at index 2 , the row index 1, and column index 1. I will break access of rows or columns into 3 scenarios for 3-D arrays. Scenario 1: When we only specify the matrix, i and row ,j, this will in-turn return a specific row from the matrix we have selected. print(c[0, 0]) >>>> [1 2 3] This returned the matrix at index 0 and the row at index 0. Scenario 2: When we want to access the column elements of a specific matrix, we fill the jth index with : to denote we want a full slice (all of the rows). print(c[1, :, 2])>>>> [12 15 18] This returned all the rows from matrix 1 that are in column index 2. Scenario 3: Occasionally, we may want to access a value in the same row and column for each index. print(c[:, 2, 0])>>>> [ 7 16 25] This a list of each element in row index 2 and column index 0 for each matrix. There are many options to indexing and learning them is a very set of skills that will be handy in your Data Science toolkit. For more on Indexing you can read the numpy Documentation which goes into indexing in great depth. See the link below for access to the code used in this story. github.com If there is anything that you think I have missed, something that you’d like to point out to me, or if you are still unsure about something, your feedback is valuable. Send a response! However, If you’d like to get in contact with me, I am most active on LinkedIn and I’d love to connect with you also. www.linkedin.com Here are some of my most recent work that you may also be interested in:
[ { "code": null, "e": 357, "s": 172, "text": "PyTrix will now be a weekly series where I present cool things that can be done in Python that are useful for Data Scientist. The last PyTrix tutorial can be found in the link below..." }, { "code": null, "e": 380, "s": 357, "text": "towardsdatascience.com" }, { "code": null, "e": 418, "s": 380, "text": "Link for the Github Repository below:" }, { "code": null, "e": 429, "s": 418, "text": "github.com" }, { "code": null, "e": 642, "s": 429, "text": "First, let’s start by explaining Numpy. Numpy is the de-facto library for scientific programming and is so commonly used amongst practitioners that it has its own standard when we import it — import numpy as np ." }, { "code": null, "e": 910, "s": 642, "text": "The Numpy framework provides us with a high-performance multidimensional array object, as well as useful tools to manipulate the arrays. On that note, we can describe numpy arrays as a grid of the same type values that is indexed via a tuple of non-negative integers." }, { "code": null, "e": 1100, "s": 910, "text": "We distinguish the number dimensions by the rank of the array. Additionally, the shape of the array is a tuple of integers that represent the size of the array along each of its dimensions." }, { "code": null, "e": 1219, "s": 1100, "text": "Note: If you aren’t familiar with the rank terminology, in the link below Steven Steinke has an fantastic explanation." }, { "code": null, "e": 1230, "s": 1219, "text": "medium.com" }, { "code": null, "e": 1340, "s": 1230, "text": "However, today’s series of PyTrix is about indexing arrays, therefore without further ado, let’s get into it!" }, { "code": null, "e": 1469, "s": 1340, "text": "The process of extracting individual elements, rows, columns or planes from multi-dimensional arrays is referred to as indexing." }, { "code": null, "e": 1715, "s": 1469, "text": "There are multiple occasions in which we may wish to obtain some value(s) from an array during our Data Science projects. Depending on the dimension (or rank) of the matrix, we’d have to adopt various strategies to effectively perform this task." }, { "code": null, "e": 1819, "s": 1715, "text": "For those that would like to read more about the np.array() class, the Documentation can be found here!" }, { "code": null, "e": 1890, "s": 1819, "text": "In the first example I will initialize a 1-D numpy array and print it:" }, { "code": null, "e": 1964, "s": 1890, "text": "Note: Assume the import for numpy from the previous section has been done" }, { "code": null, "e": 2069, "s": 1964, "text": "numbers= [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]a= np.array(numbers)print(a)>>>> [ 1 2 3 4 5 6 7 8 9 10]" }, { "code": null, "e": 2206, "s": 2069, "text": "To access the elements within the array, we follow the exact same conventions for indexing into a normal python list or tuple data type:" }, { "code": null, "e": 2311, "s": 2206, "text": "print(f\"Index 0: {a[0]}\\nIndex 5: {a[5]}\\nIndex 7: {a[7]}\")>>>> Index 0: 1 Index 5: 6 Index 7: 8" }, { "code": null, "e": 2469, "s": 2311, "text": "Next, we will instantiate a 2 dimensional numpy array from a list of list. We already have one list initialized as numbers, we would have to create one more." }, { "code": null, "e": 2662, "s": 2469, "text": "big_numbers= [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]b= np.array([numbers, big_numbers])print(b)>>>> [[ 1 2 3 4 5 6 7 8 9 10] [ 10 20 30 40 50 60 70 80 90 100]]" }, { "code": null, "e": 2840, "s": 2662, "text": "If we’d like to extract a single element from the 2-D array, we must first select the index, i, which is a pointer to the row of the matrix, then index, j, to select the column." }, { "code": null, "e": 2863, "s": 2840, "text": "print(b[1, 4]) >>>> 50" }, { "code": null, "e": 2928, "s": 2863, "text": "This denotes that we selected row 1 and column 4 from our array." }, { "code": null, "e": 3062, "s": 2928, "text": "I know my readers are very curious people. Therefore, you may be wondering what happens when you just pass the i index to our list..." }, { "code": null, "e": 3111, "s": 3062, "text": "print(b[0]) >>>> [ 1 2 3 4 5 6 7 8 9 10]" }, { "code": null, "e": 3211, "s": 3111, "text": "This returned the row vector at index 0. A Rank 1 array. What if we want to access a column vector?" }, { "code": null, "e": 3238, "s": 3211, "text": "print(b[:, 8])>>>> [ 9 90]" }, { "code": null, "e": 3516, "s": 3238, "text": "The : tells python that we we should take every row and we have broken it up with a “,” and 8 to tell python to take the rows only from column 8. However, we are getting slightly ahead of ourselves as this ties into slicing, which we will be discussing in next weeks PyTrix :)." }, { "code": null, "e": 3696, "s": 3516, "text": "Note: When we index or slice a numpy array, the same data is returned as a view of the original array, however accessed in the order that we have declared from the index or slice." }, { "code": null, "e": 3869, "s": 3696, "text": "If a 2-D array can be instantiated with a list of list, then... you guessed it. A 3-D array is instantiated with a list of list of list — take a moment to let that sink in." }, { "code": null, "e": 4207, "s": 3869, "text": "c= np.array([[[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]]])print(c)>>>> [[[ 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]]]" }, { "code": null, "e": 4385, "s": 4207, "text": "We may think of a 3-D array as a stack of matrices where the first index, i, selects the matrix. The second index, j, selects the row and the third index, k, selects the column." }, { "code": null, "e": 4430, "s": 4385, "text": "For example we will select the first matrix:" }, { "code": null, "e": 4482, "s": 4430, "text": "print(c[0])>>>> [[1 2 3] [4 5 6] [7 8 9]]" }, { "code": null, "e": 4566, "s": 4482, "text": "and if we want to select an individual element in the array, it is done as follows:" }, { "code": null, "e": 4591, "s": 4566, "text": "print(c[2, 1, 1])>>>> 23" }, { "code": null, "e": 4710, "s": 4591, "text": "To explain the above code, we printed from our 3-D array from matrix at index 2 , the row index 1, and column index 1." }, { "code": null, "e": 4782, "s": 4710, "text": "I will break access of rows or columns into 3 scenarios for 3-D arrays." }, { "code": null, "e": 4915, "s": 4782, "text": "Scenario 1: When we only specify the matrix, i and row ,j, this will in-turn return a specific row from the matrix we have selected." }, { "code": null, "e": 4943, "s": 4915, "text": "print(c[0, 0]) >>>> [1 2 3]" }, { "code": null, "e": 5003, "s": 4943, "text": "This returned the matrix at index 0 and the row at index 0." }, { "code": null, "e": 5159, "s": 5003, "text": "Scenario 2: When we want to access the column elements of a specific matrix, we fill the jth index with : to denote we want a full slice (all of the rows)." }, { "code": null, "e": 5192, "s": 5159, "text": "print(c[1, :, 2])>>>> [12 15 18]" }, { "code": null, "e": 5261, "s": 5192, "text": "This returned all the rows from matrix 1 that are in column index 2." }, { "code": null, "e": 5360, "s": 5261, "text": "Scenario 3: Occasionally, we may want to access a value in the same row and column for each index." }, { "code": null, "e": 5393, "s": 5360, "text": "print(c[:, 2, 0])>>>> [ 7 16 25]" }, { "code": null, "e": 5472, "s": 5393, "text": "This a list of each element in row index 2 and column index 0 for each matrix." }, { "code": null, "e": 5697, "s": 5472, "text": "There are many options to indexing and learning them is a very set of skills that will be handy in your Data Science toolkit. For more on Indexing you can read the numpy Documentation which goes into indexing in great depth." }, { "code": null, "e": 5759, "s": 5697, "text": "See the link below for access to the code used in this story." }, { "code": null, "e": 5770, "s": 5759, "text": "github.com" }, { "code": null, "e": 5955, "s": 5770, "text": "If there is anything that you think I have missed, something that you’d like to point out to me, or if you are still unsure about something, your feedback is valuable. Send a response!" }, { "code": null, "e": 6073, "s": 5955, "text": "However, If you’d like to get in contact with me, I am most active on LinkedIn and I’d love to connect with you also." }, { "code": null, "e": 6090, "s": 6073, "text": "www.linkedin.com" } ]
Prim's algorithm in Javascript
Prim's algorithm is a greedy algorithm that finds a minimum spanning tree for a weighted undirected graph. It finds a subset of the edges that forms a tree that includes every vertex, where the total weight of all the edges in the tree is minimized. The algorithm operates by building this tree one vertex at a time, from an arbitrary starting vertex, at each step adding the cheapest possible connection from the tree to another vertex. Let us look at an illustration of how Prim's algorithm works − 1. Choose any arbitrary node as the root node: In this case, we choose S node as the root node of Prim's spanning tree. This node is arbitrarily chosen, so any node can be the root node. One may wonder why any video can be a root node. So the answer is, in the spanning tree all the nodes of a graph are included and because it is connected then there must be at least one edge, which will join it to the rest of the tree. 2. Check outgoing edges and select the one with less cost: After choosing the root node S, we see that S, A, and S, C are two edges with weight 7 and 8, respectively. We choose the edge S, A as it is lesser than the other. Now, the tree S-7-A is treated as one node and we check for all edges going out from it. We select the one which has the lowest cost and include it in the tree. After this step, the S-7-A-3-C tree is formed. Now we'll again treat it as a node and will check all the edges again. However, we will choose only the least cost edge. In this case, C-3-D is the new edge, which is less than other edges' cost 8, 6, 4, etc. After adding node D to the spanning tree, we now have two edges going out of it having the same cost, i.e. D-2-T and D-2-B. Thus, we can add either one. But the next step will again yield edge 2 as the least cost. Hence, we are showing a spanning tree with both edges included. Now let us see how we can implement the same in our code − primsMST() { // Initialize graph that'll contain the MST const MST = new Graph(); if (this.nodes.length === 0) { return MST; } // Select first node as starting node let s = this.nodes[0]; // Create a Priority Queue and explored set let edgeQueue = new PriorityQueue(this.nodes.length * this.nodes.length); let explored = new Set(); explored.add(s); MST.addNode(s); // Add all edges from this starting node to the PQ taking weights as priority this.edges[s].forEach(edge => { edgeQueue.enqueue([s, edge.node], edge.weight); }); // Take the smallest edge and add that to the new graph let currentMinEdge = edgeQueue.dequeue(); while (!edgeQueue.isEmpty()) { // COntinue removing edges till we get an edge with an unexplored node while (!edgeQueue.isEmpty() && explored.has(currentMinEdge.data[1])) { currentMinEdge = edgeQueue.dequeue(); } let nextNode = currentMinEdge.data[1]; // Check again as queue might get empty without giving back unexplored element if (!explored.has(nextNode)) { MST.addNode(nextNode); MST.addEdge(currentMinEdge.data[0], nextNode, currentMinEdge.priority); // Again add all edges to the PQ this.edges[nextNode].forEach(edge => { edgeQueue.enqueue([nextNode, edge.node], edge.weight); }); // Mark this node as explored explored.add(nextNode); s = nextNode; } } return MST; } You can test this using: let g = new Graph(); g.addNode("A"); g.addNode("B"); g.addNode("C"); g.addNode("D"); g.addNode("E"); g.addNode("F"); g.addNode("G"); g.addEdge("A", "C", 100); g.addEdge("A", "B", 3); g.addEdge("A", "D", 4); g.addEdge("C", "D", 3); g.addEdge("D", "E", 8); g.addEdge("E", "F", 10); g.addEdge("B", "G", 9); g.primsMST().display(); This will give the output − A->B, D B->A, G D->A, C, E C->D E->D, F G->B F->E Note that our Initial graph was − /** * A * / | \ * C | B * \ | | * D G * | / * E * | * F */ Our current graph looks like − /** * A * |\ * C | B * \ | | * D G * | * E * | * F * */ We've removed the costliest edges and now have a spanning tree.
[ { "code": null, "e": 1312, "s": 1062, "text": "Prim's algorithm is a greedy algorithm that finds a minimum spanning tree for a weighted undirected graph. It finds a subset of the edges that forms a tree that includes every vertex, where the total weight of all the edges in the tree is minimized." }, { "code": null, "e": 1500, "s": 1312, "text": "The algorithm operates by building this tree one vertex at a time, from an arbitrary starting vertex, at each step adding the cheapest possible connection from the tree to another vertex." }, { "code": null, "e": 1563, "s": 1500, "text": "Let us look at an illustration of how Prim's algorithm works −" }, { "code": null, "e": 1986, "s": 1563, "text": "1. Choose any arbitrary node as the root node: In this case, we choose S node as the root node of Prim's spanning tree. This node is arbitrarily chosen, so any node can be the root node. One may wonder why any video can be a root node. So the answer is, in the spanning tree all the nodes of a graph are included and because it is connected then there must be at least one edge, which will join it to the rest of the tree." }, { "code": null, "e": 2209, "s": 1986, "text": "2. Check outgoing edges and select the one with less cost: After choosing the root node S, we see that S, A, and S, C are two edges with weight 7 and 8, respectively. We choose the edge S, A as it is lesser than the other." }, { "code": null, "e": 2370, "s": 2209, "text": "Now, the tree S-7-A is treated as one node and we check for all edges going out from it. We select the one which has the lowest cost and include it in the tree." }, { "code": null, "e": 2626, "s": 2370, "text": "After this step, the S-7-A-3-C tree is formed. Now we'll again treat it as a node and will check all the edges again. However, we will choose only the least cost edge. In this case, C-3-D is the new edge, which is less than other edges' cost 8, 6, 4, etc." }, { "code": null, "e": 2904, "s": 2626, "text": "After adding node D to the spanning tree, we now have two edges going out of it having the same cost, i.e. D-2-T and D-2-B. Thus, we can add either one. But the next step will again yield edge 2 as the least cost. Hence, we are showing a spanning tree with both edges included." }, { "code": null, "e": 2963, "s": 2904, "text": "Now let us see how we can implement the same in our code −" }, { "code": null, "e": 4471, "s": 2963, "text": "primsMST() {\n // Initialize graph that'll contain the MST\n const MST = new Graph();\n if (this.nodes.length === 0) {\n return MST;\n }\n\n\n // Select first node as starting node\n let s = this.nodes[0];\n\n\n // Create a Priority Queue and explored set\n let edgeQueue = new PriorityQueue(this.nodes.length * this.nodes.length);\n let explored = new Set();\n explored.add(s);\n MST.addNode(s);\n\n\n // Add all edges from this starting node to the PQ taking weights as priority\n this.edges[s].forEach(edge => {\n edgeQueue.enqueue([s, edge.node], edge.weight);\n });\n\n\n // Take the smallest edge and add that to the new graph\n let currentMinEdge = edgeQueue.dequeue();\n while (!edgeQueue.isEmpty()) {\n\n\n // COntinue removing edges till we get an edge with an unexplored node\n while (!edgeQueue.isEmpty() && explored.has(currentMinEdge.data[1])) {\n currentMinEdge = edgeQueue.dequeue();\n }\n let nextNode = currentMinEdge.data[1];\n\n\n // Check again as queue might get empty without giving back unexplored element\n if (!explored.has(nextNode)) {\n MST.addNode(nextNode);\n MST.addEdge(currentMinEdge.data[0], nextNode, currentMinEdge.priority);\n // Again add all edges to the PQ\n this.edges[nextNode].forEach(edge => {\n edgeQueue.enqueue([nextNode, edge.node], edge.weight);\n });\n\n\n // Mark this node as explored explored.add(nextNode);\n s = nextNode;\n }\n }\n return MST;\n}" }, { "code": null, "e": 4496, "s": 4471, "text": "You can test this using:" }, { "code": null, "e": 4826, "s": 4496, "text": "let g = new Graph();\ng.addNode(\"A\");\ng.addNode(\"B\");\ng.addNode(\"C\");\ng.addNode(\"D\");\ng.addNode(\"E\");\ng.addNode(\"F\");\ng.addNode(\"G\");\n\n\ng.addEdge(\"A\", \"C\", 100);\ng.addEdge(\"A\", \"B\", 3);\ng.addEdge(\"A\", \"D\", 4);\ng.addEdge(\"C\", \"D\", 3);\ng.addEdge(\"D\", \"E\", 8);\ng.addEdge(\"E\", \"F\", 10);\ng.addEdge(\"B\", \"G\", 9);\ng.primsMST().display();" }, { "code": null, "e": 4854, "s": 4826, "text": "This will give the output −" }, { "code": null, "e": 4904, "s": 4854, "text": "A->B, D\nB->A, G\nD->A, C, E\nC->D\nE->D, F\nG->B\nF->E" }, { "code": null, "e": 4938, "s": 4904, "text": "Note that our Initial graph was −" }, { "code": null, "e": 5090, "s": 4938, "text": "/**\n * A\n * / | \\\n * C | B\n * \\ | |\n * D G\n * | /\n * E\n * |\n * F\n*/" }, { "code": null, "e": 5121, "s": 5090, "text": "Our current graph looks like −" }, { "code": null, "e": 5267, "s": 5121, "text": "/**\n * A\n * |\\\n * C | B\n * \\ | |\n * D G\n * |\n * E\n * |\n * F\n *\n*/" }, { "code": null, "e": 5331, "s": 5267, "text": "We've removed the costliest edges and now have a spanning tree." } ]
Program to find length of longest strictly increasing then decreasing sublist in Python
Suppose we have a list of numbers called nums. We have to find the length of the longest sublist such that (minimum length 3) its values are strictly increasing and then decreasing. So, if the input is like nums = [7, 1, 3, 5, 2, 0], then the output will be 5, as the sublist is [2, 4, 6, 3, 1] is strictly increasing then decreasing. To solve this, we will follow these steps − i := 0, n := size of a, res := -infinity while i < n - 2, dost := ilinc := 0, ldec := 0while i < n - 1 and a[i] < a[i + 1], dolinc := linc + 1i := i + 1while i < n - 1 and a[i] > a[i + 1], doldec := ldec + 1i := i + 1if linc > 0 and ldec > 0, thenres := maximum of res and (i - st + 1)while i < n - 1 and a[i] is same as a[i + 1], doi := i + 1 st := i linc := 0, ldec := 0 while i < n - 1 and a[i] < a[i + 1], dolinc := linc + 1i := i + 1 linc := linc + 1 i := i + 1 while i < n - 1 and a[i] > a[i + 1], doldec := ldec + 1i := i + 1 ldec := ldec + 1 i := i + 1 if linc > 0 and ldec > 0, thenres := maximum of res and (i - st + 1) res := maximum of res and (i - st + 1) while i < n - 1 and a[i] is same as a[i + 1], doi := i + 1 i := i + 1 return res if res >= 0 otherwise 0 Let us see the following implementation to get better understanding − Live Demo class Solution: def solve(self, a): i, n, res = 0, len(a), float("-inf") while i < n - 2: st = i linc, ldec = 0, 0 while i < n - 1 and a[i] < a[i + 1]: linc += 1 i += 1 while i < n - 1 and a[i] > a[i + 1]: ldec += 1 i += 1 if linc > 0 and ldec > 0: res = max(res, i - st + 1) while i < n - 1 and a[i] == a[i + 1]: i += 1 return res if res >= 0 else 0 ob = Solution() nums = [8, 2, 4, 6, 3, 1] print(ob.solve(nums)) [[8, 2, 4, 6, 3, 1] 5
[ { "code": null, "e": 1244, "s": 1062, "text": "Suppose we have a list of numbers called nums. We have to find the length of the longest sublist such that (minimum length 3) its values are strictly increasing and then decreasing." }, { "code": null, "e": 1397, "s": 1244, "text": "So, if the input is like nums = [7, 1, 3, 5, 2, 0], then the output will be 5, as the sublist is [2, 4, 6, 3, 1] is strictly increasing then decreasing." }, { "code": null, "e": 1441, "s": 1397, "text": "To solve this, we will follow these steps −" }, { "code": null, "e": 1482, "s": 1441, "text": "i := 0, n := size of a, res := -infinity" }, { "code": null, "e": 1785, "s": 1482, "text": "while i < n - 2, dost := ilinc := 0, ldec := 0while i < n - 1 and a[i] < a[i + 1], dolinc := linc + 1i := i + 1while i < n - 1 and a[i] > a[i + 1], doldec := ldec + 1i := i + 1if linc > 0 and ldec > 0, thenres := maximum of res and (i - st + 1)while i < n - 1 and a[i] is same as a[i + 1], doi := i + 1" }, { "code": null, "e": 1793, "s": 1785, "text": "st := i" }, { "code": null, "e": 1814, "s": 1793, "text": "linc := 0, ldec := 0" }, { "code": null, "e": 1880, "s": 1814, "text": "while i < n - 1 and a[i] < a[i + 1], dolinc := linc + 1i := i + 1" }, { "code": null, "e": 1897, "s": 1880, "text": "linc := linc + 1" }, { "code": null, "e": 1908, "s": 1897, "text": "i := i + 1" }, { "code": null, "e": 1974, "s": 1908, "text": "while i < n - 1 and a[i] > a[i + 1], doldec := ldec + 1i := i + 1" }, { "code": null, "e": 1991, "s": 1974, "text": "ldec := ldec + 1" }, { "code": null, "e": 2002, "s": 1991, "text": "i := i + 1" }, { "code": null, "e": 2071, "s": 2002, "text": "if linc > 0 and ldec > 0, thenres := maximum of res and (i - st + 1)" }, { "code": null, "e": 2110, "s": 2071, "text": "res := maximum of res and (i - st + 1)" }, { "code": null, "e": 2169, "s": 2110, "text": "while i < n - 1 and a[i] is same as a[i + 1], doi := i + 1" }, { "code": null, "e": 2180, "s": 2169, "text": "i := i + 1" }, { "code": null, "e": 2215, "s": 2180, "text": "return res if res >= 0 otherwise 0" }, { "code": null, "e": 2285, "s": 2215, "text": "Let us see the following implementation to get better understanding −" }, { "code": null, "e": 2296, "s": 2285, "text": " Live Demo" }, { "code": null, "e": 2858, "s": 2296, "text": "class Solution:\n def solve(self, a):\n i, n, res = 0, len(a), float(\"-inf\")\n while i < n - 2:\n st = i\n linc, ldec = 0, 0\n while i < n - 1 and a[i] < a[i + 1]:\n linc += 1\n i += 1\n while i < n - 1 and a[i] > a[i + 1]:\n ldec += 1\n i += 1\n if linc > 0 and ldec > 0:\n res = max(res, i - st + 1)\n while i < n - 1 and a[i] == a[i + 1]:\n i += 1\n return res if res >= 0 else 0\nob = Solution()\nnums = [8, 2, 4, 6, 3, 1]\nprint(ob.solve(nums))" }, { "code": null, "e": 2878, "s": 2858, "text": "[[8, 2, 4, 6, 3, 1]" }, { "code": null, "e": 2880, "s": 2878, "text": "5" } ]
A modified game of Nim in C ?
Modified game of Nim is an optimisation games of arrays. This game predicts the winner based on the starting player and optimal moves. Game Logic − In this game, we are given an array{}, that contains elements. There are generally two players that play the game namly player1 and player2. The aim of both is to make sure that all their numbers are removed from the array. Now, player1 has to remove all the numbers that are divisible by 3 and the player2 has to remove all the numbers that are divisible by 5. The aim is to make sure that they remove all elements optimally and find the winner in this case. Array : {1,5, 75,2,65,7,25,6} Winner : playerB. A removes 75 -> B removes 5 -> A removes 6 -> B removes 65 -> No moves for A, B wins. The code will find the number of elements that A can remove , number of elements that B can remove and the number of elements that they both can remove. Based on the number of the elements they both can remove the solution is found. As A removes first elements it can win even if he has to remove one element more than B. In normal case, the player with the maximum number of elements to remove wins. #include <bits/stdc++.h> using namespace std; int main() { int arr[] = {1,5, 75,2,65,7,25,6}; int n = sizeof(arr) / sizeof(arr[0]); int movesA = 0, movesB = 0, movesBoth = 0; for (int i = 0; i < n; i++) { if (arr[i] % 3 == 0 && arr[i] % 5 == 0) movesBoth++; else if (arr[i] % 3 == 0) movesA++; else if (arr[i] % 5 == 0) movesB++; } if (movesBoth == 0) { if (movesA > movesB) cout<<"Player 1 is the Winner"; cout<<"Player 2 is the Winner"; } if (movesA + 1 > movesB) cout<<"Player 1 is the Winner"; cout<<"Player 2 is the Winner"; ; return 0; } Player 2 is the Winner
[ { "code": null, "e": 1197, "s": 1062, "text": "Modified game of Nim is an optimisation games of arrays. This game predicts the winner based on the starting player and optimal moves." }, { "code": null, "e": 1670, "s": 1197, "text": "Game Logic − In this game, we are given an array{}, that contains elements. There are generally two players that play the game namly player1 and player2. The aim of both is to make sure that all their numbers are removed from the array. Now, player1 has to remove all the numbers that are divisible by 3 and the player2 has to remove all the numbers that are divisible by 5. The aim is to make sure that they remove all elements optimally and find the winner in this case." }, { "code": null, "e": 1804, "s": 1670, "text": "Array : {1,5, 75,2,65,7,25,6}\nWinner : playerB.\nA removes 75 -> B removes 5 -> A removes 6 -> B removes 65 -> No moves for A, B wins." }, { "code": null, "e": 2205, "s": 1804, "text": "The code will find the number of elements that A can remove , number of elements that B can remove and the number of elements that they both can remove. Based on the number of the elements they both can remove the solution is found. As A removes first elements it can win even if he has to remove one element more than B. In normal case, the player with the maximum number of elements to remove wins." }, { "code": null, "e": 2851, "s": 2205, "text": "#include <bits/stdc++.h>\nusing namespace std;\nint main() {\n int arr[] = {1,5, 75,2,65,7,25,6};\n int n = sizeof(arr) / sizeof(arr[0]);\n int movesA = 0, movesB = 0, movesBoth = 0;\n for (int i = 0; i < n; i++) {\n if (arr[i] % 3 == 0 && arr[i] % 5 == 0)\n movesBoth++;\n else if (arr[i] % 3 == 0)\n movesA++;\n else if (arr[i] % 5 == 0)\n movesB++;\n }\n if (movesBoth == 0) {\n if (movesA > movesB)\n cout<<\"Player 1 is the Winner\";\n cout<<\"Player 2 is the Winner\";\n }\n if (movesA + 1 > movesB)\n cout<<\"Player 1 is the Winner\";\n cout<<\"Player 2 is the Winner\"; ;\n return 0;\n}" }, { "code": null, "e": 2874, "s": 2851, "text": "Player 2 is the Winner" } ]
Sorting a Map by value in C++ STL - GeeksforGeeks
31 May, 2020 Maps are associative containers that store elements in a mapped fashion. Each element has a key value and a mapped value. No two mapped values can have equal key values. By default, a Map in C++ is sorted in increasing order based on its key. Below is the various method to achieve this: Method 1 – using the vector of pairs The idea is to copy all contents from the map to the corresponding vector of pairs and sort the vector of pairs according to second value using the lambda function given below: bool cmp(pair<T1, T2>& a, pair<T1, T2>& b) { return a.second < b.second; } where T1 and T2 are the data-types that can be the same or different. Below is the implementation of the above approach: // C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Comparator function to sort pairs// according to second valuebool cmp(pair<string, int>& a, pair<string, int>& b){ return a.second < b.second;} // Function to sort the map according// to value in a (key-value) pairsvoid sort(map<string, int>& M){ // Declare vector of pairs vector<pair<string, int> > A; // Copy key-value pair from Map // to vector of pairs for (auto& it : M) { A.push_back(it); } // Sort using comparator function sort(A.begin(), A.end(), cmp); // Print the sorted value for (auto& it : A) { cout << it.first << ' ' << it.second << endl; }} // Driver Codeint main(){ // Declare Map map<string, int> M; // Given Map M = { { "GfG", 3 }, { "To", 2 }, { "Welcome", 1 } }; // Function Call sort(M); return 0;} Welcome 1 To 2 GfG 3 Method 2 – using the set of pairs The idea is to insert all the (key-value) pairs from the map into a set of pairs that can be constructed using a comparator function that orders the pairs according to the second value. Below is the implementation of the above approach: // C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Comparison function for sorting the// set by increasing order of its pair's// second valuestruct comp { template <typename T> // Comparator function bool operator()(const T& l, const T& r) const { if (l.second != r.second) { return l.second < r.second; } return l.first < r.first; }}; // Function to sort the map according// to value in a (key-value) pairsvoid sort(map<string, int>& M){ // Declare set of pairs and insert // pairs according to the comparator // function comp() set<pair<string, int>, comp> S(M.begin(), M.end()); // Print the sorted value for (auto& it : S) { cout << it.first << ' ' << it.second << endl; }} // Driver Codeint main(){ // Declare Map map<string, int> M; // Given Map M = { { "GfG", 3 }, { "To", 2 }, { "Welcome", 1 } }; // Function Call sort(M); return 0;} Welcome 1 To 2 GfG 3 Method 3 – using multimapMultimap is similar to a map with an addition that multiple elements can have the same keys. Rather than each element is unique, the key-value and mapped value pair have to be unique in this case.The idea is to insert all pairs from the given map into multimap using originals map’s value as a key in the multimap and original maps key value as a value in the multimap. Below is the implementation of the above approach: // C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to sort the map according// to value in a (key-value) pairsvoid sort(map<string, int>& M){ // Declare a multimap multimap<int, string> MM; // Insert every (key-value) pairs from // map M to multimap MM as (value-key) // pairs for (auto& it : M) { MM.insert({ it.second, it.first }); } // Print the multimap for (auto& it : MM) { cout << it.second << ' ' << it.first << endl; }} // Driver Codeint main(){ // Declare Map map<string, int> M; // Given Map M = { { "GfG", 3 }, { "To", 2 }, { "Welcome", 1 } }; // Function Call sort(M); return 0;} Welcome 1 To 2 GfG 3 cpp-map cpp-pair cpp-vector C++ Programs Hash Sorting Hash Sorting Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments C++ Program for QuickSort cin in C++ delete keyword in C++ Shallow Copy and Deep Copy in C++ Passing a function as a parameter in C++ Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum) Internal Working of HashMap in Java Hashing | Set 1 (Introduction) Count pairs with given sum Hashing | Set 3 (Open Addressing)
[ { "code": null, "e": 24297, "s": 24269, "text": "\n31 May, 2020" }, { "code": null, "e": 24585, "s": 24297, "text": "Maps are associative containers that store elements in a mapped fashion. Each element has a key value and a mapped value. No two mapped values can have equal key values. By default, a Map in C++ is sorted in increasing order based on its key. Below is the various method to achieve this:" }, { "code": null, "e": 24799, "s": 24585, "text": "Method 1 – using the vector of pairs The idea is to copy all contents from the map to the corresponding vector of pairs and sort the vector of pairs according to second value using the lambda function given below:" }, { "code": null, "e": 24961, "s": 24799, "text": "bool cmp(pair<T1, T2>& a,\n pair<T1, T2>& b)\n{\n return a.second < b.second;\n}\n\nwhere T1 and T2\nare the data-types \nthat can be the \nsame or different.\n" }, { "code": null, "e": 25012, "s": 24961, "text": "Below is the implementation of the above approach:" }, { "code": "// C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Comparator function to sort pairs// according to second valuebool cmp(pair<string, int>& a, pair<string, int>& b){ return a.second < b.second;} // Function to sort the map according// to value in a (key-value) pairsvoid sort(map<string, int>& M){ // Declare vector of pairs vector<pair<string, int> > A; // Copy key-value pair from Map // to vector of pairs for (auto& it : M) { A.push_back(it); } // Sort using comparator function sort(A.begin(), A.end(), cmp); // Print the sorted value for (auto& it : A) { cout << it.first << ' ' << it.second << endl; }} // Driver Codeint main(){ // Declare Map map<string, int> M; // Given Map M = { { \"GfG\", 3 }, { \"To\", 2 }, { \"Welcome\", 1 } }; // Function Call sort(M); return 0;}", "e": 25950, "s": 25012, "text": null }, { "code": null, "e": 25972, "s": 25950, "text": "Welcome 1\nTo 2\nGfG 3\n" }, { "code": null, "e": 26192, "s": 25972, "text": "Method 2 – using the set of pairs The idea is to insert all the (key-value) pairs from the map into a set of pairs that can be constructed using a comparator function that orders the pairs according to the second value." }, { "code": null, "e": 26243, "s": 26192, "text": "Below is the implementation of the above approach:" }, { "code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Comparison function for sorting the// set by increasing order of its pair's// second valuestruct comp { template <typename T> // Comparator function bool operator()(const T& l, const T& r) const { if (l.second != r.second) { return l.second < r.second; } return l.first < r.first; }}; // Function to sort the map according// to value in a (key-value) pairsvoid sort(map<string, int>& M){ // Declare set of pairs and insert // pairs according to the comparator // function comp() set<pair<string, int>, comp> S(M.begin(), M.end()); // Print the sorted value for (auto& it : S) { cout << it.first << ' ' << it.second << endl; }} // Driver Codeint main(){ // Declare Map map<string, int> M; // Given Map M = { { \"GfG\", 3 }, { \"To\", 2 }, { \"Welcome\", 1 } }; // Function Call sort(M); return 0;}", "e": 27313, "s": 26243, "text": null }, { "code": null, "e": 27335, "s": 27313, "text": "Welcome 1\nTo 2\nGfG 3\n" }, { "code": null, "e": 27730, "s": 27335, "text": "Method 3 – using multimapMultimap is similar to a map with an addition that multiple elements can have the same keys. Rather than each element is unique, the key-value and mapped value pair have to be unique in this case.The idea is to insert all pairs from the given map into multimap using originals map’s value as a key in the multimap and original maps key value as a value in the multimap." }, { "code": null, "e": 27781, "s": 27730, "text": "Below is the implementation of the above approach:" }, { "code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to sort the map according// to value in a (key-value) pairsvoid sort(map<string, int>& M){ // Declare a multimap multimap<int, string> MM; // Insert every (key-value) pairs from // map M to multimap MM as (value-key) // pairs for (auto& it : M) { MM.insert({ it.second, it.first }); } // Print the multimap for (auto& it : MM) { cout << it.second << ' ' << it.first << endl; }} // Driver Codeint main(){ // Declare Map map<string, int> M; // Given Map M = { { \"GfG\", 3 }, { \"To\", 2 }, { \"Welcome\", 1 } }; // Function Call sort(M); return 0;}", "e": 28526, "s": 27781, "text": null }, { "code": null, "e": 28548, "s": 28526, "text": "Welcome 1\nTo 2\nGfG 3\n" }, { "code": null, "e": 28556, "s": 28548, "text": "cpp-map" }, { "code": null, "e": 28565, "s": 28556, "text": "cpp-pair" }, { "code": null, "e": 28576, "s": 28565, "text": "cpp-vector" }, { "code": null, "e": 28589, "s": 28576, "text": "C++ Programs" }, { "code": null, "e": 28594, "s": 28589, "text": "Hash" }, { "code": null, "e": 28602, "s": 28594, "text": "Sorting" }, { "code": null, "e": 28607, "s": 28602, "text": "Hash" }, { "code": null, "e": 28615, "s": 28607, "text": "Sorting" }, { "code": null, "e": 28713, "s": 28615, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28722, "s": 28713, "text": "Comments" }, { "code": null, "e": 28735, "s": 28722, "text": "Old Comments" }, { "code": null, "e": 28761, "s": 28735, "text": "C++ Program for QuickSort" }, { "code": null, "e": 28772, "s": 28761, "text": "cin in C++" }, { "code": null, "e": 28794, "s": 28772, "text": "delete keyword in C++" }, { "code": null, "e": 28828, "s": 28794, "text": "Shallow Copy and Deep Copy in C++" }, { "code": null, "e": 28869, "s": 28828, "text": "Passing a function as a parameter in C++" }, { "code": null, "e": 28954, "s": 28869, "text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)" }, { "code": null, "e": 28990, "s": 28954, "text": "Internal Working of HashMap in Java" }, { "code": null, "e": 29021, "s": 28990, "text": "Hashing | Set 1 (Introduction)" }, { "code": null, "e": 29048, "s": 29021, "text": "Count pairs with given sum" } ]
Implementation of Lasso, Ridge and Elastic Net
15 May, 2021 In this article, we will look into the implementation of different regularization techniques. First, we will start with multiple linear regression. For that, we require the python3 environment with sci-kit learn and pandas preinstall. We can also use google collaboratory or any other jupyter notebook environment.First, we need to import some packages into our environment. Python3 import pandas as pdimport numpy as npimport matplotlib.pyplot as pltfrom sklearn import datasetsfrom sklearn.model_selection import train_test_splitfrom sklearn.linear_model import LinearRegression We are going to use the Boston house prediction dataset. This dataset is present in the datasets module of sklearn (scikit-learn) library. We can import this dataset as follows. Python3 # Loading pre-defined Boston Datasetboston_dataset = datasets.load_boston()print(boston_dataset.DESCR) Output: We can conclude from the above description that we have 13 independent variable and one dependent (House price) variable. Now we need to check for a correlation between independent and dependent variable. We can use scatterplot/corrplot for this. Python3 # Generate scatter plot of independent vs Dependent variableplt.style.use('ggplot')fig = plt.figure(figsize = (18, 18)) for index, feature_name in enumerate(boston_dataset.feature_names): ax = fig.add_subplot(4, 4, index + 1) ax.scatter(boston_dataset.data[:, index], boston_dataset.target) ax.set_ylabel('House Price', size = 12) ax.set_xlabel(feature_name, size = 12) plt.show() The above code produce scatter plots of different independent variable with target variable as shown below We can observe from the above scatter plots that some of the independent variables are not very much correlated (either positively or negatively) with the target variable. These variables will get their coefficients to be reduced in regularization. Code : Python code to pre-process the data. Python3 # Load the dataset into Pandas Dataframeboston_pd = pd.DataFrame(boston_dataset.data)boston_pd.columns = boston_dataset.feature_namesboston_pd_target = np.asarray(boston_dataset.target)boston_pd['House Price'] = pd.Series(boston_pd_target) # inputX = boston_pd.iloc[:, :-1] #outputY = boston_pd.iloc[:, -1] print(boston_pd.head()) Now, we apply train-test split to divide the dataset into two parts, one for training and another for testing. We will be using 25% of the data for testing. Python3 x_train, x_test, y_train, y_test = train_test_split( boston_pd.iloc[:, :-1], boston_pd.iloc[:, -1], test_size = 0.25) print("Train data shape of X = % s and Y = % s : "%( x_train.shape, y_train.shape)) print("Test data shape of X = % s and Y = % s : "%( x_test.shape, y_test.shape)) Multiple (Linear) Regression Now it’s the right time to test the models. We will be using multiple Linear Regression first. We train the model on training data and calculate the MSE on test. Python3 # Apply multiple Linear Regression Modellreg = LinearRegression()lreg.fit(x_train, y_train) # Generate Prediction on test setlreg_y_pred = lreg.predict(x_test) # calculating Mean Squared Error (mse)mean_squared_error = np.mean((lreg_y_pred - y_test)**2)print("Mean squared Error on test set : ", mean_squared_error) # Putting together the coefficient and their corresponding variable nameslreg_coefficient = pd.DataFrame()lreg_coefficient["Columns"] = x_train.columnslreg_coefficient['Coefficient Estimate'] = pd.Series(lreg.coef_)print(lreg_coefficient) Output: Let’s plot a bar chart of above coefficients using matplotlib plotting library. Python3 # plotting the coefficient scorefig, ax = plt.subplots(figsize =(20, 10)) color =['tab:gray', 'tab:blue', 'tab:orange','tab:green', 'tab:red', 'tab:purple', 'tab:brown','tab:pink', 'tab:gray', 'tab:olive', 'tab:cyan','tab:orange', 'tab:green', 'tab:blue', 'tab:olive'] ax.bar(lreg_coefficient["Columns"],lreg_coefficient['Coefficient Estimate'],color = color) ax.spines['bottom'].set_position('zero') plt.style.use('ggplot')plt.show() Output: As we can observe that lots of the variables have an insignificant coefficient, these coefficients did not contribute to the model very much and need to regulate or even eliminate some of these variables. Ridge Regression: Ridge Regression added a term in ordinary least square error function that regularizes the value of coefficients of variables. This term is the sum of squares of coefficient multiplied by the parameter The motive of adding this term is to penalize the variable corresponding to that coefficient not very much correlated to the target variable. This term is called L2 regularization. Code : Python code to use Ridge regression Python3 # import ridge regression from sklearn libraryfrom sklearn.linear_model import Ridge # Train the modelridgeR = Ridge(alpha = 1)ridgeR.fit(x_train, y_train)y_pred = ridgeR.predict(x_test) # calculate mean square errormean_squared_error_ridge = np.mean((y_pred - y_test)**2)print(mean_squared_error_ridge) # get ridge coefficient and print themridge_coefficient = pd.DataFrame()ridge_coefficient["Columns"]= x_train.columnsridge_coefficient['Coefficient Estimate'] = pd.Series(ridgeR.coef_)print(ridge_coefficient) Output: The value of MSE error and the dataframe with ridge coefficients. The bar plot of above data is: Ridge Regression at =1 In the above graph we take = 1. Let’s look at another bar plot with = 10 Ridge regression at = 10 As we can observe from the above plots that helps in regularizing the coefficient and make them converge faster. Notice that the above graphs can be misleading in a way that it shows some of the coefficients become zero. In Ridge Regularization, the coefficients can never be 0, they are just too small to observe in above plots. Lasso Regression: Lasso Regression is similar to Ridge regression except here we add Mean Absolute value of coefficients in place of mean square value. Unlike Ridge Regression, Lasso regression can completely eliminate the variable by reducing its coefficient value to 0. The new term we added to Ordinary Least Square(OLS) is called L1 Regularization.Code : Python code implementing the Lasso Regression Python3 # import Lasso regression from sklearn libraryfrom sklearn.linear_model import Lasso # Train the modellasso = Lasso(alpha = 1)lasso.fit(x_train, y_train)y_pred1 = lasso.predict(x_test) # Calculate Mean Squared Errormean_squared_error = np.mean((y_pred1 - y_test)**2)print("Mean squared error on test set", mean_squared_error)lasso_coeff = pd.DataFrame()lasso_coeff["Columns"] = x_train.columnslasso_coeff['Coefficient Estimate'] = pd.Series(lasso.coef_) print(lasso_coeff) Output: The value of MSE error and the dataframe with Lasso coefficients. Lasso Regression with = 1 The bar plot of above coefficients: Lasso Regression with =1 The Lasso Regression gave same result that ridge regression gave, when we increase the value of . Let’s look at another plot at = 10. Elastic Net : In elastic Net Regularization we added the both terms of L1 and L2 to get the final loss function. This leads us to reduce the following loss function: where is between 0 and 1. when = 1, It reduces the penalty term to L1 penalty and if = 0, it reduces that term to L2 penalty.Code : Python code implementing the Elastic Net Python3 # import modelfrom sklearn.linear_model import ElasticNet # Train the modele_net = ElasticNet(alpha = 1)e_net.fit(x_train, y_train) # calculate the prediction and mean square errory_pred_elastic = e_net.predict(x_test)mean_squared_error = np.mean((y_pred_elastic - y_test)**2)print("Mean Squared Error on test set", mean_squared_error) e_net_coeff = pd.DataFrame()e_net_coeff["Columns"] = x_train.columnse_net_coeff['Coefficient Estimate'] = pd.Series(e_net.coef_)e_net_coeff Output: Bar plot of above coefficients: Conclusion : From the above analysis we can reach the following conclusion about different regularization methods: Regularization is used to reduce the dependence on any particular independent variable by adding the penalty term to the Loss function. This term prevents the coefficients of the independent variables to take extreme values. Ridge Regression adds L2 regularization penalty term to loss function. This term reduces the coefficients but does not make them 0 and thus doesn’t eliminate any independent variable completely. It can be used to measure the impact of the different independent variables. Lasso Regression adds L1 regularization penalty term to loss function. This term reduces the coefficients as well as makes them 0 thus effectively eliminate the corresponding independent variable completely. It can be used for feature selection etc. Elastic Net is a combination of both of the above regularization. It contains both the L1 and L2 as its penalty term. It performs better than Ridge and Lasso Regression for most of the test cases. sweetyty ML-Regression Machine Learning Python Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Reinforcement learning Supervised and Unsupervised learning Decision Tree Introduction with example Search Algorithms in AI Getting started with Machine Learning Read JSON file using Python Adding new column to existing DataFrame in Pandas Python map() function How to get column names in Pandas dataframe
[ { "code": null, "e": 28, "s": 0, "text": "\n15 May, 2021" }, { "code": null, "e": 404, "s": 28, "text": "In this article, we will look into the implementation of different regularization techniques. First, we will start with multiple linear regression. For that, we require the python3 environment with sci-kit learn and pandas preinstall. We can also use google collaboratory or any other jupyter notebook environment.First, we need to import some packages into our environment. " }, { "code": null, "e": 412, "s": 404, "text": "Python3" }, { "code": "import pandas as pdimport numpy as npimport matplotlib.pyplot as pltfrom sklearn import datasetsfrom sklearn.model_selection import train_test_splitfrom sklearn.linear_model import LinearRegression", "e": 610, "s": 412, "text": null }, { "code": null, "e": 789, "s": 610, "text": "We are going to use the Boston house prediction dataset. This dataset is present in the datasets module of sklearn (scikit-learn) library. We can import this dataset as follows. " }, { "code": null, "e": 797, "s": 789, "text": "Python3" }, { "code": "# Loading pre-defined Boston Datasetboston_dataset = datasets.load_boston()print(boston_dataset.DESCR)", "e": 900, "s": 797, "text": null }, { "code": null, "e": 910, "s": 900, "text": "Output: " }, { "code": null, "e": 1159, "s": 910, "text": "We can conclude from the above description that we have 13 independent variable and one dependent (House price) variable. Now we need to check for a correlation between independent and dependent variable. We can use scatterplot/corrplot for this. " }, { "code": null, "e": 1167, "s": 1159, "text": "Python3" }, { "code": "# Generate scatter plot of independent vs Dependent variableplt.style.use('ggplot')fig = plt.figure(figsize = (18, 18)) for index, feature_name in enumerate(boston_dataset.feature_names): ax = fig.add_subplot(4, 4, index + 1) ax.scatter(boston_dataset.data[:, index], boston_dataset.target) ax.set_ylabel('House Price', size = 12) ax.set_xlabel(feature_name, size = 12) plt.show()", "e": 1560, "s": 1167, "text": null }, { "code": null, "e": 1667, "s": 1560, "text": "The above code produce scatter plots of different independent variable with target variable as shown below" }, { "code": null, "e": 1962, "s": 1667, "text": "We can observe from the above scatter plots that some of the independent variables are not very much correlated (either positively or negatively) with the target variable. These variables will get their coefficients to be reduced in regularization. Code : Python code to pre-process the data. " }, { "code": null, "e": 1970, "s": 1962, "text": "Python3" }, { "code": "# Load the dataset into Pandas Dataframeboston_pd = pd.DataFrame(boston_dataset.data)boston_pd.columns = boston_dataset.feature_namesboston_pd_target = np.asarray(boston_dataset.target)boston_pd['House Price'] = pd.Series(boston_pd_target) # inputX = boston_pd.iloc[:, :-1] #outputY = boston_pd.iloc[:, -1] print(boston_pd.head())", "e": 2301, "s": 1970, "text": null }, { "code": null, "e": 2460, "s": 2301, "text": "Now, we apply train-test split to divide the dataset into two parts, one for training and another for testing. We will be using 25% of the data for testing. " }, { "code": null, "e": 2468, "s": 2460, "text": "Python3" }, { "code": "x_train, x_test, y_train, y_test = train_test_split( boston_pd.iloc[:, :-1], boston_pd.iloc[:, -1], test_size = 0.25) print(\"Train data shape of X = % s and Y = % s : \"%( x_train.shape, y_train.shape)) print(\"Test data shape of X = % s and Y = % s : \"%( x_test.shape, y_test.shape))", "e": 2763, "s": 2468, "text": null }, { "code": null, "e": 2956, "s": 2763, "text": "Multiple (Linear) Regression Now it’s the right time to test the models. We will be using multiple Linear Regression first. We train the model on training data and calculate the MSE on test. " }, { "code": null, "e": 2964, "s": 2956, "text": "Python3" }, { "code": "# Apply multiple Linear Regression Modellreg = LinearRegression()lreg.fit(x_train, y_train) # Generate Prediction on test setlreg_y_pred = lreg.predict(x_test) # calculating Mean Squared Error (mse)mean_squared_error = np.mean((lreg_y_pred - y_test)**2)print(\"Mean squared Error on test set : \", mean_squared_error) # Putting together the coefficient and their corresponding variable nameslreg_coefficient = pd.DataFrame()lreg_coefficient[\"Columns\"] = x_train.columnslreg_coefficient['Coefficient Estimate'] = pd.Series(lreg.coef_)print(lreg_coefficient)", "e": 3519, "s": 2964, "text": null }, { "code": null, "e": 3529, "s": 3519, "text": "Output: " }, { "code": null, "e": 3611, "s": 3529, "text": "Let’s plot a bar chart of above coefficients using matplotlib plotting library. " }, { "code": null, "e": 3619, "s": 3611, "text": "Python3" }, { "code": "# plotting the coefficient scorefig, ax = plt.subplots(figsize =(20, 10)) color =['tab:gray', 'tab:blue', 'tab:orange','tab:green', 'tab:red', 'tab:purple', 'tab:brown','tab:pink', 'tab:gray', 'tab:olive', 'tab:cyan','tab:orange', 'tab:green', 'tab:blue', 'tab:olive'] ax.bar(lreg_coefficient[\"Columns\"],lreg_coefficient['Coefficient Estimate'],color = color) ax.spines['bottom'].set_position('zero') plt.style.use('ggplot')plt.show()", "e": 4054, "s": 3619, "text": null }, { "code": null, "e": 4064, "s": 4054, "text": "Output: " }, { "code": null, "e": 4717, "s": 4064, "text": "As we can observe that lots of the variables have an insignificant coefficient, these coefficients did not contribute to the model very much and need to regulate or even eliminate some of these variables. Ridge Regression: Ridge Regression added a term in ordinary least square error function that regularizes the value of coefficients of variables. This term is the sum of squares of coefficient multiplied by the parameter The motive of adding this term is to penalize the variable corresponding to that coefficient not very much correlated to the target variable. This term is called L2 regularization. Code : Python code to use Ridge regression " }, { "code": null, "e": 4725, "s": 4717, "text": "Python3" }, { "code": "# import ridge regression from sklearn libraryfrom sklearn.linear_model import Ridge # Train the modelridgeR = Ridge(alpha = 1)ridgeR.fit(x_train, y_train)y_pred = ridgeR.predict(x_test) # calculate mean square errormean_squared_error_ridge = np.mean((y_pred - y_test)**2)print(mean_squared_error_ridge) # get ridge coefficient and print themridge_coefficient = pd.DataFrame()ridge_coefficient[\"Columns\"]= x_train.columnsridge_coefficient['Coefficient Estimate'] = pd.Series(ridgeR.coef_)print(ridge_coefficient)", "e": 5238, "s": 4725, "text": null }, { "code": null, "e": 5314, "s": 5238, "text": "Output: The value of MSE error and the dataframe with ridge coefficients. " }, { "code": null, "e": 5347, "s": 5314, "text": "The bar plot of above data is: " }, { "code": null, "e": 5370, "s": 5347, "text": "Ridge Regression at =1" }, { "code": null, "e": 5445, "s": 5370, "text": "In the above graph we take = 1. Let’s look at another bar plot with = 10 " }, { "code": null, "e": 5470, "s": 5445, "text": "Ridge regression at = 10" }, { "code": null, "e": 6209, "s": 5470, "text": "As we can observe from the above plots that helps in regularizing the coefficient and make them converge faster. Notice that the above graphs can be misleading in a way that it shows some of the coefficients become zero. In Ridge Regularization, the coefficients can never be 0, they are just too small to observe in above plots. Lasso Regression: Lasso Regression is similar to Ridge regression except here we add Mean Absolute value of coefficients in place of mean square value. Unlike Ridge Regression, Lasso regression can completely eliminate the variable by reducing its coefficient value to 0. The new term we added to Ordinary Least Square(OLS) is called L1 Regularization.Code : Python code implementing the Lasso Regression " }, { "code": null, "e": 6217, "s": 6209, "text": "Python3" }, { "code": "# import Lasso regression from sklearn libraryfrom sklearn.linear_model import Lasso # Train the modellasso = Lasso(alpha = 1)lasso.fit(x_train, y_train)y_pred1 = lasso.predict(x_test) # Calculate Mean Squared Errormean_squared_error = np.mean((y_pred1 - y_test)**2)print(\"Mean squared error on test set\", mean_squared_error)lasso_coeff = pd.DataFrame()lasso_coeff[\"Columns\"] = x_train.columnslasso_coeff['Coefficient Estimate'] = pd.Series(lasso.coef_) print(lasso_coeff)", "e": 6690, "s": 6217, "text": null }, { "code": null, "e": 6766, "s": 6690, "text": "Output: The value of MSE error and the dataframe with Lasso coefficients. " }, { "code": null, "e": 6792, "s": 6766, "text": "Lasso Regression with = 1" }, { "code": null, "e": 6830, "s": 6792, "text": "The bar plot of above coefficients: " }, { "code": null, "e": 6855, "s": 6830, "text": "Lasso Regression with =1" }, { "code": null, "e": 6991, "s": 6855, "text": "The Lasso Regression gave same result that ridge regression gave, when we increase the value of . Let’s look at another plot at = 10. " }, { "code": null, "e": 7334, "s": 6991, "text": " Elastic Net : In elastic Net Regularization we added the both terms of L1 and L2 to get the final loss function. This leads us to reduce the following loss function: where is between 0 and 1. when = 1, It reduces the penalty term to L1 penalty and if = 0, it reduces that term to L2 penalty.Code : Python code implementing the Elastic Net " }, { "code": null, "e": 7342, "s": 7334, "text": "Python3" }, { "code": "# import modelfrom sklearn.linear_model import ElasticNet # Train the modele_net = ElasticNet(alpha = 1)e_net.fit(x_train, y_train) # calculate the prediction and mean square errory_pred_elastic = e_net.predict(x_test)mean_squared_error = np.mean((y_pred_elastic - y_test)**2)print(\"Mean Squared Error on test set\", mean_squared_error) e_net_coeff = pd.DataFrame()e_net_coeff[\"Columns\"] = x_train.columnse_net_coeff['Coefficient Estimate'] = pd.Series(e_net.coef_)e_net_coeff", "e": 7818, "s": 7342, "text": null }, { "code": null, "e": 7828, "s": 7818, "text": "Output: " }, { "code": null, "e": 7862, "s": 7828, "text": "Bar plot of above coefficients: " }, { "code": null, "e": 7979, "s": 7862, "text": "Conclusion : From the above analysis we can reach the following conclusion about different regularization methods: " }, { "code": null, "e": 8206, "s": 7979, "text": "Regularization is used to reduce the dependence on any particular independent variable by adding the penalty term to the Loss function. This term prevents the coefficients of the independent variables to take extreme values. " }, { "code": null, "e": 8480, "s": 8206, "text": "Ridge Regression adds L2 regularization penalty term to loss function. This term reduces the coefficients but does not make them 0 and thus doesn’t eliminate any independent variable completely. It can be used to measure the impact of the different independent variables. " }, { "code": null, "e": 8732, "s": 8480, "text": "Lasso Regression adds L1 regularization penalty term to loss function. This term reduces the coefficients as well as makes them 0 thus effectively eliminate the corresponding independent variable completely. It can be used for feature selection etc. " }, { "code": null, "e": 8931, "s": 8732, "text": "Elastic Net is a combination of both of the above regularization. It contains both the L1 and L2 as its penalty term. It performs better than Ridge and Lasso Regression for most of the test cases. " }, { "code": null, "e": 8942, "s": 8933, "text": "sweetyty" }, { "code": null, "e": 8956, "s": 8942, "text": "ML-Regression" }, { "code": null, "e": 8973, "s": 8956, "text": "Machine Learning" }, { "code": null, "e": 8980, "s": 8973, "text": "Python" }, { "code": null, "e": 8997, "s": 8980, "text": "Machine Learning" }, { "code": null, "e": 9095, "s": 8997, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 9118, "s": 9095, "text": "Reinforcement learning" }, { "code": null, "e": 9155, "s": 9118, "text": "Supervised and Unsupervised learning" }, { "code": null, "e": 9195, "s": 9155, "text": "Decision Tree Introduction with example" }, { "code": null, "e": 9219, "s": 9195, "text": "Search Algorithms in AI" }, { "code": null, "e": 9257, "s": 9219, "text": "Getting started with Machine Learning" }, { "code": null, "e": 9285, "s": 9257, "text": "Read JSON file using Python" }, { "code": null, "e": 9335, "s": 9285, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 9357, "s": 9335, "text": "Python map() function" } ]
Program to calculate Kinetic Energy and Potential Energy
12 Jul, 2021 Given three float values M, H, and V representing the mass, velocity, and height of an object respectively the task is to calculate its Kinetic Energy as well as its Potential Energy, Note: The value of acceleration due to gravity (g) is 9.8 and ignore units. Examples: Input: M = 25, H = 10, V = 15Output:Kinetic Energy = 2812.5Potential Energy = 2450Explanation : The kinetic energy of the particle is 2812.5 and the potential energy is 2450. Input : M=5.5, H=23.5, V= 10.5Output :303.1881266.65 Approach: The required values of Kinetic Energy and Potential Energy can be calculated using the following two formulas: Kinetic Energy = 0.5 * Mass ( M ) * Velocity ( V ) 2 Potential Energy = Mass ( M ) * Height ( H ) * Acceleration due to gravity ( g ) Below is the implementation of the above approach: C++14 Java Python3 C# Javascript // C++ Program to implement// the above approach #include <bits/stdc++.h>using namespace std; // Function to calculate Kinetic Energyfloat kineticEnergy(float M, float V){ // Stores the Kinetic Energy float KineticEnergy; KineticEnergy = 0.5 * M * V * V; return KineticEnergy;} // Function to calculate Potential Energyfloat potentialEnergy(float M, float H){ // Stores the Potential Energy float PotentialEnergy; PotentialEnergy = M * 9.8 * H; return PotentialEnergy;} // Driver Codeint main(){ float M = 5.5, H = 23.5, V = 10.5; cout << "Kinetic Energy = " << kineticEnergy(M, V) << endl; cout << "Potential Energy = " << potentialEnergy(M, H) << endl; return 0;} // Java program to implement// the above approachclass GFG{ // Function to calculate Kinetic Energystatic double kineticEnergy(double M, double V){ // Stores the Kinetic Energy double KineticEnergy; KineticEnergy = 0.5 * M * V * V; return KineticEnergy;} // Function to calculate Potential Energystatic double potentialEnergy(double M, double H){ // Stores the Potential Energy double PotentialEnergy; PotentialEnergy = M * 9.8 * H; return PotentialEnergy;} // Driver Codepublic static void main(String []args){ double M = 5.5, H = 23.5, V = 10.5; System.out.println("Kinetic Energy = " + kineticEnergy(M, V)); System.out.println("Potential Energy = " + potentialEnergy(M, H));}} // This code is contributed by AnkThon # Python3 program to implement# the above approach # Function to calculate Kinetic Energydef kineticEnergy(M, V): # Stores the Kinetic Energy KineticEnergy = 0.5 * M * V * V return KineticEnergy # Function to calculate Potential Energydef potentialEnergy(M, H): # Stores the Potential Energy PotentialEnergy = M * 9.8 * H return PotentialEnergy # Driver Codeif __name__ == "__main__": M = 5.5 H = 23.5 V = 10.5 print("Kinetic Energy = ", kineticEnergy(M, V)) print("Potential Energy = ", potentialEnergy(M, H)) # This code is contributed by AnkThon // C# program to implement// the above approachusing System;using System.Collections.Generic; class GFG{ /// Function to calculate Kinetic Energystatic double kineticEnergy(double M, double V){ // Stores the Kinetic Energy double KineticEnergy; KineticEnergy = 0.5 * M * V * V; return KineticEnergy;} // Function to calculate Potential Energystatic double potentialEnergy(double M, double H){ // Stores the Potential Energy double PotentialEnergy; PotentialEnergy = M * 9.8 * H; return PotentialEnergy;} // Driver Codepublic static void Main(){ double M = 5.5, H = 23.5, V = 10.5; Console.WriteLine("Kinetic Energy = " + kineticEnergy(M, V)); Console.Write("Potential Energy = " + potentialEnergy(M, H));}} // This code is contributed by bgangwar59 <script> // Javascript program for the above approach // Function to calculate Kinetic Energy function kineticEnergy(M, V) { // Stores the Kinetic Energy let KineticEnergy; KineticEnergy = 0.5 * M * V * V; return KineticEnergy; } // Function to calculate Potential Energy function potentialEnergy(M, H) { // Stores the Potential Energy let PotentialEnergy; PotentialEnergy = M * 9.8 * H; return PotentialEnergy; } // Driver Code let M = 5.5, H = 23.5, V = 10.5; document.write("Kinetic Energy = " + kineticEnergy(M, V)) document.write("<br>"); document.write( "Potential Energy = " + potentialEnergy(M, H)) // This code is contributed by Hritik </script> Kinetic Energy = 303.188 Potential Energy = 1266.65 Time Complexity: O(1)Auxiliary Space: O(1) bgangwar59 ankthon hritikrommie parthagarwal1962000 Mathematical School Programming 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++ Sieve of Eratosthenes Prime Numbers Minimum number of jumps to reach end Python Dictionary Reverse a string in Java Arrays in C/C++ Introduction To PYTHON Interfaces in Java
[ { "code": null, "e": 53, "s": 25, "text": "\n12 Jul, 2021" }, { "code": null, "e": 316, "s": 53, "text": "Given three float values M, H, and V representing the mass, velocity, and height of an object respectively the task is to calculate its Kinetic Energy as well as its Potential Energy, Note: The value of acceleration due to gravity (g) is 9.8 and ignore units. " }, { "code": null, "e": 326, "s": 316, "text": "Examples:" }, { "code": null, "e": 501, "s": 326, "text": "Input: M = 25, H = 10, V = 15Output:Kinetic Energy = 2812.5Potential Energy = 2450Explanation : The kinetic energy of the particle is 2812.5 and the potential energy is 2450." }, { "code": null, "e": 554, "s": 501, "text": "Input : M=5.5, H=23.5, V= 10.5Output :303.1881266.65" }, { "code": null, "e": 675, "s": 554, "text": "Approach: The required values of Kinetic Energy and Potential Energy can be calculated using the following two formulas:" }, { "code": null, "e": 729, "s": 675, "text": "Kinetic Energy = 0.5 * Mass ( M ) * Velocity ( V ) 2 " }, { "code": null, "e": 810, "s": 729, "text": "Potential Energy = Mass ( M ) * Height ( H ) * Acceleration due to gravity ( g )" }, { "code": null, "e": 861, "s": 810, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 867, "s": 861, "text": "C++14" }, { "code": null, "e": 872, "s": 867, "text": "Java" }, { "code": null, "e": 880, "s": 872, "text": "Python3" }, { "code": null, "e": 883, "s": 880, "text": "C#" }, { "code": null, "e": 894, "s": 883, "text": "Javascript" }, { "code": "// C++ Program to implement// the above approach #include <bits/stdc++.h>using namespace std; // Function to calculate Kinetic Energyfloat kineticEnergy(float M, float V){ // Stores the Kinetic Energy float KineticEnergy; KineticEnergy = 0.5 * M * V * V; return KineticEnergy;} // Function to calculate Potential Energyfloat potentialEnergy(float M, float H){ // Stores the Potential Energy float PotentialEnergy; PotentialEnergy = M * 9.8 * H; return PotentialEnergy;} // Driver Codeint main(){ float M = 5.5, H = 23.5, V = 10.5; cout << \"Kinetic Energy = \" << kineticEnergy(M, V) << endl; cout << \"Potential Energy = \" << potentialEnergy(M, H) << endl; return 0;}", "e": 1617, "s": 894, "text": null }, { "code": "// Java program to implement// the above approachclass GFG{ // Function to calculate Kinetic Energystatic double kineticEnergy(double M, double V){ // Stores the Kinetic Energy double KineticEnergy; KineticEnergy = 0.5 * M * V * V; return KineticEnergy;} // Function to calculate Potential Energystatic double potentialEnergy(double M, double H){ // Stores the Potential Energy double PotentialEnergy; PotentialEnergy = M * 9.8 * H; return PotentialEnergy;} // Driver Codepublic static void main(String []args){ double M = 5.5, H = 23.5, V = 10.5; System.out.println(\"Kinetic Energy = \" + kineticEnergy(M, V)); System.out.println(\"Potential Energy = \" + potentialEnergy(M, H));}} // This code is contributed by AnkThon", "e": 2429, "s": 1617, "text": null }, { "code": "# Python3 program to implement# the above approach # Function to calculate Kinetic Energydef kineticEnergy(M, V): # Stores the Kinetic Energy KineticEnergy = 0.5 * M * V * V return KineticEnergy # Function to calculate Potential Energydef potentialEnergy(M, H): # Stores the Potential Energy PotentialEnergy = M * 9.8 * H return PotentialEnergy # Driver Codeif __name__ == \"__main__\": M = 5.5 H = 23.5 V = 10.5 print(\"Kinetic Energy = \", kineticEnergy(M, V)) print(\"Potential Energy = \", potentialEnergy(M, H)) # This code is contributed by AnkThon", "e": 3022, "s": 2429, "text": null }, { "code": "// C# program to implement// the above approachusing System;using System.Collections.Generic; class GFG{ /// Function to calculate Kinetic Energystatic double kineticEnergy(double M, double V){ // Stores the Kinetic Energy double KineticEnergy; KineticEnergy = 0.5 * M * V * V; return KineticEnergy;} // Function to calculate Potential Energystatic double potentialEnergy(double M, double H){ // Stores the Potential Energy double PotentialEnergy; PotentialEnergy = M * 9.8 * H; return PotentialEnergy;} // Driver Codepublic static void Main(){ double M = 5.5, H = 23.5, V = 10.5; Console.WriteLine(\"Kinetic Energy = \" + kineticEnergy(M, V)); Console.Write(\"Potential Energy = \" + potentialEnergy(M, H));}} // This code is contributed by bgangwar59", "e": 3858, "s": 3022, "text": null }, { "code": "<script> // Javascript program for the above approach // Function to calculate Kinetic Energy function kineticEnergy(M, V) { // Stores the Kinetic Energy let KineticEnergy; KineticEnergy = 0.5 * M * V * V; return KineticEnergy; } // Function to calculate Potential Energy function potentialEnergy(M, H) { // Stores the Potential Energy let PotentialEnergy; PotentialEnergy = M * 9.8 * H; return PotentialEnergy; } // Driver Code let M = 5.5, H = 23.5, V = 10.5; document.write(\"Kinetic Energy = \" + kineticEnergy(M, V)) document.write(\"<br>\"); document.write( \"Potential Energy = \" + potentialEnergy(M, H)) // This code is contributed by Hritik </script>", "e": 4753, "s": 3858, "text": null }, { "code": null, "e": 4805, "s": 4753, "text": "Kinetic Energy = 303.188\nPotential Energy = 1266.65" }, { "code": null, "e": 4850, "s": 4807, "text": "Time Complexity: O(1)Auxiliary Space: O(1)" }, { "code": null, "e": 4863, "s": 4852, "text": "bgangwar59" }, { "code": null, "e": 4871, "s": 4863, "text": "ankthon" }, { "code": null, "e": 4884, "s": 4871, "text": "hritikrommie" }, { "code": null, "e": 4904, "s": 4884, "text": "parthagarwal1962000" }, { "code": null, "e": 4917, "s": 4904, "text": "Mathematical" }, { "code": null, "e": 4936, "s": 4917, "text": "School Programming" }, { "code": null, "e": 4949, "s": 4936, "text": "Mathematical" }, { "code": null, "e": 5047, "s": 4949, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5071, "s": 5047, "text": "Merge two sorted arrays" }, { "code": null, "e": 5092, "s": 5071, "text": "Operators in C / C++" }, { "code": null, "e": 5114, "s": 5092, "text": "Sieve of Eratosthenes" }, { "code": null, "e": 5128, "s": 5114, "text": "Prime Numbers" }, { "code": null, "e": 5165, "s": 5128, "text": "Minimum number of jumps to reach end" }, { "code": null, "e": 5183, "s": 5165, "text": "Python Dictionary" }, { "code": null, "e": 5208, "s": 5183, "text": "Reverse a string in Java" }, { "code": null, "e": 5224, "s": 5208, "text": "Arrays in C/C++" }, { "code": null, "e": 5247, "s": 5224, "text": "Introduction To PYTHON" } ]
How to get the width and height of an image ?
24 Jun, 2019 Given an image and the task is to get the width and height of the image using JavaScript. The width and height property is used to display the image width and height. Syntax for width: var width = this.width; Syntax for height: var height = this.height; Example 1: This example selects the image and then use this.width and this.height method to get the width and height of the image. <!DOCTYPE html><html> <head> <title> Get the real width and height of an image using JavaScript </title></head> <body style="text-align:center;"> <h2 style="color:green;"> GeeksforGeeks </h2> <h2 style="color:purple;"> Getting the real width and height of an image </h2> <script> function CheckImageSize() { var image = document.getElementById("Image").files[0]; createReader(image, function(w, h) { alert("Width is: " + w + "pixels, Height is: " + h + "pixels"); }); } function createReader(file, whenReady) { var reader = new FileReader; reader.onload = function(evt) { var image = new Image(); image.onload = function(evt) { var width = this.width; var height = this.height; if (whenReady) whenReady(width, height); }; image.src = evt.target.result; }; reader.readAsDataURL(file); } </script> <input type="file" id="Image" /> <input type="button" value="Find the dimensions" onclick="CheckImageSize()"/></body> <html> Output: Before clicking the button: After clicking the button: Example 2: This example display the dimension of an image. It will display the result without using the alert function. Here we will show the result in the same window. <!DOCTYPE html><html> <head> <title> Get the real width and height of an image using JavaScript </title></head> <body style="text-align:center;"> <img id="myImg" src="https://media.geeksforgeeks.org/wp-content/uploads/20190613121627/download9.png"> <p> Click the button to display the width and height of the image </p> <button onclick="myFunction()">Try it</button> <p>The width of the image in pixels:</p> <p id="geeks"></p> <p>The height of the image in pixels:</p> <p id="gfg"></p> <script> function myFunction() { var x = document.getElementById("myImg").width; var y = document.getElementById("myImg").height; document.getElementById("geeks").innerHTML = x; document.getElementById("gfg").innerHTML = y; } </script></body> </html> Output: Before clicking the button. After clicking the button: JavaScript-Misc JavaScript Web Technologies Web technologies Questions 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 Remove elements from a JavaScript Array Difference Between PUT and PATCH Request Roadmap to Learn JavaScript For Beginners JavaScript | Promises 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": 54, "s": 26, "text": "\n24 Jun, 2019" }, { "code": null, "e": 221, "s": 54, "text": "Given an image and the task is to get the width and height of the image using JavaScript. The width and height property is used to display the image width and height." }, { "code": null, "e": 239, "s": 221, "text": "Syntax for width:" }, { "code": null, "e": 263, "s": 239, "text": "var width = this.width;" }, { "code": null, "e": 282, "s": 263, "text": "Syntax for height:" }, { "code": null, "e": 308, "s": 282, "text": "var height = this.height;" }, { "code": null, "e": 439, "s": 308, "text": "Example 1: This example selects the image and then use this.width and this.height method to get the width and height of the image." }, { "code": "<!DOCTYPE html><html> <head> <title> Get the real width and height of an image using JavaScript </title></head> <body style=\"text-align:center;\"> <h2 style=\"color:green;\"> GeeksforGeeks </h2> <h2 style=\"color:purple;\"> Getting the real width and height of an image </h2> <script> function CheckImageSize() { var image = document.getElementById(\"Image\").files[0]; createReader(image, function(w, h) { alert(\"Width is: \" + w + \"pixels, Height is: \" + h + \"pixels\"); }); } function createReader(file, whenReady) { var reader = new FileReader; reader.onload = function(evt) { var image = new Image(); image.onload = function(evt) { var width = this.width; var height = this.height; if (whenReady) whenReady(width, height); }; image.src = evt.target.result; }; reader.readAsDataURL(file); } </script> <input type=\"file\" id=\"Image\" /> <input type=\"button\" value=\"Find the dimensions\" onclick=\"CheckImageSize()\"/></body> <html>", "e": 1837, "s": 439, "text": null }, { "code": null, "e": 1845, "s": 1837, "text": "Output:" }, { "code": null, "e": 1873, "s": 1845, "text": "Before clicking the button:" }, { "code": null, "e": 1900, "s": 1873, "text": "After clicking the button:" }, { "code": null, "e": 2069, "s": 1900, "text": "Example 2: This example display the dimension of an image. It will display the result without using the alert function. Here we will show the result in the same window." }, { "code": "<!DOCTYPE html><html> <head> <title> Get the real width and height of an image using JavaScript </title></head> <body style=\"text-align:center;\"> <img id=\"myImg\" src=\"https://media.geeksforgeeks.org/wp-content/uploads/20190613121627/download9.png\"> <p> Click the button to display the width and height of the image </p> <button onclick=\"myFunction()\">Try it</button> <p>The width of the image in pixels:</p> <p id=\"geeks\"></p> <p>The height of the image in pixels:</p> <p id=\"gfg\"></p> <script> function myFunction() { var x = document.getElementById(\"myImg\").width; var y = document.getElementById(\"myImg\").height; document.getElementById(\"geeks\").innerHTML = x; document.getElementById(\"gfg\").innerHTML = y; } </script></body> </html> ", "e": 2999, "s": 2069, "text": null }, { "code": null, "e": 3007, "s": 2999, "text": "Output:" }, { "code": null, "e": 3035, "s": 3007, "text": "Before clicking the button." }, { "code": null, "e": 3062, "s": 3035, "text": "After clicking the button:" }, { "code": null, "e": 3078, "s": 3062, "text": "JavaScript-Misc" }, { "code": null, "e": 3089, "s": 3078, "text": "JavaScript" }, { "code": null, "e": 3106, "s": 3089, "text": "Web Technologies" }, { "code": null, "e": 3133, "s": 3106, "text": "Web technologies Questions" }, { "code": null, "e": 3231, "s": 3133, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3292, "s": 3231, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 3332, "s": 3292, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 3373, "s": 3332, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 3415, "s": 3373, "text": "Roadmap to Learn JavaScript For Beginners" }, { "code": null, "e": 3437, "s": 3415, "text": "JavaScript | Promises" }, { "code": null, "e": 3470, "s": 3437, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 3532, "s": 3470, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 3593, "s": 3532, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 3643, "s": 3593, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
How to set the Size of the RadioButton in C#?
30 Jun, 2019 In Windows Forms, RadioButton control is used to select a single option among the group of the options. For example, select your gender from the given list, so you will choose only one option among three options like Male or Female or Transgender.In Windows Forms, you are allowed to adjust the size of the RadioButton using the Size Property of the RadioButton. This property represents both the height and width of the RadioButton in pixels. You can set this property in two different ways: 1. Design-Time: It is the easiest way to adjust the size of the RadioButton as shown in the following steps: Step 1: Create a windows form as shown in the below image:Visual Studio -> File -> New -> Project -> WindowsFormApp Step 2: Drag the RadioButton control from the ToolBox and drop it on the windows form. You are allowed to place a RadioButton control anywhere on the windows form according to your need. Step 3: After drag and drop you will go to the properties of the RadioButton control to adjust the size of RadioButton.Output: Output: 2. Run-Time: It is a little bit trickier than the above method. In this method, you can adjust the size of the RadioButton control programmatically with the help of given syntax: public System.Drawing.Size Size { get; set; } Here, Size indicates the height and width in pixels. The following steps show how to adjust the size of the RadioButton dynamically: Step 1: Create a radio button using the RadioButton() constructor is provided by the RadioButton class.// Creating radio button RadioButton r1 = new RadioButton(); // Creating radio button RadioButton r1 = new RadioButton(); Step 2: After creating RadioButton, set the Size property of the RadioButton provided by the RadioButton class.// Setting the size of the radio button r1.Size = new Size(100, 40); // Setting the size of the radio button r1.Size = new Size(100, 40); Step 3: And last add this RadioButton control to the form using Add() method.// Add this radio button to the form this.Controls.Add(r1); Example:using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp23 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting label Label l = new Label(); l.AutoSize = true; l.Location = new Point(176, 40); l.Text = "Select Post"; // Adding this label to the form this.Controls.Add(l); // Creating and setting the // properties of the RadioButton RadioButton r1 = new RadioButton(); r1.Size = new Size(100, 40); r1.Text = "Intern"; r1.Location = new Point(286, 40); r1.TextAlign = ContentAlignment.MiddleLeft; // Adding this label to the form this.Controls.Add(r1); // Creating and setting the // properties of the RadioButton RadioButton r2 = new RadioButton(); r2.Text = "Team Leader"; r2.Location = new Point(450, 40); r2.TextAlign = ContentAlignment.MiddleLeft; r2.Size = new Size(100, 40); // Adding this label to the form this.Controls.Add(r2); }}}Output: // Add this radio button to the form this.Controls.Add(r1); Example: using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp23 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting label Label l = new Label(); l.AutoSize = true; l.Location = new Point(176, 40); l.Text = "Select Post"; // Adding this label to the form this.Controls.Add(l); // Creating and setting the // properties of the RadioButton RadioButton r1 = new RadioButton(); r1.Size = new Size(100, 40); r1.Text = "Intern"; r1.Location = new Point(286, 40); r1.TextAlign = ContentAlignment.MiddleLeft; // Adding this label to the form this.Controls.Add(r1); // Creating and setting the // properties of the RadioButton RadioButton r2 = new RadioButton(); r2.Text = "Team Leader"; r2.Location = new Point(450, 40); r2.TextAlign = ContentAlignment.MiddleLeft; r2.Size = new Size(100, 40); // Adding this label to the form this.Controls.Add(r2); }}} Output: C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. C# | Multiple inheritance using interfaces Differences Between .NET Core and .NET Framework Extension Method in C# C# | List Class HashSet in C# with Examples C# | .NET Framework (Basic Architecture and Component Stack) Switch Statement in C# Lambda Expressions in C# Partial Classes in C# Hello World in C#
[ { "code": null, "e": 28, "s": 0, "text": "\n30 Jun, 2019" }, { "code": null, "e": 521, "s": 28, "text": "In Windows Forms, RadioButton control is used to select a single option among the group of the options. For example, select your gender from the given list, so you will choose only one option among three options like Male or Female or Transgender.In Windows Forms, you are allowed to adjust the size of the RadioButton using the Size Property of the RadioButton. This property represents both the height and width of the RadioButton in pixels. You can set this property in two different ways:" }, { "code": null, "e": 630, "s": 521, "text": "1. Design-Time: It is the easiest way to adjust the size of the RadioButton as shown in the following steps:" }, { "code": null, "e": 746, "s": 630, "text": "Step 1: Create a windows form as shown in the below image:Visual Studio -> File -> New -> Project -> WindowsFormApp" }, { "code": null, "e": 933, "s": 746, "text": "Step 2: Drag the RadioButton control from the ToolBox and drop it on the windows form. You are allowed to place a RadioButton control anywhere on the windows form according to your need." }, { "code": null, "e": 1060, "s": 933, "text": "Step 3: After drag and drop you will go to the properties of the RadioButton control to adjust the size of RadioButton.Output:" }, { "code": null, "e": 1068, "s": 1060, "text": "Output:" }, { "code": null, "e": 1247, "s": 1068, "text": "2. Run-Time: It is a little bit trickier than the above method. In this method, you can adjust the size of the RadioButton control programmatically with the help of given syntax:" }, { "code": null, "e": 1293, "s": 1247, "text": "public System.Drawing.Size Size { get; set; }" }, { "code": null, "e": 1426, "s": 1293, "text": "Here, Size indicates the height and width in pixels. The following steps show how to adjust the size of the RadioButton dynamically:" }, { "code": null, "e": 1591, "s": 1426, "text": "Step 1: Create a radio button using the RadioButton() constructor is provided by the RadioButton class.// Creating radio button\nRadioButton r1 = new RadioButton();\n" }, { "code": null, "e": 1653, "s": 1591, "text": "// Creating radio button\nRadioButton r1 = new RadioButton();\n" }, { "code": null, "e": 1835, "s": 1653, "text": "Step 2: After creating RadioButton, set the Size property of the RadioButton provided by the RadioButton class.// Setting the size of the radio button\n r1.Size = new Size(100, 40);\n" }, { "code": null, "e": 1906, "s": 1835, "text": "// Setting the size of the radio button\n r1.Size = new Size(100, 40);\n" }, { "code": null, "e": 3397, "s": 1906, "text": "Step 3: And last add this RadioButton control to the form using Add() method.// Add this radio button to the form\nthis.Controls.Add(r1);\nExample:using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp23 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting label Label l = new Label(); l.AutoSize = true; l.Location = new Point(176, 40); l.Text = \"Select Post\"; // Adding this label to the form this.Controls.Add(l); // Creating and setting the // properties of the RadioButton RadioButton r1 = new RadioButton(); r1.Size = new Size(100, 40); r1.Text = \"Intern\"; r1.Location = new Point(286, 40); r1.TextAlign = ContentAlignment.MiddleLeft; // Adding this label to the form this.Controls.Add(r1); // Creating and setting the // properties of the RadioButton RadioButton r2 = new RadioButton(); r2.Text = \"Team Leader\"; r2.Location = new Point(450, 40); r2.TextAlign = ContentAlignment.MiddleLeft; r2.Size = new Size(100, 40); // Adding this label to the form this.Controls.Add(r2); }}}Output:" }, { "code": null, "e": 3458, "s": 3397, "text": "// Add this radio button to the form\nthis.Controls.Add(r1);\n" }, { "code": null, "e": 3467, "s": 3458, "text": "Example:" }, { "code": "using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp23 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting label Label l = new Label(); l.AutoSize = true; l.Location = new Point(176, 40); l.Text = \"Select Post\"; // Adding this label to the form this.Controls.Add(l); // Creating and setting the // properties of the RadioButton RadioButton r1 = new RadioButton(); r1.Size = new Size(100, 40); r1.Text = \"Intern\"; r1.Location = new Point(286, 40); r1.TextAlign = ContentAlignment.MiddleLeft; // Adding this label to the form this.Controls.Add(r1); // Creating and setting the // properties of the RadioButton RadioButton r2 = new RadioButton(); r2.Text = \"Team Leader\"; r2.Location = new Point(450, 40); r2.TextAlign = ContentAlignment.MiddleLeft; r2.Size = new Size(100, 40); // Adding this label to the form this.Controls.Add(r2); }}}", "e": 4806, "s": 3467, "text": null }, { "code": null, "e": 4814, "s": 4806, "text": "Output:" }, { "code": null, "e": 4817, "s": 4814, "text": "C#" }, { "code": null, "e": 4915, "s": 4817, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4958, "s": 4915, "text": "C# | Multiple inheritance using interfaces" }, { "code": null, "e": 5007, "s": 4958, "text": "Differences Between .NET Core and .NET Framework" }, { "code": null, "e": 5030, "s": 5007, "text": "Extension Method in C#" }, { "code": null, "e": 5046, "s": 5030, "text": "C# | List Class" }, { "code": null, "e": 5074, "s": 5046, "text": "HashSet in C# with Examples" }, { "code": null, "e": 5135, "s": 5074, "text": "C# | .NET Framework (Basic Architecture and Component Stack)" }, { "code": null, "e": 5158, "s": 5135, "text": "Switch Statement in C#" }, { "code": null, "e": 5183, "s": 5158, "text": "Lambda Expressions in C#" }, { "code": null, "e": 5205, "s": 5183, "text": "Partial Classes in C#" } ]
How to convert string to array of integers in java?
You can convert a String to integer using the parseInt() method of the Integer class. To convert a string array to an integer array, convert each element of it to integer and populate the integer array with them. Live Demo import java.util.Arrays; public class StringToIntegerArray { public static void main(String args[]) { String [] str = {"123", "345", "437", "894"}; int size = str.length; int [] arr = new int [size]; for(int i=0; i<size; i++) { arr[i] = Integer.parseInt(str[i]); } System.out.println(Arrays.toString(arr)); } } [123, 345, 437, 894]
[ { "code": null, "e": 1275, "s": 1062, "text": "You can convert a String to integer using the parseInt() method of the Integer class. To convert a string array to an integer array, convert each element of it to integer and populate the integer array with them." }, { "code": null, "e": 1286, "s": 1275, "text": " Live Demo" }, { "code": null, "e": 1648, "s": 1286, "text": "import java.util.Arrays;\npublic class StringToIntegerArray {\n public static void main(String args[]) {\n String [] str = {\"123\", \"345\", \"437\", \"894\"};\n int size = str.length;\n int [] arr = new int [size];\n for(int i=0; i<size; i++) {\n arr[i] = Integer.parseInt(str[i]);\n }\n System.out.println(Arrays.toString(arr));\n }\n}" }, { "code": null, "e": 1669, "s": 1648, "text": "[123, 345, 437, 894]" } ]
Apache Camel - CamelContext
CamelContext provides access to all other services in Camel as shown in the following figure − Let us look at the various services. The Registry module by default is a JNDI registry, which holds the name of the various Javabeans that your application uses. If you use Camel with Spring, this will be the Spring ApplicationContext. If you use Camel in OSGI container, this will be OSGI registry. The Type converters as the name suggests contains the various loaded type converters, which convert your input from one format to another. You may use the built-in type converters or provide your own mechanism of conversion. The Components module contains the components used by your application. The components are loaded by auto discovery on the classpath that you specify. In case of the OSGI container, these are loaded whenever a new bundle is activated. We have already discussed the Endpoints and Routes in the previous chapters. The Data formats module contains the loaded data formats and finally the Languages module represents the loaded languages. The code snippet here will give you a glimpse of how a CamelContext is created in a Camel application − CamelContext context = new DefaultCamelContext(); try { context.addRoutes(new RouteBuilder() { // Configure filters and routes } } ); The DefaultCamelContext class provides a concrete implementation of CamelContext. In addRoutes method, we create an anonymous instance of RouteBuilder. You may create multiple RouteBuilder instances to define more than one routing. Each route in the same context must have a unique ID. Routes can be added dynamically at the runtime. A route with the ID same as the one previously defined will replace the older route. What goes inside the RouteBuilder instance is described next. The router defines the rule for moving the message from to a to location. You use RouteBuilder to define a route in Java DSL. You create a route by extending the built-in RouteBuilder class. The route begins with a from endpoint and finishes at one or more to endpoints. In between the two, you implement the processing logic. You may configure any number of routes within a single configure method. Here is a typical example of how route is created − context.addRoutes(new RouteBuilder() { @Override public void configure() throws Exception { from("direct:DistributeOrderDSL") .to("stream:out"); } } We override the configure method of RouteBuilder class and implement our routing and filtering mechanism in it. In the current case, we redirect the input received from the Endpoint DistributeOrderDSL to the console, which is specified by the Endpoint stream:out. You may create the routes in different languages. Here are a few examples of how the same route is defined in three different languages − from ("file:/order").to("jms:orderQueue"); <route> <from uri = "file:/order"/> <to uri = "jms:orderQueue"/> </route> from "file:/order" -> "jms:orderQueue" You use filter to select a part of input content. To set up a filter, you use any arbitrary Predicate implementation. The filtered input is then sent to your desired destination Endpoint. In this example, we filter out all orders for the soap so that those can be collectively sent to a soap supplier. from("direct:DistributeOrderDSL") .split(xpath("//order[@product = 'soaps']/items")) .to("stream:out"); In the example, we have used xpath predicate for filtering. If you prefer to use Java class for filtering, use the following code − from("direct:DistributeOrderDSL") .filter() .method(new Order(),"filter") .to("stream:out"); The Order is your custom Java class with your own filtering mechanism. You may combine multiple predicates in a single routing as here − from("direct:DistributeOrderDSL") .choice() .when(header("order").isEqualTo("oil")) .to("direct:oil") .when(header("order").isEqualTo("milk")) .to("direct:milk") .otherwise() .to("direct:d"); So now all “oil” orders will go to oil vendor, “milk” orders will go to milk vendor and the rest to a common pool. You may also use custom processing. The example below creates a custom processor called myCustomProcessor and uses it in the route builder. Processor myCustomProcessor = new Processor() { public void process(Exchange exchange) { // implement your custom processing } }; RouteBuilder builder = new RouteBuilder() { public void configure() { from("direct:DistributeOrderDSL") .process(myProcessor); } }; You may use custom processors along with choice and filtering to get a better control on your mediation and routing − from("direct:DistributeOrderDSL") .filter(header("order").isEqualTo("milk")) .process(myProcessor); The routes may be defined in bulkier XML, if you prefer it. The following XML snippet shows how to create a route along with some filtering via Spring XML − <camelContext xmlns = "http://camel.apache.org/schema/spring"> <route> <from uri = "direct:DistributeOrderXML"/> <log message = "Split by Distribute Order"/> <split> <xpath>//order[@product = 'Oil']/items</xpath> <to uri = "file:src/main/resources/order/"/> <to uri = "stream:out"/> </split> </route> </camelContext> Having seen how routes are built, we will now see the various techniques of creating Endpoints. 46 Lectures 3.5 hours Arnab Chakraborty 23 Lectures 1.5 hours Mukund Kumar Mishra 16 Lectures 1 hours Nilay Mehta 52 Lectures 1.5 hours Bigdata Engineer 14 Lectures 1 hours Bigdata Engineer 23 Lectures 1 hours Bigdata Engineer Print Add Notes Bookmark this page
[ { "code": null, "e": 1966, "s": 1871, "text": "CamelContext provides access to all other services in Camel as shown in the following figure −" }, { "code": null, "e": 2926, "s": 1966, "text": "Let us look at the various services. The Registry module by default is a JNDI registry, which holds the name of the various Javabeans that your application uses. If you use Camel with Spring, this will be the Spring ApplicationContext. If you use Camel in OSGI container, this will be OSGI registry. The Type converters as the name suggests contains the various loaded type converters, which convert your input from one format to another. You may use the built-in type converters or provide your own mechanism of conversion. The Components module contains the components used by your application. The components are loaded by auto discovery on the classpath that you specify. In case of the OSGI container, these are loaded whenever a new bundle is activated. We have already discussed the Endpoints and Routes in the previous chapters. The Data formats module contains the loaded data formats and finally the Languages module represents the loaded languages." }, { "code": null, "e": 3030, "s": 2926, "text": "The code snippet here will give you a glimpse of how a CamelContext is created in a Camel application −" }, { "code": null, "e": 3177, "s": 3030, "text": "CamelContext context = new DefaultCamelContext();\ntry {\n context.addRoutes(new RouteBuilder() {\n // Configure filters and routes\n }\n}\n);\n" }, { "code": null, "e": 3596, "s": 3177, "text": "The DefaultCamelContext class provides a concrete implementation of CamelContext. In addRoutes method, we create an anonymous instance of RouteBuilder. You may create multiple RouteBuilder instances to define more than one routing. Each route in the same context must have a unique ID. Routes can be added dynamically at the runtime. A route with the ID same as the one previously defined will replace the older route." }, { "code": null, "e": 3658, "s": 3596, "text": "What goes inside the RouteBuilder instance is described next." }, { "code": null, "e": 4058, "s": 3658, "text": "The router defines the rule for moving the message from to a to location. You use RouteBuilder to define a route in Java DSL. You create a route by extending the built-in RouteBuilder class. The route begins with a from endpoint and finishes at one or more to endpoints. In between the two, you implement the processing logic. You may configure any number of routes within a single configure method." }, { "code": null, "e": 4110, "s": 4058, "text": "Here is a typical example of how route is created −" }, { "code": null, "e": 4280, "s": 4110, "text": "context.addRoutes(new RouteBuilder() {\n @Override\n public void configure() throws Exception {\n from(\"direct:DistributeOrderDSL\")\n .to(\"stream:out\");\n }\n}" }, { "code": null, "e": 4544, "s": 4280, "text": "We override the configure method of RouteBuilder class and implement our routing and filtering mechanism in it. In the current case, we redirect the input received from the Endpoint DistributeOrderDSL to the console, which is specified by the Endpoint stream:out." }, { "code": null, "e": 4682, "s": 4544, "text": "You may create the routes in different languages. Here are a few examples of how the same route is defined in three different languages −" }, { "code": null, "e": 4726, "s": 4682, "text": "from (\"file:/order\").to(\"jms:orderQueue\");\n" }, { "code": null, "e": 4806, "s": 4726, "text": "<route>\n <from uri = \"file:/order\"/>\n <to uri = \"jms:orderQueue\"/>\n</route>" }, { "code": null, "e": 4845, "s": 4806, "text": "from \"file:/order\" -> \"jms:orderQueue\"" }, { "code": null, "e": 5147, "s": 4845, "text": "You use filter to select a part of input content. To set up a filter, you use any arbitrary Predicate implementation. The filtered input is then sent to your desired destination Endpoint. In this example, we filter out all orders for the soap so that those can be collectively sent to a soap supplier." }, { "code": null, "e": 5260, "s": 5147, "text": "from(\"direct:DistributeOrderDSL\")\n .split(xpath(\"//order[@product = 'soaps']/items\"))\n .to(\"stream:out\");" }, { "code": null, "e": 5392, "s": 5260, "text": "In the example, we have used xpath predicate for filtering. If you prefer to use Java class for filtering, use the following code −" }, { "code": null, "e": 5503, "s": 5392, "text": "from(\"direct:DistributeOrderDSL\")\n .filter()\n .method(new Order(),\"filter\")\n .to(\"stream:out\");" }, { "code": null, "e": 5574, "s": 5503, "text": "The Order is your custom Java class with your own filtering mechanism." }, { "code": null, "e": 5640, "s": 5574, "text": "You may combine multiple predicates in a single routing as here −" }, { "code": null, "e": 5880, "s": 5640, "text": "from(\"direct:DistributeOrderDSL\")\n .choice()\n .when(header(\"order\").isEqualTo(\"oil\"))\n .to(\"direct:oil\")\n .when(header(\"order\").isEqualTo(\"milk\"))\n .to(\"direct:milk\")\n .otherwise()\n .to(\"direct:d\");" }, { "code": null, "e": 5995, "s": 5880, "text": "So now all “oil” orders will go to oil vendor, “milk” orders will go to milk vendor and the rest to a common pool." }, { "code": null, "e": 6135, "s": 5995, "text": "You may also use custom processing. The example below creates a custom processor called myCustomProcessor and uses it in the route builder." }, { "code": null, "e": 6427, "s": 6135, "text": "Processor myCustomProcessor = new Processor() {\n public void process(Exchange exchange) {\n // implement your custom processing\n }\n};\nRouteBuilder builder = new RouteBuilder() {\n public void configure() {\n from(\"direct:DistributeOrderDSL\")\n .process(myProcessor);\n }\n};" }, { "code": null, "e": 6545, "s": 6427, "text": "You may use custom processors along with choice and filtering to get a better control on your mediation and routing −" }, { "code": null, "e": 6655, "s": 6545, "text": "from(\"direct:DistributeOrderDSL\")\n .filter(header(\"order\").isEqualTo(\"milk\"))\n .process(myProcessor);\n" }, { "code": null, "e": 6812, "s": 6655, "text": "The routes may be defined in bulkier XML, if you prefer it. The following XML snippet shows how to create a route along with some filtering via Spring XML −" }, { "code": null, "e": 7186, "s": 6812, "text": "<camelContext xmlns = \"http://camel.apache.org/schema/spring\">\n <route>\n <from uri = \"direct:DistributeOrderXML\"/>\n <log message = \"Split by Distribute Order\"/>\n <split>\n <xpath>//order[@product = 'Oil']/items</xpath>\n <to uri = \"file:src/main/resources/order/\"/>\n <to uri = \"stream:out\"/>\n </split>\n </route>\n</camelContext>" }, { "code": null, "e": 7282, "s": 7186, "text": "Having seen how routes are built, we will now see the various techniques of creating Endpoints." }, { "code": null, "e": 7317, "s": 7282, "text": "\n 46 Lectures \n 3.5 hours \n" }, { "code": null, "e": 7336, "s": 7317, "text": " Arnab Chakraborty" }, { "code": null, "e": 7371, "s": 7336, "text": "\n 23 Lectures \n 1.5 hours \n" }, { "code": null, "e": 7392, "s": 7371, "text": " Mukund Kumar Mishra" }, { "code": null, "e": 7425, "s": 7392, "text": "\n 16 Lectures \n 1 hours \n" }, { "code": null, "e": 7438, "s": 7425, "text": " Nilay Mehta" }, { "code": null, "e": 7473, "s": 7438, "text": "\n 52 Lectures \n 1.5 hours \n" }, { "code": null, "e": 7491, "s": 7473, "text": " Bigdata Engineer" }, { "code": null, "e": 7524, "s": 7491, "text": "\n 14 Lectures \n 1 hours \n" }, { "code": null, "e": 7542, "s": 7524, "text": " Bigdata Engineer" }, { "code": null, "e": 7575, "s": 7542, "text": "\n 23 Lectures \n 1 hours \n" }, { "code": null, "e": 7593, "s": 7575, "text": " Bigdata Engineer" }, { "code": null, "e": 7600, "s": 7593, "text": " Print" }, { "code": null, "e": 7611, "s": 7600, "text": " Add Notes" } ]
JupyterLab is Now Available as a Desktop App. Should You Care? | by Dario Radečić | Towards Data Science
The most popular data science IDE just got better. The days of launching JupyterLab through the terminal are thankfully over, as the desktop version was released weeks ago. Yes, you read that right — you can now install JupyterLab as a desktop application on any OS. And this article will show you how. Don’t feel like reading? Watch the six-minute video instead: No, you don’t need to download the source code and build it — but you can if you want. The authors placed links to the installers on their GitHub page, so download the file that matches your OS: For example, clicking on macOS Installer would download a .pkg file, Windows Installer would download .exe and so on. The installation is as simple as they come. On Mac, you’ll have to click on Continue a couple of times. I imagine the procedure is identical on Windows, and Linux versions are installable through the terminal. Once installed, you’ll find JupyterLab listed in your applications. Once opened, a familiar interface pops up: And that’s all you have to do — JupyterLab app is now installed. The interface of the desktop app is identical to the browser alternative. After you create a notebook, you can mess around with Markdown — select a cell and press ESC, M, and Enter, one after the other: # Heading 1 - List item 1- List item 2**This is bolded**.$$ \Large c = \sqrt{a^2 + b^2} $$ You can run Python code and use any installed library. For example, here’s how to make a Numpy array: You can also change the kernel. Let’s say you have a dedicated virtual environment for a specific project — you can access it by clicking on the kernel options at the bottom of the screen: From there, simply select the environment you want. One of mine is named env_tensorflow, so I’ll select it and try to import TensorFlow: As you can see, changing the environment restarts the runtime. It’s always a good idea to select the correct environment first, and then run the code. It will save you a lot of time, especially if you’re working with large datasets. And that’s JupyterLab Desktop in a nutshell. The question remains — should you use it? After all, it’s identical to the browser-based version. I see two reasons why you might opt for the desktop version: You prefer dedicated desktop apps in general — Navigating browser tabs gets messy real fast. Nobody needs yet another tab that’s somehow impossible to find when you need it. You accidentally close the browser way too often — That’s exactly what happens to me. On Mac, you can close any selected application by pressing CMD+C. Oftentimes, I have JupyterLab running in Safari on the left side of the screen and something like Stack Overflow on the right. Pressing CMD+C will close both, even if you only selected the right one. It’s super annoying and happens more often than I want to admit. Apart from that, the desktop version has no edge over its browser-based brother. What do you guys think? Will you install JupyterLab desktop app or are you satisfied with the web instance? Please let me know in the comment section below. Loved the article? Become a Medium member to continue learning without limits. I’ll receive a portion of your membership fee if you use the following link, with no extra cost to you. medium.com Sign up for my newsletter Subscribe on YouTube Connect on LinkedIn
[ { "code": null, "e": 474, "s": 171, "text": "The most popular data science IDE just got better. The days of launching JupyterLab through the terminal are thankfully over, as the desktop version was released weeks ago. Yes, you read that right — you can now install JupyterLab as a desktop application on any OS. And this article will show you how." }, { "code": null, "e": 535, "s": 474, "text": "Don’t feel like reading? Watch the six-minute video instead:" }, { "code": null, "e": 730, "s": 535, "text": "No, you don’t need to download the source code and build it — but you can if you want. The authors placed links to the installers on their GitHub page, so download the file that matches your OS:" }, { "code": null, "e": 848, "s": 730, "text": "For example, clicking on macOS Installer would download a .pkg file, Windows Installer would download .exe and so on." }, { "code": null, "e": 1058, "s": 848, "text": "The installation is as simple as they come. On Mac, you’ll have to click on Continue a couple of times. I imagine the procedure is identical on Windows, and Linux versions are installable through the terminal." }, { "code": null, "e": 1169, "s": 1058, "text": "Once installed, you’ll find JupyterLab listed in your applications. Once opened, a familiar interface pops up:" }, { "code": null, "e": 1234, "s": 1169, "text": "And that’s all you have to do — JupyterLab app is now installed." }, { "code": null, "e": 1437, "s": 1234, "text": "The interface of the desktop app is identical to the browser alternative. After you create a notebook, you can mess around with Markdown — select a cell and press ESC, M, and Enter, one after the other:" }, { "code": null, "e": 1528, "s": 1437, "text": "# Heading 1 - List item 1- List item 2**This is bolded**.$$ \\Large c = \\sqrt{a^2 + b^2} $$" }, { "code": null, "e": 1630, "s": 1528, "text": "You can run Python code and use any installed library. For example, here’s how to make a Numpy array:" }, { "code": null, "e": 1819, "s": 1630, "text": "You can also change the kernel. Let’s say you have a dedicated virtual environment for a specific project — you can access it by clicking on the kernel options at the bottom of the screen:" }, { "code": null, "e": 1956, "s": 1819, "text": "From there, simply select the environment you want. One of mine is named env_tensorflow, so I’ll select it and try to import TensorFlow:" }, { "code": null, "e": 2189, "s": 1956, "text": "As you can see, changing the environment restarts the runtime. It’s always a good idea to select the correct environment first, and then run the code. It will save you a lot of time, especially if you’re working with large datasets." }, { "code": null, "e": 2332, "s": 2189, "text": "And that’s JupyterLab Desktop in a nutshell. The question remains — should you use it? After all, it’s identical to the browser-based version." }, { "code": null, "e": 2393, "s": 2332, "text": "I see two reasons why you might opt for the desktop version:" }, { "code": null, "e": 2567, "s": 2393, "text": "You prefer dedicated desktop apps in general — Navigating browser tabs gets messy real fast. Nobody needs yet another tab that’s somehow impossible to find when you need it." }, { "code": null, "e": 2984, "s": 2567, "text": "You accidentally close the browser way too often — That’s exactly what happens to me. On Mac, you can close any selected application by pressing CMD+C. Oftentimes, I have JupyterLab running in Safari on the left side of the screen and something like Stack Overflow on the right. Pressing CMD+C will close both, even if you only selected the right one. It’s super annoying and happens more often than I want to admit." }, { "code": null, "e": 3065, "s": 2984, "text": "Apart from that, the desktop version has no edge over its browser-based brother." }, { "code": null, "e": 3222, "s": 3065, "text": "What do you guys think? Will you install JupyterLab desktop app or are you satisfied with the web instance? Please let me know in the comment section below." }, { "code": null, "e": 3405, "s": 3222, "text": "Loved the article? Become a Medium member to continue learning without limits. I’ll receive a portion of your membership fee if you use the following link, with no extra cost to you." }, { "code": null, "e": 3416, "s": 3405, "text": "medium.com" }, { "code": null, "e": 3442, "s": 3416, "text": "Sign up for my newsletter" }, { "code": null, "e": 3463, "s": 3442, "text": "Subscribe on YouTube" } ]
How should I enable LOAD DATA LOCAL INFILE in my.cnf in MySQL?
We can enable it with the help of the SET command with GLOBAL. The first time, local infile will be off. The following is the syntax. mysql> SHOW GLOBAL VARIABLES LIKE 'local_infile'; Here is the output. +---------------+-------+ | Variable_name | Value | +---------------+-------+ | local_infile | OFF | +---------------+-------+ 1 row in set (0.01 sec) We can enable the local infile with the help of ON or boolean value true or numeric value 1. The following is the syntax to enable the local infile. mysql> SET GLOBAL local_infile = 'ON'; Query OK, 0 rows affected (0.00 sec) mysql> SET GLOBAL local_infile = 1; Query OK, 0 rows affected (0.00 sec) mysql> SET GLOBAL local_infile = true; Query OK, 0 rows affected (0.00 sec) In MySQL version 8.0.12, let us check if it is ON or not. mysql> SHOW GLOBAL VARIABLES LIKE 'local_infile'; The following is the output. +---------------+-------+ | Variable_name | Value | +---------------+-------+ | local_infile | ON | +---------------+-------+ 1 row in set (0.00 sec) After restarting MySQL, it will set local infile to ON.
[ { "code": null, "e": 1167, "s": 1062, "text": "We can enable it with the help of the SET command with GLOBAL. The first time, local infile will be off." }, { "code": null, "e": 1196, "s": 1167, "text": "The following is the syntax." }, { "code": null, "e": 1247, "s": 1196, "text": "mysql> SHOW GLOBAL VARIABLES LIKE 'local_infile';\n" }, { "code": null, "e": 1267, "s": 1247, "text": "Here is the output." }, { "code": null, "e": 1422, "s": 1267, "text": "+---------------+-------+\n| Variable_name | Value |\n+---------------+-------+\n| local_infile | OFF |\n+---------------+-------+\n1 row in set (0.01 sec)\n" }, { "code": null, "e": 1571, "s": 1422, "text": "We can enable the local infile with the help of ON or boolean value true or numeric value 1. The following is the syntax to enable the local infile." }, { "code": null, "e": 1798, "s": 1571, "text": "mysql> SET GLOBAL local_infile = 'ON';\nQuery OK, 0 rows affected (0.00 sec)\n\nmysql> SET GLOBAL local_infile = 1;\nQuery OK, 0 rows affected (0.00 sec)\n\nmysql> SET GLOBAL local_infile = true;\nQuery OK, 0 rows affected (0.00 sec)" }, { "code": null, "e": 1856, "s": 1798, "text": "In MySQL version 8.0.12, let us check if it is ON or not." }, { "code": null, "e": 1907, "s": 1856, "text": "mysql> SHOW GLOBAL VARIABLES LIKE 'local_infile';" }, { "code": null, "e": 1936, "s": 1907, "text": "The following is the output." }, { "code": null, "e": 2091, "s": 1936, "text": "+---------------+-------+\n| Variable_name | Value |\n+---------------+-------+\n| local_infile | ON |\n+---------------+-------+\n1 row in set (0.00 sec)\n" }, { "code": null, "e": 2147, "s": 2091, "text": "After restarting MySQL, it will set local infile to ON." } ]
Quantum Physics Visualization With Python | by Syed Sadat Nazrul | Towards Data Science
On this blog, I have decided to review some college level quantum chemistry for deriving electron orbitals. The additional fun part is that, we are going to visualize wave functions and electron probabilities.. using Python! In 1926, Erwin Schrodinger advanced the famous wave equation that relates the energy of a system to its wave properties. Because its application to the hydrogen atom is rather complicated, we shall first use wave equation to solve the particle-in-a-box. The Schrodinger Wave equation expressing in 1D is Now, to simplify our equation, we assume a Particle In A Box. The particle-in-a-box problem does not correspond to any real chemical system. Its usefulness in our context is that it illustrates several quantum mechanical features. The potential energy at the barrier is set to infinity (i.e. the particle cannot escape) and the potential energy inside the barrier is set to 0. Under these conditions, classical mechanics predicts that the particle has an equal probability of being in any part of the box and the kinetic energy of the particle is allowed to have any value. Taking this assumption into consideration, we get different equations for the particle’s energy at the barrier and inside the box. At the barrier, V is infinite and the hence, the particle does not exist: Inside the box, V is zero and hence the wave can have any finite value: Inside the box, we can rearrange the equation as follows: As we can see above, the wave function would be such that if differentiated twice, should give the same function multiplied by E. The sine function possesses this behavior. Now, we need to evaluate the values for the constants, α and A. For α, we use the wave equations at the barriers, where the wave functions equal 0. Now plugging in the value for α: We can determine the value of A by requiring the wave function to be normalized. This is because, the particle must exist somewhere in the box. Hence, the sum of the probability of finding the particle in the box is 1: Plugging in the values, the final wave and energy equations are: Visualizing the Energy and wave functions using Python: import matplotlib.pyplot as pltimport numpy as np#Constantsh = 6.626e-34m = 9.11e-31#Values for L and xx_list = np.linspace(0,1,100)L = 1def psi(n,L,x): return np.sqrt(2/L)*np.sin(n*np.pi*x/L)def psi_2(n,L,x): return np.square(psi(n,L,x))plt.figure(figsize=(15,10))plt.suptitle("Wave Functions", fontsize=18)for n in range(1,4): #Empty lists for energy and psi wave psi_2_list = [] psi_list = [] for x in x_list: psi_2_list.append(psi_2(n,L,x)) psi_list.append(psi(n,L,x)) plt.subplot(3,2,2*n-1) plt.plot(x_list, psi_list) plt.xlabel("L", fontsize=13) plt.ylabel("Ψ", fontsize=13) plt.xticks(np.arange(0, 1, step=0.5)) plt.title("n="+str(n), fontsize=16) plt.grid() plt.subplot(3,2,2*n) plt.plot(x_list, psi_2_list) plt.xlabel("L", fontsize=13) plt.ylabel("Ψ*Ψ", fontsize=13) plt.xticks(np.arange(0, 1, step=0.5)) plt.title("n="+str(n), fontsize=16) plt.grid()plt.tight_layout(rect=[0, 0.03, 1, 0.95]) Notice how there are regions where both Ψ and Ψ* Ψ are zero on the same regions. This is known as the node. Energy levels of orbitals are not continuous. They exist at discreet levels, as represented by the location of the nodes. Also, as the n value increases, the density of the wave inside the box also increases. Now to get the wave equation with respect to quantum numbers, it needs to be in the following 3D format: Now, separating of variables depends on the type of atom and is too complex to cover in this blog post. Instead, we will just write the solution directly for plotting. For the following, we will be using the functions of R and Y for Hydrogen atom without deriving them. First, let’s look at the 1s orbital: The 1s wave function reveals that the probability of an electron appearing decreases exponentially as we move away from the nucleus. It also reveals a spherical shape. import matplotlib.pyplot as pltimport numpy as np#Probability of 1sdef prob_1s(x,y,z): r=np.sqrt(np.square(x)+np.square(y)+np.square(z)) #Remember.. probability is psi squared! return np.square(np.exp(-r)/np.sqrt(np.pi))#Random coordinatesx=np.linspace(0,1,30)y=np.linspace(0,1,30)z=np.linspace(0,1,30)elements = []probability = []for ix in x: for iy in y: for iz in z: #Serialize into 1D object elements.append(str((ix,iy,iz))) probability.append(prob_1s(ix,iy,iz)) #Ensure sum of probability is 1probability = probability/sum(probability)#Getting electron coordinates based on probabiliycoord = np.random.choice(elements, size=100000, replace=True, p=probability)elem_mat = [i.split(',') for i in coord]elem_mat = np.matrix(elem_mat)x_coords = [float(i.item()[1:]) for i in elem_mat[:,0]] y_coords = [float(i.item()) for i in elem_mat[:,1]] z_coords = [float(i.item()[0:-1]) for i in elem_mat[:,2]]#Plottingfig = plt.figure(figsize=(10,10))ax = fig.add_subplot(111, projection='3d')ax.scatter(x_coords, y_coords, z_coords, alpha=0.05, s=2)ax.set_title("Hydrogen 1s density")plt.show() A little hard to see from the electron density plot above. However, you can see that it has a spherical shape. As we move further away from the center, the density decreases. Generally, the cut off point is when the probability of the electron appearing is at 99%. The same density plots can also be derived for the other spdf orbitals. Hopefully, this blog has motivated you to have fun with Quantum Physics and Python programming! For more on python based visualizations, check out my blog: Python based Plotting with Matplotlib
[ { "code": null, "e": 397, "s": 172, "text": "On this blog, I have decided to review some college level quantum chemistry for deriving electron orbitals. The additional fun part is that, we are going to visualize wave functions and electron probabilities.. using Python!" }, { "code": null, "e": 701, "s": 397, "text": "In 1926, Erwin Schrodinger advanced the famous wave equation that relates the energy of a system to its wave properties. Because its application to the hydrogen atom is rather complicated, we shall first use wave equation to solve the particle-in-a-box. The Schrodinger Wave equation expressing in 1D is" }, { "code": null, "e": 763, "s": 701, "text": "Now, to simplify our equation, we assume a Particle In A Box." }, { "code": null, "e": 1406, "s": 763, "text": "The particle-in-a-box problem does not correspond to any real chemical system. Its usefulness in our context is that it illustrates several quantum mechanical features. The potential energy at the barrier is set to infinity (i.e. the particle cannot escape) and the potential energy inside the barrier is set to 0. Under these conditions, classical mechanics predicts that the particle has an equal probability of being in any part of the box and the kinetic energy of the particle is allowed to have any value. Taking this assumption into consideration, we get different equations for the particle’s energy at the barrier and inside the box." }, { "code": null, "e": 1480, "s": 1406, "text": "At the barrier, V is infinite and the hence, the particle does not exist:" }, { "code": null, "e": 1552, "s": 1480, "text": "Inside the box, V is zero and hence the wave can have any finite value:" }, { "code": null, "e": 1610, "s": 1552, "text": "Inside the box, we can rearrange the equation as follows:" }, { "code": null, "e": 1783, "s": 1610, "text": "As we can see above, the wave function would be such that if differentiated twice, should give the same function multiplied by E. The sine function possesses this behavior." }, { "code": null, "e": 1931, "s": 1783, "text": "Now, we need to evaluate the values for the constants, α and A. For α, we use the wave equations at the barriers, where the wave functions equal 0." }, { "code": null, "e": 1964, "s": 1931, "text": "Now plugging in the value for α:" }, { "code": null, "e": 2183, "s": 1964, "text": "We can determine the value of A by requiring the wave function to be normalized. This is because, the particle must exist somewhere in the box. Hence, the sum of the probability of finding the particle in the box is 1:" }, { "code": null, "e": 2248, "s": 2183, "text": "Plugging in the values, the final wave and energy equations are:" }, { "code": null, "e": 2304, "s": 2248, "text": "Visualizing the Energy and wave functions using Python:" }, { "code": null, "e": 3280, "s": 2304, "text": "import matplotlib.pyplot as pltimport numpy as np#Constantsh = 6.626e-34m = 9.11e-31#Values for L and xx_list = np.linspace(0,1,100)L = 1def psi(n,L,x): return np.sqrt(2/L)*np.sin(n*np.pi*x/L)def psi_2(n,L,x): return np.square(psi(n,L,x))plt.figure(figsize=(15,10))plt.suptitle(\"Wave Functions\", fontsize=18)for n in range(1,4): #Empty lists for energy and psi wave psi_2_list = [] psi_list = [] for x in x_list: psi_2_list.append(psi_2(n,L,x)) psi_list.append(psi(n,L,x)) plt.subplot(3,2,2*n-1) plt.plot(x_list, psi_list) plt.xlabel(\"L\", fontsize=13) plt.ylabel(\"Ψ\", fontsize=13) plt.xticks(np.arange(0, 1, step=0.5)) plt.title(\"n=\"+str(n), fontsize=16) plt.grid() plt.subplot(3,2,2*n) plt.plot(x_list, psi_2_list) plt.xlabel(\"L\", fontsize=13) plt.ylabel(\"Ψ*Ψ\", fontsize=13) plt.xticks(np.arange(0, 1, step=0.5)) plt.title(\"n=\"+str(n), fontsize=16) plt.grid()plt.tight_layout(rect=[0, 0.03, 1, 0.95])" }, { "code": null, "e": 3597, "s": 3280, "text": "Notice how there are regions where both Ψ and Ψ* Ψ are zero on the same regions. This is known as the node. Energy levels of orbitals are not continuous. They exist at discreet levels, as represented by the location of the nodes. Also, as the n value increases, the density of the wave inside the box also increases." }, { "code": null, "e": 3702, "s": 3597, "text": "Now to get the wave equation with respect to quantum numbers, it needs to be in the following 3D format:" }, { "code": null, "e": 3972, "s": 3702, "text": "Now, separating of variables depends on the type of atom and is too complex to cover in this blog post. Instead, we will just write the solution directly for plotting. For the following, we will be using the functions of R and Y for Hydrogen atom without deriving them." }, { "code": null, "e": 4009, "s": 3972, "text": "First, let’s look at the 1s orbital:" }, { "code": null, "e": 4177, "s": 4009, "text": "The 1s wave function reveals that the probability of an electron appearing decreases exponentially as we move away from the nucleus. It also reveals a spherical shape." }, { "code": null, "e": 5327, "s": 4177, "text": "import matplotlib.pyplot as pltimport numpy as np#Probability of 1sdef prob_1s(x,y,z): r=np.sqrt(np.square(x)+np.square(y)+np.square(z)) #Remember.. probability is psi squared! return np.square(np.exp(-r)/np.sqrt(np.pi))#Random coordinatesx=np.linspace(0,1,30)y=np.linspace(0,1,30)z=np.linspace(0,1,30)elements = []probability = []for ix in x: for iy in y: for iz in z: #Serialize into 1D object elements.append(str((ix,iy,iz))) probability.append(prob_1s(ix,iy,iz)) #Ensure sum of probability is 1probability = probability/sum(probability)#Getting electron coordinates based on probabiliycoord = np.random.choice(elements, size=100000, replace=True, p=probability)elem_mat = [i.split(',') for i in coord]elem_mat = np.matrix(elem_mat)x_coords = [float(i.item()[1:]) for i in elem_mat[:,0]] y_coords = [float(i.item()) for i in elem_mat[:,1]] z_coords = [float(i.item()[0:-1]) for i in elem_mat[:,2]]#Plottingfig = plt.figure(figsize=(10,10))ax = fig.add_subplot(111, projection='3d')ax.scatter(x_coords, y_coords, z_coords, alpha=0.05, s=2)ax.set_title(\"Hydrogen 1s density\")plt.show()" }, { "code": null, "e": 5592, "s": 5327, "text": "A little hard to see from the electron density plot above. However, you can see that it has a spherical shape. As we move further away from the center, the density decreases. Generally, the cut off point is when the probability of the electron appearing is at 99%." } ]
Variational Autoencoders as Generative Models with Keras | by Kartik Chaudhary | Towards Data Science
This article focuses on giving the readers some basic understanding of the Variational Autoencoders and explaining how they are different from the ordinary autoencoders in Machine Learning and Artificial Intelligence. Unlike vanilla autoencoders(like-sparse autoencoders, de-noising autoencoders .etc), Variational Autoencoders (VAEs) are generative models like GANs (Generative Adversarial Networks). This article is primarily focused on the Variational Autoencoders and I will be writing soon about the Generative Adversarial Networks in my upcoming posts. In this tutorial, we will be discussing how to train a variational autoencoder(VAE) with Keras(TensorFlow, Python) from scratch. We will be concluding our study with the demonstration of the generative capabilities of a simple VAE. The rest of the content in this tutorial can be classified as the following- Background: Variational AutoEncoders (VAEs)Building VAE in KerasTraining VAE on the MNIST datasetResultsImage Generation CapabilitiesSummaryFurther reading and resources Background: Variational AutoEncoders (VAEs) Building VAE in Keras Training VAE on the MNIST dataset Results Image Generation Capabilities Summary Further reading and resources An autoencoder is basically a neural network that takes a high dimensional data point as input, converts it into a lower-dimensional feature vector(ie., latent vector), and later reconstructs the original input sample just utilizing the latent vector representation without losing valuable information. Any given autoencoder is consists of the following two parts-an Encoder and a Decoder. The Encoder part of the model takes an input data sample and compresses it into a latent vector. While the decoder part is responsible for recreating the original input sample from the learned(learned by the encoder during training) latent representation. To learn more about the basics, do check out my article on Autoencoders in Keras and Deep Learning. Let’s continue considering that we all are on the same page until now. One issue with the ordinary autoencoders is that they encode each input sample independently. This means that the samples belonging to the same class (or the samples belonging to the same distribution) might learn very different(distant encodings in the latent space) latent embeddings. Ideally, the latent features of the same class should be somewhat similar (or closer in latent space). This happens because we are not explicitly forcing the neural network to learn the distributions of the input dataset. Due to this issue, our network might not very good at reconstructing related unseen data samples (or less generalizable). In the past tutorial on Autoencoders in Keras and Deep Learning, we trained a vanilla autoencoder and learned the latent features for the MNIST handwritten digit images. When we plotted these embeddings in the latent space with the corresponding labels, we found the learned embeddings of the same classes coming out quite random sometimes and there were no clearly visible boundaries between the embedding clusters of the different classes. The following figure shows the distribution- Variational Autoencoder is slightly different in nature. Instead of directly learning the latent features from the input samples, it actually learns the distribution of latent features. The latent features of the input data are assumed to be following a standard normal distribution. This means that the learned latent vectors are supposed to be zero centric and they can be represented with two statistics-mean and variance (as standard normal distribution can be attributed with only these two statistics). Thus the Variational AutoEncoders(VAEs) calculate the mean and variance of the latent vectors(instead of directly learning latent features) for each sample and forces them to follow a standard normal distribution. Thus the bottleneck part of the network is used to learn mean and variance for each sample, we will define two different fully connected(FC) layers to calculate both. VAEs ensure that the points that are very close to each other in the latent space, are representing very similar data samples(similar classes of data). We are going to prove this fact in this tutorial. Before jumping into the implementation details let’s first get a little understanding of the KL-divergence which is going to be used as one of the two optimization measures in our model. In the last section, we were talking about enforcing a standard normal distribution on the latent features of the input dataset. This can be accomplished using KL-divergence statistics. KL-divergence is a statistical measure of the difference between two probabilistic distributions. Thus, we will utilize KL-divergence value as an objective function(along with the reconstruction loss) in order to ensure that the learned distribution is very similar to the true distribution, which we have already assumed to be a standard normal distribution. In this case, the final objective can be written as- Objective = Reconstruction Loss + KL-Loss Here, the reconstruction loss term would encourage the model to learn the important latent features, needed to correctly reconstruct the original image (if not exactly the same, an image of the same class). While the KL-divergence-loss term would ensure that the learned distribution is similar to the true distribution(a standard normal distribution). This further means that the distribution is centered at zero and is well-spread in the space. We will prove this one also in the latter part of the tutorial. The last section has explained the basic idea behind the Variational Autoencoders(VAEs) in machine learning(ML) and artificial intelligence(AI). In this section, we will build a convolutional variational autoencoder with Keras in Python. This network will be trained on the MNIST handwritten digits dataset that is available in Keras datasets. This section can be broken into the following parts for step-wise understanding and simplicity- Data PreparationBuilding EncoderLatent Distribution and SamplingBuilding DecoderBuilding VAELoss Data Preparation Building Encoder Latent Distribution and Sampling Building Decoder Building VAE Loss In this section, we are going to download and load the MNIST handwritten digits dataset into our Python notebook to get started with the data preparation. Here are the dependencies, loaded in advance- import numpy as npimport matplotlib.pyplot as pltimport pandas as pdimport seaborn as snsimport warningswarnings.filterwarnings('ignore')%matplotlib inline The following python code can be used to download the MNIST handwritten digits dataset. Few sample images are also displayed below- from tensorflow.keras.datasets import mnist(trainX, trainy), (testX, testy) = mnist.load_data()print('Training data shapes: X=%s, y=%s' % (trainX.shape, trainy.shape))print('Testing data shapes: X=%s, y=%s' % (testX.shape, testy.shape))for j in range(5): i = np.random.randint(0, 10000) plt.subplot(550 + 1 + j) plt.imshow(trainX[i], cmap='gray') plt.title(trainy[i])plt.show() Dataset is already divided into the training and test set. The training dataset has 60K handwritten digit images with a resolution of 28*28. While the Test dataset consists of 10K handwritten digit images with similar dimensions- Each image in the dataset is a 2D matrix representing pixel intensities ranging from 0 to 255. We will first normalize the pixel values(To bring them between 0 and 1) and then add an extra dimension for image channels (as supported by Conv2D layers from Keras). Here is the preprocessing code in python- train_data = trainX.astype('float32')/255test_data = testX.astype('float32')/255train_data = np.reshape(train_data, (60000, 28, 28, 1))test_data = np.reshape(test_data, (10000, 28, 28, 1))print (train_data.shape, test_data.shape)Out[1]: (60000, 28, 28, 1) (10000, 28, 28, 1) In this section, we will define the encoder part of our VAE model. The encoder part of the autoencoder usually consists of multiple repeating convolutional layers followed by pooling layers when the input data type is images. The encoder part of a variational autoencoder is also quite similar, it’s just the bottleneck part that is slightly different as discussed above. Here is the python implementation of the encoder part with Keras- import tensorflowinput_data = tensorflow.keras.layers.Input(shape=(28, 28, 1))encoder = tensorflow.keras.layers.Conv2D(64, (5,5), activation='relu')(input_data)encoder = tensorflow.keras.layers.MaxPooling2D((2,2))(encoder)encoder = tensorflow.keras.layers.Conv2D(64, (3,3), activation='relu')(encoder)encoder = tensorflow.keras.layers.MaxPooling2D((2,2))(encoder)encoder = tensorflow.keras.layers.Conv2D(32, (3,3), activation='relu')(encoder)encoder = tensorflow.keras.layers.MaxPooling2D((2,2))(encoder)encoder = tensorflow.keras.layers.Flatten()(encoder)encoder = tensorflow.keras.layers.Dense(16)(encoder) The above snippet compresses the image input and brings down it to a 16 valued feature vector, but these are not the final latent features. The next section will complete the encoder part by adding the latent features computational logic into it. This section is responsible for taking the convoluted features from the last section and calculating the mean and log-variance of the latent features (As we have assumed that the latent features follow a standard normal distribution, and the distribution can be represented with mean and variance statistical values). Two separate fully connected(FC layers) layers are used for calculating the mean and log-variance for the input samples of a given dataset. These attributes(mean and log-variance) of the standard normal distribution(SND) are then used to estimate the latent encodings for the corresponding input data points. The function sample_latent_features defined below takes these two statistical values and returns back a latent encoding vector. This latent encoding is passed to the decoder as input for the image reconstruction purpose. def sample_latent_features(distribution): distribution_mean, distribution_variance = distribution batch_size = tensorflow.shape(distribution_variance)[0] random = tensorflow.keras.backend.random_normal(shape=(batch_size, tensorflow.shape(distribution_variance)[1])) return distribution_mean + tensorflow.exp(0.5 * distribution_variance) * random distribution_mean = tensorflow.keras.layers.Dense(2, name='mean')(encoder)distribution_variance = tensorflow.keras.layers.Dense(2, name='log_variance')(encoder)latent_encoding = tensorflow.keras.layers.Lambda(sample_latent_features)([distribution_mean, distribution_variance]) These latent features(calculated from the learned distribution) actually complete the Encoder part of the model. Now the Encoder model can be defined as follow- encoder_model = tensorflow.keras.Model(input_data, latent_encoding)encoder_model.summary() The encoder is quite simple with just around 57K trainable parameters. The Encoder part of the model takes an image as input and gives the latent encoding vector for it as output which is sampled from the learned distribution of the input dataset. The job of the decoder is to take this embedding vector as input and recreate the original image(or an image belonging to a similar class as the original image). As the latent vector is a quite compressed representation of the features, the decoder part is made up of multiple pairs of the Deconvolutional layers and upsampling layers. A deconvolutional layer basically reverses what a convolutional layer does. The upsampling layers are used to bring the original resolution of the image back. In this way, it reconstructs the image with original dimensions. Here is the python implementation of the decoder part with Keras API from TensorFlow- decoder_input = tensorflow.keras.layers.Input(shape=(2))decoder = tensorflow.keras.layers.Dense(64)(decoder_input)decoder = tensorflow.keras.layers.Reshape((1, 1, 64))(decoder)decoder = tensorflow.keras.layers.Conv2DTranspose(64, (3,3), activation='relu')(decoder) decoder = tensorflow.keras.layers.Conv2DTranspose(64, (3,3), activation='relu')(decoder)decoder = tensorflow.keras.layers.UpSampling2D((2,2))(decoder) decoder = tensorflow.keras.layers.Conv2DTranspose(64, (3,3), activation='relu')(decoder)decoder = tensorflow.keras.layers.UpSampling2D((2,2))(decoder) decoder_output = tensorflow.keras.layers.Conv2DTranspose(1, (5,5), activation='relu')(decoder) The decoder model object can be defined as below- decoder_model = tensorflow.keras.Model(decoder_input, decoder_output)decoder_model.summary() The decoder is again simple with 112K trainable parameters. Finally, the Variational Autoencoder(VAE) can be defined by combining the encoder and the decoder parts. Here is how you can create the VAE model object by sticking decoder after the encoder. encoded = encoder_model(input_data)decoded = decoder_model(encoded)autoencoder = tensorflow.keras.models.Model(input_data, decoded)autoencoder.summary() The overall setup is quite simple with just 170K trainable model parameters. Time to write the objective(or optimization function) function. As discussed earlier, the final objective(or loss) function of a variational autoencoder(VAE) is a combination of the data reconstruction loss and KL-loss. In this section, we will define our custom loss by combining these two statistics. The following implementation of the get_loss function returns a total_loss function that is a combination of reconstruction loss and KL-loss as defined below- Finally, let’s compile the model to make it ready for the training- autoencoder.compile(loss=get_loss(distribution_mean, distribution_variance), optimizer='adam') Just like the ordinary autoencoders, we will train it by giving exactly the same images for input as well as the output. The model is trained for 20 epochs with a batch size of 64. Here is the training summary- autoencoder.fit(train_data, train_data, epochs=20, batch_size=64, validation_data=(test_data, test_data)) I hope it can be trained a little more, but this is where the validation loss was not changing much and I went ahead with it. In this section, we will see the reconstruction capabilities of our model on the test images. The following python script will pick 9 images from the test dataset and we will be plotting the corresponding reconstructed images for them. offset=400print ("Real Test Images")# Real Imagesfor i in range(9): plt.subplot(330 + 1 + i) plt.imshow(test_data[i+offset,:,:, -1], cmap='gray')plt.show()# Reconstructed Imagesprint ("Reconstructed Images with Variational Autoencoder")for i in range(9): plt.subplot(330 + 1 + i) output = autoencoder.predict(np.array([test_data[i+offset]])) op_image = np.reshape(output[0]*255, (28, 28)) plt.imshow(op_image, cmap='gray')plt.show() Here is the output- The above results confirm that the model is able to reconstruct the digit images with decent efficiency. However, one important thing to notice here is that some of the reconstructed images are very different in appearance from the original images while the class(or digit) is always the same. This happens because, the reconstruction is not just dependent upon the input image, it is the distribution that has been learned. And this learned distribution is the reason for the introduced variations in the model output. This is interesting, isn’t it! The second thing to notice here is that the output images are a little blurry. This is a common case with variational autoencoders, they often produce noisy(or poor quality) outputs as the latent vectors(bottleneck) is very small and there is a separate process of learning the latent features as discussed before. Variational Autoencoders(VAEs) are not actually designed to reconstruct the images, the real purpose is learning the distribution (and it gives them the superpower to generate fake data, we will see it later in the post). As we have quoted earlier, the variational autoencoders(VAEs) learn the underlying distribution of the latent features, it basically means that the latent encodings of the samples belonging to the same class should not be very far from each other in the latent space. Secondly, the overall distribution should be standard normal, which is supposed to be centered at zero. Let’s generate the latent embeddings for all of our test images and plot them(the same color represents the digits belonging to the same class, taken from the ground truth labels). Here is the python code- x = []y = []z = []for i in range(10000): z.append(testy[i]) op = encoder_model.predict(np.array([test_data[i]])) x.append(op[0][0]) y.append(op[0][1])df = pd.DataFrame()df['x'] = xdf['y'] = ydf['z'] = ["digit-"+str(k) for k in z]plt.figure(figsize=(8, 6))sns.scatterplot(x='x', y='y', hue='z', data=df)plt.show() The above plot shows that the distribution is centered at zero. Embeddings of the same class digits are closer in the latent space. Digit separation boundaries can also be drawn easily. This is pretty much we wanted to achieve from the variational autoencoder. Let’s jump to the final part where we test the generative capabilities of our model. Variational Autoencoders can be used as generative models. The previous section shows that latent encodings of the input data are following a standard normal distribution and there are clear boundaries visible for different classes of the digits. Just think for a second-If we already know, which part of the space is dedicated to what class, we don’t even need input images to reconstruct the image. This means that we can actually generate digit images having similar characteristics as the training dataset by just passing the random points from the space (latent distribution space). In this fashion, the variational autoencoders can be used as generative models in order to generate fake data. As we can see, the spread of latent encodings is in between [-3 to 3 on the x-axis, and also -3 to 3 on the y-axis]. Let’s generate a bunch of digits with random latent encodings belonging to this range only. generator_model = decoder_modelx_values = np.linspace(-3, 3, 30)y_values = np.linspace(-3, 3, 30)figure = np.zeros((28 * 30, 28 * 30))for ix, x in enumerate(x_values): for iy, y in enumerate(y_values): latent_point = np.array([[x, y]]) generated_image = generator_model.predict(latent_point)[0] figure[ix*28:(ix+1)*28, iy*28:(iy+1)*28,] = generated_image[:,:,-1]plt.figure(figsize=(15, 15))plt.imshow(figure, cmap='gray', extent=[3,-3,3,-3])plt.show() You can find all the digits(from 0 to 9) in the above image matrix as we have tried to generate images from all the portions of the latent space. The capability of generating handwriting with variations isn’t it awesome! This tutorial explains the variational autoencoders in Deep Learning and AI. With a basic introduction, it shows how to implement a VAE with Keras and TensorFlow in python. It further trains the model on MNIST handwritten digit dataset and shows the reconstructed results. We have seen that the latent encodings are following a standard normal distribution (all thanks to KL-divergence) and how the trained decoder part of the model can be utilized as a generative model. We have proved the claims by generating fake digits using only the decoder part of the model. In case you are interested in reading my article on the Denoising Autoencoders Convolutional Denoising Autoencoders for image noise reduction Github code Link: https://github.com/kartikgill/Autoencoders Originally published on Drops of AI. Thanks for reading! Hope this was helpful. Kindly let me know your feedback by commenting below. See you in the next article. Autoencoders in Keras and Deep Learning (Introduction)Optimizers explained for training Neural NetworksOptimizing TensorFlow models with Quantization TechniquesDeep Learning with PyTorch: IntroductionDeep Learning with PyTorch: First Neural Network Autoencoders in Keras and Deep Learning (Introduction) Optimizers explained for training Neural Networks Optimizing TensorFlow models with Quantization Techniques Deep Learning with PyTorch: Introduction Deep Learning with PyTorch: First Neural Network How to Build a Variational Autoencoder in KerasVariational autoencodershttps://keras.io/examples/generative/vae/ How to Build a Variational Autoencoder in Keras Variational autoencoders https://keras.io/examples/generative/vae/ Grammar Variational AutoencoderJunction Tree Variational Autoencoder for Molecular Graph GenerationVariational Autoencoder for Deep Learning of Images, Labels, and CaptionsVariational Autoencoder based Anomaly Detection using Reconstruction ProbabilityA Hybrid Convolutional Variational Autoencoder for Text Generation Grammar Variational Autoencoder Junction Tree Variational Autoencoder for Molecular Graph Generation Variational Autoencoder for Deep Learning of Images, Labels, and Captions Variational Autoencoder based Anomaly Detection using Reconstruction Probability A Hybrid Convolutional Variational Autoencoder for Text Generation
[ { "code": null, "e": 731, "s": 172, "text": "This article focuses on giving the readers some basic understanding of the Variational Autoencoders and explaining how they are different from the ordinary autoencoders in Machine Learning and Artificial Intelligence. Unlike vanilla autoencoders(like-sparse autoencoders, de-noising autoencoders .etc), Variational Autoencoders (VAEs) are generative models like GANs (Generative Adversarial Networks). This article is primarily focused on the Variational Autoencoders and I will be writing soon about the Generative Adversarial Networks in my upcoming posts." }, { "code": null, "e": 963, "s": 731, "text": "In this tutorial, we will be discussing how to train a variational autoencoder(VAE) with Keras(TensorFlow, Python) from scratch. We will be concluding our study with the demonstration of the generative capabilities of a simple VAE." }, { "code": null, "e": 1040, "s": 963, "text": "The rest of the content in this tutorial can be classified as the following-" }, { "code": null, "e": 1210, "s": 1040, "text": "Background: Variational AutoEncoders (VAEs)Building VAE in KerasTraining VAE on the MNIST datasetResultsImage Generation CapabilitiesSummaryFurther reading and resources" }, { "code": null, "e": 1254, "s": 1210, "text": "Background: Variational AutoEncoders (VAEs)" }, { "code": null, "e": 1276, "s": 1254, "text": "Building VAE in Keras" }, { "code": null, "e": 1310, "s": 1276, "text": "Training VAE on the MNIST dataset" }, { "code": null, "e": 1318, "s": 1310, "text": "Results" }, { "code": null, "e": 1348, "s": 1318, "text": "Image Generation Capabilities" }, { "code": null, "e": 1356, "s": 1348, "text": "Summary" }, { "code": null, "e": 1386, "s": 1356, "text": "Further reading and resources" }, { "code": null, "e": 2132, "s": 1386, "text": "An autoencoder is basically a neural network that takes a high dimensional data point as input, converts it into a lower-dimensional feature vector(ie., latent vector), and later reconstructs the original input sample just utilizing the latent vector representation without losing valuable information. Any given autoencoder is consists of the following two parts-an Encoder and a Decoder. The Encoder part of the model takes an input data sample and compresses it into a latent vector. While the decoder part is responsible for recreating the original input sample from the learned(learned by the encoder during training) latent representation. To learn more about the basics, do check out my article on Autoencoders in Keras and Deep Learning." }, { "code": null, "e": 2203, "s": 2132, "text": "Let’s continue considering that we all are on the same page until now." }, { "code": null, "e": 2834, "s": 2203, "text": "One issue with the ordinary autoencoders is that they encode each input sample independently. This means that the samples belonging to the same class (or the samples belonging to the same distribution) might learn very different(distant encodings in the latent space) latent embeddings. Ideally, the latent features of the same class should be somewhat similar (or closer in latent space). This happens because we are not explicitly forcing the neural network to learn the distributions of the input dataset. Due to this issue, our network might not very good at reconstructing related unseen data samples (or less generalizable)." }, { "code": null, "e": 3321, "s": 2834, "text": "In the past tutorial on Autoencoders in Keras and Deep Learning, we trained a vanilla autoencoder and learned the latent features for the MNIST handwritten digit images. When we plotted these embeddings in the latent space with the corresponding labels, we found the learned embeddings of the same classes coming out quite random sometimes and there were no clearly visible boundaries between the embedding clusters of the different classes. The following figure shows the distribution-" }, { "code": null, "e": 3830, "s": 3321, "text": "Variational Autoencoder is slightly different in nature. Instead of directly learning the latent features from the input samples, it actually learns the distribution of latent features. The latent features of the input data are assumed to be following a standard normal distribution. This means that the learned latent vectors are supposed to be zero centric and they can be represented with two statistics-mean and variance (as standard normal distribution can be attributed with only these two statistics)." }, { "code": null, "e": 4413, "s": 3830, "text": "Thus the Variational AutoEncoders(VAEs) calculate the mean and variance of the latent vectors(instead of directly learning latent features) for each sample and forces them to follow a standard normal distribution. Thus the bottleneck part of the network is used to learn mean and variance for each sample, we will define two different fully connected(FC) layers to calculate both. VAEs ensure that the points that are very close to each other in the latent space, are representing very similar data samples(similar classes of data). We are going to prove this fact in this tutorial." }, { "code": null, "e": 4600, "s": 4413, "text": "Before jumping into the implementation details let’s first get a little understanding of the KL-divergence which is going to be used as one of the two optimization measures in our model." }, { "code": null, "e": 5146, "s": 4600, "text": "In the last section, we were talking about enforcing a standard normal distribution on the latent features of the input dataset. This can be accomplished using KL-divergence statistics. KL-divergence is a statistical measure of the difference between two probabilistic distributions. Thus, we will utilize KL-divergence value as an objective function(along with the reconstruction loss) in order to ensure that the learned distribution is very similar to the true distribution, which we have already assumed to be a standard normal distribution." }, { "code": null, "e": 5199, "s": 5146, "text": "In this case, the final objective can be written as-" }, { "code": null, "e": 5241, "s": 5199, "text": "Objective = Reconstruction Loss + KL-Loss" }, { "code": null, "e": 5752, "s": 5241, "text": "Here, the reconstruction loss term would encourage the model to learn the important latent features, needed to correctly reconstruct the original image (if not exactly the same, an image of the same class). While the KL-divergence-loss term would ensure that the learned distribution is similar to the true distribution(a standard normal distribution). This further means that the distribution is centered at zero and is well-spread in the space. We will prove this one also in the latter part of the tutorial." }, { "code": null, "e": 6096, "s": 5752, "text": "The last section has explained the basic idea behind the Variational Autoencoders(VAEs) in machine learning(ML) and artificial intelligence(AI). In this section, we will build a convolutional variational autoencoder with Keras in Python. This network will be trained on the MNIST handwritten digits dataset that is available in Keras datasets." }, { "code": null, "e": 6192, "s": 6096, "text": "This section can be broken into the following parts for step-wise understanding and simplicity-" }, { "code": null, "e": 6289, "s": 6192, "text": "Data PreparationBuilding EncoderLatent Distribution and SamplingBuilding DecoderBuilding VAELoss" }, { "code": null, "e": 6306, "s": 6289, "text": "Data Preparation" }, { "code": null, "e": 6323, "s": 6306, "text": "Building Encoder" }, { "code": null, "e": 6356, "s": 6323, "text": "Latent Distribution and Sampling" }, { "code": null, "e": 6373, "s": 6356, "text": "Building Decoder" }, { "code": null, "e": 6386, "s": 6373, "text": "Building VAE" }, { "code": null, "e": 6391, "s": 6386, "text": "Loss" }, { "code": null, "e": 6546, "s": 6391, "text": "In this section, we are going to download and load the MNIST handwritten digits dataset into our Python notebook to get started with the data preparation." }, { "code": null, "e": 6592, "s": 6546, "text": "Here are the dependencies, loaded in advance-" }, { "code": null, "e": 6748, "s": 6592, "text": "import numpy as npimport matplotlib.pyplot as pltimport pandas as pdimport seaborn as snsimport warningswarnings.filterwarnings('ignore')%matplotlib inline" }, { "code": null, "e": 6880, "s": 6748, "text": "The following python code can be used to download the MNIST handwritten digits dataset. Few sample images are also displayed below-" }, { "code": null, "e": 7270, "s": 6880, "text": "from tensorflow.keras.datasets import mnist(trainX, trainy), (testX, testy) = mnist.load_data()print('Training data shapes: X=%s, y=%s' % (trainX.shape, trainy.shape))print('Testing data shapes: X=%s, y=%s' % (testX.shape, testy.shape))for j in range(5): i = np.random.randint(0, 10000) plt.subplot(550 + 1 + j) plt.imshow(trainX[i], cmap='gray') plt.title(trainy[i])plt.show()" }, { "code": null, "e": 7500, "s": 7270, "text": "Dataset is already divided into the training and test set. The training dataset has 60K handwritten digit images with a resolution of 28*28. While the Test dataset consists of 10K handwritten digit images with similar dimensions-" }, { "code": null, "e": 7804, "s": 7500, "text": "Each image in the dataset is a 2D matrix representing pixel intensities ranging from 0 to 255. We will first normalize the pixel values(To bring them between 0 and 1) and then add an extra dimension for image channels (as supported by Conv2D layers from Keras). Here is the preprocessing code in python-" }, { "code": null, "e": 8079, "s": 7804, "text": "train_data = trainX.astype('float32')/255test_data = testX.astype('float32')/255train_data = np.reshape(train_data, (60000, 28, 28, 1))test_data = np.reshape(test_data, (10000, 28, 28, 1))print (train_data.shape, test_data.shape)Out[1]: (60000, 28, 28, 1) (10000, 28, 28, 1)" }, { "code": null, "e": 8451, "s": 8079, "text": "In this section, we will define the encoder part of our VAE model. The encoder part of the autoencoder usually consists of multiple repeating convolutional layers followed by pooling layers when the input data type is images. The encoder part of a variational autoencoder is also quite similar, it’s just the bottleneck part that is slightly different as discussed above." }, { "code": null, "e": 8517, "s": 8451, "text": "Here is the python implementation of the encoder part with Keras-" }, { "code": null, "e": 9126, "s": 8517, "text": "import tensorflowinput_data = tensorflow.keras.layers.Input(shape=(28, 28, 1))encoder = tensorflow.keras.layers.Conv2D(64, (5,5), activation='relu')(input_data)encoder = tensorflow.keras.layers.MaxPooling2D((2,2))(encoder)encoder = tensorflow.keras.layers.Conv2D(64, (3,3), activation='relu')(encoder)encoder = tensorflow.keras.layers.MaxPooling2D((2,2))(encoder)encoder = tensorflow.keras.layers.Conv2D(32, (3,3), activation='relu')(encoder)encoder = tensorflow.keras.layers.MaxPooling2D((2,2))(encoder)encoder = tensorflow.keras.layers.Flatten()(encoder)encoder = tensorflow.keras.layers.Dense(16)(encoder)" }, { "code": null, "e": 9373, "s": 9126, "text": "The above snippet compresses the image input and brings down it to a 16 valued feature vector, but these are not the final latent features. The next section will complete the encoder part by adding the latent features computational logic into it." }, { "code": null, "e": 9831, "s": 9373, "text": "This section is responsible for taking the convoluted features from the last section and calculating the mean and log-variance of the latent features (As we have assumed that the latent features follow a standard normal distribution, and the distribution can be represented with mean and variance statistical values). Two separate fully connected(FC layers) layers are used for calculating the mean and log-variance for the input samples of a given dataset." }, { "code": null, "e": 10221, "s": 9831, "text": "These attributes(mean and log-variance) of the standard normal distribution(SND) are then used to estimate the latent encodings for the corresponding input data points. The function sample_latent_features defined below takes these two statistical values and returns back a latent encoding vector. This latent encoding is passed to the decoder as input for the image reconstruction purpose." }, { "code": null, "e": 10856, "s": 10221, "text": "def sample_latent_features(distribution): distribution_mean, distribution_variance = distribution batch_size = tensorflow.shape(distribution_variance)[0] random = tensorflow.keras.backend.random_normal(shape=(batch_size, tensorflow.shape(distribution_variance)[1])) return distribution_mean + tensorflow.exp(0.5 * distribution_variance) * random distribution_mean = tensorflow.keras.layers.Dense(2, name='mean')(encoder)distribution_variance = tensorflow.keras.layers.Dense(2, name='log_variance')(encoder)latent_encoding = tensorflow.keras.layers.Lambda(sample_latent_features)([distribution_mean, distribution_variance])" }, { "code": null, "e": 11017, "s": 10856, "text": "These latent features(calculated from the learned distribution) actually complete the Encoder part of the model. Now the Encoder model can be defined as follow-" }, { "code": null, "e": 11108, "s": 11017, "text": "encoder_model = tensorflow.keras.Model(input_data, latent_encoding)encoder_model.summary()" }, { "code": null, "e": 11179, "s": 11108, "text": "The encoder is quite simple with just around 57K trainable parameters." }, { "code": null, "e": 11916, "s": 11179, "text": "The Encoder part of the model takes an image as input and gives the latent encoding vector for it as output which is sampled from the learned distribution of the input dataset. The job of the decoder is to take this embedding vector as input and recreate the original image(or an image belonging to a similar class as the original image). As the latent vector is a quite compressed representation of the features, the decoder part is made up of multiple pairs of the Deconvolutional layers and upsampling layers. A deconvolutional layer basically reverses what a convolutional layer does. The upsampling layers are used to bring the original resolution of the image back. In this way, it reconstructs the image with original dimensions." }, { "code": null, "e": 12002, "s": 11916, "text": "Here is the python implementation of the decoder part with Keras API from TensorFlow-" }, { "code": null, "e": 12664, "s": 12002, "text": "decoder_input = tensorflow.keras.layers.Input(shape=(2))decoder = tensorflow.keras.layers.Dense(64)(decoder_input)decoder = tensorflow.keras.layers.Reshape((1, 1, 64))(decoder)decoder = tensorflow.keras.layers.Conv2DTranspose(64, (3,3), activation='relu')(decoder) decoder = tensorflow.keras.layers.Conv2DTranspose(64, (3,3), activation='relu')(decoder)decoder = tensorflow.keras.layers.UpSampling2D((2,2))(decoder) decoder = tensorflow.keras.layers.Conv2DTranspose(64, (3,3), activation='relu')(decoder)decoder = tensorflow.keras.layers.UpSampling2D((2,2))(decoder) decoder_output = tensorflow.keras.layers.Conv2DTranspose(1, (5,5), activation='relu')(decoder)" }, { "code": null, "e": 12714, "s": 12664, "text": "The decoder model object can be defined as below-" }, { "code": null, "e": 12807, "s": 12714, "text": "decoder_model = tensorflow.keras.Model(decoder_input, decoder_output)decoder_model.summary()" }, { "code": null, "e": 12867, "s": 12807, "text": "The decoder is again simple with 112K trainable parameters." }, { "code": null, "e": 13059, "s": 12867, "text": "Finally, the Variational Autoencoder(VAE) can be defined by combining the encoder and the decoder parts. Here is how you can create the VAE model object by sticking decoder after the encoder." }, { "code": null, "e": 13212, "s": 13059, "text": "encoded = encoder_model(input_data)decoded = decoder_model(encoded)autoencoder = tensorflow.keras.models.Model(input_data, decoded)autoencoder.summary()" }, { "code": null, "e": 13353, "s": 13212, "text": "The overall setup is quite simple with just 170K trainable model parameters. Time to write the objective(or optimization function) function." }, { "code": null, "e": 13592, "s": 13353, "text": "As discussed earlier, the final objective(or loss) function of a variational autoencoder(VAE) is a combination of the data reconstruction loss and KL-loss. In this section, we will define our custom loss by combining these two statistics." }, { "code": null, "e": 13751, "s": 13592, "text": "The following implementation of the get_loss function returns a total_loss function that is a combination of reconstruction loss and KL-loss as defined below-" }, { "code": null, "e": 13819, "s": 13751, "text": "Finally, let’s compile the model to make it ready for the training-" }, { "code": null, "e": 13914, "s": 13819, "text": "autoencoder.compile(loss=get_loss(distribution_mean, distribution_variance), optimizer='adam')" }, { "code": null, "e": 14095, "s": 13914, "text": "Just like the ordinary autoencoders, we will train it by giving exactly the same images for input as well as the output. The model is trained for 20 epochs with a batch size of 64." }, { "code": null, "e": 14125, "s": 14095, "text": "Here is the training summary-" }, { "code": null, "e": 14231, "s": 14125, "text": "autoencoder.fit(train_data, train_data, epochs=20, batch_size=64, validation_data=(test_data, test_data))" }, { "code": null, "e": 14357, "s": 14231, "text": "I hope it can be trained a little more, but this is where the validation loss was not changing much and I went ahead with it." }, { "code": null, "e": 14593, "s": 14357, "text": "In this section, we will see the reconstruction capabilities of our model on the test images. The following python script will pick 9 images from the test dataset and we will be plotting the corresponding reconstructed images for them." }, { "code": null, "e": 15044, "s": 14593, "text": "offset=400print (\"Real Test Images\")# Real Imagesfor i in range(9): plt.subplot(330 + 1 + i) plt.imshow(test_data[i+offset,:,:, -1], cmap='gray')plt.show()# Reconstructed Imagesprint (\"Reconstructed Images with Variational Autoencoder\")for i in range(9): plt.subplot(330 + 1 + i) output = autoencoder.predict(np.array([test_data[i+offset]])) op_image = np.reshape(output[0]*255, (28, 28)) plt.imshow(op_image, cmap='gray')plt.show()" }, { "code": null, "e": 15064, "s": 15044, "text": "Here is the output-" }, { "code": null, "e": 15615, "s": 15064, "text": "The above results confirm that the model is able to reconstruct the digit images with decent efficiency. However, one important thing to notice here is that some of the reconstructed images are very different in appearance from the original images while the class(or digit) is always the same. This happens because, the reconstruction is not just dependent upon the input image, it is the distribution that has been learned. And this learned distribution is the reason for the introduced variations in the model output. This is interesting, isn’t it!" }, { "code": null, "e": 16152, "s": 15615, "text": "The second thing to notice here is that the output images are a little blurry. This is a common case with variational autoencoders, they often produce noisy(or poor quality) outputs as the latent vectors(bottleneck) is very small and there is a separate process of learning the latent features as discussed before. Variational Autoencoders(VAEs) are not actually designed to reconstruct the images, the real purpose is learning the distribution (and it gives them the superpower to generate fake data, we will see it later in the post)." }, { "code": null, "e": 16524, "s": 16152, "text": "As we have quoted earlier, the variational autoencoders(VAEs) learn the underlying distribution of the latent features, it basically means that the latent encodings of the samples belonging to the same class should not be very far from each other in the latent space. Secondly, the overall distribution should be standard normal, which is supposed to be centered at zero." }, { "code": null, "e": 16730, "s": 16524, "text": "Let’s generate the latent embeddings for all of our test images and plot them(the same color represents the digits belonging to the same class, taken from the ground truth labels). Here is the python code-" }, { "code": null, "e": 17055, "s": 16730, "text": "x = []y = []z = []for i in range(10000): z.append(testy[i]) op = encoder_model.predict(np.array([test_data[i]])) x.append(op[0][0]) y.append(op[0][1])df = pd.DataFrame()df['x'] = xdf['y'] = ydf['z'] = [\"digit-\"+str(k) for k in z]plt.figure(figsize=(8, 6))sns.scatterplot(x='x', y='y', hue='z', data=df)plt.show()" }, { "code": null, "e": 17401, "s": 17055, "text": "The above plot shows that the distribution is centered at zero. Embeddings of the same class digits are closer in the latent space. Digit separation boundaries can also be drawn easily. This is pretty much we wanted to achieve from the variational autoencoder. Let’s jump to the final part where we test the generative capabilities of our model." }, { "code": null, "e": 17648, "s": 17401, "text": "Variational Autoencoders can be used as generative models. The previous section shows that latent encodings of the input data are following a standard normal distribution and there are clear boundaries visible for different classes of the digits." }, { "code": null, "e": 18100, "s": 17648, "text": "Just think for a second-If we already know, which part of the space is dedicated to what class, we don’t even need input images to reconstruct the image. This means that we can actually generate digit images having similar characteristics as the training dataset by just passing the random points from the space (latent distribution space). In this fashion, the variational autoencoders can be used as generative models in order to generate fake data." }, { "code": null, "e": 18309, "s": 18100, "text": "As we can see, the spread of latent encodings is in between [-3 to 3 on the x-axis, and also -3 to 3 on the y-axis]. Let’s generate a bunch of digits with random latent encodings belonging to this range only." }, { "code": null, "e": 18785, "s": 18309, "text": "generator_model = decoder_modelx_values = np.linspace(-3, 3, 30)y_values = np.linspace(-3, 3, 30)figure = np.zeros((28 * 30, 28 * 30))for ix, x in enumerate(x_values): for iy, y in enumerate(y_values): latent_point = np.array([[x, y]]) generated_image = generator_model.predict(latent_point)[0] figure[ix*28:(ix+1)*28, iy*28:(iy+1)*28,] = generated_image[:,:,-1]plt.figure(figsize=(15, 15))plt.imshow(figure, cmap='gray', extent=[3,-3,3,-3])plt.show()" }, { "code": null, "e": 19006, "s": 18785, "text": "You can find all the digits(from 0 to 9) in the above image matrix as we have tried to generate images from all the portions of the latent space. The capability of generating handwriting with variations isn’t it awesome!" }, { "code": null, "e": 19279, "s": 19006, "text": "This tutorial explains the variational autoencoders in Deep Learning and AI. With a basic introduction, it shows how to implement a VAE with Keras and TensorFlow in python. It further trains the model on MNIST handwritten digit dataset and shows the reconstructed results." }, { "code": null, "e": 19572, "s": 19279, "text": "We have seen that the latent encodings are following a standard normal distribution (all thanks to KL-divergence) and how the trained decoder part of the model can be utilized as a generative model. We have proved the claims by generating fake digits using only the decoder part of the model." }, { "code": null, "e": 19651, "s": 19572, "text": "In case you are interested in reading my article on the Denoising Autoencoders" }, { "code": null, "e": 19714, "s": 19651, "text": "Convolutional Denoising Autoencoders for image noise reduction" }, { "code": null, "e": 19775, "s": 19714, "text": "Github code Link: https://github.com/kartikgill/Autoencoders" }, { "code": null, "e": 19812, "s": 19775, "text": "Originally published on Drops of AI." }, { "code": null, "e": 19938, "s": 19812, "text": "Thanks for reading! Hope this was helpful. Kindly let me know your feedback by commenting below. See you in the next article." }, { "code": null, "e": 20187, "s": 19938, "text": "Autoencoders in Keras and Deep Learning (Introduction)Optimizers explained for training Neural NetworksOptimizing TensorFlow models with Quantization TechniquesDeep Learning with PyTorch: IntroductionDeep Learning with PyTorch: First Neural Network" }, { "code": null, "e": 20242, "s": 20187, "text": "Autoencoders in Keras and Deep Learning (Introduction)" }, { "code": null, "e": 20292, "s": 20242, "text": "Optimizers explained for training Neural Networks" }, { "code": null, "e": 20350, "s": 20292, "text": "Optimizing TensorFlow models with Quantization Techniques" }, { "code": null, "e": 20391, "s": 20350, "text": "Deep Learning with PyTorch: Introduction" }, { "code": null, "e": 20440, "s": 20391, "text": "Deep Learning with PyTorch: First Neural Network" }, { "code": null, "e": 20553, "s": 20440, "text": "How to Build a Variational Autoencoder in KerasVariational autoencodershttps://keras.io/examples/generative/vae/" }, { "code": null, "e": 20601, "s": 20553, "text": "How to Build a Variational Autoencoder in Keras" }, { "code": null, "e": 20626, "s": 20601, "text": "Variational autoencoders" }, { "code": null, "e": 20668, "s": 20626, "text": "https://keras.io/examples/generative/vae/" }, { "code": null, "e": 20987, "s": 20668, "text": "Grammar Variational AutoencoderJunction Tree Variational Autoencoder for Molecular Graph GenerationVariational Autoencoder for Deep Learning of Images, Labels, and CaptionsVariational Autoencoder based Anomaly Detection using Reconstruction ProbabilityA Hybrid Convolutional Variational Autoencoder for Text Generation" }, { "code": null, "e": 21019, "s": 20987, "text": "Grammar Variational Autoencoder" }, { "code": null, "e": 21088, "s": 21019, "text": "Junction Tree Variational Autoencoder for Molecular Graph Generation" }, { "code": null, "e": 21162, "s": 21088, "text": "Variational Autoencoder for Deep Learning of Images, Labels, and Captions" }, { "code": null, "e": 21243, "s": 21162, "text": "Variational Autoencoder based Anomaly Detection using Reconstruction Probability" } ]
Removing an element from C++ std::vector<> by index?
Remove an element from C++ std::vector<> by index can be done by following way − Live Demo #include<iostream> #include<vector> using namespace std; int main() { vector<int> v; //declare vector //insert elements into vector v.push_back(-10); v.push_back(7); v.push_back(6); // Deletes the first element (v[0]) v.erase(v.begin() ); for (int i = 0; i < v.size(); i++) cout << v[i] << " "; } 7 6
[ { "code": null, "e": 1143, "s": 1062, "text": "Remove an element from C++ std::vector<> by index can be done by following way −" }, { "code": null, "e": 1154, "s": 1143, "text": " Live Demo" }, { "code": null, "e": 1481, "s": 1154, "text": "#include<iostream>\n#include<vector>\nusing namespace std;\nint main() {\n vector<int> v; //declare vector\n //insert elements into vector\n v.push_back(-10);\n v.push_back(7);\n v.push_back(6);\n // Deletes the first element (v[0])\n v.erase(v.begin() );\n for (int i = 0; i < v.size(); i++)\n cout << v[i] << \" \";\n}" }, { "code": null, "e": 1485, "s": 1481, "text": "7 6" } ]
How can I iterate through two lists in parallel in Python?
Assuming that two lists may be of unequal length, parallel traversal over common indices can be done using for loop over over range of minimum length >>> L1 ['a', 'b', 'c', 'd'] >>> L2 [4, 5, 6] >>> l=len(L1) if len(L1)<=len(L2)else len(L2) >>> l 3 >>> for i in range(l): print (L1[i], L2[i]) a 4 b 5 c 6 A more pythonic way is to use zip() function which results in an iterator that aggregates elements from each iterables >>> for i,j in zip(L1,L2): print (i,j) a 4 b 5 c 6
[ { "code": null, "e": 1212, "s": 1062, "text": "Assuming that two lists may be of unequal length, parallel traversal over common indices can be done using for loop over over range of minimum length" }, { "code": null, "e": 1372, "s": 1212, "text": ">>> L1\n['a', 'b', 'c', 'd']\n>>> L2\n[4, 5, 6]\n>>> l=len(L1) if len(L1)<=len(L2)else len(L2)\n>>> l\n3\n>>> for i in range(l):\n print (L1[i], L2[i])\n\na 4\nb 5\nc 6" }, { "code": null, "e": 1491, "s": 1372, "text": "A more pythonic way is to use zip() function which results in an iterator that aggregates elements from each iterables" }, { "code": null, "e": 1547, "s": 1491, "text": ">>> for i,j in zip(L1,L2):\n print (i,j)\n\na 4\nb 5\nc 6" } ]
Get ceiling value of a number using Math.ceil in Java
In order to get the ceiling value of a number in Java, we use the java.lang.Math.ceil() method. The Math.ceil() method returns the smallest (closest to negative infinity) double value which is greater than or equal to the parameter and has a value which is equal to a mathematical integer on the number line. If the parameter is NaN or an infinity or positive zero or negative zero, then the result is the same as the argument. If the argument value is less than zero but greater than -1.0, then the value returned is negative zero. Declaration − The java.lang.Math.ceil() method is declared as follows − public static double ceil(double a) Let us see a program to get the ceiling value of a number in Java. Live Demo import java.lang.Math; public class Example { public static void main(String[] args) { // declaring and initialising some double values double a = -100.01d; double b = 34.6; double c = 600; // printing their ceiling values System.out.println("Ceiling value of " + a + " = " + Math.ceil(a)); System.out.println("Ceiling value of " + b + " = " + Math.ceil(b)); System.out.println("Ceiling value of " + c + " = " + Math.ceil(c)); } } Ceiling value of -100.01 = -100.0 Ceiling value of 34.6 = 35.0 Ceiling value of 600.0 = 600.0
[ { "code": null, "e": 1595, "s": 1062, "text": "In order to get the ceiling value of a number in Java, we use the java.lang.Math.ceil() method. The Math.ceil() method returns the smallest (closest to negative infinity) double value which is greater than or equal to the parameter and has a value which is equal to a mathematical integer on the number line. If the parameter is NaN or an infinity or positive zero or negative zero, then the result is the same as the argument. If the argument value is less than zero but greater than -1.0, then the value returned is negative zero." }, { "code": null, "e": 1667, "s": 1595, "text": "Declaration − The java.lang.Math.ceil() method is declared as follows −" }, { "code": null, "e": 1703, "s": 1667, "text": "public static double ceil(double a)" }, { "code": null, "e": 1770, "s": 1703, "text": "Let us see a program to get the ceiling value of a number in Java." }, { "code": null, "e": 1780, "s": 1770, "text": "Live Demo" }, { "code": null, "e": 2265, "s": 1780, "text": "import java.lang.Math;\npublic class Example {\n public static void main(String[] args) {\n // declaring and initialising some double values\n double a = -100.01d;\n double b = 34.6;\n double c = 600;\n // printing their ceiling values\n System.out.println(\"Ceiling value of \" + a + \" = \" + Math.ceil(a));\n System.out.println(\"Ceiling value of \" + b + \" = \" + Math.ceil(b));\n System.out.println(\"Ceiling value of \" + c + \" = \" + Math.ceil(c));\n }\n}" }, { "code": null, "e": 2359, "s": 2265, "text": "Ceiling value of -100.01 = -100.0\nCeiling value of 34.6 = 35.0\nCeiling value of 600.0 = 600.0" } ]
Difference Between COMMIT and ROLLBACK in SQL
In this post, we will understand the difference between COMMIT and ROLLBACK in SQL. It validates the modifications that are made by the current transaction. It validates the modifications that are made by the current transaction. Once the COMMIT statement has been executed, the transaction can’t be rolled back using ROLLBACK. Once the COMMIT statement has been executed, the transaction can’t be rolled back using ROLLBACK. It occurs when the transaction is successfully executed. It occurs when the transaction is successfully executed. Syntax COMMIT; It removes the modifications that were made by the current transaction. It removes the modifications that were made by the current transaction. Once ROLLBACK is executed, the database would reach its previous state. Once ROLLBACK is executed, the database would reach its previous state. This is the state where the first statement of the transaction would be in execution. This is the state where the first statement of the transaction would be in execution. ROLLBACK happens when the transaction is aborted in between its execution. ROLLBACK happens when the transaction is aborted in between its execution. Syntax ROLLBACK;
[ { "code": null, "e": 1146, "s": 1062, "text": "In this post, we will understand the difference between COMMIT and ROLLBACK in SQL." }, { "code": null, "e": 1219, "s": 1146, "text": "It validates the modifications that are made by the current transaction." }, { "code": null, "e": 1292, "s": 1219, "text": "It validates the modifications that are made by the current transaction." }, { "code": null, "e": 1390, "s": 1292, "text": "Once the COMMIT statement has been executed, the transaction can’t be rolled back using\nROLLBACK." }, { "code": null, "e": 1488, "s": 1390, "text": "Once the COMMIT statement has been executed, the transaction can’t be rolled back using\nROLLBACK." }, { "code": null, "e": 1545, "s": 1488, "text": "It occurs when the transaction is successfully executed." }, { "code": null, "e": 1602, "s": 1545, "text": "It occurs when the transaction is successfully executed." }, { "code": null, "e": 1609, "s": 1602, "text": "Syntax" }, { "code": null, "e": 1617, "s": 1609, "text": "COMMIT;" }, { "code": null, "e": 1689, "s": 1617, "text": "It removes the modifications that were made by the current transaction." }, { "code": null, "e": 1761, "s": 1689, "text": "It removes the modifications that were made by the current transaction." }, { "code": null, "e": 1833, "s": 1761, "text": "Once ROLLBACK is executed, the database would reach its previous state." }, { "code": null, "e": 1905, "s": 1833, "text": "Once ROLLBACK is executed, the database would reach its previous state." }, { "code": null, "e": 1991, "s": 1905, "text": "This is the state where the first statement of the transaction would be in execution." }, { "code": null, "e": 2077, "s": 1991, "text": "This is the state where the first statement of the transaction would be in execution." }, { "code": null, "e": 2152, "s": 2077, "text": "ROLLBACK happens when the transaction is aborted in between its execution." }, { "code": null, "e": 2227, "s": 2152, "text": "ROLLBACK happens when the transaction is aborted in between its execution." }, { "code": null, "e": 2234, "s": 2227, "text": "Syntax" }, { "code": null, "e": 2244, "s": 2234, "text": "ROLLBACK;" } ]
C# Program to pass Parameter to a Thread
To work with threads, add the following namespace in your code − using System.Threading; Firstly, you need to create a new thread in C# − Thread thread = new Thread(threadDemo); Above, threadDemo is our thread function. Now pass a parameter to the thread − thread.Start(str); The parameter set above is − String str = "Hello World!"; Let us see the complete code to pass a parameter to a thread in C#. Live Demo using System; using System.Threading; namespace Sample { class Demo { static void Main(string[] args) { String str = "Hello World!"; // new thread Thread thread = new Thread(threadDemo); // passing parameter thread.Start(str); } static void threadDemo(object str) { Console.WriteLine("Value passed to the thread: "+str); } } } Value passed to the thread: Hello World!
[ { "code": null, "e": 1127, "s": 1062, "text": "To work with threads, add the following namespace in your code −" }, { "code": null, "e": 1151, "s": 1127, "text": "using System.Threading;" }, { "code": null, "e": 1200, "s": 1151, "text": "Firstly, you need to create a new thread in C# −" }, { "code": null, "e": 1240, "s": 1200, "text": "Thread thread = new Thread(threadDemo);" }, { "code": null, "e": 1282, "s": 1240, "text": "Above, threadDemo is our thread function." }, { "code": null, "e": 1319, "s": 1282, "text": "Now pass a parameter to the thread −" }, { "code": null, "e": 1338, "s": 1319, "text": "thread.Start(str);" }, { "code": null, "e": 1367, "s": 1338, "text": "The parameter set above is −" }, { "code": null, "e": 1396, "s": 1367, "text": "String str = \"Hello World!\";" }, { "code": null, "e": 1464, "s": 1396, "text": "Let us see the complete code to pass a parameter to a thread in C#." }, { "code": null, "e": 1474, "s": 1464, "text": "Live Demo" }, { "code": null, "e": 1885, "s": 1474, "text": "using System;\nusing System.Threading;\nnamespace Sample {\n class Demo {\n static void Main(string[] args) {\n String str = \"Hello World!\";\n // new thread\n Thread thread = new Thread(threadDemo);\n // passing parameter\n thread.Start(str);\n }\n static void threadDemo(object str) {\n Console.WriteLine(\"Value passed to the thread: \"+str);\n }\n }\n}" }, { "code": null, "e": 1926, "s": 1885, "text": "Value passed to the thread: Hello World!" } ]
What are factory functions in JavaScript ?
24 Jun, 2021 The Factory Function is similar to constructor functions/class functions, but instead of using new to create an object, factory functions simply creates an object and returns it. Factory Functions are a very useful tool in JavaScript. Factory Functions in JavaScript are similar to constructor functions/class functions, but they do not require the use of the ‘this‘ keyword for inner values or the use of the ‘new‘ keyword when instantiating new objects. Factory Functions can contain inner values, methods, etc. just like normal regular functions. Factory Functions differ from regular functions as they always return an object, which will contain any value, method, etc. Why it is useful? If we have complex logic, and we have to create multiple objects again and again that have the same logic, we can write the logic once in a function and use that function as a factory to create our objects. It’s exactly the same as a real-world factory producing products. Example 1: We have a factory function that will produce new robots with a single logic. Using this we can produce as many objects/robots as we want. Javascript <script> // Function creating new objects // without use of 'new' keyword function createRobot(name) { return { name: name, talk: function () { console.log('My name is ' + name + ', the robot.'); } }; } //Create a robot with name Chitti const robo1 = createRobot('Chitti'); robo1.talk(); // Create a robot with name Chitti 2.O Upgraded const robo2 = createRobot('Chitti 2.O Upgraded'); robo2.talk();</script> Output: My name is Chitti, the robot. My name is Chitti 2.0 Upgraded, the robot. Example 2: Javascript <script> // Factory Function creating person var Person = function (name, age) { // creating person object var person = {}; // parameters as keys to this object person.name = name; person.age = age; // function to greet person.greeting = function () { return ( 'Hello I am ' + person.name + '. I am ' + person.age + ' years old. ' ); }; return person; }; var person1 = Person('Abhishek', 20); console.log(person1.greeting()); var person2 = Person('Raj', 25); console.log(person2.greeting());</script> Output: Hello I am Abhishek. I am 20 years old. Hello I am Raj. I am 25 years old. JavaScript-Questions Picked 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 Remove elements from a JavaScript Array Difference Between PUT and PATCH Request Roadmap to Learn JavaScript For Beginners JavaScript | Promises 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": 52, "s": 24, "text": "\n24 Jun, 2021" }, { "code": null, "e": 231, "s": 52, "text": "The Factory Function is similar to constructor functions/class functions, but instead of using new to create an object, factory functions simply creates an object and returns it." }, { "code": null, "e": 726, "s": 231, "text": "Factory Functions are a very useful tool in JavaScript. Factory Functions in JavaScript are similar to constructor functions/class functions, but they do not require the use of the ‘this‘ keyword for inner values or the use of the ‘new‘ keyword when instantiating new objects. Factory Functions can contain inner values, methods, etc. just like normal regular functions. Factory Functions differ from regular functions as they always return an object, which will contain any value, method, etc." }, { "code": null, "e": 744, "s": 726, "text": "Why it is useful?" }, { "code": null, "e": 1017, "s": 744, "text": "If we have complex logic, and we have to create multiple objects again and again that have the same logic, we can write the logic once in a function and use that function as a factory to create our objects. It’s exactly the same as a real-world factory producing products." }, { "code": null, "e": 1168, "s": 1019, "text": "Example 1: We have a factory function that will produce new robots with a single logic. Using this we can produce as many objects/robots as we want." }, { "code": null, "e": 1179, "s": 1168, "text": "Javascript" }, { "code": "<script> // Function creating new objects // without use of 'new' keyword function createRobot(name) { return { name: name, talk: function () { console.log('My name is ' + name + ', the robot.'); } }; } //Create a robot with name Chitti const robo1 = createRobot('Chitti'); robo1.talk(); // Create a robot with name Chitti 2.O Upgraded const robo2 = createRobot('Chitti 2.O Upgraded'); robo2.talk();</script>", "e": 1709, "s": 1179, "text": null }, { "code": null, "e": 1717, "s": 1709, "text": "Output:" }, { "code": null, "e": 1790, "s": 1717, "text": "My name is Chitti, the robot.\nMy name is Chitti 2.0 Upgraded, the robot." }, { "code": null, "e": 1801, "s": 1790, "text": "Example 2:" }, { "code": null, "e": 1812, "s": 1801, "text": "Javascript" }, { "code": "<script> // Factory Function creating person var Person = function (name, age) { // creating person object var person = {}; // parameters as keys to this object person.name = name; person.age = age; // function to greet person.greeting = function () { return ( 'Hello I am ' + person.name + '. I am ' + person.age + ' years old. ' ); }; return person; }; var person1 = Person('Abhishek', 20); console.log(person1.greeting()); var person2 = Person('Raj', 25); console.log(person2.greeting());</script>", "e": 2488, "s": 1812, "text": null }, { "code": null, "e": 2496, "s": 2488, "text": "Output:" }, { "code": null, "e": 2573, "s": 2496, "text": "Hello I am Abhishek. I am 20 years old. \nHello I am Raj. I am 25 years old. " }, { "code": null, "e": 2594, "s": 2573, "text": "JavaScript-Questions" }, { "code": null, "e": 2601, "s": 2594, "text": "Picked" }, { "code": null, "e": 2612, "s": 2601, "text": "JavaScript" }, { "code": null, "e": 2629, "s": 2612, "text": "Web Technologies" }, { "code": null, "e": 2727, "s": 2629, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2788, "s": 2727, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2828, "s": 2788, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 2869, "s": 2828, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 2911, "s": 2869, "text": "Roadmap to Learn JavaScript For Beginners" }, { "code": null, "e": 2933, "s": 2911, "text": "JavaScript | Promises" }, { "code": null, "e": 2966, "s": 2933, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 3028, "s": 2966, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 3089, "s": 3028, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 3139, "s": 3089, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Longest Zig-Zag Subsequence
10 Jun, 2021 The longest Zig-Zag subsequence problem is to find length of the longest subsequence of given sequence such that all elements of this are alternating. If a sequence {x1, x2, .. xn} is alternating sequence then its element satisfy one of the following relation : x1 < x2 > x3 < x4 > x5 < .... xn or x1 > x2 < x3 > x4 < x5 > .... xn Examples : Input: arr[] = {1, 5, 4} Output: 3 The whole arrays is of the form x1 < x2 > x3 Input: arr[] = {1, 4, 5} Output: 2 All subsequences of length 2 are either of the form x1 < x2; or x1 > x2 Input: arr[] = {10, 22, 9, 33, 49, 50, 31, 60} Output: 6 The subsequences {10, 22, 9, 33, 31, 60} or {10, 22, 9, 49, 31, 60} or {10, 22, 9, 50, 31, 60} are longest Zig-Zag of length 6. This problem is an extension of longest increasing subsequence problem, but requires more thinking for finding optimal substructure property in this.We will solve this problem by dynamic Programming method, Let A is given array of length n of integers. We define a 2D array Z[n][2] such that Z[i][0] contains longest Zig-Zag subsequence ending at index i and last element is greater than its previous element and Z[i][1] contains longest Zig-Zag subsequence ending at index i and last element is smaller than its previous element, then we have following recurrence relation between them, Z[i][0] = Length of the longest Zig-Zag subsequence ending at index i and last element is greater than its previous element Z[i][1] = Length of the longest Zig-Zag subsequence ending at index i and last element is smaller than its previous element Recursive Formulation: Z[i][0] = max (Z[i][0], Z[j][1] + 1); for all j < i and A[j] < A[i] Z[i][1] = max (Z[i][1], Z[j][0] + 1); for all j < i and A[j] > A[i] The first recurrence relation is based on the fact that, If we are at position i and this element has to bigger than its previous element then for this sequence (upto i) to be bigger we will try to choose an element j ( < i) such that A[j] < A[i] i.e. A[j] can become A[i]’s previous element and Z[j][1] + 1 is bigger than Z[i][0] then we will update Z[i][0]. Remember we have chosen Z[j][1] + 1 not Z[j][0] + 1 to satisfy alternate property because in Z[j][0] last element is bigger than its previous one and A[i] is greater than A[j] which will break the alternating property if we update. So above fact derives first recurrence relation, similar argument can be made for second recurrence relation also. C++ C Java Python3 C# PHP Javascript // C++ program to find longest Zig-Zag subsequence in// an array#include <bits/stdc++.h>using namespace std; // function to return max of two numbersint max(int a, int b) { return (a > b) ? a : b; } // Function to return longest Zig-Zag subsequence lengthint zzis(int arr[], int n){ /*Z[i][0] = Length of the longest Zig-Zag subsequence ending at index i and last element is greater than its previous element Z[i][1] = Length of the longest Zig-Zag subsequence ending at index i and last element is smaller than its previous element */ int Z[n][2]; /* Initialize all values from 1 */ for (int i = 0; i < n; i++) Z[i][0] = Z[i][1] = 1; int res = 1; // Initialize result /* Compute values in bottom up manner */ for (int i = 1; i < n; i++) { // Consider all elements as previous of arr[i] for (int j = 0; j < i; j++) { // If arr[i] is greater, then check with Z[j][1] if (arr[j] < arr[i] && Z[i][0] < Z[j][1] + 1) Z[i][0] = Z[j][1] + 1; // If arr[i] is smaller, then check with Z[j][0] if( arr[j] > arr[i] && Z[i][1] < Z[j][0] + 1) Z[i][1] = Z[j][0] + 1; } /* Pick maximum of both values at index i */ if (res < max(Z[i][0], Z[i][1])) res = max(Z[i][0], Z[i][1]); } return res;} /* Driver program */int main(){ int arr[] = { 10, 22, 9, 33, 49, 50, 31, 60 }; int n = sizeof(arr)/sizeof(arr[0]); cout<<"Length of Longest Zig-Zag subsequence is "<<zzis(arr, n)<<endl; return 0;} // This code is contributed by noob2000. // C program to find longest Zig-Zag subsequence in// an array#include <stdio.h>#include <stdlib.h> // function to return max of two numbersint max(int a, int b) { return (a > b) ? a : b; } // Function to return longest Zig-Zag subsequence lengthint zzis(int arr[], int n){ /*Z[i][0] = Length of the longest Zig-Zag subsequence ending at index i and last element is greater than its previous element Z[i][1] = Length of the longest Zig-Zag subsequence ending at index i and last element is smaller than its previous element */ int Z[n][2]; /* Initialize all values from 1 */ for (int i = 0; i < n; i++) Z[i][0] = Z[i][1] = 1; int res = 1; // Initialize result /* Compute values in bottom up manner */ for (int i = 1; i < n; i++) { // Consider all elements as previous of arr[i] for (int j = 0; j < i; j++) { // If arr[i] is greater, then check with Z[j][1] if (arr[j] < arr[i] && Z[i][0] < Z[j][1] + 1) Z[i][0] = Z[j][1] + 1; // If arr[i] is smaller, then check with Z[j][0] if( arr[j] > arr[i] && Z[i][1] < Z[j][0] + 1) Z[i][1] = Z[j][0] + 1; } /* Pick maximum of both values at index i */ if (res < max(Z[i][0], Z[i][1])) res = max(Z[i][0], Z[i][1]); } return res;} /* Driver program */int main(){ int arr[] = { 10, 22, 9, 33, 49, 50, 31, 60 }; int n = sizeof(arr)/sizeof(arr[0]); printf("Length of Longest Zig-Zag subsequence is %d\n", zzis(arr, n) ); return 0;} // Java program to find longest// Zig-Zag subsequence in an arrayimport java.io.*; class GFG { // Function to return longest// Zig-Zag subsequence lengthstatic int zzis(int arr[], int n){ /*Z[i][0] = Length of the longest Zig-Zag subsequence ending at index i and last element is greater than its previous element Z[i][1] = Length of the longest Zig-Zag subsequence ending at index i and last element is smaller than its previous element */ int Z[][] = new int[n][2]; /* Initialize all values from 1 */ for (int i = 0; i < n; i++) Z[i][0] = Z[i][1] = 1; int res = 1; // Initialize result /* Compute values in bottom up manner */ for (int i = 1; i < n; i++) { // Consider all elements as // previous of arr[i] for (int j = 0; j < i; j++) { // If arr[i] is greater, then // check with Z[j][1] if (arr[j] < arr[i] && Z[i][0] < Z[j][1] + 1) Z[i][0] = Z[j][1] + 1; // If arr[i] is smaller, then // check with Z[j][0] if( arr[j] > arr[i] && Z[i][1] < Z[j][0] + 1) Z[i][1] = Z[j][0] + 1; } /* Pick maximum of both values at index i */ if (res < Math.max(Z[i][0], Z[i][1])) res = Math.max(Z[i][0], Z[i][1]); } return res;} /* Driver program */public static void main(String[] args){ int arr[] = { 10, 22, 9, 33, 49, 50, 31, 60 }; int n = arr.length; System.out.println("Length of Longest "+ "Zig-Zag subsequence is " + zzis(arr, n));}}// This code is contributed by Prerna Saini # Python3 program to find longest# Zig-Zag subsequence in an array # Function to return max of two numbers # Function to return longest# Zig-Zag subsequence lengthdef zzis(arr, n): '''Z[i][0] = Length of the longest Zig-Zag subsequence ending at index i and last element is greater than its previous element Z[i][1] = Length of the longest Zig-Zag subsequence ending at index i and last element is smaller than its previous element ''' Z = [[1 for i in range(2)] for i in range(n)] res = 1 # Initialize result # Compute values in bottom up manner ''' for i in range(1, n): # Consider all elements as previous of arr[i] for j in range(i): # If arr[i] is greater, then check with Z[j][1] if (arr[j] < arr[i] and Z[i][0] < Z[j][1] + 1): Z[i][0] = Z[j][1] + 1 # If arr[i] is smaller, then check with Z[j][0] if( arr[j] > arr[i] and Z[i][1] < Z[j][0] + 1): Z[i][1] = Z[j][0] + 1 # Pick maximum of both values at index i ''' if (res < max(Z[i][0], Z[i][1])): res = max(Z[i][0], Z[i][1]) return res # Driver Codearr = [10, 22, 9, 33, 49, 50, 31, 60]n = len(arr)print("Length of Longest Zig-Zag subsequence is", zzis(arr, n)) # This code is contributed by Mohit Kumar // C# program to find longest// Zig-Zag subsequence in an arrayusing System; class GFG{ // Function to return longest// Zig-Zag subsequence lengthstatic int zzis(int []arr, int n){ /*Z[i][0] = Length of the longest Zig-Zag subsequence ending at index i and last element is greater than its previous element Z[i][1] = Length of the longest Zig-Zag subsequence ending at index i and last element is smaller than its previous element */ int [,]Z = new int[n, 2]; /* Initialize all values from 1 */ for (int i = 0; i < n; i++) Z[i, 0] = Z[i, 1] = 1; // Initialize result int res = 1; /* Compute values in bottom up manner */ for (int i = 1; i < n; i++) { // Consider all elements as // previous of arr[i] for (int j = 0; j < i; j++) { // If arr[i] is greater, then // check with Z[j][1] if (arr[j] < arr[i] && Z[i, 0] < Z[j, 1] + 1) Z[i, 0] = Z[j, 1] + 1; // If arr[i] is smaller, then // check with Z[j][0] if( arr[j] > arr[i] && Z[i, 1] < Z[j, 0] + 1) Z[i, 1] = Z[j, 0] + 1; } /* Pick maximum of both values at index i */ if (res < Math.Max(Z[i, 0], Z[i, 1])) res = Math.Max(Z[i, 0], Z[i, 1]); } return res;} // Driver Codestatic public void Main (){ int []arr = {10, 22, 9, 33, 49, 50, 31, 60}; int n = arr.Length; Console.WriteLine("Length of Longest "+ "Zig-Zag subsequence is " + zzis(arr, n)); }} // This code is contributed by ajit <?php//PHP program to find longest Zig-Zag//subsequence in an array // function to return max of two numbersfunction maxD($a, $b) { return ($a > $b) ? $a : $b; } // Function to return longest Zig-Zag subsequence lengthfunction zzis($arr, $n){ /*Z[i][0] = Length of the longest Zig-Zag subsequence ending at index i and last element is greater than its previous element Z[i][1] = Length of the longest Zig-Zag subsequence ending at index i and last element is smaller than its previous element */ //$Z[$n][2]; /* Initialize all values from 1 */ for ($i = 0; $i < $n; $i++) $Z[$i][0] = $Z[$i][1] = 1; $res = 1; // Initialize result /* Compute values in bottom up manner */ for ($i = 1; $i < $n; $i++) { // Consider all elements as previous of arr[i] for ($j = 0; $j < $i; $j++) { // If arr[i] is greater, then check with Z[j][1] if ($arr[$j] < $arr[$i] && $Z[$i][0] < $Z[$j][1] + 1) $Z[$i][0] = $Z[$j][1] + 1; // If arr[i] is smaller, then check with Z[j][0] if( $arr[$j] > $arr[$i] && $Z[$i][1] < $Z[$j][0] + 1) $Z[$i][1] = $Z[$j][0] + 1; } /* Pick maximum of both values at index i */ if ($res < max($Z[$i][0], $Z[$i][1])) $res = max($Z[$i][0], $Z[$i][1]); } return $res;} /* Driver program */ $arr = array( 10, 22, 9, 33, 49, 50, 31, 60 ); $n = sizeof($arr); echo "Length of Longest Zig-Zag subsequence is ", zzis($arr, $n) ; echo "\n"; #This code is contributed by aj_36?> <script> // Javascript program to find longest // Zig-Zag subsequence in an array // Function to return longest // Zig-Zag subsequence length function zzis(arr, n) { /*Z[i][0] = Length of the longest Zig-Zag subsequence ending at index i and last element is greater than its previous element Z[i][1] = Length of the longest Zig-Zag subsequence ending at index i and last element is smaller than its previous element */ let Z = new Array(n); for(let i = 0; i < n; i++) { Z[i] = new Array(2); } /* Initialize all values from 1 */ for (let i = 0; i < n; i++) Z[i][0] = Z[i][1] = 1; let res = 1; // Initialize result /* Compute values in bottom up manner */ for (let i = 1; i < n; i++) { // Consider all elements as // previous of arr[i] for (let j = 0; j < i; j++) { // If arr[i] is greater, then // check with Z[j][1] if (arr[j] < arr[i] && Z[i][0] < Z[j][1] + 1) Z[i][0] = Z[j][1] + 1; // If arr[i] is smaller, then // check with Z[j][0] if( arr[j] > arr[i] && Z[i][1] < Z[j][0] + 1) Z[i][1] = Z[j][0] + 1; } /* Pick maximum of both values at index i */ if (res < Math.max(Z[i][0], Z[i][1])) res = Math.max(Z[i][0], Z[i][1]); } return res; } let arr = [ 10, 22, 9, 33, 49, 50, 31, 60 ]; let n = arr.length; document.write("Length of Longest "+ "Zig-Zag subsequence is " + zzis(arr, n)); </script> Output : Length of Longest Zig-Zag subsequence is 6 Time Complexity : O(n2) Auxiliary Space : O(n)A better approach with time complexity O(n) is explained below: Let the sequence be stored in an unsorted integer array arr[N]. We shall proceed by comparing the mathematical signs(negative or positive) of the difference of two consecutive elements of arr. To achieve this, we shall store the sign of (arr[i] – arr[i-1]) in a variable, subsequently comparing it with that of (arr[i+1] – arr[i]). If it is different, we shall increment our result. For checking the sign, we shall use a simple Signum Function, which shall determine the sign of a number passed to it. That is, Considering the fact that we traverse the sequence only once, this becomes an O(n) solution.The algorithm for the approach discussed above is : Input integer array seq[N]. Initialize integer lastSign to 0. FOR i in range 1 to N - 1 integer sign = signum(seq[i] - seq[i-1]) IF sign != lastSign AND IF sign != 0 increment length by 1. lastSign = sign. END IF END FOR return length. Following is the implementation of the above approach: C++ Java Python3 C# Javascript /*CPP program to find the maximum length of zig-zagsub-sequence in given sequence*/#include <bits/stdc++.h>#include <iostream>using namespace std; // Function prototype.int signum(int n); /* Function to calculate maximum length of zig-zagsub-sequence in given sequence.*/int maxZigZag(int seq[], int n){ if (n == 0) { return 0; } int lastSign = 0, length = 1; // Length is initialized to 1 as // that is minimum value // for arbitrary sequence. for (int i = 1; i < n; ++i) { int Sign = signum(seq[i] - seq[i - 1]); // It qualifies if (Sign != lastSign && Sign != 0) { // Updating lastSign lastSign = Sign; length++; } } return length;} /* Signum function :Returns 1 when passed a positive integerReturns -1 when passed a negative integerReturns 0 when passed 0. */int signum(int n){ if (n != 0) { return n > 0 ? 1 : -1; } else { return 0; }}// Driver methodint main(){ int sequence1[4] = { 1, 3, 6, 2 }; int sequence2[5] = { 5, 0, 3, 1, 0 }; int n1 = sizeof(sequence1) / sizeof(*sequence1); // size of sequences int n2 = sizeof(sequence2) / sizeof(*sequence2); int maxLength1 = maxZigZag(sequence1, n1); int maxLength2 = maxZigZag(sequence2, n2); // function call cout << "The maximum length of zig-zag sub-sequence in " "first sequence is: " << maxLength1; cout << endl; cout << "The maximum length of zig-zag sub-sequence in " "second sequence is: " << maxLength2;} // Java code to find out maximum length of zig-zag// sub-sequence in given sequenceclass zigZagMaxLength { // Driver method public static void main(String[] args) { int[] sequence1 = { 1, 3, 6, 2 }; int[] sequence2 = { 5, 0, 3, 1, 0 }; int n1 = sequence1.length; // size of sequences int n2 = sequence2.length; int maxLength1 = maxZigZag(sequence1, n1); int maxLength2 = maxZigZag(sequence2, n2); // function call System.out.println( "The maximum length of zig-zag sub-sequence in first sequence is: " + maxLength1); System.out.println( "The maximum length of zig-zag sub-sequence in second sequence is: " + maxLength2); } /* Function to calculate maximum length of zig-zag sub-sequence in given sequence. */ static int maxZigZag(int[] seq, int n) { if (n == 0) { return 0; } int lastSign = 0, length = 1; // length is initialized to 1 as that is minimum // value for arbitrary sequence. for (int i = 1; i < n; ++i) { int Sign = signum(seq[i] - seq[i - 1]); if (Sign != 0 && Sign != lastSign) // it qualifies { lastSign = Sign; // updating lastSign length++; } } return length; } /* Signum function : Returns 1 when passed a positive integer Returns -1 when passed a negative integer Returns 0 when passed 0. */ static int signum(int n) { if (n != 0) { return n > 0 ? 1 : -1; } else { return 0; } }} # Python3 program to find the maximum# length of zig-zag sub-sequence in# given sequence # Function to calculate maximum length# of zig-zag sub-sequence in given sequence. def maxZigZag(seq, n): if (n == 0): return 0 lastSign = 0 # Length is initialized to 1 as that is # minimum value for arbitrary sequence length = 1 for i in range(1, n): Sign = signum(seq[i] - seq[i - 1]) # It qualifies if (Sign != lastSign and Sign != 0): # Updating lastSign lastSign = Sign length += 1 return length # Signum function :# Returns 1 when passed a positive integer# Returns -1 when passed a negative integer# Returns 0 when passed 0. def signum(n): if (n != 0): return 1 if n > 0 else -1 else: return 0 # Driver codeif __name__ == '__main__': sequence1 = [1, 3, 6, 2] sequence2 = [5, 0, 3, 1, 0] n1 = len(sequence1) n2 = len(sequence2) # Function call maxLength1 = maxZigZag(sequence1, n1) maxLength2 = maxZigZag(sequence2, n2) print("The maximum length of zig-zag sub-sequence " "in first sequence is:", maxLength1) print("The maximum length of zig-zag sub-sequence " "in second sequence is:", maxLength2) # This code is contributed by himanshu77 // C# code to find out maximum length of// zig-zag sub-sequence in given sequenceusing System; class zigZagMaxLength { // Driver method public static void Main(String[] args) { int[] sequence1 = { 1, 3, 6, 2 }; int[] sequence2 = { 5, 0, 3, 1, 0 }; int n1 = sequence1.Length; // size of sequences int n2 = sequence2.Length; int maxLength1 = maxZigZag(sequence1, n1); int maxLength2 = maxZigZag(sequence2, n2); // function call Console.WriteLine( "The maximum length of zig-zag sub-sequence" + " in first sequence is: " + maxLength1); Console.WriteLine( "The maximum length of zig-zag " + "sub-sequence in second sequence is: " + maxLength2); } /* Function to calculate maximum length of zig-zag sub-sequence in given sequence. */ static int maxZigZag(int[] seq, int n) { if (n == 0) { return 0; } // length is initialized to 1 as that is minimum // value for arbitrary sequence. int lastSign = 0, length = 1; for (int i = 1; i < n; ++i) { int Sign = signum(seq[i] - seq[i - 1]); if (Sign != 0 && Sign != lastSign) // it qualifies { lastSign = Sign; // updating lastSign length++; } } return length; } /* Signum function : Returns 1 when passed a positive integer Returns -1 when passed a negative integer Returns 0 when passed 0. */ static int signum(int n) { if (n != 0) { return n > 0 ? 1 : -1; } else { return 0; } }} // This code is contributed by Rajput-Ji <script> // Javascript code to find out maximum length of // zig-zag sub-sequence in given sequence /* Function to calculate maximum length of zig-zag sub-sequence in given sequence. */ function maxZigZag(seq, n) { if (n == 0) { return 0; } // length is initialized to 1 as that is minimum // value for arbitrary sequence. let lastSign = 0, length = 1; for (let i = 1; i < n; ++i) { let Sign = signum(seq[i] - seq[i - 1]); if (Sign != 0 && Sign != lastSign) // it qualifies { lastSign = Sign; // updating lastSign length++; } } return length; } /* Signum function : Returns 1 when passed a positive integer Returns -1 when passed a negative integer Returns 0 when passed 0. */ function signum(n) { if (n != 0) { return n > 0 ? 1 : -1; } else { return 0; } } let sequence1 = [ 1, 3, 6, 2 ]; let sequence2 = [ 5, 0, 3, 1, 0 ]; let n1 = sequence1.length; // size of sequences let n2 = sequence2.length; let maxLength1 = maxZigZag(sequence1, n1); let maxLength2 = maxZigZag(sequence2, n2); // function call document.write("The maximum length of zig-zag sub-sequence" + " in first sequence is: " + maxLength1 + "</br>"); document.write( "The maximum length of zig-zag " + "sub-sequence in second sequence is: " + maxLength2 + "</br>"); </script> Output : The maximum length of zig-zag sub-sequence in first sequence is: 3 The maximum length of zig-zag sub-sequence in second sequence is: 4 Time Complexity : O(n) Auxiliary Space : O(1)This article is contributed by Utkarsh Trivedi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. jit_t santhanambr2002 mohit kumar 29 Rajput-Ji himanshu77 winter_soldier rameshtravel07 divyeshrabadiya07 noob2000 Accolite subsequence Arrays Dynamic Programming Accolite Arrays Dynamic Programming 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 Multidimensional Arrays in Java Stack Data Structure (Introduction and Program) Linear Search Program for Fibonacci numbers 0-1 Knapsack Problem | DP-10 Longest Common Subsequence | DP-4 Longest Palindromic Substring | Set 1 Longest Increasing Subsequence | DP-3
[ { "code": null, "e": 52, "s": 24, "text": "\n10 Jun, 2021" }, { "code": null, "e": 315, "s": 52, "text": "The longest Zig-Zag subsequence problem is to find length of the longest subsequence of given sequence such that all elements of this are alternating. If a sequence {x1, x2, .. xn} is alternating sequence then its element satisfy one of the following relation : " }, { "code": null, "e": 390, "s": 315, "text": " x1 < x2 > x3 < x4 > x5 < .... xn or \n x1 > x2 < x3 > x4 < x5 > .... xn " }, { "code": null, "e": 401, "s": 390, "text": "Examples :" }, { "code": null, "e": 778, "s": 401, "text": "Input: arr[] = {1, 5, 4}\nOutput: 3\nThe whole arrays is of the form x1 < x2 > x3 \n\nInput: arr[] = {1, 4, 5}\nOutput: 2\nAll subsequences of length 2 are either of the form \nx1 < x2; or x1 > x2\n\nInput: arr[] = {10, 22, 9, 33, 49, 50, 31, 60}\nOutput: 6\nThe subsequences {10, 22, 9, 33, 31, 60} or\n{10, 22, 9, 49, 31, 60} or {10, 22, 9, 50, 31, 60}\nare longest Zig-Zag of length 6." }, { "code": null, "e": 1367, "s": 778, "text": "This problem is an extension of longest increasing subsequence problem, but requires more thinking for finding optimal substructure property in this.We will solve this problem by dynamic Programming method, Let A is given array of length n of integers. We define a 2D array Z[n][2] such that Z[i][0] contains longest Zig-Zag subsequence ending at index i and last element is greater than its previous element and Z[i][1] contains longest Zig-Zag subsequence ending at index i and last element is smaller than its previous element, then we have following recurrence relation between them, " }, { "code": null, "e": 1852, "s": 1367, "text": "Z[i][0] = Length of the longest Zig-Zag subsequence \n ending at index i and last element is greater\n than its previous element\nZ[i][1] = Length of the longest Zig-Zag subsequence \n ending at index i and last element is smaller\n than its previous element\n\nRecursive Formulation:\n Z[i][0] = max (Z[i][0], Z[j][1] + 1); \n for all j < i and A[j] < A[i] \n Z[i][1] = max (Z[i][1], Z[j][0] + 1); \n for all j < i and A[j] > A[i]" }, { "code": null, "e": 2560, "s": 1852, "text": "The first recurrence relation is based on the fact that, If we are at position i and this element has to bigger than its previous element then for this sequence (upto i) to be bigger we will try to choose an element j ( < i) such that A[j] < A[i] i.e. A[j] can become A[i]’s previous element and Z[j][1] + 1 is bigger than Z[i][0] then we will update Z[i][0]. Remember we have chosen Z[j][1] + 1 not Z[j][0] + 1 to satisfy alternate property because in Z[j][0] last element is bigger than its previous one and A[i] is greater than A[j] which will break the alternating property if we update. So above fact derives first recurrence relation, similar argument can be made for second recurrence relation also. " }, { "code": null, "e": 2564, "s": 2560, "text": "C++" }, { "code": null, "e": 2566, "s": 2564, "text": "C" }, { "code": null, "e": 2571, "s": 2566, "text": "Java" }, { "code": null, "e": 2579, "s": 2571, "text": "Python3" }, { "code": null, "e": 2582, "s": 2579, "text": "C#" }, { "code": null, "e": 2586, "s": 2582, "text": "PHP" }, { "code": null, "e": 2597, "s": 2586, "text": "Javascript" }, { "code": "// C++ program to find longest Zig-Zag subsequence in// an array#include <bits/stdc++.h>using namespace std; // function to return max of two numbersint max(int a, int b) { return (a > b) ? a : b; } // Function to return longest Zig-Zag subsequence lengthint zzis(int arr[], int n){ /*Z[i][0] = Length of the longest Zig-Zag subsequence ending at index i and last element is greater than its previous element Z[i][1] = Length of the longest Zig-Zag subsequence ending at index i and last element is smaller than its previous element */ int Z[n][2]; /* Initialize all values from 1 */ for (int i = 0; i < n; i++) Z[i][0] = Z[i][1] = 1; int res = 1; // Initialize result /* Compute values in bottom up manner */ for (int i = 1; i < n; i++) { // Consider all elements as previous of arr[i] for (int j = 0; j < i; j++) { // If arr[i] is greater, then check with Z[j][1] if (arr[j] < arr[i] && Z[i][0] < Z[j][1] + 1) Z[i][0] = Z[j][1] + 1; // If arr[i] is smaller, then check with Z[j][0] if( arr[j] > arr[i] && Z[i][1] < Z[j][0] + 1) Z[i][1] = Z[j][0] + 1; } /* Pick maximum of both values at index i */ if (res < max(Z[i][0], Z[i][1])) res = max(Z[i][0], Z[i][1]); } return res;} /* Driver program */int main(){ int arr[] = { 10, 22, 9, 33, 49, 50, 31, 60 }; int n = sizeof(arr)/sizeof(arr[0]); cout<<\"Length of Longest Zig-Zag subsequence is \"<<zzis(arr, n)<<endl; return 0;} // This code is contributed by noob2000.", "e": 4242, "s": 2597, "text": null }, { "code": "// C program to find longest Zig-Zag subsequence in// an array#include <stdio.h>#include <stdlib.h> // function to return max of two numbersint max(int a, int b) { return (a > b) ? a : b; } // Function to return longest Zig-Zag subsequence lengthint zzis(int arr[], int n){ /*Z[i][0] = Length of the longest Zig-Zag subsequence ending at index i and last element is greater than its previous element Z[i][1] = Length of the longest Zig-Zag subsequence ending at index i and last element is smaller than its previous element */ int Z[n][2]; /* Initialize all values from 1 */ for (int i = 0; i < n; i++) Z[i][0] = Z[i][1] = 1; int res = 1; // Initialize result /* Compute values in bottom up manner */ for (int i = 1; i < n; i++) { // Consider all elements as previous of arr[i] for (int j = 0; j < i; j++) { // If arr[i] is greater, then check with Z[j][1] if (arr[j] < arr[i] && Z[i][0] < Z[j][1] + 1) Z[i][0] = Z[j][1] + 1; // If arr[i] is smaller, then check with Z[j][0] if( arr[j] > arr[i] && Z[i][1] < Z[j][0] + 1) Z[i][1] = Z[j][0] + 1; } /* Pick maximum of both values at index i */ if (res < max(Z[i][0], Z[i][1])) res = max(Z[i][0], Z[i][1]); } return res;} /* Driver program */int main(){ int arr[] = { 10, 22, 9, 33, 49, 50, 31, 60 }; int n = sizeof(arr)/sizeof(arr[0]); printf(\"Length of Longest Zig-Zag subsequence is %d\\n\", zzis(arr, n) ); return 0;}", "e": 5846, "s": 4242, "text": null }, { "code": "// Java program to find longest// Zig-Zag subsequence in an arrayimport java.io.*; class GFG { // Function to return longest// Zig-Zag subsequence lengthstatic int zzis(int arr[], int n){ /*Z[i][0] = Length of the longest Zig-Zag subsequence ending at index i and last element is greater than its previous element Z[i][1] = Length of the longest Zig-Zag subsequence ending at index i and last element is smaller than its previous element */ int Z[][] = new int[n][2]; /* Initialize all values from 1 */ for (int i = 0; i < n; i++) Z[i][0] = Z[i][1] = 1; int res = 1; // Initialize result /* Compute values in bottom up manner */ for (int i = 1; i < n; i++) { // Consider all elements as // previous of arr[i] for (int j = 0; j < i; j++) { // If arr[i] is greater, then // check with Z[j][1] if (arr[j] < arr[i] && Z[i][0] < Z[j][1] + 1) Z[i][0] = Z[j][1] + 1; // If arr[i] is smaller, then // check with Z[j][0] if( arr[j] > arr[i] && Z[i][1] < Z[j][0] + 1) Z[i][1] = Z[j][0] + 1; } /* Pick maximum of both values at index i */ if (res < Math.max(Z[i][0], Z[i][1])) res = Math.max(Z[i][0], Z[i][1]); } return res;} /* Driver program */public static void main(String[] args){ int arr[] = { 10, 22, 9, 33, 49, 50, 31, 60 }; int n = arr.length; System.out.println(\"Length of Longest \"+ \"Zig-Zag subsequence is \" + zzis(arr, n));}}// This code is contributed by Prerna Saini", "e": 7567, "s": 5846, "text": null }, { "code": "# Python3 program to find longest# Zig-Zag subsequence in an array # Function to return max of two numbers # Function to return longest# Zig-Zag subsequence lengthdef zzis(arr, n): '''Z[i][0] = Length of the longest Zig-Zag subsequence ending at index i and last element is greater than its previous element Z[i][1] = Length of the longest Zig-Zag subsequence ending at index i and last element is smaller than its previous element ''' Z = [[1 for i in range(2)] for i in range(n)] res = 1 # Initialize result # Compute values in bottom up manner ''' for i in range(1, n): # Consider all elements as previous of arr[i] for j in range(i): # If arr[i] is greater, then check with Z[j][1] if (arr[j] < arr[i] and Z[i][0] < Z[j][1] + 1): Z[i][0] = Z[j][1] + 1 # If arr[i] is smaller, then check with Z[j][0] if( arr[j] > arr[i] and Z[i][1] < Z[j][0] + 1): Z[i][1] = Z[j][0] + 1 # Pick maximum of both values at index i ''' if (res < max(Z[i][0], Z[i][1])): res = max(Z[i][0], Z[i][1]) return res # Driver Codearr = [10, 22, 9, 33, 49, 50, 31, 60]n = len(arr)print(\"Length of Longest Zig-Zag subsequence is\", zzis(arr, n)) # This code is contributed by Mohit Kumar", "e": 8945, "s": 7567, "text": null }, { "code": "// C# program to find longest// Zig-Zag subsequence in an arrayusing System; class GFG{ // Function to return longest// Zig-Zag subsequence lengthstatic int zzis(int []arr, int n){ /*Z[i][0] = Length of the longest Zig-Zag subsequence ending at index i and last element is greater than its previous element Z[i][1] = Length of the longest Zig-Zag subsequence ending at index i and last element is smaller than its previous element */ int [,]Z = new int[n, 2]; /* Initialize all values from 1 */ for (int i = 0; i < n; i++) Z[i, 0] = Z[i, 1] = 1; // Initialize result int res = 1; /* Compute values in bottom up manner */ for (int i = 1; i < n; i++) { // Consider all elements as // previous of arr[i] for (int j = 0; j < i; j++) { // If arr[i] is greater, then // check with Z[j][1] if (arr[j] < arr[i] && Z[i, 0] < Z[j, 1] + 1) Z[i, 0] = Z[j, 1] + 1; // If arr[i] is smaller, then // check with Z[j][0] if( arr[j] > arr[i] && Z[i, 1] < Z[j, 0] + 1) Z[i, 1] = Z[j, 0] + 1; } /* Pick maximum of both values at index i */ if (res < Math.Max(Z[i, 0], Z[i, 1])) res = Math.Max(Z[i, 0], Z[i, 1]); } return res;} // Driver Codestatic public void Main (){ int []arr = {10, 22, 9, 33, 49, 50, 31, 60}; int n = arr.Length; Console.WriteLine(\"Length of Longest \"+ \"Zig-Zag subsequence is \" + zzis(arr, n)); }} // This code is contributed by ajit", "e": 10674, "s": 8945, "text": null }, { "code": "<?php//PHP program to find longest Zig-Zag//subsequence in an array // function to return max of two numbersfunction maxD($a, $b) { return ($a > $b) ? $a : $b; } // Function to return longest Zig-Zag subsequence lengthfunction zzis($arr, $n){ /*Z[i][0] = Length of the longest Zig-Zag subsequence ending at index i and last element is greater than its previous element Z[i][1] = Length of the longest Zig-Zag subsequence ending at index i and last element is smaller than its previous element */ //$Z[$n][2]; /* Initialize all values from 1 */ for ($i = 0; $i < $n; $i++) $Z[$i][0] = $Z[$i][1] = 1; $res = 1; // Initialize result /* Compute values in bottom up manner */ for ($i = 1; $i < $n; $i++) { // Consider all elements as previous of arr[i] for ($j = 0; $j < $i; $j++) { // If arr[i] is greater, then check with Z[j][1] if ($arr[$j] < $arr[$i] && $Z[$i][0] < $Z[$j][1] + 1) $Z[$i][0] = $Z[$j][1] + 1; // If arr[i] is smaller, then check with Z[j][0] if( $arr[$j] > $arr[$i] && $Z[$i][1] < $Z[$j][0] + 1) $Z[$i][1] = $Z[$j][0] + 1; } /* Pick maximum of both values at index i */ if ($res < max($Z[$i][0], $Z[$i][1])) $res = max($Z[$i][0], $Z[$i][1]); } return $res;} /* Driver program */ $arr = array( 10, 22, 9, 33, 49, 50, 31, 60 ); $n = sizeof($arr); echo \"Length of Longest Zig-Zag subsequence is \", zzis($arr, $n) ; echo \"\\n\"; #This code is contributed by aj_36?>", "e": 12288, "s": 10674, "text": null }, { "code": "<script> // Javascript program to find longest // Zig-Zag subsequence in an array // Function to return longest // Zig-Zag subsequence length function zzis(arr, n) { /*Z[i][0] = Length of the longest Zig-Zag subsequence ending at index i and last element is greater than its previous element Z[i][1] = Length of the longest Zig-Zag subsequence ending at index i and last element is smaller than its previous element */ let Z = new Array(n); for(let i = 0; i < n; i++) { Z[i] = new Array(2); } /* Initialize all values from 1 */ for (let i = 0; i < n; i++) Z[i][0] = Z[i][1] = 1; let res = 1; // Initialize result /* Compute values in bottom up manner */ for (let i = 1; i < n; i++) { // Consider all elements as // previous of arr[i] for (let j = 0; j < i; j++) { // If arr[i] is greater, then // check with Z[j][1] if (arr[j] < arr[i] && Z[i][0] < Z[j][1] + 1) Z[i][0] = Z[j][1] + 1; // If arr[i] is smaller, then // check with Z[j][0] if( arr[j] > arr[i] && Z[i][1] < Z[j][0] + 1) Z[i][1] = Z[j][0] + 1; } /* Pick maximum of both values at index i */ if (res < Math.max(Z[i][0], Z[i][1])) res = Math.max(Z[i][0], Z[i][1]); } return res; } let arr = [ 10, 22, 9, 33, 49, 50, 31, 60 ]; let n = arr.length; document.write(\"Length of Longest \"+ \"Zig-Zag subsequence is \" + zzis(arr, n)); </script>", "e": 14124, "s": 12288, "text": null }, { "code": null, "e": 14134, "s": 14124, "text": "Output : " }, { "code": null, "e": 14177, "s": 14134, "text": "Length of Longest Zig-Zag subsequence is 6" }, { "code": null, "e": 14943, "s": 14177, "text": "Time Complexity : O(n2) Auxiliary Space : O(n)A better approach with time complexity O(n) is explained below: Let the sequence be stored in an unsorted integer array arr[N]. We shall proceed by comparing the mathematical signs(negative or positive) of the difference of two consecutive elements of arr. To achieve this, we shall store the sign of (arr[i] – arr[i-1]) in a variable, subsequently comparing it with that of (arr[i+1] – arr[i]). If it is different, we shall increment our result. For checking the sign, we shall use a simple Signum Function, which shall determine the sign of a number passed to it. That is, Considering the fact that we traverse the sequence only once, this becomes an O(n) solution.The algorithm for the approach discussed above is : " }, { "code": null, "e": 15200, "s": 14943, "text": "Input integer array seq[N].\nInitialize integer lastSign to 0. \nFOR i in range 1 to N - 1\n integer sign = signum(seq[i] - seq[i-1])\n IF sign != lastSign AND IF sign != 0\n increment length by 1. lastSign = sign.\n END IF\nEND FOR\nreturn length." }, { "code": null, "e": 15256, "s": 15200, "text": "Following is the implementation of the above approach: " }, { "code": null, "e": 15260, "s": 15256, "text": "C++" }, { "code": null, "e": 15265, "s": 15260, "text": "Java" }, { "code": null, "e": 15273, "s": 15265, "text": "Python3" }, { "code": null, "e": 15276, "s": 15273, "text": "C#" }, { "code": null, "e": 15287, "s": 15276, "text": "Javascript" }, { "code": "/*CPP program to find the maximum length of zig-zagsub-sequence in given sequence*/#include <bits/stdc++.h>#include <iostream>using namespace std; // Function prototype.int signum(int n); /* Function to calculate maximum length of zig-zagsub-sequence in given sequence.*/int maxZigZag(int seq[], int n){ if (n == 0) { return 0; } int lastSign = 0, length = 1; // Length is initialized to 1 as // that is minimum value // for arbitrary sequence. for (int i = 1; i < n; ++i) { int Sign = signum(seq[i] - seq[i - 1]); // It qualifies if (Sign != lastSign && Sign != 0) { // Updating lastSign lastSign = Sign; length++; } } return length;} /* Signum function :Returns 1 when passed a positive integerReturns -1 when passed a negative integerReturns 0 when passed 0. */int signum(int n){ if (n != 0) { return n > 0 ? 1 : -1; } else { return 0; }}// Driver methodint main(){ int sequence1[4] = { 1, 3, 6, 2 }; int sequence2[5] = { 5, 0, 3, 1, 0 }; int n1 = sizeof(sequence1) / sizeof(*sequence1); // size of sequences int n2 = sizeof(sequence2) / sizeof(*sequence2); int maxLength1 = maxZigZag(sequence1, n1); int maxLength2 = maxZigZag(sequence2, n2); // function call cout << \"The maximum length of zig-zag sub-sequence in \" \"first sequence is: \" << maxLength1; cout << endl; cout << \"The maximum length of zig-zag sub-sequence in \" \"second sequence is: \" << maxLength2;}", "e": 16887, "s": 15287, "text": null }, { "code": "// Java code to find out maximum length of zig-zag// sub-sequence in given sequenceclass zigZagMaxLength { // Driver method public static void main(String[] args) { int[] sequence1 = { 1, 3, 6, 2 }; int[] sequence2 = { 5, 0, 3, 1, 0 }; int n1 = sequence1.length; // size of sequences int n2 = sequence2.length; int maxLength1 = maxZigZag(sequence1, n1); int maxLength2 = maxZigZag(sequence2, n2); // function call System.out.println( \"The maximum length of zig-zag sub-sequence in first sequence is: \" + maxLength1); System.out.println( \"The maximum length of zig-zag sub-sequence in second sequence is: \" + maxLength2); } /* Function to calculate maximum length of zig-zag sub-sequence in given sequence. */ static int maxZigZag(int[] seq, int n) { if (n == 0) { return 0; } int lastSign = 0, length = 1; // length is initialized to 1 as that is minimum // value for arbitrary sequence. for (int i = 1; i < n; ++i) { int Sign = signum(seq[i] - seq[i - 1]); if (Sign != 0 && Sign != lastSign) // it qualifies { lastSign = Sign; // updating lastSign length++; } } return length; } /* Signum function : Returns 1 when passed a positive integer Returns -1 when passed a negative integer Returns 0 when passed 0. */ static int signum(int n) { if (n != 0) { return n > 0 ? 1 : -1; } else { return 0; } }}", "e": 18566, "s": 16887, "text": null }, { "code": "# Python3 program to find the maximum# length of zig-zag sub-sequence in# given sequence # Function to calculate maximum length# of zig-zag sub-sequence in given sequence. def maxZigZag(seq, n): if (n == 0): return 0 lastSign = 0 # Length is initialized to 1 as that is # minimum value for arbitrary sequence length = 1 for i in range(1, n): Sign = signum(seq[i] - seq[i - 1]) # It qualifies if (Sign != lastSign and Sign != 0): # Updating lastSign lastSign = Sign length += 1 return length # Signum function :# Returns 1 when passed a positive integer# Returns -1 when passed a negative integer# Returns 0 when passed 0. def signum(n): if (n != 0): return 1 if n > 0 else -1 else: return 0 # Driver codeif __name__ == '__main__': sequence1 = [1, 3, 6, 2] sequence2 = [5, 0, 3, 1, 0] n1 = len(sequence1) n2 = len(sequence2) # Function call maxLength1 = maxZigZag(sequence1, n1) maxLength2 = maxZigZag(sequence2, n2) print(\"The maximum length of zig-zag sub-sequence \" \"in first sequence is:\", maxLength1) print(\"The maximum length of zig-zag sub-sequence \" \"in second sequence is:\", maxLength2) # This code is contributed by himanshu77", "e": 19864, "s": 18566, "text": null }, { "code": "// C# code to find out maximum length of// zig-zag sub-sequence in given sequenceusing System; class zigZagMaxLength { // Driver method public static void Main(String[] args) { int[] sequence1 = { 1, 3, 6, 2 }; int[] sequence2 = { 5, 0, 3, 1, 0 }; int n1 = sequence1.Length; // size of sequences int n2 = sequence2.Length; int maxLength1 = maxZigZag(sequence1, n1); int maxLength2 = maxZigZag(sequence2, n2); // function call Console.WriteLine( \"The maximum length of zig-zag sub-sequence\" + \" in first sequence is: \" + maxLength1); Console.WriteLine( \"The maximum length of zig-zag \" + \"sub-sequence in second sequence is: \" + maxLength2); } /* Function to calculate maximum length of zig-zag sub-sequence in given sequence. */ static int maxZigZag(int[] seq, int n) { if (n == 0) { return 0; } // length is initialized to 1 as that is minimum // value for arbitrary sequence. int lastSign = 0, length = 1; for (int i = 1; i < n; ++i) { int Sign = signum(seq[i] - seq[i - 1]); if (Sign != 0 && Sign != lastSign) // it qualifies { lastSign = Sign; // updating lastSign length++; } } return length; } /* Signum function : Returns 1 when passed a positive integer Returns -1 when passed a negative integer Returns 0 when passed 0. */ static int signum(int n) { if (n != 0) { return n > 0 ? 1 : -1; } else { return 0; } }} // This code is contributed by Rajput-Ji", "e": 21614, "s": 19864, "text": null }, { "code": "<script> // Javascript code to find out maximum length of // zig-zag sub-sequence in given sequence /* Function to calculate maximum length of zig-zag sub-sequence in given sequence. */ function maxZigZag(seq, n) { if (n == 0) { return 0; } // length is initialized to 1 as that is minimum // value for arbitrary sequence. let lastSign = 0, length = 1; for (let i = 1; i < n; ++i) { let Sign = signum(seq[i] - seq[i - 1]); if (Sign != 0 && Sign != lastSign) // it qualifies { lastSign = Sign; // updating lastSign length++; } } return length; } /* Signum function : Returns 1 when passed a positive integer Returns -1 when passed a negative integer Returns 0 when passed 0. */ function signum(n) { if (n != 0) { return n > 0 ? 1 : -1; } else { return 0; } } let sequence1 = [ 1, 3, 6, 2 ]; let sequence2 = [ 5, 0, 3, 1, 0 ]; let n1 = sequence1.length; // size of sequences let n2 = sequence2.length; let maxLength1 = maxZigZag(sequence1, n1); let maxLength2 = maxZigZag(sequence2, n2); // function call document.write(\"The maximum length of zig-zag sub-sequence\" + \" in first sequence is: \" + maxLength1 + \"</br>\"); document.write( \"The maximum length of zig-zag \" + \"sub-sequence in second sequence is: \" + maxLength2 + \"</br>\"); </script>", "e": 23170, "s": 21614, "text": null }, { "code": null, "e": 23180, "s": 23170, "text": "Output : " }, { "code": null, "e": 23315, "s": 23180, "text": "The maximum length of zig-zag sub-sequence in first sequence is: 3\nThe maximum length of zig-zag sub-sequence in second sequence is: 4" }, { "code": null, "e": 23534, "s": 23315, "text": "Time Complexity : O(n) Auxiliary Space : O(1)This article is contributed by Utkarsh Trivedi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 23540, "s": 23534, "text": "jit_t" }, { "code": null, "e": 23556, "s": 23540, "text": "santhanambr2002" }, { "code": null, "e": 23571, "s": 23556, "text": "mohit kumar 29" }, { "code": null, "e": 23581, "s": 23571, "text": "Rajput-Ji" }, { "code": null, "e": 23592, "s": 23581, "text": "himanshu77" }, { "code": null, "e": 23607, "s": 23592, "text": "winter_soldier" }, { "code": null, "e": 23622, "s": 23607, "text": "rameshtravel07" }, { "code": null, "e": 23640, "s": 23622, "text": "divyeshrabadiya07" }, { "code": null, "e": 23649, "s": 23640, "text": "noob2000" }, { "code": null, "e": 23658, "s": 23649, "text": "Accolite" }, { "code": null, "e": 23670, "s": 23658, "text": "subsequence" }, { "code": null, "e": 23677, "s": 23670, "text": "Arrays" }, { "code": null, "e": 23697, "s": 23677, "text": "Dynamic Programming" }, { "code": null, "e": 23706, "s": 23697, "text": "Accolite" }, { "code": null, "e": 23713, "s": 23706, "text": "Arrays" }, { "code": null, "e": 23733, "s": 23713, "text": "Dynamic Programming" }, { "code": null, "e": 23831, "s": 23733, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 23899, "s": 23831, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 23943, "s": 23899, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 23975, "s": 23943, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 24023, "s": 23975, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 24037, "s": 24023, "text": "Linear Search" }, { "code": null, "e": 24067, "s": 24037, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 24096, "s": 24067, "text": "0-1 Knapsack Problem | DP-10" }, { "code": null, "e": 24130, "s": 24096, "text": "Longest Common Subsequence | DP-4" }, { "code": null, "e": 24168, "s": 24130, "text": "Longest Palindromic Substring | Set 1" } ]
Converting string ‘yyyy-mm-dd’ into DateTime in Python
23 Aug, 2021 In this article, we are going to convert DateTime string of the format ‘yyyy-mm-dd’ into DateTime using Python. yyyy-mm-dd stands for year-month-day . We can convert string format to datetime by using the strptime() function. We will use the ‘%Y/%m/%d’ format to get the string to datetime. Syntax: datetime.datetime.strptime(input,format) Parameter: input is the string datetime format is the format – ‘yyyy-mm-dd’ datetime is the module Example: Python program to convert string datetime format to datetime Python3 # import the datetime moduleimport datetime # datetime in string format for may 25 1999input = '2021/05/25' # formatformat = '%Y/%m/%d' # convert from string format to datetime formatdatetime = datetime.datetime.strptime(input, format) # get the date from the datetime using date() # functionprint(datetime.date()) 2021-05-25 Example 2: Convert a list of string DateTime to DateTime Python3 # import the datetime moduleimport datetime # datetime in string format for list of datesinput = ['2021/05/25', '2020/05/25', '2019/02/15', '1999/02/4'] # formatformat = '%Y/%m/%d'for i in input: # convert from string format to datetime format # and get the date print(datetime.datetime.strptime(i, format).date()) 2021-05-25 2020-05-25 2019-02-15 1999-02-04 Picked Python-datetime Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to iterate through Excel rows in Python? Rotate axis tick labels in Seaborn and Matplotlib Deque in Python Queue in Python Defaultdict in Python Check if element exists in list in Python Python Classes and Objects Bar Plot in Matplotlib reduce() in Python Python | Get unique values from a list
[ { "code": null, "e": 53, "s": 25, "text": "\n23 Aug, 2021" }, { "code": null, "e": 166, "s": 53, "text": "In this article, we are going to convert DateTime string of the format ‘yyyy-mm-dd’ into DateTime using Python. " }, { "code": null, "e": 205, "s": 166, "text": "yyyy-mm-dd stands for year-month-day ." }, { "code": null, "e": 347, "s": 205, "text": "We can convert string format to datetime by using the strptime() function. We will use the ‘%Y/%m/%d’ format to get the string to datetime." }, { "code": null, "e": 355, "s": 347, "text": "Syntax:" }, { "code": null, "e": 396, "s": 355, "text": "datetime.datetime.strptime(input,format)" }, { "code": null, "e": 407, "s": 396, "text": "Parameter:" }, { "code": null, "e": 436, "s": 407, "text": "input is the string datetime" }, { "code": null, "e": 472, "s": 436, "text": "format is the format – ‘yyyy-mm-dd’" }, { "code": null, "e": 495, "s": 472, "text": "datetime is the module" }, { "code": null, "e": 565, "s": 495, "text": "Example: Python program to convert string datetime format to datetime" }, { "code": null, "e": 573, "s": 565, "text": "Python3" }, { "code": "# import the datetime moduleimport datetime # datetime in string format for may 25 1999input = '2021/05/25' # formatformat = '%Y/%m/%d' # convert from string format to datetime formatdatetime = datetime.datetime.strptime(input, format) # get the date from the datetime using date() # functionprint(datetime.date())", "e": 892, "s": 573, "text": null }, { "code": null, "e": 904, "s": 892, "text": "2021-05-25\n" }, { "code": null, "e": 961, "s": 904, "text": "Example 2: Convert a list of string DateTime to DateTime" }, { "code": null, "e": 969, "s": 961, "text": "Python3" }, { "code": "# import the datetime moduleimport datetime # datetime in string format for list of datesinput = ['2021/05/25', '2020/05/25', '2019/02/15', '1999/02/4'] # formatformat = '%Y/%m/%d'for i in input: # convert from string format to datetime format # and get the date print(datetime.datetime.strptime(i, format).date())", "e": 1299, "s": 969, "text": null }, { "code": null, "e": 1344, "s": 1299, "text": "2021-05-25\n2020-05-25\n2019-02-15\n1999-02-04\n" }, { "code": null, "e": 1351, "s": 1344, "text": "Picked" }, { "code": null, "e": 1367, "s": 1351, "text": "Python-datetime" }, { "code": null, "e": 1374, "s": 1367, "text": "Python" }, { "code": null, "e": 1472, "s": 1374, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1517, "s": 1472, "text": "How to iterate through Excel rows in Python?" }, { "code": null, "e": 1567, "s": 1517, "text": "Rotate axis tick labels in Seaborn and Matplotlib" }, { "code": null, "e": 1583, "s": 1567, "text": "Deque in Python" }, { "code": null, "e": 1599, "s": 1583, "text": "Queue in Python" }, { "code": null, "e": 1621, "s": 1599, "text": "Defaultdict in Python" }, { "code": null, "e": 1663, "s": 1621, "text": "Check if element exists in list in Python" }, { "code": null, "e": 1690, "s": 1663, "text": "Python Classes and Objects" }, { "code": null, "e": 1713, "s": 1690, "text": "Bar Plot in Matplotlib" }, { "code": null, "e": 1732, "s": 1713, "text": "reduce() in Python" } ]
Difference between NULL pointer, Null character (‘\0’) and ‘0’ in C with Examples
01 Jun, 2020 NULL Pointer:The integer constant zero(0) has different meanings depending upon it’s used. In all cases, it is an integer constant with the value 0, it is just described in different ways.If any pointer is being compared to 0, then this is a check to see if the pointer is a null pointer. This 0 is then referred to as a null pointer constant. The C standard defines that 0 is typecast to (void *) is both a null pointer and a null pointer constant.The macro NULL is provided in the header file “stddef.h”. Below are the ways to check for a NULL pointer: NULL is defined to compare equal to a null pointer as:if(pointer == NULL) if(pointer == NULL) Below if statement implicitly checks “is not 0”, so we reverse that to mean “is 0” as:if(!pointer) if(!pointer) Null Characters(‘\0’):‘\0’ is defined to be a null character. It is a character with all bits set to zero. This has nothing to do with pointers. ‘\0’ is (like all character literals) an integer constant with the value zero. Below statement checks if the string pointer is pointing at a null character.if (!*string_pointer) Below statement checks if the string pointer is pointing at a not-null character.if (*string_pointer) Below statement checks if the string pointer is pointing at a null character.if (!*string_pointer) if (!*string_pointer) Below statement checks if the string pointer is pointing at a not-null character.if (*string_pointer) if (*string_pointer) In C language string is nothing but an array of char type. It stores each of the characters in a memory space of 1 byte. Each array is terminated with ‘\0’ or null character but if we store a ‘0’ inside a string both are not same according to the C language. ‘0’ means 48 according to the ASCII Table whereas ‘\0’ means 0 according to the ASCII table. Below is the C program to print the value of ‘\0’ and ‘0’: // C program to print the value of// '\0' and '0'#include <stdio.h> // Driver Codeint main(){ // Print the value of // '\0' and '0' printf("\\0 is %d\n", '\0'); printf("0 is %d\n", '0'); return 0;} \0 is 0 0 is 48 C Basics C-Pointer Basics C Programs Difference Between Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. C Program to read contents of Whole File Producer Consumer Problem in C Difference between break and continue statement in C C Hello World Program Handling multiple clients on server with multithreading using Socket Programming in C/C++ Class method vs Static method in Python Difference between BFS and DFS Difference between var, let and const keywords in JavaScript Difference Between Method Overloading and Method Overriding in Java Differences between JDK, JRE and JVM
[ { "code": null, "e": 54, "s": 26, "text": "\n01 Jun, 2020" }, { "code": null, "e": 561, "s": 54, "text": "NULL Pointer:The integer constant zero(0) has different meanings depending upon it’s used. In all cases, it is an integer constant with the value 0, it is just described in different ways.If any pointer is being compared to 0, then this is a check to see if the pointer is a null pointer. This 0 is then referred to as a null pointer constant. The C standard defines that 0 is typecast to (void *) is both a null pointer and a null pointer constant.The macro NULL is provided in the header file “stddef.h”." }, { "code": null, "e": 609, "s": 561, "text": "Below are the ways to check for a NULL pointer:" }, { "code": null, "e": 684, "s": 609, "text": "NULL is defined to compare equal to a null pointer as:if(pointer == NULL)\n" }, { "code": null, "e": 705, "s": 684, "text": "if(pointer == NULL)\n" }, { "code": null, "e": 806, "s": 705, "text": "Below if statement implicitly checks “is not 0”, so we reverse that to mean “is 0” as:if(!pointer) \n" }, { "code": null, "e": 821, "s": 806, "text": "if(!pointer) \n" }, { "code": null, "e": 1045, "s": 821, "text": "Null Characters(‘\\0’):‘\\0’ is defined to be a null character. It is a character with all bits set to zero. This has nothing to do with pointers. ‘\\0’ is (like all character literals) an integer constant with the value zero." }, { "code": null, "e": 1247, "s": 1045, "text": "Below statement checks if the string pointer is pointing at a null character.if (!*string_pointer)\nBelow statement checks if the string pointer is pointing at a not-null character.if (*string_pointer)\n" }, { "code": null, "e": 1347, "s": 1247, "text": "Below statement checks if the string pointer is pointing at a null character.if (!*string_pointer)\n" }, { "code": null, "e": 1370, "s": 1347, "text": "if (!*string_pointer)\n" }, { "code": null, "e": 1473, "s": 1370, "text": "Below statement checks if the string pointer is pointing at a not-null character.if (*string_pointer)\n" }, { "code": null, "e": 1495, "s": 1473, "text": "if (*string_pointer)\n" }, { "code": null, "e": 1847, "s": 1495, "text": "In C language string is nothing but an array of char type. It stores each of the characters in a memory space of 1 byte. Each array is terminated with ‘\\0’ or null character but if we store a ‘0’ inside a string both are not same according to the C language. ‘0’ means 48 according to the ASCII Table whereas ‘\\0’ means 0 according to the ASCII table." }, { "code": null, "e": 1906, "s": 1847, "text": "Below is the C program to print the value of ‘\\0’ and ‘0’:" }, { "code": "// C program to print the value of// '\\0' and '0'#include <stdio.h> // Driver Codeint main(){ // Print the value of // '\\0' and '0' printf(\"\\\\0 is %d\\n\", '\\0'); printf(\"0 is %d\\n\", '0'); return 0;}", "e": 2120, "s": 1906, "text": null }, { "code": null, "e": 2137, "s": 2120, "text": "\\0 is 0\n0 is 48\n" }, { "code": null, "e": 2146, "s": 2137, "text": "C Basics" }, { "code": null, "e": 2163, "s": 2146, "text": "C-Pointer Basics" }, { "code": null, "e": 2174, "s": 2163, "text": "C Programs" }, { "code": null, "e": 2193, "s": 2174, "text": "Difference Between" }, { "code": null, "e": 2291, "s": 2193, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2332, "s": 2291, "text": "C Program to read contents of Whole File" }, { "code": null, "e": 2363, "s": 2332, "text": "Producer Consumer Problem in C" }, { "code": null, "e": 2416, "s": 2363, "text": "Difference between break and continue statement in C" }, { "code": null, "e": 2438, "s": 2416, "text": "C Hello World Program" }, { "code": null, "e": 2528, "s": 2438, "text": "Handling multiple clients on server with multithreading using Socket Programming in C/C++" }, { "code": null, "e": 2568, "s": 2528, "text": "Class method vs Static method in Python" }, { "code": null, "e": 2599, "s": 2568, "text": "Difference between BFS and DFS" }, { "code": null, "e": 2660, "s": 2599, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2728, "s": 2660, "text": "Difference Between Method Overloading and Method Overriding in Java" } ]
Program to print the Alphabets of a Given Word using * pattern
15 Jun, 2021 Given a word str, the task is to print the alphabets of this word using * pattern.Examples: Input: GFG Output: ****** * * * * **** * * * * * * *** * ******* ** ** ****** ** ** ** ****** * * * * **** * * * * * * *** * Approach: A simple implementation is to form the pattern for each letter A-Z and call them as functions.Below is the implementation of the above approach: C++ C Java C# // C++ Program to print the Alphabets// of a Given Word using * pattern#include <iostream>using namespace std;char ch; // Function to print the letter Avoid a(void){ cout << endl; for (int i = 0; i < 8; i++) { cout << " "; for (int a = 0; a < 8; a++) { if (i == 0 && (a == 0 || a == 7)) cout << " "; else if (a < 2 || a > 5) { cout << ch; } else if (i < 2 || (i > 3 && i < 5)) { cout << ch; } else cout << " "; } cout << endl; }} // Function to print the letter Bvoid b(void){ cout << endl; for (int i = 0; i < 9; i++) { cout << ch << ch; for (int r = 0; r < 6; r++) { if (i == 0 && r < 5) cout << ch; else if (i == 1) cout << ch; else if (i < 4 && i > 0 && r > 3) { cout << ch; } else if (i == 4 && r < 5) { cout << ch; } else if (i > 4 && i < 7 && r > 3) { cout << ch; } else if (i == 7) { cout << ch; } else if (i == 8 && r < 5) { cout << ch; } else cout << " "; } cout << endl; }} // Function to print the letter Cvoid c(void){ cout << endl; for (int i = 0; i < 8; i++) { cout << " "; for (int o = 0; o < 8; o++) { if (i == 0 && (o <= 1)) cout << " "; else if (i == 1 && (o == 0 || o == 8 - i || (o > 1))) cout << " "; else if (i == 2 && (o == 1 || o == 8 - i || (o > 1))) cout << " "; else if ((i == 3 || i == 4 || i == 5) && (o > 0)) cout << " "; else if (i == 6 && (o == 0 || o == 8 + 5 - i || (o > 1))) cout << " "; else if (i == 7 && (o <= 1)) cout << " "; else { cout << ch; } } cout << endl; }} // Function to print the letter Dvoid d(void){ cout << endl; for (int i = 0; i < 8; i++) { { cout << " "<< ch; } for (int o = 0; o < 8; o++) { if (i == 0 && (o >= 6 - i)) cout << " "; else if (i == 1 && (o == 0 || o == 8 - i || (o < 6))) cout << " "; else if (i == 2 && (o == 1 || o == 8 - i || (o < 6))) cout << " "; else if ((i == 3 || i == 4 || i == 5) && (o < 7)) cout << " "; else if (i == 6 && (o == 0 || o == 8 + 5 - i || (o < 6))) cout << " "; else if (i == 7 && (o >= 6 - i + 7)) cout << " "; else { cout << ch; } } cout << endl; }} // Function to print the letter Evoid e(void){ cout << endl; for (int i = 0; i < 8; i++) { cout << " "; for (int j = 0; j < 7; j++) { if (i == 0) { cout << ch; } else if (i > 0 && i < 3 && j < 2) { cout << ch; } else if (i == 3 && j < 6) { cout << ch; } else if (i > 3 && i < 6 && j < 2) { cout << ch; } else if (i == 6) { cout << ch; } else cout << " "; } cout << endl; }} // Function to print the letter Fvoid f(void){ cout << endl; for (int i = 0; i < 8; i++) { cout << " "; for (int j = 0; j < 7; j++) { if (i == 0) { cout << ch; } else if (i > 0 && i < 3 && j < 2) { cout << ch; } else if (i == 3 && j < 6) { cout << ch; } else if (i > 3 && i < 7 && j < 2) { cout << ch; } else cout << " "; } cout << endl; }} // Function to print the letter Gvoid g(void){ cout << endl; for (int i = 0; i < 8; i++) { cout << " "; for (int o = 0; o < 8; o++) { if (i == 4 && o > 3 || (o == 4 || o == 7) && i > 4) { cout << ch; } else if (i == 0 && (o <= 1)) cout << " "; else if (i == 1 && (o == 0 || o == 8 - i || (o > 1))) cout << " "; else if (i == 2 && (o == 1 || o == 8 - i || (o > 1))) cout << " "; else if ((i == 3 || i == 4 || i == 5) && (o > 0)) cout << " "; else if (i == 6 && (o == 0 || (o > 1))) cout << " "; else if (i == 7 && (o <= 1 || o == 5 || o == 6)) cout << " "; else { cout << ch; } } cout << endl; }} // Function to print the letter Hvoid h(void){ cout << endl; for (int i = 0; i < 8; i++) { cout << " "; for (int h = 0; h < 8; h++) { if (h < 2 || h > 5) { cout << ch; } else if (i > 2 && i < 5) { cout << ch; } else cout << " "; } cout << endl; }} // Function to print the letter Ivoid i(void){ cout << endl; for (int i = 0; i < 8; i++) { cout << " "; for (int t = 0; t < 8; t++) { if ((i < 1 || i > 6) && t < 8) { cout << ch; } else if (i > 0 && t < 3) cout << " "; else if (i > 0 && t > 2 && t < 5) { cout << ch; } else if (i > 0 && t > 4) cout << " "; else { } } cout << endl; }} // Function to print the letter Jvoid j(void){ cout << endl; for (int i = 0; i < 8; i++) { cout << " "; for (int h = 0; h < 8; h++) { if (i < 1) { cout << ch; } else if (i == 5 && h < 1) { cout << ch; } else if (i < 7 && h > 5) { cout << ch; } else if (i == 7 && (h == 0 || h == 7)) cout << " "; else if (i > 5) { cout << ch; } else cout << " "; } cout << endl; }} // Function to print the letter Kvoid k(void){ cout << endl; for (int i = 0; i < 8; i++) { cout << " "; for (int k1 = 0; k1 < 7; k1++) { if (k1 < 2) { cout << ch; } else if ((k1 >= 5 - i) && (k1 <= 6 - i)) { cout << ch; } else if (i >= 4) { if (k1 == i - 2 || k1 == i - 1) { cout << ch; } else cout << " "; } else cout << " "; } cout << endl; }} // Function to print the letter Lvoid l(void){ cout << endl; for (int i = 0; i < 8; i++) { cout << " "; { cout << ch << ch; } if (i == 6) { { cout << ch << ch; } { cout << ch << ch; } cout << ch << ch; } if (i == 7) { { cout << ch << ch; } { cout << ch << ch; } cout << ch << ch; } cout << endl; }} // Function to print the letter Mvoid m(void){ cout << endl; for (int i = 0; i < 8; i++) { cout << " "; for (int j = 0; j < 8; j++) { if (j == 0 || j == 7) { cout << ch; } else if (i < 4 && (j == 7 - i || j == i)) { cout << ch; } else cout << " "; } cout << endl; }} // Function to print the letter Nvoid n(void){ cout << endl; for (int i = 0; i < 8; i++) { cout << " "; for (int n = 0; n < 8; n++) { if (n < 2 || n > 5) { cout << ch; } else if (i == n - 1 || i == n + 1 || i == n) { cout << ch; } else cout << " "; } cout << endl; }} // Function to print the letter Ovoid o(void){ cout << endl; for (int i = 0; i < 8; i++) { cout << " "; for (int o = 0; o < 8; o++) { if (i == 0 && (o <= 1 || o >= 6 - i)) cout << " "; else if (i == 1 && (o == 0 || o == 8 - i || (o < 6 && o > 1))) cout << " "; else if (i == 2 && (o == 1 || o == 8 - i || (o < 6 && o > 1))) cout << " "; else if ((i == 3 || i == 4 || i == 5) && (o > 0 && o < 7)) cout << " "; else if (i == 6 && (o == 0 || o == 8 + 5 - i || (o < 6 && o > 1))) cout << " "; else if (i == 7 && (o <= 1 || o >= 6 - i + 7)) cout << " "; else { cout << ch; } } cout << endl; }} // Function to print the letter Pvoid p(void){ cout << endl; for (int i = 0; i < 8; i++) { cout << " "; { cout << ch << ch; } for (int r = 0; r < 6; r++) { if (i == 0 && r < 5) cout << ch; else if (i == 1) cout << ch; else if (i < 4 && i > 0 && r > 3) { cout << ch; } else if (i == 4 && r < 5) { cout << ch; } else cout << " "; } cout << endl; }} // Function to print the letter Qvoid q(void){ cout << endl; for (int i = 0; i < 8; i++) { cout << " "; for (int o = 0; o < 8; o++) { if (o == i) cout << ch; else if (i == 0 && (o <= 1 || o >= 6 - i)) cout << " "; else if (i == 1 && (o == 0 || o == 8 - i || (o < 6 && o > 1))) cout << " "; else if (i == 2 && (o == 1 || o == 8 - i || (o < 6 && o > 1))) cout << " "; else if ((i == 3 || i == 4 || i == 5) && (o > 0 && o < 7)) cout << " "; else if (i == 6 && (o == 0 || o == 8 + 5 - i || (o < 6 && o > 1))) cout << " "; else if (i == 7 && (o <= 1 || o >= 6 - i + 7)) cout << " "; else { cout << ch; } } cout << endl; }} // Function to print the letter Rvoid r(void){ cout << endl; for (int i = 0; i < 8; i++) { cout << " "; { cout << ch << ch; } for (int r = 0; r < 6; r++) { if (i == 0 && r < 5) cout << ch; else if (i == 1) cout << ch; else if (i < 4 && i > 0 && r > 3) { cout << ch; } else if (i >= 4) { if (i == 4 && (r == 3 || r == 4)) { cout << ch; } else if (r == i - 2 || r == i - 3) { cout << ch; } else cout << " "; } else cout << " "; } cout << endl; }} // Function to print the letter Svoid s(void){ cout << endl; for (int i = 0; i < 8; i++) { cout << " "; for (int j = 0; j < 7; j++) { if (i == 0 && j > 0) { cout << ch; } else if (i > 0 && i < 3 && j < 2) { cout << ch; } else if (i == 3 && j > 0 && j < 6) { cout << ch; } else if (i > 3 && i < 6 && j > 4) { cout << ch; } else if (i == 6 && j < 6) { cout << ch; } else cout << " "; } cout << endl; }} // Function to print the letter Tvoid t(void){ cout << endl; for (int i = 0; i < 8; i++) { cout << " "; for (int t = 0; t < 8; t++) { if (i < 2 && t < 8) { cout << ch; } if (i > 1 && t < 3) cout << " "; if (i > 1 && t > 2 && t < 5) { cout << ch; } if (i > 1 && t > 4) cout << " "; } cout << endl; }} // Function to print the letter Uvoid u(void){ cout << endl; for (int i = 0; i < 8; i++) { cout << " "; for (int h = 0; h < 8; h++) { if (i < 7 && (h < 2 || h > 5)) { cout << ch; } else if (i == 7 && (h == 0 || h == 7)) cout << " "; else if (i > 5) { cout << ch; } else cout << " "; } cout << endl; }} // Function to print the letter Vvoid v(void){ cout << endl; for (int i = 0; i < 8; i++) { cout << " "; for (int v = 0; v < 8; v++) if ((v == 0 || v == 7) && i < 4) { cout << ch; } else if ((v == i - 4 || v == 11 - i) && i >= 4) { cout << ch; } else cout << " "; cout << endl; }} // Function to print the letter Wvoid w(void){ cout << endl; for (int i = 0; i < 8; i++) { cout << " "; for (int j = 0; j < 8; j++) { if (j == 0 || j == 7) { cout << ch; } else if (i > 3 && (j == 7 - i || j == i)) { cout << ch; } else cout << " "; } cout << endl; }} // Function to print the letter Xvoid x(void){ cout << endl; for (int i = 0; i < 8; i++) { cout << " "; for (int m = 0; m < 8; m++) { if (i == m || m == 7 - i) { cout << ch; } else cout << " "; } cout << endl; }} // Function to print the letter Yvoid y(void){ cout << endl; for (int i = 0; i < 8; i++) { cout << " "; for (int y = 0; y < 8; y++) { if (i < 4) { if (y == i || y == i + 1 || y == 6 - i || y == 7 - i) { cout << ch; } else cout << " "; } else if (y == 3 || y == 4) { cout << ch; } else cout << " "; } cout << endl; }} // Function to print the letter Zvoid z(void){ cout << endl; for (int i = 0; i < 8; i++) { cout << " "; for (int j = 0; j < 8; j++) { if (i == 0 || i == 7) { cout << ch; } else if (j == 7 - i) { cout << ch; } else cout << " "; } cout << endl; }} // Function to print the required pattern// by taking out each characters in itvoid printPattern(char* str){ int in = 0; while (str[in]) { char ch = str[in]; if (ch < 95) ch = ch + 32; switch (ch) { case 'a': a(); break; case 'b': b(); break; case 'c': c(); break; case 'd': d(); break; case 'e': e(); break; case 'f': f(); break; case 'g': g(); break; case 'h': h(); break; case 'i': i(); break; case 'j': j(); break; case 'k': k(); break; case 'l': l(); break; case 'm': m(); break; case 'n': n(); break; case 'o': o(); break; case 'p': p(); break; case 'q': q(); break; case 'r': r(); break; case 's': s(); break; case 't': t(); break; case 'u': u(); break; case 'v': v(); break; case 'w': w(); break; case 'x': x(); break; case 'y': y(); break; case 'z': z(); break; default: break; } in++; }} // Driver codeint main(){ ch = '*'; char *str = "GFG"; printPattern(str); return 0;} // This code is contributed by shubhamsingh // C Program to print the Alphabets// of a Given Word using * pattern #include <stdio.h>#include <string.h> char ch; // Function to print the letter Avoid a(void){ printf("\n"); for (int i = 0; i < 8; i++) { printf(" "); for (int a = 0; a < 8; a++) { if (i == 0 && (a == 0 || a == 7)) printf(" "); else if (a < 2 || a > 5) { printf("%c", ch); } else if (i < 2 || (i > 3 && i < 5)) { printf("%c", ch); } else printf(" "); } printf("\n"); }} // Function to print the letter Bvoid b(void){ printf("\n"); for (int i = 0; i < 9; i++) { printf(" %c%c", ch, ch); for (int r = 0; r < 6; r++) { if (i == 0 && r < 5) printf("%c", ch); else if (i == 1) printf("%c", ch); else if (i < 4 && i > 0 && r > 3) { printf("%c", ch); } else if (i == 4 && r < 5) { printf("%c", ch); } else if (i > 4 && i < 7 && r > 3) { printf("%c", ch); } else if (i == 7) { printf("%c", ch); } else if (i == 8 && r < 5) { printf("%c", ch); } else printf(" "); } printf("\n"); }} // Function to print the letter Cvoid c(void){ printf("\n"); for (int i = 0; i < 8; i++) { printf(" "); for (int o = 0; o < 8; o++) { if (i == 0 && (o <= 1)) printf(" "); else if (i == 1 && (o == 0 || o == 8 - i || (o > 1))) printf(" "); else if (i == 2 && (o == 1 || o == 8 - i || (o > 1))) printf(" "); else if ((i == 3 || i == 4 || i == 5) && (o > 0)) printf(" "); else if (i == 6 && (o == 0 || o == 8 + 5 - i || (o > 1))) printf(" "); else if (i == 7 && (o <= 1)) printf(" "); else { printf("%c", ch); } } printf("\n"); }} // Function to print the letter Dvoid d(void){ printf("\n"); for (int i = 0; i < 8; i++) { { printf(" %c", ch); } for (int o = 0; o < 8; o++) { if (i == 0 && (o >= 6 - i)) printf(" "); else if (i == 1 && (o == 0 || o == 8 - i || (o < 6))) printf(" "); else if (i == 2 && (o == 1 || o == 8 - i || (o < 6))) printf(" "); else if ((i == 3 || i == 4 || i == 5) && (o < 7)) printf(" "); else if (i == 6 && (o == 0 || o == 8 + 5 - i || (o < 6))) printf(" "); else if (i == 7 && (o >= 6 - i + 7)) printf(" "); else { printf("%c", ch); } } printf("\n"); }} // Function to print the letter Evoid e(void){ printf("\n"); for (int i = 0; i < 8; i++) { printf(" "); for (int j = 0; j < 7; j++) { if (i == 0) { printf("%c", ch); } else if (i > 0 && i < 3 && j < 2) { printf("%c", ch); } else if (i == 3 && j < 6) { printf("%c", ch); } else if (i > 3 && i < 6 && j < 2) { printf("%c", ch); } else if (i == 6) { printf("%c", ch); } else printf(" "); } printf("\n"); }} // Function to print the letter Fvoid f(void){ printf("\n"); for (int i = 0; i < 8; i++) { printf(" "); for (int j = 0; j < 7; j++) { if (i == 0) { printf("%c", ch); } else if (i > 0 && i < 3 && j < 2) { printf("%c", ch); } else if (i == 3 && j < 6) { printf("%c", ch); } else if (i > 3 && i < 7 && j < 2) { printf("%c", ch); } else printf(" "); } printf("\n"); }} // Function to print the letter Gvoid g(void){ printf("\n"); for (int i = 0; i < 8; i++) { printf(" "); for (int o = 0; o < 8; o++) { if (i == 4 && o > 3 || (o == 4 || o == 7) && i > 4) { printf("%c", ch); } else if (i == 0 && (o <= 1)) printf(" "); else if (i == 1 && (o == 0 || o == 8 - i || (o > 1))) printf(" "); else if (i == 2 && (o == 1 || o == 8 - i || (o > 1))) printf(" "); else if ((i == 3 || i == 4 || i == 5) && (o > 0)) printf(" "); else if (i == 6 && (o == 0 || (o > 1))) printf(" "); else if (i == 7 && (o <= 1 || o == 5 || o == 6)) printf(" "); else { printf("%c", ch); } } printf("\n"); }} // Function to print the letter Hvoid h(void){ printf("\n"); for (int i = 0; i < 8; i++) { printf(" "); for (int h = 0; h < 8; h++) { if (h < 2 || h > 5) { printf("%c", ch); } else if (i > 2 && i < 5) { printf("%c", ch); } else printf(" "); } printf("\n"); }} // Function to print the letter Ivoid i(void){ printf("\n"); for (int i = 0; i < 8; i++) { printf(" "); for (int t = 0; t < 8; t++) { if ((i < 1 || i > 6) && t < 8) { printf("%c", ch); } else if (i > 0 && t < 3) printf(" "); else if (i > 0 && t > 2 && t < 5) { printf("%c", ch); } else if (i > 0 && t > 4) printf(" "); else { } } printf("\n"); }} // Function to print the letter Jvoid j(void){ printf("\n"); for (int i = 0; i < 8; i++) { printf(" "); for (int h = 0; h < 8; h++) { if (i < 1) { printf("%c", ch); } else if (i == 5 && h < 1) { printf("%c", ch); } else if (i < 7 && h > 5) { printf("%c", ch); } else if (i == 7 && (h == 0 || h == 7)) printf(" "); else if (i > 5) { printf("%c", ch); } else printf(" "); } printf("\n"); }} // Function to print the letter Kvoid k(void){ printf("\n"); for (int i = 0; i < 8; i++) { printf(" "); for (int k1 = 0; k1 < 7; k1++) { if (k1 < 2) { printf("%c", ch); } else if ((k1 >= 5 - i) && (k1 <= 6 - i)) { printf("%c", ch); } else if (i >= 4) { if (k1 == i - 2 || k1 == i - 1) { printf("%c", ch); } else printf(" "); } else printf(" "); } printf("\n"); }} // Function to print the letter Lvoid l(void){ printf("\n"); for (int i = 0; i < 8; i++) { printf(" "); { printf("%c%c", ch, ch); } if (i == 6) { { printf("%c%c", ch, ch); } { printf("%c%c", ch, ch); } printf("%c%c", ch, ch); } if (i == 7) { { printf("%c%c", ch, ch); } { printf("%c%c", ch, ch); } printf("%c%c", ch, ch); } printf("\n"); }} // Function to print the letter Mvoid m(void){ printf("\n"); for (int i = 0; i < 8; i++) { printf(" "); for (int j = 0; j < 8; j++) { if (j == 0 || j == 7) { printf("%c", ch); } else if (i < 4 && (j == 7 - i || j == i)) { printf("%c", ch); } else printf(" "); } printf("\n"); }} // Function to print the letter Nvoid n(void){ printf("\n"); for (int i = 0; i < 8; i++) { printf(" "); for (int n = 0; n < 8; n++) { if (n < 2 || n > 5) { printf("%c", ch); } else if (i == n - 1 || i == n + 1 || i == n) { printf("%c", ch); } else printf(" "); } printf("\n"); }} // Function to print the letter Ovoid o(void){ printf("\n"); for (int i = 0; i < 8; i++) { printf(" "); for (int o = 0; o < 8; o++) { if (i == 0 && (o <= 1 || o >= 6 - i)) printf(" "); else if (i == 1 && (o == 0 || o == 8 - i || (o < 6 && o > 1))) printf(" "); else if (i == 2 && (o == 1 || o == 8 - i || (o < 6 && o > 1))) printf(" "); else if ((i == 3 || i == 4 || i == 5) && (o > 0 && o < 7)) printf(" "); else if (i == 6 && (o == 0 || o == 8 + 5 - i || (o < 6 && o > 1))) printf(" "); else if (i == 7 && (o <= 1 || o >= 6 - i + 7)) printf(" "); else { printf("%c", ch); } } printf("\n"); }} // Function to print the letter Pvoid p(void){ printf("\n"); for (int i = 0; i < 8; i++) { printf(" "); { printf("%c%c", ch, ch); } for (int r = 0; r < 6; r++) { if (i == 0 && r < 5) printf("%c", ch); else if (i == 1) printf("%c", ch); else if (i < 4 && i > 0 && r > 3) { printf("%c", ch); } else if (i == 4 && r < 5) { printf("%c", ch); } else printf(" "); } printf("\n"); }} // Function to print the letter Qvoid q(void){ printf("\n"); for (int i = 0; i < 8; i++) { printf(" "); for (int o = 0; o < 8; o++) { if (o == i) printf("%c", ch); else if (i == 0 && (o <= 1 || o >= 6 - i)) printf(" "); else if (i == 1 && (o == 0 || o == 8 - i || (o < 6 && o > 1))) printf(" "); else if (i == 2 && (o == 1 || o == 8 - i || (o < 6 && o > 1))) printf(" "); else if ((i == 3 || i == 4 || i == 5) && (o > 0 && o < 7)) printf(" "); else if (i == 6 && (o == 0 || o == 8 + 5 - i || (o < 6 && o > 1))) printf(" "); else if (i == 7 && (o <= 1 || o >= 6 - i + 7)) printf(" "); else { printf("%c", ch); } } printf("\n"); }} // Function to print the letter Rvoid r(void){ printf("\n"); for (int i = 0; i < 8; i++) { printf(" "); { printf("%c%c", ch, ch); } for (int r = 0; r < 6; r++) { if (i == 0 && r < 5) printf("%c", ch); else if (i == 1) printf("%c", ch); else if (i < 4 && i > 0 && r > 3) { printf("%c", ch); } else if (i >= 4) { if (i == 4 && (r == 3 || r == 4)) { printf("%c", ch); } else if (r == i - 2 || r == i - 3) { printf("%c", ch); } else printf(" "); } else printf(" "); } printf("\n"); }} // Function to print the letter Svoid s(void){ printf("\n"); for (int i = 0; i < 8; i++) { printf(" "); for (int j = 0; j < 7; j++) { if (i == 0 && j > 0) { printf("%c", ch); } else if (i > 0 && i < 3 && j < 2) { printf("%c", ch); } else if (i == 3 && j > 0 && j < 6) { printf("%c", ch); } else if (i > 3 && i < 6 && j > 4) { printf("%c", ch); } else if (i == 6 && j < 6) { printf("%c", ch); } else printf(" "); } printf("\n"); }} // Function to print the letter Tvoid t(void){ printf("\n"); for (int i = 0; i < 8; i++) { printf(" "); for (int t = 0; t < 8; t++) { if (i < 2 && t < 8) { printf("%c", ch); } if (i > 1 && t < 3) printf(" "); if (i > 1 && t > 2 && t < 5) { printf("%c", ch); } if (i > 1 && t > 4) printf(" "); } printf("\n"); }} // Function to print the letter Uvoid u(void){ printf("\n"); for (int i = 0; i < 8; i++) { printf(" "); for (int h = 0; h < 8; h++) { if (i < 7 && (h < 2 || h > 5)) { printf("%c", ch); } else if (i == 7 && (h == 0 || h == 7)) printf(" "); else if (i > 5) { printf("%c", ch); } else printf(" "); } printf("\n"); }} // Function to print the letter Vvoid v(void){ printf("\n"); for (int i = 0; i < 8; i++) { printf(" "); for (int v = 0; v < 8; v++) if ((v == 0 || v == 7) && i < 4) { printf("%c", ch); } else if ((v == i - 4 || v == 11 - i) && i >= 4) { printf("%c", ch); } else printf(" "); printf("\n"); }} // Function to print the letter Wvoid w(void){ printf("\n"); for (int i = 0; i < 8; i++) { printf(" "); for (int j = 0; j < 8; j++) { if (j == 0 || j == 7) { printf("%c", ch); } else if (i > 3 && (j == 7 - i || j == i)) { printf("%c", ch); } else printf(" "); } printf("\n"); }} // Function to print the letter Xvoid x(void){ printf("\n"); for (int i = 0; i < 8; i++) { printf(" "); for (int m = 0; m < 8; m++) { if (i == m || m == 7 - i) { printf("%c", ch); } else printf(" "); } printf("\n"); }} // Function to print the letter Yvoid y(void){ printf("\n"); for (int i = 0; i < 8; i++) { printf(" "); for (int y = 0; y < 8; y++) { if (i < 4) { if (y == i || y == i + 1 || y == 6 - i || y == 7 - i) { printf("%c", ch); } else printf(" "); } else if (y == 3 || y == 4) { printf("%c", ch); } else printf(" "); } printf("\n"); }} // Function to print the letter Zvoid z(void){ printf("\n"); for (int i = 0; i < 8; i++) { printf(" "); for (int j = 0; j < 8; j++) { if (i == 0 || i == 7) { printf("%c", ch); } else if (j == 7 - i) { printf("%c", ch); } else printf(" "); } printf("\n"); }} // Function to print the required pattern// by taking out each characters in itvoid printPattern(char* str){ int in = 0; while (str[in]) { char ch = str[in]; if (ch < 95) ch = ch + 32; switch (ch) { case 'a': a(); break; case 'b': b(); break; case 'c': c(); break; case 'd': d(); break; case 'e': e(); break; case 'f': f(); break; case 'g': g(); break; case 'h': h(); break; case 'i': i(); break; case 'j': j(); break; case 'k': k(); break; case 'l': l(); break; case 'm': m(); break; case 'n': n(); break; case 'o': o(); break; case 'p': p(); break; case 'q': q(); break; case 'r': r(); break; case 's': s(); break; case 't': t(); break; case 'u': u(); break; case 'v': v(); break; case 'w': w(); break; case 'x': x(); break; case 'y': y(); break; case 'z': z(); break; default: break; } in++; }} // Driver codeint main(){ ch = '*'; char* str = "GFG"; printPattern(str); return 0;} // Java Program to print the Alphabets// of a Given Word using * patternclass GFG{ static char ch; // Function to print the letter Astatic void a(){ System.out.printf("\n"); for (int i = 0; i < 8; i++) { System.out.printf(" "); for (int a = 0; a < 8; a++) { if (i == 0 && (a == 0 || a == 7)) System.out.printf(" "); else if (a < 2 || a > 5) { System.out.printf("%c", ch); } else if (i < 2 || (i > 3 && i < 5)) { System.out.printf("%c", ch); } else System.out.printf(" "); } System.out.printf("\n"); }} // Function to print the letter Bstatic void b(){ System.out.printf("\n"); for (int i = 0; i < 9; i++) { System.out.printf(" %c%c", ch, ch); for (int r = 0; r < 6; r++) { if (i == 0 && r < 5) System.out.printf("%c", ch); else if (i == 1) System.out.printf("%c", ch); else if (i < 4 && i > 0 && r > 3) { System.out.printf("%c", ch); } else if (i == 4 && r < 5) { System.out.printf("%c", ch); } else if (i > 4 && i < 7 && r > 3) { System.out.printf("%c", ch); } else if (i == 7) { System.out.printf("%c", ch); } else if (i == 8 && r < 5) { System.out.printf("%c", ch); } else System.out.printf(" "); } System.out.printf("\n"); }} // Function to print the letter Cstatic void c(){ System.out.printf("\n"); for (int i = 0; i < 8; i++) { System.out.printf(" "); for (int o = 0; o < 8; o++) { if (i == 0 && (o <= 1)) System.out.printf(" "); else if (i == 1 && (o == 0 || o == 8 - i || (o > 1))) System.out.printf(" "); else if (i == 2 && (o == 1 || o == 8 - i || (o > 1))) System.out.printf(" "); else if ((i == 3 || i == 4 || i == 5) && (o > 0)) System.out.printf(" "); else if (i == 6 && (o == 0 || o == 8 + 5 - i || (o > 1))) System.out.printf(" "); else if (i == 7 && (o <= 1)) System.out.printf(" "); else { System.out.printf("%c", ch); } } System.out.printf("\n"); }} // Function to print the letter Dstatic void d(){ System.out.printf("\n"); for (int i = 0; i < 8; i++) { { System.out.printf(" %c", ch); } for (int o = 0; o < 8; o++) { if (i == 0 && (o >= 6 - i)) System.out.printf(" "); else if (i == 1 && (o == 0 || o == 8 - i || (o < 6))) System.out.printf(" "); else if (i == 2 && (o == 1 || o == 8 - i || (o < 6))) System.out.printf(" "); else if ((i == 3 || i == 4 || i == 5) && (o < 7)) System.out.printf(" "); else if (i == 6 && (o == 0 || o == 8 + 5 - i || (o < 6))) System.out.printf(" "); else if (i == 7 && (o >= 6 - i + 7)) System.out.printf(" "); else { System.out.printf("%c", ch); } } System.out.printf("\n"); }} // Function to print the letter Estatic void e(){ System.out.printf("\n"); for (int i = 0; i < 8; i++) { System.out.printf(" "); for (int j = 0; j < 7; j++) { if (i == 0) { System.out.printf("%c", ch); } else if (i > 0 && i < 3 && j < 2) { System.out.printf("%c", ch); } else if (i == 3 && j < 6) { System.out.printf("%c", ch); } else if (i > 3 && i < 6 && j < 2) { System.out.printf("%c", ch); } else if (i == 6) { System.out.printf("%c", ch); } else System.out.printf(" "); } System.out.printf("\n"); }} // Function to print the letter Fstatic void f(){ System.out.printf("\n"); for (int i = 0; i < 8; i++) { System.out.printf(" "); for (int j = 0; j < 7; j++) { if (i == 0) { System.out.printf("%c", ch); } else if (i > 0 && i < 3 && j < 2) { System.out.printf("%c", ch); } else if (i == 3 && j < 6) { System.out.printf("%c", ch); } else if (i > 3 && i < 7 && j < 2) { System.out.printf("%c", ch); } else System.out.printf(" "); } System.out.printf("\n"); }} // Function to print the letter Gstatic void g(){ System.out.printf("\n"); for (int i = 0; i < 8; i++) { System.out.printf(" "); for (int o = 0; o < 8; o++) { if (i == 4 && o > 3 || (o == 4 || o == 7) && i > 4) { System.out.printf("%c", ch); } else if (i == 0 && (o <= 1)) System.out.printf(" "); else if (i == 1 && (o == 0 || o == 8 - i || (o > 1))) System.out.printf(" "); else if (i == 2 && (o == 1 || o == 8 - i || (o > 1))) System.out.printf(" "); else if ((i == 3 || i == 4 || i == 5) && (o > 0)) System.out.printf(" "); else if (i == 6 && (o == 0 || (o > 1))) System.out.printf(" "); else if (i == 7 && (o <= 1 || o == 5 || o == 6)) System.out.printf(" "); else { System.out.printf("%c", ch); } } System.out.printf("\n"); }} // Function to print the letter Hstatic void h(){ System.out.printf("\n"); for (int i = 0; i < 8; i++) { System.out.printf(" "); for (int h = 0; h < 8; h++) { if (h < 2 || h > 5) { System.out.printf("%c", ch); } else if (i > 2 && i < 5) { System.out.printf("%c", ch); } else System.out.printf(" "); } System.out.printf("\n"); }} // Function to print the letter Istatic void i(){ System.out.printf("\n"); for (int i = 0; i < 8; i++) { System.out.printf(" "); for (int t = 0; t < 8; t++) { if ((i < 1 || i > 6) && t < 8) { System.out.printf("%c", ch); } else if (i > 0 && t < 3) System.out.printf(" "); else if (i > 0 && t > 2 && t < 5) { System.out.printf("%c", ch); } else if (i > 0 && t > 4) System.out.printf(" "); else { } } System.out.printf("\n"); }} // Function to print the letter Jstatic void j(){ System.out.printf("\n"); for (int i = 0; i < 8; i++) { System.out.printf(" "); for (int h = 0; h < 8; h++) { if (i < 1) { System.out.printf("%c", ch); } else if (i == 5 && h < 1) { System.out.printf("%c", ch); } else if (i < 7 && h > 5) { System.out.printf("%c", ch); } else if (i == 7 && (h == 0 || h == 7)) System.out.printf(" "); else if (i > 5) { System.out.printf("%c", ch); } else System.out.printf(" "); } System.out.printf("\n"); }} // Function to print the letter Kstatic void k(){ System.out.printf("\n"); for (int i = 0; i < 8; i++) { System.out.printf(" "); for (int k1 = 0; k1 < 7; k1++) { if (k1 < 2) { System.out.printf("%c", ch); } else if ((k1 >= 5 - i) && (k1 <= 6 - i)) { System.out.printf("%c", ch); } else if (i >= 4) { if (k1 == i - 2 || k1 == i - 1) { System.out.printf("%c", ch); } else System.out.printf(" "); } else System.out.printf(" "); } System.out.printf("\n"); }} // Function to print the letter Lstatic void l(){ System.out.printf("\n"); for (int i = 0; i < 8; i++) { System.out.printf(" "); { System.out.printf("%c%c", ch, ch); } if (i == 6) { { System.out.printf("%c%c", ch, ch); } { System.out.printf("%c%c", ch, ch); } System.out.printf("%c%c", ch, ch); } if (i == 7) { { System.out.printf("%c%c", ch, ch); } { System.out.printf("%c%c", ch, ch); } System.out.printf("%c%c", ch, ch); } System.out.printf("\n"); }} // Function to print the letter Mstatic void m(){ System.out.printf("\n"); for (int i = 0; i < 8; i++) { System.out.printf(" "); for (int j = 0; j < 8; j++) { if (j == 0 || j == 7) { System.out.printf("%c", ch); } else if (i < 4 && (j == 7 - i || j == i)) { System.out.printf("%c", ch); } else System.out.printf(" "); } System.out.printf("\n"); }} // Function to print the letter Nstatic void n(){ System.out.printf("\n"); for (int i = 0; i < 8; i++) { System.out.printf(" "); for (int n = 0; n < 8; n++) { if (n < 2 || n > 5) { System.out.printf("%c", ch); } else if (i == n - 1 || i == n + 1 || i == n) { System.out.printf("%c", ch); } else System.out.printf(" "); } System.out.printf("\n"); }} // Function to print the letter Ostatic void o(){ System.out.printf("\n"); for (int i = 0; i < 8; i++) { System.out.printf(" "); for (int o = 0; o < 8; o++) { if (i == 0 && (o <= 1 || o >= 6 - i)) System.out.printf(" "); else if (i == 1 && (o == 0 || o == 8 - i || (o < 6 && o > 1))) System.out.printf(" "); else if (i == 2 && (o == 1 || o == 8 - i || (o < 6 && o > 1))) System.out.printf(" "); else if ((i == 3 || i == 4 || i == 5) && (o > 0 && o < 7)) System.out.printf(" "); else if (i == 6 && (o == 0 || o == 8 + 5 - i || (o < 6 && o > 1))) System.out.printf(" "); else if (i == 7 && (o <= 1 || o >= 6 - i + 7)) System.out.printf(" "); else { System.out.printf("%c", ch); } } System.out.printf("\n"); }} // Function to print the letter Pstatic void p(){ System.out.printf("\n"); for (int i = 0; i < 8; i++) { System.out.printf(" "); { System.out.printf("%c%c", ch, ch); } for (int r = 0; r < 6; r++) { if (i == 0 && r < 5) System.out.printf("%c", ch); else if (i == 1) System.out.printf("%c", ch); else if (i < 4 && i > 0 && r > 3) { System.out.printf("%c", ch); } else if (i == 4 && r < 5) { System.out.printf("%c", ch); } else System.out.printf(" "); } System.out.printf("\n"); }} // Function to print the letter Qstatic void q(){ System.out.printf("\n"); for (int i = 0; i < 8; i++) { System.out.printf(" "); for (int o = 0; o < 8; o++) { if (o == i) System.out.printf("%c", ch); else if (i == 0 && (o <= 1 || o >= 6 - i)) System.out.printf(" "); else if (i == 1 && (o == 0 || o == 8 - i || (o < 6 && o > 1))) System.out.printf(" "); else if (i == 2 && (o == 1 || o == 8 - i || (o < 6 && o > 1))) System.out.printf(" "); else if ((i == 3 || i == 4 || i == 5) && (o > 0 && o < 7)) System.out.printf(" "); else if (i == 6 && (o == 0 || o == 8 + 5 - i || (o < 6 && o > 1))) System.out.printf(" "); else if (i == 7 && (o <= 1 || o >= 6 - i + 7)) System.out.printf(" "); else { System.out.printf("%c", ch); } } System.out.printf("\n"); }} // Function to print the letter Rstatic void r(){ System.out.printf("\n"); for (int i = 0; i < 8; i++) { System.out.printf(" "); { System.out.printf("%c%c", ch, ch); } for (int r = 0; r < 6; r++) { if (i == 0 && r < 5) System.out.printf("%c", ch); else if (i == 1) System.out.printf("%c", ch); else if (i < 4 && i > 0 && r > 3) { System.out.printf("%c", ch); } else if (i >= 4) { if (i == 4 && (r == 3 || r == 4)) { System.out.printf("%c", ch); } else if (r == i - 2 || r == i - 3) { System.out.printf("%c", ch); } else System.out.printf(" "); } else System.out.printf(" "); } System.out.printf("\n"); }} // Function to print the letter Sstatic void s(){ System.out.printf("\n"); for (int i = 0; i < 8; i++) { System.out.printf(" "); for (int j = 0; j < 7; j++) { if (i == 0 && j > 0) { System.out.printf("%c", ch); } else if (i > 0 && i < 3 && j < 2) { System.out.printf("%c", ch); } else if (i == 3 && j > 0 && j < 6) { System.out.printf("%c", ch); } else if (i > 3 && i < 6 && j > 4) { System.out.printf("%c", ch); } else if (i == 6 && j < 6) { System.out.printf("%c", ch); } else System.out.printf(" "); } System.out.printf("\n"); }} // Function to print the letter Tstatic void t(){ System.out.printf("\n"); for (int i = 0; i < 8; i++) { System.out.printf(" "); for (int t = 0; t < 8; t++) { if (i < 2 && t < 8) { System.out.printf("%c", ch); } if (i > 1 && t < 3) System.out.printf(" "); if (i > 1 && t > 2 && t < 5) { System.out.printf("%c", ch); } if (i > 1 && t > 4) System.out.printf(" "); } System.out.printf("\n"); }} // Function to print the letter Ustatic void u(){ System.out.printf("\n"); for (int i = 0; i < 8; i++) { System.out.printf(" "); for (int h = 0; h < 8; h++) { if (i < 7 && (h < 2 || h > 5)) { System.out.printf("%c", ch); } else if (i == 7 && (h == 0 || h == 7)) System.out.printf(" "); else if (i > 5) { System.out.printf("%c", ch); } else System.out.printf(" "); } System.out.printf("\n"); }} // Function to print the letter Vstatic void v(){ System.out.printf("\n"); for (int i = 0; i < 8; i++) { System.out.printf(" "); for (int v = 0; v < 8; v++) if ((v == 0 || v == 7) && i < 4) { System.out.printf("%c", ch); } else if ((v == i - 4 || v == 11 - i) && i >= 4) { System.out.printf("%c", ch); } else System.out.printf(" "); System.out.printf("\n"); }} // Function to print the letter Wstatic void w(){ System.out.printf("\n"); for (int i = 0; i < 8; i++) { System.out.printf(" "); for (int j = 0; j < 8; j++) { if (j == 0 || j == 7) { System.out.printf("%c", ch); } else if (i > 3 && (j == 7 - i || j == i)) { System.out.printf("%c", ch); } else System.out.printf(" "); } System.out.printf("\n"); }} // Function to print the letter Xstatic void x(){ System.out.printf("\n"); for (int i = 0; i < 8; i++) { System.out.printf(" "); for (int m = 0; m < 8; m++) { if (i == m || m == 7 - i) { System.out.printf("%c", ch); } else System.out.printf(" "); } System.out.printf("\n"); }} // Function to print the letter Ystatic void y(){ System.out.printf("\n"); for (int i = 0; i < 8; i++) { System.out.printf(" "); for (int y = 0; y < 8; y++) { if (i < 4) { if (y == i || y == i + 1 || y == 6 - i || y == 7 - i) { System.out.printf("%c", ch); } else System.out.printf(" "); } else if (y == 3 || y == 4) { System.out.printf("%c", ch); } else System.out.printf(" "); } System.out.printf("\n"); }} // Function to print the letter Zstatic void z(){ System.out.printf("\n"); for (int i = 0; i < 8; i++) { System.out.printf(" "); for (int j = 0; j < 8; j++) { if (i == 0 || i == 7) { System.out.printf("%c", ch); } else if (j == 7 - i) { System.out.printf("%c", ch); } else System.out.printf(" "); } System.out.printf("\n"); }} // Function to print the required pattern// by taking out each characters in itstatic void printPattern(char[] str){ int in = 0; while (in<str.length) { char ch = str[in]; if (ch < 95) ch = (char) (ch + 32); switch (ch) { case 'a': a(); break; case 'b': b(); break; case 'c': c(); break; case 'd': d(); break; case 'e': e(); break; case 'f': f(); break; case 'g': g(); break; case 'h': h(); break; case 'i': i(); break; case 'j': j(); break; case 'k': k(); break; case 'l': l(); break; case 'm': m(); break; case 'n': n(); break; case 'o': o(); break; case 'p': p(); break; case 'q': q(); break; case 'r': r(); break; case 's': s(); break; case 't': t(); break; case 'u': u(); break; case 'v': v(); break; case 'w': w(); break; case 'x': x(); break; case 'y': y(); break; case 'z': z(); break; default: break; } in++; }} // Driver codepublic static void main(String[] args){ ch = '*'; char[] str = "GFG".toCharArray(); printPattern(str); }} // This code contributed by Rajput-Ji // C# Program to print the Alphabets// of a Given Word using * patternusing System; class GFG{ static char ch; // Function to print the letter Astatic void a(){ Console.Write("\n"); for (int i = 0; i < 8; i++) { Console.Write(" "); for (int a = 0; a < 8; a++) { if (i == 0 && (a == 0 || a == 7)) Console.Write(" "); else if (a < 2 || a > 5) { Console.Write("{0}", ch); } else if (i < 2 || (i > 3 && i < 5)) { Console.Write("{0}", ch); } else Console.Write(" "); } Console.Write("\n"); }} // Function to print the letter Bstatic void b(){ Console.Write("\n"); for (int i = 0; i < 9; i++) { Console.Write(" {0}{0}", ch, ch); for (int r = 0; r < 6; r++) { if (i == 0 && r < 5) Console.Write("{0}", ch); else if (i == 1) Console.Write("{0}", ch); else if (i < 4 && i > 0 && r > 3) { Console.Write("{0}", ch); } else if (i == 4 && r < 5) { Console.Write("{0}", ch); } else if (i > 4 && i < 7 && r > 3) { Console.Write("{0}", ch); } else if (i == 7) { Console.Write("{0}", ch); } else if (i == 8 && r < 5) { Console.Write("{0}", ch); } else Console.Write(" "); } Console.Write("\n"); }} // Function to print the letter Cstatic void c(){ Console.Write("\n"); for (int i = 0; i < 8; i++) { Console.Write(" "); for (int o = 0; o < 8; o++) { if (i == 0 && (o <= 1)) Console.Write(" "); else if (i == 1 && (o == 0 || o == 8 - i || (o > 1))) Console.Write(" "); else if (i == 2 && (o == 1 || o == 8 - i || (o > 1))) Console.Write(" "); else if ((i == 3 || i == 4 || i == 5) && (o > 0)) Console.Write(" "); else if (i == 6 && (o == 0 || o == 8 + 5 - i || (o > 1))) Console.Write(" "); else if (i == 7 && (o <= 1)) Console.Write(" "); else { Console.Write("{0}", ch); } } Console.Write("\n"); }} // Function to print the letter Dstatic void d(){ Console.Write("\n"); for (int i = 0; i < 8; i++) { { Console.Write(" {0}", ch); } for (int o = 0; o < 8; o++) { if (i == 0 && (o >= 6 - i)) Console.Write(" "); else if (i == 1 && (o == 0 || o == 8 - i || (o < 6))) Console.Write(" "); else if (i == 2 && (o == 1 || o == 8 - i || (o < 6))) Console.Write(" "); else if ((i == 3 || i == 4 || i == 5) && (o < 7)) Console.Write(" "); else if (i == 6 && (o == 0 || o == 8 + 5 - i || (o < 6))) Console.Write(" "); else if (i == 7 && (o >= 6 - i + 7)) Console.Write(" "); else { Console.Write("{0}", ch); } } Console.Write("\n"); }} // Function to print the letter Estatic void e(){ Console.Write("\n"); for (int i = 0; i < 8; i++) { Console.Write(" "); for (int j = 0; j < 7; j++) { if (i == 0) { Console.Write("{0}", ch); } else if (i > 0 && i < 3 && j < 2) { Console.Write("{0}", ch); } else if (i == 3 && j < 6) { Console.Write("{0}", ch); } else if (i > 3 && i < 6 && j < 2) { Console.Write("{0}", ch); } else if (i == 6) { Console.Write("{0}", ch); } else Console.Write(" "); } Console.Write("\n"); }} // Function to print the letter Fstatic void f(){ Console.Write("\n"); for (int i = 0; i < 8; i++) { Console.Write(" "); for (int j = 0; j < 7; j++) { if (i == 0) { Console.Write("{0}", ch); } else if (i > 0 && i < 3 && j < 2) { Console.Write("{0}", ch); } else if (i == 3 && j < 6) { Console.Write("{0}", ch); } else if (i > 3 && i < 7 && j < 2) { Console.Write("{0}", ch); } else Console.Write(" "); } Console.Write("\n"); }} // Function to print the letter Gstatic void g(){ Console.Write("\n"); for (int i = 0; i < 8; i++) { Console.Write(" "); for (int o = 0; o < 8; o++) { if (i == 4 && o > 3 || (o == 4 || o == 7) && i > 4) { Console.Write("{0}", ch); } else if (i == 0 && (o <= 1)) Console.Write(" "); else if (i == 1 && (o == 0 || o == 8 - i || (o > 1))) Console.Write(" "); else if (i == 2 && (o == 1 || o == 8 - i || (o > 1))) Console.Write(" "); else if ((i == 3 || i == 4 || i == 5) && (o > 0)) Console.Write(" "); else if (i == 6 && (o == 0 || (o > 1))) Console.Write(" "); else if (i == 7 && (o <= 1 || o == 5 || o == 6)) Console.Write(" "); else { Console.Write("{0}", ch); } } Console.Write("\n"); }} // Function to print the letter Hstatic void h(){ Console.Write("\n"); for (int i = 0; i < 8; i++) { Console.Write(" "); for (int h = 0; h < 8; h++) { if (h < 2 || h > 5) { Console.Write("{0}", ch); } else if (i > 2 && i < 5) { Console.Write("{0}", ch); } else Console.Write(" "); } Console.Write("\n"); }} // Function to print the letter Istatic void i(){ Console.Write("\n"); for (int i = 0; i < 8; i++) { Console.Write(" "); for (int t = 0; t < 8; t++) { if ((i < 1 || i > 6) && t < 8) { Console.Write("{0}", ch); } else if (i > 0 && t < 3) Console.Write(" "); else if (i > 0 && t > 2 && t < 5) { Console.Write("{0}", ch); } else if (i > 0 && t > 4) Console.Write(" "); else { } } Console.Write("\n"); }} // Function to print the letter Jstatic void j(){ Console.Write("\n"); for (int i = 0; i < 8; i++) { Console.Write(" "); for (int h = 0; h < 8; h++) { if (i < 1) { Console.Write("{0}", ch); } else if (i == 5 && h < 1) { Console.Write("{0}", ch); } else if (i < 7 && h > 5) { Console.Write("{0}", ch); } else if (i == 7 && (h == 0 || h == 7)) Console.Write(" "); else if (i > 5) { Console.Write("{0}", ch); } else Console.Write(" "); } Console.Write("\n"); }} // Function to print the letter Kstatic void k(){ Console.Write("\n"); for (int i = 0; i < 8; i++) { Console.Write(" "); for (int k1 = 0; k1 < 7; k1++) { if (k1 < 2) { Console.Write("{0}", ch); } else if ((k1 >= 5 - i) && (k1 <= 6 - i)) { Console.Write("{0}", ch); } else if (i >= 4) { if (k1 == i - 2 || k1 == i - 1) { Console.Write("{0}", ch); } else Console.Write(" "); } else Console.Write(" "); } Console.Write("\n"); }} // Function to print the letter Lstatic void l(){ Console.Write("\n"); for (int i = 0; i < 8; i++) { Console.Write(" "); { Console.Write("{0}{0}", ch, ch); } if (i == 6) { { Console.Write("{0}{0}", ch, ch); } { Console.Write("{0}{0}", ch, ch); } Console.Write("{0}{0}", ch, ch); } if (i == 7) { { Console.Write("{0}{0}", ch, ch); } { Console.Write("{0}{0}", ch, ch); } Console.Write("{0}{0}", ch, ch); } Console.Write("\n"); }} // Function to print the letter Mstatic void m(){ Console.Write("\n"); for (int i = 0; i < 8; i++) { Console.Write(" "); for (int j = 0; j < 8; j++) { if (j == 0 || j == 7) { Console.Write("{0}", ch); } else if (i < 4 && (j == 7 - i || j == i)) { Console.Write("{0}", ch); } else Console.Write(" "); } Console.Write("\n"); }} // Function to print the letter Nstatic void n(){ Console.Write("\n"); for (int i = 0; i < 8; i++) { Console.Write(" "); for (int n = 0; n < 8; n++) { if (n < 2 || n > 5) { Console.Write("{0}", ch); } else if (i == n - 1 || i == n + 1 || i == n) { Console.Write("{0}", ch); } else Console.Write(" "); } Console.Write("\n"); }} // Function to print the letter Ostatic void o(){ Console.Write("\n"); for (int i = 0; i < 8; i++) { Console.Write(" "); for (int o = 0; o < 8; o++) { if (i == 0 && (o <= 1 || o >= 6 - i)) Console.Write(" "); else if (i == 1 && (o == 0 || o == 8 - i || (o < 6 && o > 1))) Console.Write(" "); else if (i == 2 && (o == 1 || o == 8 - i || (o < 6 && o > 1))) Console.Write(" "); else if ((i == 3 || i == 4 || i == 5) && (o > 0 && o < 7)) Console.Write(" "); else if (i == 6 && (o == 0 || o == 8 + 5 - i || (o < 6 && o > 1))) Console.Write(" "); else if (i == 7 && (o <= 1 || o >= 6 - i + 7)) Console.Write(" "); else { Console.Write("{0}", ch); } } Console.Write("\n"); }} // Function to print the letter Pstatic void p(){ Console.Write("\n"); for (int i = 0; i < 8; i++) { Console.Write(" "); { Console.Write("{0}{0}", ch, ch); } for (int r = 0; r < 6; r++) { if (i == 0 && r < 5) Console.Write("{0}", ch); else if (i == 1) Console.Write("{0}", ch); else if (i < 4 && i > 0 && r > 3) { Console.Write("{0}", ch); } else if (i == 4 && r < 5) { Console.Write("{0}", ch); } else Console.Write(" "); } Console.Write("\n"); }} // Function to print the letter Qstatic void q(){ Console.Write("\n"); for (int i = 0; i < 8; i++) { Console.Write(" "); for (int o = 0; o < 8; o++) { if (o == i) Console.Write("{0}", ch); else if (i == 0 && (o <= 1 || o >= 6 - i)) Console.Write(" "); else if (i == 1 && (o == 0 || o == 8 - i || (o < 6 && o > 1))) Console.Write(" "); else if (i == 2 && (o == 1 || o == 8 - i || (o < 6 && o > 1))) Console.Write(" "); else if ((i == 3 || i == 4 || i == 5) && (o > 0 && o < 7)) Console.Write(" "); else if (i == 6 && (o == 0 || o == 8 + 5 - i || (o < 6 && o > 1))) Console.Write(" "); else if (i == 7 && (o <= 1 || o >= 6 - i + 7)) Console.Write(" "); else { Console.Write("{0}", ch); } } Console.Write("\n"); }} // Function to print the letter Rstatic void r(){ Console.Write("\n"); for (int i = 0; i < 8; i++) { Console.Write(" "); { Console.Write("{0}{0}", ch, ch); } for (int r = 0; r < 6; r++) { if (i == 0 && r < 5) Console.Write("{0}", ch); else if (i == 1) Console.Write("{0}", ch); else if (i < 4 && i > 0 && r > 3) { Console.Write("{0}", ch); } else if (i >= 4) { if (i == 4 && (r == 3 || r == 4)) { Console.Write("{0}", ch); } else if (r == i - 2 || r == i - 3) { Console.Write("{0}", ch); } else Console.Write(" "); } else Console.Write(" "); } Console.Write("\n"); }} // Function to print the letter Sstatic void s(){ Console.Write("\n"); for (int i = 0; i < 8; i++) { Console.Write(" "); for (int j = 0; j < 7; j++) { if (i == 0 && j > 0) { Console.Write("{0}", ch); } else if (i > 0 && i < 3 && j < 2) { Console.Write("{0}", ch); } else if (i == 3 && j > 0 && j < 6) { Console.Write("{0}", ch); } else if (i > 3 && i < 6 && j > 4) { Console.Write("{0}", ch); } else if (i == 6 && j < 6) { Console.Write("{0}", ch); } else Console.Write(" "); } Console.Write("\n"); }} // Function to print the letter Tstatic void t(){ Console.Write("\n"); for (int i = 0; i < 8; i++) { Console.Write(" "); for (int t = 0; t < 8; t++) { if (i < 2 && t < 8) { Console.Write("{0}", ch); } if (i > 1 && t < 3) Console.Write(" "); if (i > 1 && t > 2 && t < 5) { Console.Write("{0}", ch); } if (i > 1 && t > 4) Console.Write(" "); } Console.Write("\n"); }} // Function to print the letter Ustatic void u(){ Console.Write("\n"); for (int i = 0; i < 8; i++) { Console.Write(" "); for (int h = 0; h < 8; h++) { if (i < 7 && (h < 2 || h > 5)) { Console.Write("{0}", ch); } else if (i == 7 && (h == 0 || h == 7)) Console.Write(" "); else if (i > 5) { Console.Write("{0}", ch); } else Console.Write(" "); } Console.Write("\n"); }} // Function to print the letter Vstatic void v(){ Console.Write("\n"); for (int i = 0; i < 8; i++) { Console.Write(" "); for (int v = 0; v < 8; v++) if ((v == 0 || v == 7) && i < 4) { Console.Write("{0}", ch); } else if ((v == i - 4 || v == 11 - i) && i >= 4) { Console.Write("{0}", ch); } else Console.Write(" "); Console.Write("\n"); }} // Function to print the letter Wstatic void w(){ Console.Write("\n"); for (int i = 0; i < 8; i++) { Console.Write(" "); for (int j = 0; j < 8; j++) { if (j == 0 || j == 7) { Console.Write("{0}", ch); } else if (i > 3 && (j == 7 - i || j == i)) { Console.Write("{0}", ch); } else Console.Write(" "); } Console.Write("\n"); }} // Function to print the letter Xstatic void x(){ Console.Write("\n"); for (int i = 0; i < 8; i++) { Console.Write(" "); for (int m = 0; m < 8; m++) { if (i == m || m == 7 - i) { Console.Write("{0}", ch); } else Console.Write(" "); } Console.Write("\n"); }} // Function to print the letter Ystatic void y(){ Console.Write("\n"); for (int i = 0; i < 8; i++) { Console.Write(" "); for (int y = 0; y < 8; y++) { if (i < 4) { if (y == i || y == i + 1 || y == 6 - i || y == 7 - i) { Console.Write("{0}", ch); } else Console.Write(" "); } else if (y == 3 || y == 4) { Console.Write("{0}", ch); } else Console.Write(" "); } Console.Write("\n"); }} // Function to print the letter Zstatic void z(){ Console.Write("\n"); for (int i = 0; i < 8; i++) { Console.Write(" "); for (int j = 0; j < 8; j++) { if (i == 0 || i == 7) { Console.Write("{0}", ch); } else if (j == 7 - i) { Console.Write("{0}", ch); } else Console.Write(" "); } Console.Write("\n"); }} // Function to print the required pattern// by taking out each characters in itstatic void printPattern(char[] str){ int iN = 0; while (iN<str.Length) { char ch = str[iN]; if (ch < 95) ch = (char) (ch + 32); switch (ch) { case 'a': a(); break; case 'b': b(); break; case 'c': c(); break; case 'd': d(); break; case 'e': e(); break; case 'f': f(); break; case 'g': g(); break; case 'h': h(); break; case 'i': i(); break; case 'j': j(); break; case 'k': k(); break; case 'l': l(); break; case 'm': m(); break; case 'n': n(); break; case 'o': o(); break; case 'p': p(); break; case 'q': q(); break; case 'r': r(); break; case 's': s(); break; case 't': t(); break; case 'u': u(); break; case 'v': v(); break; case 'w': w(); break; case 'x': x(); break; case 'y': y(); break; case 'z': z(); break; default: break; } iN++; }} // Driver codepublic static void Main(String[] args){ ch = '*'; char[] str = "GFG".ToCharArray(); printPattern(str); }}// This code is contributed by 29AjayKumar ****** * * * * **** * * * * * * *** * ******* ** ** ****** ** ** ** ****** * * * * **** * * * * * * *** * Rajput-Ji 29AjayKumar SHUBHAMSINGH10 pattern-printing C Programs C++ Programs pattern-printing Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. C Program to read contents of Whole File Producer Consumer Problem in C Difference between break and continue statement in C C Hello World Program Exit codes in C/C++ with Examples Sorting a Map by value in C++ STL Shallow Copy and Deep Copy in C++ C++ program for hashing with chaining C++ Program to check if a given String is Palindrome or not delete keyword in C++
[ { "code": null, "e": 54, "s": 26, "text": "\n15 Jun, 2021" }, { "code": null, "e": 148, "s": 54, "text": "Given a word str, the task is to print the alphabets of this word using * pattern.Examples: " }, { "code": null, "e": 401, "s": 148, "text": "Input: GFG\nOutput:\n ******\n * \n * \n * \n * ****\n * * *\n * * *\n *** *\n\n *******\n ** \n ** \n ****** \n ** \n ** \n ** \n \n\n ******\n * \n * \n * \n * ****\n * * *\n * * *\n *** *" }, { "code": null, "e": 558, "s": 401, "text": "Approach: A simple implementation is to form the pattern for each letter A-Z and call them as functions.Below is the implementation of the above approach: " }, { "code": null, "e": 562, "s": 558, "text": "C++" }, { "code": null, "e": 564, "s": 562, "text": "C" }, { "code": null, "e": 569, "s": 564, "text": "Java" }, { "code": null, "e": 572, "s": 569, "text": "C#" }, { "code": "// C++ Program to print the Alphabets// of a Given Word using * pattern#include <iostream>using namespace std;char ch; // Function to print the letter Avoid a(void){ cout << endl; for (int i = 0; i < 8; i++) { cout << \" \"; for (int a = 0; a < 8; a++) { if (i == 0 && (a == 0 || a == 7)) cout << \" \"; else if (a < 2 || a > 5) { cout << ch; } else if (i < 2 || (i > 3 && i < 5)) { cout << ch; } else cout << \" \"; } cout << endl; }} // Function to print the letter Bvoid b(void){ cout << endl; for (int i = 0; i < 9; i++) { cout << ch << ch; for (int r = 0; r < 6; r++) { if (i == 0 && r < 5) cout << ch; else if (i == 1) cout << ch; else if (i < 4 && i > 0 && r > 3) { cout << ch; } else if (i == 4 && r < 5) { cout << ch; } else if (i > 4 && i < 7 && r > 3) { cout << ch; } else if (i == 7) { cout << ch; } else if (i == 8 && r < 5) { cout << ch; } else cout << \" \"; } cout << endl; }} // Function to print the letter Cvoid c(void){ cout << endl; for (int i = 0; i < 8; i++) { cout << \" \"; for (int o = 0; o < 8; o++) { if (i == 0 && (o <= 1)) cout << \" \"; else if (i == 1 && (o == 0 || o == 8 - i || (o > 1))) cout << \" \"; else if (i == 2 && (o == 1 || o == 8 - i || (o > 1))) cout << \" \"; else if ((i == 3 || i == 4 || i == 5) && (o > 0)) cout << \" \"; else if (i == 6 && (o == 0 || o == 8 + 5 - i || (o > 1))) cout << \" \"; else if (i == 7 && (o <= 1)) cout << \" \"; else { cout << ch; } } cout << endl; }} // Function to print the letter Dvoid d(void){ cout << endl; for (int i = 0; i < 8; i++) { { cout << \" \"<< ch; } for (int o = 0; o < 8; o++) { if (i == 0 && (o >= 6 - i)) cout << \" \"; else if (i == 1 && (o == 0 || o == 8 - i || (o < 6))) cout << \" \"; else if (i == 2 && (o == 1 || o == 8 - i || (o < 6))) cout << \" \"; else if ((i == 3 || i == 4 || i == 5) && (o < 7)) cout << \" \"; else if (i == 6 && (o == 0 || o == 8 + 5 - i || (o < 6))) cout << \" \"; else if (i == 7 && (o >= 6 - i + 7)) cout << \" \"; else { cout << ch; } } cout << endl; }} // Function to print the letter Evoid e(void){ cout << endl; for (int i = 0; i < 8; i++) { cout << \" \"; for (int j = 0; j < 7; j++) { if (i == 0) { cout << ch; } else if (i > 0 && i < 3 && j < 2) { cout << ch; } else if (i == 3 && j < 6) { cout << ch; } else if (i > 3 && i < 6 && j < 2) { cout << ch; } else if (i == 6) { cout << ch; } else cout << \" \"; } cout << endl; }} // Function to print the letter Fvoid f(void){ cout << endl; for (int i = 0; i < 8; i++) { cout << \" \"; for (int j = 0; j < 7; j++) { if (i == 0) { cout << ch; } else if (i > 0 && i < 3 && j < 2) { cout << ch; } else if (i == 3 && j < 6) { cout << ch; } else if (i > 3 && i < 7 && j < 2) { cout << ch; } else cout << \" \"; } cout << endl; }} // Function to print the letter Gvoid g(void){ cout << endl; for (int i = 0; i < 8; i++) { cout << \" \"; for (int o = 0; o < 8; o++) { if (i == 4 && o > 3 || (o == 4 || o == 7) && i > 4) { cout << ch; } else if (i == 0 && (o <= 1)) cout << \" \"; else if (i == 1 && (o == 0 || o == 8 - i || (o > 1))) cout << \" \"; else if (i == 2 && (o == 1 || o == 8 - i || (o > 1))) cout << \" \"; else if ((i == 3 || i == 4 || i == 5) && (o > 0)) cout << \" \"; else if (i == 6 && (o == 0 || (o > 1))) cout << \" \"; else if (i == 7 && (o <= 1 || o == 5 || o == 6)) cout << \" \"; else { cout << ch; } } cout << endl; }} // Function to print the letter Hvoid h(void){ cout << endl; for (int i = 0; i < 8; i++) { cout << \" \"; for (int h = 0; h < 8; h++) { if (h < 2 || h > 5) { cout << ch; } else if (i > 2 && i < 5) { cout << ch; } else cout << \" \"; } cout << endl; }} // Function to print the letter Ivoid i(void){ cout << endl; for (int i = 0; i < 8; i++) { cout << \" \"; for (int t = 0; t < 8; t++) { if ((i < 1 || i > 6) && t < 8) { cout << ch; } else if (i > 0 && t < 3) cout << \" \"; else if (i > 0 && t > 2 && t < 5) { cout << ch; } else if (i > 0 && t > 4) cout << \" \"; else { } } cout << endl; }} // Function to print the letter Jvoid j(void){ cout << endl; for (int i = 0; i < 8; i++) { cout << \" \"; for (int h = 0; h < 8; h++) { if (i < 1) { cout << ch; } else if (i == 5 && h < 1) { cout << ch; } else if (i < 7 && h > 5) { cout << ch; } else if (i == 7 && (h == 0 || h == 7)) cout << \" \"; else if (i > 5) { cout << ch; } else cout << \" \"; } cout << endl; }} // Function to print the letter Kvoid k(void){ cout << endl; for (int i = 0; i < 8; i++) { cout << \" \"; for (int k1 = 0; k1 < 7; k1++) { if (k1 < 2) { cout << ch; } else if ((k1 >= 5 - i) && (k1 <= 6 - i)) { cout << ch; } else if (i >= 4) { if (k1 == i - 2 || k1 == i - 1) { cout << ch; } else cout << \" \"; } else cout << \" \"; } cout << endl; }} // Function to print the letter Lvoid l(void){ cout << endl; for (int i = 0; i < 8; i++) { cout << \" \"; { cout << ch << ch; } if (i == 6) { { cout << ch << ch; } { cout << ch << ch; } cout << ch << ch; } if (i == 7) { { cout << ch << ch; } { cout << ch << ch; } cout << ch << ch; } cout << endl; }} // Function to print the letter Mvoid m(void){ cout << endl; for (int i = 0; i < 8; i++) { cout << \" \"; for (int j = 0; j < 8; j++) { if (j == 0 || j == 7) { cout << ch; } else if (i < 4 && (j == 7 - i || j == i)) { cout << ch; } else cout << \" \"; } cout << endl; }} // Function to print the letter Nvoid n(void){ cout << endl; for (int i = 0; i < 8; i++) { cout << \" \"; for (int n = 0; n < 8; n++) { if (n < 2 || n > 5) { cout << ch; } else if (i == n - 1 || i == n + 1 || i == n) { cout << ch; } else cout << \" \"; } cout << endl; }} // Function to print the letter Ovoid o(void){ cout << endl; for (int i = 0; i < 8; i++) { cout << \" \"; for (int o = 0; o < 8; o++) { if (i == 0 && (o <= 1 || o >= 6 - i)) cout << \" \"; else if (i == 1 && (o == 0 || o == 8 - i || (o < 6 && o > 1))) cout << \" \"; else if (i == 2 && (o == 1 || o == 8 - i || (o < 6 && o > 1))) cout << \" \"; else if ((i == 3 || i == 4 || i == 5) && (o > 0 && o < 7)) cout << \" \"; else if (i == 6 && (o == 0 || o == 8 + 5 - i || (o < 6 && o > 1))) cout << \" \"; else if (i == 7 && (o <= 1 || o >= 6 - i + 7)) cout << \" \"; else { cout << ch; } } cout << endl; }} // Function to print the letter Pvoid p(void){ cout << endl; for (int i = 0; i < 8; i++) { cout << \" \"; { cout << ch << ch; } for (int r = 0; r < 6; r++) { if (i == 0 && r < 5) cout << ch; else if (i == 1) cout << ch; else if (i < 4 && i > 0 && r > 3) { cout << ch; } else if (i == 4 && r < 5) { cout << ch; } else cout << \" \"; } cout << endl; }} // Function to print the letter Qvoid q(void){ cout << endl; for (int i = 0; i < 8; i++) { cout << \" \"; for (int o = 0; o < 8; o++) { if (o == i) cout << ch; else if (i == 0 && (o <= 1 || o >= 6 - i)) cout << \" \"; else if (i == 1 && (o == 0 || o == 8 - i || (o < 6 && o > 1))) cout << \" \"; else if (i == 2 && (o == 1 || o == 8 - i || (o < 6 && o > 1))) cout << \" \"; else if ((i == 3 || i == 4 || i == 5) && (o > 0 && o < 7)) cout << \" \"; else if (i == 6 && (o == 0 || o == 8 + 5 - i || (o < 6 && o > 1))) cout << \" \"; else if (i == 7 && (o <= 1 || o >= 6 - i + 7)) cout << \" \"; else { cout << ch; } } cout << endl; }} // Function to print the letter Rvoid r(void){ cout << endl; for (int i = 0; i < 8; i++) { cout << \" \"; { cout << ch << ch; } for (int r = 0; r < 6; r++) { if (i == 0 && r < 5) cout << ch; else if (i == 1) cout << ch; else if (i < 4 && i > 0 && r > 3) { cout << ch; } else if (i >= 4) { if (i == 4 && (r == 3 || r == 4)) { cout << ch; } else if (r == i - 2 || r == i - 3) { cout << ch; } else cout << \" \"; } else cout << \" \"; } cout << endl; }} // Function to print the letter Svoid s(void){ cout << endl; for (int i = 0; i < 8; i++) { cout << \" \"; for (int j = 0; j < 7; j++) { if (i == 0 && j > 0) { cout << ch; } else if (i > 0 && i < 3 && j < 2) { cout << ch; } else if (i == 3 && j > 0 && j < 6) { cout << ch; } else if (i > 3 && i < 6 && j > 4) { cout << ch; } else if (i == 6 && j < 6) { cout << ch; } else cout << \" \"; } cout << endl; }} // Function to print the letter Tvoid t(void){ cout << endl; for (int i = 0; i < 8; i++) { cout << \" \"; for (int t = 0; t < 8; t++) { if (i < 2 && t < 8) { cout << ch; } if (i > 1 && t < 3) cout << \" \"; if (i > 1 && t > 2 && t < 5) { cout << ch; } if (i > 1 && t > 4) cout << \" \"; } cout << endl; }} // Function to print the letter Uvoid u(void){ cout << endl; for (int i = 0; i < 8; i++) { cout << \" \"; for (int h = 0; h < 8; h++) { if (i < 7 && (h < 2 || h > 5)) { cout << ch; } else if (i == 7 && (h == 0 || h == 7)) cout << \" \"; else if (i > 5) { cout << ch; } else cout << \" \"; } cout << endl; }} // Function to print the letter Vvoid v(void){ cout << endl; for (int i = 0; i < 8; i++) { cout << \" \"; for (int v = 0; v < 8; v++) if ((v == 0 || v == 7) && i < 4) { cout << ch; } else if ((v == i - 4 || v == 11 - i) && i >= 4) { cout << ch; } else cout << \" \"; cout << endl; }} // Function to print the letter Wvoid w(void){ cout << endl; for (int i = 0; i < 8; i++) { cout << \" \"; for (int j = 0; j < 8; j++) { if (j == 0 || j == 7) { cout << ch; } else if (i > 3 && (j == 7 - i || j == i)) { cout << ch; } else cout << \" \"; } cout << endl; }} // Function to print the letter Xvoid x(void){ cout << endl; for (int i = 0; i < 8; i++) { cout << \" \"; for (int m = 0; m < 8; m++) { if (i == m || m == 7 - i) { cout << ch; } else cout << \" \"; } cout << endl; }} // Function to print the letter Yvoid y(void){ cout << endl; for (int i = 0; i < 8; i++) { cout << \" \"; for (int y = 0; y < 8; y++) { if (i < 4) { if (y == i || y == i + 1 || y == 6 - i || y == 7 - i) { cout << ch; } else cout << \" \"; } else if (y == 3 || y == 4) { cout << ch; } else cout << \" \"; } cout << endl; }} // Function to print the letter Zvoid z(void){ cout << endl; for (int i = 0; i < 8; i++) { cout << \" \"; for (int j = 0; j < 8; j++) { if (i == 0 || i == 7) { cout << ch; } else if (j == 7 - i) { cout << ch; } else cout << \" \"; } cout << endl; }} // Function to print the required pattern// by taking out each characters in itvoid printPattern(char* str){ int in = 0; while (str[in]) { char ch = str[in]; if (ch < 95) ch = ch + 32; switch (ch) { case 'a': a(); break; case 'b': b(); break; case 'c': c(); break; case 'd': d(); break; case 'e': e(); break; case 'f': f(); break; case 'g': g(); break; case 'h': h(); break; case 'i': i(); break; case 'j': j(); break; case 'k': k(); break; case 'l': l(); break; case 'm': m(); break; case 'n': n(); break; case 'o': o(); break; case 'p': p(); break; case 'q': q(); break; case 'r': r(); break; case 's': s(); break; case 't': t(); break; case 'u': u(); break; case 'v': v(); break; case 'w': w(); break; case 'x': x(); break; case 'y': y(); break; case 'z': z(); break; default: break; } in++; }} // Driver codeint main(){ ch = '*'; char *str = \"GFG\"; printPattern(str); return 0;} // This code is contributed by shubhamsingh", "e": 18838, "s": 572, "text": null }, { "code": "// C Program to print the Alphabets// of a Given Word using * pattern #include <stdio.h>#include <string.h> char ch; // Function to print the letter Avoid a(void){ printf(\"\\n\"); for (int i = 0; i < 8; i++) { printf(\" \"); for (int a = 0; a < 8; a++) { if (i == 0 && (a == 0 || a == 7)) printf(\" \"); else if (a < 2 || a > 5) { printf(\"%c\", ch); } else if (i < 2 || (i > 3 && i < 5)) { printf(\"%c\", ch); } else printf(\" \"); } printf(\"\\n\"); }} // Function to print the letter Bvoid b(void){ printf(\"\\n\"); for (int i = 0; i < 9; i++) { printf(\" %c%c\", ch, ch); for (int r = 0; r < 6; r++) { if (i == 0 && r < 5) printf(\"%c\", ch); else if (i == 1) printf(\"%c\", ch); else if (i < 4 && i > 0 && r > 3) { printf(\"%c\", ch); } else if (i == 4 && r < 5) { printf(\"%c\", ch); } else if (i > 4 && i < 7 && r > 3) { printf(\"%c\", ch); } else if (i == 7) { printf(\"%c\", ch); } else if (i == 8 && r < 5) { printf(\"%c\", ch); } else printf(\" \"); } printf(\"\\n\"); }} // Function to print the letter Cvoid c(void){ printf(\"\\n\"); for (int i = 0; i < 8; i++) { printf(\" \"); for (int o = 0; o < 8; o++) { if (i == 0 && (o <= 1)) printf(\" \"); else if (i == 1 && (o == 0 || o == 8 - i || (o > 1))) printf(\" \"); else if (i == 2 && (o == 1 || o == 8 - i || (o > 1))) printf(\" \"); else if ((i == 3 || i == 4 || i == 5) && (o > 0)) printf(\" \"); else if (i == 6 && (o == 0 || o == 8 + 5 - i || (o > 1))) printf(\" \"); else if (i == 7 && (o <= 1)) printf(\" \"); else { printf(\"%c\", ch); } } printf(\"\\n\"); }} // Function to print the letter Dvoid d(void){ printf(\"\\n\"); for (int i = 0; i < 8; i++) { { printf(\" %c\", ch); } for (int o = 0; o < 8; o++) { if (i == 0 && (o >= 6 - i)) printf(\" \"); else if (i == 1 && (o == 0 || o == 8 - i || (o < 6))) printf(\" \"); else if (i == 2 && (o == 1 || o == 8 - i || (o < 6))) printf(\" \"); else if ((i == 3 || i == 4 || i == 5) && (o < 7)) printf(\" \"); else if (i == 6 && (o == 0 || o == 8 + 5 - i || (o < 6))) printf(\" \"); else if (i == 7 && (o >= 6 - i + 7)) printf(\" \"); else { printf(\"%c\", ch); } } printf(\"\\n\"); }} // Function to print the letter Evoid e(void){ printf(\"\\n\"); for (int i = 0; i < 8; i++) { printf(\" \"); for (int j = 0; j < 7; j++) { if (i == 0) { printf(\"%c\", ch); } else if (i > 0 && i < 3 && j < 2) { printf(\"%c\", ch); } else if (i == 3 && j < 6) { printf(\"%c\", ch); } else if (i > 3 && i < 6 && j < 2) { printf(\"%c\", ch); } else if (i == 6) { printf(\"%c\", ch); } else printf(\" \"); } printf(\"\\n\"); }} // Function to print the letter Fvoid f(void){ printf(\"\\n\"); for (int i = 0; i < 8; i++) { printf(\" \"); for (int j = 0; j < 7; j++) { if (i == 0) { printf(\"%c\", ch); } else if (i > 0 && i < 3 && j < 2) { printf(\"%c\", ch); } else if (i == 3 && j < 6) { printf(\"%c\", ch); } else if (i > 3 && i < 7 && j < 2) { printf(\"%c\", ch); } else printf(\" \"); } printf(\"\\n\"); }} // Function to print the letter Gvoid g(void){ printf(\"\\n\"); for (int i = 0; i < 8; i++) { printf(\" \"); for (int o = 0; o < 8; o++) { if (i == 4 && o > 3 || (o == 4 || o == 7) && i > 4) { printf(\"%c\", ch); } else if (i == 0 && (o <= 1)) printf(\" \"); else if (i == 1 && (o == 0 || o == 8 - i || (o > 1))) printf(\" \"); else if (i == 2 && (o == 1 || o == 8 - i || (o > 1))) printf(\" \"); else if ((i == 3 || i == 4 || i == 5) && (o > 0)) printf(\" \"); else if (i == 6 && (o == 0 || (o > 1))) printf(\" \"); else if (i == 7 && (o <= 1 || o == 5 || o == 6)) printf(\" \"); else { printf(\"%c\", ch); } } printf(\"\\n\"); }} // Function to print the letter Hvoid h(void){ printf(\"\\n\"); for (int i = 0; i < 8; i++) { printf(\" \"); for (int h = 0; h < 8; h++) { if (h < 2 || h > 5) { printf(\"%c\", ch); } else if (i > 2 && i < 5) { printf(\"%c\", ch); } else printf(\" \"); } printf(\"\\n\"); }} // Function to print the letter Ivoid i(void){ printf(\"\\n\"); for (int i = 0; i < 8; i++) { printf(\" \"); for (int t = 0; t < 8; t++) { if ((i < 1 || i > 6) && t < 8) { printf(\"%c\", ch); } else if (i > 0 && t < 3) printf(\" \"); else if (i > 0 && t > 2 && t < 5) { printf(\"%c\", ch); } else if (i > 0 && t > 4) printf(\" \"); else { } } printf(\"\\n\"); }} // Function to print the letter Jvoid j(void){ printf(\"\\n\"); for (int i = 0; i < 8; i++) { printf(\" \"); for (int h = 0; h < 8; h++) { if (i < 1) { printf(\"%c\", ch); } else if (i == 5 && h < 1) { printf(\"%c\", ch); } else if (i < 7 && h > 5) { printf(\"%c\", ch); } else if (i == 7 && (h == 0 || h == 7)) printf(\" \"); else if (i > 5) { printf(\"%c\", ch); } else printf(\" \"); } printf(\"\\n\"); }} // Function to print the letter Kvoid k(void){ printf(\"\\n\"); for (int i = 0; i < 8; i++) { printf(\" \"); for (int k1 = 0; k1 < 7; k1++) { if (k1 < 2) { printf(\"%c\", ch); } else if ((k1 >= 5 - i) && (k1 <= 6 - i)) { printf(\"%c\", ch); } else if (i >= 4) { if (k1 == i - 2 || k1 == i - 1) { printf(\"%c\", ch); } else printf(\" \"); } else printf(\" \"); } printf(\"\\n\"); }} // Function to print the letter Lvoid l(void){ printf(\"\\n\"); for (int i = 0; i < 8; i++) { printf(\" \"); { printf(\"%c%c\", ch, ch); } if (i == 6) { { printf(\"%c%c\", ch, ch); } { printf(\"%c%c\", ch, ch); } printf(\"%c%c\", ch, ch); } if (i == 7) { { printf(\"%c%c\", ch, ch); } { printf(\"%c%c\", ch, ch); } printf(\"%c%c\", ch, ch); } printf(\"\\n\"); }} // Function to print the letter Mvoid m(void){ printf(\"\\n\"); for (int i = 0; i < 8; i++) { printf(\" \"); for (int j = 0; j < 8; j++) { if (j == 0 || j == 7) { printf(\"%c\", ch); } else if (i < 4 && (j == 7 - i || j == i)) { printf(\"%c\", ch); } else printf(\" \"); } printf(\"\\n\"); }} // Function to print the letter Nvoid n(void){ printf(\"\\n\"); for (int i = 0; i < 8; i++) { printf(\" \"); for (int n = 0; n < 8; n++) { if (n < 2 || n > 5) { printf(\"%c\", ch); } else if (i == n - 1 || i == n + 1 || i == n) { printf(\"%c\", ch); } else printf(\" \"); } printf(\"\\n\"); }} // Function to print the letter Ovoid o(void){ printf(\"\\n\"); for (int i = 0; i < 8; i++) { printf(\" \"); for (int o = 0; o < 8; o++) { if (i == 0 && (o <= 1 || o >= 6 - i)) printf(\" \"); else if (i == 1 && (o == 0 || o == 8 - i || (o < 6 && o > 1))) printf(\" \"); else if (i == 2 && (o == 1 || o == 8 - i || (o < 6 && o > 1))) printf(\" \"); else if ((i == 3 || i == 4 || i == 5) && (o > 0 && o < 7)) printf(\" \"); else if (i == 6 && (o == 0 || o == 8 + 5 - i || (o < 6 && o > 1))) printf(\" \"); else if (i == 7 && (o <= 1 || o >= 6 - i + 7)) printf(\" \"); else { printf(\"%c\", ch); } } printf(\"\\n\"); }} // Function to print the letter Pvoid p(void){ printf(\"\\n\"); for (int i = 0; i < 8; i++) { printf(\" \"); { printf(\"%c%c\", ch, ch); } for (int r = 0; r < 6; r++) { if (i == 0 && r < 5) printf(\"%c\", ch); else if (i == 1) printf(\"%c\", ch); else if (i < 4 && i > 0 && r > 3) { printf(\"%c\", ch); } else if (i == 4 && r < 5) { printf(\"%c\", ch); } else printf(\" \"); } printf(\"\\n\"); }} // Function to print the letter Qvoid q(void){ printf(\"\\n\"); for (int i = 0; i < 8; i++) { printf(\" \"); for (int o = 0; o < 8; o++) { if (o == i) printf(\"%c\", ch); else if (i == 0 && (o <= 1 || o >= 6 - i)) printf(\" \"); else if (i == 1 && (o == 0 || o == 8 - i || (o < 6 && o > 1))) printf(\" \"); else if (i == 2 && (o == 1 || o == 8 - i || (o < 6 && o > 1))) printf(\" \"); else if ((i == 3 || i == 4 || i == 5) && (o > 0 && o < 7)) printf(\" \"); else if (i == 6 && (o == 0 || o == 8 + 5 - i || (o < 6 && o > 1))) printf(\" \"); else if (i == 7 && (o <= 1 || o >= 6 - i + 7)) printf(\" \"); else { printf(\"%c\", ch); } } printf(\"\\n\"); }} // Function to print the letter Rvoid r(void){ printf(\"\\n\"); for (int i = 0; i < 8; i++) { printf(\" \"); { printf(\"%c%c\", ch, ch); } for (int r = 0; r < 6; r++) { if (i == 0 && r < 5) printf(\"%c\", ch); else if (i == 1) printf(\"%c\", ch); else if (i < 4 && i > 0 && r > 3) { printf(\"%c\", ch); } else if (i >= 4) { if (i == 4 && (r == 3 || r == 4)) { printf(\"%c\", ch); } else if (r == i - 2 || r == i - 3) { printf(\"%c\", ch); } else printf(\" \"); } else printf(\" \"); } printf(\"\\n\"); }} // Function to print the letter Svoid s(void){ printf(\"\\n\"); for (int i = 0; i < 8; i++) { printf(\" \"); for (int j = 0; j < 7; j++) { if (i == 0 && j > 0) { printf(\"%c\", ch); } else if (i > 0 && i < 3 && j < 2) { printf(\"%c\", ch); } else if (i == 3 && j > 0 && j < 6) { printf(\"%c\", ch); } else if (i > 3 && i < 6 && j > 4) { printf(\"%c\", ch); } else if (i == 6 && j < 6) { printf(\"%c\", ch); } else printf(\" \"); } printf(\"\\n\"); }} // Function to print the letter Tvoid t(void){ printf(\"\\n\"); for (int i = 0; i < 8; i++) { printf(\" \"); for (int t = 0; t < 8; t++) { if (i < 2 && t < 8) { printf(\"%c\", ch); } if (i > 1 && t < 3) printf(\" \"); if (i > 1 && t > 2 && t < 5) { printf(\"%c\", ch); } if (i > 1 && t > 4) printf(\" \"); } printf(\"\\n\"); }} // Function to print the letter Uvoid u(void){ printf(\"\\n\"); for (int i = 0; i < 8; i++) { printf(\" \"); for (int h = 0; h < 8; h++) { if (i < 7 && (h < 2 || h > 5)) { printf(\"%c\", ch); } else if (i == 7 && (h == 0 || h == 7)) printf(\" \"); else if (i > 5) { printf(\"%c\", ch); } else printf(\" \"); } printf(\"\\n\"); }} // Function to print the letter Vvoid v(void){ printf(\"\\n\"); for (int i = 0; i < 8; i++) { printf(\" \"); for (int v = 0; v < 8; v++) if ((v == 0 || v == 7) && i < 4) { printf(\"%c\", ch); } else if ((v == i - 4 || v == 11 - i) && i >= 4) { printf(\"%c\", ch); } else printf(\" \"); printf(\"\\n\"); }} // Function to print the letter Wvoid w(void){ printf(\"\\n\"); for (int i = 0; i < 8; i++) { printf(\" \"); for (int j = 0; j < 8; j++) { if (j == 0 || j == 7) { printf(\"%c\", ch); } else if (i > 3 && (j == 7 - i || j == i)) { printf(\"%c\", ch); } else printf(\" \"); } printf(\"\\n\"); }} // Function to print the letter Xvoid x(void){ printf(\"\\n\"); for (int i = 0; i < 8; i++) { printf(\" \"); for (int m = 0; m < 8; m++) { if (i == m || m == 7 - i) { printf(\"%c\", ch); } else printf(\" \"); } printf(\"\\n\"); }} // Function to print the letter Yvoid y(void){ printf(\"\\n\"); for (int i = 0; i < 8; i++) { printf(\" \"); for (int y = 0; y < 8; y++) { if (i < 4) { if (y == i || y == i + 1 || y == 6 - i || y == 7 - i) { printf(\"%c\", ch); } else printf(\" \"); } else if (y == 3 || y == 4) { printf(\"%c\", ch); } else printf(\" \"); } printf(\"\\n\"); }} // Function to print the letter Zvoid z(void){ printf(\"\\n\"); for (int i = 0; i < 8; i++) { printf(\" \"); for (int j = 0; j < 8; j++) { if (i == 0 || i == 7) { printf(\"%c\", ch); } else if (j == 7 - i) { printf(\"%c\", ch); } else printf(\" \"); } printf(\"\\n\"); }} // Function to print the required pattern// by taking out each characters in itvoid printPattern(char* str){ int in = 0; while (str[in]) { char ch = str[in]; if (ch < 95) ch = ch + 32; switch (ch) { case 'a': a(); break; case 'b': b(); break; case 'c': c(); break; case 'd': d(); break; case 'e': e(); break; case 'f': f(); break; case 'g': g(); break; case 'h': h(); break; case 'i': i(); break; case 'j': j(); break; case 'k': k(); break; case 'l': l(); break; case 'm': m(); break; case 'n': n(); break; case 'o': o(); break; case 'p': p(); break; case 'q': q(); break; case 'r': r(); break; case 's': s(); break; case 't': t(); break; case 'u': u(); break; case 'v': v(); break; case 'w': w(); break; case 'x': x(); break; case 'y': y(); break; case 'z': z(); break; default: break; } in++; }} // Driver codeint main(){ ch = '*'; char* str = \"GFG\"; printPattern(str); return 0;}", "e": 37522, "s": 18838, "text": null }, { "code": "// Java Program to print the Alphabets// of a Given Word using * patternclass GFG{ static char ch; // Function to print the letter Astatic void a(){ System.out.printf(\"\\n\"); for (int i = 0; i < 8; i++) { System.out.printf(\" \"); for (int a = 0; a < 8; a++) { if (i == 0 && (a == 0 || a == 7)) System.out.printf(\" \"); else if (a < 2 || a > 5) { System.out.printf(\"%c\", ch); } else if (i < 2 || (i > 3 && i < 5)) { System.out.printf(\"%c\", ch); } else System.out.printf(\" \"); } System.out.printf(\"\\n\"); }} // Function to print the letter Bstatic void b(){ System.out.printf(\"\\n\"); for (int i = 0; i < 9; i++) { System.out.printf(\" %c%c\", ch, ch); for (int r = 0; r < 6; r++) { if (i == 0 && r < 5) System.out.printf(\"%c\", ch); else if (i == 1) System.out.printf(\"%c\", ch); else if (i < 4 && i > 0 && r > 3) { System.out.printf(\"%c\", ch); } else if (i == 4 && r < 5) { System.out.printf(\"%c\", ch); } else if (i > 4 && i < 7 && r > 3) { System.out.printf(\"%c\", ch); } else if (i == 7) { System.out.printf(\"%c\", ch); } else if (i == 8 && r < 5) { System.out.printf(\"%c\", ch); } else System.out.printf(\" \"); } System.out.printf(\"\\n\"); }} // Function to print the letter Cstatic void c(){ System.out.printf(\"\\n\"); for (int i = 0; i < 8; i++) { System.out.printf(\" \"); for (int o = 0; o < 8; o++) { if (i == 0 && (o <= 1)) System.out.printf(\" \"); else if (i == 1 && (o == 0 || o == 8 - i || (o > 1))) System.out.printf(\" \"); else if (i == 2 && (o == 1 || o == 8 - i || (o > 1))) System.out.printf(\" \"); else if ((i == 3 || i == 4 || i == 5) && (o > 0)) System.out.printf(\" \"); else if (i == 6 && (o == 0 || o == 8 + 5 - i || (o > 1))) System.out.printf(\" \"); else if (i == 7 && (o <= 1)) System.out.printf(\" \"); else { System.out.printf(\"%c\", ch); } } System.out.printf(\"\\n\"); }} // Function to print the letter Dstatic void d(){ System.out.printf(\"\\n\"); for (int i = 0; i < 8; i++) { { System.out.printf(\" %c\", ch); } for (int o = 0; o < 8; o++) { if (i == 0 && (o >= 6 - i)) System.out.printf(\" \"); else if (i == 1 && (o == 0 || o == 8 - i || (o < 6))) System.out.printf(\" \"); else if (i == 2 && (o == 1 || o == 8 - i || (o < 6))) System.out.printf(\" \"); else if ((i == 3 || i == 4 || i == 5) && (o < 7)) System.out.printf(\" \"); else if (i == 6 && (o == 0 || o == 8 + 5 - i || (o < 6))) System.out.printf(\" \"); else if (i == 7 && (o >= 6 - i + 7)) System.out.printf(\" \"); else { System.out.printf(\"%c\", ch); } } System.out.printf(\"\\n\"); }} // Function to print the letter Estatic void e(){ System.out.printf(\"\\n\"); for (int i = 0; i < 8; i++) { System.out.printf(\" \"); for (int j = 0; j < 7; j++) { if (i == 0) { System.out.printf(\"%c\", ch); } else if (i > 0 && i < 3 && j < 2) { System.out.printf(\"%c\", ch); } else if (i == 3 && j < 6) { System.out.printf(\"%c\", ch); } else if (i > 3 && i < 6 && j < 2) { System.out.printf(\"%c\", ch); } else if (i == 6) { System.out.printf(\"%c\", ch); } else System.out.printf(\" \"); } System.out.printf(\"\\n\"); }} // Function to print the letter Fstatic void f(){ System.out.printf(\"\\n\"); for (int i = 0; i < 8; i++) { System.out.printf(\" \"); for (int j = 0; j < 7; j++) { if (i == 0) { System.out.printf(\"%c\", ch); } else if (i > 0 && i < 3 && j < 2) { System.out.printf(\"%c\", ch); } else if (i == 3 && j < 6) { System.out.printf(\"%c\", ch); } else if (i > 3 && i < 7 && j < 2) { System.out.printf(\"%c\", ch); } else System.out.printf(\" \"); } System.out.printf(\"\\n\"); }} // Function to print the letter Gstatic void g(){ System.out.printf(\"\\n\"); for (int i = 0; i < 8; i++) { System.out.printf(\" \"); for (int o = 0; o < 8; o++) { if (i == 4 && o > 3 || (o == 4 || o == 7) && i > 4) { System.out.printf(\"%c\", ch); } else if (i == 0 && (o <= 1)) System.out.printf(\" \"); else if (i == 1 && (o == 0 || o == 8 - i || (o > 1))) System.out.printf(\" \"); else if (i == 2 && (o == 1 || o == 8 - i || (o > 1))) System.out.printf(\" \"); else if ((i == 3 || i == 4 || i == 5) && (o > 0)) System.out.printf(\" \"); else if (i == 6 && (o == 0 || (o > 1))) System.out.printf(\" \"); else if (i == 7 && (o <= 1 || o == 5 || o == 6)) System.out.printf(\" \"); else { System.out.printf(\"%c\", ch); } } System.out.printf(\"\\n\"); }} // Function to print the letter Hstatic void h(){ System.out.printf(\"\\n\"); for (int i = 0; i < 8; i++) { System.out.printf(\" \"); for (int h = 0; h < 8; h++) { if (h < 2 || h > 5) { System.out.printf(\"%c\", ch); } else if (i > 2 && i < 5) { System.out.printf(\"%c\", ch); } else System.out.printf(\" \"); } System.out.printf(\"\\n\"); }} // Function to print the letter Istatic void i(){ System.out.printf(\"\\n\"); for (int i = 0; i < 8; i++) { System.out.printf(\" \"); for (int t = 0; t < 8; t++) { if ((i < 1 || i > 6) && t < 8) { System.out.printf(\"%c\", ch); } else if (i > 0 && t < 3) System.out.printf(\" \"); else if (i > 0 && t > 2 && t < 5) { System.out.printf(\"%c\", ch); } else if (i > 0 && t > 4) System.out.printf(\" \"); else { } } System.out.printf(\"\\n\"); }} // Function to print the letter Jstatic void j(){ System.out.printf(\"\\n\"); for (int i = 0; i < 8; i++) { System.out.printf(\" \"); for (int h = 0; h < 8; h++) { if (i < 1) { System.out.printf(\"%c\", ch); } else if (i == 5 && h < 1) { System.out.printf(\"%c\", ch); } else if (i < 7 && h > 5) { System.out.printf(\"%c\", ch); } else if (i == 7 && (h == 0 || h == 7)) System.out.printf(\" \"); else if (i > 5) { System.out.printf(\"%c\", ch); } else System.out.printf(\" \"); } System.out.printf(\"\\n\"); }} // Function to print the letter Kstatic void k(){ System.out.printf(\"\\n\"); for (int i = 0; i < 8; i++) { System.out.printf(\" \"); for (int k1 = 0; k1 < 7; k1++) { if (k1 < 2) { System.out.printf(\"%c\", ch); } else if ((k1 >= 5 - i) && (k1 <= 6 - i)) { System.out.printf(\"%c\", ch); } else if (i >= 4) { if (k1 == i - 2 || k1 == i - 1) { System.out.printf(\"%c\", ch); } else System.out.printf(\" \"); } else System.out.printf(\" \"); } System.out.printf(\"\\n\"); }} // Function to print the letter Lstatic void l(){ System.out.printf(\"\\n\"); for (int i = 0; i < 8; i++) { System.out.printf(\" \"); { System.out.printf(\"%c%c\", ch, ch); } if (i == 6) { { System.out.printf(\"%c%c\", ch, ch); } { System.out.printf(\"%c%c\", ch, ch); } System.out.printf(\"%c%c\", ch, ch); } if (i == 7) { { System.out.printf(\"%c%c\", ch, ch); } { System.out.printf(\"%c%c\", ch, ch); } System.out.printf(\"%c%c\", ch, ch); } System.out.printf(\"\\n\"); }} // Function to print the letter Mstatic void m(){ System.out.printf(\"\\n\"); for (int i = 0; i < 8; i++) { System.out.printf(\" \"); for (int j = 0; j < 8; j++) { if (j == 0 || j == 7) { System.out.printf(\"%c\", ch); } else if (i < 4 && (j == 7 - i || j == i)) { System.out.printf(\"%c\", ch); } else System.out.printf(\" \"); } System.out.printf(\"\\n\"); }} // Function to print the letter Nstatic void n(){ System.out.printf(\"\\n\"); for (int i = 0; i < 8; i++) { System.out.printf(\" \"); for (int n = 0; n < 8; n++) { if (n < 2 || n > 5) { System.out.printf(\"%c\", ch); } else if (i == n - 1 || i == n + 1 || i == n) { System.out.printf(\"%c\", ch); } else System.out.printf(\" \"); } System.out.printf(\"\\n\"); }} // Function to print the letter Ostatic void o(){ System.out.printf(\"\\n\"); for (int i = 0; i < 8; i++) { System.out.printf(\" \"); for (int o = 0; o < 8; o++) { if (i == 0 && (o <= 1 || o >= 6 - i)) System.out.printf(\" \"); else if (i == 1 && (o == 0 || o == 8 - i || (o < 6 && o > 1))) System.out.printf(\" \"); else if (i == 2 && (o == 1 || o == 8 - i || (o < 6 && o > 1))) System.out.printf(\" \"); else if ((i == 3 || i == 4 || i == 5) && (o > 0 && o < 7)) System.out.printf(\" \"); else if (i == 6 && (o == 0 || o == 8 + 5 - i || (o < 6 && o > 1))) System.out.printf(\" \"); else if (i == 7 && (o <= 1 || o >= 6 - i + 7)) System.out.printf(\" \"); else { System.out.printf(\"%c\", ch); } } System.out.printf(\"\\n\"); }} // Function to print the letter Pstatic void p(){ System.out.printf(\"\\n\"); for (int i = 0; i < 8; i++) { System.out.printf(\" \"); { System.out.printf(\"%c%c\", ch, ch); } for (int r = 0; r < 6; r++) { if (i == 0 && r < 5) System.out.printf(\"%c\", ch); else if (i == 1) System.out.printf(\"%c\", ch); else if (i < 4 && i > 0 && r > 3) { System.out.printf(\"%c\", ch); } else if (i == 4 && r < 5) { System.out.printf(\"%c\", ch); } else System.out.printf(\" \"); } System.out.printf(\"\\n\"); }} // Function to print the letter Qstatic void q(){ System.out.printf(\"\\n\"); for (int i = 0; i < 8; i++) { System.out.printf(\" \"); for (int o = 0; o < 8; o++) { if (o == i) System.out.printf(\"%c\", ch); else if (i == 0 && (o <= 1 || o >= 6 - i)) System.out.printf(\" \"); else if (i == 1 && (o == 0 || o == 8 - i || (o < 6 && o > 1))) System.out.printf(\" \"); else if (i == 2 && (o == 1 || o == 8 - i || (o < 6 && o > 1))) System.out.printf(\" \"); else if ((i == 3 || i == 4 || i == 5) && (o > 0 && o < 7)) System.out.printf(\" \"); else if (i == 6 && (o == 0 || o == 8 + 5 - i || (o < 6 && o > 1))) System.out.printf(\" \"); else if (i == 7 && (o <= 1 || o >= 6 - i + 7)) System.out.printf(\" \"); else { System.out.printf(\"%c\", ch); } } System.out.printf(\"\\n\"); }} // Function to print the letter Rstatic void r(){ System.out.printf(\"\\n\"); for (int i = 0; i < 8; i++) { System.out.printf(\" \"); { System.out.printf(\"%c%c\", ch, ch); } for (int r = 0; r < 6; r++) { if (i == 0 && r < 5) System.out.printf(\"%c\", ch); else if (i == 1) System.out.printf(\"%c\", ch); else if (i < 4 && i > 0 && r > 3) { System.out.printf(\"%c\", ch); } else if (i >= 4) { if (i == 4 && (r == 3 || r == 4)) { System.out.printf(\"%c\", ch); } else if (r == i - 2 || r == i - 3) { System.out.printf(\"%c\", ch); } else System.out.printf(\" \"); } else System.out.printf(\" \"); } System.out.printf(\"\\n\"); }} // Function to print the letter Sstatic void s(){ System.out.printf(\"\\n\"); for (int i = 0; i < 8; i++) { System.out.printf(\" \"); for (int j = 0; j < 7; j++) { if (i == 0 && j > 0) { System.out.printf(\"%c\", ch); } else if (i > 0 && i < 3 && j < 2) { System.out.printf(\"%c\", ch); } else if (i == 3 && j > 0 && j < 6) { System.out.printf(\"%c\", ch); } else if (i > 3 && i < 6 && j > 4) { System.out.printf(\"%c\", ch); } else if (i == 6 && j < 6) { System.out.printf(\"%c\", ch); } else System.out.printf(\" \"); } System.out.printf(\"\\n\"); }} // Function to print the letter Tstatic void t(){ System.out.printf(\"\\n\"); for (int i = 0; i < 8; i++) { System.out.printf(\" \"); for (int t = 0; t < 8; t++) { if (i < 2 && t < 8) { System.out.printf(\"%c\", ch); } if (i > 1 && t < 3) System.out.printf(\" \"); if (i > 1 && t > 2 && t < 5) { System.out.printf(\"%c\", ch); } if (i > 1 && t > 4) System.out.printf(\" \"); } System.out.printf(\"\\n\"); }} // Function to print the letter Ustatic void u(){ System.out.printf(\"\\n\"); for (int i = 0; i < 8; i++) { System.out.printf(\" \"); for (int h = 0; h < 8; h++) { if (i < 7 && (h < 2 || h > 5)) { System.out.printf(\"%c\", ch); } else if (i == 7 && (h == 0 || h == 7)) System.out.printf(\" \"); else if (i > 5) { System.out.printf(\"%c\", ch); } else System.out.printf(\" \"); } System.out.printf(\"\\n\"); }} // Function to print the letter Vstatic void v(){ System.out.printf(\"\\n\"); for (int i = 0; i < 8; i++) { System.out.printf(\" \"); for (int v = 0; v < 8; v++) if ((v == 0 || v == 7) && i < 4) { System.out.printf(\"%c\", ch); } else if ((v == i - 4 || v == 11 - i) && i >= 4) { System.out.printf(\"%c\", ch); } else System.out.printf(\" \"); System.out.printf(\"\\n\"); }} // Function to print the letter Wstatic void w(){ System.out.printf(\"\\n\"); for (int i = 0; i < 8; i++) { System.out.printf(\" \"); for (int j = 0; j < 8; j++) { if (j == 0 || j == 7) { System.out.printf(\"%c\", ch); } else if (i > 3 && (j == 7 - i || j == i)) { System.out.printf(\"%c\", ch); } else System.out.printf(\" \"); } System.out.printf(\"\\n\"); }} // Function to print the letter Xstatic void x(){ System.out.printf(\"\\n\"); for (int i = 0; i < 8; i++) { System.out.printf(\" \"); for (int m = 0; m < 8; m++) { if (i == m || m == 7 - i) { System.out.printf(\"%c\", ch); } else System.out.printf(\" \"); } System.out.printf(\"\\n\"); }} // Function to print the letter Ystatic void y(){ System.out.printf(\"\\n\"); for (int i = 0; i < 8; i++) { System.out.printf(\" \"); for (int y = 0; y < 8; y++) { if (i < 4) { if (y == i || y == i + 1 || y == 6 - i || y == 7 - i) { System.out.printf(\"%c\", ch); } else System.out.printf(\" \"); } else if (y == 3 || y == 4) { System.out.printf(\"%c\", ch); } else System.out.printf(\" \"); } System.out.printf(\"\\n\"); }} // Function to print the letter Zstatic void z(){ System.out.printf(\"\\n\"); for (int i = 0; i < 8; i++) { System.out.printf(\" \"); for (int j = 0; j < 8; j++) { if (i == 0 || i == 7) { System.out.printf(\"%c\", ch); } else if (j == 7 - i) { System.out.printf(\"%c\", ch); } else System.out.printf(\" \"); } System.out.printf(\"\\n\"); }} // Function to print the required pattern// by taking out each characters in itstatic void printPattern(char[] str){ int in = 0; while (in<str.length) { char ch = str[in]; if (ch < 95) ch = (char) (ch + 32); switch (ch) { case 'a': a(); break; case 'b': b(); break; case 'c': c(); break; case 'd': d(); break; case 'e': e(); break; case 'f': f(); break; case 'g': g(); break; case 'h': h(); break; case 'i': i(); break; case 'j': j(); break; case 'k': k(); break; case 'l': l(); break; case 'm': m(); break; case 'n': n(); break; case 'o': o(); break; case 'p': p(); break; case 'q': q(); break; case 'r': r(); break; case 's': s(); break; case 't': t(); break; case 'u': u(); break; case 'v': v(); break; case 'w': w(); break; case 'x': x(); break; case 'y': y(); break; case 'z': z(); break; default: break; } in++; }} // Driver codepublic static void main(String[] args){ ch = '*'; char[] str = \"GFG\".toCharArray(); printPattern(str); }} // This code contributed by Rajput-Ji", "e": 58758, "s": 37522, "text": null }, { "code": "// C# Program to print the Alphabets// of a Given Word using * patternusing System; class GFG{ static char ch; // Function to print the letter Astatic void a(){ Console.Write(\"\\n\"); for (int i = 0; i < 8; i++) { Console.Write(\" \"); for (int a = 0; a < 8; a++) { if (i == 0 && (a == 0 || a == 7)) Console.Write(\" \"); else if (a < 2 || a > 5) { Console.Write(\"{0}\", ch); } else if (i < 2 || (i > 3 && i < 5)) { Console.Write(\"{0}\", ch); } else Console.Write(\" \"); } Console.Write(\"\\n\"); }} // Function to print the letter Bstatic void b(){ Console.Write(\"\\n\"); for (int i = 0; i < 9; i++) { Console.Write(\" {0}{0}\", ch, ch); for (int r = 0; r < 6; r++) { if (i == 0 && r < 5) Console.Write(\"{0}\", ch); else if (i == 1) Console.Write(\"{0}\", ch); else if (i < 4 && i > 0 && r > 3) { Console.Write(\"{0}\", ch); } else if (i == 4 && r < 5) { Console.Write(\"{0}\", ch); } else if (i > 4 && i < 7 && r > 3) { Console.Write(\"{0}\", ch); } else if (i == 7) { Console.Write(\"{0}\", ch); } else if (i == 8 && r < 5) { Console.Write(\"{0}\", ch); } else Console.Write(\" \"); } Console.Write(\"\\n\"); }} // Function to print the letter Cstatic void c(){ Console.Write(\"\\n\"); for (int i = 0; i < 8; i++) { Console.Write(\" \"); for (int o = 0; o < 8; o++) { if (i == 0 && (o <= 1)) Console.Write(\" \"); else if (i == 1 && (o == 0 || o == 8 - i || (o > 1))) Console.Write(\" \"); else if (i == 2 && (o == 1 || o == 8 - i || (o > 1))) Console.Write(\" \"); else if ((i == 3 || i == 4 || i == 5) && (o > 0)) Console.Write(\" \"); else if (i == 6 && (o == 0 || o == 8 + 5 - i || (o > 1))) Console.Write(\" \"); else if (i == 7 && (o <= 1)) Console.Write(\" \"); else { Console.Write(\"{0}\", ch); } } Console.Write(\"\\n\"); }} // Function to print the letter Dstatic void d(){ Console.Write(\"\\n\"); for (int i = 0; i < 8; i++) { { Console.Write(\" {0}\", ch); } for (int o = 0; o < 8; o++) { if (i == 0 && (o >= 6 - i)) Console.Write(\" \"); else if (i == 1 && (o == 0 || o == 8 - i || (o < 6))) Console.Write(\" \"); else if (i == 2 && (o == 1 || o == 8 - i || (o < 6))) Console.Write(\" \"); else if ((i == 3 || i == 4 || i == 5) && (o < 7)) Console.Write(\" \"); else if (i == 6 && (o == 0 || o == 8 + 5 - i || (o < 6))) Console.Write(\" \"); else if (i == 7 && (o >= 6 - i + 7)) Console.Write(\" \"); else { Console.Write(\"{0}\", ch); } } Console.Write(\"\\n\"); }} // Function to print the letter Estatic void e(){ Console.Write(\"\\n\"); for (int i = 0; i < 8; i++) { Console.Write(\" \"); for (int j = 0; j < 7; j++) { if (i == 0) { Console.Write(\"{0}\", ch); } else if (i > 0 && i < 3 && j < 2) { Console.Write(\"{0}\", ch); } else if (i == 3 && j < 6) { Console.Write(\"{0}\", ch); } else if (i > 3 && i < 6 && j < 2) { Console.Write(\"{0}\", ch); } else if (i == 6) { Console.Write(\"{0}\", ch); } else Console.Write(\" \"); } Console.Write(\"\\n\"); }} // Function to print the letter Fstatic void f(){ Console.Write(\"\\n\"); for (int i = 0; i < 8; i++) { Console.Write(\" \"); for (int j = 0; j < 7; j++) { if (i == 0) { Console.Write(\"{0}\", ch); } else if (i > 0 && i < 3 && j < 2) { Console.Write(\"{0}\", ch); } else if (i == 3 && j < 6) { Console.Write(\"{0}\", ch); } else if (i > 3 && i < 7 && j < 2) { Console.Write(\"{0}\", ch); } else Console.Write(\" \"); } Console.Write(\"\\n\"); }} // Function to print the letter Gstatic void g(){ Console.Write(\"\\n\"); for (int i = 0; i < 8; i++) { Console.Write(\" \"); for (int o = 0; o < 8; o++) { if (i == 4 && o > 3 || (o == 4 || o == 7) && i > 4) { Console.Write(\"{0}\", ch); } else if (i == 0 && (o <= 1)) Console.Write(\" \"); else if (i == 1 && (o == 0 || o == 8 - i || (o > 1))) Console.Write(\" \"); else if (i == 2 && (o == 1 || o == 8 - i || (o > 1))) Console.Write(\" \"); else if ((i == 3 || i == 4 || i == 5) && (o > 0)) Console.Write(\" \"); else if (i == 6 && (o == 0 || (o > 1))) Console.Write(\" \"); else if (i == 7 && (o <= 1 || o == 5 || o == 6)) Console.Write(\" \"); else { Console.Write(\"{0}\", ch); } } Console.Write(\"\\n\"); }} // Function to print the letter Hstatic void h(){ Console.Write(\"\\n\"); for (int i = 0; i < 8; i++) { Console.Write(\" \"); for (int h = 0; h < 8; h++) { if (h < 2 || h > 5) { Console.Write(\"{0}\", ch); } else if (i > 2 && i < 5) { Console.Write(\"{0}\", ch); } else Console.Write(\" \"); } Console.Write(\"\\n\"); }} // Function to print the letter Istatic void i(){ Console.Write(\"\\n\"); for (int i = 0; i < 8; i++) { Console.Write(\" \"); for (int t = 0; t < 8; t++) { if ((i < 1 || i > 6) && t < 8) { Console.Write(\"{0}\", ch); } else if (i > 0 && t < 3) Console.Write(\" \"); else if (i > 0 && t > 2 && t < 5) { Console.Write(\"{0}\", ch); } else if (i > 0 && t > 4) Console.Write(\" \"); else { } } Console.Write(\"\\n\"); }} // Function to print the letter Jstatic void j(){ Console.Write(\"\\n\"); for (int i = 0; i < 8; i++) { Console.Write(\" \"); for (int h = 0; h < 8; h++) { if (i < 1) { Console.Write(\"{0}\", ch); } else if (i == 5 && h < 1) { Console.Write(\"{0}\", ch); } else if (i < 7 && h > 5) { Console.Write(\"{0}\", ch); } else if (i == 7 && (h == 0 || h == 7)) Console.Write(\" \"); else if (i > 5) { Console.Write(\"{0}\", ch); } else Console.Write(\" \"); } Console.Write(\"\\n\"); }} // Function to print the letter Kstatic void k(){ Console.Write(\"\\n\"); for (int i = 0; i < 8; i++) { Console.Write(\" \"); for (int k1 = 0; k1 < 7; k1++) { if (k1 < 2) { Console.Write(\"{0}\", ch); } else if ((k1 >= 5 - i) && (k1 <= 6 - i)) { Console.Write(\"{0}\", ch); } else if (i >= 4) { if (k1 == i - 2 || k1 == i - 1) { Console.Write(\"{0}\", ch); } else Console.Write(\" \"); } else Console.Write(\" \"); } Console.Write(\"\\n\"); }} // Function to print the letter Lstatic void l(){ Console.Write(\"\\n\"); for (int i = 0; i < 8; i++) { Console.Write(\" \"); { Console.Write(\"{0}{0}\", ch, ch); } if (i == 6) { { Console.Write(\"{0}{0}\", ch, ch); } { Console.Write(\"{0}{0}\", ch, ch); } Console.Write(\"{0}{0}\", ch, ch); } if (i == 7) { { Console.Write(\"{0}{0}\", ch, ch); } { Console.Write(\"{0}{0}\", ch, ch); } Console.Write(\"{0}{0}\", ch, ch); } Console.Write(\"\\n\"); }} // Function to print the letter Mstatic void m(){ Console.Write(\"\\n\"); for (int i = 0; i < 8; i++) { Console.Write(\" \"); for (int j = 0; j < 8; j++) { if (j == 0 || j == 7) { Console.Write(\"{0}\", ch); } else if (i < 4 && (j == 7 - i || j == i)) { Console.Write(\"{0}\", ch); } else Console.Write(\" \"); } Console.Write(\"\\n\"); }} // Function to print the letter Nstatic void n(){ Console.Write(\"\\n\"); for (int i = 0; i < 8; i++) { Console.Write(\" \"); for (int n = 0; n < 8; n++) { if (n < 2 || n > 5) { Console.Write(\"{0}\", ch); } else if (i == n - 1 || i == n + 1 || i == n) { Console.Write(\"{0}\", ch); } else Console.Write(\" \"); } Console.Write(\"\\n\"); }} // Function to print the letter Ostatic void o(){ Console.Write(\"\\n\"); for (int i = 0; i < 8; i++) { Console.Write(\" \"); for (int o = 0; o < 8; o++) { if (i == 0 && (o <= 1 || o >= 6 - i)) Console.Write(\" \"); else if (i == 1 && (o == 0 || o == 8 - i || (o < 6 && o > 1))) Console.Write(\" \"); else if (i == 2 && (o == 1 || o == 8 - i || (o < 6 && o > 1))) Console.Write(\" \"); else if ((i == 3 || i == 4 || i == 5) && (o > 0 && o < 7)) Console.Write(\" \"); else if (i == 6 && (o == 0 || o == 8 + 5 - i || (o < 6 && o > 1))) Console.Write(\" \"); else if (i == 7 && (o <= 1 || o >= 6 - i + 7)) Console.Write(\" \"); else { Console.Write(\"{0}\", ch); } } Console.Write(\"\\n\"); }} // Function to print the letter Pstatic void p(){ Console.Write(\"\\n\"); for (int i = 0; i < 8; i++) { Console.Write(\" \"); { Console.Write(\"{0}{0}\", ch, ch); } for (int r = 0; r < 6; r++) { if (i == 0 && r < 5) Console.Write(\"{0}\", ch); else if (i == 1) Console.Write(\"{0}\", ch); else if (i < 4 && i > 0 && r > 3) { Console.Write(\"{0}\", ch); } else if (i == 4 && r < 5) { Console.Write(\"{0}\", ch); } else Console.Write(\" \"); } Console.Write(\"\\n\"); }} // Function to print the letter Qstatic void q(){ Console.Write(\"\\n\"); for (int i = 0; i < 8; i++) { Console.Write(\" \"); for (int o = 0; o < 8; o++) { if (o == i) Console.Write(\"{0}\", ch); else if (i == 0 && (o <= 1 || o >= 6 - i)) Console.Write(\" \"); else if (i == 1 && (o == 0 || o == 8 - i || (o < 6 && o > 1))) Console.Write(\" \"); else if (i == 2 && (o == 1 || o == 8 - i || (o < 6 && o > 1))) Console.Write(\" \"); else if ((i == 3 || i == 4 || i == 5) && (o > 0 && o < 7)) Console.Write(\" \"); else if (i == 6 && (o == 0 || o == 8 + 5 - i || (o < 6 && o > 1))) Console.Write(\" \"); else if (i == 7 && (o <= 1 || o >= 6 - i + 7)) Console.Write(\" \"); else { Console.Write(\"{0}\", ch); } } Console.Write(\"\\n\"); }} // Function to print the letter Rstatic void r(){ Console.Write(\"\\n\"); for (int i = 0; i < 8; i++) { Console.Write(\" \"); { Console.Write(\"{0}{0}\", ch, ch); } for (int r = 0; r < 6; r++) { if (i == 0 && r < 5) Console.Write(\"{0}\", ch); else if (i == 1) Console.Write(\"{0}\", ch); else if (i < 4 && i > 0 && r > 3) { Console.Write(\"{0}\", ch); } else if (i >= 4) { if (i == 4 && (r == 3 || r == 4)) { Console.Write(\"{0}\", ch); } else if (r == i - 2 || r == i - 3) { Console.Write(\"{0}\", ch); } else Console.Write(\" \"); } else Console.Write(\" \"); } Console.Write(\"\\n\"); }} // Function to print the letter Sstatic void s(){ Console.Write(\"\\n\"); for (int i = 0; i < 8; i++) { Console.Write(\" \"); for (int j = 0; j < 7; j++) { if (i == 0 && j > 0) { Console.Write(\"{0}\", ch); } else if (i > 0 && i < 3 && j < 2) { Console.Write(\"{0}\", ch); } else if (i == 3 && j > 0 && j < 6) { Console.Write(\"{0}\", ch); } else if (i > 3 && i < 6 && j > 4) { Console.Write(\"{0}\", ch); } else if (i == 6 && j < 6) { Console.Write(\"{0}\", ch); } else Console.Write(\" \"); } Console.Write(\"\\n\"); }} // Function to print the letter Tstatic void t(){ Console.Write(\"\\n\"); for (int i = 0; i < 8; i++) { Console.Write(\" \"); for (int t = 0; t < 8; t++) { if (i < 2 && t < 8) { Console.Write(\"{0}\", ch); } if (i > 1 && t < 3) Console.Write(\" \"); if (i > 1 && t > 2 && t < 5) { Console.Write(\"{0}\", ch); } if (i > 1 && t > 4) Console.Write(\" \"); } Console.Write(\"\\n\"); }} // Function to print the letter Ustatic void u(){ Console.Write(\"\\n\"); for (int i = 0; i < 8; i++) { Console.Write(\" \"); for (int h = 0; h < 8; h++) { if (i < 7 && (h < 2 || h > 5)) { Console.Write(\"{0}\", ch); } else if (i == 7 && (h == 0 || h == 7)) Console.Write(\" \"); else if (i > 5) { Console.Write(\"{0}\", ch); } else Console.Write(\" \"); } Console.Write(\"\\n\"); }} // Function to print the letter Vstatic void v(){ Console.Write(\"\\n\"); for (int i = 0; i < 8; i++) { Console.Write(\" \"); for (int v = 0; v < 8; v++) if ((v == 0 || v == 7) && i < 4) { Console.Write(\"{0}\", ch); } else if ((v == i - 4 || v == 11 - i) && i >= 4) { Console.Write(\"{0}\", ch); } else Console.Write(\" \"); Console.Write(\"\\n\"); }} // Function to print the letter Wstatic void w(){ Console.Write(\"\\n\"); for (int i = 0; i < 8; i++) { Console.Write(\" \"); for (int j = 0; j < 8; j++) { if (j == 0 || j == 7) { Console.Write(\"{0}\", ch); } else if (i > 3 && (j == 7 - i || j == i)) { Console.Write(\"{0}\", ch); } else Console.Write(\" \"); } Console.Write(\"\\n\"); }} // Function to print the letter Xstatic void x(){ Console.Write(\"\\n\"); for (int i = 0; i < 8; i++) { Console.Write(\" \"); for (int m = 0; m < 8; m++) { if (i == m || m == 7 - i) { Console.Write(\"{0}\", ch); } else Console.Write(\" \"); } Console.Write(\"\\n\"); }} // Function to print the letter Ystatic void y(){ Console.Write(\"\\n\"); for (int i = 0; i < 8; i++) { Console.Write(\" \"); for (int y = 0; y < 8; y++) { if (i < 4) { if (y == i || y == i + 1 || y == 6 - i || y == 7 - i) { Console.Write(\"{0}\", ch); } else Console.Write(\" \"); } else if (y == 3 || y == 4) { Console.Write(\"{0}\", ch); } else Console.Write(\" \"); } Console.Write(\"\\n\"); }} // Function to print the letter Zstatic void z(){ Console.Write(\"\\n\"); for (int i = 0; i < 8; i++) { Console.Write(\" \"); for (int j = 0; j < 8; j++) { if (i == 0 || i == 7) { Console.Write(\"{0}\", ch); } else if (j == 7 - i) { Console.Write(\"{0}\", ch); } else Console.Write(\" \"); } Console.Write(\"\\n\"); }} // Function to print the required pattern// by taking out each characters in itstatic void printPattern(char[] str){ int iN = 0; while (iN<str.Length) { char ch = str[iN]; if (ch < 95) ch = (char) (ch + 32); switch (ch) { case 'a': a(); break; case 'b': b(); break; case 'c': c(); break; case 'd': d(); break; case 'e': e(); break; case 'f': f(); break; case 'g': g(); break; case 'h': h(); break; case 'i': i(); break; case 'j': j(); break; case 'k': k(); break; case 'l': l(); break; case 'm': m(); break; case 'n': n(); break; case 'o': o(); break; case 'p': p(); break; case 'q': q(); break; case 'r': r(); break; case 's': s(); break; case 't': t(); break; case 'u': u(); break; case 'v': v(); break; case 'w': w(); break; case 'x': x(); break; case 'y': y(); break; case 'z': z(); break; default: break; } iN++; }} // Driver codepublic static void Main(String[] args){ ch = '*'; char[] str = \"GFG\".ToCharArray(); printPattern(str); }}// This code is contributed by 29AjayKumar", "e": 79113, "s": 58758, "text": null }, { "code": null, "e": 79347, "s": 79113, "text": " ******\n * \n * \n * \n * ****\n * * *\n * * *\n *** *\n\n *******\n ** \n ** \n ****** \n ** \n ** \n ** \n \n\n ******\n * \n * \n * \n * ****\n * * *\n * * *\n *** *" }, { "code": null, "e": 79359, "s": 79349, "text": "Rajput-Ji" }, { "code": null, "e": 79371, "s": 79359, "text": "29AjayKumar" }, { "code": null, "e": 79386, "s": 79371, "text": "SHUBHAMSINGH10" }, { "code": null, "e": 79403, "s": 79386, "text": "pattern-printing" }, { "code": null, "e": 79414, "s": 79403, "text": "C Programs" }, { "code": null, "e": 79427, "s": 79414, "text": "C++ Programs" }, { "code": null, "e": 79444, "s": 79427, "text": "pattern-printing" }, { "code": null, "e": 79542, "s": 79444, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 79583, "s": 79542, "text": "C Program to read contents of Whole File" }, { "code": null, "e": 79614, "s": 79583, "text": "Producer Consumer Problem in C" }, { "code": null, "e": 79667, "s": 79614, "text": "Difference between break and continue statement in C" }, { "code": null, "e": 79689, "s": 79667, "text": "C Hello World Program" }, { "code": null, "e": 79723, "s": 79689, "text": "Exit codes in C/C++ with Examples" }, { "code": null, "e": 79757, "s": 79723, "text": "Sorting a Map by value in C++ STL" }, { "code": null, "e": 79791, "s": 79757, "text": "Shallow Copy and Deep Copy in C++" }, { "code": null, "e": 79829, "s": 79791, "text": "C++ program for hashing with chaining" }, { "code": null, "e": 79889, "s": 79829, "text": "C++ Program to check if a given String is Palindrome or not" } ]
How to Install Golang on MacOS?
06 Oct, 2021 Before, we start with the process of Installing Golang on our System. We must have first-hand knowledge of What the Go Language is and what it actually does? Go is an open-source and statically typed programming language developed in 2007 by Robert Griesemer, Rob Pike, and Ken Thompson at Google but launched in 2009. It is also known as the Golang and it supports the procedural programming language. It was initially developed to improve programming productivity of the large codebases, multicore, and networked machines.Golang programs can be written in any plain text editor like TextEdit, Sublime Text, or anything of that sort. One can also use an online IDE for writing Golang codes or can even install one on their system to make it more feasible to write these codes. Using an IDE makes it easier to write Golang codes because IDEs provide a lot of features like intuitive code editor, debugger, compiler, etc. In this article, we have covered the following topics: Steps for Installing Golang on MacOS Setting up the Go Workspace Executing the First Golang program Step 1: Checking if Go is installed or not. Before we begin with the installation of Go, it is good to check if it might be already installed on your system. To check if your device is preinstalled with Golang or not, just go to the Terminal and run the command: go version If Golang is already installed, it will generate a message with all the details of the Golang version available as shown below, otherwise, it will give an error. Step 2: Before starting with the installation process, you need to download it. So for that, all versions of Go for MacOS are available on https://golang.org/dl/ Download the Golang according to your system architecture. Here, we have downloaded go1.13.1drawin-amd64.pkg for the system. Step 3: After downloading process, install the package on your system: Step 4: After completing the installation processes. Open a program known as Terminal(It is a command-line interface for macOS) to check whether Go install properly or not using the Golang version command. As shown in the below image, here it shows the version information of the Golang which means Go install successfully in your system. After successfully installing Go on your system, now we are going to set up the Go workspace. Go workspace is a folder on your computer where all your go code will going to store. Step 1: Creating a folder named as Go in documents(or wherever you want in your system) like as shown in the below image: Step 2: Now tell the Go tools to where to find this folder. So for that first of all, you go to your home directory using the following command: cd ~ After that set path of the folder using the following command: echo "export GOPATH=/Users/anki/Documents/go" >> .bash_profile Here, we are adding export GOPATH=/Users/anki/Documents/go to .bash_profile. The .bash_profile is a file that automatically loaded when you logged into your Mac account and it contains all the startup configurations and preferences for your command-line interface(CLI). Step 3: Now check check that your .bash_profile conatins the following path using the following command: cat .bash_profile Step 4: Now we are going to check our go path using the following command. If you want to skip this step you can do that also. echo $GOPATH Step 1: Download and install a text editor according to your choice. After installation, create a folder named go(or whatever name you want) in Documents(or wherever you want in your system). In this folder, create another folder named as source and in this source folder create another folder named as welcome. In this folder, all your go programs are going to be stored. Step 2: Let’s create first go program. Open the text editor and write go program as shown below: Step 3: After creating a go program save that program with extension .go. Step 4: Now open terminal to run your first go program. Step 5: Change the directory in which your program is stored. Step 6: After changing directory, run the go program using the following command: go run name_of_the_program.go how-to-install Go Language How To Installation Guide Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Different ways to concatenate two strings in Golang time.Sleep() Function in Golang With Examples strings.Replace() Function in Golang With Examples strings.Contains Function in Golang with Examples fmt.Sprintf() Function in Golang With Examples How to Install PIP on Windows ? How to Find the Wi-Fi Password Using CMD in Windows? How to install Jupyter Notebook on Windows? Java Tutorial How to Align Text in HTML?
[ { "code": null, "e": 28, "s": 0, "text": "\n06 Oct, 2021" }, { "code": null, "e": 1004, "s": 28, "text": "Before, we start with the process of Installing Golang on our System. We must have first-hand knowledge of What the Go Language is and what it actually does? Go is an open-source and statically typed programming language developed in 2007 by Robert Griesemer, Rob Pike, and Ken Thompson at Google but launched in 2009. It is also known as the Golang and it supports the procedural programming language. It was initially developed to improve programming productivity of the large codebases, multicore, and networked machines.Golang programs can be written in any plain text editor like TextEdit, Sublime Text, or anything of that sort. One can also use an online IDE for writing Golang codes or can even install one on their system to make it more feasible to write these codes. Using an IDE makes it easier to write Golang codes because IDEs provide a lot of features like intuitive code editor, debugger, compiler, etc. In this article, we have covered the following topics:" }, { "code": null, "e": 1041, "s": 1004, "text": "Steps for Installing Golang on MacOS" }, { "code": null, "e": 1069, "s": 1041, "text": "Setting up the Go Workspace" }, { "code": null, "e": 1104, "s": 1069, "text": "Executing the First Golang program" }, { "code": null, "e": 1367, "s": 1104, "text": "Step 1: Checking if Go is installed or not. Before we begin with the installation of Go, it is good to check if it might be already installed on your system. To check if your device is preinstalled with Golang or not, just go to the Terminal and run the command:" }, { "code": null, "e": 1378, "s": 1367, "text": "go version" }, { "code": null, "e": 1540, "s": 1378, "text": "If Golang is already installed, it will generate a message with all the details of the Golang version available as shown below, otherwise, it will give an error." }, { "code": null, "e": 1702, "s": 1540, "text": "Step 2: Before starting with the installation process, you need to download it. So for that, all versions of Go for MacOS are available on https://golang.org/dl/" }, { "code": null, "e": 1827, "s": 1702, "text": "Download the Golang according to your system architecture. Here, we have downloaded go1.13.1drawin-amd64.pkg for the system." }, { "code": null, "e": 1898, "s": 1827, "text": "Step 3: After downloading process, install the package on your system:" }, { "code": null, "e": 2237, "s": 1898, "text": "Step 4: After completing the installation processes. Open a program known as Terminal(It is a command-line interface for macOS) to check whether Go install properly or not using the Golang version command. As shown in the below image, here it shows the version information of the Golang which means Go install successfully in your system." }, { "code": null, "e": 2417, "s": 2237, "text": "After successfully installing Go on your system, now we are going to set up the Go workspace. Go workspace is a folder on your computer where all your go code will going to store." }, { "code": null, "e": 2539, "s": 2417, "text": "Step 1: Creating a folder named as Go in documents(or wherever you want in your system) like as shown in the below image:" }, { "code": null, "e": 2684, "s": 2539, "text": "Step 2: Now tell the Go tools to where to find this folder. So for that first of all, you go to your home directory using the following command:" }, { "code": null, "e": 2689, "s": 2684, "text": "cd ~" }, { "code": null, "e": 2752, "s": 2689, "text": "After that set path of the folder using the following command:" }, { "code": null, "e": 2815, "s": 2752, "text": "echo \"export GOPATH=/Users/anki/Documents/go\" >> .bash_profile" }, { "code": null, "e": 3085, "s": 2815, "text": "Here, we are adding export GOPATH=/Users/anki/Documents/go to .bash_profile. The .bash_profile is a file that automatically loaded when you logged into your Mac account and it contains all the startup configurations and preferences for your command-line interface(CLI)." }, { "code": null, "e": 3190, "s": 3085, "text": "Step 3: Now check check that your .bash_profile conatins the following path using the following command:" }, { "code": null, "e": 3208, "s": 3190, "text": "cat .bash_profile" }, { "code": null, "e": 3335, "s": 3208, "text": "Step 4: Now we are going to check our go path using the following command. If you want to skip this step you can do that also." }, { "code": null, "e": 3348, "s": 3335, "text": "echo $GOPATH" }, { "code": null, "e": 3721, "s": 3348, "text": "Step 1: Download and install a text editor according to your choice. After installation, create a folder named go(or whatever name you want) in Documents(or wherever you want in your system). In this folder, create another folder named as source and in this source folder create another folder named as welcome. In this folder, all your go programs are going to be stored." }, { "code": null, "e": 3818, "s": 3721, "text": "Step 2: Let’s create first go program. Open the text editor and write go program as shown below:" }, { "code": null, "e": 3892, "s": 3818, "text": "Step 3: After creating a go program save that program with extension .go." }, { "code": null, "e": 3948, "s": 3892, "text": "Step 4: Now open terminal to run your first go program." }, { "code": null, "e": 4010, "s": 3948, "text": "Step 5: Change the directory in which your program is stored." }, { "code": null, "e": 4092, "s": 4010, "text": "Step 6: After changing directory, run the go program using the following command:" }, { "code": null, "e": 4122, "s": 4092, "text": "go run name_of_the_program.go" }, { "code": null, "e": 4137, "s": 4122, "text": "how-to-install" }, { "code": null, "e": 4149, "s": 4137, "text": "Go Language" }, { "code": null, "e": 4156, "s": 4149, "text": "How To" }, { "code": null, "e": 4175, "s": 4156, "text": "Installation Guide" }, { "code": null, "e": 4273, "s": 4175, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4325, "s": 4273, "text": "Different ways to concatenate two strings in Golang" }, { "code": null, "e": 4371, "s": 4325, "text": "time.Sleep() Function in Golang With Examples" }, { "code": null, "e": 4422, "s": 4371, "text": "strings.Replace() Function in Golang With Examples" }, { "code": null, "e": 4472, "s": 4422, "text": "strings.Contains Function in Golang with Examples" }, { "code": null, "e": 4519, "s": 4472, "text": "fmt.Sprintf() Function in Golang With Examples" }, { "code": null, "e": 4551, "s": 4519, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 4604, "s": 4551, "text": "How to Find the Wi-Fi Password Using CMD in Windows?" }, { "code": null, "e": 4648, "s": 4604, "text": "How to install Jupyter Notebook on Windows?" }, { "code": null, "e": 4662, "s": 4648, "text": "Java Tutorial" } ]
CSS | Combinators
30 Jun, 2021 CSS combinators are explaining the relationship between two selectors. CSS selectors are the patterns used to select the elements for style purpose. A CSS selector can be a simple selector or a complex selector consisting of more than one selector connected using combinators. There are four types of combinators available in CSS which are discussed below: General Sibling selector (~) Adjecant Sibling selector (+) Child selector (>) Descendant selector (space) General Sibling selector: The general sibling selector is used to select the element that follows the first selector element and also share the same parent as the first selector element. This can be used to select a group of elements that share the same parent element. HTML <!DOCTYPE html><html><head> <title>Combinator Property</title> <style> div ~ p{ color: #009900; font-size:32px; font-weight:bold; margin:0px; text-align:center; } div { text-align:center; } </style></head> <body> <div>General sibling selector property</div> <p>GeeksforGeeks</p> <div> <div>child div content</div> <p>G4G</p> </div> <p>Geeks</p> <p>Hello</p> </body></html> Output: Adjacent Sibling selector: The Adjacent sibling selector is used to select the element that is adjacent or the element that is the next to the specified selector tag. This combinator selects only one tag that is just next to the specified tag. html <!DOCTYPE html><html><head> <title>Combinator Property</title> <style> div + p{ color: #009900; font-size:32px; font-weight:bold; margin:0px; text-align:center; } div { text-align:center; } p { text-align:center; } </style></head> <body> <div>Adjacent sibling selector property</div> <p>GeeksforGeeks</p> <div> <div>child div content</div> <p>G4G</p> </div> <p>Geeks</p> <p>Hello</p> </body></html> Output: Child Selector: This selector is used to select the element that is the immediate child of the specified tag. This combinator is stricter than the descendant selector because it selects only the second selector if it has the first selector element as its parent. html <!DOCTYPE html><html><head> <title>Combinator Property</title> <style> div > p{ color: #009900; font-size:32px; font-weight:bold; margin:0px; text-align:center; } div { text-align:center; } p { text-align:center; } </style></head> <body> <div>Child selector property</div> <p>GeeksforGeeks</p> <div> <div>child div content</div> <p>G4G</p> </div> <p>Geeks</p> <p>Hello</p> </body></html> Output: Descendant selector: This selector is used to select all the child elements of the specified tag. The tags can be the direct child of the specified tag or can be very deep in the specified tag. This combinator combines the two selectors such that selected elements have an ancestor same as the first selector element. html <!DOCTYPE html><html><head> <title>Combinator Property</title> <style> div p{ color: #009900; font-size:32px; font-weight:bold; margin:0px; text-align:center; } div { text-align:center; } p { text-align:center; } </style></head> <body> <div>Descendant selector property</div> <p>GeeksforGeeks</p> <div> <div>child div content</div> <p>G4G</p> <p>Descendant selector</p> </div> <p>Geeks</p> <p>Hello</p> </body></html> Output: Supported Browser: Google Chrome Internet Explorer (after IE 7.0) Firefox Opera Safari ysachin2314 CSS-Basics 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": 54, "s": 26, "text": "\n30 Jun, 2021" }, { "code": null, "e": 413, "s": 54, "text": "CSS combinators are explaining the relationship between two selectors. CSS selectors are the patterns used to select the elements for style purpose. A CSS selector can be a simple selector or a complex selector consisting of more than one selector connected using combinators. There are four types of combinators available in CSS which are discussed below: " }, { "code": null, "e": 442, "s": 413, "text": "General Sibling selector (~)" }, { "code": null, "e": 472, "s": 442, "text": "Adjecant Sibling selector (+)" }, { "code": null, "e": 491, "s": 472, "text": "Child selector (>)" }, { "code": null, "e": 519, "s": 491, "text": "Descendant selector (space)" }, { "code": null, "e": 790, "s": 519, "text": "General Sibling selector: The general sibling selector is used to select the element that follows the first selector element and also share the same parent as the first selector element. This can be used to select a group of elements that share the same parent element. " }, { "code": null, "e": 795, "s": 790, "text": "HTML" }, { "code": "<!DOCTYPE html><html><head> <title>Combinator Property</title> <style> div ~ p{ color: #009900; font-size:32px; font-weight:bold; margin:0px; text-align:center; } div { text-align:center; } </style></head> <body> <div>General sibling selector property</div> <p>GeeksforGeeks</p> <div> <div>child div content</div> <p>G4G</p> </div> <p>Geeks</p> <p>Hello</p> </body></html> ", "e": 1329, "s": 795, "text": null }, { "code": null, "e": 1339, "s": 1329, "text": "Output: " }, { "code": null, "e": 1584, "s": 1339, "text": "Adjacent Sibling selector: The Adjacent sibling selector is used to select the element that is adjacent or the element that is the next to the specified selector tag. This combinator selects only one tag that is just next to the specified tag. " }, { "code": null, "e": 1589, "s": 1584, "text": "html" }, { "code": "<!DOCTYPE html><html><head> <title>Combinator Property</title> <style> div + p{ color: #009900; font-size:32px; font-weight:bold; margin:0px; text-align:center; } div { text-align:center; } p { text-align:center; } </style></head> <body> <div>Adjacent sibling selector property</div> <p>GeeksforGeeks</p> <div> <div>child div content</div> <p>G4G</p> </div> <p>Geeks</p> <p>Hello</p> </body></html> ", "e": 2174, "s": 1589, "text": null }, { "code": null, "e": 2184, "s": 2174, "text": "Output: " }, { "code": null, "e": 2449, "s": 2184, "text": "Child Selector: This selector is used to select the element that is the immediate child of the specified tag. This combinator is stricter than the descendant selector because it selects only the second selector if it has the first selector element as its parent. " }, { "code": null, "e": 2454, "s": 2449, "text": "html" }, { "code": "<!DOCTYPE html><html><head> <title>Combinator Property</title> <style> div > p{ color: #009900; font-size:32px; font-weight:bold; margin:0px; text-align:center; } div { text-align:center; } p { text-align:center; } </style></head> <body> <div>Child selector property</div> <p>GeeksforGeeks</p> <div> <div>child div content</div> <p>G4G</p> </div> <p>Geeks</p> <p>Hello</p> </body></html> ", "e": 3028, "s": 2454, "text": null }, { "code": null, "e": 3038, "s": 3028, "text": "Output: " }, { "code": null, "e": 3357, "s": 3038, "text": "Descendant selector: This selector is used to select all the child elements of the specified tag. The tags can be the direct child of the specified tag or can be very deep in the specified tag. This combinator combines the two selectors such that selected elements have an ancestor same as the first selector element. " }, { "code": null, "e": 3362, "s": 3357, "text": "html" }, { "code": "<!DOCTYPE html><html><head> <title>Combinator Property</title> <style> div p{ color: #009900; font-size:32px; font-weight:bold; margin:0px; text-align:center; } div { text-align:center; } p { text-align:center; } </style></head> <body> <div>Descendant selector property</div> <p>GeeksforGeeks</p> <div> <div>child div content</div> <p>G4G</p> <p>Descendant selector</p> </div> <p>Geeks</p> <p>Hello</p> </body></html> ", "e": 3975, "s": 3362, "text": null }, { "code": null, "e": 3985, "s": 3975, "text": "Output: " }, { "code": null, "e": 4004, "s": 3985, "text": "Supported Browser:" }, { "code": null, "e": 4018, "s": 4004, "text": "Google Chrome" }, { "code": null, "e": 4051, "s": 4018, "text": "Internet Explorer (after IE 7.0)" }, { "code": null, "e": 4059, "s": 4051, "text": "Firefox" }, { "code": null, "e": 4065, "s": 4059, "text": "Opera" }, { "code": null, "e": 4072, "s": 4065, "text": "Safari" }, { "code": null, "e": 4084, "s": 4072, "text": "ysachin2314" }, { "code": null, "e": 4095, "s": 4084, "text": "CSS-Basics" }, { "code": null, "e": 4099, "s": 4095, "text": "CSS" }, { "code": null, "e": 4104, "s": 4099, "text": "HTML" }, { "code": null, "e": 4121, "s": 4104, "text": "Web Technologies" }, { "code": null, "e": 4126, "s": 4121, "text": "HTML" }, { "code": null, "e": 4224, "s": 4126, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4272, "s": 4224, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 4334, "s": 4272, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 4384, "s": 4334, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 4442, "s": 4384, "text": "How to create footer to stay at the bottom of a Web page?" }, { "code": null, "e": 4492, "s": 4442, "text": "CSS to put icon inside an input element in a form" }, { "code": null, "e": 4540, "s": 4492, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 4602, "s": 4540, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 4652, "s": 4602, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 4676, "s": 4652, "text": "REST API (Introduction)" } ]
Sum of all subsequences of length K
04 May, 2021 Given an array arr[]and an integer K, the task is to find the sum of all K length subsequences from the given array. Example: Input: arr[] = {2, 3, 4}, K = 2 Output: 18 Explanation: There are 3 possible subsequences of length 2 which are {2, 3}, {2, 4} and {3, 4} The sum of all 2 length subsequences is 5 + 6 + 7 = 18 Input: arr[] = {7, 8, 9, 2}, K = 2 Output: 78 Explanation: There are 6 subsequences of length 2 which are {7, 8}, {7, 9}, {7, 2}, {8, 9}, {8, 2} and {9, 2}. The sum of all 2 length sub sequences is 15 + 16 + 9 + 17 + 10 + 11 = 78 Approach: To solve the problem mentioned above we have to consider all K length subsequence that is “n choose k”, i.e. The count of total element in all K length subsequences is , possibility of appearing of each element is same. So each element appears times and it contributes in the result. Hence, the sum of all K length subsequence is Below is the implementation of the above mentioned approach: C++ Java Python3 C# Javascript // C++ implementation to find sum// of all subsequences of length K #include <bits/stdc++.h>using namespace std; int fact(int n); // Function to find nCrint nCr(int n, int r){ return fact(n) / (fact(r) * fact(n - r));} // Function that returns// factorial of nint fact(int n){ int res = 1; for (int i = 2; i <= n; i++) res = res * i; return res;} // Function for finding sum// of all K length subsequencesint sumSubsequences( int arr[], int n, int k){ int sum = 0; // Calculate the sum of array for (int i = 0; i < n; i++) { sum += arr[i]; } int kLengthSubSequence; // Calculate nCk kLengthSubSequence = nCr(n, k); int ans = sum * ((k * kLengthSubSequence) / n); // Return the final result return ans;} // Driver codeint main(){ int arr[] = { 7, 8, 9, 2 }; int K = 2; int n = sizeof(arr) / sizeof(arr[0]); cout << sumSubsequences(arr, n, K); return 0;} // Java implementation to find sum// of all subsequences of length Kclass GFG{ // Function to find nCrstatic int nCr(int n, int r){ return fact(n) / (fact(r) * fact(n - r));} // Function that returns// factorial of nstatic int fact(int n){ int res = 1; for (int i = 2; i <= n; i++) res = res * i; return res;} // Function for finding sum// of all K length subsequencesstatic int sumSubsequences(int arr[], int n, int k){ int sum = 0; // Calculate the sum of array for (int i = 0; i < n; i++) { sum += arr[i]; } int kLengthSubSequence; // Calculate nCk kLengthSubSequence = nCr(n, k); int ans = sum * ((k * kLengthSubSequence) / n); // Return the final result return ans;} // Driver codepublic static void main(String[] args){ int arr[] = { 7, 8, 9, 2 }; int K = 2; int n = arr.length; System.out.print(sumSubsequences(arr, n, K));}} // This code contributed by Rajput-Ji # Python3 implementation to find sum # of all subsequences of length K # Function to find nCr def nCr(n, r): return fact(n) / (fact(r) * fact(n - r)) # Function that returns # factorial of ndef fact(n): res = 1 for i in range(2, n + 1): res = res * i return res # Function for finding sum # of all K length subsequencesdef sumSubsequences(arr, n, k): sum = 0 # Calculate the sum of array for i in range(0, n): sum = sum + arr[i] # Calculate nCk kLengthSubSequence = nCr(n, k) ans = sum * ((k * kLengthSubSequence) / n); # Return the final result return ans # Driver Code arr = [ 7, 8, 9, 2 ]k = 2n = len(arr) print(sumSubsequences(arr, n, k)) # This code is contributed by skylags // C# implementation to find sum// of all subsequences of length Kusing System; class GFG{ // Function to find nCrstatic int nCr(int n, int r){ return fact(n) / (fact(r) * fact(n - r));} // Function that returns// factorial of nstatic int fact(int n){ int res = 1; for(int i = 2; i <= n; i++) res = res * i; return res;} // Function for finding sum// of all K length subsequencesstatic int sumSubsequences(int[] arr, int n, int k){ int sum = 0; // Calculate the sum of array for(int i = 0; i < n; i++) { sum += arr[i]; } int kLengthSubSequence; // Calculate nCk kLengthSubSequence = nCr(n, k); int ans = sum * ((k * kLengthSubSequence) / n); // Return the final result return ans;} // Driver codestatic void Main() { int[] arr = { 7, 8, 9, 2 }; int K = 2; int n = arr.Length; Console.Write(sumSubsequences(arr, n, K));}} // This code is contributed by divyeshrabadiya07 <script> // Javascript implementation to find sum// of all subsequences of length K // Function to find nCrfunction nCr(n, r){ return fact(n) / (fact(r) * fact(n - r));} // Function that returns// factorial of nfunction fact(n){ var res = 1; for(var i = 2; i <= n; i++) res = res * i; return res;} // Function for finding sum// of all K length subsequencesfunction sumSubsequences(arr, n, k){ var sum = 0; // Calculate the sum of array for(var i = 0; i < n; i++) { sum += arr[i]; } var kLengthSubSequence; // Calculate nCk kLengthSubSequence = nCr(n, k); var ans = sum * ((k * kLengthSubSequence) / n); // Return the final result return ans;} // Driver codevar arr = [ 7, 8, 9, 2 ];var K = 2;var n = arr.length; document.write(sumSubsequences(arr, n, K)); // This code is contributed by noob2000 </script> 78 skylags Rajput-Ji divyeshrabadiya07 nidhi_biet noob2000 Permutation and Combination subsequence Arrays Combinatorial Mathematical Arrays Mathematical Combinatorial Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Count of subarrays with average K Introduction to Data Structures Window Sliding Technique Find subarray with given sum | Set 1 (Nonnegative Numbers) Next Greater Element Write a program to print all permutations of a given string Permutation and Combination in Python Program to calculate value of nCr Count of subsets with sum equal to X itertools.combinations() module in Python to print all possible combinations
[ { "code": null, "e": 52, "s": 24, "text": "\n04 May, 2021" }, { "code": null, "e": 169, "s": 52, "text": "Given an array arr[]and an integer K, the task is to find the sum of all K length subsequences from the given array." }, { "code": null, "e": 179, "s": 169, "text": "Example: " }, { "code": null, "e": 372, "s": 179, "text": "Input: arr[] = {2, 3, 4}, K = 2 Output: 18 Explanation: There are 3 possible subsequences of length 2 which are {2, 3}, {2, 4} and {3, 4} The sum of all 2 length subsequences is 5 + 6 + 7 = 18" }, { "code": null, "e": 604, "s": 372, "text": "Input: arr[] = {7, 8, 9, 2}, K = 2 Output: 78 Explanation: There are 6 subsequences of length 2 which are {7, 8}, {7, 9}, {7, 2}, {8, 9}, {8, 2} and {9, 2}. The sum of all 2 length sub sequences is 15 + 16 + 9 + 17 + 10 + 11 = 78 " }, { "code": null, "e": 724, "s": 604, "text": "Approach: To solve the problem mentioned above we have to consider all K length subsequence that is “n choose k”, i.e. " }, { "code": null, "e": 835, "s": 724, "text": "The count of total element in all K length subsequences is , possibility of appearing of each element is same." }, { "code": null, "e": 900, "s": 835, "text": "So each element appears times and it contributes in the result." }, { "code": null, "e": 947, "s": 900, "text": "Hence, the sum of all K length subsequence is " }, { "code": null, "e": 1009, "s": 947, "text": "Below is the implementation of the above mentioned approach: " }, { "code": null, "e": 1013, "s": 1009, "text": "C++" }, { "code": null, "e": 1018, "s": 1013, "text": "Java" }, { "code": null, "e": 1026, "s": 1018, "text": "Python3" }, { "code": null, "e": 1029, "s": 1026, "text": "C#" }, { "code": null, "e": 1040, "s": 1029, "text": "Javascript" }, { "code": "// C++ implementation to find sum// of all subsequences of length K #include <bits/stdc++.h>using namespace std; int fact(int n); // Function to find nCrint nCr(int n, int r){ return fact(n) / (fact(r) * fact(n - r));} // Function that returns// factorial of nint fact(int n){ int res = 1; for (int i = 2; i <= n; i++) res = res * i; return res;} // Function for finding sum// of all K length subsequencesint sumSubsequences( int arr[], int n, int k){ int sum = 0; // Calculate the sum of array for (int i = 0; i < n; i++) { sum += arr[i]; } int kLengthSubSequence; // Calculate nCk kLengthSubSequence = nCr(n, k); int ans = sum * ((k * kLengthSubSequence) / n); // Return the final result return ans;} // Driver codeint main(){ int arr[] = { 7, 8, 9, 2 }; int K = 2; int n = sizeof(arr) / sizeof(arr[0]); cout << sumSubsequences(arr, n, K); return 0;}", "e": 2042, "s": 1040, "text": null }, { "code": "// Java implementation to find sum// of all subsequences of length Kclass GFG{ // Function to find nCrstatic int nCr(int n, int r){ return fact(n) / (fact(r) * fact(n - r));} // Function that returns// factorial of nstatic int fact(int n){ int res = 1; for (int i = 2; i <= n; i++) res = res * i; return res;} // Function for finding sum// of all K length subsequencesstatic int sumSubsequences(int arr[], int n, int k){ int sum = 0; // Calculate the sum of array for (int i = 0; i < n; i++) { sum += arr[i]; } int kLengthSubSequence; // Calculate nCk kLengthSubSequence = nCr(n, k); int ans = sum * ((k * kLengthSubSequence) / n); // Return the final result return ans;} // Driver codepublic static void main(String[] args){ int arr[] = { 7, 8, 9, 2 }; int K = 2; int n = arr.length; System.out.print(sumSubsequences(arr, n, K));}} // This code contributed by Rajput-Ji", "e": 3031, "s": 2042, "text": null }, { "code": "# Python3 implementation to find sum # of all subsequences of length K # Function to find nCr def nCr(n, r): return fact(n) / (fact(r) * fact(n - r)) # Function that returns # factorial of ndef fact(n): res = 1 for i in range(2, n + 1): res = res * i return res # Function for finding sum # of all K length subsequencesdef sumSubsequences(arr, n, k): sum = 0 # Calculate the sum of array for i in range(0, n): sum = sum + arr[i] # Calculate nCk kLengthSubSequence = nCr(n, k) ans = sum * ((k * kLengthSubSequence) / n); # Return the final result return ans # Driver Code arr = [ 7, 8, 9, 2 ]k = 2n = len(arr) print(sumSubsequences(arr, n, k)) # This code is contributed by skylags ", "e": 3842, "s": 3031, "text": null }, { "code": "// C# implementation to find sum// of all subsequences of length Kusing System; class GFG{ // Function to find nCrstatic int nCr(int n, int r){ return fact(n) / (fact(r) * fact(n - r));} // Function that returns// factorial of nstatic int fact(int n){ int res = 1; for(int i = 2; i <= n; i++) res = res * i; return res;} // Function for finding sum// of all K length subsequencesstatic int sumSubsequences(int[] arr, int n, int k){ int sum = 0; // Calculate the sum of array for(int i = 0; i < n; i++) { sum += arr[i]; } int kLengthSubSequence; // Calculate nCk kLengthSubSequence = nCr(n, k); int ans = sum * ((k * kLengthSubSequence) / n); // Return the final result return ans;} // Driver codestatic void Main() { int[] arr = { 7, 8, 9, 2 }; int K = 2; int n = arr.Length; Console.Write(sumSubsequences(arr, n, K));}} // This code is contributed by divyeshrabadiya07", "e": 4867, "s": 3842, "text": null }, { "code": "<script> // Javascript implementation to find sum// of all subsequences of length K // Function to find nCrfunction nCr(n, r){ return fact(n) / (fact(r) * fact(n - r));} // Function that returns// factorial of nfunction fact(n){ var res = 1; for(var i = 2; i <= n; i++) res = res * i; return res;} // Function for finding sum// of all K length subsequencesfunction sumSubsequences(arr, n, k){ var sum = 0; // Calculate the sum of array for(var i = 0; i < n; i++) { sum += arr[i]; } var kLengthSubSequence; // Calculate nCk kLengthSubSequence = nCr(n, k); var ans = sum * ((k * kLengthSubSequence) / n); // Return the final result return ans;} // Driver codevar arr = [ 7, 8, 9, 2 ];var K = 2;var n = arr.length; document.write(sumSubsequences(arr, n, K)); // This code is contributed by noob2000 </script>", "e": 5783, "s": 4867, "text": null }, { "code": null, "e": 5786, "s": 5783, "text": "78" }, { "code": null, "e": 5796, "s": 5788, "text": "skylags" }, { "code": null, "e": 5806, "s": 5796, "text": "Rajput-Ji" }, { "code": null, "e": 5824, "s": 5806, "text": "divyeshrabadiya07" }, { "code": null, "e": 5835, "s": 5824, "text": "nidhi_biet" }, { "code": null, "e": 5844, "s": 5835, "text": "noob2000" }, { "code": null, "e": 5872, "s": 5844, "text": "Permutation and Combination" }, { "code": null, "e": 5884, "s": 5872, "text": "subsequence" }, { "code": null, "e": 5891, "s": 5884, "text": "Arrays" }, { "code": null, "e": 5905, "s": 5891, "text": "Combinatorial" }, { "code": null, "e": 5918, "s": 5905, "text": "Mathematical" }, { "code": null, "e": 5925, "s": 5918, "text": "Arrays" }, { "code": null, "e": 5938, "s": 5925, "text": "Mathematical" }, { "code": null, "e": 5952, "s": 5938, "text": "Combinatorial" }, { "code": null, "e": 6050, "s": 5952, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6084, "s": 6050, "text": "Count of subarrays with average K" }, { "code": null, "e": 6116, "s": 6084, "text": "Introduction to Data Structures" }, { "code": null, "e": 6141, "s": 6116, "text": "Window Sliding Technique" }, { "code": null, "e": 6200, "s": 6141, "text": "Find subarray with given sum | Set 1 (Nonnegative Numbers)" }, { "code": null, "e": 6221, "s": 6200, "text": "Next Greater Element" }, { "code": null, "e": 6281, "s": 6221, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 6319, "s": 6281, "text": "Permutation and Combination in Python" }, { "code": null, "e": 6353, "s": 6319, "text": "Program to calculate value of nCr" }, { "code": null, "e": 6390, "s": 6353, "text": "Count of subsets with sum equal to X" } ]
Regex - reusing patterns to capture groups in JavaScript?
For this, use regular expression with digit along with $. var groupValues1 = "10 10 10"; var groupValues2 = "10 10 10 10"; var groupValues3 = "10 10"; var regularExpression = /^(\d+)(\s)\1\2\1$/; var isValidGroup1 = regularExpression.test(groupValues1); var isValidGroup2 = regularExpression.test(groupValues2); var isValidGroup3 = regularExpression.test(groupValues3); if(isValidGroup1==true) console.log("This is a valid group="+groupValues1); else console.log("This is not a valid group="+groupValues1); if(isValidGroup2==true) console.log("This is a valid group="+groupValues2); else console.log("This is not a valid group="+groupValues2); if(isValidGroup3==true) console.log("This is a valid group="+groupValues3); else console.log("This is not a valid group="+groupValues3); To run the above program, you need to use the following command − node fileName.js. Here, my file name is demo188.js. The below output matches only groups 3. This will produce the following output − PS C:\Users\Amit\javascript-code> node demo188.js This is a valid group=10 10 10 This is not a valid group=10 10 10 10 This is not a valid group=10 10
[ { "code": null, "e": 1245, "s": 1187, "text": "For this, use regular expression with digit along with $." }, { "code": null, "e": 1986, "s": 1245, "text": "var groupValues1 = \"10 10 10\";\nvar groupValues2 = \"10 10 10 10\";\nvar groupValues3 = \"10 10\";\nvar regularExpression = /^(\\d+)(\\s)\\1\\2\\1$/;\nvar isValidGroup1 = regularExpression.test(groupValues1);\nvar isValidGroup2 = regularExpression.test(groupValues2);\nvar isValidGroup3 = regularExpression.test(groupValues3);\nif(isValidGroup1==true)\n console.log(\"This is a valid group=\"+groupValues1);\nelse\n console.log(\"This is not a valid group=\"+groupValues1);\nif(isValidGroup2==true)\n console.log(\"This is a valid group=\"+groupValues2);\nelse\n console.log(\"This is not a valid group=\"+groupValues2);\nif(isValidGroup3==true)\n console.log(\"This is a valid group=\"+groupValues3);\nelse\n console.log(\"This is not a valid group=\"+groupValues3);" }, { "code": null, "e": 2052, "s": 1986, "text": "To run the above program, you need to use the following command −" }, { "code": null, "e": 2070, "s": 2052, "text": "node fileName.js." }, { "code": null, "e": 2104, "s": 2070, "text": "Here, my file name is demo188.js." }, { "code": null, "e": 2185, "s": 2104, "text": "The below output matches only groups 3. This will produce the following output −" }, { "code": null, "e": 2336, "s": 2185, "text": "PS C:\\Users\\Amit\\javascript-code> node demo188.js\nThis is a valid group=10 10 10\nThis is not a valid group=10 10 10 10\nThis is not a valid group=10 10" } ]
LocalDate getMonth() method in Java
28 Nov, 2018 The getMonth() method of LocalDate class in Java gets the month-of-year field using the Month enum. Syntax: public Month getMonth() Parameter: This method does not accepts any parameter. Return Value: The function returns the month of the year. Below programs illustrate the getMonth() method of LocalDate in Java:Program 1: // Program to illustrate the getMonth() method import java.util.*;import java.time.*; public class GfG { public static void main(String[] args) { // Parses the date LocalDate dt = LocalDate.parse("2018-11-27"); // Prints the day number System.out.println(dt.getMonth()); }} NOVEMBER Program 2: // Program to illustrate the getMonth() method import java.util.*;import java.time.*; public class GfG { public static void main(String[] args) { // Parses the date LocalDate dt = LocalDate.parse("2018-01-02"); // Prints the day number System.out.println(dt.getMonth()); }} JANUARY Reference: https://docs.oracle.com/javase/10/docs/api/java/time/LocalDate.html#getMonth() Java-Functions Java-LocalDate Java-time package Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n28 Nov, 2018" }, { "code": null, "e": 128, "s": 28, "text": "The getMonth() method of LocalDate class in Java gets the month-of-year field using the Month enum." }, { "code": null, "e": 136, "s": 128, "text": "Syntax:" }, { "code": null, "e": 161, "s": 136, "text": "public Month getMonth()\n" }, { "code": null, "e": 216, "s": 161, "text": "Parameter: This method does not accepts any parameter." }, { "code": null, "e": 274, "s": 216, "text": "Return Value: The function returns the month of the year." }, { "code": null, "e": 354, "s": 274, "text": "Below programs illustrate the getMonth() method of LocalDate in Java:Program 1:" }, { "code": "// Program to illustrate the getMonth() method import java.util.*;import java.time.*; public class GfG { public static void main(String[] args) { // Parses the date LocalDate dt = LocalDate.parse(\"2018-11-27\"); // Prints the day number System.out.println(dt.getMonth()); }}", "e": 669, "s": 354, "text": null }, { "code": null, "e": 679, "s": 669, "text": "NOVEMBER\n" }, { "code": null, "e": 690, "s": 679, "text": "Program 2:" }, { "code": "// Program to illustrate the getMonth() method import java.util.*;import java.time.*; public class GfG { public static void main(String[] args) { // Parses the date LocalDate dt = LocalDate.parse(\"2018-01-02\"); // Prints the day number System.out.println(dt.getMonth()); }}", "e": 1005, "s": 690, "text": null }, { "code": null, "e": 1014, "s": 1005, "text": "JANUARY\n" }, { "code": null, "e": 1104, "s": 1014, "text": "Reference: https://docs.oracle.com/javase/10/docs/api/java/time/LocalDate.html#getMonth()" }, { "code": null, "e": 1119, "s": 1104, "text": "Java-Functions" }, { "code": null, "e": 1134, "s": 1119, "text": "Java-LocalDate" }, { "code": null, "e": 1152, "s": 1134, "text": "Java-time package" }, { "code": null, "e": 1157, "s": 1152, "text": "Java" }, { "code": null, "e": 1162, "s": 1157, "text": "Java" } ]
C# | Data Types
18 Jun, 2020 Data types specify the type of data that a valid C# variable can hold. C# is a strongly typed programming language because in C#, each type of data (such as integer, character, float, and so forth) is predefined as part of the programming language and all constants or variables defined for a given program must be described with one of the data types. Data types in C# is mainly divided into three categories Value Data Types Reference Data Types Pointer Data Type Value Data Types : In C#, the Value Data Types will directly store the variable value in memory and it will also accept both signed and unsigned literals. The derived class for these data types are System.ValueType. Following are different Value Data Types in C# programming language :Signed & Unsigned Integral Types : There are 8 integral types which provide support for 8-bit, 16-bit, 32-bit, and 64-bit values in signed or unsigned form.AliasType NameTypeSize(bits)RangeDefault ValuesbyteSystem.Sbytesigned integer8-128 to 1270shortSystem.Int16signed integer16-32768 to 327670IntSystem.Int32signed integer32-231 to 231-10longSystem.Int64signed integer64-263 to 263-10LbyteSystem.byteunsigned integer80 to 2550ushortSystem.UInt16unsigned integer160 to 655350uintSystem.UInt32unsigned integer320 to 2320ulongSystem.UInt64unsigned integer640 to 2630Floating Point Types :There are 2 floating point data types which contain the decimal point.Float: It is 32-bit single-precision floating point type. It has 7 digit Precision. To initialize a float variable, use the suffix f or F. Like, float x = 3.5F;. If the suffix F or f will not use then it is treated as double.Double:It is 64-bit double-precision floating point type. It has 14 – 15 digit Precision. To initialize a double variable, use the suffix d or D. But it is not mandatory to use suffix because by default floating data types are the double type.AliasType nameSize(bits)Range (aprox)Default ValuefloatSystem.Single32±1.5 × 10-45 to ±3.4 × 10380.0FdoubleSystem.Double64±5.0 × 10-324 to ±1.7 × 103080.0DDecimal Types : The decimal type is a 128-bit data type suitable for financial and monetary calculations. It has 28-29 digit Precision. To initialize a decimal variable, use the suffix m or M. Like as, decimal x = 300.5m;. If the suffix m or M will not use then it is treated as double.AliasType nameSize(bits)Range (aprox)Default valuedecimalSystem.Decimal128±1.0 × 10-28 to ±7.9228 × 10280.0MCharacter Types : The character types represents a UTF-16 code unit or represents the 16-bit Unicode character.AliasType nameSize In(Bits)RangeDefault valuecharSystem.Char16U +0000 to U +ffff‘\0’Example :// C# program to demonstrate // the above data typesusing System;namespace ValueTypeTest { class GeeksforGeeks { // Main function static void Main() { // declaring character char a = 'G'; // Integer data type is generally // used for numeric values int i = 89; short s = 56; // this will give error as number // is larger than short range // short s1 = 87878787878; // long uses Integer values which // may signed or unsigned long l = 4564; // UInt data type is generally // used for unsigned integer values uint ui = 95; ushort us = 76; // this will give error as number is // larger than short range // ulong data type is generally // used for unsigned integer values ulong ul = 3624573; // by default fraction value // is double in C# double d = 8.358674532; // for float use 'f' as suffix float f = 3.7330645f; // for float use 'm' as suffix decimal dec = 389.5m; Console.WriteLine("char: " + a); Console.WriteLine("integer: " + i); Console.WriteLine("short: " + s); Console.WriteLine("long: " + l); Console.WriteLine("float: " + f); Console.WriteLine("double: " + d); Console.WriteLine("decimal: " + dec); Console.WriteLine("Unsinged integer: " + ui); Console.WriteLine("Unsinged short: " + us); Console.WriteLine("Unsinged long: " + ul); }}}Output :char: G integer: 89 short: 56 long: 4564 float: 3.733064 double: 8.358674532 decimal: 389.5 Unsinged integer: 95 Unsinged short: 76 Unsinged long: 3624573 Example :// C# program to demonstrate the Sbyte// signed integral data typeusing System;namespace ValueTypeTest { class GeeksforGeeks { // Main function static void Main() { sbyte a = 126; // sbyte is 8 bit // singned value Console.WriteLine(a); a++; Console.WriteLine(a); // It overflows here because // byte can hold values // from -128 to 127 a++; Console.WriteLine(a); // Looping back within // the range a++; Console.WriteLine(a); }}}Output :126 127 -128 -127 Example :// C# program to demonstrate // the byte data typeusing System;namespace ValueTypeTest { class GeeksforGeeks { // Main function static void Main() { byte a = 0; // byte is 8 bit // unsigned value Console.WriteLine(a); a++; Console.WriteLine(a); a = 254; // It overflows here because // byte can hold values from // 0 to 255 a++; Console.WriteLine(a); // Looping back within the range a++; Console.WriteLine(a); }}}Output :0 1 255 0 Boolean Types : It has to be assigned either true or false value. Values of type bool are not converted implicitly or explicitly (with casts) to any other type. But the programmer can easily write conversion code.AliasType nameValuesboolSystem.BooleanTrue / FalseExample :// C# program to demonstrate the// boolean data typeusing System;namespace ValueTypeTest { class GeeksforGeeks { // Main function static void Main() { // boolean data type bool b = true; if (b == true) Console.WriteLine("Hi Geek"); } }}Output :Hi Geek Reference Data Types : The Reference Data Types will contain a memory address of variable value because the reference types won’t store the variable value directly in memory. The built-in reference types are string, object.String : It represents a sequence of Unicode characters and its type name is System.String. So, string and String are equivalent.Example :string s1 = "hello"; // creating through string keyword String s2 = "welcome"; // creating through String class Object : In C#, all types, predefined and user-defined, reference types and value types, inherit directly or indirectly from Object. So basically it is the base class for all the data types in C#. Before assigning values, it needs type conversion. When a variable of a value type is converted to object, it’s called boxing. When a variable of type object is converted to a value type, it’s called unboxing. Its type name is System.Object.Example :// C# program to demonstrate // the Reference data typesusing System;namespace ValueTypeTest { class GeeksforGeeks { // Main Function static void Main() { // declaring string string a = "Geeks"; //append in a a+="for"; a = a+"Geeks"; Console.WriteLine(a); // declare object obj object obj; obj = 20; Console.WriteLine(obj); // to show type of object // using GetType() Console.WriteLine(obj.GetType()); } }}Output :GeeksforGeeks 20 System.Int32 Pointer Data Type : The Pointer Data Types will contain a memory address of the variable value.To get the pointer details we have a two symbols ampersand (&) and asterisk (*).ampersand (&): It is Known as Address Operator. It is used to determine the address of a variable.asterisk (*): It also known as Indirection Operator. It is used to access the value of an address.Syntax :type* identifier; Example :int* p1, p; // Valid syntax int *p1, *p; // Invalid Example :// Note: This program will not work on// online compiler// Error: Unsafe code requires the `unsafe' // command line option to be specified// For its solution:// Go to your project properties page and// check under Build the checkbox Allow// unsafe code.using System;namespace Pointerprogram { class GFG { // Main function static void Main() { unsafe { // declare variable int n = 10; // store variable n address // location in pointer variable p int* p = &n; Console.WriteLine("Value :{0}", n); Console.WriteLine("Address :{0}", (int)p); } }}} Value Data Types : In C#, the Value Data Types will directly store the variable value in memory and it will also accept both signed and unsigned literals. The derived class for these data types are System.ValueType. Following are different Value Data Types in C# programming language :Signed & Unsigned Integral Types : There are 8 integral types which provide support for 8-bit, 16-bit, 32-bit, and 64-bit values in signed or unsigned form.AliasType NameTypeSize(bits)RangeDefault ValuesbyteSystem.Sbytesigned integer8-128 to 1270shortSystem.Int16signed integer16-32768 to 327670IntSystem.Int32signed integer32-231 to 231-10longSystem.Int64signed integer64-263 to 263-10LbyteSystem.byteunsigned integer80 to 2550ushortSystem.UInt16unsigned integer160 to 655350uintSystem.UInt32unsigned integer320 to 2320ulongSystem.UInt64unsigned integer640 to 2630Floating Point Types :There are 2 floating point data types which contain the decimal point.Float: It is 32-bit single-precision floating point type. It has 7 digit Precision. To initialize a float variable, use the suffix f or F. Like, float x = 3.5F;. If the suffix F or f will not use then it is treated as double.Double:It is 64-bit double-precision floating point type. It has 14 – 15 digit Precision. To initialize a double variable, use the suffix d or D. But it is not mandatory to use suffix because by default floating data types are the double type.AliasType nameSize(bits)Range (aprox)Default ValuefloatSystem.Single32±1.5 × 10-45 to ±3.4 × 10380.0FdoubleSystem.Double64±5.0 × 10-324 to ±1.7 × 103080.0DDecimal Types : The decimal type is a 128-bit data type suitable for financial and monetary calculations. It has 28-29 digit Precision. To initialize a decimal variable, use the suffix m or M. Like as, decimal x = 300.5m;. If the suffix m or M will not use then it is treated as double.AliasType nameSize(bits)Range (aprox)Default valuedecimalSystem.Decimal128±1.0 × 10-28 to ±7.9228 × 10280.0MCharacter Types : The character types represents a UTF-16 code unit or represents the 16-bit Unicode character.AliasType nameSize In(Bits)RangeDefault valuecharSystem.Char16U +0000 to U +ffff‘\0’Example :// C# program to demonstrate // the above data typesusing System;namespace ValueTypeTest { class GeeksforGeeks { // Main function static void Main() { // declaring character char a = 'G'; // Integer data type is generally // used for numeric values int i = 89; short s = 56; // this will give error as number // is larger than short range // short s1 = 87878787878; // long uses Integer values which // may signed or unsigned long l = 4564; // UInt data type is generally // used for unsigned integer values uint ui = 95; ushort us = 76; // this will give error as number is // larger than short range // ulong data type is generally // used for unsigned integer values ulong ul = 3624573; // by default fraction value // is double in C# double d = 8.358674532; // for float use 'f' as suffix float f = 3.7330645f; // for float use 'm' as suffix decimal dec = 389.5m; Console.WriteLine("char: " + a); Console.WriteLine("integer: " + i); Console.WriteLine("short: " + s); Console.WriteLine("long: " + l); Console.WriteLine("float: " + f); Console.WriteLine("double: " + d); Console.WriteLine("decimal: " + dec); Console.WriteLine("Unsinged integer: " + ui); Console.WriteLine("Unsinged short: " + us); Console.WriteLine("Unsinged long: " + ul); }}}Output :char: G integer: 89 short: 56 long: 4564 float: 3.733064 double: 8.358674532 decimal: 389.5 Unsinged integer: 95 Unsinged short: 76 Unsinged long: 3624573 Example :// C# program to demonstrate the Sbyte// signed integral data typeusing System;namespace ValueTypeTest { class GeeksforGeeks { // Main function static void Main() { sbyte a = 126; // sbyte is 8 bit // singned value Console.WriteLine(a); a++; Console.WriteLine(a); // It overflows here because // byte can hold values // from -128 to 127 a++; Console.WriteLine(a); // Looping back within // the range a++; Console.WriteLine(a); }}}Output :126 127 -128 -127 Example :// C# program to demonstrate // the byte data typeusing System;namespace ValueTypeTest { class GeeksforGeeks { // Main function static void Main() { byte a = 0; // byte is 8 bit // unsigned value Console.WriteLine(a); a++; Console.WriteLine(a); a = 254; // It overflows here because // byte can hold values from // 0 to 255 a++; Console.WriteLine(a); // Looping back within the range a++; Console.WriteLine(a); }}}Output :0 1 255 0 Boolean Types : It has to be assigned either true or false value. Values of type bool are not converted implicitly or explicitly (with casts) to any other type. But the programmer can easily write conversion code.AliasType nameValuesboolSystem.BooleanTrue / FalseExample :// C# program to demonstrate the// boolean data typeusing System;namespace ValueTypeTest { class GeeksforGeeks { // Main function static void Main() { // boolean data type bool b = true; if (b == true) Console.WriteLine("Hi Geek"); } }}Output :Hi Geek Signed & Unsigned Integral Types : There are 8 integral types which provide support for 8-bit, 16-bit, 32-bit, and 64-bit values in signed or unsigned form.AliasType NameTypeSize(bits)RangeDefault ValuesbyteSystem.Sbytesigned integer8-128 to 1270shortSystem.Int16signed integer16-32768 to 327670IntSystem.Int32signed integer32-231 to 231-10longSystem.Int64signed integer64-263 to 263-10LbyteSystem.byteunsigned integer80 to 2550ushortSystem.UInt16unsigned integer160 to 655350uintSystem.UInt32unsigned integer320 to 2320ulongSystem.UInt64unsigned integer640 to 2630 Floating Point Types :There are 2 floating point data types which contain the decimal point.Float: It is 32-bit single-precision floating point type. It has 7 digit Precision. To initialize a float variable, use the suffix f or F. Like, float x = 3.5F;. If the suffix F or f will not use then it is treated as double.Double:It is 64-bit double-precision floating point type. It has 14 – 15 digit Precision. To initialize a double variable, use the suffix d or D. But it is not mandatory to use suffix because by default floating data types are the double type.AliasType nameSize(bits)Range (aprox)Default ValuefloatSystem.Single32±1.5 × 10-45 to ±3.4 × 10380.0FdoubleSystem.Double64±5.0 × 10-324 to ±1.7 × 103080.0D Floating Point Types :There are 2 floating point data types which contain the decimal point. Float: It is 32-bit single-precision floating point type. It has 7 digit Precision. To initialize a float variable, use the suffix f or F. Like, float x = 3.5F;. If the suffix F or f will not use then it is treated as double. Double:It is 64-bit double-precision floating point type. It has 14 – 15 digit Precision. To initialize a double variable, use the suffix d or D. But it is not mandatory to use suffix because by default floating data types are the double type. Decimal Types : The decimal type is a 128-bit data type suitable for financial and monetary calculations. It has 28-29 digit Precision. To initialize a decimal variable, use the suffix m or M. Like as, decimal x = 300.5m;. If the suffix m or M will not use then it is treated as double.AliasType nameSize(bits)Range (aprox)Default valuedecimalSystem.Decimal128±1.0 × 10-28 to ±7.9228 × 10280.0M Character Types : The character types represents a UTF-16 code unit or represents the 16-bit Unicode character.AliasType nameSize In(Bits)RangeDefault valuecharSystem.Char16U +0000 to U +ffff‘\0’ Example : // C# program to demonstrate // the above data typesusing System;namespace ValueTypeTest { class GeeksforGeeks { // Main function static void Main() { // declaring character char a = 'G'; // Integer data type is generally // used for numeric values int i = 89; short s = 56; // this will give error as number // is larger than short range // short s1 = 87878787878; // long uses Integer values which // may signed or unsigned long l = 4564; // UInt data type is generally // used for unsigned integer values uint ui = 95; ushort us = 76; // this will give error as number is // larger than short range // ulong data type is generally // used for unsigned integer values ulong ul = 3624573; // by default fraction value // is double in C# double d = 8.358674532; // for float use 'f' as suffix float f = 3.7330645f; // for float use 'm' as suffix decimal dec = 389.5m; Console.WriteLine("char: " + a); Console.WriteLine("integer: " + i); Console.WriteLine("short: " + s); Console.WriteLine("long: " + l); Console.WriteLine("float: " + f); Console.WriteLine("double: " + d); Console.WriteLine("decimal: " + dec); Console.WriteLine("Unsinged integer: " + ui); Console.WriteLine("Unsinged short: " + us); Console.WriteLine("Unsinged long: " + ul); }}} Output : char: G integer: 89 short: 56 long: 4564 float: 3.733064 double: 8.358674532 decimal: 389.5 Unsinged integer: 95 Unsinged short: 76 Unsinged long: 3624573 Example : // C# program to demonstrate the Sbyte// signed integral data typeusing System;namespace ValueTypeTest { class GeeksforGeeks { // Main function static void Main() { sbyte a = 126; // sbyte is 8 bit // singned value Console.WriteLine(a); a++; Console.WriteLine(a); // It overflows here because // byte can hold values // from -128 to 127 a++; Console.WriteLine(a); // Looping back within // the range a++; Console.WriteLine(a); }}} Output : 126 127 -128 -127 Example : // C# program to demonstrate // the byte data typeusing System;namespace ValueTypeTest { class GeeksforGeeks { // Main function static void Main() { byte a = 0; // byte is 8 bit // unsigned value Console.WriteLine(a); a++; Console.WriteLine(a); a = 254; // It overflows here because // byte can hold values from // 0 to 255 a++; Console.WriteLine(a); // Looping back within the range a++; Console.WriteLine(a); }}} Output : 0 1 255 0 Boolean Types : It has to be assigned either true or false value. Values of type bool are not converted implicitly or explicitly (with casts) to any other type. But the programmer can easily write conversion code.AliasType nameValuesboolSystem.BooleanTrue / FalseExample :// C# program to demonstrate the// boolean data typeusing System;namespace ValueTypeTest { class GeeksforGeeks { // Main function static void Main() { // boolean data type bool b = true; if (b == true) Console.WriteLine("Hi Geek"); } }}Output :Hi Geek Example : // C# program to demonstrate the// boolean data typeusing System;namespace ValueTypeTest { class GeeksforGeeks { // Main function static void Main() { // boolean data type bool b = true; if (b == true) Console.WriteLine("Hi Geek"); } }} Output : Hi Geek Reference Data Types : The Reference Data Types will contain a memory address of variable value because the reference types won’t store the variable value directly in memory. The built-in reference types are string, object.String : It represents a sequence of Unicode characters and its type name is System.String. So, string and String are equivalent.Example :string s1 = "hello"; // creating through string keyword String s2 = "welcome"; // creating through String class Object : In C#, all types, predefined and user-defined, reference types and value types, inherit directly or indirectly from Object. So basically it is the base class for all the data types in C#. Before assigning values, it needs type conversion. When a variable of a value type is converted to object, it’s called boxing. When a variable of type object is converted to a value type, it’s called unboxing. Its type name is System.Object.Example :// C# program to demonstrate // the Reference data typesusing System;namespace ValueTypeTest { class GeeksforGeeks { // Main Function static void Main() { // declaring string string a = "Geeks"; //append in a a+="for"; a = a+"Geeks"; Console.WriteLine(a); // declare object obj object obj; obj = 20; Console.WriteLine(obj); // to show type of object // using GetType() Console.WriteLine(obj.GetType()); } }}Output :GeeksforGeeks 20 System.Int32 String : It represents a sequence of Unicode characters and its type name is System.String. So, string and String are equivalent.Example :string s1 = "hello"; // creating through string keyword String s2 = "welcome"; // creating through String class string s1 = "hello"; // creating through string keyword String s2 = "welcome"; // creating through String class Object : In C#, all types, predefined and user-defined, reference types and value types, inherit directly or indirectly from Object. So basically it is the base class for all the data types in C#. Before assigning values, it needs type conversion. When a variable of a value type is converted to object, it’s called boxing. When a variable of type object is converted to a value type, it’s called unboxing. Its type name is System.Object. Example : // C# program to demonstrate // the Reference data typesusing System;namespace ValueTypeTest { class GeeksforGeeks { // Main Function static void Main() { // declaring string string a = "Geeks"; //append in a a+="for"; a = a+"Geeks"; Console.WriteLine(a); // declare object obj object obj; obj = 20; Console.WriteLine(obj); // to show type of object // using GetType() Console.WriteLine(obj.GetType()); } }} Output : GeeksforGeeks 20 System.Int32 Pointer Data Type : The Pointer Data Types will contain a memory address of the variable value.To get the pointer details we have a two symbols ampersand (&) and asterisk (*).ampersand (&): It is Known as Address Operator. It is used to determine the address of a variable.asterisk (*): It also known as Indirection Operator. It is used to access the value of an address.Syntax :type* identifier; Example :int* p1, p; // Valid syntax int *p1, *p; // Invalid Example :// Note: This program will not work on// online compiler// Error: Unsafe code requires the `unsafe' // command line option to be specified// For its solution:// Go to your project properties page and// check under Build the checkbox Allow// unsafe code.using System;namespace Pointerprogram { class GFG { // Main function static void Main() { unsafe { // declare variable int n = 10; // store variable n address // location in pointer variable p int* p = &n; Console.WriteLine("Value :{0}", n); Console.WriteLine("Address :{0}", (int)p); } }}} type* identifier; Example : int* p1, p; // Valid syntax int *p1, *p; // Invalid Example : // Note: This program will not work on// online compiler// Error: Unsafe code requires the `unsafe' // command line option to be specified// For its solution:// Go to your project properties page and// check under Build the checkbox Allow// unsafe code.using System;namespace Pointerprogram { class GFG { // Main function static void Main() { unsafe { // declare variable int n = 10; // store variable n address // location in pointer variable p int* p = &n; Console.WriteLine("Value :{0}", n); Console.WriteLine("Address :{0}", (int)p); } }}} AlokSingh9 CSharp-Basics CSharp-data-types C# Programming Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between Abstract Class and Interface in C# C# | How to check whether a List contains a specified element C# | Multiple inheritance using interfaces C# | Arrays of Strings C# | IsNullOrEmpty() Method Differences between Procedural and Object Oriented Programming Arrow operator -> in C/C++ with Examples Modulo Operator (%) in C/C++ with Examples Structures in C++ Decorators with parameters in Python
[ { "code": null, "e": 53, "s": 25, "text": "\n18 Jun, 2020" }, { "code": null, "e": 406, "s": 53, "text": "Data types specify the type of data that a valid C# variable can hold. C# is a strongly typed programming language because in C#, each type of data (such as integer, character, float, and so forth) is predefined as part of the programming language and all constants or variables defined for a given program must be described with one of the data types." }, { "code": null, "e": 463, "s": 406, "text": "Data types in C# is mainly divided into three categories" }, { "code": null, "e": 480, "s": 463, "text": "Value Data Types" }, { "code": null, "e": 501, "s": 480, "text": "Reference Data Types" }, { "code": null, "e": 519, "s": 501, "text": "Pointer Data Type" }, { "code": null, "e": 8894, "s": 519, "text": "Value Data Types : In C#, the Value Data Types will directly store the variable value in memory and it will also accept both signed and unsigned literals. The derived class for these data types are System.ValueType. Following are different Value Data Types in C# programming language :Signed & Unsigned Integral Types : There are 8 integral types which provide support for 8-bit, 16-bit, 32-bit, and 64-bit values in signed or unsigned form.AliasType NameTypeSize(bits)RangeDefault ValuesbyteSystem.Sbytesigned integer8-128 to 1270shortSystem.Int16signed integer16-32768 to 327670IntSystem.Int32signed integer32-231 to 231-10longSystem.Int64signed integer64-263 to 263-10LbyteSystem.byteunsigned integer80 to 2550ushortSystem.UInt16unsigned integer160 to 655350uintSystem.UInt32unsigned integer320 to 2320ulongSystem.UInt64unsigned integer640 to 2630Floating Point Types :There are 2 floating point data types which contain the decimal point.Float: It is 32-bit single-precision floating point type. It has 7 digit Precision. To initialize a float variable, use the suffix f or F. Like, float x = 3.5F;. If the suffix F or f will not use then it is treated as double.Double:It is 64-bit double-precision floating point type. It has 14 – 15 digit Precision. To initialize a double variable, use the suffix d or D. But it is not mandatory to use suffix because by default floating data types are the double type.AliasType nameSize(bits)Range (aprox)Default ValuefloatSystem.Single32±1.5 × 10-45 to ±3.4 × 10380.0FdoubleSystem.Double64±5.0 × 10-324 to ±1.7 × 103080.0DDecimal Types : The decimal type is a 128-bit data type suitable for financial and monetary calculations. It has 28-29 digit Precision. To initialize a decimal variable, use the suffix m or M. Like as, decimal x = 300.5m;. If the suffix m or M will not use then it is treated as double.AliasType nameSize(bits)Range (aprox)Default valuedecimalSystem.Decimal128±1.0 × 10-28 to ±7.9228 × 10280.0MCharacter Types : The character types represents a UTF-16 code unit or represents the 16-bit Unicode character.AliasType nameSize In(Bits)RangeDefault valuecharSystem.Char16U +0000 to U +ffff‘\\0’Example :// C# program to demonstrate // the above data typesusing System;namespace ValueTypeTest { class GeeksforGeeks { // Main function static void Main() { // declaring character char a = 'G'; // Integer data type is generally // used for numeric values int i = 89; short s = 56; // this will give error as number // is larger than short range // short s1 = 87878787878; // long uses Integer values which // may signed or unsigned long l = 4564; // UInt data type is generally // used for unsigned integer values uint ui = 95; ushort us = 76; // this will give error as number is // larger than short range // ulong data type is generally // used for unsigned integer values ulong ul = 3624573; // by default fraction value // is double in C# double d = 8.358674532; // for float use 'f' as suffix float f = 3.7330645f; // for float use 'm' as suffix decimal dec = 389.5m; Console.WriteLine(\"char: \" + a); Console.WriteLine(\"integer: \" + i); Console.WriteLine(\"short: \" + s); Console.WriteLine(\"long: \" + l); Console.WriteLine(\"float: \" + f); Console.WriteLine(\"double: \" + d); Console.WriteLine(\"decimal: \" + dec); Console.WriteLine(\"Unsinged integer: \" + ui); Console.WriteLine(\"Unsinged short: \" + us); Console.WriteLine(\"Unsinged long: \" + ul); }}}Output :char: G\ninteger: 89\nshort: 56\nlong: 4564\nfloat: 3.733064\ndouble: 8.358674532\ndecimal: 389.5\nUnsinged integer: 95\nUnsinged short: 76\nUnsinged long: 3624573\nExample :// C# program to demonstrate the Sbyte// signed integral data typeusing System;namespace ValueTypeTest { class GeeksforGeeks { // Main function static void Main() { sbyte a = 126; // sbyte is 8 bit // singned value Console.WriteLine(a); a++; Console.WriteLine(a); // It overflows here because // byte can hold values // from -128 to 127 a++; Console.WriteLine(a); // Looping back within // the range a++; Console.WriteLine(a); }}}Output :126\n127\n-128\n-127\nExample :// C# program to demonstrate // the byte data typeusing System;namespace ValueTypeTest { class GeeksforGeeks { // Main function static void Main() { byte a = 0; // byte is 8 bit // unsigned value Console.WriteLine(a); a++; Console.WriteLine(a); a = 254; // It overflows here because // byte can hold values from // 0 to 255 a++; Console.WriteLine(a); // Looping back within the range a++; Console.WriteLine(a); }}}Output :0\n1\n255\n0\nBoolean Types : It has to be assigned either true or false value. Values of type bool are not converted implicitly or explicitly (with casts) to any other type. But the programmer can easily write conversion code.AliasType nameValuesboolSystem.BooleanTrue / FalseExample :// C# program to demonstrate the// boolean data typeusing System;namespace ValueTypeTest { class GeeksforGeeks { // Main function static void Main() { // boolean data type bool b = true; if (b == true) Console.WriteLine(\"Hi Geek\"); } }}Output :Hi Geek\nReference Data Types : The Reference Data Types will contain a memory address of variable value because the reference types won’t store the variable value directly in memory. The built-in reference types are string, object.String : It represents a sequence of Unicode characters and its type name is System.String. So, string and String are equivalent.Example :string s1 = \"hello\"; // creating through string keyword \nString s2 = \"welcome\"; // creating through String class \nObject : In C#, all types, predefined and user-defined, reference types and value types, inherit directly or indirectly from Object. So basically it is the base class for all the data types in C#. Before assigning values, it needs type conversion. When a variable of a value type is converted to object, it’s called boxing. When a variable of type object is converted to a value type, it’s called unboxing. Its type name is System.Object.Example :// C# program to demonstrate // the Reference data typesusing System;namespace ValueTypeTest { class GeeksforGeeks { // Main Function static void Main() { // declaring string string a = \"Geeks\"; //append in a a+=\"for\"; a = a+\"Geeks\"; Console.WriteLine(a); // declare object obj object obj; obj = 20; Console.WriteLine(obj); // to show type of object // using GetType() Console.WriteLine(obj.GetType()); } }}Output :GeeksforGeeks\n20\nSystem.Int32\nPointer Data Type : The Pointer Data Types will contain a memory address of the variable value.To get the pointer details we have a two symbols ampersand (&) and asterisk (*).ampersand (&): It is Known as Address Operator. It is used to determine the address of a variable.asterisk (*): It also known as Indirection Operator. It is used to access the value of an address.Syntax :type* identifier;\nExample :int* p1, p; // Valid syntax\nint *p1, *p; // Invalid \nExample :// Note: This program will not work on// online compiler// Error: Unsafe code requires the `unsafe' // command line option to be specified// For its solution:// Go to your project properties page and// check under Build the checkbox Allow// unsafe code.using System;namespace Pointerprogram { class GFG { // Main function static void Main() { unsafe { // declare variable int n = 10; // store variable n address // location in pointer variable p int* p = &n; Console.WriteLine(\"Value :{0}\", n); Console.WriteLine(\"Address :{0}\", (int)p); } }}}" }, { "code": null, "e": 14581, "s": 8894, "text": "Value Data Types : In C#, the Value Data Types will directly store the variable value in memory and it will also accept both signed and unsigned literals. The derived class for these data types are System.ValueType. Following are different Value Data Types in C# programming language :Signed & Unsigned Integral Types : There are 8 integral types which provide support for 8-bit, 16-bit, 32-bit, and 64-bit values in signed or unsigned form.AliasType NameTypeSize(bits)RangeDefault ValuesbyteSystem.Sbytesigned integer8-128 to 1270shortSystem.Int16signed integer16-32768 to 327670IntSystem.Int32signed integer32-231 to 231-10longSystem.Int64signed integer64-263 to 263-10LbyteSystem.byteunsigned integer80 to 2550ushortSystem.UInt16unsigned integer160 to 655350uintSystem.UInt32unsigned integer320 to 2320ulongSystem.UInt64unsigned integer640 to 2630Floating Point Types :There are 2 floating point data types which contain the decimal point.Float: It is 32-bit single-precision floating point type. It has 7 digit Precision. To initialize a float variable, use the suffix f or F. Like, float x = 3.5F;. If the suffix F or f will not use then it is treated as double.Double:It is 64-bit double-precision floating point type. It has 14 – 15 digit Precision. To initialize a double variable, use the suffix d or D. But it is not mandatory to use suffix because by default floating data types are the double type.AliasType nameSize(bits)Range (aprox)Default ValuefloatSystem.Single32±1.5 × 10-45 to ±3.4 × 10380.0FdoubleSystem.Double64±5.0 × 10-324 to ±1.7 × 103080.0DDecimal Types : The decimal type is a 128-bit data type suitable for financial and monetary calculations. It has 28-29 digit Precision. To initialize a decimal variable, use the suffix m or M. Like as, decimal x = 300.5m;. If the suffix m or M will not use then it is treated as double.AliasType nameSize(bits)Range (aprox)Default valuedecimalSystem.Decimal128±1.0 × 10-28 to ±7.9228 × 10280.0MCharacter Types : The character types represents a UTF-16 code unit or represents the 16-bit Unicode character.AliasType nameSize In(Bits)RangeDefault valuecharSystem.Char16U +0000 to U +ffff‘\\0’Example :// C# program to demonstrate // the above data typesusing System;namespace ValueTypeTest { class GeeksforGeeks { // Main function static void Main() { // declaring character char a = 'G'; // Integer data type is generally // used for numeric values int i = 89; short s = 56; // this will give error as number // is larger than short range // short s1 = 87878787878; // long uses Integer values which // may signed or unsigned long l = 4564; // UInt data type is generally // used for unsigned integer values uint ui = 95; ushort us = 76; // this will give error as number is // larger than short range // ulong data type is generally // used for unsigned integer values ulong ul = 3624573; // by default fraction value // is double in C# double d = 8.358674532; // for float use 'f' as suffix float f = 3.7330645f; // for float use 'm' as suffix decimal dec = 389.5m; Console.WriteLine(\"char: \" + a); Console.WriteLine(\"integer: \" + i); Console.WriteLine(\"short: \" + s); Console.WriteLine(\"long: \" + l); Console.WriteLine(\"float: \" + f); Console.WriteLine(\"double: \" + d); Console.WriteLine(\"decimal: \" + dec); Console.WriteLine(\"Unsinged integer: \" + ui); Console.WriteLine(\"Unsinged short: \" + us); Console.WriteLine(\"Unsinged long: \" + ul); }}}Output :char: G\ninteger: 89\nshort: 56\nlong: 4564\nfloat: 3.733064\ndouble: 8.358674532\ndecimal: 389.5\nUnsinged integer: 95\nUnsinged short: 76\nUnsinged long: 3624573\nExample :// C# program to demonstrate the Sbyte// signed integral data typeusing System;namespace ValueTypeTest { class GeeksforGeeks { // Main function static void Main() { sbyte a = 126; // sbyte is 8 bit // singned value Console.WriteLine(a); a++; Console.WriteLine(a); // It overflows here because // byte can hold values // from -128 to 127 a++; Console.WriteLine(a); // Looping back within // the range a++; Console.WriteLine(a); }}}Output :126\n127\n-128\n-127\nExample :// C# program to demonstrate // the byte data typeusing System;namespace ValueTypeTest { class GeeksforGeeks { // Main function static void Main() { byte a = 0; // byte is 8 bit // unsigned value Console.WriteLine(a); a++; Console.WriteLine(a); a = 254; // It overflows here because // byte can hold values from // 0 to 255 a++; Console.WriteLine(a); // Looping back within the range a++; Console.WriteLine(a); }}}Output :0\n1\n255\n0\nBoolean Types : It has to be assigned either true or false value. Values of type bool are not converted implicitly or explicitly (with casts) to any other type. But the programmer can easily write conversion code.AliasType nameValuesboolSystem.BooleanTrue / FalseExample :// C# program to demonstrate the// boolean data typeusing System;namespace ValueTypeTest { class GeeksforGeeks { // Main function static void Main() { // boolean data type bool b = true; if (b == true) Console.WriteLine(\"Hi Geek\"); } }}Output :Hi Geek\n" }, { "code": null, "e": 15147, "s": 14581, "text": "Signed & Unsigned Integral Types : There are 8 integral types which provide support for 8-bit, 16-bit, 32-bit, and 64-bit values in signed or unsigned form.AliasType NameTypeSize(bits)RangeDefault ValuesbyteSystem.Sbytesigned integer8-128 to 1270shortSystem.Int16signed integer16-32768 to 327670IntSystem.Int32signed integer32-231 to 231-10longSystem.Int64signed integer64-263 to 263-10LbyteSystem.byteunsigned integer80 to 2550ushortSystem.UInt16unsigned integer160 to 655350uintSystem.UInt32unsigned integer320 to 2320ulongSystem.UInt64unsigned integer640 to 2630" }, { "code": null, "e": 15863, "s": 15147, "text": "Floating Point Types :There are 2 floating point data types which contain the decimal point.Float: It is 32-bit single-precision floating point type. It has 7 digit Precision. To initialize a float variable, use the suffix f or F. Like, float x = 3.5F;. If the suffix F or f will not use then it is treated as double.Double:It is 64-bit double-precision floating point type. It has 14 – 15 digit Precision. To initialize a double variable, use the suffix d or D. But it is not mandatory to use suffix because by default floating data types are the double type.AliasType nameSize(bits)Range (aprox)Default ValuefloatSystem.Single32±1.5 × 10-45 to ±3.4 × 10380.0FdoubleSystem.Double64±5.0 × 10-324 to ±1.7 × 103080.0D" }, { "code": null, "e": 15956, "s": 15863, "text": "Floating Point Types :There are 2 floating point data types which contain the decimal point." }, { "code": null, "e": 16182, "s": 15956, "text": "Float: It is 32-bit single-precision floating point type. It has 7 digit Precision. To initialize a float variable, use the suffix f or F. Like, float x = 3.5F;. If the suffix F or f will not use then it is treated as double." }, { "code": null, "e": 16426, "s": 16182, "text": "Double:It is 64-bit double-precision floating point type. It has 14 – 15 digit Precision. To initialize a double variable, use the suffix d or D. But it is not mandatory to use suffix because by default floating data types are the double type." }, { "code": null, "e": 16821, "s": 16426, "text": "Decimal Types : The decimal type is a 128-bit data type suitable for financial and monetary calculations. It has 28-29 digit Precision. To initialize a decimal variable, use the suffix m or M. Like as, decimal x = 300.5m;. If the suffix m or M will not use then it is treated as double.AliasType nameSize(bits)Range (aprox)Default valuedecimalSystem.Decimal128±1.0 × 10-28 to ±7.9228 × 10280.0M" }, { "code": null, "e": 17017, "s": 16821, "text": "Character Types : The character types represents a UTF-16 code unit or represents the 16-bit Unicode character.AliasType nameSize In(Bits)RangeDefault valuecharSystem.Char16U +0000 to U +ffff‘\\0’" }, { "code": null, "e": 17027, "s": 17017, "text": "Example :" }, { "code": "// C# program to demonstrate // the above data typesusing System;namespace ValueTypeTest { class GeeksforGeeks { // Main function static void Main() { // declaring character char a = 'G'; // Integer data type is generally // used for numeric values int i = 89; short s = 56; // this will give error as number // is larger than short range // short s1 = 87878787878; // long uses Integer values which // may signed or unsigned long l = 4564; // UInt data type is generally // used for unsigned integer values uint ui = 95; ushort us = 76; // this will give error as number is // larger than short range // ulong data type is generally // used for unsigned integer values ulong ul = 3624573; // by default fraction value // is double in C# double d = 8.358674532; // for float use 'f' as suffix float f = 3.7330645f; // for float use 'm' as suffix decimal dec = 389.5m; Console.WriteLine(\"char: \" + a); Console.WriteLine(\"integer: \" + i); Console.WriteLine(\"short: \" + s); Console.WriteLine(\"long: \" + l); Console.WriteLine(\"float: \" + f); Console.WriteLine(\"double: \" + d); Console.WriteLine(\"decimal: \" + dec); Console.WriteLine(\"Unsinged integer: \" + ui); Console.WriteLine(\"Unsinged short: \" + us); Console.WriteLine(\"Unsinged long: \" + ul); }}}", "e": 18605, "s": 17027, "text": null }, { "code": null, "e": 18614, "s": 18605, "text": "Output :" }, { "code": null, "e": 18770, "s": 18614, "text": "char: G\ninteger: 89\nshort: 56\nlong: 4564\nfloat: 3.733064\ndouble: 8.358674532\ndecimal: 389.5\nUnsinged integer: 95\nUnsinged short: 76\nUnsinged long: 3624573\n" }, { "code": null, "e": 18780, "s": 18770, "text": "Example :" }, { "code": "// C# program to demonstrate the Sbyte// signed integral data typeusing System;namespace ValueTypeTest { class GeeksforGeeks { // Main function static void Main() { sbyte a = 126; // sbyte is 8 bit // singned value Console.WriteLine(a); a++; Console.WriteLine(a); // It overflows here because // byte can hold values // from -128 to 127 a++; Console.WriteLine(a); // Looping back within // the range a++; Console.WriteLine(a); }}}", "e": 19342, "s": 18780, "text": null }, { "code": null, "e": 19351, "s": 19342, "text": "Output :" }, { "code": null, "e": 19370, "s": 19351, "text": "126\n127\n-128\n-127\n" }, { "code": null, "e": 19380, "s": 19370, "text": "Example :" }, { "code": "// C# program to demonstrate // the byte data typeusing System;namespace ValueTypeTest { class GeeksforGeeks { // Main function static void Main() { byte a = 0; // byte is 8 bit // unsigned value Console.WriteLine(a); a++; Console.WriteLine(a); a = 254; // It overflows here because // byte can hold values from // 0 to 255 a++; Console.WriteLine(a); // Looping back within the range a++; Console.WriteLine(a); }}}", "e": 19938, "s": 19380, "text": null }, { "code": null, "e": 19947, "s": 19938, "text": "Output :" }, { "code": null, "e": 19958, "s": 19947, "text": "0\n1\n255\n0\n" }, { "code": null, "e": 20562, "s": 19958, "text": "Boolean Types : It has to be assigned either true or false value. Values of type bool are not converted implicitly or explicitly (with casts) to any other type. But the programmer can easily write conversion code.AliasType nameValuesboolSystem.BooleanTrue / FalseExample :// C# program to demonstrate the// boolean data typeusing System;namespace ValueTypeTest { class GeeksforGeeks { // Main function static void Main() { // boolean data type bool b = true; if (b == true) Console.WriteLine(\"Hi Geek\"); } }}Output :Hi Geek\n" }, { "code": null, "e": 20572, "s": 20562, "text": "Example :" }, { "code": "// C# program to demonstrate the// boolean data typeusing System;namespace ValueTypeTest { class GeeksforGeeks { // Main function static void Main() { // boolean data type bool b = true; if (b == true) Console.WriteLine(\"Hi Geek\"); } }}", "e": 20888, "s": 20572, "text": null }, { "code": null, "e": 20897, "s": 20888, "text": "Output :" }, { "code": null, "e": 20906, "s": 20897, "text": "Hi Geek\n" }, { "code": null, "e": 22434, "s": 20906, "text": "Reference Data Types : The Reference Data Types will contain a memory address of variable value because the reference types won’t store the variable value directly in memory. The built-in reference types are string, object.String : It represents a sequence of Unicode characters and its type name is System.String. So, string and String are equivalent.Example :string s1 = \"hello\"; // creating through string keyword \nString s2 = \"welcome\"; // creating through String class \nObject : In C#, all types, predefined and user-defined, reference types and value types, inherit directly or indirectly from Object. So basically it is the base class for all the data types in C#. Before assigning values, it needs type conversion. When a variable of a value type is converted to object, it’s called boxing. When a variable of type object is converted to a value type, it’s called unboxing. Its type name is System.Object.Example :// C# program to demonstrate // the Reference data typesusing System;namespace ValueTypeTest { class GeeksforGeeks { // Main Function static void Main() { // declaring string string a = \"Geeks\"; //append in a a+=\"for\"; a = a+\"Geeks\"; Console.WriteLine(a); // declare object obj object obj; obj = 20; Console.WriteLine(obj); // to show type of object // using GetType() Console.WriteLine(obj.GetType()); } }}Output :GeeksforGeeks\n20\nSystem.Int32\n" }, { "code": null, "e": 22689, "s": 22434, "text": "String : It represents a sequence of Unicode characters and its type name is System.String. So, string and String are equivalent.Example :string s1 = \"hello\"; // creating through string keyword \nString s2 = \"welcome\"; // creating through String class \n" }, { "code": null, "e": 22806, "s": 22689, "text": "string s1 = \"hello\"; // creating through string keyword \nString s2 = \"welcome\"; // creating through String class \n" }, { "code": null, "e": 23245, "s": 22806, "text": "Object : In C#, all types, predefined and user-defined, reference types and value types, inherit directly or indirectly from Object. So basically it is the base class for all the data types in C#. Before assigning values, it needs type conversion. When a variable of a value type is converted to object, it’s called boxing. When a variable of type object is converted to a value type, it’s called unboxing. Its type name is System.Object." }, { "code": null, "e": 23255, "s": 23245, "text": "Example :" }, { "code": "// C# program to demonstrate // the Reference data typesusing System;namespace ValueTypeTest { class GeeksforGeeks { // Main Function static void Main() { // declaring string string a = \"Geeks\"; //append in a a+=\"for\"; a = a+\"Geeks\"; Console.WriteLine(a); // declare object obj object obj; obj = 20; Console.WriteLine(obj); // to show type of object // using GetType() Console.WriteLine(obj.GetType()); } }}", "e": 23821, "s": 23255, "text": null }, { "code": null, "e": 23830, "s": 23821, "text": "Output :" }, { "code": null, "e": 23861, "s": 23830, "text": "GeeksforGeeks\n20\nSystem.Int32\n" }, { "code": null, "e": 25023, "s": 23861, "text": "Pointer Data Type : The Pointer Data Types will contain a memory address of the variable value.To get the pointer details we have a two symbols ampersand (&) and asterisk (*).ampersand (&): It is Known as Address Operator. It is used to determine the address of a variable.asterisk (*): It also known as Indirection Operator. It is used to access the value of an address.Syntax :type* identifier;\nExample :int* p1, p; // Valid syntax\nint *p1, *p; // Invalid \nExample :// Note: This program will not work on// online compiler// Error: Unsafe code requires the `unsafe' // command line option to be specified// For its solution:// Go to your project properties page and// check under Build the checkbox Allow// unsafe code.using System;namespace Pointerprogram { class GFG { // Main function static void Main() { unsafe { // declare variable int n = 10; // store variable n address // location in pointer variable p int* p = &n; Console.WriteLine(\"Value :{0}\", n); Console.WriteLine(\"Address :{0}\", (int)p); } }}}" }, { "code": null, "e": 25042, "s": 25023, "text": "type* identifier;\n" }, { "code": null, "e": 25052, "s": 25042, "text": "Example :" }, { "code": null, "e": 25110, "s": 25052, "text": "int* p1, p; // Valid syntax\nint *p1, *p; // Invalid \n" }, { "code": null, "e": 25120, "s": 25110, "text": "Example :" }, { "code": "// Note: This program will not work on// online compiler// Error: Unsafe code requires the `unsafe' // command line option to be specified// For its solution:// Go to your project properties page and// check under Build the checkbox Allow// unsafe code.using System;namespace Pointerprogram { class GFG { // Main function static void Main() { unsafe { // declare variable int n = 10; // store variable n address // location in pointer variable p int* p = &n; Console.WriteLine(\"Value :{0}\", n); Console.WriteLine(\"Address :{0}\", (int)p); } }}}", "e": 25810, "s": 25120, "text": null }, { "code": null, "e": 25821, "s": 25810, "text": "AlokSingh9" }, { "code": null, "e": 25835, "s": 25821, "text": "CSharp-Basics" }, { "code": null, "e": 25853, "s": 25835, "text": "CSharp-data-types" }, { "code": null, "e": 25856, "s": 25853, "text": "C#" }, { "code": null, "e": 25877, "s": 25856, "text": "Programming Language" }, { "code": null, "e": 25975, "s": 25877, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26029, "s": 25975, "text": "Difference between Abstract Class and Interface in C#" }, { "code": null, "e": 26091, "s": 26029, "text": "C# | How to check whether a List contains a specified element" }, { "code": null, "e": 26134, "s": 26091, "text": "C# | Multiple inheritance using interfaces" }, { "code": null, "e": 26157, "s": 26134, "text": "C# | Arrays of Strings" }, { "code": null, "e": 26185, "s": 26157, "text": "C# | IsNullOrEmpty() Method" }, { "code": null, "e": 26248, "s": 26185, "text": "Differences between Procedural and Object Oriented Programming" }, { "code": null, "e": 26289, "s": 26248, "text": "Arrow operator -> in C/C++ with Examples" }, { "code": null, "e": 26332, "s": 26289, "text": "Modulo Operator (%) in C/C++ with Examples" }, { "code": null, "e": 26350, "s": 26332, "text": "Structures in C++" } ]
Replace a character c1 with c2 and c2 with c1 in a string S
15 Jun, 2022 Given a string S, c1 and c2. Replace character c1 with c2 and c2 with c1. Examples: Input : grrksfoegrrks, c1 = e, c2 = r Output : geeksforgeeks Input : ratul, c1 = t, c2 = h Output : rahul Traverse through the string and check for the occurrences of c1 and c2. If c1 is found then replace it with c2 and else if c2 is found replace it with c1. C++ Java Python3 C# PHP Javascript // CPP program to replace c1 with c2// and c2 with c1#include <bits/stdc++.h>using namespace std;string replace(string s, char c1, char c2){ int l = s.length(); // loop to traverse in the string for (int i = 0; i < l; i++) { // check for c1 and replace if (s[i] == c1) s[i] = c2; // check for c2 and replace else if (s[i] == c2) s[i] = c1; } return s;} // Driver code to check the above functionint main(){ string s = "grrksfoegrrks"; char c1 = 'e', c2 = 'r'; cout << replace(s, c1, c2); return 0;} // Java program to replace c1 with c2// and c2 with c1class GFG{ static String replace(String s, char c1, char c2){ int l = s.length(); char []arr = s.toCharArray(); // loop to traverse in the string for (int i = 0; i < l; i++) { // check for c1 and replace if (arr[i] == c1) arr[i] = c2; // check for c2 and replace else if (arr[i] == c2) arr[i] = c1; } return String.valueOf(arr);} // Driver codepublic static void main(String []args){ String s = "grrksfoegrrks"; char c1 = 'e', c2 = 'r'; System.out.println(replace(s, c1, c2));}} // This code is contributed// by ChitraNayal # Python3 program to replace c1 with c2# and c2 with c1def replace(s, c1, c2): l = len(s) # loop to traverse in the string for i in range(l): # check for c1 and replace if (s[i] == c1): s = s[0:i] + c2 + s[i + 1:] # check for c2 and replace elif (s[i] == c2): s = s[0:i] + c1 + s[i + 1:] return s # Driver Codeif __name__ == '__main__': s = "grrksfoegrrks" c1 = 'e' c2 = 'r' print(replace(s, c1, c2)) # This code is contributed# by PrinciRaj1992 // C# program to replace c1 with c2// and c2 with c1using System;public class GFG{ static String replace(String s, char c1, char c2) { int l = s.Length; char []arr = s.ToCharArray(); // loop to traverse in the string for (int i = 0; i < l; i++) { // check for c1 and replace if (arr[i] == c1) arr[i] = c2; // check for c2 and replace else if (arr[i] == c2) arr[i] = c1; } return string.Join("", arr); } // Driver code public static void Main() { String s = "grrksfoegrrks"; char c1 = 'e', c2 = 'r'; Console.WriteLine(replace(s, c1, c2)); }}// This code is contributed by 29AjayKumar <?php// PHP program to replace c1// with c2 and c2 with c1function replace($s, $c1, $c2){ $l = strlen($s); // loop to traverse // in the string for ($i = 0; $i < $l; $i++) { // check for c1 and replace if ($s[$i] == $c1) $s[$i] = $c2; // check for c2 and replace else if ($s[$i] == $c2) $s[$i] = $c1; } return $s;} // Driver Code$s = "grrksfoegrrks";$c1 = 'e'; $c2 = 'r';echo replace($s, $c1, $c2); // This code is contributed by anuj_67.?> <script>// Javascript program to replace c1 with c2// and c2 with c1 function replace(s,c1,c2) { let l = s.length; let arr = s.split(""); // loop to traverse in the string for (let i = 0; i < l; i++) { // check for c1 and replace if (arr[i] == c1) arr[i] = c2; // check for c2 and replace else if (arr[i] == c2) arr[i] = c1; } return arr.join(""); } // Driver code let s = "grrksfoegrrks"; let c1 = 'e', c2 = 'r'; document.write(replace(s, c1, c2)); // This code is contributed by rag2127</script> Output: geeksforgeeks Time Complexity: O(n) Chapters descriptions off, selected captions settings, opens captions settings dialog captions off, selected English default, selected This is a modal window. Beginning of dialog window. Escape will cancel and close the window. End of dialog window. Auxiliary Space: 0(1) Replace a character c1 with c2 and c2 with c1 in a string S | GeeksforGeeks - YouTubeGeeksforGeeks529K subscribersReplace a character c1 with c2 and c2 with c1 in a string S | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 2:31•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=_dy1oByB_b8" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> vt_m ukasp 29AjayKumar princiraj1992 gfg_sal_gfg rag2127 geekygirl2001 School Programming Strings Strings Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Constructors in Java Exceptions in Java Python Exception Handling Python Try Except Ternary Operator in Python Write a program to reverse an array or string Write a program to print all permutations of a given string Longest Common Subsequence | DP-4 Check for Balanced Brackets in an expression (well-formedness) using Stack KMP Algorithm for Pattern Searching
[ { "code": null, "e": 53, "s": 25, "text": "\n15 Jun, 2022" }, { "code": null, "e": 139, "s": 53, "text": "Given a string S, c1 and c2. Replace character c1 with c2 and c2 with c1. Examples: " }, { "code": null, "e": 265, "s": 139, "text": "Input : grrksfoegrrks,\n c1 = e, c2 = r \nOutput : geeksforgeeks \n\nInput : ratul,\n c1 = t, c2 = h \nOutput : rahul" }, { "code": null, "e": 424, "s": 267, "text": "Traverse through the string and check for the occurrences of c1 and c2. If c1 is found then replace it with c2 and else if c2 is found replace it with c1. " }, { "code": null, "e": 428, "s": 424, "text": "C++" }, { "code": null, "e": 433, "s": 428, "text": "Java" }, { "code": null, "e": 441, "s": 433, "text": "Python3" }, { "code": null, "e": 444, "s": 441, "text": "C#" }, { "code": null, "e": 448, "s": 444, "text": "PHP" }, { "code": null, "e": 459, "s": 448, "text": "Javascript" }, { "code": "// CPP program to replace c1 with c2// and c2 with c1#include <bits/stdc++.h>using namespace std;string replace(string s, char c1, char c2){ int l = s.length(); // loop to traverse in the string for (int i = 0; i < l; i++) { // check for c1 and replace if (s[i] == c1) s[i] = c2; // check for c2 and replace else if (s[i] == c2) s[i] = c1; } return s;} // Driver code to check the above functionint main(){ string s = \"grrksfoegrrks\"; char c1 = 'e', c2 = 'r'; cout << replace(s, c1, c2); return 0;}", "e": 1038, "s": 459, "text": null }, { "code": "// Java program to replace c1 with c2// and c2 with c1class GFG{ static String replace(String s, char c1, char c2){ int l = s.length(); char []arr = s.toCharArray(); // loop to traverse in the string for (int i = 0; i < l; i++) { // check for c1 and replace if (arr[i] == c1) arr[i] = c2; // check for c2 and replace else if (arr[i] == c2) arr[i] = c1; } return String.valueOf(arr);} // Driver codepublic static void main(String []args){ String s = \"grrksfoegrrks\"; char c1 = 'e', c2 = 'r'; System.out.println(replace(s, c1, c2));}} // This code is contributed// by ChitraNayal", "e": 1747, "s": 1038, "text": null }, { "code": "# Python3 program to replace c1 with c2# and c2 with c1def replace(s, c1, c2): l = len(s) # loop to traverse in the string for i in range(l): # check for c1 and replace if (s[i] == c1): s = s[0:i] + c2 + s[i + 1:] # check for c2 and replace elif (s[i] == c2): s = s[0:i] + c1 + s[i + 1:] return s # Driver Codeif __name__ == '__main__': s = \"grrksfoegrrks\" c1 = 'e' c2 = 'r' print(replace(s, c1, c2)) # This code is contributed# by PrinciRaj1992", "e": 2290, "s": 1747, "text": null }, { "code": "// C# program to replace c1 with c2// and c2 with c1using System;public class GFG{ static String replace(String s, char c1, char c2) { int l = s.Length; char []arr = s.ToCharArray(); // loop to traverse in the string for (int i = 0; i < l; i++) { // check for c1 and replace if (arr[i] == c1) arr[i] = c2; // check for c2 and replace else if (arr[i] == c2) arr[i] = c1; } return string.Join(\"\", arr); } // Driver code public static void Main() { String s = \"grrksfoegrrks\"; char c1 = 'e', c2 = 'r'; Console.WriteLine(replace(s, c1, c2)); }}// This code is contributed by 29AjayKumar", "e": 3083, "s": 2290, "text": null }, { "code": "<?php// PHP program to replace c1// with c2 and c2 with c1function replace($s, $c1, $c2){ $l = strlen($s); // loop to traverse // in the string for ($i = 0; $i < $l; $i++) { // check for c1 and replace if ($s[$i] == $c1) $s[$i] = $c2; // check for c2 and replace else if ($s[$i] == $c2) $s[$i] = $c1; } return $s;} // Driver Code$s = \"grrksfoegrrks\";$c1 = 'e'; $c2 = 'r';echo replace($s, $c1, $c2); // This code is contributed by anuj_67.?>", "e": 3598, "s": 3083, "text": null }, { "code": "<script>// Javascript program to replace c1 with c2// and c2 with c1 function replace(s,c1,c2) { let l = s.length; let arr = s.split(\"\"); // loop to traverse in the string for (let i = 0; i < l; i++) { // check for c1 and replace if (arr[i] == c1) arr[i] = c2; // check for c2 and replace else if (arr[i] == c2) arr[i] = c1; } return arr.join(\"\"); } // Driver code let s = \"grrksfoegrrks\"; let c1 = 'e', c2 = 'r'; document.write(replace(s, c1, c2)); // This code is contributed by rag2127</script>", "e": 4246, "s": 3598, "text": null }, { "code": null, "e": 4255, "s": 4246, "text": "Output: " }, { "code": null, "e": 4269, "s": 4255, "text": "geeksforgeeks" }, { "code": null, "e": 4292, "s": 4269, "text": "Time Complexity: O(n) " }, { "code": null, "e": 4301, "s": 4292, "text": "Chapters" }, { "code": null, "e": 4328, "s": 4301, "text": "descriptions off, selected" }, { "code": null, "e": 4378, "s": 4328, "text": "captions settings, opens captions settings dialog" }, { "code": null, "e": 4401, "s": 4378, "text": "captions off, selected" }, { "code": null, "e": 4409, "s": 4401, "text": "English" }, { "code": null, "e": 4427, "s": 4409, "text": "default, selected" }, { "code": null, "e": 4451, "s": 4427, "text": "This is a modal window." }, { "code": null, "e": 4520, "s": 4451, "text": "Beginning of dialog window. Escape will cancel and close the window." }, { "code": null, "e": 4542, "s": 4520, "text": "End of dialog window." }, { "code": null, "e": 4565, "s": 4542, "text": "Auxiliary Space: 0(1) " }, { "code": null, "e": 5501, "s": 4565, "text": "Replace a character c1 with c2 and c2 with c1 in a string S | GeeksforGeeks - YouTubeGeeksforGeeks529K subscribersReplace a character c1 with c2 and c2 with c1 in a string S | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 2:31•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=_dy1oByB_b8\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>" }, { "code": null, "e": 5508, "s": 5503, "text": "vt_m" }, { "code": null, "e": 5514, "s": 5508, "text": "ukasp" }, { "code": null, "e": 5526, "s": 5514, "text": "29AjayKumar" }, { "code": null, "e": 5540, "s": 5526, "text": "princiraj1992" }, { "code": null, "e": 5552, "s": 5540, "text": "gfg_sal_gfg" }, { "code": null, "e": 5560, "s": 5552, "text": "rag2127" }, { "code": null, "e": 5574, "s": 5560, "text": "geekygirl2001" }, { "code": null, "e": 5593, "s": 5574, "text": "School Programming" }, { "code": null, "e": 5601, "s": 5593, "text": "Strings" }, { "code": null, "e": 5609, "s": 5601, "text": "Strings" }, { "code": null, "e": 5707, "s": 5609, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5728, "s": 5707, "text": "Constructors in Java" }, { "code": null, "e": 5747, "s": 5728, "text": "Exceptions in Java" }, { "code": null, "e": 5773, "s": 5747, "text": "Python Exception Handling" }, { "code": null, "e": 5791, "s": 5773, "text": "Python Try Except" }, { "code": null, "e": 5818, "s": 5791, "text": "Ternary Operator in Python" }, { "code": null, "e": 5864, "s": 5818, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 5924, "s": 5864, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 5958, "s": 5924, "text": "Longest Common Subsequence | DP-4" }, { "code": null, "e": 6033, "s": 5958, "text": "Check for Balanced Brackets in an expression (well-formedness) using Stack" } ]
Program to calculate the Surface Area of a Triangular Prism
18 Mar, 2021 In mathematics, a triangular prism is a three-dimensional solid shape with two identical ends connected by equal parallel lines, and have 5 faces, 9 edges, and 6 vertices. where “b” is the length of the base, “h” is the height of the triangle, “s1, s2, s3” are the respective length of each side of the triangle, and H is the height of the prism (which is also the length of the rectangle).Given the base, the height of the triangle, height of prism and the length of each side of triangle base and the task is to calculate the surface area of the triangular prism.Examples: Input: b = 3, h = 4, s1 = 3, s2 = 6, s3 = 6, Ht = 8 Output: The area of triangular prism is 132.000000Input: b = 2, h = 3, s1 = 4, s2 = 5, s3 = 6, Ht = 8 Output: The area of triangular prism is 126.000000 Formula for calculating the surface area: As stated above, the prism contains two triangles of the area (1/2)*(b)*(h) and three rectangles of the area H*s1, H*s2 and H*s3. Now after adding all the terms we get the total surface area: SA = b * h + (s1 + s2 + s3 ) * H C++ C Java Python3 C# PHP Javascript // C++ Program to calculate the// Surface area of a triangular prism#include <bits/stdc++.h>using namespace std; // Function for calculating the areavoid Calculate_area(){ // Initialization float b = 3, h = 4, s1 = 3, s2 = 6; float s3 = 6, Ht = 8, SA; // Formula for calculating the area SA = b * h + (s1 + s2 + s3) * Ht; // Displaying the area cout << "The area of triangular prism is : " << SA;} // Driver codeint main(){ // Function calling Calculate_area(); return 0;} // C Program to calculate the// Surface area of a triangular prism#include <stdio.h> // Function for calculating the areavoid Calculate_area(){ // Initialization float b = 3, h = 4, s1 = 3, s2 = 6; float s3 = 6, Ht = 8, SA; // Formula for calculating the area SA = b * h + (s1 + s2 + s3) * Ht; // Displaying the output printf("The area of triangular prism is : %f", SA);} // Driver codeint main(){ // Function calling Calculate_area(); return 0;} // Java Program to calculate the// Surface area of a triangular prism import java.util.Scanner;public class Prism { public static void Calculate_area() { // Initialization double b = 3, h = 4, s1 = 3, s2 = 6; double s3 = 6, Ht = 8, SA; // Formula for calculating the area SA = b * h + (s1 + s2 + s3) * Ht; // Displaying the area System.out.printf("The area of triangular prism is : %f", SA); } public static void main(String[] args) { Calculate_area(); }}// This code is contributed by Nishant Tanwar # Python3 Program to calculate the# Surface area of a triangular prism # Function for calculating the areadef Calculate_area(): # Initialization b = 3 h = 4 s1 = 3 s2 = 6 s3 = 6 Ht = 8 # Formula for calculating the area SA = b * h + (s1 + s2 + s3) * Ht # Displaying the area print ("The area of triangular prism is :",SA) # Driver codeif __name__ == '__main__': # Function calling Calculate_area() # This code is contributed by# Surendra_Gangwar // C# Program to calculate the// Surface area of a triangular prismusing System;public class Prism { static void Calculate_area() { // Initialization double b = 3, h = 4, s1 = 3, s2 = 6; double s3 = 6, Ht = 8, SA; // Formula for calculating the area SA = b * h + (s1 + s2 + s3) * Ht; // Displaying the area Console.WriteLine("The area of triangular prism is : " + SA); } static public void Main(String[] args) { Calculate_area(); }} <?php// PHP Program to calculate// the Surface area of a// triangular prism // Function for calculating// the areafunction Calculate_area(){ // Initialization $b = 3; $h = 4; $s1 = 3; $s2 = 6; $s3 = 6; $Ht = 8; $SA; // Formula for calculating // the area $SA = $b * $h + ($s1 + $s2 + $s3) * $Ht; // Displaying the area echo "The area of triangular". " prism is : " , $SA;} // Driver code // Function callingCalculate_area(); // This code is contributed by m_kit?> <script>// javascript Program to calculate the// Surface area of a triangular prism // Function for calculating the areafunction Calculate_area(){ // Initialization let b = 3, h = 4, s1 = 3, s2 = 6; let s3 = 6, Ht = 8, SA; // Formula for calculating the area SA = b * h + (s1 + s2 + s3) * Ht; // Displaying the area document.write( "The area of triangular prism is : " +SA);} // Driver code // Function calling Calculate_area(); // This code is contributed by Rajput-Ji </script> The area of triangular prism is : 132 jit_t Nishant Tanwar SURENDRA_GANGWAR Rajput-Ji school-programming Geometric Mathematical Mathematical Geometric Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n18 Mar, 2021" }, { "code": null, "e": 201, "s": 28, "text": "In mathematics, a triangular prism is a three-dimensional solid shape with two identical ends connected by equal parallel lines, and have 5 faces, 9 edges, and 6 vertices. " }, { "code": null, "e": 606, "s": 201, "text": "where “b” is the length of the base, “h” is the height of the triangle, “s1, s2, s3” are the respective length of each side of the triangle, and H is the height of the prism (which is also the length of the rectangle).Given the base, the height of the triangle, height of prism and the length of each side of triangle base and the task is to calculate the surface area of the triangular prism.Examples: " }, { "code": null, "e": 813, "s": 606, "text": "Input: b = 3, h = 4, s1 = 3, s2 = 6, s3 = 6, Ht = 8 Output: The area of triangular prism is 132.000000Input: b = 2, h = 3, s1 = 4, s2 = 5, s3 = 6, Ht = 8 Output: The area of triangular prism is 126.000000 " }, { "code": null, "e": 1049, "s": 813, "text": "Formula for calculating the surface area: As stated above, the prism contains two triangles of the area (1/2)*(b)*(h) and three rectangles of the area H*s1, H*s2 and H*s3. Now after adding all the terms we get the total surface area: " }, { "code": null, "e": 1082, "s": 1049, "text": "SA = b * h + (s1 + s2 + s3 ) * H" }, { "code": null, "e": 1088, "s": 1084, "text": "C++" }, { "code": null, "e": 1090, "s": 1088, "text": "C" }, { "code": null, "e": 1095, "s": 1090, "text": "Java" }, { "code": null, "e": 1103, "s": 1095, "text": "Python3" }, { "code": null, "e": 1106, "s": 1103, "text": "C#" }, { "code": null, "e": 1110, "s": 1106, "text": "PHP" }, { "code": null, "e": 1121, "s": 1110, "text": "Javascript" }, { "code": "// C++ Program to calculate the// Surface area of a triangular prism#include <bits/stdc++.h>using namespace std; // Function for calculating the areavoid Calculate_area(){ // Initialization float b = 3, h = 4, s1 = 3, s2 = 6; float s3 = 6, Ht = 8, SA; // Formula for calculating the area SA = b * h + (s1 + s2 + s3) * Ht; // Displaying the area cout << \"The area of triangular prism is : \" << SA;} // Driver codeint main(){ // Function calling Calculate_area(); return 0;}", "e": 1627, "s": 1121, "text": null }, { "code": "// C Program to calculate the// Surface area of a triangular prism#include <stdio.h> // Function for calculating the areavoid Calculate_area(){ // Initialization float b = 3, h = 4, s1 = 3, s2 = 6; float s3 = 6, Ht = 8, SA; // Formula for calculating the area SA = b * h + (s1 + s2 + s3) * Ht; // Displaying the output printf(\"The area of triangular prism is : %f\", SA);} // Driver codeint main(){ // Function calling Calculate_area(); return 0;}", "e": 2107, "s": 1627, "text": null }, { "code": "// Java Program to calculate the// Surface area of a triangular prism import java.util.Scanner;public class Prism { public static void Calculate_area() { // Initialization double b = 3, h = 4, s1 = 3, s2 = 6; double s3 = 6, Ht = 8, SA; // Formula for calculating the area SA = b * h + (s1 + s2 + s3) * Ht; // Displaying the area System.out.printf(\"The area of triangular prism is : %f\", SA); } public static void main(String[] args) { Calculate_area(); }}// This code is contributed by Nishant Tanwar", "e": 2685, "s": 2107, "text": null }, { "code": "# Python3 Program to calculate the# Surface area of a triangular prism # Function for calculating the areadef Calculate_area(): # Initialization b = 3 h = 4 s1 = 3 s2 = 6 s3 = 6 Ht = 8 # Formula for calculating the area SA = b * h + (s1 + s2 + s3) * Ht # Displaying the area print (\"The area of triangular prism is :\",SA) # Driver codeif __name__ == '__main__': # Function calling Calculate_area() # This code is contributed by# Surendra_Gangwar", "e": 3177, "s": 2685, "text": null }, { "code": "// C# Program to calculate the// Surface area of a triangular prismusing System;public class Prism { static void Calculate_area() { // Initialization double b = 3, h = 4, s1 = 3, s2 = 6; double s3 = 6, Ht = 8, SA; // Formula for calculating the area SA = b * h + (s1 + s2 + s3) * Ht; // Displaying the area Console.WriteLine(\"The area of triangular prism is : \" + SA); } static public void Main(String[] args) { Calculate_area(); }}", "e": 3690, "s": 3177, "text": null }, { "code": "<?php// PHP Program to calculate// the Surface area of a// triangular prism // Function for calculating// the areafunction Calculate_area(){ // Initialization $b = 3; $h = 4; $s1 = 3; $s2 = 6; $s3 = 6; $Ht = 8; $SA; // Formula for calculating // the area $SA = $b * $h + ($s1 + $s2 + $s3) * $Ht; // Displaying the area echo \"The area of triangular\". \" prism is : \" , $SA;} // Driver code // Function callingCalculate_area(); // This code is contributed by m_kit?>", "e": 4204, "s": 3690, "text": null }, { "code": "<script>// javascript Program to calculate the// Surface area of a triangular prism // Function for calculating the areafunction Calculate_area(){ // Initialization let b = 3, h = 4, s1 = 3, s2 = 6; let s3 = 6, Ht = 8, SA; // Formula for calculating the area SA = b * h + (s1 + s2 + s3) * Ht; // Displaying the area document.write( \"The area of triangular prism is : \" +SA);} // Driver code // Function calling Calculate_area(); // This code is contributed by Rajput-Ji </script>", "e": 4722, "s": 4204, "text": null }, { "code": null, "e": 4760, "s": 4722, "text": "The area of triangular prism is : 132" }, { "code": null, "e": 4766, "s": 4760, "text": "jit_t" }, { "code": null, "e": 4781, "s": 4766, "text": "Nishant Tanwar" }, { "code": null, "e": 4798, "s": 4781, "text": "SURENDRA_GANGWAR" }, { "code": null, "e": 4808, "s": 4798, "text": "Rajput-Ji" }, { "code": null, "e": 4827, "s": 4808, "text": "school-programming" }, { "code": null, "e": 4837, "s": 4827, "text": "Geometric" }, { "code": null, "e": 4850, "s": 4837, "text": "Mathematical" }, { "code": null, "e": 4863, "s": 4850, "text": "Mathematical" }, { "code": null, "e": 4873, "s": 4863, "text": "Geometric" } ]
Working With the TextView in Android
10 Jun, 2021 TextView in Android is one of the basic and important UI elements. This plays a very important role in the UI experience and depends on how the information is displayed to the user. This TextView widget in android can be dynamized in various contexts. For example, if the important part of the information is to be highlighted then the substring that contains, it is to be italicized or it has to be made bold, one more scenario is where if the information in TextView contains a hyperlink that directs to a particular web URL then it has to be spanned with hyperlink and has to be underlined. Have a look at the following list and image to get an idea of the overall discussion. Formatting the TextViewSize of the TextViewChanging Text StyleChanging the Text ColorText ShadowLetter Spacing and All CapsAdding Icons for TextViewHTML Formatting of the TextView Formatting the TextView Size of the TextView Changing Text Style Changing the Text Color Text Shadow Letter Spacing and All Caps Adding Icons for TextView HTML Formatting of the TextView Step 1: Create an Empty Activity Project Create an empty activity Android Studio Project. Refer to Android | How to Create/Start a New Project in Android Studio? to know how To Create an empty activity Android Studio project. Step 2: Working with the activity_main.xml file The main layout and one, which includes only a TextView and as varied as we go on discuss the various contexts. To implement the UI of the activity invoke the following code inside the activity_main.xml file. 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" tools:ignore="HardcodedText"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="GeeksforGeeks" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent" /> </androidx.constraintlayout.widget.ConstraintLayout> Output UI: Android offers mainly 3 types of typefaces normal sans serif monospace The above four types of faces are to be invoked under the “typeFace” attribute of the TextView in XML. Invoke the following code and note the “typeFace” attribute of the TextView. 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" tools:ignore="HardcodedText"> <!--the below typeFace attribute has to invoked with values mentioned--> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="GeeksforGeeks" android:textSize="32sp" android:typeface="normal" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent" /> </androidx.constraintlayout.widget.ConstraintLayout> Output: This feature of the Text view upholds what type of content has to be shown to the user. For example, if there is a Heading, there are 6 types of heading that can be implemented have a look at the following image which contains the guidelines for the size of the text view and style of the text view which is recommended by Google’s Material Design. The attribute which is used to change the size of the Text View in android is “textSize”. Refer to the following code and its output for better understanding. XML <?xml version="1.0" encoding="utf-8"?><LinearLayout 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" android:orientation="vertical" tools:context=".MainActivity" tools:ignore="HardcodedText"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginStart="32dp" android:layout_marginTop="64dp" android:textSize="48sp" android:text="H3 Heading" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginStart="32dp" android:layout_marginTop="32dp" android:textSize="32sp" android:text="H6 Heading" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginStart="32dp" android:layout_marginTop="32dp" android:textSize="16sp" android:text="Body 1" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginStart="32dp" android:layout_marginTop="32dp" android:textSize="14sp" android:text="Body 2" /> </LinearLayout> Output: In Android there are basically three text styles: Bold Italic Normal The text style of the text in android can be implemented using the attribute “textStyle”. Multiple text styles can also be implemented using the pipeline operator. Example “android:textStyle=”bold|italic”. To implement the various text styles refer to the following code and its output. XML <?xml version="1.0" encoding="utf-8"?><LinearLayout 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" tools:ignore="HardcodedText"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginStart="32dp" android:layout_marginTop="32dp" android:orientation="vertical"> <!--the below textStyle attribute has to invoked with values mentioned--> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="GeeksforGeeks" android:textStyle="italic" android:textSize="32sp" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="32dp" android:text="GeeksforGeeks" android:textStyle="bold" android:textSize="32sp" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="32dp" android:text="GeeksforGeeks" android:textStyle="normal" android:textSize="32sp" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="32dp" android:text="GeeksforGeeks" android:textStyle="bold|italic" android:textSize="32sp" /> </LinearLayout> </LinearLayout> Output: The color of the text should also change according to the change in the context of the information displayed to the user. For example, if there is warning text it must be in the red color and for disabled text, the opacity or the text color should be grayish. To change the color of the text, the attribute “textColor” is used. Android also offers the predefined text colors, which can be implemented using “@android:color/yourColor” as value for the “textColor”. Here the value may be hex code or the predefined colors offered by the android. Refer to the following code and its output for better understanding. XML <?xml version="1.0" encoding="utf-8"?><LinearLayout 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" android:orientation="vertical" tools:context=".MainActivity" tools:ignore="HardcodedText"> <!--the value predefined by android--> <TextView android:id="@+id/text" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginStart="32dp" android:layout_marginTop="64dp" android:text="Warning Message" android:textColor="#B00020" android:textSize="32sp" /> <!--the value predefined by android--> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginStart="32dp" android:layout_marginTop="16dp" android:text="Disabled Text" android:textColor="@android:color/darker_gray" android:textSize="32sp" /> <!--the value is hex code--> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginStart="32dp" android:layout_marginTop="16dp" android:text="GeeksforGeeks" android:textColor="#000000" android:textSize="32sp" /> </LinearLayout> Output: Shadow for the text can also be given in Android. The attributes required for the shadowed text view are: android:shadowDx=”integer_value” -> which decides the distance of text from its shadow with respect to x axis, if the integer_value is positive the shadow is on positive of the x axis and vice versa. android:shadowDy=”integer_value” -> which decides the distance of text from its shadow with respect to y axis, if the integer_value is positive the shadow is on negative of the y axis and vice versa. android:shadowRadius=”integer_value” -> which decides the amount of the shadow to be given for the text view. Refer to the following code and its output for better understanding. XML <?xml version="1.0" encoding="utf-8"?><LinearLayout 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" android:orientation="vertical" tools:context=".MainActivity" tools:ignore="HardcodedText"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginStart="32dp" android:layout_marginTop="16dp" android:shadowColor="@color/green_500" android:shadowDx="4" android:shadowDy="4" android:shadowRadius="10" android:text="GeeksforGeeks" android:textColor="#000000" android:textSize="32sp" tools:targetApi="ice_cream_sandwich" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginStart="32dp" android:layout_marginTop="16dp" android:padding="8dp" android:shadowColor="@color/green_500" android:shadowDx="-15" android:shadowDy="4" android:shadowRadius="10" android:text="GeeksforGeeks" android:textColor="#000000" android:textSize="32sp" tools:targetApi="ice_cream_sandwich" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginStart="32dp" android:layout_marginTop="16dp" android:shadowColor="@color/green_500" android:shadowDx="4" android:shadowDy="-15" android:shadowRadius="10" android:text="GeeksforGeeks" android:textColor="#000000" android:textSize="32sp" tools:targetApi="ice_cream_sandwich" /> </LinearLayout> Output: Letter spacing and capital letters are some of the important properties of the text View in android. For the text of buttons and tab layouts, the text should be in uppercase letters recommended by Google Material Design. The letter spacing also should be maintained according to the scenario. android:letterSpacing=”floatingTypeValue” -> This attribute is used to give the space between each of the letters. android:textAllCaps=”trueOrfalse” -> This attribute decides, all the letters should be in uppercase or not. Refer to the following code and its output for better understanding. XML <?xml version="1.0" encoding="utf-8"?><LinearLayout 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" android:orientation="vertical" tools:context=".MainActivity" tools:ignore="HardcodedText"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginStart="32dp" android:layout_marginTop="64dp" android:letterSpacing="0.15" android:text="GeeksforGeeks" android:textColor="@android:color/black" android:textSize="32sp" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginStart="32dp" android:layout_marginTop="64dp" android:text="GeeksforGeeks" android:textAllCaps="true" android:textColor="@android:color/black" android:textSize="32sp" /> </LinearLayout> Output: Android also allows adding drawable with the text views. There are three positions to add the icons for the TextView. They are a start, end, top, and bottom. Refer to the following code and its output, to know how to add the drawable icons to the Text View. XML <?xml version="1.0" encoding="utf-8"?><LinearLayout 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" android:orientation="vertical" tools:context=".MainActivity" tools:ignore="HardcodedText"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginStart="32dp" android:layout_marginTop="64dp" android:drawableStart="@drawable/ic_lappy" android:padding="4dp" android:text="GeeksforGeeks" android:textColor="@android:color/black" android:textSize="32sp" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginStart="32dp" android:layout_marginTop="64dp" android:drawableEnd="@drawable/ic_lappy" android:padding="4dp" android:text="GeeksforGeeks" android:textColor="@android:color/black" android:textSize="32sp" /> </LinearLayout> Output: In Android, the string can be formatted using the Html class. Refer to the following example for a better understanding. Add the following code inside the activity_main.xml. 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:id="@+id/text" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginStart="8dp" android:layout_marginEnd="8dp" android:focusable="auto" android:textSize="32sp" 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 add the following code inside the MainActivity.kt file. Kotlin import android.os.Buildimport androidx.appcompat.app.AppCompatActivityimport android.os.Bundleimport android.text.Htmlimport android.text.method.LinkMovementMethodimport android.widget.TextViewimport androidx.annotation.RequiresApi class MainActivity : AppCompatActivity() { @RequiresApi(Build.VERSION_CODES.N) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val text: TextView = findViewById(R.id.text) val s: String = "This is <i>italic</i> <b>bold</b> <u>underlined</u> <br>Goto <a href='https://www.geeksforgeeks.org'>GeegksforGeeks</a>" // movementMethod which traverses the links in the text buffer text.movementMethod = LinkMovementMethod.getInstance() text.text = Html.fromHtml(s, Html.FROM_HTML_MODE_COMPACT) }} Output: Run on Emulator ruhelaa48 android Android-View Technical Scripter 2020 Android Technical Scripter Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Android SDK and it's Components Flutter - Custom Bottom Navigation Bar Retrofit with Kotlin Coroutine in Android How to Post Data to API using Retrofit in Android? Flutter - Stack Widget Introduction to Android Development Animation in Android with Example Data Binding in Android with Example Fragment Lifecycle in Android Activity Lifecycle in Android with Demo App
[ { "code": null, "e": 28, "s": 0, "text": "\n10 Jun, 2021" }, { "code": null, "e": 708, "s": 28, "text": "TextView in Android is one of the basic and important UI elements. This plays a very important role in the UI experience and depends on how the information is displayed to the user. This TextView widget in android can be dynamized in various contexts. For example, if the important part of the information is to be highlighted then the substring that contains, it is to be italicized or it has to be made bold, one more scenario is where if the information in TextView contains a hyperlink that directs to a particular web URL then it has to be spanned with hyperlink and has to be underlined. Have a look at the following list and image to get an idea of the overall discussion." }, { "code": null, "e": 888, "s": 708, "text": "Formatting the TextViewSize of the TextViewChanging Text StyleChanging the Text ColorText ShadowLetter Spacing and All CapsAdding Icons for TextViewHTML Formatting of the TextView" }, { "code": null, "e": 912, "s": 888, "text": "Formatting the TextView" }, { "code": null, "e": 933, "s": 912, "text": "Size of the TextView" }, { "code": null, "e": 953, "s": 933, "text": "Changing Text Style" }, { "code": null, "e": 977, "s": 953, "text": "Changing the Text Color" }, { "code": null, "e": 989, "s": 977, "text": "Text Shadow" }, { "code": null, "e": 1017, "s": 989, "text": "Letter Spacing and All Caps" }, { "code": null, "e": 1043, "s": 1017, "text": "Adding Icons for TextView" }, { "code": null, "e": 1075, "s": 1043, "text": "HTML Formatting of the TextView" }, { "code": null, "e": 1116, "s": 1075, "text": "Step 1: Create an Empty Activity Project" }, { "code": null, "e": 1301, "s": 1116, "text": "Create an empty activity Android Studio Project. Refer to Android | How to Create/Start a New Project in Android Studio? to know how To Create an empty activity Android Studio project." }, { "code": null, "e": 1349, "s": 1301, "text": "Step 2: Working with the activity_main.xml file" }, { "code": null, "e": 1461, "s": 1349, "text": "The main layout and one, which includes only a TextView and as varied as we go on discuss the various contexts." }, { "code": null, "e": 1558, "s": 1461, "text": "To implement the UI of the activity invoke the following code inside the activity_main.xml file." }, { "code": null, "e": 1562, "s": 1558, "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\" tools:ignore=\"HardcodedText\"> <TextView android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:text=\"GeeksforGeeks\" 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": 2364, "s": 1562, "text": null }, { "code": null, "e": 2379, "s": 2368, "text": "Output UI:" }, { "code": null, "e": 2424, "s": 2381, "text": "Android offers mainly 3 types of typefaces" }, { "code": null, "e": 2431, "s": 2424, "text": "normal" }, { "code": null, "e": 2436, "s": 2431, "text": "sans" }, { "code": null, "e": 2442, "s": 2436, "text": "serif" }, { "code": null, "e": 2452, "s": 2442, "text": "monospace" }, { "code": null, "e": 2555, "s": 2452, "text": "The above four types of faces are to be invoked under the “typeFace” attribute of the TextView in XML." }, { "code": null, "e": 2632, "s": 2555, "text": "Invoke the following code and note the “typeFace” attribute of the TextView." }, { "code": null, "e": 2638, "s": 2634, "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\" tools:ignore=\"HardcodedText\"> <!--the below typeFace attribute has to invoked with values mentioned--> <TextView android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:text=\"GeeksforGeeks\" android:textSize=\"32sp\" android:typeface=\"normal\" 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": 3590, "s": 2638, "text": null }, { "code": null, "e": 3602, "s": 3594, "text": "Output:" }, { "code": null, "e": 3953, "s": 3604, "text": "This feature of the Text view upholds what type of content has to be shown to the user. For example, if there is a Heading, there are 6 types of heading that can be implemented have a look at the following image which contains the guidelines for the size of the text view and style of the text view which is recommended by Google’s Material Design." }, { "code": null, "e": 4043, "s": 3953, "text": "The attribute which is used to change the size of the Text View in android is “textSize”." }, { "code": null, "e": 4112, "s": 4043, "text": "Refer to the following code and its output for better understanding." }, { "code": null, "e": 4118, "s": 4114, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><LinearLayout 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\" android:orientation=\"vertical\" tools:context=\".MainActivity\" tools:ignore=\"HardcodedText\"> <TextView android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_marginStart=\"32dp\" android:layout_marginTop=\"64dp\" android:textSize=\"48sp\" android:text=\"H3 Heading\" /> <TextView android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_marginStart=\"32dp\" android:layout_marginTop=\"32dp\" android:textSize=\"32sp\" android:text=\"H6 Heading\" /> <TextView android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_marginStart=\"32dp\" android:layout_marginTop=\"32dp\" android:textSize=\"16sp\" android:text=\"Body 1\" /> <TextView android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_marginStart=\"32dp\" android:layout_marginTop=\"32dp\" android:textSize=\"14sp\" android:text=\"Body 2\" /> </LinearLayout>", "e": 5470, "s": 4118, "text": null }, { "code": null, "e": 5483, "s": 5474, "text": "Output: " }, { "code": null, "e": 5535, "s": 5485, "text": "In Android there are basically three text styles:" }, { "code": null, "e": 5540, "s": 5535, "text": "Bold" }, { "code": null, "e": 5547, "s": 5540, "text": "Italic" }, { "code": null, "e": 5554, "s": 5547, "text": "Normal" }, { "code": null, "e": 5644, "s": 5554, "text": "The text style of the text in android can be implemented using the attribute “textStyle”." }, { "code": null, "e": 5760, "s": 5644, "text": "Multiple text styles can also be implemented using the pipeline operator. Example “android:textStyle=”bold|italic”." }, { "code": null, "e": 5841, "s": 5760, "text": "To implement the various text styles refer to the following code and its output." }, { "code": null, "e": 5847, "s": 5843, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><LinearLayout 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\" tools:ignore=\"HardcodedText\"> <LinearLayout android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_marginStart=\"32dp\" android:layout_marginTop=\"32dp\" android:orientation=\"vertical\"> <!--the below textStyle attribute has to invoked with values mentioned--> <TextView android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:text=\"GeeksforGeeks\" android:textStyle=\"italic\" android:textSize=\"32sp\" /> <TextView android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_marginTop=\"32dp\" android:text=\"GeeksforGeeks\" android:textStyle=\"bold\" android:textSize=\"32sp\" /> <TextView android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_marginTop=\"32dp\" android:text=\"GeeksforGeeks\" android:textStyle=\"normal\" android:textSize=\"32sp\" /> <TextView android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_marginTop=\"32dp\" android:text=\"GeeksforGeeks\" android:textStyle=\"bold|italic\" android:textSize=\"32sp\" /> </LinearLayout> </LinearLayout>", "e": 7630, "s": 5847, "text": null }, { "code": null, "e": 7642, "s": 7634, "text": "Output:" }, { "code": null, "e": 7766, "s": 7644, "text": "The color of the text should also change according to the change in the context of the information displayed to the user." }, { "code": null, "e": 7972, "s": 7766, "text": "For example, if there is warning text it must be in the red color and for disabled text, the opacity or the text color should be grayish. To change the color of the text, the attribute “textColor” is used." }, { "code": null, "e": 8188, "s": 7972, "text": "Android also offers the predefined text colors, which can be implemented using “@android:color/yourColor” as value for the “textColor”. Here the value may be hex code or the predefined colors offered by the android." }, { "code": null, "e": 8257, "s": 8188, "text": "Refer to the following code and its output for better understanding." }, { "code": null, "e": 8263, "s": 8259, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><LinearLayout 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\" android:orientation=\"vertical\" tools:context=\".MainActivity\" tools:ignore=\"HardcodedText\"> <!--the value predefined by android--> <TextView android:id=\"@+id/text\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_marginStart=\"32dp\" android:layout_marginTop=\"64dp\" android:text=\"Warning Message\" android:textColor=\"#B00020\" android:textSize=\"32sp\" /> <!--the value predefined by android--> <TextView android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_marginStart=\"32dp\" android:layout_marginTop=\"16dp\" android:text=\"Disabled Text\" android:textColor=\"@android:color/darker_gray\" android:textSize=\"32sp\" /> <!--the value is hex code--> <TextView android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_marginStart=\"32dp\" android:layout_marginTop=\"16dp\" android:text=\"GeeksforGeeks\" android:textColor=\"#000000\" android:textSize=\"32sp\" /> </LinearLayout>", "e": 9651, "s": 8263, "text": null }, { "code": null, "e": 9664, "s": 9655, "text": "Output: " }, { "code": null, "e": 9772, "s": 9666, "text": "Shadow for the text can also be given in Android. The attributes required for the shadowed text view are:" }, { "code": null, "e": 9972, "s": 9772, "text": "android:shadowDx=”integer_value” -> which decides the distance of text from its shadow with respect to x axis, if the integer_value is positive the shadow is on positive of the x axis and vice versa." }, { "code": null, "e": 10172, "s": 9972, "text": "android:shadowDy=”integer_value” -> which decides the distance of text from its shadow with respect to y axis, if the integer_value is positive the shadow is on negative of the y axis and vice versa." }, { "code": null, "e": 10282, "s": 10172, "text": "android:shadowRadius=”integer_value” -> which decides the amount of the shadow to be given for the text view." }, { "code": null, "e": 10351, "s": 10282, "text": "Refer to the following code and its output for better understanding." }, { "code": null, "e": 10357, "s": 10353, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><LinearLayout 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\" android:orientation=\"vertical\" tools:context=\".MainActivity\" tools:ignore=\"HardcodedText\"> <TextView android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_marginStart=\"32dp\" android:layout_marginTop=\"16dp\" android:shadowColor=\"@color/green_500\" android:shadowDx=\"4\" android:shadowDy=\"4\" android:shadowRadius=\"10\" android:text=\"GeeksforGeeks\" android:textColor=\"#000000\" android:textSize=\"32sp\" tools:targetApi=\"ice_cream_sandwich\" /> <TextView android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_marginStart=\"32dp\" android:layout_marginTop=\"16dp\" android:padding=\"8dp\" android:shadowColor=\"@color/green_500\" android:shadowDx=\"-15\" android:shadowDy=\"4\" android:shadowRadius=\"10\" android:text=\"GeeksforGeeks\" android:textColor=\"#000000\" android:textSize=\"32sp\" tools:targetApi=\"ice_cream_sandwich\" /> <TextView android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_marginStart=\"32dp\" android:layout_marginTop=\"16dp\" android:shadowColor=\"@color/green_500\" android:shadowDx=\"4\" android:shadowDy=\"-15\" android:shadowRadius=\"10\" android:text=\"GeeksforGeeks\" android:textColor=\"#000000\" android:textSize=\"32sp\" tools:targetApi=\"ice_cream_sandwich\" /> </LinearLayout>", "e": 12144, "s": 10357, "text": null }, { "code": null, "e": 12156, "s": 12148, "text": "Output:" }, { "code": null, "e": 12259, "s": 12158, "text": "Letter spacing and capital letters are some of the important properties of the text View in android." }, { "code": null, "e": 12379, "s": 12259, "text": "For the text of buttons and tab layouts, the text should be in uppercase letters recommended by Google Material Design." }, { "code": null, "e": 12451, "s": 12379, "text": "The letter spacing also should be maintained according to the scenario." }, { "code": null, "e": 12566, "s": 12451, "text": "android:letterSpacing=”floatingTypeValue” -> This attribute is used to give the space between each of the letters." }, { "code": null, "e": 12674, "s": 12566, "text": "android:textAllCaps=”trueOrfalse” -> This attribute decides, all the letters should be in uppercase or not." }, { "code": null, "e": 12743, "s": 12674, "text": "Refer to the following code and its output for better understanding." }, { "code": null, "e": 12749, "s": 12745, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><LinearLayout 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\" android:orientation=\"vertical\" tools:context=\".MainActivity\" tools:ignore=\"HardcodedText\"> <TextView android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_marginStart=\"32dp\" android:layout_marginTop=\"64dp\" android:letterSpacing=\"0.15\" android:text=\"GeeksforGeeks\" android:textColor=\"@android:color/black\" android:textSize=\"32sp\" /> <TextView android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_marginStart=\"32dp\" android:layout_marginTop=\"64dp\" android:text=\"GeeksforGeeks\" android:textAllCaps=\"true\" android:textColor=\"@android:color/black\" android:textSize=\"32sp\" /> </LinearLayout>", "e": 13776, "s": 12749, "text": null }, { "code": null, "e": 13788, "s": 13780, "text": "Output:" }, { "code": null, "e": 13847, "s": 13790, "text": "Android also allows adding drawable with the text views." }, { "code": null, "e": 13948, "s": 13847, "text": "There are three positions to add the icons for the TextView. They are a start, end, top, and bottom." }, { "code": null, "e": 14048, "s": 13948, "text": "Refer to the following code and its output, to know how to add the drawable icons to the Text View." }, { "code": null, "e": 14054, "s": 14050, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><LinearLayout 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\" android:orientation=\"vertical\" tools:context=\".MainActivity\" tools:ignore=\"HardcodedText\"> <TextView android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_marginStart=\"32dp\" android:layout_marginTop=\"64dp\" android:drawableStart=\"@drawable/ic_lappy\" android:padding=\"4dp\" android:text=\"GeeksforGeeks\" android:textColor=\"@android:color/black\" android:textSize=\"32sp\" /> <TextView android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_marginStart=\"32dp\" android:layout_marginTop=\"64dp\" android:drawableEnd=\"@drawable/ic_lappy\" android:padding=\"4dp\" android:text=\"GeeksforGeeks\" android:textColor=\"@android:color/black\" android:textSize=\"32sp\" /> </LinearLayout>", "e": 15222, "s": 14054, "text": null }, { "code": null, "e": 15235, "s": 15226, "text": "Output: " }, { "code": null, "e": 15299, "s": 15237, "text": "In Android, the string can be formatted using the Html class." }, { "code": null, "e": 15358, "s": 15299, "text": "Refer to the following example for a better understanding." }, { "code": null, "e": 15411, "s": 15358, "text": "Add the following code inside the activity_main.xml." }, { "code": null, "e": 15417, "s": 15413, "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:id=\"@+id/text\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_marginStart=\"8dp\" android:layout_marginEnd=\"8dp\" android:focusable=\"auto\" android:textSize=\"32sp\" 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": 16322, "s": 15417, "text": null }, { "code": null, "e": 16385, "s": 16325, "text": "Now add the following code inside the MainActivity.kt file." }, { "code": null, "e": 16394, "s": 16387, "text": "Kotlin" }, { "code": "import android.os.Buildimport androidx.appcompat.app.AppCompatActivityimport android.os.Bundleimport android.text.Htmlimport android.text.method.LinkMovementMethodimport android.widget.TextViewimport androidx.annotation.RequiresApi class MainActivity : AppCompatActivity() { @RequiresApi(Build.VERSION_CODES.N) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val text: TextView = findViewById(R.id.text) val s: String = \"This is <i>italic</i> <b>bold</b> <u>underlined</u> <br>Goto <a href='https://www.geeksforgeeks.org'>GeegksforGeeks</a>\" // movementMethod which traverses the links in the text buffer text.movementMethod = LinkMovementMethod.getInstance() text.text = Html.fromHtml(s, Html.FROM_HTML_MODE_COMPACT) }}", "e": 17266, "s": 16394, "text": null }, { "code": null, "e": 17294, "s": 17270, "text": "Output: Run on Emulator" }, { "code": null, "e": 17308, "s": 17298, "text": "ruhelaa48" }, { "code": null, "e": 17316, "s": 17308, "text": "android" }, { "code": null, "e": 17329, "s": 17316, "text": "Android-View" }, { "code": null, "e": 17353, "s": 17329, "text": "Technical Scripter 2020" }, { "code": null, "e": 17361, "s": 17353, "text": "Android" }, { "code": null, "e": 17380, "s": 17361, "text": "Technical Scripter" }, { "code": null, "e": 17388, "s": 17380, "text": "Android" }, { "code": null, "e": 17486, "s": 17388, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 17518, "s": 17486, "text": "Android SDK and it's Components" }, { "code": null, "e": 17557, "s": 17518, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 17599, "s": 17557, "text": "Retrofit with Kotlin Coroutine in Android" }, { "code": null, "e": 17650, "s": 17599, "text": "How to Post Data to API using Retrofit in Android?" }, { "code": null, "e": 17673, "s": 17650, "text": "Flutter - Stack Widget" }, { "code": null, "e": 17709, "s": 17673, "text": "Introduction to Android Development" }, { "code": null, "e": 17743, "s": 17709, "text": "Animation in Android with Example" }, { "code": null, "e": 17780, "s": 17743, "text": "Data Binding in Android with Example" }, { "code": null, "e": 17810, "s": 17780, "text": "Fragment Lifecycle in Android" } ]
Generate simple ASCII tables using prettytable in Python
29 Aug, 2020 Prettytable is a Python library used to print ASCII tables in an attractive form and to read data from CSV, HTML, or database cursor and output data in ASCII or HTML. We can control many aspects of a table, such as the width of the column padding, the alignment of text, or the table border. In order to be able to use prettytable library first we need toinstall it using pip tool command: pip install prettytable Data can be inserted in a PrettyTable either row by row or column by column. To do this you can set the field names first using the field_names attribute, and then add the rows one at a time using the add_row method. Example: Python3 # importing required libraryfrom prettytable import PrettyTable # creating an empty PrettyTablex = PrettyTable() # adding data into the table# row by rowx.field_names = ["First name", "Last name", "Salary", "City", "DOB"]x.add_row(["Shubham", "Chauhan", 60000, "Lucknow", "22 Feb 1999"])x.add_row(["Saksham", "Chauhan", 50000, "Hardoi", "21 Aug 2000"])x.add_row(["Preeti", "Singh", 40000, "Unnao", "10 Jan 1995"])x.add_row(["Ayushi", "Chauhan", 65000, "Haridwar", "30 Jan 2002"])x.add_row(["Abhishek", "Rai", 70000, "Greater Noida", "16 Jan 1999"])x.add_row(["Dinesh", "Pratap", 80000, "Delhi", "3 Aug 1998"])x.add_row(["Chandra", "Kant", 85000, "Ghaziabad", "18 Sept 1997"]) # printing generated tableprint(x) Output: To do this you use the add_column method, which takes two arguments – a string which is the name for the field the column you are adding corresponds to, and a list or tuple which contains the column data”Example: Python3 # importing required libraryfrom prettytable import PrettyTable # creating an empty PrettyTablex = PrettyTable() # adding data into the table# column by columnx.add_column("First name", ["Shubham", "Saksham", "Preeti", "Ayushi", "Abhishek", "Dinesh", "Chandra"]) x.add_column("Last name", ["Chauhan", "Chauhan", "Singh", "Chauhan", "Rai", "Pratap", "Kant"]) x.add_column("Salary", [60000, 50000, 40000, 65000, 70000, 80000, 85000])x.add_column("City", ["Lucknow", "Hardoi", "Unnao", "Haridwar", "Greater Noida", "Delhi", "Ghaziabad"]) x.add_column("DOB", ["22 Feb 1999", "21 Aug 2000", "10 Jan 1995", "30 Jan 2002", "16 Jan 1999", "3 Aug 1998", "18 Sept 1997"]) # printing generated tableprint(x) Output: A specific row can be deleted using the del_row() method. Index of the row to be deleted is passed as a parameter. Example: Python3 # importing required libraryfrom prettytable import PrettyTable # creating an empty PrettyTablex = PrettyTable() # adding data into the table# column by columnx.add_column("First name", ["Shubham", "Saksham", "Preeti", "Ayushi", "Abhishek", "Dinesh", "Chandra"]) x.add_column("Last name", ["Chauhan", "Chauhan", "Singh", "Chauhan", "Rai", "Pratap", "Kant"]) x.add_column("Salary", [60000, 50000, 40000, 65000, 70000, 80000, 85000])x.add_column("City", ["Lucknow", "Hardoi", "Unnao", "Haridwar", "Greater Noida", "Delhi", "Ghaziabad"]) x.add_column("DOB", ["22 Feb 1999", "21 Aug 2000", "10 Jan 1995", "30 Jan 2002", "16 Jan 1999", "3 Aug 1998", "18 Sept 1997"]) # Deleting rowx.del_row(2)x.del_row(3) # printing generated tableprint(x) Output: All the rows in the table can be deleted using the clear_rows() method. This method will keep the column names. To delete both rows and columns name clear() method is used. Example: Python3 # importing required libraryfrom prettytable import PrettyTable # creating an empty PrettyTablex = PrettyTable() # adding data into the table# column by columnx.add_column("First name", ["Shubham", "Saksham", "Preeti", "Ayushi", "Abhishek", "Dinesh", "Chandra"]) x.add_column("Last name", ["Chauhan", "Chauhan", "Singh", "Chauhan", "Rai", "Pratap", "Kant"]) x.add_column("Salary", [60000, 50000, 40000, 65000, 70000, 80000, 85000])x.add_column("City", ["Lucknow", "Hardoi", "Unnao", "Haridwar", "Greater Noida", "Delhi", "Ghaziabad"]) x.add_column("DOB", ["22 Feb 1999", "21 Aug 2000", "10 Jan 1995", "30 Jan 2002", "16 Jan 1999", "3 Aug 1998", "18 Sept 1997"]) # Deleting all rowsx.clear_rows() print(x) # Deleting column name as wellprint("\nAfter clearing column names as well")x.clear() print(x) Output: You can control which rows or which columns are going to be displayed. Python3 # importing required libraryfrom prettytable import PrettyTable # creating an empty PrettyTablex = PrettyTable() # adding data into the table# column by columnx.field_names = ["First name", "Last name", "Salary", "City", "DOB"]x.add_row(["Shubham", "Chauhan", 60000, "Lucknow", "22 Feb 1999"])x.add_row(["Saksham", "Chauhan", 50000, "Hardoi", "21 Aug 2000"])x.add_row(["Preeti", "Singh", 40000, "Unnao", "10 Jan 1995"])x.add_row(["Ayushi", "Chauhan", 65000, "Haridwar", "30 Jan 2002"])x.add_row(["Abhishek", "Rai", 70000, "Greater Noida", "16 Jan 1999"])x.add_row(["Dinesh", "Pratap", 80000, "Delhi", "3 Aug 1998"])x.add_row(["Chandra", "Kant", 85000, "Ghaziabad", "18 Sept 1997"]) # With the start and end parameters, we can select# which rows to display in the output.print(x.get_string(start=2, end=4)) # With the fields option we can select columns# which are going to be displayed.print(x.get_string(fields=["First name", "Salary", "City"])) Output: Sorting(ascending or descending) can be performed using the sortby property, in which we sort the table by specifying a column to be sorted. HTML output of the table can be generated using the get_html_string method. Python3 # importing required libraryfrom prettytable import PrettyTable # creating an empty PrettyTablex = PrettyTable() # adding data into the table# row by rowx.field_names = ["First name", "Last name", "Salary", "City", "DOB"]x.add_row(["Shubham", "Chauhan", 60000, "Lucknow", "22 Feb 1999"])x.add_row(["Saksham", "Chauhan", 50000, "Hardoi", "21 Aug 2000"])x.add_row(["Preeti", "Singh", 40000, "Unnao", "10 Jan 1995"])x.add_row(["Ayushi", "Chauhan", 65000, "Haridwar", "30 Jan 2002"])x.add_row(["Abhishek", "Rai", 70000, "Greater Noida", "16 Jan 1999"])x.add_row(["Dinesh", "Pratap", 80000, "Delhi", "3 Aug 1998"])x.add_row(["Chandra", "Kant", 85000, "Ghaziabad", "18 Sept 1997"]) # printing generated tableprint("Original Table:")print(x) # printing the HTML string of this tableprint("\nHTML code for this Table:")print(x.get_html_string()) # printing table after sorting(ascending) # by column salaryx.sortby = "Salary"print("\nSorted Table by Salary:")print(x.get_string()) # printing table after sorting(ascending) # by column cityx.sortby = "City"x.reversesort = Trueprint("\nReverse Sorted Table by City:")print(x.get_string()) Output: Python-PrettyTable Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n29 Aug, 2020" }, { "code": null, "e": 321, "s": 28, "text": "Prettytable is a Python library used to print ASCII tables in an attractive form and to read data from CSV, HTML, or database cursor and output data in ASCII or HTML. We can control many aspects of a table, such as the width of the column padding, the alignment of text, or the table border. " }, { "code": null, "e": 419, "s": 321, "text": "In order to be able to use prettytable library first we need toinstall it using pip tool command:" }, { "code": null, "e": 444, "s": 419, "text": "pip install prettytable\n" }, { "code": null, "e": 521, "s": 444, "text": "Data can be inserted in a PrettyTable either row by row or column by column." }, { "code": null, "e": 670, "s": 521, "text": "To do this you can set the field names first using the field_names attribute, and then add the rows one at a time using the add_row method. Example:" }, { "code": null, "e": 678, "s": 670, "text": "Python3" }, { "code": "# importing required libraryfrom prettytable import PrettyTable # creating an empty PrettyTablex = PrettyTable() # adding data into the table# row by rowx.field_names = [\"First name\", \"Last name\", \"Salary\", \"City\", \"DOB\"]x.add_row([\"Shubham\", \"Chauhan\", 60000, \"Lucknow\", \"22 Feb 1999\"])x.add_row([\"Saksham\", \"Chauhan\", 50000, \"Hardoi\", \"21 Aug 2000\"])x.add_row([\"Preeti\", \"Singh\", 40000, \"Unnao\", \"10 Jan 1995\"])x.add_row([\"Ayushi\", \"Chauhan\", 65000, \"Haridwar\", \"30 Jan 2002\"])x.add_row([\"Abhishek\", \"Rai\", 70000, \"Greater Noida\", \"16 Jan 1999\"])x.add_row([\"Dinesh\", \"Pratap\", 80000, \"Delhi\", \"3 Aug 1998\"])x.add_row([\"Chandra\", \"Kant\", 85000, \"Ghaziabad\", \"18 Sept 1997\"]) # printing generated tableprint(x)", "e": 1392, "s": 678, "text": null }, { "code": null, "e": 1400, "s": 1392, "text": "Output:" }, { "code": null, "e": 1613, "s": 1400, "text": "To do this you use the add_column method, which takes two arguments – a string which is the name for the field the column you are adding corresponds to, and a list or tuple which contains the column data”Example:" }, { "code": null, "e": 1621, "s": 1613, "text": "Python3" }, { "code": "# importing required libraryfrom prettytable import PrettyTable # creating an empty PrettyTablex = PrettyTable() # adding data into the table# column by columnx.add_column(\"First name\", [\"Shubham\", \"Saksham\", \"Preeti\", \"Ayushi\", \"Abhishek\", \"Dinesh\", \"Chandra\"]) x.add_column(\"Last name\", [\"Chauhan\", \"Chauhan\", \"Singh\", \"Chauhan\", \"Rai\", \"Pratap\", \"Kant\"]) x.add_column(\"Salary\", [60000, 50000, 40000, 65000, 70000, 80000, 85000])x.add_column(\"City\", [\"Lucknow\", \"Hardoi\", \"Unnao\", \"Haridwar\", \"Greater Noida\", \"Delhi\", \"Ghaziabad\"]) x.add_column(\"DOB\", [\"22 Feb 1999\", \"21 Aug 2000\", \"10 Jan 1995\", \"30 Jan 2002\", \"16 Jan 1999\", \"3 Aug 1998\", \"18 Sept 1997\"]) # printing generated tableprint(x)", "e": 2485, "s": 1621, "text": null }, { "code": null, "e": 2493, "s": 2485, "text": "Output:" }, { "code": null, "e": 2608, "s": 2493, "text": "A specific row can be deleted using the del_row() method. Index of the row to be deleted is passed as a parameter." }, { "code": null, "e": 2617, "s": 2608, "text": "Example:" }, { "code": null, "e": 2625, "s": 2617, "text": "Python3" }, { "code": "# importing required libraryfrom prettytable import PrettyTable # creating an empty PrettyTablex = PrettyTable() # adding data into the table# column by columnx.add_column(\"First name\", [\"Shubham\", \"Saksham\", \"Preeti\", \"Ayushi\", \"Abhishek\", \"Dinesh\", \"Chandra\"]) x.add_column(\"Last name\", [\"Chauhan\", \"Chauhan\", \"Singh\", \"Chauhan\", \"Rai\", \"Pratap\", \"Kant\"]) x.add_column(\"Salary\", [60000, 50000, 40000, 65000, 70000, 80000, 85000])x.add_column(\"City\", [\"Lucknow\", \"Hardoi\", \"Unnao\", \"Haridwar\", \"Greater Noida\", \"Delhi\", \"Ghaziabad\"]) x.add_column(\"DOB\", [\"22 Feb 1999\", \"21 Aug 2000\", \"10 Jan 1995\", \"30 Jan 2002\", \"16 Jan 1999\", \"3 Aug 1998\", \"18 Sept 1997\"]) # Deleting rowx.del_row(2)x.del_row(3) # printing generated tableprint(x)", "e": 3529, "s": 2625, "text": null }, { "code": null, "e": 3537, "s": 3529, "text": "Output:" }, { "code": null, "e": 3710, "s": 3537, "text": "All the rows in the table can be deleted using the clear_rows() method. This method will keep the column names. To delete both rows and columns name clear() method is used." }, { "code": null, "e": 3719, "s": 3710, "text": "Example:" }, { "code": null, "e": 3727, "s": 3719, "text": "Python3" }, { "code": "# importing required libraryfrom prettytable import PrettyTable # creating an empty PrettyTablex = PrettyTable() # adding data into the table# column by columnx.add_column(\"First name\", [\"Shubham\", \"Saksham\", \"Preeti\", \"Ayushi\", \"Abhishek\", \"Dinesh\", \"Chandra\"]) x.add_column(\"Last name\", [\"Chauhan\", \"Chauhan\", \"Singh\", \"Chauhan\", \"Rai\", \"Pratap\", \"Kant\"]) x.add_column(\"Salary\", [60000, 50000, 40000, 65000, 70000, 80000, 85000])x.add_column(\"City\", [\"Lucknow\", \"Hardoi\", \"Unnao\", \"Haridwar\", \"Greater Noida\", \"Delhi\", \"Ghaziabad\"]) x.add_column(\"DOB\", [\"22 Feb 1999\", \"21 Aug 2000\", \"10 Jan 1995\", \"30 Jan 2002\", \"16 Jan 1999\", \"3 Aug 1998\", \"18 Sept 1997\"]) # Deleting all rowsx.clear_rows() print(x) # Deleting column name as wellprint(\"\\nAfter clearing column names as well\")x.clear() print(x)", "e": 4697, "s": 3727, "text": null }, { "code": null, "e": 4705, "s": 4697, "text": "Output:" }, { "code": null, "e": 4777, "s": 4705, "text": "You can control which rows or which columns are going to be displayed. " }, { "code": null, "e": 4785, "s": 4777, "text": "Python3" }, { "code": "# importing required libraryfrom prettytable import PrettyTable # creating an empty PrettyTablex = PrettyTable() # adding data into the table# column by columnx.field_names = [\"First name\", \"Last name\", \"Salary\", \"City\", \"DOB\"]x.add_row([\"Shubham\", \"Chauhan\", 60000, \"Lucknow\", \"22 Feb 1999\"])x.add_row([\"Saksham\", \"Chauhan\", 50000, \"Hardoi\", \"21 Aug 2000\"])x.add_row([\"Preeti\", \"Singh\", 40000, \"Unnao\", \"10 Jan 1995\"])x.add_row([\"Ayushi\", \"Chauhan\", 65000, \"Haridwar\", \"30 Jan 2002\"])x.add_row([\"Abhishek\", \"Rai\", 70000, \"Greater Noida\", \"16 Jan 1999\"])x.add_row([\"Dinesh\", \"Pratap\", 80000, \"Delhi\", \"3 Aug 1998\"])x.add_row([\"Chandra\", \"Kant\", 85000, \"Ghaziabad\", \"18 Sept 1997\"]) # With the start and end parameters, we can select# which rows to display in the output.print(x.get_string(start=2, end=4)) # With the fields option we can select columns# which are going to be displayed.print(x.get_string(fields=[\"First name\", \"Salary\", \"City\"]))", "e": 5736, "s": 4785, "text": null }, { "code": null, "e": 5744, "s": 5736, "text": "Output:" }, { "code": null, "e": 5885, "s": 5744, "text": "Sorting(ascending or descending) can be performed using the sortby property, in which we sort the table by specifying a column to be sorted." }, { "code": null, "e": 5961, "s": 5885, "text": "HTML output of the table can be generated using the get_html_string method." }, { "code": null, "e": 5969, "s": 5961, "text": "Python3" }, { "code": "# importing required libraryfrom prettytable import PrettyTable # creating an empty PrettyTablex = PrettyTable() # adding data into the table# row by rowx.field_names = [\"First name\", \"Last name\", \"Salary\", \"City\", \"DOB\"]x.add_row([\"Shubham\", \"Chauhan\", 60000, \"Lucknow\", \"22 Feb 1999\"])x.add_row([\"Saksham\", \"Chauhan\", 50000, \"Hardoi\", \"21 Aug 2000\"])x.add_row([\"Preeti\", \"Singh\", 40000, \"Unnao\", \"10 Jan 1995\"])x.add_row([\"Ayushi\", \"Chauhan\", 65000, \"Haridwar\", \"30 Jan 2002\"])x.add_row([\"Abhishek\", \"Rai\", 70000, \"Greater Noida\", \"16 Jan 1999\"])x.add_row([\"Dinesh\", \"Pratap\", 80000, \"Delhi\", \"3 Aug 1998\"])x.add_row([\"Chandra\", \"Kant\", 85000, \"Ghaziabad\", \"18 Sept 1997\"]) # printing generated tableprint(\"Original Table:\")print(x) # printing the HTML string of this tableprint(\"\\nHTML code for this Table:\")print(x.get_html_string()) # printing table after sorting(ascending) # by column salaryx.sortby = \"Salary\"print(\"\\nSorted Table by Salary:\")print(x.get_string()) # printing table after sorting(ascending) # by column cityx.sortby = \"City\"x.reversesort = Trueprint(\"\\nReverse Sorted Table by City:\")print(x.get_string())", "e": 7105, "s": 5969, "text": null }, { "code": null, "e": 7113, "s": 7105, "text": "Output:" }, { "code": null, "e": 7132, "s": 7113, "text": "Python-PrettyTable" }, { "code": null, "e": 7139, "s": 7132, "text": "Python" } ]
Reader read() method in Java with Examples
07 Feb, 2019 The read() method of Reader Class in Java is used to read a single character from the stream. This method blocks the stream till: It has taken some input from the stream. Some IOException has occurred It has reached the end of the stream while reading. This method is declared as abstract method. It means that the subclasses of Reader abstract class should override this method if desired operation needs to be changed while reading a character. Syntax: public abstract int read() Parameters: This method does not accepts any parameters Return Value: This method returns an integer value which is the integer value read from the stream. It can range from 0 to 65535. Else it returns -1 if no character has been read. Exception: This method throws IOException if some error occurs while input output. Below methods illustrates the working of read() method: Program 1: // Java program to demonstrate// Reader read() method import java.io.*;import java.util.*; class GFG { public static void main(String[] args) { try { String str = "GeeksForGeeks"; // Create a Reader instance Reader reader = new StringReader(str); // Get the character // to be read from the stream int ch; // Read the first 5 characters // to this reader using read() method // This will put the str in the stream // till it is read by the reader for (int i = 0; i < 5; i++) { ch = reader.read(); System.out.println("\nInteger value " + "of character read: " + ch); System.out.println("Actual " + "character read: " + (char)ch); } reader.close(); } catch (Exception e) { System.out.println(e); } }} Integer value of character read: 71 Actual character read: G Integer value of character read: 101 Actual character read: e Integer value of character read: 101 Actual character read: e Integer value of character read: 107 Actual character read: k Integer value of character read: 115 Actual character read: s Program 2: // Java program to demonstrate// Reader read() method import java.io.*;import java.util.*; class GFG { public static void main(String[] args) { try { String str = "GeeksForGeeks"; // Create a Reader instance Reader reader = new StringReader(str); // Get the character // to be read from the stream int ch; // Read the first character // to this reader using read() method // This will put the str in the stream // till it is read by the reader ch = reader.read(); System.out.println("\nInteger value " + "of character read: " + ch); System.out.println("Actual " + "character read: " + (char)ch); reader.close(); } catch (Exception e) { System.out.println(e); } }} Integer value of character read: 71 Actual character read: G Reference: https://docs.oracle.com/javase/9/docs/api/java/io/Reader.html#read– Java-Functions Java-IO package Java-Reader Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Object Oriented Programming (OOPs) Concept in Java How to iterate any Map in Java Interfaces in Java HashMap in Java with Examples Stream In Java ArrayList in Java Collections in Java Singleton Class in Java Multidimensional Arrays in Java Set in Java
[ { "code": null, "e": 52, "s": 24, "text": "\n07 Feb, 2019" }, { "code": null, "e": 182, "s": 52, "text": "The read() method of Reader Class in Java is used to read a single character from the stream. This method blocks the stream till:" }, { "code": null, "e": 223, "s": 182, "text": "It has taken some input from the stream." }, { "code": null, "e": 253, "s": 223, "text": "Some IOException has occurred" }, { "code": null, "e": 305, "s": 253, "text": "It has reached the end of the stream while reading." }, { "code": null, "e": 499, "s": 305, "text": "This method is declared as abstract method. It means that the subclasses of Reader abstract class should override this method if desired operation needs to be changed while reading a character." }, { "code": null, "e": 507, "s": 499, "text": "Syntax:" }, { "code": null, "e": 534, "s": 507, "text": "public abstract int read()" }, { "code": null, "e": 590, "s": 534, "text": "Parameters: This method does not accepts any parameters" }, { "code": null, "e": 770, "s": 590, "text": "Return Value: This method returns an integer value which is the integer value read from the stream. It can range from 0 to 65535. Else it returns -1 if no character has been read." }, { "code": null, "e": 853, "s": 770, "text": "Exception: This method throws IOException if some error occurs while input output." }, { "code": null, "e": 909, "s": 853, "text": "Below methods illustrates the working of read() method:" }, { "code": null, "e": 920, "s": 909, "text": "Program 1:" }, { "code": "// Java program to demonstrate// Reader read() method import java.io.*;import java.util.*; class GFG { public static void main(String[] args) { try { String str = \"GeeksForGeeks\"; // Create a Reader instance Reader reader = new StringReader(str); // Get the character // to be read from the stream int ch; // Read the first 5 characters // to this reader using read() method // This will put the str in the stream // till it is read by the reader for (int i = 0; i < 5; i++) { ch = reader.read(); System.out.println(\"\\nInteger value \" + \"of character read: \" + ch); System.out.println(\"Actual \" + \"character read: \" + (char)ch); } reader.close(); } catch (Exception e) { System.out.println(e); } }}", "e": 2020, "s": 920, "text": null }, { "code": null, "e": 2334, "s": 2020, "text": "Integer value of character read: 71\nActual character read: G\n\nInteger value of character read: 101\nActual character read: e\n\nInteger value of character read: 101\nActual character read: e\n\nInteger value of character read: 107\nActual character read: k\n\nInteger value of character read: 115\nActual character read: s\n" }, { "code": null, "e": 2345, "s": 2334, "text": "Program 2:" }, { "code": "// Java program to demonstrate// Reader read() method import java.io.*;import java.util.*; class GFG { public static void main(String[] args) { try { String str = \"GeeksForGeeks\"; // Create a Reader instance Reader reader = new StringReader(str); // Get the character // to be read from the stream int ch; // Read the first character // to this reader using read() method // This will put the str in the stream // till it is read by the reader ch = reader.read(); System.out.println(\"\\nInteger value \" + \"of character read: \" + ch); System.out.println(\"Actual \" + \"character read: \" + (char)ch); reader.close(); } catch (Exception e) { System.out.println(e); } }}", "e": 3358, "s": 2345, "text": null }, { "code": null, "e": 3420, "s": 3358, "text": "Integer value of character read: 71\nActual character read: G\n" }, { "code": null, "e": 3499, "s": 3420, "text": "Reference: https://docs.oracle.com/javase/9/docs/api/java/io/Reader.html#read–" }, { "code": null, "e": 3514, "s": 3499, "text": "Java-Functions" }, { "code": null, "e": 3530, "s": 3514, "text": "Java-IO package" }, { "code": null, "e": 3542, "s": 3530, "text": "Java-Reader" }, { "code": null, "e": 3547, "s": 3542, "text": "Java" }, { "code": null, "e": 3552, "s": 3547, "text": "Java" }, { "code": null, "e": 3650, "s": 3552, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3701, "s": 3650, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 3732, "s": 3701, "text": "How to iterate any Map in Java" }, { "code": null, "e": 3751, "s": 3732, "text": "Interfaces in Java" }, { "code": null, "e": 3781, "s": 3751, "text": "HashMap in Java with Examples" }, { "code": null, "e": 3796, "s": 3781, "text": "Stream In Java" }, { "code": null, "e": 3814, "s": 3796, "text": "ArrayList in Java" }, { "code": null, "e": 3834, "s": 3814, "text": "Collections in Java" }, { "code": null, "e": 3858, "s": 3834, "text": "Singleton Class in Java" }, { "code": null, "e": 3890, "s": 3858, "text": "Multidimensional Arrays in Java" } ]
Minimum swaps and K together | Practice | GeeksforGeeks
Given an array arr of n positive integers and a number k. One can apply a swap operation on the array any number of times, i.e choose any two index i and j (i < j) and swap arr[i] , arr[j] . Find the minimum number of swaps required to bring all the numbers less than or equal to k together, i.e. make them a contiguous subarray. Example 1: Input : arr[ ] = {2, 1, 5, 6, 3} K = 3 Output : 1 Explanation: To bring elements 2, 1, 3 together, swap index 2 with 4 (0-based indexing), i.e. element arr[2] = 5 with arr[4] = 3 such that final array will be- arr[] = {2, 1, 3, 6, 5} Example 2: Input : arr[ ] = {2, 7, 9, 5, 8, 7, 4} K = 6 Output : 2 Explanation: To bring elements 2, 5, 4 together, swap index 0 with 2 (0-based indexing) and index 4 with 6 (0-based indexing) such that final array will be- arr[] = {9, 7, 2, 5, 4, 7, 8} Your Task: This is a function problem. The input is already taken care of by the driver code. You only need to complete the function minSwap() that takes an array (arr), sizeOfArray (n), an integer K, and return the minimum swaps required. The driver code takes care of the printing. Expected Time Complexity: O(N). Expected Auxiliary Space: O(1). Constraints: 1 ≤ N ≤ 105 1 ≤ Arri, K ≤107 +1 naman77564 days ago C++ solution Easy int minSwap(int a[], int n, int k) { int count=0; for(int i=0; i<n; ++i){ if(a[i]<=k){ count++; } } int cnt=0, ans=INT_MAX; for(int i=0; i<count; ++i){ if(a[i]<=k){ cnt++; } } ans=count-cnt; for(int i=1; i<=n-count; ++i){ if(a[i-1]<=k){ cnt--; } if(a[i+count-1]<=k){ cnt++; } ans=min(count-cnt, ans); // cout<<i<<endl; // cout<<ans<<endl; // cout<<count<<endl; // cout<<cnt<<endl<<endl; } return ans; } -3 singhchandankumariit2 weeks ago int minSwap(int arr[], int n, int k) { int cnt=0; for(int i=0;i<n;i++){ if(arr[i]<=k)cnt++; } for(int i=0;i<n;i++) if(arr[i]<=k)arr[i]=0; int cnt0=0; for(int i=0;i<cnt;i++) if(arr[i]==0)cnt0++; int mx=cnt0; int i=cnt; while(i<n){ if(arr[i]==0&&arr[i-cnt]!=0)cnt0++; else if(arr[i]!=0&&arr[i-cnt]==0)cnt0--; mx=max(mx,cnt0); i++; } return cnt-mx; } +4 mandeepjain002 weeks ago Problem statement we make swap in such way that all element in array less than k should arranged in continusly (order is not req) but that swaps should be minimum Approach first calculate total number of element in array which is less than k (that beacomes a window size) then start window slide algoif greater than k (arr[j] > k) element come in window we increase bad++when we hit window size (j-i+1 == count) we check for min of bad and slide the window by checking if ith element is is contibuting in bad tou make bad-- and do i++ COde int minSwap(int arr[], int n, int k) { // Complet the function int count = 0;//number of element less than or equal k (window size) for(int i=0; i<n; i++) if(arr[i] <= k)count++; //koi element chota hai hi ni tou kese if(count == 0) return 0; int i=0, j=0; int bad = 0; int ans = INT_MAX; while(j < n){ if(arr[j] > k) bad++; //curr window me kitne greater k ele(jinko swap krna hoga) if(j-i+1 < count) j++; else if(j-i+1 == count){ ans = min(ans, bad); //slide windlow if(arr[i] > k) bad--; i++,j++; } } return ans; } +1 numaan_esc3 weeks ago Solved with JAVA. All test cases passed. For any query comment down below. Sliding Window technique used public static int minSwap (int[] arr, int n, int k) { // number of element smaller than and equal to K int totalEle = 0; // finding number of element through this loop for(int i = 0; i < n; i++) if(arr[i] <= k) totalEle++; // if there is no small element in the array then we'll print 0 if(totalEle == 0) return 0; // finding element in first window( of size totalEle) which is less than and equal to K int i; // Count in first window int count = 0; for(i = 0; i < totalEle; i++) if(arr[i] <= k) count++; // Initialise maxCount as to check which window has the highest number of element in every window of size totalEle int maxCount = count; while(i < n){ // while moving to next window, we have to check 2 points // 1 - last element which is going to be kicked less than or equal to K or not // if yes then we'll decrement the count if(arr[i-totalEle] <= k) count--; // 2 - element at index i is less than or equal to K or not // if yes then we'll increment the count if(arr[i] <= k) count++; // we'll keep note that which windows has the highest amount of elements belongs to this category (<=K) maxCount = Math.max(maxCount, count); i++; } // then to sum up, after getting window with maximum number of elements (<=K) // we'll just subtract it with total elements which is <=K // in order to get the amount of min swap return totalEle - maxCount; } 0 lloda2973 weeks ago PROPER STEP-BY STEP EXPPLANATION USING SLIDING WINDOW TECHNIQUE class Solution { public: int minSwap(int arr[], int n, int k) { deque<int>dq; int count=0; for(int i=0;i<n;i++){ // LOOP TO FIND HOW MANY ELEMENTS if(arr[i]<=k){ // ARE <=K IN THE ARRAY count++; } } int count2=0,maximumer=INT_MIN; for(int i=0;i<count;i++){ //LOOP INITIATES THE SLIDING WINDOW dq.push_back(arr[i]); //WITH 1ST SET OF NUMBERS. THE WINDOW if(dq.back()<=k){ //SIZE='NO. OF ELEMENTS<=K' count2++; } } maximumer=max(maximumer,count2); for(int j=count;j<n;j++){ //TO SLIDE THE WINDOW BY ELIMINATING FROM if(dq.front()<=k){ //FRONT AND PUSHING AT BACK SIMULTANEOUSLY count2--; } dq.pop_front(); if(arr[j]<=k){ count2++; } dq.push_back(arr[j]); //MAX THE GROUP OF SUCH NO. PRESENT maximumer=max(maximumer,count2); //MIN THE REQUIRED OPERATIONS BE } return count-maximumer; //RETURN MIN. REQUIRED OPERATIONS } }; 0 mrajneesh7233 weeks ago Sliding Window Approach: class Solution //MT :){public: int minSwap(int arr[], int n, int k) { int cnt=0; for(int i=0;i<n;i++){ if(arr[i]<=k)cnt++; } int ans=0; int fans=0; for(int i=0;i<cnt;i++){ if(arr[i]<=k)ans++; } fans=max(ans,fans); for(int i=cnt;i<n;i++){ if(arr[i-cnt]<=k)ans--; if(arr[i]<=k)ans++; fans=max(ans,fans); } return cnt-fans; // Complet the function }}; +2 ruchitchudasama1233 weeks ago public: int minSwap(int arr[], int n, int k) { int wsize=0; for(int i=0;i<n;i++){ if(arr[i]<=k)wsize++; } int count=0; for(int i=0;i<wsize;i++){ if(arr[i]<=k)count++; } int ans=wsize-count; for(int i=wsize;i<n;i++){ if(arr[i-wsize]<=k)count--; if(arr[i]<=k)count++; ans=min(ans,wsize-count); } return ans; } 0 yashmandaviya7021 month ago int minSwap(int v[], int n, int k) { // Complet the function int c=0; for(int i=0;i<n;i++) if(v[i]<=k) c++; int ans = INT_MAX; int inwindow=0; for(int i=0;i<n;i++){ if(i<c) {if(v[i]<=k)inwindow++;} else{ if(v[i]<=k) inwindow++; if(v[i-c]<=k && inwindow>0) inwindow--; } ans=min(ans,c-inwindow); } return ans; } +1 madhukartemba1 month ago JAVA SOLUTION USING SLIDING WINDOW: class Complete{ // Function for finding maximum and value pair public static int minSwap (int arr[], int n, int k) { int n_ele = 0; for(int x : arr) { if(x<=k) n_ele++; } int l = 0; int count = 0; int max_count = 0; for(int r=0; r<n; r++) { if(r>=n_ele) { if(arr[l]<=k) { count--; } l++; } if(arr[r]<=k) count++; max_count = Math.max(max_count, count); } return n_ele - max_count; } } 0 anupkumarmridhanet1 month ago int minSwap(int arr[], int n, int k) { // Complet the function int count=0; for(int i=0;i<n;i++){ if(arr[i]<=k){ count++; } } int requiredSwap=0; for(int i=0;i<count;i++){ if(arr[i]>k){ requiredSwap++; } } int ans=requiredSwap; for(int i=0, j=count; j<n;i++,j++){ if(arr[i]>k){ requiredSwap--; } if(arr[j]>k) { requiredSwap++; } ans=min(ans,requiredSwap); } return ans; } 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": 568, "s": 238, "text": "Given an array arr of n positive integers and a number k. One can apply a swap operation on the array any number of times, i.e choose any two index i and j (i < j) and swap arr[i] , arr[j] . Find the minimum number of swaps required to bring all the numbers less than or equal to k together, i.e. make them a contiguous subarray." }, { "code": null, "e": 579, "s": 568, "text": "Example 1:" }, { "code": null, "e": 818, "s": 579, "text": "Input : \narr[ ] = {2, 1, 5, 6, 3} \nK = 3\nOutput : \n1\nExplanation:\nTo bring elements 2, 1, 3 together,\nswap index 2 with 4 (0-based indexing),\ni.e. element arr[2] = 5 with arr[4] = 3\nsuch that final array will be- \narr[] = {2, 1, 3, 6, 5}\n" }, { "code": null, "e": 830, "s": 818, "text": "\nExample 2:" }, { "code": null, "e": 1083, "s": 830, "text": "Input : \narr[ ] = {2, 7, 9, 5, 8, 7, 4} \nK = 6 \nOutput : \n2 \nExplanation: \nTo bring elements 2, 5, 4 together, \nswap index 0 with 2 (0-based indexing)\nand index 4 with 6 (0-based indexing)\nsuch that final array will be- \narr[] = {9, 7, 2, 5, 4, 7, 8}\n" }, { "code": null, "e": 1369, "s": 1085, "text": "Your Task:\nThis is a function problem. The input is already taken care of by the driver code. You only need to complete the function minSwap() that takes an array (arr), sizeOfArray (n), an integer K, and return the minimum swaps required. The driver code takes care of the printing." }, { "code": null, "e": 1433, "s": 1369, "text": "Expected Time Complexity: O(N).\nExpected Auxiliary Space: O(1)." }, { "code": null, "e": 1476, "s": 1433, "text": "\nConstraints:\n1 ≤ N ≤ 105\n1 ≤ Arri, K ≤107" }, { "code": null, "e": 1479, "s": 1476, "text": "+1" }, { "code": null, "e": 1499, "s": 1479, "text": "naman77564 days ago" }, { "code": null, "e": 1517, "s": 1499, "text": "C++ solution Easy" }, { "code": null, "e": 2232, "s": 1519, "text": "int minSwap(int a[], int n, int k) {\n int count=0;\n for(int i=0; i<n; ++i){\n if(a[i]<=k){\n count++;\n }\n }\n int cnt=0, ans=INT_MAX;\n for(int i=0; i<count; ++i){\n if(a[i]<=k){\n cnt++;\n }\n }\n ans=count-cnt;\n\n for(int i=1; i<=n-count; ++i){\n if(a[i-1]<=k){\n cnt--;\n }\n if(a[i+count-1]<=k){\n cnt++;\n }\n \n ans=min(count-cnt, ans);\n // cout<<i<<endl;\n // cout<<ans<<endl;\n // cout<<count<<endl;\n // cout<<cnt<<endl<<endl;\n }\n return ans;\n }" }, { "code": null, "e": 2239, "s": 2236, "text": "-3" }, { "code": null, "e": 2271, "s": 2239, "text": "singhchandankumariit2 weeks ago" }, { "code": null, "e": 2807, "s": 2271, "text": "int minSwap(int arr[], int n, int k) { int cnt=0; for(int i=0;i<n;i++){ if(arr[i]<=k)cnt++; } for(int i=0;i<n;i++) if(arr[i]<=k)arr[i]=0; int cnt0=0; for(int i=0;i<cnt;i++) if(arr[i]==0)cnt0++; int mx=cnt0; int i=cnt; while(i<n){ if(arr[i]==0&&arr[i-cnt]!=0)cnt0++; else if(arr[i]!=0&&arr[i-cnt]==0)cnt0--; mx=max(mx,cnt0); i++; } return cnt-mx; }" }, { "code": null, "e": 2810, "s": 2807, "text": "+4" }, { "code": null, "e": 2835, "s": 2810, "text": "mandeepjain002 weeks ago" }, { "code": null, "e": 2853, "s": 2835, "text": "Problem statement" }, { "code": null, "e": 2998, "s": 2853, "text": "we make swap in such way that all element in array less than k should arranged in continusly (order is not req) but that swaps should be minimum" }, { "code": null, "e": 3009, "s": 3000, "text": "Approach" }, { "code": null, "e": 3109, "s": 3009, "text": "first calculate total number of element in array which is less than k (that beacomes a window size)" }, { "code": null, "e": 3373, "s": 3109, "text": "then start window slide algoif greater than k (arr[j] > k) element come in window we increase bad++when we hit window size (j-i+1 == count) we check for min of bad and slide the window by checking if ith element is is contibuting in bad tou make bad-- and do i++" }, { "code": null, "e": 3378, "s": 3373, "text": "COde" }, { "code": null, "e": 4144, "s": 3384, "text": " int minSwap(int arr[], int n, int k) {\n // Complet the function\n int count = 0;//number of element less than or equal k (window size)\n for(int i=0; i<n; i++)\n if(arr[i] <= k)count++;\n \n //koi element chota hai hi ni tou kese\n if(count == 0) return 0;\n int i=0, j=0;\n int bad = 0;\n int ans = INT_MAX;\n \n while(j < n){\n if(arr[j] > k) bad++; //curr window me kitne greater k ele(jinko swap krna hoga)\n if(j-i+1 < count) j++;\n else if(j-i+1 == count){\n ans = min(ans, bad);\n //slide windlow\n if(arr[i] > k) bad--;\n i++,j++;\n }\n }\n return ans;\n \n }" }, { "code": null, "e": 4147, "s": 4144, "text": "+1" }, { "code": null, "e": 4169, "s": 4147, "text": "numaan_esc3 weeks ago" }, { "code": null, "e": 4210, "s": 4169, "text": "Solved with JAVA. All test cases passed." }, { "code": null, "e": 4244, "s": 4210, "text": "For any query comment down below." }, { "code": null, "e": 4274, "s": 4244, "text": "Sliding Window technique used" }, { "code": null, "e": 6019, "s": 4276, "text": "public static int minSwap (int[] arr, int n, int k) {\n // number of element smaller than and equal to K\n int totalEle = 0;\n\n // finding number of element through this loop\n for(int i = 0; i < n; i++)\n if(arr[i] <= k)\n totalEle++;\n\n // if there is no small element in the array then we'll print 0\n if(totalEle == 0)\n return 0;\n\n // finding element in first window( of size totalEle) which is less than and equal to K\n int i;\n // Count in first window\n int count = 0;\n for(i = 0; i < totalEle; i++)\n if(arr[i] <= k)\n count++;\n\n // Initialise maxCount as to check which window has the highest number of element in every window of size totalEle\n int maxCount = count;\n \n while(i < n){\n // while moving to next window, we have to check 2 points\n // 1 - last element which is going to be kicked less than or equal to K or not\n // if yes then we'll decrement the count\n if(arr[i-totalEle] <= k)\n count--;\n // 2 - element at index i is less than or equal to K or not\n // if yes then we'll increment the count\n if(arr[i] <= k)\n count++;\n\n // we'll keep note that which windows has the highest amount of elements belongs to this category (<=K)\n maxCount = Math.max(maxCount, count);\n i++;\n }\n\n // then to sum up, after getting window with maximum number of elements (<=K)\n // we'll just subtract it with total elements which is <=K\n // in order to get the amount of min swap\n return totalEle - maxCount;\n }" }, { "code": null, "e": 6021, "s": 6019, "text": "0" }, { "code": null, "e": 6041, "s": 6021, "text": "lloda2973 weeks ago" }, { "code": null, "e": 6105, "s": 6041, "text": "PROPER STEP-BY STEP EXPPLANATION USING SLIDING WINDOW TECHNIQUE" }, { "code": null, "e": 7311, "s": 6105, "text": "class Solution\n{\npublic:\n int minSwap(int arr[], int n, int k) {\n deque<int>dq; \n int count=0;\n for(int i=0;i<n;i++){ // LOOP TO FIND HOW MANY ELEMENTS\n if(arr[i]<=k){ // ARE <=K IN THE ARRAY\n count++;\n }\n }\n int count2=0,maximumer=INT_MIN;\n for(int i=0;i<count;i++){ //LOOP INITIATES THE SLIDING WINDOW\n dq.push_back(arr[i]); //WITH 1ST SET OF NUMBERS. THE WINDOW \n if(dq.back()<=k){ //SIZE='NO. OF ELEMENTS<=K'\n count2++;\n }\n }\n maximumer=max(maximumer,count2);\n for(int j=count;j<n;j++){ //TO SLIDE THE WINDOW BY ELIMINATING FROM \n if(dq.front()<=k){ //FRONT AND PUSHING AT BACK SIMULTANEOUSLY\n count2--; \n }\n dq.pop_front();\n if(arr[j]<=k){\n count2++;\n }\n dq.push_back(arr[j]); //MAX THE GROUP OF SUCH NO. PRESENT \n maximumer=max(maximumer,count2); //MIN THE REQUIRED OPERATIONS BE\n }\n return count-maximumer; //RETURN MIN. REQUIRED OPERATIONS\n }\n};" }, { "code": null, "e": 7315, "s": 7313, "text": "0" }, { "code": null, "e": 7339, "s": 7315, "text": "mrajneesh7233 weeks ago" }, { "code": null, "e": 7364, "s": 7339, "text": "Sliding Window Approach:" }, { "code": null, "e": 7847, "s": 7364, "text": "class Solution //MT :){public: int minSwap(int arr[], int n, int k) { int cnt=0; for(int i=0;i<n;i++){ if(arr[i]<=k)cnt++; } int ans=0; int fans=0; for(int i=0;i<cnt;i++){ if(arr[i]<=k)ans++; } fans=max(ans,fans); for(int i=cnt;i<n;i++){ if(arr[i-cnt]<=k)ans--; if(arr[i]<=k)ans++; fans=max(ans,fans); } return cnt-fans; // Complet the function }};" }, { "code": null, "e": 7850, "s": 7847, "text": "+2" }, { "code": null, "e": 7880, "s": 7850, "text": "ruchitchudasama1233 weeks ago" }, { "code": null, "e": 8344, "s": 7880, "text": "public:\n int minSwap(int arr[], int n, int k) {\n int wsize=0;\n for(int i=0;i<n;i++){\n if(arr[i]<=k)wsize++; \n }\n int count=0;\n for(int i=0;i<wsize;i++){\n if(arr[i]<=k)count++;\n }\n int ans=wsize-count;\n for(int i=wsize;i<n;i++){\n if(arr[i-wsize]<=k)count--;\n if(arr[i]<=k)count++;\n ans=min(ans,wsize-count);\n }\n return ans;\n }" }, { "code": null, "e": 8346, "s": 8344, "text": "0" }, { "code": null, "e": 8374, "s": 8346, "text": "yashmandaviya7021 month ago" }, { "code": null, "e": 8746, "s": 8374, "text": "int minSwap(int v[], int n, int k) { // Complet the function int c=0; for(int i=0;i<n;i++) if(v[i]<=k) c++; int ans = INT_MAX; int inwindow=0; for(int i=0;i<n;i++){ if(i<c) {if(v[i]<=k)inwindow++;} else{ if(v[i]<=k) inwindow++; if(v[i-c]<=k && inwindow>0) inwindow--; } ans=min(ans,c-inwindow); } return ans; }" }, { "code": null, "e": 8749, "s": 8746, "text": "+1" }, { "code": null, "e": 8774, "s": 8749, "text": "madhukartemba1 month ago" }, { "code": null, "e": 8810, "s": 8774, "text": "JAVA SOLUTION USING SLIDING WINDOW:" }, { "code": null, "e": 9615, "s": 8810, "text": "class Complete{\n \n \n // Function for finding maximum and value pair\n public static int minSwap (int arr[], int n, int k) {\n \n int n_ele = 0;\n \n for(int x : arr)\n {\n if(x<=k) n_ele++;\n }\n \n int l = 0;\n \n int count = 0;\n \n int max_count = 0;\n \n for(int r=0; r<n; r++)\n {\n if(r>=n_ele)\n {\n if(arr[l]<=k)\n {\n count--;\n \n }\n \n l++;\n }\n \n if(arr[r]<=k) count++;\n \n max_count = Math.max(max_count, count);\n }\n \n \n return n_ele - max_count;\n \n }\n \n \n}" }, { "code": null, "e": 9617, "s": 9615, "text": "0" }, { "code": null, "e": 9647, "s": 9617, "text": "anupkumarmridhanet1 month ago" }, { "code": null, "e": 10284, "s": 9647, "text": "int minSwap(int arr[], int n, int k) { // Complet the function int count=0; for(int i=0;i<n;i++){ if(arr[i]<=k){ count++; } } int requiredSwap=0; for(int i=0;i<count;i++){ if(arr[i]>k){ requiredSwap++; } } int ans=requiredSwap; for(int i=0, j=count; j<n;i++,j++){ if(arr[i]>k){ requiredSwap--; } if(arr[j]>k) { requiredSwap++; } ans=min(ans,requiredSwap); } return ans; }" }, { "code": null, "e": 10430, "s": 10284, "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": 10466, "s": 10430, "text": " Login to access your submissions. " }, { "code": null, "e": 10476, "s": 10466, "text": "\nProblem\n" }, { "code": null, "e": 10486, "s": 10476, "text": "\nContest\n" }, { "code": null, "e": 10549, "s": 10486, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 10734, "s": 10549, "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": 11018, "s": 10734, "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": 11164, "s": 11018, "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": 11241, "s": 11164, "text": "You can view the solutions submitted by other users from the submission tab." }, { "code": null, "e": 11282, "s": 11241, "text": "Make sure you are not using ad-blockers." }, { "code": null, "e": 11310, "s": 11282, "text": "Disable browser extensions." }, { "code": null, "e": 11381, "s": 11310, "text": "We recommend using latest version of your browser for best experience." }, { "code": null, "e": 11568, "s": 11381, "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." } ]
Vertex Cover Problem | Set 1 (Introduction and Approximate Algorithm)
18 Aug, 2021 A vertex cover of an undirected graph is a subset of its vertices such that for every edge (u, v) of the graph, either ‘u’ or ‘v’ is in the vertex cover. Although the name is Vertex Cover, the set covers all edges of the given graph. Given an undirected graph, the vertex cover problem is to find minimum size vertex cover. The following are some examples. Vertex Cover Problem is a known NP Complete problem, i.e., there is no polynomial-time solution for this unless P = NP. There are approximate polynomial-time algorithms to solve the problem though. Following is a simple approximate algorithm adapted from CLRS book. Naive Approach: Consider all the subset of vertices one by one and find out whether it covers all edges of the graph. For eg. in a graph consisting only 3 vertices the set consisting of the combination of vertices are:{0,1,2,{0,1},{0,2},{1,2},{0,1,2}} . Using each element of this set check whether these vertices cover all all the edges of the graph. Hence update the optimal answer. And hence print the subset having minimum number of vertices which also covers all the edges of the graph. Approximate Algorithm for Vertex Cover: 1) Initialize the result as {} 2) Consider a set of all edges in given graph. Let the set be E. 3) Do following while E is not empty ...a) Pick an arbitrary edge (u, v) from set E and add 'u' and 'v' to result ...b) Remove all edges from E which are either incident on u or v. 4) Return result Below diagram to show the execution of the above approximate algorithm: How well the above algorithm perform? It can be proved that the above approximate algorithm never finds a vertex cover whose size is more than twice the size of the minimum possible vertex cover (Refer this for proof)Implementation: The following are C++ and Java implementations of the above approximate algorithm. C++ Java Python3 C# Javascript // Program to print Vertex Cover of a given undirected graph#include<iostream>#include <list>using namespace std; // This class represents a undirected graph using adjacency listclass Graph{ int V; // No. of vertices list<int> *adj; // Pointer to an array containing adjacency listspublic: Graph(int V); // Constructor void addEdge(int v, int w); // function to add an edge to graph void printVertexCover(); // prints vertex cover}; Graph::Graph(int V){ this->V = V; adj = new list<int>[V];} void Graph::addEdge(int v, int w){ adj[v].push_back(w); // Add w to v’s list. adj[w].push_back(v); // Since the graph is undirected} // The function to print vertex covervoid Graph::printVertexCover(){ // Initialize all vertices as not visited. bool visited[V]; for (int i=0; i<V; i++) visited[i] = false; list<int>::iterator i; // Consider all edges one by one for (int u=0; u<V; u++) { // An edge is only picked when both visited[u] and visited[v] // are false if (visited[u] == false) { // Go through all adjacents of u and pick the first not // yet visited vertex (We are basically picking an edge // (u, v) from remaining edges. for (i= adj[u].begin(); i != adj[u].end(); ++i) { int v = *i; if (visited[v] == false) { // Add the vertices (u, v) to the result set. // We make the vertex u and v visited so that // all edges from/to them would be ignored visited[v] = true; visited[u] = true; break; } } } } // Print the vertex cover for (int i=0; i<V; i++) if (visited[i]) cout << i << " ";} // Driver program to test methods of graph classint main(){ // Create a graph given in the above diagram Graph g(7); g.addEdge(0, 1); g.addEdge(0, 2); g.addEdge(1, 3); g.addEdge(3, 4); g.addEdge(4, 5); g.addEdge(5, 6); g.printVertexCover(); return 0;} // Java Program to print Vertex// Cover of a given undirected graphimport java.io.*;import java.util.*;import java.util.LinkedList; // This class represents an undirected// graph using adjacency listclass Graph{ private int V; // No. of vertices // Array of lists for Adjacency List Representation private LinkedList<Integer> adj[]; // Constructor Graph(int v) { V = v; adj = new LinkedList[v]; for (int i=0; i<v; ++i) adj[i] = new LinkedList(); } //Function to add an edge into the graph void addEdge(int v, int w) { adj[v].add(w); // Add w to v's list. adj[w].add(v); //Graph is undirected } // The function to print vertex cover void printVertexCover() { // Initialize all vertices as not visited. boolean visited[] = new boolean[V]; for (int i=0; i<V; i++) visited[i] = false; Iterator<Integer> i; // Consider all edges one by one for (int u=0; u<V; u++) { // An edge is only picked when both visited[u] // and visited[v] are false if (visited[u] == false) { // Go through all adjacents of u and pick the // first not yet visited vertex (We are basically // picking an edge (u, v) from remaining edges. i = adj[u].iterator(); while (i.hasNext()) { int v = i.next(); if (visited[v] == false) { // Add the vertices (u, v) to the result // set. We make the vertex u and v visited // so that all edges from/to them would // be ignored visited[v] = true; visited[u] = true; break; } } } } // Print the vertex cover for (int j=0; j<V; j++) if (visited[j]) System.out.print(j+" "); } // Driver method public static void main(String args[]) { // Create a graph given in the above diagram Graph g = new Graph(7); g.addEdge(0, 1); g.addEdge(0, 2); g.addEdge(1, 3); g.addEdge(3, 4); g.addEdge(4, 5); g.addEdge(5, 6); g.printVertexCover(); }} // This code is contributed by Aakash Hasija # Python3 program to print Vertex Cover# of a given undirected graphfrom collections import defaultdict # This class represents a directed graph# using adjacency list representationclass Graph: def __init__(self, vertices): # No. of vertices self.V = vertices # Default dictionary to store graph self.graph = defaultdict(list) # Function to add an edge to graph def addEdge(self, u, v): self.graph[u].append(v) # The function to print vertex cover def printVertexCover(self): # Initialize all vertices as not visited. visited = [False] * (self.V) # Consider all edges one by one for u in range(self.V): # An edge is only picked when # both visited[u] and visited[v] # are false if not visited[u]: # Go through all adjacents of u and # pick the first not yet visited # vertex (We are basically picking # an edge (u, v) from remaining edges. for v in self.graph[u]: if not visited[v]: # Add the vertices (u, v) to the # result set. We make the vertex # u and v visited so that all # edges from/to them would # be ignored visited[v] = True visited[u] = True break # Print the vertex cover for j in range(self.V): if visited[j]: print(j, end = ' ') print() # Driver code # Create a graph given in# the above diagramg = Graph(7)g.addEdge(0, 1)g.addEdge(0, 2)g.addEdge(1, 3)g.addEdge(3, 4)g.addEdge(4, 5)g.addEdge(5, 6) g.printVertexCover() # This code is contributed by Prateek Gupta // C# Program to print Vertex// Cover of a given undirected// graphusing System;using System.Collections.Generic; // This class represents an// undirected graph using// adjacency listclass Graph{ // No. of verticespublic int V; // Array of lists for// Adjacency List Representationpublic List<int> []adj; // Constructorpublic Graph(int v){ V = v; adj = new List<int>[v]; for (int i = 0; i < v; ++i) adj[i] = new List<int>();} //Function to add an edge// into the graphvoid addEdge(int v, int w){ // Add w to v's list. adj[v].Add(w); //Graph is undirected adj[w].Add(v);} // The function to print// vertex covervoid printVertexCover(){ // Initialize all vertices // as not visited. bool []visited = new bool[V]; // Consider all edges one // by one for (int u = 0; u < V; u++) { // An edge is only picked // when both visited[u] // and visited[v] are false if (visited[u] == false) { // Go through all adjacents // of u and pick the first // not yet visited vertex // (We are basically picking // an edge (u, v) from remaining // edges. foreach(int i in adj[u]) { int v = i; if (visited[v] == false) { // Add the vertices (u, v) // to the result set. We // make the vertex u and // v visited so that all // edges from/to them would // be ignored visited[v] = true; visited[u] = true; break; } } } } // Print the vertex cover for (int j = 0; j < V; j++) if (visited[j]) Console.Write(j + " ");} // Driver methodpublic static void Main(String []args){ // Create a graph given in // the above diagram Graph g = new Graph(7); g.addEdge(0, 1); g.addEdge(0, 2); g.addEdge(1, 3); g.addEdge(3, 4); g.addEdge(4, 5); g.addEdge(5, 6); g.printVertexCover();}} // This code is contributed by gauravrajput1 <script>// Javascript Program to print Vertex// Cover of a given undirected graph // This class represents an undirected// graph using adjacency listclass Graph{ // Constructor constructor(v) { this.V=v; this.adj = new Array(v); for (let i = 0; i < v; ++i) this.adj[i] = []; } // Function to add an edge into the graph addEdge(v, w) { this.adj[v].push(w); // Add w to v's list. this.adj[w].push(v); //Graph is undirected } // The function to print vertex cover printVertexCover() { // Initialize all vertices as not visited. let visited = new Array(this.V); for (let i = 0; i < this.V; i++) visited[i] = false; // Consider all edges one by one for (let u = 0; u < this.V; u++) { // An edge is only picked when both visited[u] // and visited[v] are false if (visited[u] == false) { // Go through all adjacents of u and pick the // first not yet visited vertex (We are basically // picking an edge (u, v) from remaining edges. for(let i = 0; i < this.adj[u].length; i++) { let v = this.adj[u][i]; if (visited[v] == false) { // Add the vertices (u, v) to the result // set. We make the vertex u and v visited // so that all edges from/to them would // be ignored visited[v] = true; visited[u] = true; break; } } } } // Print the vertex cover for (let j = 0; j < this.V; j++) if (visited[j]) document.write(j+" "); }} // Driver method// Create a graph given in the above diagramlet g = new Graph(7);g.addEdge(0, 1);g.addEdge(0, 2);g.addEdge(1, 3);g.addEdge(3, 4);g.addEdge(4, 5);g.addEdge(5, 6); g.printVertexCover(); // This code is contributed by patel2127</script> Output: 0 1 3 4 5 6 The Time Complexity of the above algorithm is O(V + E).Exact Algorithms: Although the problem is NP complete, it can be solved in polynomial time for the following types of graphs. 1) Bipartite Graph 2) Tree GraphThe problem to check whether there is a vertex cover of size smaller than or equal to a given number k can also be solved in polynomial time if k is bounded by O(LogV) (Refer this)We will soon be discussing exact algorithms for vertex cover.This article is contributed by Shubham. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above PrateekGupta10 GauravRajput1 patel2127 riyaprasad01 NPHard Graph Graph Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Dijkstra's shortest path algorithm | Greedy Algo-7 Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2 Find if there is a path between two vertices in a directed graph Detect Cycle in a Directed Graph Introduction to Data Structures What is Data Structure: Types, Classifications and Applications Bellman–Ford Algorithm | DP-23 Find if there is a path between two vertices in an undirected graph Minimum number of swaps required to sort an array m Coloring Problem | Backtracking-5
[ { "code": null, "e": 54, "s": 26, "text": "\n18 Aug, 2021" }, { "code": null, "e": 413, "s": 54, "text": "A vertex cover of an undirected graph is a subset of its vertices such that for every edge (u, v) of the graph, either ‘u’ or ‘v’ is in the vertex cover. Although the name is Vertex Cover, the set covers all edges of the given graph. Given an undirected graph, the vertex cover problem is to find minimum size vertex cover. The following are some examples. " }, { "code": null, "e": 679, "s": 413, "text": "Vertex Cover Problem is a known NP Complete problem, i.e., there is no polynomial-time solution for this unless P = NP. There are approximate polynomial-time algorithms to solve the problem though. Following is a simple approximate algorithm adapted from CLRS book." }, { "code": null, "e": 695, "s": 679, "text": "Naive Approach:" }, { "code": null, "e": 1172, "s": 695, "text": "Consider all the subset of vertices one by one and find out whether it covers all edges of the graph. For eg. in a graph consisting only 3 vertices the set consisting of the combination of vertices are:{0,1,2,{0,1},{0,2},{1,2},{0,1,2}} . Using each element of this set check whether these vertices cover all all the edges of the graph. Hence update the optimal answer. And hence print the subset having minimum number of vertices which also covers all the edges of the graph." }, { "code": null, "e": 1214, "s": 1172, "text": "Approximate Algorithm for Vertex Cover: " }, { "code": null, "e": 1510, "s": 1214, "text": "1) Initialize the result as {}\n2) Consider a set of all edges in given graph. Let the set be E.\n3) Do following while E is not empty\n...a) Pick an arbitrary edge (u, v) from set E and add 'u' and 'v' to result\n...b) Remove all edges from E which are either incident on u or v.\n4) Return result " }, { "code": null, "e": 1584, "s": 1510, "text": "Below diagram to show the execution of the above approximate algorithm: " }, { "code": null, "e": 1902, "s": 1584, "text": "How well the above algorithm perform? It can be proved that the above approximate algorithm never finds a vertex cover whose size is more than twice the size of the minimum possible vertex cover (Refer this for proof)Implementation: The following are C++ and Java implementations of the above approximate algorithm. " }, { "code": null, "e": 1906, "s": 1902, "text": "C++" }, { "code": null, "e": 1911, "s": 1906, "text": "Java" }, { "code": null, "e": 1919, "s": 1911, "text": "Python3" }, { "code": null, "e": 1922, "s": 1919, "text": "C#" }, { "code": null, "e": 1933, "s": 1922, "text": "Javascript" }, { "code": "// Program to print Vertex Cover of a given undirected graph#include<iostream>#include <list>using namespace std; // This class represents a undirected graph using adjacency listclass Graph{ int V; // No. of vertices list<int> *adj; // Pointer to an array containing adjacency listspublic: Graph(int V); // Constructor void addEdge(int v, int w); // function to add an edge to graph void printVertexCover(); // prints vertex cover}; Graph::Graph(int V){ this->V = V; adj = new list<int>[V];} void Graph::addEdge(int v, int w){ adj[v].push_back(w); // Add w to v’s list. adj[w].push_back(v); // Since the graph is undirected} // The function to print vertex covervoid Graph::printVertexCover(){ // Initialize all vertices as not visited. bool visited[V]; for (int i=0; i<V; i++) visited[i] = false; list<int>::iterator i; // Consider all edges one by one for (int u=0; u<V; u++) { // An edge is only picked when both visited[u] and visited[v] // are false if (visited[u] == false) { // Go through all adjacents of u and pick the first not // yet visited vertex (We are basically picking an edge // (u, v) from remaining edges. for (i= adj[u].begin(); i != adj[u].end(); ++i) { int v = *i; if (visited[v] == false) { // Add the vertices (u, v) to the result set. // We make the vertex u and v visited so that // all edges from/to them would be ignored visited[v] = true; visited[u] = true; break; } } } } // Print the vertex cover for (int i=0; i<V; i++) if (visited[i]) cout << i << \" \";} // Driver program to test methods of graph classint main(){ // Create a graph given in the above diagram Graph g(7); g.addEdge(0, 1); g.addEdge(0, 2); g.addEdge(1, 3); g.addEdge(3, 4); g.addEdge(4, 5); g.addEdge(5, 6); g.printVertexCover(); return 0;}", "e": 4076, "s": 1933, "text": null }, { "code": "// Java Program to print Vertex// Cover of a given undirected graphimport java.io.*;import java.util.*;import java.util.LinkedList; // This class represents an undirected// graph using adjacency listclass Graph{ private int V; // No. of vertices // Array of lists for Adjacency List Representation private LinkedList<Integer> adj[]; // Constructor Graph(int v) { V = v; adj = new LinkedList[v]; for (int i=0; i<v; ++i) adj[i] = new LinkedList(); } //Function to add an edge into the graph void addEdge(int v, int w) { adj[v].add(w); // Add w to v's list. adj[w].add(v); //Graph is undirected } // The function to print vertex cover void printVertexCover() { // Initialize all vertices as not visited. boolean visited[] = new boolean[V]; for (int i=0; i<V; i++) visited[i] = false; Iterator<Integer> i; // Consider all edges one by one for (int u=0; u<V; u++) { // An edge is only picked when both visited[u] // and visited[v] are false if (visited[u] == false) { // Go through all adjacents of u and pick the // first not yet visited vertex (We are basically // picking an edge (u, v) from remaining edges. i = adj[u].iterator(); while (i.hasNext()) { int v = i.next(); if (visited[v] == false) { // Add the vertices (u, v) to the result // set. We make the vertex u and v visited // so that all edges from/to them would // be ignored visited[v] = true; visited[u] = true; break; } } } } // Print the vertex cover for (int j=0; j<V; j++) if (visited[j]) System.out.print(j+\" \"); } // Driver method public static void main(String args[]) { // Create a graph given in the above diagram Graph g = new Graph(7); g.addEdge(0, 1); g.addEdge(0, 2); g.addEdge(1, 3); g.addEdge(3, 4); g.addEdge(4, 5); g.addEdge(5, 6); g.printVertexCover(); }} // This code is contributed by Aakash Hasija", "e": 6547, "s": 4076, "text": null }, { "code": "# Python3 program to print Vertex Cover# of a given undirected graphfrom collections import defaultdict # This class represents a directed graph# using adjacency list representationclass Graph: def __init__(self, vertices): # No. of vertices self.V = vertices # Default dictionary to store graph self.graph = defaultdict(list) # Function to add an edge to graph def addEdge(self, u, v): self.graph[u].append(v) # The function to print vertex cover def printVertexCover(self): # Initialize all vertices as not visited. visited = [False] * (self.V) # Consider all edges one by one for u in range(self.V): # An edge is only picked when # both visited[u] and visited[v] # are false if not visited[u]: # Go through all adjacents of u and # pick the first not yet visited # vertex (We are basically picking # an edge (u, v) from remaining edges. for v in self.graph[u]: if not visited[v]: # Add the vertices (u, v) to the # result set. We make the vertex # u and v visited so that all # edges from/to them would # be ignored visited[v] = True visited[u] = True break # Print the vertex cover for j in range(self.V): if visited[j]: print(j, end = ' ') print() # Driver code # Create a graph given in# the above diagramg = Graph(7)g.addEdge(0, 1)g.addEdge(0, 2)g.addEdge(1, 3)g.addEdge(3, 4)g.addEdge(4, 5)g.addEdge(5, 6) g.printVertexCover() # This code is contributed by Prateek Gupta", "e": 8485, "s": 6547, "text": null }, { "code": "// C# Program to print Vertex// Cover of a given undirected// graphusing System;using System.Collections.Generic; // This class represents an// undirected graph using// adjacency listclass Graph{ // No. of verticespublic int V; // Array of lists for// Adjacency List Representationpublic List<int> []adj; // Constructorpublic Graph(int v){ V = v; adj = new List<int>[v]; for (int i = 0; i < v; ++i) adj[i] = new List<int>();} //Function to add an edge// into the graphvoid addEdge(int v, int w){ // Add w to v's list. adj[v].Add(w); //Graph is undirected adj[w].Add(v);} // The function to print// vertex covervoid printVertexCover(){ // Initialize all vertices // as not visited. bool []visited = new bool[V]; // Consider all edges one // by one for (int u = 0; u < V; u++) { // An edge is only picked // when both visited[u] // and visited[v] are false if (visited[u] == false) { // Go through all adjacents // of u and pick the first // not yet visited vertex // (We are basically picking // an edge (u, v) from remaining // edges. foreach(int i in adj[u]) { int v = i; if (visited[v] == false) { // Add the vertices (u, v) // to the result set. We // make the vertex u and // v visited so that all // edges from/to them would // be ignored visited[v] = true; visited[u] = true; break; } } } } // Print the vertex cover for (int j = 0; j < V; j++) if (visited[j]) Console.Write(j + \" \");} // Driver methodpublic static void Main(String []args){ // Create a graph given in // the above diagram Graph g = new Graph(7); g.addEdge(0, 1); g.addEdge(0, 2); g.addEdge(1, 3); g.addEdge(3, 4); g.addEdge(4, 5); g.addEdge(5, 6); g.printVertexCover();}} // This code is contributed by gauravrajput1", "e": 10396, "s": 8485, "text": null }, { "code": "<script>// Javascript Program to print Vertex// Cover of a given undirected graph // This class represents an undirected// graph using adjacency listclass Graph{ // Constructor constructor(v) { this.V=v; this.adj = new Array(v); for (let i = 0; i < v; ++i) this.adj[i] = []; } // Function to add an edge into the graph addEdge(v, w) { this.adj[v].push(w); // Add w to v's list. this.adj[w].push(v); //Graph is undirected } // The function to print vertex cover printVertexCover() { // Initialize all vertices as not visited. let visited = new Array(this.V); for (let i = 0; i < this.V; i++) visited[i] = false; // Consider all edges one by one for (let u = 0; u < this.V; u++) { // An edge is only picked when both visited[u] // and visited[v] are false if (visited[u] == false) { // Go through all adjacents of u and pick the // first not yet visited vertex (We are basically // picking an edge (u, v) from remaining edges. for(let i = 0; i < this.adj[u].length; i++) { let v = this.adj[u][i]; if (visited[v] == false) { // Add the vertices (u, v) to the result // set. We make the vertex u and v visited // so that all edges from/to them would // be ignored visited[v] = true; visited[u] = true; break; } } } } // Print the vertex cover for (let j = 0; j < this.V; j++) if (visited[j]) document.write(j+\" \"); }} // Driver method// Create a graph given in the above diagramlet g = new Graph(7);g.addEdge(0, 1);g.addEdge(0, 2);g.addEdge(1, 3);g.addEdge(3, 4);g.addEdge(4, 5);g.addEdge(5, 6); g.printVertexCover(); // This code is contributed by patel2127</script>", "e": 12600, "s": 10396, "text": null }, { "code": null, "e": 12609, "s": 12600, "text": "Output: " }, { "code": null, "e": 12621, "s": 12609, "text": "0 1 3 4 5 6" }, { "code": null, "e": 13239, "s": 12621, "text": "The Time Complexity of the above algorithm is O(V + E).Exact Algorithms: Although the problem is NP complete, it can be solved in polynomial time for the following types of graphs. 1) Bipartite Graph 2) Tree GraphThe problem to check whether there is a vertex cover of size smaller than or equal to a given number k can also be solved in polynomial time if k is bounded by O(LogV) (Refer this)We will soon be discussing exact algorithms for vertex cover.This article is contributed by Shubham. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above" }, { "code": null, "e": 13256, "s": 13241, "text": "PrateekGupta10" }, { "code": null, "e": 13270, "s": 13256, "text": "GauravRajput1" }, { "code": null, "e": 13280, "s": 13270, "text": "patel2127" }, { "code": null, "e": 13293, "s": 13280, "text": "riyaprasad01" }, { "code": null, "e": 13300, "s": 13293, "text": "NPHard" }, { "code": null, "e": 13306, "s": 13300, "text": "Graph" }, { "code": null, "e": 13312, "s": 13306, "text": "Graph" }, { "code": null, "e": 13410, "s": 13312, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 13461, "s": 13410, "text": "Dijkstra's shortest path algorithm | Greedy Algo-7" }, { "code": null, "e": 13519, "s": 13461, "text": "Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2" }, { "code": null, "e": 13584, "s": 13519, "text": "Find if there is a path between two vertices in a directed graph" }, { "code": null, "e": 13617, "s": 13584, "text": "Detect Cycle in a Directed Graph" }, { "code": null, "e": 13649, "s": 13617, "text": "Introduction to Data Structures" }, { "code": null, "e": 13713, "s": 13649, "text": "What is Data Structure: Types, Classifications and Applications" }, { "code": null, "e": 13744, "s": 13713, "text": "Bellman–Ford Algorithm | DP-23" }, { "code": null, "e": 13812, "s": 13744, "text": "Find if there is a path between two vertices in an undirected graph" }, { "code": null, "e": 13862, "s": 13812, "text": "Minimum number of swaps required to sort an array" } ]
Daemon Thread in Java - GeeksforGeeks
07 Dec, 2021 Daemon thread in Java is a low-priority thread that runs in the background to perform tasks such as garbage collection. Daemon thread in Java is also a service provider thread that provides services to the user thread. Its life depends on the mercy of user threads i.e. when all the user threads die, JVM terminates this thread automatically. In simple words, we can say that it provides services to user threads for background supporting tasks. It has no role in life other than to serve user threads. Example of Daemon Thread in Java: Garbage collection in Java (gc), finalizer, etc. Properties of Java Daemon Thread They can not prevent the JVM from exiting when all the user threads finish their execution. JVM terminates itself when all user threads finish their execution. If JVM finds a running daemon thread, it terminates the thread and, after that, shutdown it. JVM does not care whether the Daemon thread is running or not. It is an utmost low priority thread. By default, the main thread is always non-daemon but for all the remaining threads, daemon nature will be inherited from parent to child. That is, if the parent is Daemon, the child is also a Daemon and if the parent is a non-daemon, then the child is also a non-daemon. Note: Whenever the last non-daemon thread terminates, all the daemon threads will be terminated automatically. This method marks the current thread as a daemon thread or user thread. For example, if I have a user thread tU then tU.setDaemon(true) would make it a Daemon thread. On the other hand, if I have a Daemon thread tD then calling tD.setDaemon(false) would make it a user thread. Syntax: public final void setDaemon(boolean on) Parameters: on: If true, marks this thread as a daemon thread. Exceptions: IllegalThreadStateException: if only this thread is active. SecurityException: if the current thread cannot modify this thread. This method is used to check that the current thread is a daemon. It returns true if the thread is Daemon. Else, it returns false. Syntax: public final boolean isDaemon() Returns: This method returns true if this thread is a daemon thread; false otherwise Java // Java program to demonstrate the usage of// setDaemon() and isDaemon() method. public class DaemonThread extends Thread{ public DaemonThread(String name){ super(name); } public void run() { // Checking whether the thread is Daemon or not if(Thread.currentThread().isDaemon()) { System.out.println(getName() + " is Daemon thread"); } else { System.out.println(getName() + " is User thread"); } } public static void main(String[] args) { DaemonThread t1 = new DaemonThread("t1"); DaemonThread t2 = new DaemonThread("t2"); DaemonThread t3 = new DaemonThread("t3"); // Setting user thread t1 to Daemon t1.setDaemon(true); // starting first 2 threads t1.start(); t2.start(); // Setting user thread t3 to Daemon t3.setDaemon(true); t3.start(); }} Output: t1 is Daemon thread t3 is Daemon thread t2 is User thread If you call the setDaemon() method after starting the thread, it would throw IllegalThreadStateException. Java // Java program to demonstrate the usage of// exception in Daemon() Thread public class DaemonThread extends Thread{ public void run() { System.out.println("Thread name: " + Thread.currentThread().getName()); System.out.println("Check if its DaemonThread: " + Thread.currentThread().isDaemon()); } public static void main(String[] args) { DaemonThread t1 = new DaemonThread(); DaemonThread t2 = new DaemonThread(); t1.start(); // Exception as the thread is already started t1.setDaemon(true); t2.start(); }} Runtime exception: Exception in thread "main" java.lang.IllegalThreadStateException at java.lang.Thread.setDaemon(Thread.java:1352) at DaemonThread.main(DaemonThread.java:19) Output: Thread name: Thread-0 Check if its DaemonThread: false This clearly shows that we cannot call the setDaemon() method after starting the thread. Priority: When the only remaining threads in a process are daemon threads, the interpreter exits. This makes sense because when only daemon threads remain, there is no other thread for which a daemon thread can provide a service.Usage: Daemon thread is to provide services to user thread for background supporting task. Priority: When the only remaining threads in a process are daemon threads, the interpreter exits. This makes sense because when only daemon threads remain, there is no other thread for which a daemon thread can provide a service. Usage: Daemon thread is to provide services to user thread for background supporting task. This article is contributed by Saket Kumar. If you like GeeksforGeeks and would like to contribute, you can 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. MayureshJakhotia Anirban166 nishkarshgandhi Java-Multithreading Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Arrays in Java Split() String method in Java with examples For-each loop in Java Stream In Java Object Oriented Programming (OOPs) Concept in Java Reverse a string in Java HashMap in Java with Examples Arrays.sort() in Java with examples Interfaces in Java How to iterate any Map in Java
[ { "code": null, "e": 24050, "s": 24022, "text": "\n07 Dec, 2021" }, { "code": null, "e": 24393, "s": 24050, "text": "Daemon thread in Java is a low-priority thread that runs in the background to perform tasks such as garbage collection. Daemon thread in Java is also a service provider thread that provides services to the user thread. Its life depends on the mercy of user threads i.e. when all the user threads die, JVM terminates this thread automatically." }, { "code": null, "e": 24553, "s": 24393, "text": "In simple words, we can say that it provides services to user threads for background supporting tasks. It has no role in life other than to serve user threads." }, { "code": null, "e": 24636, "s": 24553, "text": "Example of Daemon Thread in Java: Garbage collection in Java (gc), finalizer, etc." }, { "code": null, "e": 24669, "s": 24636, "text": "Properties of Java Daemon Thread" }, { "code": null, "e": 24761, "s": 24669, "text": "They can not prevent the JVM from exiting when all the user threads finish their execution." }, { "code": null, "e": 24829, "s": 24761, "text": "JVM terminates itself when all user threads finish their execution." }, { "code": null, "e": 24985, "s": 24829, "text": "If JVM finds a running daemon thread, it terminates the thread and, after that, shutdown it. JVM does not care whether the Daemon thread is running or not." }, { "code": null, "e": 25022, "s": 24985, "text": "It is an utmost low priority thread." }, { "code": null, "e": 25293, "s": 25022, "text": "By default, the main thread is always non-daemon but for all the remaining threads, daemon nature will be inherited from parent to child. That is, if the parent is Daemon, the child is also a Daemon and if the parent is a non-daemon, then the child is also a non-daemon." }, { "code": null, "e": 25404, "s": 25293, "text": "Note: Whenever the last non-daemon thread terminates, all the daemon threads will be terminated automatically." }, { "code": null, "e": 25682, "s": 25404, "text": "This method marks the current thread as a daemon thread or user thread. For example, if I have a user thread tU then tU.setDaemon(true) would make it a Daemon thread. On the other hand, if I have a Daemon thread tD then calling tD.setDaemon(false) would make it a user thread. " }, { "code": null, "e": 25691, "s": 25682, "text": "Syntax: " }, { "code": null, "e": 25731, "s": 25691, "text": "public final void setDaemon(boolean on)" }, { "code": null, "e": 25743, "s": 25731, "text": "Parameters:" }, { "code": null, "e": 25794, "s": 25743, "text": "on: If true, marks this thread as a daemon thread." }, { "code": null, "e": 25806, "s": 25794, "text": "Exceptions:" }, { "code": null, "e": 25866, "s": 25806, "text": "IllegalThreadStateException: if only this thread is active." }, { "code": null, "e": 25934, "s": 25866, "text": "SecurityException: if the current thread cannot modify this thread." }, { "code": null, "e": 26066, "s": 25934, "text": "This method is used to check that the current thread is a daemon. It returns true if the thread is Daemon. Else, it returns false. " }, { "code": null, "e": 26075, "s": 26066, "text": "Syntax: " }, { "code": null, "e": 26107, "s": 26075, "text": "public final boolean isDaemon()" }, { "code": null, "e": 26117, "s": 26107, "text": "Returns: " }, { "code": null, "e": 26193, "s": 26117, "text": "This method returns true if this thread is a daemon thread; false otherwise" }, { "code": null, "e": 26198, "s": 26193, "text": "Java" }, { "code": "// Java program to demonstrate the usage of// setDaemon() and isDaemon() method. public class DaemonThread extends Thread{ public DaemonThread(String name){ super(name); } public void run() { // Checking whether the thread is Daemon or not if(Thread.currentThread().isDaemon()) { System.out.println(getName() + \" is Daemon thread\"); } else { System.out.println(getName() + \" is User thread\"); } } public static void main(String[] args) { DaemonThread t1 = new DaemonThread(\"t1\"); DaemonThread t2 = new DaemonThread(\"t2\"); DaemonThread t3 = new DaemonThread(\"t3\"); // Setting user thread t1 to Daemon t1.setDaemon(true); // starting first 2 threads t1.start(); t2.start(); // Setting user thread t3 to Daemon t3.setDaemon(true); t3.start(); }}", "e": 27175, "s": 26198, "text": null }, { "code": null, "e": 27184, "s": 27175, "text": "Output: " }, { "code": null, "e": 27242, "s": 27184, "text": "t1 is Daemon thread\nt3 is Daemon thread\nt2 is User thread" }, { "code": null, "e": 27348, "s": 27242, "text": "If you call the setDaemon() method after starting the thread, it would throw IllegalThreadStateException." }, { "code": null, "e": 27353, "s": 27348, "text": "Java" }, { "code": "// Java program to demonstrate the usage of// exception in Daemon() Thread public class DaemonThread extends Thread{ public void run() { System.out.println(\"Thread name: \" + Thread.currentThread().getName()); System.out.println(\"Check if its DaemonThread: \" + Thread.currentThread().isDaemon()); } public static void main(String[] args) { DaemonThread t1 = new DaemonThread(); DaemonThread t2 = new DaemonThread(); t1.start(); // Exception as the thread is already started t1.setDaemon(true); t2.start(); }}", "e": 27981, "s": 27353, "text": null }, { "code": null, "e": 28001, "s": 27981, "text": "Runtime exception: " }, { "code": null, "e": 28165, "s": 28001, "text": "Exception in thread \"main\" java.lang.IllegalThreadStateException\n at java.lang.Thread.setDaemon(Thread.java:1352)\n at DaemonThread.main(DaemonThread.java:19)" }, { "code": null, "e": 28174, "s": 28165, "text": "Output: " }, { "code": null, "e": 28229, "s": 28174, "text": "Thread name: Thread-0\nCheck if its DaemonThread: false" }, { "code": null, "e": 28319, "s": 28229, "text": "This clearly shows that we cannot call the setDaemon() method after starting the thread. " }, { "code": null, "e": 28639, "s": 28319, "text": "Priority: When the only remaining threads in a process are daemon threads, the interpreter exits. This makes sense because when only daemon threads remain, there is no other thread for which a daemon thread can provide a service.Usage: Daemon thread is to provide services to user thread for background supporting task." }, { "code": null, "e": 28869, "s": 28639, "text": "Priority: When the only remaining threads in a process are daemon threads, the interpreter exits. This makes sense because when only daemon threads remain, there is no other thread for which a daemon thread can provide a service." }, { "code": null, "e": 28960, "s": 28869, "text": "Usage: Daemon thread is to provide services to user thread for background supporting task." }, { "code": null, "e": 29375, "s": 28960, "text": "This article is contributed by Saket Kumar. If you like GeeksforGeeks and would like to contribute, you can 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": 29392, "s": 29375, "text": "MayureshJakhotia" }, { "code": null, "e": 29403, "s": 29392, "text": "Anirban166" }, { "code": null, "e": 29419, "s": 29403, "text": "nishkarshgandhi" }, { "code": null, "e": 29439, "s": 29419, "text": "Java-Multithreading" }, { "code": null, "e": 29444, "s": 29439, "text": "Java" }, { "code": null, "e": 29449, "s": 29444, "text": "Java" }, { "code": null, "e": 29547, "s": 29449, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29562, "s": 29547, "text": "Arrays in Java" }, { "code": null, "e": 29606, "s": 29562, "text": "Split() String method in Java with examples" }, { "code": null, "e": 29628, "s": 29606, "text": "For-each loop in Java" }, { "code": null, "e": 29643, "s": 29628, "text": "Stream In Java" }, { "code": null, "e": 29694, "s": 29643, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 29719, "s": 29694, "text": "Reverse a string in Java" }, { "code": null, "e": 29749, "s": 29719, "text": "HashMap in Java with Examples" }, { "code": null, "e": 29785, "s": 29749, "text": "Arrays.sort() in Java with examples" }, { "code": null, "e": 29804, "s": 29785, "text": "Interfaces in Java" } ]
Python | Test if tuple is distinct - GeeksforGeeks
03 Nov, 2019 Sometimes, while working with records, we have a problem in which we need to find if all elements of tuple are different. This can have applications in many domains including web development. Let’s discuss certain ways in which this task can be performed. Method #1 : Using loopThis is a brute force way in which this task can be performed. In this, we just iterate through all tuple elements and put it in set if it’s the first occurrence. During the subsequence occurrence we check in set, if it exists, we return False. # Python3 code to demonstrate working of# Test if tuple is distinct# Using loop # initialize tuple test_tup = (1, 4, 5, 6, 1, 4) # printing original tuple print("The original tuple is : " + str(test_tup)) # Test if tuple is distinct# Using loopres = True temp = set()for ele in test_tup: if ele in temp: res = False break temp.add(ele) # printing resultprint("Is tuple distinct ? : " + str(res)) The original tuple is : (1, 4, 5, 6, 1, 4) Is tuple distinct ? : False Method #2 : Using set() + len()In this method, we convert the tuple into a set using set(), and then check it with original tuple length, if matches, means that it was a distinct tuple and returns True. # Python3 code to demonstrate working of# Test if tuple is distinct# Using set() + len() # initialize tuple test_tup = (1, 4, 5, 6) # printing original tuple print("The original tuple is : " + str(test_tup)) # Test if tuple is distinct# Using set() + len()res = len(set(test_tup)) == len(test_tup) # printing resultprint("Is tuple distinct ? : " + str(res)) The original tuple is : (1, 4, 5, 6) Is tuple distinct ? : True Python tuple-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 ? How To Convert Python Dictionary To JSON? Check if element exists in list in Python How to drop one or multiple columns in Pandas Dataframe Python Classes and Objects Defaultdict in Python Python | Get dictionary keys as a list Python | Split string into list of characters Python | Convert a list to dictionary How to print without newline in Python?
[ { "code": null, "e": 25647, "s": 25619, "text": "\n03 Nov, 2019" }, { "code": null, "e": 25903, "s": 25647, "text": "Sometimes, while working with records, we have a problem in which we need to find if all elements of tuple are different. This can have applications in many domains including web development. Let’s discuss certain ways in which this task can be performed." }, { "code": null, "e": 26170, "s": 25903, "text": "Method #1 : Using loopThis is a brute force way in which this task can be performed. In this, we just iterate through all tuple elements and put it in set if it’s the first occurrence. During the subsequence occurrence we check in set, if it exists, we return False." }, { "code": "# Python3 code to demonstrate working of# Test if tuple is distinct# Using loop # initialize tuple test_tup = (1, 4, 5, 6, 1, 4) # printing original tuple print(\"The original tuple is : \" + str(test_tup)) # Test if tuple is distinct# Using loopres = True temp = set()for ele in test_tup: if ele in temp: res = False break temp.add(ele) # printing resultprint(\"Is tuple distinct ? : \" + str(res))", "e": 26591, "s": 26170, "text": null }, { "code": null, "e": 26663, "s": 26591, "text": "The original tuple is : (1, 4, 5, 6, 1, 4)\nIs tuple distinct ? : False\n" }, { "code": null, "e": 26868, "s": 26665, "text": "Method #2 : Using set() + len()In this method, we convert the tuple into a set using set(), and then check it with original tuple length, if matches, means that it was a distinct tuple and returns True." }, { "code": "# Python3 code to demonstrate working of# Test if tuple is distinct# Using set() + len() # initialize tuple test_tup = (1, 4, 5, 6) # printing original tuple print(\"The original tuple is : \" + str(test_tup)) # Test if tuple is distinct# Using set() + len()res = len(set(test_tup)) == len(test_tup) # printing resultprint(\"Is tuple distinct ? : \" + str(res))", "e": 27230, "s": 26868, "text": null }, { "code": null, "e": 27295, "s": 27230, "text": "The original tuple is : (1, 4, 5, 6)\nIs tuple distinct ? : True\n" }, { "code": null, "e": 27317, "s": 27295, "text": "Python tuple-programs" }, { "code": null, "e": 27324, "s": 27317, "text": "Python" }, { "code": null, "e": 27340, "s": 27324, "text": "Python Programs" }, { "code": null, "e": 27438, "s": 27340, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27470, "s": 27438, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27512, "s": 27470, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 27554, "s": 27512, "text": "Check if element exists in list in Python" }, { "code": null, "e": 27610, "s": 27554, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 27637, "s": 27610, "text": "Python Classes and Objects" }, { "code": null, "e": 27659, "s": 27637, "text": "Defaultdict in Python" }, { "code": null, "e": 27698, "s": 27659, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 27744, "s": 27698, "text": "Python | Split string into list of characters" }, { "code": null, "e": 27782, "s": 27744, "text": "Python | Convert a list to dictionary" } ]
C# | How to insert the elements of a collection into the List at the specified index - GeeksforGeeks
18 Oct, 2019 List<T>.InsertRange(Int32, IEnumerable<T>) Method is used to insert the elements of a collection into the List<T> at the specified index. Properties of List: It is different from the arrays. A list can be resized dynamically but arrays cannot. List class can accept null as a valid value for reference types and it also allows duplicate elements. If the Count becomes equals to Capacity then the capacity of the List increases automatically by reallocating the internal array. The existing elements will be copied to the new array before the addition of the new element. Syntax: public void InsertRange (int index, System.Collections.Generic.IEnumerable<T> collection); Parameter: index: It is the zero-based index at which the new elements should be inserted. collection: It is the collection whose elements will be inserted into the List<T> Note: The collection itself cannot be null. But it can contain elements which can be null if the type T is a reference type. Exceptions: ArgumentNullException: If the collection is null. ArgumentOutOfRangeException: If the index is less than zero or greater than count. Below programs illustrate the use of above discussed method: Example 1: // C# Program to insert the elements of// a collection into the List<T> at the// specified indexusing System;using System.Collections;using System.Collections.Generic; class Geeks { // Main Method public static void Main(String[] args) { string[] str1 = { "Geeks", "for", "Geeks" }; // Creating an List<T> of strings // adding str1 elements to List List<String> firstlist = new List<String>(str1); // displaying the elements of firstlist Console.WriteLine("Elements in List: \n"); foreach(string dis in firstlist) { Console.WriteLine(dis); } Console.WriteLine(" "); // contains new Elements which is // to be added in the List str1 = new string[] { "New", "Element", "Added" }; // using InsertRange Method Console.WriteLine("InsertRange(2, str1)\n"); // adding elements after 2nd // index of the List firstlist.InsertRange(2, str1); // displaying the elements of // List after InsertRange Method foreach(string res in firstlist) { Console.WriteLine(res); } }} Output: Elements in List: Geeks for Geeks InsertRange(2, str1) Geeks for New Element Added Geeks Example 2: // C# Program to insert the elements of// a collection into the List<T> at the// specified indexusing System;using System.Collections;using System.Collections.Generic; class Geeks { // Main Method public static void Main(String[] args) { string[] str1 = { "Geeks", "for", "Geeks" }; // Creating an List<T> of strings // adding str1 elements to List List<String> firstlist = new List<String>(str1); // displaying the elements of firstlist Console.WriteLine("Elements in List: \n"); foreach(string dis in firstlist) { Console.WriteLine(dis); } Console.WriteLine(" "); // contains new Elements which is // to be added in the List str1 = new string[] { "New", "Element", "Added" }; // using InsertRange Method Console.WriteLine("InsertRange(2, str1)\n"); // this will give error as // index is less than 0 firstlist.InsertRange(-1, str1); // displaying the elements of // List after InsertRange Method foreach(string res in firstlist) { Console.WriteLine(res); } }} Error: Unhandled Exception:System.ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection.Parameter name: index Reference: https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1.insertrange?view=netframework-4.7.2 nidhi_biet CSharp-Collections-Namespace CSharp-Generic-List CSharp-Generic-Namespace CSharp-method C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. C# | Delegates C# | Abstract Classes Difference between Ref and Out keywords in C# Extension Method in C# C# | Class and Object C# | Replace() Method C# | Constructors Introduction to .NET Framework C# | Data Types HashSet in C# with Examples
[ { "code": null, "e": 25882, "s": 25854, "text": "\n18 Oct, 2019" }, { "code": null, "e": 26020, "s": 25882, "text": "List<T>.InsertRange(Int32, IEnumerable<T>) Method is used to insert the elements of a collection into the List<T> at the specified index." }, { "code": null, "e": 26040, "s": 26020, "text": "Properties of List:" }, { "code": null, "e": 26126, "s": 26040, "text": "It is different from the arrays. A list can be resized dynamically but arrays cannot." }, { "code": null, "e": 26229, "s": 26126, "text": "List class can accept null as a valid value for reference types and it also allows duplicate elements." }, { "code": null, "e": 26453, "s": 26229, "text": "If the Count becomes equals to Capacity then the capacity of the List increases automatically by reallocating the internal array. The existing elements will be copied to the new array before the addition of the new element." }, { "code": null, "e": 26461, "s": 26453, "text": "Syntax:" }, { "code": null, "e": 26553, "s": 26461, "text": "public void InsertRange (int index, System.Collections.Generic.IEnumerable<T> collection);\n" }, { "code": null, "e": 26564, "s": 26553, "text": "Parameter:" }, { "code": null, "e": 26644, "s": 26564, "text": "index: It is the zero-based index at which the new elements should be inserted." }, { "code": null, "e": 26726, "s": 26644, "text": "collection: It is the collection whose elements will be inserted into the List<T>" }, { "code": null, "e": 26851, "s": 26726, "text": "Note: The collection itself cannot be null. But it can contain elements which can be null if the type T is a reference type." }, { "code": null, "e": 26863, "s": 26851, "text": "Exceptions:" }, { "code": null, "e": 26913, "s": 26863, "text": "ArgumentNullException: If the collection is null." }, { "code": null, "e": 26996, "s": 26913, "text": "ArgumentOutOfRangeException: If the index is less than zero or greater than count." }, { "code": null, "e": 27057, "s": 26996, "text": "Below programs illustrate the use of above discussed method:" }, { "code": null, "e": 27068, "s": 27057, "text": "Example 1:" }, { "code": "// C# Program to insert the elements of// a collection into the List<T> at the// specified indexusing System;using System.Collections;using System.Collections.Generic; class Geeks { // Main Method public static void Main(String[] args) { string[] str1 = { \"Geeks\", \"for\", \"Geeks\" }; // Creating an List<T> of strings // adding str1 elements to List List<String> firstlist = new List<String>(str1); // displaying the elements of firstlist Console.WriteLine(\"Elements in List: \\n\"); foreach(string dis in firstlist) { Console.WriteLine(dis); } Console.WriteLine(\" \"); // contains new Elements which is // to be added in the List str1 = new string[] { \"New\", \"Element\", \"Added\" }; // using InsertRange Method Console.WriteLine(\"InsertRange(2, str1)\\n\"); // adding elements after 2nd // index of the List firstlist.InsertRange(2, str1); // displaying the elements of // List after InsertRange Method foreach(string res in firstlist) { Console.WriteLine(res); } }}", "e": 28352, "s": 27068, "text": null }, { "code": null, "e": 28360, "s": 28352, "text": "Output:" }, { "code": null, "e": 28455, "s": 28360, "text": "Elements in List: \n\nGeeks\nfor\nGeeks\n \nInsertRange(2, str1)\n\nGeeks\nfor\nNew\nElement\nAdded\nGeeks\n" }, { "code": null, "e": 28466, "s": 28455, "text": "Example 2:" }, { "code": "// C# Program to insert the elements of// a collection into the List<T> at the// specified indexusing System;using System.Collections;using System.Collections.Generic; class Geeks { // Main Method public static void Main(String[] args) { string[] str1 = { \"Geeks\", \"for\", \"Geeks\" }; // Creating an List<T> of strings // adding str1 elements to List List<String> firstlist = new List<String>(str1); // displaying the elements of firstlist Console.WriteLine(\"Elements in List: \\n\"); foreach(string dis in firstlist) { Console.WriteLine(dis); } Console.WriteLine(\" \"); // contains new Elements which is // to be added in the List str1 = new string[] { \"New\", \"Element\", \"Added\" }; // using InsertRange Method Console.WriteLine(\"InsertRange(2, str1)\\n\"); // this will give error as // index is less than 0 firstlist.InsertRange(-1, str1); // displaying the elements of // List after InsertRange Method foreach(string res in firstlist) { Console.WriteLine(res); } }}", "e": 29752, "s": 28466, "text": null }, { "code": null, "e": 29759, "s": 29752, "text": "Error:" }, { "code": null, "e": 29923, "s": 29759, "text": "Unhandled Exception:System.ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection.Parameter name: index" }, { "code": null, "e": 29934, "s": 29923, "text": "Reference:" }, { "code": null, "e": 30048, "s": 29934, "text": "https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1.insertrange?view=netframework-4.7.2" }, { "code": null, "e": 30059, "s": 30048, "text": "nidhi_biet" }, { "code": null, "e": 30088, "s": 30059, "text": "CSharp-Collections-Namespace" }, { "code": null, "e": 30108, "s": 30088, "text": "CSharp-Generic-List" }, { "code": null, "e": 30133, "s": 30108, "text": "CSharp-Generic-Namespace" }, { "code": null, "e": 30147, "s": 30133, "text": "CSharp-method" }, { "code": null, "e": 30150, "s": 30147, "text": "C#" }, { "code": null, "e": 30248, "s": 30150, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30263, "s": 30248, "text": "C# | Delegates" }, { "code": null, "e": 30285, "s": 30263, "text": "C# | Abstract Classes" }, { "code": null, "e": 30331, "s": 30285, "text": "Difference between Ref and Out keywords in C#" }, { "code": null, "e": 30354, "s": 30331, "text": "Extension Method in C#" }, { "code": null, "e": 30376, "s": 30354, "text": "C# | Class and Object" }, { "code": null, "e": 30398, "s": 30376, "text": "C# | Replace() Method" }, { "code": null, "e": 30416, "s": 30398, "text": "C# | Constructors" }, { "code": null, "e": 30447, "s": 30416, "text": "Introduction to .NET Framework" }, { "code": null, "e": 30463, "s": 30447, "text": "C# | Data Types" } ]
Print Diagonally | Practice | GeeksforGeeks
Give a N * N square matrix, return all the elements of its anti-diagonals from top to bottom. Example 1: Input: N = 2 A = [[1, 2], [3, 4]] Output: 1 2 3 4 Explanation: Topmost anti-diagonal is [[1, ], [ , ]] Next anti-diagonal is [[ , 2], ​ [3, ]] and the last anti-diagonal is [[ , ], ​ [ , 4]] Hence, elements will be returned in the order {1, 2, 3, 4}. Example 2: Input: N = 3 A = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] Output: 1 2 4 3 5 7 6 8 9 Your Task: You don't need to read input or print anything. Your task is to complete the function downwardDigonal() which takes an integer N and a 2D matrix A[ ][ ] as input parameters and returns the list of all elements of its anti-diagonals from top to bottom. Expected Time Complexity: O(N*N) Expected Auxillary Space: O(N*N) Constraints: 1 ≤ N, M ≤ 103 0 ≤ A[i][j] ≤ 106 0 priyansh708902 days ago vector<int>v; for(int i=0;i<n;i++){ int row=0,col=i; while(col>=0){ v.push_back(A[row][col]);row++;col--; } } for(int i=1;i<n;i++){ int row=i,col=n-1; while(row<n){ v.push_back(A[row][col]); row++; col--; } } return v;} 0 roy99mustang4 days ago Easy python solution : #User function Template for python3 def downwardDigonal(n, A): c = [] for l in range(2*n-1): t, b = max(0, l+1-n), min(l, n-1) for i in range(t, b+1): c.append(A[i][l-i]) return c #{ # Driver Code Starts #Initial Template for Python 3 if __name__ == '__main__': t = int(input()) for _ in range(t): n = int(input()) matrix =[] for i in range(n): row = list(map(int, input().strip().split())) matrix.append(row) ans = downwardDigonal(n,matrix) for i in ans: print(i,end=" ") print() # } Driver Code Ends +1 sharma9897akash1 week ago SINGLE LOOP O(n) SOLUTION ArrayList<Integer> al=new ArrayList<>(); int count=0,st=0,en=0; for(int i=0;i<n*(n+1)/2;i++) { al.add(A[st][en]); if(en==0) { en=st+1; st=0; } else { st+=1; en-=1; } } st=1;en=n-1; int c; for(int i=0;i<n*(n-1)/2;i++) { al.add(A[st][en]); if(st==n-1) { c=en; en=st; st=c+1; } else { st+=1; en-=1; } } return al; 0 harshsinghreal2 weeks ago MY C++ Approach vector<int> downwardDigonal(int n, vector<vector<int>> A) { vector<int> v; for(int k=0;k<n;k++){ int i = 0,j=k; while(j>=0){ v.push_back(A[i][j]); i++; j--; } } for(int k=1;k<n;k++){ int i = k, j = n-1; while(i<n){ v.push_back(A[i][j]); j--; i++; } } return v; } 0 amansidd178613 weeks ago vector<int> downwardDigonal(int n, vector<vector<int>> arr){ // Your code goes here vector<int> ans; int row=0; int i=0; while(row<n){ int r = row; int c = i; while(r<n and c>=0){ ans.push_back(arr[r][c]); r++,c--; } if(i==n-1) row++; else i++; } return ans;} 0 kmehta33 weeks ago Python Naïve implementation: def downwardDigonal(n, A): # code here output = [] for col in range(n): j = col row = 0 while j >= 0: element = A[row][j] output.append(element) row += 1 j -= 1 for row in range(1, n): i = row col = n - 1 while i < n: element = A[i][col] output.append(element) col -= 1 i += 1 return output 0 ajay7yadav953 weeks ago //hi JavaScript lovers -----------→ A7 let arr = [[1, 2], [3, 4]]; let str = ""; for(let i=0;i<arr.length;i++){ for(let j=0;j<arr[0].length;j++){ str += arr[i][j]+" "; } } return str; 0 bajpayeevinayak2281 month ago reader...keep faith in your self...you are the best...and you only can help your self... // { Driver Code Starts#include<bits/stdc++.h>using namespace std; // } Driver Code Ends class Solution{public:vector<int> downwardDigonal(int n, vector<vector<int>> A){ // Your code goes here vector<int> ans; ///reader you need to dry run the code have faith in your self;;; for(int i=0;i<n;i++) { int j=i,k=0; for(;j>=0;j--) { ans.push_back(A[k][j]); k++; } } for(int i=1;i<n;i++) { int j=i,k=n-1; for(;j<n;j++) { ans.push_back(A[j][k]); k--; } } return ans;} }; // { Driver Code Starts. int main(){ int t; cin >> t; while(t--) { int n; cin >> n; vector<vector<int>> A(n, vector<int>(n)); for(int i = 0; i < n; i++) for(int j = 0; j < n; j++) cin >> A[i][j]; Solution obj; vector<int> ans = obj.downwardDigonal(n, A); for(auto i:ans) cout << i << " "; cout << "\n"; } return 0;} // } Driver Code Ends +1 durpb12011 month ago C++ code vector<int> res; int k= 0,l=1; while(k<(A[0].size()+A.size()-1)){ if(k<A[0].size()){ int i = 0; for(int j = k;j >=0;j--) { res.push_back(A[i][j]); i++; } k++; } else { int j = A[0].size()-1; for(int i = l ; i < A.size();i++) { res.push_back(A[i][j]); j--; } l++; k++; } } return res; 0 abhisinha6562 months ago vector<int> downwardDigonal(int n, vector<vector<int>> A){ vector<int>V; for(int i=0; i<n; i++){ int k=0, j=i; for(; j>=0; j--){ V.push_back(A[k][j]); k++; } } for(int i=1; i<n; i++){ int k = n-1, j=i; for(; j<n; j++){ V.push_back(A[j][k]); k--; } } return V;} 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": 321, "s": 226, "text": "Give a N * N square matrix, return all the elements of its anti-diagonals from top to bottom. " }, { "code": null, "e": 332, "s": 321, "text": "Example 1:" }, { "code": null, "e": 693, "s": 332, "text": "Input: \nN = 2\nA = [[1, 2],\n [3, 4]]\nOutput:\n1 2 3 4\nExplanation: Topmost anti-diagonal is [[1, ], \n [ , ]]\nNext anti-diagonal is [[ , 2], \n​ [3, ]]\nand the last anti-diagonal is [[ , ], \n​ [ , 4]]\nHence, elements will be returned in the \norder {1, 2, 3, 4}.\n" }, { "code": null, "e": 704, "s": 693, "text": "Example 2:" }, { "code": null, "e": 795, "s": 704, "text": "Input: \nN = 3 \nA = [[1, 2, 3],\n [4, 5, 6],\n [7, 8, 9]]\nOutput: \n1 2 4 3 5 7 6 8 9\n" }, { "code": null, "e": 1058, "s": 795, "text": "Your Task:\nYou don't need to read input or print anything. Your task is to complete the function downwardDigonal() which takes an integer N and a 2D matrix A[ ][ ] as input parameters and returns the list of all elements of its anti-diagonals from top to bottom." }, { "code": null, "e": 1124, "s": 1058, "text": "Expected Time Complexity: O(N*N)\nExpected Auxillary Space: O(N*N)" }, { "code": null, "e": 1170, "s": 1124, "text": "Constraints:\n1 ≤ N, M ≤ 103\n0 ≤ A[i][j] ≤ 106" }, { "code": null, "e": 1172, "s": 1170, "text": "0" }, { "code": null, "e": 1196, "s": 1172, "text": "priyansh708902 days ago" }, { "code": null, "e": 1483, "s": 1196, "text": " vector<int>v; for(int i=0;i<n;i++){ int row=0,col=i; while(col>=0){ v.push_back(A[row][col]);row++;col--; } } for(int i=1;i<n;i++){ int row=i,col=n-1; while(row<n){ v.push_back(A[row][col]); row++; col--; } } return v;}" }, { "code": null, "e": 1485, "s": 1483, "text": "0" }, { "code": null, "e": 1508, "s": 1485, "text": "roy99mustang4 days ago" }, { "code": null, "e": 1532, "s": 1508, "text": "Easy python solution : " }, { "code": null, "e": 2196, "s": 1532, "text": "#User function Template for python3\n\ndef downwardDigonal(n, A): \n c = []\n for l in range(2*n-1):\n t, b = max(0, l+1-n), min(l, n-1)\n \n for i in range(t, b+1):\n c.append(A[i][l-i])\n \n return c\n \n \n#{ \n# Driver Code Starts\n#Initial Template for Python 3\n\nif __name__ == '__main__':\n t = int(input())\n for _ in range(t):\n n = int(input())\n matrix =[]\n for i in range(n):\n row = list(map(int, input().strip().split()))\n matrix.append(row)\n ans = downwardDigonal(n,matrix)\n for i in ans:\n print(i,end=\" \")\n print()\n\n# } Driver Code Ends" }, { "code": null, "e": 2199, "s": 2196, "text": "+1" }, { "code": null, "e": 2225, "s": 2199, "text": "sharma9897akash1 week ago" }, { "code": null, "e": 2253, "s": 2227, "text": "SINGLE LOOP O(n) SOLUTION" }, { "code": null, "e": 2922, "s": 2255, "text": "ArrayList<Integer> al=new ArrayList<>(); int count=0,st=0,en=0; for(int i=0;i<n*(n+1)/2;i++) { al.add(A[st][en]); if(en==0) { en=st+1; st=0; } else { st+=1; en-=1; } } st=1;en=n-1; int c; for(int i=0;i<n*(n-1)/2;i++) { al.add(A[st][en]); if(st==n-1) { c=en; en=st; st=c+1; } else { st+=1; en-=1; } } return al;" }, { "code": null, "e": 2924, "s": 2922, "text": "0" }, { "code": null, "e": 2950, "s": 2924, "text": "harshsinghreal2 weeks ago" }, { "code": null, "e": 2966, "s": 2950, "text": "MY C++ Approach" }, { "code": null, "e": 3361, "s": 2966, "text": "vector<int> downwardDigonal(int n, vector<vector<int>> A)\n\t{\n\t vector<int> v;\n\t\tfor(int k=0;k<n;k++){\n\t\t int i = 0,j=k;\n\t\t \n\t\t while(j>=0){\n\t\t v.push_back(A[i][j]);\n\t\t i++; j--;\n\t\t }\n\t\t}\n\t\t\n\t\t\n\t\tfor(int k=1;k<n;k++){\n\t\t int i = k, j = n-1;\n\t\t \n\t\t while(i<n){\n\t\t v.push_back(A[i][j]);\n\t\t j--;\n\t\t i++;\n\t\t }\n\t\t}\n\t\t\n\t\treturn v;\n\t}" }, { "code": null, "e": 3363, "s": 3361, "text": "0" }, { "code": null, "e": 3388, "s": 3363, "text": "amansidd178613 weeks ago" }, { "code": null, "e": 3664, "s": 3388, "text": "vector<int> downwardDigonal(int n, vector<vector<int>> arr){ // Your code goes here vector<int> ans; int row=0; int i=0; while(row<n){ int r = row; int c = i; while(r<n and c>=0){ ans.push_back(arr[r][c]); r++,c--; } if(i==n-1) row++; else i++; } return ans;}" }, { "code": null, "e": 3666, "s": 3664, "text": "0" }, { "code": null, "e": 3685, "s": 3666, "text": "kmehta33 weeks ago" }, { "code": null, "e": 3715, "s": 3685, "text": "Python Naïve implementation:" }, { "code": null, "e": 4139, "s": 3717, "text": "def downwardDigonal(n, A): # code here output = [] for col in range(n): j = col row = 0 while j >= 0: element = A[row][j] output.append(element) row += 1 j -= 1 for row in range(1, n): i = row col = n - 1 while i < n: element = A[i][col] output.append(element) col -= 1 i += 1 return output " }, { "code": null, "e": 4141, "s": 4139, "text": "0" }, { "code": null, "e": 4165, "s": 4141, "text": "ajay7yadav953 weeks ago" }, { "code": null, "e": 4204, "s": 4165, "text": "//hi JavaScript lovers -----------→ A7" }, { "code": null, "e": 4223, "s": 4204, "text": "let arr = [[1, 2]," }, { "code": null, "e": 4242, "s": 4223, "text": " [3, 4]];" }, { "code": null, "e": 4256, "s": 4242, "text": "let str = \"\";" }, { "code": null, "e": 4287, "s": 4256, "text": "for(let i=0;i<arr.length;i++){" }, { "code": null, "e": 4325, "s": 4287, "text": " for(let j=0;j<arr[0].length;j++){" }, { "code": null, "e": 4355, "s": 4325, "text": " str += arr[i][j]+\" \";" }, { "code": null, "e": 4361, "s": 4355, "text": " }" }, { "code": null, "e": 4363, "s": 4361, "text": "}" }, { "code": null, "e": 4375, "s": 4363, "text": "return str;" }, { "code": null, "e": 4377, "s": 4375, "text": "0" }, { "code": null, "e": 4407, "s": 4377, "text": "bajpayeevinayak2281 month ago" }, { "code": null, "e": 4500, "s": 4411, "text": "reader...keep faith in your self...you are the best...and you only can help your self..." }, { "code": null, "e": 4567, "s": 4500, "text": "// { Driver Code Starts#include<bits/stdc++.h>using namespace std;" }, { "code": null, "e": 4589, "s": 4567, "text": "// } Driver Code Ends" }, { "code": null, "e": 5026, "s": 4589, "text": "class Solution{public:vector<int> downwardDigonal(int n, vector<vector<int>> A){ // Your code goes here vector<int> ans; ///reader you need to dry run the code have faith in your self;;; for(int i=0;i<n;i++) { int j=i,k=0; for(;j>=0;j--) { ans.push_back(A[k][j]); k++; } } for(int i=1;i<n;i++) { int j=i,k=n-1; for(;j<n;j++) { ans.push_back(A[j][k]); k--; } } return ans;}" }, { "code": null, "e": 5029, "s": 5026, "text": "};" }, { "code": null, "e": 5054, "s": 5029, "text": "// { Driver Code Starts." }, { "code": null, "e": 5068, "s": 5056, "text": "int main(){" }, { "code": null, "e": 5140, "s": 5068, "text": " int t; cin >> t; while(t--) { int n; cin >> n;" }, { "code": null, "e": 5189, "s": 5140, "text": " vector<vector<int>> A(n, vector<int>(n));" }, { "code": null, "e": 5281, "s": 5189, "text": " for(int i = 0; i < n; i++) for(int j = 0; j < n; j++) cin >> A[i][j];" }, { "code": null, "e": 5353, "s": 5281, "text": " Solution obj; vector<int> ans = obj.downwardDigonal(n, A);" }, { "code": null, "e": 5401, "s": 5353, "text": " for(auto i:ans) cout << i << \" \";" }, { "code": null, "e": 5423, "s": 5401, "text": " cout << \"\\n\"; }" }, { "code": null, "e": 5459, "s": 5423, "text": " return 0;} // } Driver Code Ends" }, { "code": null, "e": 5462, "s": 5459, "text": "+1" }, { "code": null, "e": 5483, "s": 5462, "text": "durpb12011 month ago" }, { "code": null, "e": 5492, "s": 5483, "text": "C++ code" }, { "code": null, "e": 5973, "s": 5492, "text": "\tvector<int> res;\n\t\tint k= 0,l=1;\n\t\twhile(k<(A[0].size()+A.size()-1)){\n\t\t if(k<A[0].size()){\n\t\t int i = 0;\n\t\t for(int j = k;j >=0;j--)\n\t\t {\n\t\t res.push_back(A[i][j]);\n\t\t i++;\n\t\t }\n\t\t k++;\n\t\t }\n\t\t else\n\t\t {\n\t\t int j = A[0].size()-1;\n\t\t for(int i = l ; i < A.size();i++)\n\t\t {\n\t\t res.push_back(A[i][j]);\n\t\t j--;\n\t\t }\n\t\t l++;\n\t\t k++;\n\t\t }\n\t\t}\n\t\treturn res;" }, { "code": null, "e": 5975, "s": 5973, "text": "0" }, { "code": null, "e": 6000, "s": 5975, "text": "abhisinha6562 months ago" }, { "code": null, "e": 6407, "s": 6000, "text": "vector<int> downwardDigonal(int n, vector<vector<int>> A){ vector<int>V; for(int i=0; i<n; i++){ int k=0, j=i; for(; j>=0; j--){ V.push_back(A[k][j]); k++; } } for(int i=1; i<n; i++){ int k = n-1, j=i; for(; j<n; j++){ V.push_back(A[j][k]); k--; } } return V;}" }, { "code": null, "e": 6553, "s": 6407, "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": 6589, "s": 6553, "text": " Login to access your submissions. " }, { "code": null, "e": 6599, "s": 6589, "text": "\nProblem\n" }, { "code": null, "e": 6609, "s": 6599, "text": "\nContest\n" }, { "code": null, "e": 6672, "s": 6609, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 6820, "s": 6672, "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": 7028, "s": 6820, "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": 7134, "s": 7028, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Python | Pandas PeriodIndex.freq - GeeksforGeeks
20 Aug, 2021 Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas PeriodIndex.freq attribute returns the time series frequency that is applied on the given PeriodIndex object. Syntax : PeriodIndex.freqParameters : NoneReturn : Index Example #1: Use PeriodIndex.freq attribute to find the time series frequency of the given PeriodIndex object. Python3 # importing pandas as pdimport pandas as pd # Create the PeriodIndex objectpidx = pd.PeriodIndex(start='2005-12-21 08:45 ', end='2005-12-21 11:55', freq='H') # Print the PeriodIndex objectprint(pidx) Output : Now we will use the PeriodIndex.freq attribute to find the time series frequency of the given object. Python3 # return the frequencypidx.freq Output : As we can see in the output, the PeriodIndex.freq attribute has returned ‘Hourly’ frequency. This is the time series frequency that is applied on the given PeriodIndex object. Example #2: Use PeriodIndex.freq attribute to find the time series frequency of the given PeriodIndex object. Python3 # importing pandas as pdimport pandas as pd # Create the PeriodIndex objectpidx = pd.PeriodIndex(start='2011-02-1 ', end='2011-08-14', freq='M') # Print the PeriodIndex objectprint(pidx) Output : Now we will use the PeriodIndex.freq attribute to find the time series frequency of the given object. Python3 # return the frequencypidx.freq Output : As we can see in the output, the PeriodIndex.freq attribute has returned the ‘Monthly’ frequency. This is the time series frequency that is applied on the given PeriodIndex object. anikakapoor Pandas periodIndex Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Iterate over a list in Python Python String | replace() Reading and Writing to text files in Python *args and **kwargs in Python Create a Pandas DataFrame from Lists Convert integer to string in Python
[ { "code": null, "e": 24942, "s": 24914, "text": "\n20 Aug, 2021" }, { "code": null, "e": 25156, "s": 24942, "text": "Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier." }, { "code": null, "e": 25273, "s": 25156, "text": "Pandas PeriodIndex.freq attribute returns the time series frequency that is applied on the given PeriodIndex object." }, { "code": null, "e": 25332, "s": 25273, "text": "Syntax : PeriodIndex.freqParameters : NoneReturn : Index " }, { "code": null, "e": 25443, "s": 25332, "text": "Example #1: Use PeriodIndex.freq attribute to find the time series frequency of the given PeriodIndex object. " }, { "code": null, "e": 25451, "s": 25443, "text": "Python3" }, { "code": "# importing pandas as pdimport pandas as pd # Create the PeriodIndex objectpidx = pd.PeriodIndex(start='2005-12-21 08:45 ', end='2005-12-21 11:55', freq='H') # Print the PeriodIndex objectprint(pidx)", "e": 25664, "s": 25451, "text": null }, { "code": null, "e": 25674, "s": 25664, "text": "Output : " }, { "code": null, "e": 25776, "s": 25674, "text": "Now we will use the PeriodIndex.freq attribute to find the time series frequency of the given object." }, { "code": null, "e": 25784, "s": 25776, "text": "Python3" }, { "code": "# return the frequencypidx.freq", "e": 25816, "s": 25784, "text": null }, { "code": null, "e": 25826, "s": 25816, "text": "Output : " }, { "code": null, "e": 26002, "s": 25826, "text": "As we can see in the output, the PeriodIndex.freq attribute has returned ‘Hourly’ frequency. This is the time series frequency that is applied on the given PeriodIndex object." }, { "code": null, "e": 26113, "s": 26002, "text": "Example #2: Use PeriodIndex.freq attribute to find the time series frequency of the given PeriodIndex object. " }, { "code": null, "e": 26121, "s": 26113, "text": "Python3" }, { "code": "# importing pandas as pdimport pandas as pd # Create the PeriodIndex objectpidx = pd.PeriodIndex(start='2011-02-1 ', end='2011-08-14', freq='M') # Print the PeriodIndex objectprint(pidx)", "e": 26320, "s": 26121, "text": null }, { "code": null, "e": 26331, "s": 26320, "text": "Output : " }, { "code": null, "e": 26433, "s": 26331, "text": "Now we will use the PeriodIndex.freq attribute to find the time series frequency of the given object." }, { "code": null, "e": 26441, "s": 26433, "text": "Python3" }, { "code": "# return the frequencypidx.freq", "e": 26473, "s": 26441, "text": null }, { "code": null, "e": 26484, "s": 26473, "text": "Output : " }, { "code": null, "e": 26666, "s": 26484, "text": "As we can see in the output, the PeriodIndex.freq attribute has returned the ‘Monthly’ frequency. This is the time series frequency that is applied on the given PeriodIndex object. " }, { "code": null, "e": 26678, "s": 26666, "text": "anikakapoor" }, { "code": null, "e": 26697, "s": 26678, "text": "Pandas periodIndex" }, { "code": null, "e": 26711, "s": 26697, "text": "Python-pandas" }, { "code": null, "e": 26718, "s": 26711, "text": "Python" }, { "code": null, "e": 26816, "s": 26718, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26834, "s": 26816, "text": "Python Dictionary" }, { "code": null, "e": 26866, "s": 26834, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26888, "s": 26866, "text": "Enumerate() in Python" }, { "code": null, "e": 26930, "s": 26888, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 26960, "s": 26930, "text": "Iterate over a list in Python" }, { "code": null, "e": 26986, "s": 26960, "text": "Python String | replace()" }, { "code": null, "e": 27030, "s": 26986, "text": "Reading and Writing to text files in Python" }, { "code": null, "e": 27059, "s": 27030, "text": "*args and **kwargs in Python" }, { "code": null, "e": 27096, "s": 27059, "text": "Create a Pandas DataFrame from Lists" } ]
Case Study 1: Customer satisfaction prediction on Olist Brazillian Dataset | by Ashwin Michael | Towards Data Science
Businesses have always tried to keep their customer base engaged and satisfied with the services provided by them. For remaining relevant in the industry, they need to incorporate the latest technological advances into their services. More than a decade back, it was the internet which was completely new and various industries tried to leverage the capabilities of this technology that effortlessly acted as a medium of communication between various businesses and their customers. In this decade, industries have started to provide services that are catered towards each client’s individual needs. For such services, they are required to leverage the power of artificial intelligence. We shall be exploring an aspect of this technology in this case study. This case study has been divided into the following sections: - Business problem ML formulation of business problem Basic data analysis Business constraints Performance metric Data Description Exploratory data analysis Feature engineering Machine learning Future work Links References The Olist store is an e-commerce business headquartered in Sao Paulo, Brazil. This firm acts as a single point of contact between various small businesses and the customers who wish to buy their products. Recently, they uploaded a dataset on Kaggle that contains information about 100k orders made at multiple marketplaces between 2016 to 2018. What we purchase on e-commerce websites is affected by the reviews which we read about the product posted on that website. This firm can certainly leverage these reviews to remove those products which consistently receive negative reviews. It could also advertise those items which are popular amongst the customers. The source code for this case study is available here. We are presented with a 5-star rating system that summarizes the overall satisfaction of the customer with the product which he or she had just purchased. We can convert this aspect into a binary classification problem by treating the 4 and 5-star ratings as the positive class and the rest as the negative class. We are given multiple tables and a schema depicting how these tables are connected. After merging all the tables, we analyze the entire dataset. It contains multiple categorical and numerical columns. After converting the given 5-star ratings into binary, we see that the positive class occupies 76% of the dataset and the remaining is populated by the negative class. This means that the dataset is heavily imbalanced. Furniture decor, beauty products and sports equipment are the most popular categories as per the sales records. It is known that customers spend around 125 Brazilian real on average for purchasing the products from this website. On analyzing the state-wise distribution of the customers, we can see that the majority of the orders had been placed by customers located in Sao Paulo. The freight cost on most of the items was reasonable. This can be a reason why many were satisfied with the product overall. The majority of the transactions took place using credit cards. Negative reviews are less, yet important. We should see to it that a lesser number of negative reviews are classified as positive. This means that we need to minimize the number of false positives. No constraint on latency is required for completing this task. Confusion matrices are used for getting an insight into the type of errors that the model makes. Precision is required for reducing the number of false positives and recall is needed for reducing the number of false negatives. This is why we shall use the macro F1 score as a metric. When you check the schematic diagram explaining the database connectivity, you’ll find eight tables. The description of these tables is as follows: - 1)olist_orders_dataset: This table is connected to 4 other tables. It is used to connect all the details related to an order.2) olist_order_items_dataset: It contains the details of an item that had been purchased such as shipping date, price and so on. 3) olist_order_reviews_dataset: It contains details related to any reviews posted by the customer on a particular product that he had purchased.4) olist_products_dataset: It contains related to a product such as the ID, category name and measurements.5) olist_order_payments_dataset: The information contained in this table is related to the payment details associated with a particular order.6) olist_customers_dataset: Details the customer base information of this firm.7) olist_geolocation_dataset: It contains geographical information related to both the sellers and customers.8) olist_sellers_dataset: This table contains the information related to all the sellers who have registered with this firm. All of these tables are connected using primary and foreign keys. We shall join all the individual CSV files to create a large table. All of these keys end with the suffix ‘id’ or ‘prefix’. Since this dataset is based on a Brazilian e-commerce company, the area of circulation is most probably Brazil and its neighbouring countries. This is why we shall take the plot of the South American continent and use the geographical data mentioned in the geolocation dataset to visually depict the geographical locations of the orders. As you can see on the map, the majority of the customers are located in Brazil. For further analysis, we won’t be using the geolocation dataset. This is why it won’t be added to the main dataframe. order_items_products = pd.merge(order_items_dataset,products_dataset,on='product_id')order_items_products_sellers = pd.merge(order_items_products,sellers_dataset,on='seller_id')two_order_items_products_sellers = pd.merge(order_items_products_sellers,orders_dataset,on='order_id')two_order_items_products_sellers_customer = pd.merge(two_order_items_products_sellers,customers_dataset,on='customer_id')two_order_items_products_sellers_customer_reviews = pd.merge(two_order_items_products_sellers_customer,order_reviews_dataset,on='order_id')final_dataframe = pd.merge(two_order_items_products_sellers_customer_reviews,order_payments_dataset,on='order_id') There is a possibility that some of the observations may be repeated. These are redundant and that is why we need to remove them. We shall be dropping those observations which have the same Order ID, Customer ID, purchase timestamp and review from the dataset. This is because a customer cannot post the same review multiple times for the same product at the same instant of time. Notice that all the ID values, which acted as the primary and foreign keys, are unique. We cannot find a pattern with such rows, and thus, we shall be dropping them. It is not possible to impute datetime data. That’s why we should remove those rows which contain null values in any of the datetime columns. While parsing through the datetime columns, we and extracting the date information and creating two extra columns using it. The ‘purchase delivery difference’ column gives us the number of days between the time of purchase and delivery. The ‘estimated actual delivery difference’ column gives us the delay or the cut-down in the number of days required for the delivery. intermediate_time = final_dataframe['order_delivered_customer_date'].apply(lambda x: datetime.strptime(x, "%Y-%m-%d %H:%M:%S").date()) - final_dataframe['order_purchase_timestamp'].apply(lambda x: datetime.strptime(x, "%Y-%m-%d %H:%M:%S").date())final_dataframe['purchase-delivery difference'] = intermediate_time.apply(lambda x:x.days)intermediate_time = final_dataframe['order_estimated_delivery_date'].apply(lambda x: datetime.strptime(x, "%Y-%m-%d %H:%M:%S").date()) - final_dataframe['order_delivered_customer_date'].apply(lambda x: datetime.strptime(x, "%Y-%m-%d %H:%M:%S").date())final_dataframe['estimated-actual delivery difference'] = intermediate_time.apply(lambda x:x.days) Let us now try to impute the other types of columns. For the categorical columns, we shall use the mode of that column and for numerical columns, we shall use the median of that column for imputation. For reviews comment and title, we use the term ‘indisponível’, which is the Portuguese translation for the English term ‘unavailable’. final_dataframe['product_category_name'].fillna(value=final_dataframe['product_category_name'].mode()[0], inplace=True)final_dataframe['product_name_lenght'].fillna(value=final_dataframe['product_name_lenght'].mode()[0], inplace=True)final_dataframe['product_description_lenght'].fillna(value=final_dataframe['product_description_lenght'].median(), inplace=True)final_dataframe['product_photos_qty'].fillna(value=final_dataframe['product_photos_qty'].mode()[0], inplace=True)final_dataframe['product_weight_g'].fillna(value=final_dataframe['product_weight_g'].mode()[0], inplace=True)final_dataframe['product_length_cm'].fillna(value=final_dataframe['product_length_cm'].mode()[0], inplace=True)final_dataframe['product_height_cm'].fillna(value=final_dataframe['product_height_cm'].mode()[0], inplace=True)final_dataframe['product_width_cm'].fillna(value=final_dataframe['product_width_cm'].mode()[0], inplace=True)final_dataframe['review_comment_message'].fillna(value='indisponível', inplace=True) We aim to convert this case study into a binary classification task. For that, we need to create a new column that contains the labels. Values that are rated more than 3 are labelled as positive and those whose values are 3 or below are labelled as negative. final_dataframe['review_score'] = final_dataframe['review_score'].apply(lambda x: 1 if x > 3 else 0) On plotting the pie chart showing the labels, we see that the positive class occupies 77.60% of the entire dataset; whereas the negative class only occupies 22.40%. This indicates that the entire dataset is imbalanced. Some columns contain only numerical data. This means that finding the basic statistics of these columns is one thing that we can try. Notice that there is a significant difference between the mean and median values for the ‘price’ and ‘product length description’ columns. Let us create a new column called ‘price category’ This column is used to categorize the goods as expensive, cheap and affordable based on their price. We have used the first, second and third quartiles as the conditions for creating these categories. final_dataframe['price_category'] = final_dataframe['price'].apply(lambda x:'expensive' if x>=139 else ('affordable' if x>=40 and x<139 else 'cheap')) We are now finding the top 12 most popular product categories in terms of the frequency of purchase. The category ‘bed bath table’ is significantly more popular than most of the other categories. It is the only category whose sales have crossed 10000 units. The category in the 12th position- ‘garden tools’ only had around 3600 units sold. Sao Paulo, also shortened to ‘SP’ is by leaps and bounds the state with the highest customer base of this firm. It might be because this company’s headquarters is set up in Sao Paulo and more customers were informed about this website due to their heavy marketing strategy around this area. More than 40000 units were sold in Sao Paulo between 2016 and 2018. When we check the pricing per product category, we can see that the average cost of a product is the highest for the items belonging to the ‘computers’ category. The average cost is around 1150 real. The second-highest category has an average price of nearly half of the highest category. For this plot, we considered the overall average cost of an item. This means that it is the sum of the freight charges and the original cost of the item. We can see that the ordering of the plot hasn’t changed. It’s only that the average cost of each category that has increased. We are now finding the city which generates the highest revenue. The city named ‘Pianco’ generates is at the top. There are only two statuses visible here. Only 6 orders have been cancelled to date. It doesn’t make sense to analyze those products which have been cancelled. Thus, we shall delete them. final_dataframe = final_dataframe[final_dataframe['order_status'] != 'canceled'] The below-given scatter plot takes the price on the x-axis and the total time difference between delivery and purchase on the y-axis. It can be seen that as the time taken for delivery increases, the chances of being dissatisfied with the product increases significantly. The increase in the price of an item does not cause too much dissatisfaction if it is delivered on time. We are now creating a new column called ‘purchase delivery diff per price’, which is the time difference between the purchase and delivery of a product given the price. final_dataframe['purchase_delivery_diff_per_price'] = final_dataframe['purchase-delivery difference']/final_dataframe['price'] The scatter plot between the freight cost and item cost very much descriptive. But it can be said that even if the freight cost is high, customers were satisfied when the item cost is less. Credit cards are the most popular mode of payment amongst customers. They are much more popular than the other alternatives. The second in line, Boletos, are a type of voucher that can only be found in Brazil. From this plot, we could see that the bad reviews given to a product were most probably not because of a payment related issue. Now it’s time to drop all the columns which aren’t necessary for the machine learning task. All the datetime columns should be removed. final_dataframe.drop(['shipping_limit_date','order_purchase_timestamp','order_approved_at','order_delivered_carrier_date','order_delivered_customer_date','order_estimated_delivery_date','customer_id'], axis=1, inplace=True) We shall now create a new variable called ‘labels’ which contain the edited class polarity. This column should be removed from the original data frame. labels = final_dataframe['review_score']final_dataframe.drop('review_score', axis=1, inplace=True) The ‘review availability’ column indicates whether the review of a particular item is available or not. Including this column is better than including a bunch of zeros in the ‘review comment message’ because it avoids sparsity. The problem with sparsity is that it can severely reduce the performance of any model. final_dataframe['review_availability'] = final_dataframe['review_comment_message'].apply(lambda x: 1 if x != 'indisponível' else 0) For machine learning, we need to define a train set for training the data and a test set for predicting. Both these sets contain both the classes in equal proportion. Since the dataset is imbalanced, there is a chance that the distribution of these labels could heavily affect the performance of any machine learning model. So, we need to see to it that both the test and train sets contain positive and negative labels in the same proportion. And for reproducibility of the results, we need to add a seed value. X_train, X_test, y_train, y_test = train_test_split(final_dataframe, labels, stratify=labels, test_size=0.2, random_state=0) Some columns contain multiple categories. The encoding technique which we normally think about is either one-hot encoding or ordinal encoding. The problem of sparsity arises when we use the one-hot encoding technique because there are too many categories. Ordinal encoding cannot be used unless ordinality is present in the categories. One way to tackle this situation is by using response coding. In this technique, we add the probability of occurrence of all the categories with each label. This means that each category will have two probability values- one for the positive class and another for the negative class. Overall, two distinct columns are being created for each categorical column. def train_response(frame): f1 = frame[frame.iloc[:,1] == 0] f2 = frame[frame.iloc[:,1] == 1] global dict_frame, dict_f1, dict_f2 dict_frame = dict(frame.iloc[:,0].value_counts()) dict_f1 = dict(f1.iloc[:,0].value_counts()) dict_f2 = dict(f2.iloc[:,0].value_counts()) state_0, state_1 = [],[], for i in range(len(frame)): if frame.iloc[:,1][i] == 0: state_0.append(dict_f1.get(frame.iloc[:,0][i],0) / dict_frame[frame.iloc[:,0][i]]) state_1.append(float(1-state_0[-1])) else: state_1.append(dict_f2.get(frame.iloc[:,0][i],0) / dict_frame[frame.iloc[:,0][i]]) state_0.append(float(1-state_1[-1])) df3 = pd.DataFrame({'State_0':state_0, 'State_1':state_1}) return df3.to_numpy()def test_response(test): t_state_0, t_state_1 = [],[] for i in range(len(test)): if dict_frame.get(test[i]): t_state_0.append(dict_f1.get(test[i],0) / dict_frame.get(test[i])) t_state_1.append(dict_f2.get(test[i],0) / dict_frame.get(test[i])) else: t_state_0.append(0.5) t_state_1.append(0.5) df4 = pd.DataFrame({'State_0':t_state_0, 'State_1':t_state_1}) return df4.to_numpy()def test_response(test): t_state_0, t_state_1 = [],[] for i in range(len(test)): if dict_frame.get(test[i]): t_state_0.append(dict_f1.get(test[i],0)/dict_frame.get(test[i])) t_state_1.append(dict_f2.get(test[i],0)/dict_frame.get(test[i])) else: t_state_0.append(0.5) t_state_1.append(0.5) df4 = pd.DataFrame({'State_0':t_state_0, 'State_1':t_state_1}) return df4.to_numpy() We shall encode the categorical features which contain fewer categories using either ordinal or one hot encoding and encode them using response coding if there are too many categories. There is no need to encode the numerical features. Note that we aren’t considering all the columns present in the data frame. Only those are encoded which we deem as necessary. The encoding pattern per category is mentioned below: - Next, we shall look at text data. One of the best ways to handle text data is to convert them into word embeddings. Word embeddings are better than TF-IDF vectors and Bag-of-words because they carry the semantic meaning of words. We shall be using FastText as the word embedding technique in this case study. It would’ve been possible to transform these words into TF-IDF vectors and later reduce the dimensionality using techniques such as Latent semantic analysis. This approach is faster, but the problem is that the dense vectors which we derive using this technique do to contain the semantic representation of these words. This approach would then reduce the accuracy of our models. Before vectorizing the text, we need to clean it. First, we shall remove the stop words and clean the remaining using regex. sp = spacy.load('pt')all_stopwords = sp.Defaults.stop_wordsdef process_texts(texts):processed_text = [] dates = '^([0]?[1-9]|[1|2][0-9]|[3][0|1])[./-]([0]?[1-9]|[1][0-2])[./-]([0-9]{4}|[0-9]{2})$' for text in texts: text = re.sub(r'\r\n|\r|\n', ' ', text) text = re.sub(r'^https?:\/\/.*[\r\n]*', ' ', text) text = re.sub(dates, ' ', text) text = re.sub('[ \t]+$', '', text) text = re.sub('\W', ' ', text) text = re.sub('[0-9]+', ' ', text) text = re.sub('\s+', ' ', text) text = ' '.join(e for e in text.split() if e.lower() not in all_stopwords) processed_text.append(text.lower().strip()) return processed_text We still haven’t brought all the numerical features into the same scale. For this, we shall be using standardization. We are using standardization instead of normalization because as seen in the description of the basic statistics, there are many outliers present in this dataset. strn = StandardScaler()strn.fit(X_train[['price','freight_value','product_photos_qty','product_weight_g', 'product_length_cm', 'product_height_cm', 'product_width_cm', 'payment_value','purchase-delivery difference','estimated-actual delivery difference','purchase_delivery_diff_per_price']])X_train_strn = strn.transform(X_train[['price','freight_value','product_photos_qty','product_weight_g', 'product_length_cm', 'product_height_cm', 'product_width_cm', 'payment_value','purchase-delivery difference','estimated-actual delivery difference','purchase_delivery_diff_per_price']])X_test_strn = strn.transform(X_test[['price','freight_value','product_photos_qty','product_weight_g', 'product_length_cm', 'product_height_cm', 'product_width_cm', 'payment_value','purchase-delivery difference','estimated-actual delivery difference','purchase_delivery_diff_per_price']]) It is now time to concatenate all the necessary features together and check the shape of the final dataframe. It can be seen that there are 332 features overall. We shall try to reduce this dimensionality using two techniques. One is by finding the hard threshold using singular value decomposition and the other is by using autoencoders. Singular value decomposition is a widely used matrix factorization technique that can be applied to matrices of any dimension. It converts the given matrix into a set of three matrices, named as U, Σ and V* respectively. Note that the symbol ‘*’ is used to indicate the transpose operator. The singular values of any matrix A of dimensionality MxN are the square roots of the eigenvalues of the square matrix A*A of dimensionality NxN. Here, Σ is a diagonal matrix that contains the singular values as its elements along the diagonal. The rows of U and the columns V* matrices which correspond to the diagonal elements of Σ are known as the left and right singular vectors. Remember that we are taking the transpose of the matrix V by default. Let us explain singular values using a geometric intuition. As we already know, a matrix of dimensionality MxN is a linear transformation from the real space RN into the real space RM, mathematically notated as RN→ RM. SVD is a way to decompose this direct transformation into a set of three transformations, which are- first rotation, scaling and second rotation. Now consider a unit circle with two vectors given in yellow and magenta colours. Here we are considering a transformation from R2 to R2. So, both M and N are equal to 2 in this example. After transformation, this circle changes into an ellipse which has been rotated. This overall transformation can be broken into 3 steps as mentioned in the diagram. After the first rotation(applying V*), the circle rotates through an angle. Then the Σ matrix scales the axis of this figure. The scaling of each axis is proportional to the magnitude of the singular vectors. Note that our two vectors would change in magnitude. After the second rotation(applying U), the ellipse gets rotated by an angle. Rank reduction is a technique by which high-dimensional noisy data can be transformed into low-dimensional cleaner data. The rank defines a threshold value that we could consider for truncating the U matrix which we had obtained using SVD. Researchers used to take a heuristic approach for finding an optimal rank. The problem with the approach was that they were unsure whether the truncated matrix obtained using this rank contained sufficient information to reconstruct the clean image. Another approach would be to use trial-and-error, which is time-consuming. In a recent paper, a technique named optimal singular valued hard threshold was mentioned which laid the theoretical foundation of finding the optimal threshold value for truncation. We are required to find a threshold value τ*, which is the optimal threshold. The ‘*’ symbol used in this formula does not indicate transpose. The formula depends on whether the value of noise added to the image is known and whether the matrix is square or not. This noise is assumed to have a mean value of 0 and a standard deviation of 1. It is very unlikely that the matrix is square and the noise is known. But if these two conditions are fulfilled, the formula is Here, ’n’ is the dimensionality of the square matrix and ‘σ’ is the noise. Under most circumstances, we don’t know the amount of noise that has been added. The formula is Here, β=n/m and ymed is the median of all the singular values. Note that the value of ω(β) which we have used here is just an approximation. Their actual value could also be calculated, but it would require further processing. Since we are using this rank reduction technique in SVD only for dimensionality reduction purposes and not for image denoising, finding the exact value of ω(β) isn’t important. X_final_sparse = scipy.sparse.csr_matrix(np.vstack((X_train_final,X_test_final)))U, sigma, VT = randomized_svd(X_final_sparse, n_components=min(X_final_sparse.shape[0],X_final_sparse.shape[1])-1,n_iter=5,random_state=45)beta = min(X_final_sparse.shape) / max(X_final_sparse.shape)omega_approx = 0.56*beta**3 - 0.95*beta**2 + 1.82*beta + 1.43tau = np.median(sigma)*omega_approxk = np.max(np.where(sigma>tau))+1 It can be seen that the newly formed matrix has 116 features, which preserves most of the variance. After this, we split the truncated matrix into train and test sets. It is possible to reduce the dimensionality using neural networks. We shall be using autoencoders, a type of neural networks to encode the data efficiently. Note that autoencoders fall under unsupervised learning. In the autoencoder architecture, the size of the input and output layers are the same. The size of the hidden layers will always be lesser than the size of the external layers. The size of each consecutive hidden layer keeps on reducing till it reaches the bottleneck layer; beyond which the size keeps on increasing. Note that the architecture is symmetrical. The part which compresses the data is known as the encoder and the part which decompresses it is known as the decoder. The encoder extends from the input towards the bottleneck layer and from there on the decoder extends till the end. The bottleneck layer should have the dimensionality which we require for our data to be encoded into. An autoencoder aims to minimize the reconstruction error. The input gets compressed at the bottleneck layer and then gets decompressed at the output layer. The training converges after the error between the input and output gets minimized. In our architecture, we are using the dimensionality of 116 at the bottleneck layer. Only two hidden layers are being used on each side of the network. After the training converges, we need to drop the decoder part and use the encoder part to transform both our training and test sets into the required dimensionality. Now that we have created two versions of the data using two different dimensionality reduction techniques, we shall try to model the data using various machine learning and deep learning algorithms and then try to compare their performance using different metrics. We plan to apply five different algorithms to each of them. These algorithms are- K-nearest neighbours(KNN), logistic regression, random forests, xgboost and multi-layered perceptrons(MLP). We shall apply each of them on one form of data and then all of them on the other form. The hyperparameter used in the case of KNN is the count of the nearest neighbours(K) whose values are odd numbers ranging from 1 to 9. The performance is said to be the best when the value of K is 3. The validation macro F1 score is 0.8587 and it isn’t great. By checking the test confusion matrices, we can see that the count of the false positive points is greater than the count of the false negative points. This isn’t a good classifier. The hyperparameters used in the case of logistic regression is the inverse regularization constant(C) whose values are the powers of 10 that range from 1e-7 to 1e-3. This model performs the best when the value of C is 1e-5. The validation macro F1 score is 0.9003 and it is good. Unfortunately, we can see that the count of the false positive points is greater than the count of the true negative points when we plot the confusion matrices of the test set. This isn’t a good classifier. The hyperparameters used in random forest is the count of the base estimators, which in this case are decision trees. Six values are chosen between 50 and 210 as the number of estimators, where the limits are inclusive in the set. There is a difference of 30 between any two consecutive values. The validation macro F1 score is 0.9161 and it is great. The count of true negatives is greater than the count of false positives. This is a good classifier. The hyperparameters used in xgboost is the count of the base estimators, which also in this case are decision trees. Six values are chosen between 50 and 210 as the number of estimators, where the limits are inclusive in the set as mentioned above. The validation macro F1 score is 0.9191 and it is great. The count of true negatives is greater than the count of false positives. This is a good classifier. Now we shall use multi-layered perceptrons for classification. The optimizer used in this case is Adam and the learning rate is 1e-3. The validation macro F1 score is 0.9074 and it is good. The count of true negatives is greater than the count of false positives in this case. This is a good classifier. From what we’ve seen till now, random forest, Xgboost and mlp can properly classify the points. Xgboost performs the best amongst them. The hyperparameter used in the case of KNN is the count of the nearest neighbours(K) whose values are odd numbers ranging from 1 to 9. The performance is said to be the best when the value of K is 3. The validation macro F1 score is 0.8564 and it isn’t great. By checking the test confusion matrices, we can see that the count of the false positive points is greater than the count of the false negative points. This isn’t a good classifier. The hyperparameters used in the case of logistic regression is the inverse regularization constant(C) whose values are the powers of 10 that range from 1e-7 to 1e-3. This model performs the best when the value of C is 1e-2. The validation macro F1 score is 0.8874 and it is okay. We can see that the count of the false positive points is greater than the count of the true negative points when we plot the confusion matrices of the test set. This is a bad classifier. The hyperparameters used in random forest is the count of the base estimators, which in this case are decision trees. Six values are chosen between 50 and 210 as the number of estimators, where the limits are inclusive in the set. There is a difference of 30 between any two consecutive values. The validation macro F1 score is 0.8895 and it is good. Unfortunately, the count of true negatives is lesser than the count of false positives. This is a bad classifier. The hyperparameters used in xgboost is the count of the base estimators, which also in this case are decision trees. Six values are chosen between 50 and 210 as the number of estimators, where the limits are inclusive in the set as mentioned above. The validation macro F1 score is 0.8867 and it is okay. Unfortunately, the count of true negatives is lesser than the count of false positives. This is a bad classifier. Now we shall use multi-layered perceptron for classification. The optimizer used in this case is Adam and the learning rate is 1e-3. The validation macro F1 score is 0.8924 and it is okay. The count of true negatives is lesser than the count of false positives in this case. This is a bad classifier. From what we have here, it is observable that we cannot design a good classifier using the dataset compressed using autoencoders. We still haven’t tried feeding the tokenized reviews directly as input to the models. For this to happen, we are required to operate on the entire dataset rather than the truncated or compressed version of the same. For this purpose, we shall try two deep learning models. In the initial model, we shall try using Long short term memory(LSTM) only. We are creating two different inputs for this model. The first input is for numerical data and the other is for text data. An embedding layer converts the tokenized input into a fixed-length vector. We are training the embedding layer using FastText. Thus, the tokenized and padded text is converted into word embeddings using this layer. The next layer on this path is LSTM. This layer is capable of learning the order dependence when given a sequence. The next layer is directly fed to the dense layers. Both these inputs later get combined and there is a sigmoid activation function at the output. The validation macro F1 score is 0.9211 and it is great. The count of true negatives is greater than the count of false positives. This is a good classifier. In the next model, we are planning to use 1-dimensional convolutional neural networks along with LSTM. Here we are using two pairs of 1-D CNN and LSTM layers consecutively before combining it with the numerical data. Here also, we are using sigmoid as the activation function at the end. The validation macro F1 score is 0.9010 and it is good. The count of true negatives is greater than the count of false positives. This is a good classifier. When we check the summarized tables, we can see that both dual input LSTM and xgboost on data truncated using hard threshold SVD perform the best on the test data. We could convert this problem into a multi-class classification problem and check the rating predict. This is a metric called log loss which could also be used as an alternative. There is also the possibility of using other ensembles. Screenshot of the deployment is mentioned given below. A video recording of the same can be viewed here. LinkedIn: https://www.linkedin.com/in/ashwin-michael-10b617142/Github repository: https://github.com/Ashcom-git/case-study-1Kaggle dataset: https://www.kaggle.com/olistbr/brazilian-ecommerce Applied Roots. 2021. Applied AI Course. [online] Available at: <https://www.appliedaicourse.com/.> [Accessed 6 May 2021].Taylor, R., 2021. Optimal Singular Value Hard Threshold. [online] Pyrunner.com. Available at: <http://www.pyrunner.com/weblog/2016/08/01/optimal-svht/> [Accessed 9 May 2021].Brownlee, J., 2021. Autoencoder Feature Extraction for Classification. [online] Machine Learning Mastery. Available at: <https://machinelearningmastery.com/autoencoder-for-classification/> [Accessed 12 May 2021].Calin, T. and Xue, J., 2021. Custom f1_score metric in tensorflow. [online] Stack Overflow. Available at: <https://stackoverflow.com/a/64477588> [Accessed 7 May 2021].Stack Overflow. 2021. How to change legend size with matplotlib.pyplot. [online] Available at: <https://stackoverflow.com/a/7125157> [Accessed 3 May 2021].Aziz, H., Kumar, S., Korshunov, V. and Atha, P., 2021. Regex to match date formats DD-MM-YYYY and DD/MM/YYYY. [online] Stack Overflow. Available at: <https://stackoverflow.com/a/47218282> [Accessed 13 May 2021].Wal, P. and Paving, C., 2021. Match linebreaks — \n or \r\n?. [online] Stack Overflow. Available at: <https://stackoverflow.com/a/52057778> [Accessed 14 May 2021].Python, H. and Martin, L., 2021. How to remove any URL within a string in Python. [online] Stack Overflow. Available at: <https://stackoverflow.com/a/11332580> [Accessed 14 May 2021].Mortensen, P., 2021. How do I remove trailing whitespace using a regular expression?. [online] Stack Overflow. Available at: <https://stackoverflow.com/a/9532388> [Accessed 16 May 2021].
[ { "code": null, "e": 994, "s": 172, "text": "Businesses have always tried to keep their customer base engaged and satisfied with the services provided by them. For remaining relevant in the industry, they need to incorporate the latest technological advances into their services. More than a decade back, it was the internet which was completely new and various industries tried to leverage the capabilities of this technology that effortlessly acted as a medium of communication between various businesses and their customers. In this decade, industries have started to provide services that are catered towards each client’s individual needs. For such services, they are required to leverage the power of artificial intelligence. We shall be exploring an aspect of this technology in this case study. This case study has been divided into the following sections: -" }, { "code": null, "e": 1011, "s": 994, "text": "Business problem" }, { "code": null, "e": 1046, "s": 1011, "text": "ML formulation of business problem" }, { "code": null, "e": 1066, "s": 1046, "text": "Basic data analysis" }, { "code": null, "e": 1087, "s": 1066, "text": "Business constraints" }, { "code": null, "e": 1106, "s": 1087, "text": "Performance metric" }, { "code": null, "e": 1123, "s": 1106, "text": "Data Description" }, { "code": null, "e": 1149, "s": 1123, "text": "Exploratory data analysis" }, { "code": null, "e": 1169, "s": 1149, "text": "Feature engineering" }, { "code": null, "e": 1186, "s": 1169, "text": "Machine learning" }, { "code": null, "e": 1198, "s": 1186, "text": "Future work" }, { "code": null, "e": 1204, "s": 1198, "text": "Links" }, { "code": null, "e": 1215, "s": 1204, "text": "References" }, { "code": null, "e": 1932, "s": 1215, "text": "The Olist store is an e-commerce business headquartered in Sao Paulo, Brazil. This firm acts as a single point of contact between various small businesses and the customers who wish to buy their products. Recently, they uploaded a dataset on Kaggle that contains information about 100k orders made at multiple marketplaces between 2016 to 2018. What we purchase on e-commerce websites is affected by the reviews which we read about the product posted on that website. This firm can certainly leverage these reviews to remove those products which consistently receive negative reviews. It could also advertise those items which are popular amongst the customers. The source code for this case study is available here." }, { "code": null, "e": 2246, "s": 1932, "text": "We are presented with a 5-star rating system that summarizes the overall satisfaction of the customer with the product which he or she had just purchased. We can convert this aspect into a binary classification problem by treating the 4 and 5-star ratings as the positive class and the rest as the negative class." }, { "code": null, "e": 3237, "s": 2246, "text": "We are given multiple tables and a schema depicting how these tables are connected. After merging all the tables, we analyze the entire dataset. It contains multiple categorical and numerical columns. After converting the given 5-star ratings into binary, we see that the positive class occupies 76% of the dataset and the remaining is populated by the negative class. This means that the dataset is heavily imbalanced. Furniture decor, beauty products and sports equipment are the most popular categories as per the sales records. It is known that customers spend around 125 Brazilian real on average for purchasing the products from this website. On analyzing the state-wise distribution of the customers, we can see that the majority of the orders had been placed by customers located in Sao Paulo. The freight cost on most of the items was reasonable. This can be a reason why many were satisfied with the product overall. The majority of the transactions took place using credit cards." }, { "code": null, "e": 3498, "s": 3237, "text": "Negative reviews are less, yet important. We should see to it that a lesser number of negative reviews are classified as positive. This means that we need to minimize the number of false positives. No constraint on latency is required for completing this task." }, { "code": null, "e": 3782, "s": 3498, "text": "Confusion matrices are used for getting an insight into the type of errors that the model makes. Precision is required for reducing the number of false positives and recall is needed for reducing the number of false negatives. This is why we shall use the macro F1 score as a metric." }, { "code": null, "e": 3932, "s": 3782, "text": "When you check the schematic diagram explaining the database connectivity, you’ll find eight tables. The description of these tables is as follows: -" }, { "code": null, "e": 4892, "s": 3932, "text": "1)olist_orders_dataset: This table is connected to 4 other tables. It is used to connect all the details related to an order.2) olist_order_items_dataset: It contains the details of an item that had been purchased such as shipping date, price and so on. 3) olist_order_reviews_dataset: It contains details related to any reviews posted by the customer on a particular product that he had purchased.4) olist_products_dataset: It contains related to a product such as the ID, category name and measurements.5) olist_order_payments_dataset: The information contained in this table is related to the payment details associated with a particular order.6) olist_customers_dataset: Details the customer base information of this firm.7) olist_geolocation_dataset: It contains geographical information related to both the sellers and customers.8) olist_sellers_dataset: This table contains the information related to all the sellers who have registered with this firm." }, { "code": null, "e": 5082, "s": 4892, "text": "All of these tables are connected using primary and foreign keys. We shall join all the individual CSV files to create a large table. All of these keys end with the suffix ‘id’ or ‘prefix’." }, { "code": null, "e": 5420, "s": 5082, "text": "Since this dataset is based on a Brazilian e-commerce company, the area of circulation is most probably Brazil and its neighbouring countries. This is why we shall take the plot of the South American continent and use the geographical data mentioned in the geolocation dataset to visually depict the geographical locations of the orders." }, { "code": null, "e": 5618, "s": 5420, "text": "As you can see on the map, the majority of the customers are located in Brazil. For further analysis, we won’t be using the geolocation dataset. This is why it won’t be added to the main dataframe." }, { "code": null, "e": 6272, "s": 5618, "text": "order_items_products = pd.merge(order_items_dataset,products_dataset,on='product_id')order_items_products_sellers = pd.merge(order_items_products,sellers_dataset,on='seller_id')two_order_items_products_sellers = pd.merge(order_items_products_sellers,orders_dataset,on='order_id')two_order_items_products_sellers_customer = pd.merge(two_order_items_products_sellers,customers_dataset,on='customer_id')two_order_items_products_sellers_customer_reviews = pd.merge(two_order_items_products_sellers_customer,order_reviews_dataset,on='order_id')final_dataframe = pd.merge(two_order_items_products_sellers_customer_reviews,order_payments_dataset,on='order_id')" }, { "code": null, "e": 6819, "s": 6272, "text": "There is a possibility that some of the observations may be repeated. These are redundant and that is why we need to remove them. We shall be dropping those observations which have the same Order ID, Customer ID, purchase timestamp and review from the dataset. This is because a customer cannot post the same review multiple times for the same product at the same instant of time. Notice that all the ID values, which acted as the primary and foreign keys, are unique. We cannot find a pattern with such rows, and thus, we shall be dropping them." }, { "code": null, "e": 7331, "s": 6819, "text": "It is not possible to impute datetime data. That’s why we should remove those rows which contain null values in any of the datetime columns. While parsing through the datetime columns, we and extracting the date information and creating two extra columns using it. The ‘purchase delivery difference’ column gives us the number of days between the time of purchase and delivery. The ‘estimated actual delivery difference’ column gives us the delay or the cut-down in the number of days required for the delivery." }, { "code": null, "e": 8017, "s": 7331, "text": "intermediate_time = final_dataframe['order_delivered_customer_date'].apply(lambda x: datetime.strptime(x, \"%Y-%m-%d %H:%M:%S\").date()) - final_dataframe['order_purchase_timestamp'].apply(lambda x: datetime.strptime(x, \"%Y-%m-%d %H:%M:%S\").date())final_dataframe['purchase-delivery difference'] = intermediate_time.apply(lambda x:x.days)intermediate_time = final_dataframe['order_estimated_delivery_date'].apply(lambda x: datetime.strptime(x, \"%Y-%m-%d %H:%M:%S\").date()) - final_dataframe['order_delivered_customer_date'].apply(lambda x: datetime.strptime(x, \"%Y-%m-%d %H:%M:%S\").date())final_dataframe['estimated-actual delivery difference'] = intermediate_time.apply(lambda x:x.days)" }, { "code": null, "e": 8354, "s": 8017, "text": "Let us now try to impute the other types of columns. For the categorical columns, we shall use the mode of that column and for numerical columns, we shall use the median of that column for imputation. For reviews comment and title, we use the term ‘indisponível’, which is the Portuguese translation for the English term ‘unavailable’." }, { "code": null, "e": 9355, "s": 8354, "text": "final_dataframe['product_category_name'].fillna(value=final_dataframe['product_category_name'].mode()[0], inplace=True)final_dataframe['product_name_lenght'].fillna(value=final_dataframe['product_name_lenght'].mode()[0], inplace=True)final_dataframe['product_description_lenght'].fillna(value=final_dataframe['product_description_lenght'].median(), inplace=True)final_dataframe['product_photos_qty'].fillna(value=final_dataframe['product_photos_qty'].mode()[0], inplace=True)final_dataframe['product_weight_g'].fillna(value=final_dataframe['product_weight_g'].mode()[0], inplace=True)final_dataframe['product_length_cm'].fillna(value=final_dataframe['product_length_cm'].mode()[0], inplace=True)final_dataframe['product_height_cm'].fillna(value=final_dataframe['product_height_cm'].mode()[0], inplace=True)final_dataframe['product_width_cm'].fillna(value=final_dataframe['product_width_cm'].mode()[0], inplace=True)final_dataframe['review_comment_message'].fillna(value='indisponível', inplace=True)" }, { "code": null, "e": 9614, "s": 9355, "text": "We aim to convert this case study into a binary classification task. For that, we need to create a new column that contains the labels. Values that are rated more than 3 are labelled as positive and those whose values are 3 or below are labelled as negative." }, { "code": null, "e": 9715, "s": 9614, "text": "final_dataframe['review_score'] = final_dataframe['review_score'].apply(lambda x: 1 if x > 3 else 0)" }, { "code": null, "e": 9934, "s": 9715, "text": "On plotting the pie chart showing the labels, we see that the positive class occupies 77.60% of the entire dataset; whereas the negative class only occupies 22.40%. This indicates that the entire dataset is imbalanced." }, { "code": null, "e": 10207, "s": 9934, "text": "Some columns contain only numerical data. This means that finding the basic statistics of these columns is one thing that we can try. Notice that there is a significant difference between the mean and median values for the ‘price’ and ‘product length description’ columns." }, { "code": null, "e": 10459, "s": 10207, "text": "Let us create a new column called ‘price category’ This column is used to categorize the goods as expensive, cheap and affordable based on their price. We have used the first, second and third quartiles as the conditions for creating these categories." }, { "code": null, "e": 10610, "s": 10459, "text": "final_dataframe['price_category'] = final_dataframe['price'].apply(lambda x:'expensive' if x>=139 else ('affordable' if x>=40 and x<139 else 'cheap'))" }, { "code": null, "e": 10951, "s": 10610, "text": "We are now finding the top 12 most popular product categories in terms of the frequency of purchase. The category ‘bed bath table’ is significantly more popular than most of the other categories. It is the only category whose sales have crossed 10000 units. The category in the 12th position- ‘garden tools’ only had around 3600 units sold." }, { "code": null, "e": 11310, "s": 10951, "text": "Sao Paulo, also shortened to ‘SP’ is by leaps and bounds the state with the highest customer base of this firm. It might be because this company’s headquarters is set up in Sao Paulo and more customers were informed about this website due to their heavy marketing strategy around this area. More than 40000 units were sold in Sao Paulo between 2016 and 2018." }, { "code": null, "e": 11599, "s": 11310, "text": "When we check the pricing per product category, we can see that the average cost of a product is the highest for the items belonging to the ‘computers’ category. The average cost is around 1150 real. The second-highest category has an average price of nearly half of the highest category." }, { "code": null, "e": 11879, "s": 11599, "text": "For this plot, we considered the overall average cost of an item. This means that it is the sum of the freight charges and the original cost of the item. We can see that the ordering of the plot hasn’t changed. It’s only that the average cost of each category that has increased." }, { "code": null, "e": 11993, "s": 11879, "text": "We are now finding the city which generates the highest revenue. The city named ‘Pianco’ generates is at the top." }, { "code": null, "e": 12181, "s": 11993, "text": "There are only two statuses visible here. Only 6 orders have been cancelled to date. It doesn’t make sense to analyze those products which have been cancelled. Thus, we shall delete them." }, { "code": null, "e": 12262, "s": 12181, "text": "final_dataframe = final_dataframe[final_dataframe['order_status'] != 'canceled']" }, { "code": null, "e": 12639, "s": 12262, "text": "The below-given scatter plot takes the price on the x-axis and the total time difference between delivery and purchase on the y-axis. It can be seen that as the time taken for delivery increases, the chances of being dissatisfied with the product increases significantly. The increase in the price of an item does not cause too much dissatisfaction if it is delivered on time." }, { "code": null, "e": 12808, "s": 12639, "text": "We are now creating a new column called ‘purchase delivery diff per price’, which is the time difference between the purchase and delivery of a product given the price." }, { "code": null, "e": 12935, "s": 12808, "text": "final_dataframe['purchase_delivery_diff_per_price'] = final_dataframe['purchase-delivery difference']/final_dataframe['price']" }, { "code": null, "e": 13125, "s": 12935, "text": "The scatter plot between the freight cost and item cost very much descriptive. But it can be said that even if the freight cost is high, customers were satisfied when the item cost is less." }, { "code": null, "e": 13463, "s": 13125, "text": "Credit cards are the most popular mode of payment amongst customers. They are much more popular than the other alternatives. The second in line, Boletos, are a type of voucher that can only be found in Brazil. From this plot, we could see that the bad reviews given to a product were most probably not because of a payment related issue." }, { "code": null, "e": 13599, "s": 13463, "text": "Now it’s time to drop all the columns which aren’t necessary for the machine learning task. All the datetime columns should be removed." }, { "code": null, "e": 13823, "s": 13599, "text": "final_dataframe.drop(['shipping_limit_date','order_purchase_timestamp','order_approved_at','order_delivered_carrier_date','order_delivered_customer_date','order_estimated_delivery_date','customer_id'], axis=1, inplace=True)" }, { "code": null, "e": 13975, "s": 13823, "text": "We shall now create a new variable called ‘labels’ which contain the edited class polarity. This column should be removed from the original data frame." }, { "code": null, "e": 14074, "s": 13975, "text": "labels = final_dataframe['review_score']final_dataframe.drop('review_score', axis=1, inplace=True)" }, { "code": null, "e": 14389, "s": 14074, "text": "The ‘review availability’ column indicates whether the review of a particular item is available or not. Including this column is better than including a bunch of zeros in the ‘review comment message’ because it avoids sparsity. The problem with sparsity is that it can severely reduce the performance of any model." }, { "code": null, "e": 14522, "s": 14389, "text": "final_dataframe['review_availability'] = final_dataframe['review_comment_message'].apply(lambda x: 1 if x != 'indisponível' else 0)" }, { "code": null, "e": 15035, "s": 14522, "text": "For machine learning, we need to define a train set for training the data and a test set for predicting. Both these sets contain both the classes in equal proportion. Since the dataset is imbalanced, there is a chance that the distribution of these labels could heavily affect the performance of any machine learning model. So, we need to see to it that both the test and train sets contain positive and negative labels in the same proportion. And for reproducibility of the results, we need to add a seed value." }, { "code": null, "e": 15160, "s": 15035, "text": "X_train, X_test, y_train, y_test = train_test_split(final_dataframe, labels, stratify=labels, test_size=0.2, random_state=0)" }, { "code": null, "e": 15857, "s": 15160, "text": "Some columns contain multiple categories. The encoding technique which we normally think about is either one-hot encoding or ordinal encoding. The problem of sparsity arises when we use the one-hot encoding technique because there are too many categories. Ordinal encoding cannot be used unless ordinality is present in the categories. One way to tackle this situation is by using response coding. In this technique, we add the probability of occurrence of all the categories with each label. This means that each category will have two probability values- one for the positive class and another for the negative class. Overall, two distinct columns are being created for each categorical column." }, { "code": null, "e": 17376, "s": 15857, "text": "def train_response(frame): f1 = frame[frame.iloc[:,1] == 0] f2 = frame[frame.iloc[:,1] == 1] global dict_frame, dict_f1, dict_f2 dict_frame = dict(frame.iloc[:,0].value_counts()) dict_f1 = dict(f1.iloc[:,0].value_counts()) dict_f2 = dict(f2.iloc[:,0].value_counts()) state_0, state_1 = [],[], for i in range(len(frame)): if frame.iloc[:,1][i] == 0: state_0.append(dict_f1.get(frame.iloc[:,0][i],0) / dict_frame[frame.iloc[:,0][i]]) state_1.append(float(1-state_0[-1])) else: state_1.append(dict_f2.get(frame.iloc[:,0][i],0) / dict_frame[frame.iloc[:,0][i]]) state_0.append(float(1-state_1[-1])) df3 = pd.DataFrame({'State_0':state_0, 'State_1':state_1}) return df3.to_numpy()def test_response(test): t_state_0, t_state_1 = [],[] for i in range(len(test)): if dict_frame.get(test[i]): t_state_0.append(dict_f1.get(test[i],0) / dict_frame.get(test[i])) t_state_1.append(dict_f2.get(test[i],0) / dict_frame.get(test[i])) else: t_state_0.append(0.5) t_state_1.append(0.5) df4 = pd.DataFrame({'State_0':t_state_0, 'State_1':t_state_1}) return df4.to_numpy()def test_response(test): t_state_0, t_state_1 = [],[] for i in range(len(test)): if dict_frame.get(test[i]): t_state_0.append(dict_f1.get(test[i],0)/dict_frame.get(test[i])) t_state_1.append(dict_f2.get(test[i],0)/dict_frame.get(test[i])) else: t_state_0.append(0.5) t_state_1.append(0.5) df4 = pd.DataFrame({'State_0':t_state_0, 'State_1':t_state_1}) return df4.to_numpy()" }, { "code": null, "e": 17794, "s": 17376, "text": "We shall encode the categorical features which contain fewer categories using either ordinal or one hot encoding and encode them using response coding if there are too many categories. There is no need to encode the numerical features. Note that we aren’t considering all the columns present in the data frame. Only those are encoded which we deem as necessary. The encoding pattern per category is mentioned below: -" }, { "code": null, "e": 18608, "s": 17794, "text": "Next, we shall look at text data. One of the best ways to handle text data is to convert them into word embeddings. Word embeddings are better than TF-IDF vectors and Bag-of-words because they carry the semantic meaning of words. We shall be using FastText as the word embedding technique in this case study. It would’ve been possible to transform these words into TF-IDF vectors and later reduce the dimensionality using techniques such as Latent semantic analysis. This approach is faster, but the problem is that the dense vectors which we derive using this technique do to contain the semantic representation of these words. This approach would then reduce the accuracy of our models. Before vectorizing the text, we need to clean it. First, we shall remove the stop words and clean the remaining using regex." }, { "code": null, "e": 19309, "s": 18608, "text": "sp = spacy.load('pt')all_stopwords = sp.Defaults.stop_wordsdef process_texts(texts):processed_text = [] dates = '^([0]?[1-9]|[1|2][0-9]|[3][0|1])[./-]([0]?[1-9]|[1][0-2])[./-]([0-9]{4}|[0-9]{2})$' for text in texts: text = re.sub(r'\\r\\n|\\r|\\n', ' ', text) text = re.sub(r'^https?:\\/\\/.*[\\r\\n]*', ' ', text) text = re.sub(dates, ' ', text) text = re.sub('[ \\t]+$', '', text) text = re.sub('\\W', ' ', text) text = re.sub('[0-9]+', ' ', text) text = re.sub('\\s+', ' ', text) text = ' '.join(e for e in text.split() if e.lower() not in all_stopwords) processed_text.append(text.lower().strip()) return processed_text" }, { "code": null, "e": 19590, "s": 19309, "text": "We still haven’t brought all the numerical features into the same scale. For this, we shall be using standardization. We are using standardization instead of normalization because as seen in the description of the basic statistics, there are many outliers present in this dataset." }, { "code": null, "e": 20476, "s": 19590, "text": "strn = StandardScaler()strn.fit(X_train[['price','freight_value','product_photos_qty','product_weight_g', 'product_length_cm', 'product_height_cm', 'product_width_cm', 'payment_value','purchase-delivery difference','estimated-actual delivery difference','purchase_delivery_diff_per_price']])X_train_strn = strn.transform(X_train[['price','freight_value','product_photos_qty','product_weight_g', 'product_length_cm', 'product_height_cm', 'product_width_cm', 'payment_value','purchase-delivery difference','estimated-actual delivery difference','purchase_delivery_diff_per_price']])X_test_strn = strn.transform(X_test[['price','freight_value','product_photos_qty','product_weight_g', 'product_length_cm', 'product_height_cm', 'product_width_cm', 'payment_value','purchase-delivery difference','estimated-actual delivery difference','purchase_delivery_diff_per_price']])" }, { "code": null, "e": 20638, "s": 20476, "text": "It is now time to concatenate all the necessary features together and check the shape of the final dataframe. It can be seen that there are 332 features overall." }, { "code": null, "e": 22615, "s": 20638, "text": "We shall try to reduce this dimensionality using two techniques. One is by finding the hard threshold using singular value decomposition and the other is by using autoencoders. Singular value decomposition is a widely used matrix factorization technique that can be applied to matrices of any dimension. It converts the given matrix into a set of three matrices, named as U, Σ and V* respectively. Note that the symbol ‘*’ is used to indicate the transpose operator. The singular values of any matrix A of dimensionality MxN are the square roots of the eigenvalues of the square matrix A*A of dimensionality NxN. Here, Σ is a diagonal matrix that contains the singular values as its elements along the diagonal. The rows of U and the columns V* matrices which correspond to the diagonal elements of Σ are known as the left and right singular vectors. Remember that we are taking the transpose of the matrix V by default. Let us explain singular values using a geometric intuition. As we already know, a matrix of dimensionality MxN is a linear transformation from the real space RN into the real space RM, mathematically notated as RN→ RM. SVD is a way to decompose this direct transformation into a set of three transformations, which are- first rotation, scaling and second rotation. Now consider a unit circle with two vectors given in yellow and magenta colours. Here we are considering a transformation from R2 to R2. So, both M and N are equal to 2 in this example. After transformation, this circle changes into an ellipse which has been rotated. This overall transformation can be broken into 3 steps as mentioned in the diagram. After the first rotation(applying V*), the circle rotates through an angle. Then the Σ matrix scales the axis of this figure. The scaling of each axis is proportional to the magnitude of the singular vectors. Note that our two vectors would change in magnitude. After the second rotation(applying U), the ellipse gets rotated by an angle." }, { "code": null, "e": 23832, "s": 22615, "text": "Rank reduction is a technique by which high-dimensional noisy data can be transformed into low-dimensional cleaner data. The rank defines a threshold value that we could consider for truncating the U matrix which we had obtained using SVD. Researchers used to take a heuristic approach for finding an optimal rank. The problem with the approach was that they were unsure whether the truncated matrix obtained using this rank contained sufficient information to reconstruct the clean image. Another approach would be to use trial-and-error, which is time-consuming. In a recent paper, a technique named optimal singular valued hard threshold was mentioned which laid the theoretical foundation of finding the optimal threshold value for truncation. We are required to find a threshold value τ*, which is the optimal threshold. The ‘*’ symbol used in this formula does not indicate transpose. The formula depends on whether the value of noise added to the image is known and whether the matrix is square or not. This noise is assumed to have a mean value of 0 and a standard deviation of 1. It is very unlikely that the matrix is square and the noise is known. But if these two conditions are fulfilled, the formula is" }, { "code": null, "e": 24003, "s": 23832, "text": "Here, ’n’ is the dimensionality of the square matrix and ‘σ’ is the noise. Under most circumstances, we don’t know the amount of noise that has been added. The formula is" }, { "code": null, "e": 24407, "s": 24003, "text": "Here, β=n/m and ymed is the median of all the singular values. Note that the value of ω(β) which we have used here is just an approximation. Their actual value could also be calculated, but it would require further processing. Since we are using this rank reduction technique in SVD only for dimensionality reduction purposes and not for image denoising, finding the exact value of ω(β) isn’t important." }, { "code": null, "e": 24817, "s": 24407, "text": "X_final_sparse = scipy.sparse.csr_matrix(np.vstack((X_train_final,X_test_final)))U, sigma, VT = randomized_svd(X_final_sparse, n_components=min(X_final_sparse.shape[0],X_final_sparse.shape[1])-1,n_iter=5,random_state=45)beta = min(X_final_sparse.shape) / max(X_final_sparse.shape)omega_approx = 0.56*beta**3 - 0.95*beta**2 + 1.82*beta + 1.43tau = np.median(sigma)*omega_approxk = np.max(np.where(sigma>tau))+1" }, { "code": null, "e": 24985, "s": 24817, "text": "It can be seen that the newly formed matrix has 116 features, which preserves most of the variance. After this, we split the truncated matrix into train and test sets." }, { "code": null, "e": 26137, "s": 24985, "text": "It is possible to reduce the dimensionality using neural networks. We shall be using autoencoders, a type of neural networks to encode the data efficiently. Note that autoencoders fall under unsupervised learning. In the autoencoder architecture, the size of the input and output layers are the same. The size of the hidden layers will always be lesser than the size of the external layers. The size of each consecutive hidden layer keeps on reducing till it reaches the bottleneck layer; beyond which the size keeps on increasing. Note that the architecture is symmetrical. The part which compresses the data is known as the encoder and the part which decompresses it is known as the decoder. The encoder extends from the input towards the bottleneck layer and from there on the decoder extends till the end. The bottleneck layer should have the dimensionality which we require for our data to be encoded into. An autoencoder aims to minimize the reconstruction error. The input gets compressed at the bottleneck layer and then gets decompressed at the output layer. The training converges after the error between the input and output gets minimized." }, { "code": null, "e": 26456, "s": 26137, "text": "In our architecture, we are using the dimensionality of 116 at the bottleneck layer. Only two hidden layers are being used on each side of the network. After the training converges, we need to drop the decoder part and use the encoder part to transform both our training and test sets into the required dimensionality." }, { "code": null, "e": 26999, "s": 26456, "text": "Now that we have created two versions of the data using two different dimensionality reduction techniques, we shall try to model the data using various machine learning and deep learning algorithms and then try to compare their performance using different metrics. We plan to apply five different algorithms to each of them. These algorithms are- K-nearest neighbours(KNN), logistic regression, random forests, xgboost and multi-layered perceptrons(MLP). We shall apply each of them on one form of data and then all of them on the other form." }, { "code": null, "e": 27441, "s": 26999, "text": "The hyperparameter used in the case of KNN is the count of the nearest neighbours(K) whose values are odd numbers ranging from 1 to 9. The performance is said to be the best when the value of K is 3. The validation macro F1 score is 0.8587 and it isn’t great. By checking the test confusion matrices, we can see that the count of the false positive points is greater than the count of the false negative points. This isn’t a good classifier." }, { "code": null, "e": 27928, "s": 27441, "text": "The hyperparameters used in the case of logistic regression is the inverse regularization constant(C) whose values are the powers of 10 that range from 1e-7 to 1e-3. This model performs the best when the value of C is 1e-5. The validation macro F1 score is 0.9003 and it is good. Unfortunately, we can see that the count of the false positive points is greater than the count of the true negative points when we plot the confusion matrices of the test set. This isn’t a good classifier." }, { "code": null, "e": 28381, "s": 27928, "text": "The hyperparameters used in random forest is the count of the base estimators, which in this case are decision trees. Six values are chosen between 50 and 210 as the number of estimators, where the limits are inclusive in the set. There is a difference of 30 between any two consecutive values. The validation macro F1 score is 0.9161 and it is great. The count of true negatives is greater than the count of false positives. This is a good classifier." }, { "code": null, "e": 28788, "s": 28381, "text": "The hyperparameters used in xgboost is the count of the base estimators, which also in this case are decision trees. Six values are chosen between 50 and 210 as the number of estimators, where the limits are inclusive in the set as mentioned above. The validation macro F1 score is 0.9191 and it is great. The count of true negatives is greater than the count of false positives. This is a good classifier." }, { "code": null, "e": 29092, "s": 28788, "text": "Now we shall use multi-layered perceptrons for classification. The optimizer used in this case is Adam and the learning rate is 1e-3. The validation macro F1 score is 0.9074 and it is good. The count of true negatives is greater than the count of false positives in this case. This is a good classifier." }, { "code": null, "e": 29228, "s": 29092, "text": "From what we’ve seen till now, random forest, Xgboost and mlp can properly classify the points. Xgboost performs the best amongst them." }, { "code": null, "e": 29670, "s": 29228, "text": "The hyperparameter used in the case of KNN is the count of the nearest neighbours(K) whose values are odd numbers ranging from 1 to 9. The performance is said to be the best when the value of K is 3. The validation macro F1 score is 0.8564 and it isn’t great. By checking the test confusion matrices, we can see that the count of the false positive points is greater than the count of the false negative points. This isn’t a good classifier." }, { "code": null, "e": 30138, "s": 29670, "text": "The hyperparameters used in the case of logistic regression is the inverse regularization constant(C) whose values are the powers of 10 that range from 1e-7 to 1e-3. This model performs the best when the value of C is 1e-2. The validation macro F1 score is 0.8874 and it is okay. We can see that the count of the false positive points is greater than the count of the true negative points when we plot the confusion matrices of the test set. This is a bad classifier." }, { "code": null, "e": 30603, "s": 30138, "text": "The hyperparameters used in random forest is the count of the base estimators, which in this case are decision trees. Six values are chosen between 50 and 210 as the number of estimators, where the limits are inclusive in the set. There is a difference of 30 between any two consecutive values. The validation macro F1 score is 0.8895 and it is good. Unfortunately, the count of true negatives is lesser than the count of false positives. This is a bad classifier." }, { "code": null, "e": 31022, "s": 30603, "text": "The hyperparameters used in xgboost is the count of the base estimators, which also in this case are decision trees. Six values are chosen between 50 and 210 as the number of estimators, where the limits are inclusive in the set as mentioned above. The validation macro F1 score is 0.8867 and it is okay. Unfortunately, the count of true negatives is lesser than the count of false positives. This is a bad classifier." }, { "code": null, "e": 31323, "s": 31022, "text": "Now we shall use multi-layered perceptron for classification. The optimizer used in this case is Adam and the learning rate is 1e-3. The validation macro F1 score is 0.8924 and it is okay. The count of true negatives is lesser than the count of false positives in this case. This is a bad classifier." }, { "code": null, "e": 31453, "s": 31323, "text": "From what we have here, it is observable that we cannot design a good classifier using the dataset compressed using autoencoders." }, { "code": null, "e": 31726, "s": 31453, "text": "We still haven’t tried feeding the tokenized reviews directly as input to the models. For this to happen, we are required to operate on the entire dataset rather than the truncated or compressed version of the same. For this purpose, we shall try two deep learning models." }, { "code": null, "e": 32561, "s": 31726, "text": "In the initial model, we shall try using Long short term memory(LSTM) only. We are creating two different inputs for this model. The first input is for numerical data and the other is for text data. An embedding layer converts the tokenized input into a fixed-length vector. We are training the embedding layer using FastText. Thus, the tokenized and padded text is converted into word embeddings using this layer. The next layer on this path is LSTM. This layer is capable of learning the order dependence when given a sequence. The next layer is directly fed to the dense layers. Both these inputs later get combined and there is a sigmoid activation function at the output. The validation macro F1 score is 0.9211 and it is great. The count of true negatives is greater than the count of false positives. This is a good classifier." }, { "code": null, "e": 33006, "s": 32561, "text": "In the next model, we are planning to use 1-dimensional convolutional neural networks along with LSTM. Here we are using two pairs of 1-D CNN and LSTM layers consecutively before combining it with the numerical data. Here also, we are using sigmoid as the activation function at the end. The validation macro F1 score is 0.9010 and it is good. The count of true negatives is greater than the count of false positives. This is a good classifier." }, { "code": null, "e": 33170, "s": 33006, "text": "When we check the summarized tables, we can see that both dual input LSTM and xgboost on data truncated using hard threshold SVD perform the best on the test data." }, { "code": null, "e": 33405, "s": 33170, "text": "We could convert this problem into a multi-class classification problem and check the rating predict. This is a metric called log loss which could also be used as an alternative. There is also the possibility of using other ensembles." }, { "code": null, "e": 33510, "s": 33405, "text": "Screenshot of the deployment is mentioned given below. A video recording of the same can be viewed here." }, { "code": null, "e": 33701, "s": 33510, "text": "LinkedIn: https://www.linkedin.com/in/ashwin-michael-10b617142/Github repository: https://github.com/Ashcom-git/case-study-1Kaggle dataset: https://www.kaggle.com/olistbr/brazilian-ecommerce" } ]
Add a vertical slider with matplotlib - GeeksforGeeks
17 May, 2021 Matplotlib not only allows static graphs, but we can also prepare plots that can be modified interactively. For this, we can use the Sliders widget present in the widgets submodule to control the visual properties of your plot. The only difference between horizontal and vertical Sliders being the presence of an additional parameter ‘orientation’ which is by default set to ‘horizontal’. amp_slider = Slider( ax=axamp, label=”Amplitude”, valmin=0, valmax=10, valinit=init_amplitude, orientation=”vertical” # Update it to “horizontal” if you need a horizontal graph ) Example: Here we will use the Slider widget to create a plot of a function with a scroll bar that can be used to modify the plot. In this example, two sliders (one vertical and one horizontal )are being used to choose the amplitude and frequencies of a sine wave. We can control many continuously-varying properties of our plot in this way. Python import numpy as npimport matplotlib.pyplot as pltfrom matplotlib.widgets import Slider, Button # The parameterized function to be plotteddef f(t, amplitude, frequency): return amplitude * np.sin(2 * np.pi * frequency * t) t = np.linspace(0, 1, 1000) # Defining the initial parametersinit_amplitude = 5init_frequency = 3 # Creating the figure and the graph line that we will updatefig, ax = plt.subplots()line, = plt.plot(t, f(t, init_amplitude, init_frequency), lw=2)ax.set_xlabel('Time [s]') axcolor = 'lightgoldenrodyellow'ax.margins(x=0) # adjusting the main plot to make space for our slidersplt.subplots_adjust(left=0.25, bottom=0.25) # Making a horizontally oriented slider to# control the frequency.axfreq = plt.axes([0.25, 0.1, 0.65, 0.03], facecolor=axcolor)freq_slider = Slider( ax=axfreq, label='Frequency [Hz]', valmin=0.1, valmax=30, valinit=init_frequency, # orientation="horizontal" is Default) # Making a vertically oriented slider to control the amplitudeaxamp = plt.axes([0.1, 0.25, 0.0225, 0.63], facecolor=axcolor)amp_slider = Slider( ax=axamp, label="Amplitude", valmin=0, valmax=10, valinit=init_amplitude, orientation="vertical") # Function to be rendered anytime a slider's value changesdef update(val): line.set_ydata(f(t, amp_slider.val, freq_slider.val)) fig.canvas.draw_idle() # Registering the update function with each slider Updatefreq_slider.on_changed(update)amp_slider.on_changed(update) # Create a `matplotlib.widgets.Button` to reset# the sliders to initial parameters.resetax = plt.axes([0.8, 0.025, 0.1, 0.04])button = Button(resetax, 'Reset', color=axcolor, hovercolor='0.975') def reset(event): freq_slider.reset() amp_slider.reset() button.on_clicked(reset) plt.show() Output : Continuously-varying properties like Amplitude and Frequency of a Sine Wve could be controlled using Sliders effectively : As we can observe from example images the plot can be modified during runtime by using the Sliders submodule present in Matplotlib. Therefore, the only difference between the horizontal and vertical Sliders is the presence of an additional parameter ‘orientation’ which is by default set to ‘horizontal’ and there is no difference in implementation of the orientation you want. gabaa406 Picked Python-matplotlib Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? How To Convert Python Dictionary To JSON? Check if element exists in list in Python How to drop one or multiple columns in Pandas Dataframe Python Classes and Objects Python | os.path.join() method Create a directory in Python Python | Get unique values from a list Python | Pandas dataframe.groupby() Defaultdict in Python
[ { "code": null, "e": 25555, "s": 25527, "text": "\n17 May, 2021" }, { "code": null, "e": 25784, "s": 25555, "text": "Matplotlib not only allows static graphs, but we can also prepare plots that can be modified interactively. For this, we can use the Sliders widget present in the widgets submodule to control the visual properties of your plot." }, { "code": null, "e": 25945, "s": 25784, "text": "The only difference between horizontal and vertical Sliders being the presence of an additional parameter ‘orientation’ which is by default set to ‘horizontal’." }, { "code": null, "e": 25966, "s": 25945, "text": "amp_slider = Slider(" }, { "code": null, "e": 25979, "s": 25966, "text": " ax=axamp," }, { "code": null, "e": 26001, "s": 25979, "text": " label=”Amplitude”," }, { "code": null, "e": 26014, "s": 26001, "text": " valmin=0," }, { "code": null, "e": 26028, "s": 26014, "text": " valmax=10," }, { "code": null, "e": 26055, "s": 26028, "text": " valinit=init_amplitude," }, { "code": null, "e": 26140, "s": 26055, "text": " orientation=”vertical” # Update it to “horizontal” if you need a horizontal graph" }, { "code": null, "e": 26142, "s": 26140, "text": ")" }, { "code": null, "e": 26151, "s": 26142, "text": "Example:" }, { "code": null, "e": 26483, "s": 26151, "text": "Here we will use the Slider widget to create a plot of a function with a scroll bar that can be used to modify the plot. In this example, two sliders (one vertical and one horizontal )are being used to choose the amplitude and frequencies of a sine wave. We can control many continuously-varying properties of our plot in this way." }, { "code": null, "e": 26490, "s": 26483, "text": "Python" }, { "code": "import numpy as npimport matplotlib.pyplot as pltfrom matplotlib.widgets import Slider, Button # The parameterized function to be plotteddef f(t, amplitude, frequency): return amplitude * np.sin(2 * np.pi * frequency * t) t = np.linspace(0, 1, 1000) # Defining the initial parametersinit_amplitude = 5init_frequency = 3 # Creating the figure and the graph line that we will updatefig, ax = plt.subplots()line, = plt.plot(t, f(t, init_amplitude, init_frequency), lw=2)ax.set_xlabel('Time [s]') axcolor = 'lightgoldenrodyellow'ax.margins(x=0) # adjusting the main plot to make space for our slidersplt.subplots_adjust(left=0.25, bottom=0.25) # Making a horizontally oriented slider to# control the frequency.axfreq = plt.axes([0.25, 0.1, 0.65, 0.03], facecolor=axcolor)freq_slider = Slider( ax=axfreq, label='Frequency [Hz]', valmin=0.1, valmax=30, valinit=init_frequency, # orientation=\"horizontal\" is Default) # Making a vertically oriented slider to control the amplitudeaxamp = plt.axes([0.1, 0.25, 0.0225, 0.63], facecolor=axcolor)amp_slider = Slider( ax=axamp, label=\"Amplitude\", valmin=0, valmax=10, valinit=init_amplitude, orientation=\"vertical\") # Function to be rendered anytime a slider's value changesdef update(val): line.set_ydata(f(t, amp_slider.val, freq_slider.val)) fig.canvas.draw_idle() # Registering the update function with each slider Updatefreq_slider.on_changed(update)amp_slider.on_changed(update) # Create a `matplotlib.widgets.Button` to reset# the sliders to initial parameters.resetax = plt.axes([0.8, 0.025, 0.1, 0.04])button = Button(resetax, 'Reset', color=axcolor, hovercolor='0.975') def reset(event): freq_slider.reset() amp_slider.reset() button.on_clicked(reset) plt.show()", "e": 28251, "s": 26490, "text": null }, { "code": null, "e": 28260, "s": 28251, "text": "Output :" }, { "code": null, "e": 28383, "s": 28260, "text": "Continuously-varying properties like Amplitude and Frequency of a Sine Wve could be controlled using Sliders effectively :" }, { "code": null, "e": 28517, "s": 28383, "text": " As we can observe from example images the plot can be modified during runtime by using the Sliders submodule present in Matplotlib." }, { "code": null, "e": 28763, "s": 28517, "text": "Therefore, the only difference between the horizontal and vertical Sliders is the presence of an additional parameter ‘orientation’ which is by default set to ‘horizontal’ and there is no difference in implementation of the orientation you want." }, { "code": null, "e": 28772, "s": 28763, "text": "gabaa406" }, { "code": null, "e": 28779, "s": 28772, "text": "Picked" }, { "code": null, "e": 28797, "s": 28779, "text": "Python-matplotlib" }, { "code": null, "e": 28804, "s": 28797, "text": "Python" }, { "code": null, "e": 28902, "s": 28804, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28934, "s": 28902, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28976, "s": 28934, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 29018, "s": 28976, "text": "Check if element exists in list in Python" }, { "code": null, "e": 29074, "s": 29018, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 29101, "s": 29074, "text": "Python Classes and Objects" }, { "code": null, "e": 29132, "s": 29101, "text": "Python | os.path.join() method" }, { "code": null, "e": 29161, "s": 29132, "text": "Create a directory in Python" }, { "code": null, "e": 29200, "s": 29161, "text": "Python | Get unique values from a list" }, { "code": null, "e": 29236, "s": 29200, "text": "Python | Pandas dataframe.groupby()" } ]
Compute the value of Quantile Function over F Distribution in R Programming - qf() Function - GeeksforGeeks
25 Jun, 2020 qf() function in R Language is used to compute the value of quantile function over F distribution for a sequence of numeric values. It also creates a density plot of quantile function over F Distribution. Syntax: qf(x, df1, df2) Parameters:x: Numeric Vectordf: Degree of Freedom Example 1: # R Program to compute value of# Quantile Function over F Distribution # Creating a sequence of x-valuesx <- seq(0, 1, by = 0.2) # Calling qf() Functiony <- qf(x, df1 = 2, df2 = 3)y Output: [1] 0.0000000 0.2405958 0.6085817 1.2630236 2.8860266 Inf Example 2: # R Program to compute the value of# Quantile Function over F Distribution # Creating a sequence of x-valuesx <- seq(0, 1, by = 0.02) # Calling qf() Functiony <- qf(x, df1 = 2, df2 = 3) # Plot a graphplot(y) Output: R Statistics-Function R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Filter data by multiple conditions in R using Dplyr Loops in R (for, while, repeat) Change Color of Bars in Barchart using ggplot2 in R How to change Row Names of DataFrame in R ? Remove rows with NA in one column of R DataFrame 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? K-Means Clustering in R Programming Logistic Regression in R Programming
[ { "code": null, "e": 24972, "s": 24944, "text": "\n25 Jun, 2020" }, { "code": null, "e": 25177, "s": 24972, "text": "qf() function in R Language is used to compute the value of quantile function over F distribution for a sequence of numeric values. It also creates a density plot of quantile function over F Distribution." }, { "code": null, "e": 25201, "s": 25177, "text": "Syntax: qf(x, df1, df2)" }, { "code": null, "e": 25251, "s": 25201, "text": "Parameters:x: Numeric Vectordf: Degree of Freedom" }, { "code": null, "e": 25262, "s": 25251, "text": "Example 1:" }, { "code": "# R Program to compute value of# Quantile Function over F Distribution # Creating a sequence of x-valuesx <- seq(0, 1, by = 0.2) # Calling qf() Functiony <- qf(x, df1 = 2, df2 = 3)y", "e": 25446, "s": 25262, "text": null }, { "code": null, "e": 25454, "s": 25446, "text": "Output:" }, { "code": null, "e": 25519, "s": 25454, "text": "[1] 0.0000000 0.2405958 0.6085817 1.2630236 2.8860266 Inf\n" }, { "code": null, "e": 25530, "s": 25519, "text": "Example 2:" }, { "code": "# R Program to compute the value of# Quantile Function over F Distribution # Creating a sequence of x-valuesx <- seq(0, 1, by = 0.02) # Calling qf() Functiony <- qf(x, df1 = 2, df2 = 3) # Plot a graphplot(y)", "e": 25741, "s": 25530, "text": null }, { "code": null, "e": 25749, "s": 25741, "text": "Output:" }, { "code": null, "e": 25771, "s": 25749, "text": "R Statistics-Function" }, { "code": null, "e": 25782, "s": 25771, "text": "R Language" }, { "code": null, "e": 25880, "s": 25782, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25889, "s": 25880, "text": "Comments" }, { "code": null, "e": 25902, "s": 25889, "text": "Old Comments" }, { "code": null, "e": 25954, "s": 25902, "text": "Filter data by multiple conditions in R using Dplyr" }, { "code": null, "e": 25986, "s": 25954, "text": "Loops in R (for, while, repeat)" }, { "code": null, "e": 26038, "s": 25986, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 26082, "s": 26038, "text": "How to change Row Names of DataFrame in R ?" }, { "code": null, "e": 26131, "s": 26082, "text": "Remove rows with NA in one column of R DataFrame" }, { "code": null, "e": 26169, "s": 26131, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 26204, "s": 26169, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 26262, "s": 26204, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 26298, "s": 26262, "text": "K-Means Clustering in R Programming" } ]
Program to check if matrix is singular or not
05 Jul, 2021 A matrix is said to be singular if the determinant of the matrix is 0 otherwise it is non-singular .Examples: Input : 0 0 0 4 5 6 1 2 3 Output : Yes Determinant value of the matrix is 0 (Note first row is 0) Input : 1 0 0 4 5 6 1 2 3 Output : No Determinant value of the matrix is 3 (which is non-zero). First find the determinant of the matrix and the check the condition if the determinant id 0 or not, if it is 0 then matrix is a singular matrix otherwise it is a non-singular matrix . C++ Java Python3 C# Javascript // C++ program check if a matrix is// singular or not.#include <bits/stdc++.h>using namespace std;#define N 4 // Function to get cofactor of mat[p][q] in temp[][].// n is current dimension of mat[][]void 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++; } } } }} /* Recursive function to check if mat[][] is singular or not. */bool isSingular(int mat[N][N], int n){ int D = 0; // Initialize result // Base case : if matrix contains single element if (n == 1) return mat[0][0]; int temp[N][N]; // To store cofactors int sign = 1; // To store sign multiplier // 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] * isSingular(temp, n - 1); // terms are to be added with alternate sign sign = -sign; } return D;} // Driver program to test above functionsint main(){ int mat[N][N] = { { 4, 10, 1 }, { 0, 0, 0 }, { 1, 4, -3 } }; if (isSingular(mat, N)) cout << "Matrix is Singular" << endl; else cout << "Matrix is non-singular" << endl; return 0;} // Java program check if a matrix is// singular or not.class GFG{ static final int N = 3; // Function to get cofactor of mat[p][q] in temp[][]. // n is current dimension of mat[][] 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++; } } } } } /* Recursive function to check if mat[][] is singular or not. */ static int isSingular(int mat[][], int n) { int D = 0; // Initialize result // Base case : if matrix contains single element if (n == 1) { return mat[0][0]; } int temp[][] = new int[N][N]; // To store cofactors int sign = 1; // To store sign multiplier // 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] * isSingular(temp, n - 1); // terms are to be added with alternate sign sign = -sign; } return D; } // Driver code public static void main(String[] args) { int mat[][] = {{4, 10, 1}, {0, 0, 0}, {1, 4, -3}}; if (isSingular(mat, N) == 1) { System.out.println("Matrix is Singular"); } else { System.out.println("Matrix is non-singular"); } }} /* This code contributed by PrinciRaj1992 */ # python 3 program check if a matrix is# singular or not.global NN = 3 # Function to get cofactor of mat[p][q] in temp[][].# n is current dimension of mat[][]def getCofactor(mat,temp,p,q,n): i = 0 j = 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 # Recursive function to check if mat[][] is# singular or not. */def isSingular(mat,n): D = 0 # Initialize result # Base case : if matrix contains single element if (n == 1): return mat[0][0] temp = [[0 for i in range(N + 1)] for i in range(N + 1)]# To store cofactors sign = 1 # To store sign multiplier # 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] * isSingular(temp, n - 1) # terms are to be added with alternate sign sign = -sign return D # Driver program to test above functionsif __name__ == '__main__': mat = [[4, 10, 1],[0, 0, 0],[1, 4, -3]] if (isSingular(mat, N)): print("Matrix is Singular") else: print("Matrix is non-singular") # This code is contributed by# Surendra_Gangwar // C# program check if a matrix is// singular or not.using System; class GFG{ static readonly int N = 3; // Function to get cofactor of mat[p,q] in temp[,]. // n is current dimension of mat[,] 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++; } } } } } /* Recursive function to check if mat[,] is singular or not. */ static int isSingular(int [,]mat, int n) { int D = 0; // Initialize result // Base case : if matrix contains single element if (n == 1) { return mat[0, 0]; } int [,]temp = new int[N, N]; // To store cofactors int sign = 1; // To store sign multiplier // 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] * isSingular(temp, n - 1); // terms are to be added with alternate sign sign = -sign; } return D; } // Driver code public static void Main(String[] args) { int [,]mat = {{4, 10, 1}, {0, 0, 0}, {1, 4, -3}}; if (isSingular(mat, N) == 1) { Console.WriteLine("Matrix is Singular"); } else { Console.WriteLine("Matrix is non-singular"); } }} // This code contributed by Rajput-Ji <script> // Javascript program check if a matrix is// singular or not.var N = 3;// Function to get cofactor of mat[p,q] in temp[,].// n is current dimension of mat[,]function getCofactor(mat, temp, p, q, n){ var i = 0, j = 0; // Looping for each element of the matrix for (var row = 0; row < n; row++) { for (var 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++; } } } }}/* Recursive function to check if mat[,] issingular or not. */function isSingular(mat, n){ var D = 0; // Initialize result // Base case : if matrix contains single element if (n == 1) { return mat[0][0]; } var temp = Array.from(Array(N), ()=>Array(N));// To store cofactors var sign = 1; // To store sign multiplier // Iterate for each element of first row for(var f = 0; f < n; f++) { // Getting Cofactor of mat[0,f] getCofactor(mat, temp, 0, f, n); D += sign * mat[0][f] * isSingular(temp, n - 1); // terms are to be added with alternate sign sign = -sign; } return D;}// Driver codevar mat = [[4, 10, 1], [0, 0, 0], [1, 4, -3]];if (isSingular(mat, N) == 1){ document.write("Matrix is Singular");}else{ document.write("Matrix is non-singular");} // This code is contributed by noob2000.</script> Matrix is non-singular princiraj1992 Rajput-Ji SURENDRA_GANGWAR noob2000 Algebra Matrix Matrix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Unique paths in a Grid with Obstacles Find the longest path in a matrix with given constraints Find median in row wise sorted matrix Zigzag (or diagonal) traversal of Matrix A Boolean Matrix Question Traverse a given Matrix using Recursion Find a specific pair in Matrix Common elements in all rows of a given matrix Shortest distance between two cells in a matrix or grid Python program to add two Matrices
[ { "code": null, "e": 52, "s": 24, "text": "\n05 Jul, 2021" }, { "code": null, "e": 164, "s": 52, "text": "A matrix is said to be singular if the determinant of the matrix is 0 otherwise it is non-singular .Examples: " }, { "code": null, "e": 397, "s": 164, "text": "Input : 0 0 0\n 4 5 6\n 1 2 3\nOutput : Yes\nDeterminant value of the matrix is\n0 (Note first row is 0)\n\nInput : 1 0 0\n 4 5 6\n 1 2 3\nOutput : No\nDeterminant value of the matrix is 3\n(which is non-zero)." }, { "code": null, "e": 585, "s": 399, "text": "First find the determinant of the matrix and the check the condition if the determinant id 0 or not, if it is 0 then matrix is a singular matrix otherwise it is a non-singular matrix . " }, { "code": null, "e": 589, "s": 585, "text": "C++" }, { "code": null, "e": 594, "s": 589, "text": "Java" }, { "code": null, "e": 602, "s": 594, "text": "Python3" }, { "code": null, "e": 605, "s": 602, "text": "C#" }, { "code": null, "e": 616, "s": 605, "text": "Javascript" }, { "code": "// C++ program check if a matrix is// singular or not.#include <bits/stdc++.h>using namespace std;#define N 4 // Function to get cofactor of mat[p][q] in temp[][].// n is current dimension of mat[][]void 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++; } } } }} /* Recursive function to check if mat[][] is singular or not. */bool isSingular(int mat[N][N], int n){ int D = 0; // Initialize result // Base case : if matrix contains single element if (n == 1) return mat[0][0]; int temp[N][N]; // To store cofactors int sign = 1; // To store sign multiplier // 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] * isSingular(temp, n - 1); // terms are to be added with alternate sign sign = -sign; } return D;} // Driver program to test above functionsint main(){ int mat[N][N] = { { 4, 10, 1 }, { 0, 0, 0 }, { 1, 4, -3 } }; if (isSingular(mat, N)) cout << \"Matrix is Singular\" << endl; else cout << \"Matrix is non-singular\" << endl; return 0;}", "e": 2442, "s": 616, "text": null }, { "code": "// Java program check if a matrix is// singular or not.class GFG{ static final int N = 3; // Function to get cofactor of mat[p][q] in temp[][]. // n is current dimension of mat[][] 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++; } } } } } /* Recursive function to check if mat[][] is singular or not. */ static int isSingular(int mat[][], int n) { int D = 0; // Initialize result // Base case : if matrix contains single element if (n == 1) { return mat[0][0]; } int temp[][] = new int[N][N]; // To store cofactors int sign = 1; // To store sign multiplier // 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] * isSingular(temp, n - 1); // terms are to be added with alternate sign sign = -sign; } return D; } // Driver code public static void main(String[] args) { int mat[][] = {{4, 10, 1}, {0, 0, 0}, {1, 4, -3}}; if (isSingular(mat, N) == 1) { System.out.println(\"Matrix is Singular\"); } else { System.out.println(\"Matrix is non-singular\"); } }} /* This code contributed by PrinciRaj1992 */", "e": 4637, "s": 2442, "text": null }, { "code": "# python 3 program check if a matrix is# singular or not.global NN = 3 # Function to get cofactor of mat[p][q] in temp[][].# n is current dimension of mat[][]def getCofactor(mat,temp,p,q,n): i = 0 j = 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 # Recursive function to check if mat[][] is# singular or not. */def isSingular(mat,n): D = 0 # Initialize result # Base case : if matrix contains single element if (n == 1): return mat[0][0] temp = [[0 for i in range(N + 1)] for i in range(N + 1)]# To store cofactors sign = 1 # To store sign multiplier # 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] * isSingular(temp, n - 1) # terms are to be added with alternate sign sign = -sign return D # Driver program to test above functionsif __name__ == '__main__': mat = [[4, 10, 1],[0, 0, 0],[1, 4, -3]] if (isSingular(mat, N)): print(\"Matrix is Singular\") else: print(\"Matrix is non-singular\") # This code is contributed by# Surendra_Gangwar", "e": 6294, "s": 4637, "text": null }, { "code": "// C# program check if a matrix is// singular or not.using System; class GFG{ static readonly int N = 3; // Function to get cofactor of mat[p,q] in temp[,]. // n is current dimension of mat[,] 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++; } } } } } /* Recursive function to check if mat[,] is singular or not. */ static int isSingular(int [,]mat, int n) { int D = 0; // Initialize result // Base case : if matrix contains single element if (n == 1) { return mat[0, 0]; } int [,]temp = new int[N, N]; // To store cofactors int sign = 1; // To store sign multiplier // 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] * isSingular(temp, n - 1); // terms are to be added with alternate sign sign = -sign; } return D; } // Driver code public static void Main(String[] args) { int [,]mat = {{4, 10, 1}, {0, 0, 0}, {1, 4, -3}}; if (isSingular(mat, N) == 1) { Console.WriteLine(\"Matrix is Singular\"); } else { Console.WriteLine(\"Matrix is non-singular\"); } }} // This code contributed by Rajput-Ji", "e": 8483, "s": 6294, "text": null }, { "code": "<script> // Javascript program check if a matrix is// singular or not.var N = 3;// Function to get cofactor of mat[p,q] in temp[,].// n is current dimension of mat[,]function getCofactor(mat, temp, p, q, n){ var i = 0, j = 0; // Looping for each element of the matrix for (var row = 0; row < n; row++) { for (var 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++; } } } }}/* Recursive function to check if mat[,] issingular or not. */function isSingular(mat, n){ var D = 0; // Initialize result // Base case : if matrix contains single element if (n == 1) { return mat[0][0]; } var temp = Array.from(Array(N), ()=>Array(N));// To store cofactors var sign = 1; // To store sign multiplier // Iterate for each element of first row for(var f = 0; f < n; f++) { // Getting Cofactor of mat[0,f] getCofactor(mat, temp, 0, f, n); D += sign * mat[0][f] * isSingular(temp, n - 1); // terms are to be added with alternate sign sign = -sign; } return D;}// Driver codevar mat = [[4, 10, 1], [0, 0, 0], [1, 4, -3]];if (isSingular(mat, N) == 1){ document.write(\"Matrix is Singular\");}else{ document.write(\"Matrix is non-singular\");} // This code is contributed by noob2000.</script>", "e": 10221, "s": 8483, "text": null }, { "code": null, "e": 10244, "s": 10221, "text": "Matrix is non-singular" }, { "code": null, "e": 10260, "s": 10246, "text": "princiraj1992" }, { "code": null, "e": 10270, "s": 10260, "text": "Rajput-Ji" }, { "code": null, "e": 10287, "s": 10270, "text": "SURENDRA_GANGWAR" }, { "code": null, "e": 10296, "s": 10287, "text": "noob2000" }, { "code": null, "e": 10304, "s": 10296, "text": "Algebra" }, { "code": null, "e": 10311, "s": 10304, "text": "Matrix" }, { "code": null, "e": 10318, "s": 10311, "text": "Matrix" }, { "code": null, "e": 10416, "s": 10318, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 10454, "s": 10416, "text": "Unique paths in a Grid with Obstacles" }, { "code": null, "e": 10511, "s": 10454, "text": "Find the longest path in a matrix with given constraints" }, { "code": null, "e": 10549, "s": 10511, "text": "Find median in row wise sorted matrix" }, { "code": null, "e": 10590, "s": 10549, "text": "Zigzag (or diagonal) traversal of Matrix" }, { "code": null, "e": 10616, "s": 10590, "text": "A Boolean Matrix Question" }, { "code": null, "e": 10656, "s": 10616, "text": "Traverse a given Matrix using Recursion" }, { "code": null, "e": 10687, "s": 10656, "text": "Find a specific pair in Matrix" }, { "code": null, "e": 10733, "s": 10687, "text": "Common elements in all rows of a given matrix" }, { "code": null, "e": 10789, "s": 10733, "text": "Shortest distance between two cells in a matrix or grid" } ]
How to select a drop-down menu option value with Selenium (Python)?
We can select a drop-down menu option value with Selenium webdriver. The Select class in Selenium is used to handle drop-down. In an html document, the drop-down is identified with the <select> tag. Let us see the html structure of a drop-down. For using the methods of Select class we have to import selenium.webdriver.support.select.Select in our code. Let us discuss the methods available to select an option from drop-down− select_by_visible_text (arg) – The arg which is passed as a parameter to the method is selected if it matches with the text which is visible in the dropdown.Syntax−sel = Select (driver.find_element_by_id ("name"))sel.select_by_visible_text ('Visible Text') select_by_visible_text (arg) – The arg which is passed as a parameter to the method is selected if it matches with the text which is visible in the dropdown. Syntax− sel = Select (driver.find_element_by_id ("name")) sel.select_by_visible_text ('Visible Text') select_by_value (arg) – The arg which is passed as a parameter to the method is selected if it matches with the option value in the dropdown.Syntax−sel = Select (driver.find_element_by_id ("name"))sel.select_by_value ('Value') select_by_value (arg) – The arg which is passed as a parameter to the method is selected if it matches with the option value in the dropdown. Syntax− sel = Select (driver.find_element_by_id ("name")) sel.select_by_value ('Value') select_by_index (arg) – The arg which is passed as a parameter to the method is selected if it matches with the option index in the dropdown.The index begins from zero.Syntax−sel = Select (driver.find_element_by_id ("name"))sel.select_by_index (1) select_by_index (arg) – The arg which is passed as a parameter to the method is selected if it matches with the option index in the dropdown. The index begins from zero. Syntax− sel = Select (driver.find_element_by_id ("name")) sel.select_by_index (1) from selenium import webdriver from selenium.webdriver.support.select import Select import timedriver = webdriver.Chrome(executable_path="C:\\chromedriver.exe") driver.implicitly_wait(0.5) driver.get("https://www.tutorialspoint.com/selenium/selenium_automation_practice.htm") # identify dropdown with Select class sel = Select(driver.find_element_by_xpath("//select[@name='continents']")) #select by select_by_visible_text() method sel.select_by_visible_text("Europe") time.sleep(0.8) #select by select_by_index() method sel.select_by_index(0) driver.close()
[ { "code": null, "e": 1386, "s": 1187, "text": "We can select a drop-down menu option value with Selenium webdriver.\nThe Select class in Selenium is used to handle drop-down. In an html document, the drop-down is identified with the <select> tag." }, { "code": null, "e": 1432, "s": 1386, "text": "Let us see the html structure of a drop-down." }, { "code": null, "e": 1615, "s": 1432, "text": "For using the methods of Select class we have to import selenium.webdriver.support.select.Select in our code. Let us discuss the methods available to select an option from drop-down−" }, { "code": null, "e": 1872, "s": 1615, "text": "select_by_visible_text (arg) – The arg which is passed as a parameter to the method is selected if it matches with the text which is visible in the dropdown.Syntax−sel = Select (driver.find_element_by_id (\"name\"))sel.select_by_visible_text ('Visible Text')" }, { "code": null, "e": 2030, "s": 1872, "text": "select_by_visible_text (arg) – The arg which is passed as a parameter to the method is selected if it matches with the text which is visible in the dropdown." }, { "code": null, "e": 2038, "s": 2030, "text": "Syntax−" }, { "code": null, "e": 2088, "s": 2038, "text": "sel = Select (driver.find_element_by_id (\"name\"))" }, { "code": null, "e": 2132, "s": 2088, "text": "sel.select_by_visible_text ('Visible Text')" }, { "code": null, "e": 2359, "s": 2132, "text": "select_by_value (arg) – The arg which is passed as a parameter to the method is selected if it matches with the option value in the dropdown.Syntax−sel = Select (driver.find_element_by_id (\"name\"))sel.select_by_value ('Value')" }, { "code": null, "e": 2501, "s": 2359, "text": "select_by_value (arg) – The arg which is passed as a parameter to the method is selected if it matches with the option value in the dropdown." }, { "code": null, "e": 2509, "s": 2501, "text": "Syntax−" }, { "code": null, "e": 2559, "s": 2509, "text": "sel = Select (driver.find_element_by_id (\"name\"))" }, { "code": null, "e": 2589, "s": 2559, "text": "sel.select_by_value ('Value')" }, { "code": null, "e": 2837, "s": 2589, "text": "select_by_index (arg) – The arg which is passed as a parameter to the method is selected if it matches with the option index in the dropdown.The index begins from zero.Syntax−sel = Select (driver.find_element_by_id (\"name\"))sel.select_by_index (1)" }, { "code": null, "e": 2979, "s": 2837, "text": "select_by_index (arg) – The arg which is passed as a parameter to the method is selected if it matches with the option index in the dropdown." }, { "code": null, "e": 3007, "s": 2979, "text": "The index begins from zero." }, { "code": null, "e": 3015, "s": 3007, "text": "Syntax−" }, { "code": null, "e": 3065, "s": 3015, "text": "sel = Select (driver.find_element_by_id (\"name\"))" }, { "code": null, "e": 3089, "s": 3065, "text": "sel.select_by_index (1)" }, { "code": null, "e": 3648, "s": 3089, "text": "from selenium import webdriver\nfrom selenium.webdriver.support.select import Select\nimport timedriver = webdriver.Chrome(executable_path=\"C:\\\\chromedriver.exe\")\ndriver.implicitly_wait(0.5)\ndriver.get(\"https://www.tutorialspoint.com/selenium/selenium_automation_practice.htm\")\n# identify dropdown with Select class\nsel = Select(driver.find_element_by_xpath(\"//select[@name='continents']\"))\n#select by select_by_visible_text() method\nsel.select_by_visible_text(\"Europe\")\ntime.sleep(0.8)\n#select by select_by_index() method\nsel.select_by_index(0)\ndriver.close()" } ]
Kotlin Ranges
29 Nov, 2019 In Kotlin, the range is a collection of finite values which is defined by endpoints. The range in Kotlin consists of a start, a stop, and the step. The start and stop are inclusive in the Range and the value of step is by default 1.The range is used with comparable types. There are three ways for creating Range in Kotlin – Using (..) operator Using rangeTo() function Using downTo() function It is the simplest way to work with range. It will create a range from the start to end including both the values of start and end. It is the operator form of rangeTo() function. Using (..) operator we can create range for integers as well as characters.Kotlin program of integer range using (..) operator – fun main(args : Array<String>){ println("Integer range:") // creating integer range for(num in 1..5){ println(num) }} Output: Integer range: 1 2 3 4 5 Kotlin program of character range using (..) operator – fun main(args : Array<String>){ println("Character range:") // creating character range for(ch in 'a'..'e'){ println(ch) }} Output: Character range: a b c d e It is similar to (..) operator. It will create a range upto the value passed as an argument. It is also used to create range for integers as well as characters.Kotlin program of integer range using rangeTo() function – fun main(args : Array<String>){ println("Integer range:") // creating integer range for(num in 1.rangeTo(5)){ println(num) }} Output: Integer range: 1 2 3 4 5 Kotlin program of character range using rangeTo() function – fun main(args : Array<String>){ println("Character range:") // creating character range for(ch in 'a'.rangeTo('e')){ println(ch) }} Output: Character range: a b c d e It is reverse of the rangeTo() or (..) operator. It creates a range in descending order, i.e. from bigger values to smaller value. Below we create range in reverse order for integer and characters both.Kotlin program of integer range using downTo() function – fun main(args : Array<String>){ println("Integer range in descending order:") // creating integer range for(num in 5.downTo(1)){ println(num) }} Output: Integer range in descending order: 5 4 3 2 1 Kotlin program of character range using downTo() function – fun main(args : Array<String>){ println("Character range in reverse order:") // creating character range for(ch in 'e'.downTo('a')){ println(ch) }} Output: Character range in reverse order: e d c b a The forEach loop is also used to traverse over the range. fun main(args : Array<String>){ println("Integer range:") // creating integer range (2..5).forEach(::println)} Output: Integer range: 2 3 4 5 With keyword step, one can provide step between values. It is mainly used in order to provide the gap between the two values in rangeTo() or downTo() or in (..) operator. The default value for step is 1 and the value of step function cannot be 0. Kotlin program of using step – fun main(args: Array<String>) { //for iterating over the range var i = 2 // for loop with step keyword for (i in 3..10 step 2) print("$i ") println() // print first value of the range println((11..20 step 2).first) // print last value of the range println((11..20 step 4).last) // print the step used in the range println((11..20 step 5).step) } Output: 3 5 7 9 11 19 5 It is used to reverse the given range type. Instead of downTo() we can use reverse() function to print the range in descending order. fun main(args: Array<String>) { var range = 2..8 for (x in range.reversed()){ print("$x ") }} Output: 8 7 6 5 4 3 2 There are some predefined function in Kotlin Range: min(), max(), sum(), average(). fun main() { val predefined = (15..20) println("The minimum value of range is: "+predefined.min()) println("The maximum value of range is: "+predefined.max()) println("The sum of all values of range is: "+predefined.sum()) println("The average value of range is: "+predefined.average())} Output: The minimum value of range is: 15 The maximum value of range is: 20 The sum of all values of range is: 105 The average value of range is: 17.5 fun main(args: Array<String>){ var i = 2 //to check whether the value lies in the range if( i in 5..10) println("$i is lie within the range") else println("$i does not lie within the range")} Output: 2 does not lie within the range shubham_singh Kotlin Ranges Picked Kotlin Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n29 Nov, 2019" }, { "code": null, "e": 301, "s": 28, "text": "In Kotlin, the range is a collection of finite values which is defined by endpoints. The range in Kotlin consists of a start, a stop, and the step. The start and stop are inclusive in the Range and the value of step is by default 1.The range is used with comparable types." }, { "code": null, "e": 353, "s": 301, "text": "There are three ways for creating Range in Kotlin –" }, { "code": null, "e": 373, "s": 353, "text": "Using (..) operator" }, { "code": null, "e": 398, "s": 373, "text": "Using rangeTo() function" }, { "code": null, "e": 422, "s": 398, "text": "Using downTo() function" }, { "code": null, "e": 730, "s": 422, "text": "It is the simplest way to work with range. It will create a range from the start to end including both the values of start and end. It is the operator form of rangeTo() function. Using (..) operator we can create range for integers as well as characters.Kotlin program of integer range using (..) operator –" }, { "code": "fun main(args : Array<String>){ println(\"Integer range:\") // creating integer range for(num in 1..5){ println(num) }}", "e": 870, "s": 730, "text": null }, { "code": null, "e": 878, "s": 870, "text": "Output:" }, { "code": null, "e": 904, "s": 878, "text": "Integer range:\n1\n2\n3\n4\n5\n" }, { "code": null, "e": 960, "s": 904, "text": "Kotlin program of character range using (..) operator –" }, { "code": "fun main(args : Array<String>){ println(\"Character range:\") // creating character range for(ch in 'a'..'e'){ println(ch) }}", "e": 1106, "s": 960, "text": null }, { "code": null, "e": 1114, "s": 1106, "text": "Output:" }, { "code": null, "e": 1142, "s": 1114, "text": "Character range:\na\nb\nc\nd\ne\n" }, { "code": null, "e": 1361, "s": 1142, "text": "It is similar to (..) operator. It will create a range upto the value passed as an argument. It is also used to create range for integers as well as characters.Kotlin program of integer range using rangeTo() function –" }, { "code": "fun main(args : Array<String>){ println(\"Integer range:\") // creating integer range for(num in 1.rangeTo(5)){ println(num) }}", "e": 1509, "s": 1361, "text": null }, { "code": null, "e": 1517, "s": 1509, "text": "Output:" }, { "code": null, "e": 1543, "s": 1517, "text": "Integer range:\n1\n2\n3\n4\n5\n" }, { "code": null, "e": 1604, "s": 1543, "text": "Kotlin program of character range using rangeTo() function –" }, { "code": "fun main(args : Array<String>){ println(\"Character range:\") // creating character range for(ch in 'a'.rangeTo('e')){ println(ch) }}", "e": 1758, "s": 1604, "text": null }, { "code": null, "e": 1766, "s": 1758, "text": "Output:" }, { "code": null, "e": 1795, "s": 1766, "text": "Character range:\na\nb\nc\nd\ne\n" }, { "code": null, "e": 2055, "s": 1795, "text": "It is reverse of the rangeTo() or (..) operator. It creates a range in descending order, i.e. from bigger values to smaller value. Below we create range in reverse order for integer and characters both.Kotlin program of integer range using downTo() function –" }, { "code": "fun main(args : Array<String>){ println(\"Integer range in descending order:\") // creating integer range for(num in 5.downTo(1)){ println(num) }}", "e": 2221, "s": 2055, "text": null }, { "code": null, "e": 2229, "s": 2221, "text": "Output:" }, { "code": null, "e": 2275, "s": 2229, "text": "Integer range in descending order:\n5\n4\n3\n2\n1\n" }, { "code": null, "e": 2335, "s": 2275, "text": "Kotlin program of character range using downTo() function –" }, { "code": "fun main(args : Array<String>){ println(\"Character range in reverse order:\") // creating character range for(ch in 'e'.downTo('a')){ println(ch) }}", "e": 2504, "s": 2335, "text": null }, { "code": null, "e": 2512, "s": 2504, "text": "Output:" }, { "code": null, "e": 2557, "s": 2512, "text": "Character range in reverse order:\ne\nd\nc\nb\na\n" }, { "code": null, "e": 2615, "s": 2557, "text": "The forEach loop is also used to traverse over the range." }, { "code": "fun main(args : Array<String>){ println(\"Integer range:\") // creating integer range (2..5).forEach(::println)}", "e": 2738, "s": 2615, "text": null }, { "code": null, "e": 2746, "s": 2738, "text": "Output:" }, { "code": null, "e": 2771, "s": 2746, "text": "Integer range:\n2\n3\n4\n5\n" }, { "code": null, "e": 3018, "s": 2771, "text": "With keyword step, one can provide step between values. It is mainly used in order to provide the gap between the two values in rangeTo() or downTo() or in (..) operator. The default value for step is 1 and the value of step function cannot be 0." }, { "code": null, "e": 3049, "s": 3018, "text": "Kotlin program of using step –" }, { "code": "fun main(args: Array<String>) { //for iterating over the range var i = 2 // for loop with step keyword for (i in 3..10 step 2) print(\"$i \") println() // print first value of the range println((11..20 step 2).first) // print last value of the range println((11..20 step 4).last) // print the step used in the range println((11..20 step 5).step) }", "e": 3442, "s": 3049, "text": null }, { "code": null, "e": 3450, "s": 3442, "text": "Output:" }, { "code": null, "e": 3468, "s": 3450, "text": "3 5 7 9 \n11\n19\n5\n" }, { "code": null, "e": 3602, "s": 3468, "text": "It is used to reverse the given range type. Instead of downTo() we can use reverse() function to print the range in descending order." }, { "code": "fun main(args: Array<String>) { var range = 2..8 for (x in range.reversed()){ print(\"$x \") }}", "e": 3712, "s": 3602, "text": null }, { "code": null, "e": 3720, "s": 3712, "text": "Output:" }, { "code": null, "e": 3735, "s": 3720, "text": "8 7 6 5 4 3 2 " }, { "code": null, "e": 3819, "s": 3735, "text": "There are some predefined function in Kotlin Range: min(), max(), sum(), average()." }, { "code": "fun main() { val predefined = (15..20) println(\"The minimum value of range is: \"+predefined.min()) println(\"The maximum value of range is: \"+predefined.max()) println(\"The sum of all values of range is: \"+predefined.sum()) println(\"The average value of range is: \"+predefined.average())}", "e": 4126, "s": 3819, "text": null }, { "code": null, "e": 4134, "s": 4126, "text": "Output:" }, { "code": null, "e": 4278, "s": 4134, "text": "The minimum value of range is: 15\nThe maximum value of range is: 20\nThe sum of all values of range is: 105\nThe average value of range is: 17.5\n" }, { "code": "fun main(args: Array<String>){ var i = 2 //to check whether the value lies in the range if( i in 5..10) println(\"$i is lie within the range\") else println(\"$i does not lie within the range\")}", "e": 4497, "s": 4278, "text": null }, { "code": null, "e": 4505, "s": 4497, "text": "Output:" }, { "code": null, "e": 4537, "s": 4505, "text": "2 does not lie within the range" }, { "code": null, "e": 4551, "s": 4537, "text": "shubham_singh" }, { "code": null, "e": 4565, "s": 4551, "text": "Kotlin Ranges" }, { "code": null, "e": 4572, "s": 4565, "text": "Picked" }, { "code": null, "e": 4579, "s": 4572, "text": "Kotlin" } ]
What is the Application Cache and why it is used in HTML5 ?
18 Aug, 2021 The task is to learn about the application cache in HTML5. HTML stands for HyperText Markup Language and it is used to design web pages using a markup language. HTML5 is current or we can also say that it’s the 5th version of HTML. Application Cache in HTML5: The current version of HTML5 introduces application cache, which means that a web application is cached, and accessible without an internet connection. Now we can make an offline web application that will run without an internet connection by just creating a manifest file in our application. Syntax: <html manifest="demo.appcache"> Structure of HTML file: HTML is nothing but just an element tag that comes after the doctype tag in HTML structure. HTML <!DOCTYPE html><html> <!-- In this element we will add an attribute called manifest attribute--> <head> <title>Page Title</title> </head> <body> <h2>Welcome To GFG</h2> <p>It is a paragraph element</p> </body></html> Let us understand the concept of application cache with the help of an example. Approach: Create an HTML file with the manifest attribute. Create another HTML file then link it to the previously created HTML file. Example: The name of the main file is “index.html”. First, the main file will execute and when you try to open the linked page the next page will run. After that, you just have to go offline and reload the page. the content of the page will still work fine. HTML <!DOCTYPE html><html manifest="demo.appcache"> <body> Welcome to GeeksForGeeks. <p> Try opening <a href="index2.html">this page</a>, then go offline, and reload the page. The content should still work. </p> </body></html> HTML <!DOCTYPE html><html manifest="demo.appcache"> <body> Welcome to GFG, a computer science portal for geeks. </body></html> Output: Uses of the application cache are: Offline browsing: The users can use the application whenever they want to access the site when they’re offline Speed: When the data is already stored then it is easy to access data with the greater speed, cached resources load faster than uncached resources. Reduced server load: The browser will only download updated resources from the server. Supported browsers: Chrome 4.0 and above Internet 10.0 and above Mozilla Firefox 3.5 and above Opera 11.5 and above Safari 4.0 HTML-Questions HTML5 Picked HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. REST API (Introduction) Design a Tribute Page using HTML & CSS Build a Survey Form using HTML and CSS Angular File Upload Design a web page using HTML and CSS Installation of Node.js on Linux Difference between var, let and const keywords in JavaScript How to fetch data from an API in ReactJS ? Differences between Functional Components and Class Components in React Remove elements from a JavaScript Array
[ { "code": null, "e": 28, "s": 0, "text": "\n18 Aug, 2021" }, { "code": null, "e": 260, "s": 28, "text": "The task is to learn about the application cache in HTML5. HTML stands for HyperText Markup Language and it is used to design web pages using a markup language. HTML5 is current or we can also say that it’s the 5th version of HTML." }, { "code": null, "e": 582, "s": 260, "text": "Application Cache in HTML5: The current version of HTML5 introduces application cache, which means that a web application is cached, and accessible without an internet connection. Now we can make an offline web application that will run without an internet connection by just creating a manifest file in our application. " }, { "code": null, "e": 590, "s": 582, "text": "Syntax:" }, { "code": null, "e": 622, "s": 590, "text": "<html manifest=\"demo.appcache\">" }, { "code": null, "e": 739, "s": 622, "text": "Structure of HTML file: HTML is nothing but just an element tag that comes after the doctype tag in HTML structure. " }, { "code": null, "e": 746, "s": 741, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <!-- In this element we will add an attribute called manifest attribute--> <head> <title>Page Title</title> </head> <body> <h2>Welcome To GFG</h2> <p>It is a paragraph element</p> </body></html>", "e": 985, "s": 746, "text": null }, { "code": null, "e": 1065, "s": 985, "text": "Let us understand the concept of application cache with the help of an example." }, { "code": null, "e": 1076, "s": 1065, "text": "Approach: " }, { "code": null, "e": 1125, "s": 1076, "text": "Create an HTML file with the manifest attribute." }, { "code": null, "e": 1200, "s": 1125, "text": "Create another HTML file then link it to the previously created HTML file." }, { "code": null, "e": 1458, "s": 1200, "text": "Example: The name of the main file is “index.html”. First, the main file will execute and when you try to open the linked page the next page will run. After that, you just have to go offline and reload the page. the content of the page will still work fine." }, { "code": null, "e": 1463, "s": 1458, "text": "HTML" }, { "code": "<!DOCTYPE html><html manifest=\"demo.appcache\"> <body> Welcome to GeeksForGeeks. <p> Try opening <a href=\"index2.html\">this page</a>, then go offline, and reload the page. The content should still work. </p> </body></html>", "e": 1714, "s": 1463, "text": null }, { "code": null, "e": 1719, "s": 1714, "text": "HTML" }, { "code": "<!DOCTYPE html><html manifest=\"demo.appcache\"> <body> Welcome to GFG, a computer science portal for geeks. </body></html>", "e": 1846, "s": 1719, "text": null }, { "code": null, "e": 1855, "s": 1846, "text": "Output: " }, { "code": null, "e": 1890, "s": 1855, "text": "Uses of the application cache are:" }, { "code": null, "e": 2001, "s": 1890, "text": "Offline browsing: The users can use the application whenever they want to access the site when they’re offline" }, { "code": null, "e": 2149, "s": 2001, "text": "Speed: When the data is already stored then it is easy to access data with the greater speed, cached resources load faster than uncached resources." }, { "code": null, "e": 2236, "s": 2149, "text": "Reduced server load: The browser will only download updated resources from the server." }, { "code": null, "e": 2256, "s": 2236, "text": "Supported browsers:" }, { "code": null, "e": 2277, "s": 2256, "text": "Chrome 4.0 and above" }, { "code": null, "e": 2301, "s": 2277, "text": "Internet 10.0 and above" }, { "code": null, "e": 2331, "s": 2301, "text": "Mozilla Firefox 3.5 and above" }, { "code": null, "e": 2352, "s": 2331, "text": "Opera 11.5 and above" }, { "code": null, "e": 2363, "s": 2352, "text": "Safari 4.0" }, { "code": null, "e": 2378, "s": 2363, "text": "HTML-Questions" }, { "code": null, "e": 2384, "s": 2378, "text": "HTML5" }, { "code": null, "e": 2391, "s": 2384, "text": "Picked" }, { "code": null, "e": 2396, "s": 2391, "text": "HTML" }, { "code": null, "e": 2413, "s": 2396, "text": "Web Technologies" }, { "code": null, "e": 2418, "s": 2413, "text": "HTML" }, { "code": null, "e": 2516, "s": 2418, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2540, "s": 2516, "text": "REST API (Introduction)" }, { "code": null, "e": 2579, "s": 2540, "text": "Design a Tribute Page using HTML & CSS" }, { "code": null, "e": 2618, "s": 2579, "text": "Build a Survey Form using HTML and CSS" }, { "code": null, "e": 2638, "s": 2618, "text": "Angular File Upload" }, { "code": null, "e": 2675, "s": 2638, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 2708, "s": 2675, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 2769, "s": 2708, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2812, "s": 2769, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 2884, "s": 2812, "text": "Differences between Functional Components and Class Components in React" } ]
How to replace line breaks with <br> using JavaScript ?
19 Sep, 2021 Given a multiline string and the task is to replace line breaks with <br> tag. Example: Input: `Geeks for Geeks is a computer science portal where people study computer science`Output: “Geeks for Geeks is <br> a computer science portal <br> where people study computer science” To achieve this we have the following methods : Method 1: Using Regex, in this example, we are creating a paragraph and a button and on clicking the button we are changing (Adding the <br>)the text of the paragraph. We are using the String.replace() method of regex to replace the new line with <br>. The String.replace() is an inbuilt method in JavaScript that is used to replace a part of the given string with another string or a regular expression. The original string will remain unchanged. Example 1: HTML <!DOCTYPE html><html> <body> <p id="para"></p> <p> <button onClick="myFunc()">Change</button> <script> let str = `Geeks for Geeks is a computer science portal where people study computer science`; let para = document.getElementById("para"); para.innerHTML = str; function myFunc() { // Replace the \n with <br> str = str.replace(/(?:\r\n|\r|\n)/g, "<br>"); // Update the value of paragraph para.innerHTML = str; } </script> </p> </body></html> Output: The initial output After clicking the button Method 2: Using split and join, in this method, we split the string from the delimiter “\n” which returns an array of substrings, and then we join the Array using the join method and pass <br /> so that every joining contains <br />. Example 2: HTML <!DOCTYPE html><html> <body> <p id="para"></p> <p> <button onClick="myFunc()">Change</button> <script> let str = `Geeks for Geeks is a computer science portal where people study computer science`; let para = document.getElementById("para"); para.innerHTML = str; function myFunc() { // Replace the \n with <br> str = str.split("\n").join("<br />"); // Update the value of paragraph para.innerHTML = str; } </script> </p> </body></html> Output: The initial output After clicking the button sweetyty javascript-functions JavaScript-Methods JavaScript-Questions JavaScript-RegExp javascript-string 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 Hide or show elements in HTML using display property How to append HTML code to a div using JavaScript ? Top 10 Projects For Beginners To Practice HTML and CSS Skills Installation of Node.js on Linux 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": "\n19 Sep, 2021" }, { "code": null, "e": 107, "s": 28, "text": "Given a multiline string and the task is to replace line breaks with <br> tag." }, { "code": null, "e": 116, "s": 107, "text": "Example:" }, { "code": null, "e": 306, "s": 116, "text": "Input: `Geeks for Geeks is a computer science portal where people study computer science`Output: “Geeks for Geeks is <br> a computer science portal <br> where people study computer science”" }, { "code": null, "e": 354, "s": 306, "text": "To achieve this we have the following methods :" }, { "code": null, "e": 522, "s": 354, "text": "Method 1: Using Regex, in this example, we are creating a paragraph and a button and on clicking the button we are changing (Adding the <br>)the text of the paragraph." }, { "code": null, "e": 607, "s": 522, "text": "We are using the String.replace() method of regex to replace the new line with <br>." }, { "code": null, "e": 802, "s": 607, "text": "The String.replace() is an inbuilt method in JavaScript that is used to replace a part of the given string with another string or a regular expression. The original string will remain unchanged." }, { "code": null, "e": 813, "s": 802, "text": "Example 1:" }, { "code": null, "e": 818, "s": 813, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <body> <p id=\"para\"></p> <p> <button onClick=\"myFunc()\">Change</button> <script> let str = `Geeks for Geeks is a computer science portal where people study computer science`; let para = document.getElementById(\"para\"); para.innerHTML = str; function myFunc() { // Replace the \\n with <br> str = str.replace(/(?:\\r\\n|\\r|\\n)/g, \"<br>\"); // Update the value of paragraph para.innerHTML = str; } </script> </p> </body></html>", "e": 1386, "s": 818, "text": null }, { "code": null, "e": 1394, "s": 1386, "text": "Output:" }, { "code": null, "e": 1413, "s": 1394, "text": "The initial output" }, { "code": null, "e": 1439, "s": 1413, "text": "After clicking the button" }, { "code": null, "e": 1673, "s": 1439, "text": "Method 2: Using split and join, in this method, we split the string from the delimiter “\\n” which returns an array of substrings, and then we join the Array using the join method and pass <br /> so that every joining contains <br />." }, { "code": null, "e": 1686, "s": 1675, "text": "Example 2:" }, { "code": null, "e": 1691, "s": 1686, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <body> <p id=\"para\"></p> <p> <button onClick=\"myFunc()\">Change</button> <script> let str = `Geeks for Geeks is a computer science portal where people study computer science`; let para = document.getElementById(\"para\"); para.innerHTML = str; function myFunc() { // Replace the \\n with <br> str = str.split(\"\\n\").join(\"<br />\"); // Update the value of paragraph para.innerHTML = str; } </script> </p> </body></html>", "e": 2250, "s": 1691, "text": null }, { "code": null, "e": 2258, "s": 2250, "text": "Output:" }, { "code": null, "e": 2277, "s": 2258, "text": "The initial output" }, { "code": null, "e": 2303, "s": 2277, "text": "After clicking the button" }, { "code": null, "e": 2312, "s": 2303, "text": "sweetyty" }, { "code": null, "e": 2333, "s": 2312, "text": "javascript-functions" }, { "code": null, "e": 2352, "s": 2333, "text": "JavaScript-Methods" }, { "code": null, "e": 2373, "s": 2352, "text": "JavaScript-Questions" }, { "code": null, "e": 2391, "s": 2373, "text": "JavaScript-RegExp" }, { "code": null, "e": 2409, "s": 2391, "text": "javascript-string" }, { "code": null, "e": 2420, "s": 2409, "text": "JavaScript" }, { "code": null, "e": 2437, "s": 2420, "text": "Web Technologies" }, { "code": null, "e": 2535, "s": 2437, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2596, "s": 2535, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2668, "s": 2596, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 2708, "s": 2668, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 2761, "s": 2708, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 2813, "s": 2761, "text": "How to append HTML code to a div using JavaScript ?" }, { "code": null, "e": 2875, "s": 2813, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 2908, "s": 2875, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 2969, "s": 2908, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 3019, "s": 2969, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Sparse Matrix and its representations | Set 1 (Using Arrays and Linked Lists)
07 Jul, 2022 A matrix is a two-dimensional data object made of m rows and n columns, therefore having total m x n values. If most of the elements of the matrix have 0 value, then it is called a sparse matrix. Why to use Sparse Matrix instead of simple matrix ? Storage: There are lesser non-zero elements than zeros and thus lesser memory can be used to store only those elements. Computing time: Computing time can be saved by logically designing a data structure traversing only non-zero elements.. Example: 0 0 3 0 4 0 0 5 7 0 0 0 0 0 0 0 2 6 0 0 Representing a sparse matrix by a 2D array leads to wastage of lots of memory as zeroes in the matrix are of no use in most of the cases. So, instead of storing zeroes with non-zero elements, we only store non-zero elements. This means storing non-zero elements with triples- (Row, Column, value). Sparse Matrix Representations can be done in many ways following are two common representations: Array representationLinked list representation Array representation Linked list representation Method 1: Using Arrays: 2D array is used to represent a sparse matrix in which there are three rows named as Row: Index of row, where non-zero element is located Column: Index of column, where non-zero element is located Value: Value of the non zero element located at index – (row,column) Implementation: C++ C Java Python3 C# // C++ program for Sparse Matrix Representation// using Array#include <iostream>using namespace std; int main(){ // Assume 4x5 sparse matrix int sparseMatrix[4][5] = { {0 , 0 , 3 , 0 , 4 }, {0 , 0 , 5 , 7 , 0 }, {0 , 0 , 0 , 0 , 0 }, {0 , 2 , 6 , 0 , 0 } }; int size = 0; for (int i = 0; i < 4; i++) for (int j = 0; j < 5; j++) if (sparseMatrix[i][j] != 0) size++; // number of columns in compactMatrix (size) must be // equal to number of non - zero elements in // sparseMatrix int compactMatrix[3][size]; // Making of new matrix int k = 0; for (int i = 0; i < 4; i++) for (int j = 0; j < 5; j++) if (sparseMatrix[i][j] != 0) { compactMatrix[0][k] = i; compactMatrix[1][k] = j; compactMatrix[2][k] = sparseMatrix[i][j]; k++; } for (int i=0; i<3; i++) { for (int j=0; j<size; j++) cout <<" "<< compactMatrix[i][j]; cout <<"\n"; } return 0;} // this code is contributed by shivanisinghss2110 // C++ program for Sparse Matrix Representation// using Array#include<stdio.h> int main(){ // Assume 4x5 sparse matrix int sparseMatrix[4][5] = { {0 , 0 , 3 , 0 , 4 }, {0 , 0 , 5 , 7 , 0 }, {0 , 0 , 0 , 0 , 0 }, {0 , 2 , 6 , 0 , 0 } }; int size = 0; for (int i = 0; i < 4; i++) for (int j = 0; j < 5; j++) if (sparseMatrix[i][j] != 0) size++; // number of columns in compactMatrix (size) must be // equal to number of non - zero elements in // sparseMatrix int compactMatrix[3][size]; // Making of new matrix int k = 0; for (int i = 0; i < 4; i++) for (int j = 0; j < 5; j++) if (sparseMatrix[i][j] != 0) { compactMatrix[0][k] = i; compactMatrix[1][k] = j; compactMatrix[2][k] = sparseMatrix[i][j]; k++; } for (int i=0; i<3; i++) { for (int j=0; j<size; j++) printf("%d ", compactMatrix[i][j]); printf("\n"); } return 0;} // Java program for Sparse Matrix Representation// using Arrayclass GFG{ public static void main(String[] args) { int sparseMatrix[][] = { {0, 0, 3, 0, 4}, {0, 0, 5, 7, 0}, {0, 0, 0, 0, 0}, {0, 2, 6, 0, 0} }; int size = 0; for (int i = 0; i < 4; i++) { for (int j = 0; j < 5; j++) { if (sparseMatrix[i][j] != 0) { size++; } } } // number of columns in compactMatrix (size) must be // equal to number of non - zero elements in // sparseMatrix int compactMatrix[][] = new int[3][size]; // Making of new matrix int k = 0; for (int i = 0; i < 4; i++) { for (int j = 0; j < 5; j++) { if (sparseMatrix[i][j] != 0) { compactMatrix[0][k] = i; compactMatrix[1][k] = j; compactMatrix[2][k] = sparseMatrix[i][j]; k++; } } } for (int i = 0; i < 3; i++) { for (int j = 0; j < size; j++) { System.out.printf("%d ", compactMatrix[i][j]); } System.out.printf("\n"); } }} /* This code contributed by PrinciRaj1992 */ # Python program for Sparse Matrix Representation# using arrays # assume a sparse matrix of order 4*5# let assume another matrix compactMatrix# now store the value,row,column of arr1 in sparse matrix compactMatrix sparseMatrix = [[0,0,3,0,4],[0,0,5,7,0],[0,0,0,0,0],[0,2,6,0,0]] # initialize size as 0size = 0 for i in range(4): for j in range(5): if (sparseMatrix[i][j] != 0): size += 1 # number of columns in compactMatrix(size) should# be equal to number of non-zero elements in sparseMatrixrows, cols = (3, size)compactMatrix = [[0 for i in range(cols)] for j in range(rows)] k = 0for i in range(4): for j in range(5): if (sparseMatrix[i][j] != 0): compactMatrix[0][k] = i compactMatrix[1][k] = j compactMatrix[2][k] = sparseMatrix[i][j] k += 1 for i in compactMatrix: print(i) # This code is contributed by MRINALWALIA // C# program for Sparse Matrix Representation// using Array using System; class Program { static void Main(string[] args) { // Assume 4x5 sparse matrix int[, ] sparseMatrix = new int[4, 5] { { 0, 0, 3, 0, 4 }, { 0, 0, 5, 7, 0 }, { 0, 0, 0, 0, 0 }, { 0, 2, 6, 0, 0 } }; int size = 0; for (int i = 0; i < 4; i++) for (int j = 0; j < 5; j++) if (sparseMatrix[i, j] != 0) size++; // number of columns in compactMatrix (size) must be // equal to number of non - zero elements in // sparseMatrix int[, ] compactMatrix = new int[3, size]; // Making of new matrix int k = 0; for (int i = 0; i < 4; i++) { for (int j = 0; j < 5; j++) if (sparseMatrix[i, j] != 0) { compactMatrix[0, k] = i; compactMatrix[1, k] = j; compactMatrix[2, k] = sparseMatrix[i, j]; k++; } } for (int i = 0; i < 3; i++) { for (int j = 0; j < size; j++) Console.Write(" " + compactMatrix[i, j]); Console.WriteLine(); } }}// This code is contributed by Tapesh(tapeshdua420) 0 0 1 1 3 3 2 4 2 3 1 2 3 4 5 7 2 6 Method 2: Using Linked ListsIn linked list, each node has four fields. These four fields are defined as: Row: Index of row, where non-zero element is located Column: Index of column, where non-zero element is located Value: Value of the non zero element located at index – (row,column) Next node: Address of the next node C++ C Java Python3 C# // C++ program for sparse matrix representation.// Using Link list#include<iostream>using namespace std; // Node class to represent link listclass Node{ public: int row; int col; int data; Node *next;}; // Function to create new nodevoid create_new_node(Node **p, int row_index, int col_index, int x){ Node *temp = *p; Node *r; // If link list is empty then // create first node and assign value. if (temp == NULL) { temp = new Node(); temp->row = row_index; temp->col = col_index; temp->data = x; temp->next = NULL; *p = temp; } // If link list is already created // then append newly created node else { while (temp->next != NULL) temp = temp->next; r = new Node(); r->row = row_index; r->col = col_index; r->data = x; r->next = NULL; temp->next = r; }} // Function prints contents of linked list// starting from startvoid printList(Node *start){ Node *ptr = start; cout << "row_position:"; while (ptr != NULL) { cout << ptr->row << " "; ptr = ptr->next; } cout << endl; cout << "column_position:"; ptr = start; while (ptr != NULL) { cout << ptr->col << " "; ptr = ptr->next; } cout << endl; cout << "Value:"; ptr = start; while (ptr != NULL) { cout << ptr->data << " "; ptr = ptr->next; }} // Driver Codeint main(){ // 4x5 sparse matrix int sparseMatrix[4][5] = { { 0 , 0 , 3 , 0 , 4 }, { 0 , 0 , 5 , 7 , 0 }, { 0 , 0 , 0 , 0 , 0 }, { 0 , 2 , 6 , 0 , 0 } }; // Creating head/first node of list as NULL Node *first = NULL; for(int i = 0; i < 4; i++) { for(int j = 0; j < 5; j++) { // Pass only those values which // are non - zero if (sparseMatrix[i][j] != 0) create_new_node(&first, i, j, sparseMatrix[i][j]); } } printList(first); return 0;} // This code is contributed by ronaksuba // C program for Sparse Matrix Representation// using Linked Lists#include<stdio.h>#include<stdlib.h> // Node to represent sparse matrixstruct Node{ int value; int row_position; int column_postion; struct Node *next;}; // Function to create new nodevoid create_new_node(struct Node** start, int non_zero_element, int row_index, int column_index ){ struct Node *temp, *r; temp = *start; if (temp == NULL) { // Create new node dynamically temp = (struct Node *) malloc (sizeof(struct Node)); temp->value = non_zero_element; temp->row_position = row_index; temp->column_postion = column_index; temp->next = NULL; *start = temp; } else { while (temp->next != NULL) temp = temp->next; // Create new node dynamically r = (struct Node *) malloc (sizeof(struct Node)); r->value = non_zero_element; r->row_position = row_index; r->column_postion = column_index; r->next = NULL; temp->next = r; }} // This function prints contents of linked list// starting from startvoid PrintList(struct Node* start){ struct Node *temp, *r, *s; temp = r = s = start; printf("row_position: "); while(temp != NULL) { printf("%d ", temp->row_position); temp = temp->next; } printf("\n"); printf("column_postion: "); while(r != NULL) { printf("%d ", r->column_postion); r = r->next; } printf("\n"); printf("Value: "); while(s != NULL) { printf("%d ", s->value); s = s->next; } printf("\n");} // Driver of the programint main(){ // Assume 4x5 sparse matrix int sparseMatric[4][5] = { {0 , 0 , 3 , 0 , 4 }, {0 , 0 , 5 , 7 , 0 }, {0 , 0 , 0 , 0 , 0 }, {0 , 2 , 6 , 0 , 0 } }; /* Start with the empty list */ struct Node* start = NULL; for (int i = 0; i < 4; i++) for (int j = 0; j < 5; j++) // Pass only those values which are non - zero if (sparseMatric[i][j] != 0) create_new_node(&start, sparseMatric[i][j], i, j); PrintList(start); return 0;} // Java program for sparse matrix representation.// Using Link listimport java.util.*; public class SparseMatrix { // Creating head/first node of list as NULL static Node first = null; // Node class to represent link list public static class Node { int row; int col; int data; Node next; }; // Driver Code public static void main(String[] args) { // 4x5 sparse matrix int[][] sparseMatrix = { { 0, 0, 3, 0, 4 }, { 0, 0, 5, 7, 0 }, { 0, 0, 0, 0, 0 }, { 0, 2, 6, 0, 0 } }; for (int i = 0; i < 4; i++) { for (int j = 0; j < 5; j++) { // Pass only those values which // are non - zero if (sparseMatrix[i][j] != 0) { create_new_node(i, j, sparseMatrix[i][j]); } } } printList(first); } // Function to create new node private static void create_new_node(int row_index, int col_index, int x) { Node temp = first; Node r; // If link list is empty then // create first node and assign value. if (temp == null) { temp = new Node(); temp.row = row_index; temp.col = col_index; temp.data = x; temp.next = null; first = temp; } // If link list is already created // then append newly created node else { while (temp.next != null) temp = temp.next; r = new Node(); r.row = row_index; r.col = col_index; r.data = x; r.next = null; temp.next = r; } } // Function prints contents of linked list // starting from start public static void printList(Node start) { Node ptr = start; System.out.print("row_position:"); while (ptr != null) { System.out.print(ptr.row + " "); ptr = ptr.next; } System.out.println(""); System.out.print("column_position:"); ptr = start; while (ptr != null) { System.out.print(ptr.col + " "); ptr = ptr.next; } System.out.println(""); System.out.print("Value:"); ptr = start; while (ptr != null) { System.out.print(ptr.data + " "); ptr = ptr.next; } }} // This code is contributed by Tapesh (tapeshdua420) # Python Program for Representation of# Sparse Matrix into Linked List # Node Class to represent Linked List Nodeclass Node: # Making the slots for storing row, # column, value, and address __slots__ = "row", "col", "data", "next" # Constructor to initialize the values def __init__(self, row=0, col=0, data=0, next=None): self.row = row self.col = col self.data = data self.next = next # Class to convert Sparse Matrix# into Linked Listclass Sparse: # Initialize Class Variables def __init__(self): self.head = None self.temp = None self.size = 0 # Function which returns the size # of the Linked List def __len__(self): return self.size # Check the Linked List is # Empty or not def isempty(self): return self.size == 0 # Responsible function to create # Linked List from Sparse Matrix def create_new_node(self, row, col, data): # Creating New Node newNode = Node(row, col, data, None) # Check whether the List is # empty or not if self.isempty(): self.head = newNode else: self.temp.next = newNode self.temp = newNode # Incrementing the size self.size += 1 # Function display the contents of # Linked List def PrintList(self): temp = r = s = self.head print("row_position:", end=" ") while temp != None: print(temp.row, end=" ") temp = temp.next print() print("column_postion:", end=" ") while r != None: print(r.col, end=" ") r = r.next print() print("Value:", end=" ") while s != None: print(s.data, end=" ") s = s.next print() # Driver Codeif __name__ == "__main__": # Creating Object s = Sparse() # Assuming 4x5 Sparse Matrix sparseMatric = [[0, 0, 3, 0, 4], [0, 0, 5, 7, 0], [0, 0, 0, 0, 0], [0, 2, 6, 0, 0]] for i in range(4): for j in range(5): # Creating Linked List by only those # elements which are non-zero if sparseMatric[i][j] != 0: s.create_new_node(i, j, sparseMatric[i][j]) # Printing the Linked List Representation # of the sparse matrix s.PrintList() # This code is contributed by Naveen Rathore // C# program for sparse matrix representation.// Using Link listusing System; class Program{ // Creating head/first node of list as NULL static Node first = null; // Node class to represent link list public class Node { public int row; public int col; public int data; public Node next; }; // Driver Code static void Main(string[] args) { // 4x5 sparse matrix int[, ] sparseMatrix = { { 0, 0, 3, 0, 4 }, { 0, 0, 5, 7, 0 }, { 0, 0, 0, 0, 0 }, { 0, 2, 6, 0, 0 } }; for (int i = 0; i < 4; i++) { for (int j = 0; j < 5; j++) { // Pass only those values which // are non - zero if (sparseMatrix[i, j] != 0) { create_new_node(i, j, sparseMatrix[i, j]); } } } printList(first); } // Function to create new node private static void create_new_node(int row_index, int col_index, int x) { Node temp = first; Node r; // If link list is empty then // create first node and assign value. if (temp == null) { temp = new Node(); temp.row = row_index; temp.col = col_index; temp.data = x; temp.next = null; first = temp; } // If link list is already created // then append newly created node else { while (temp.next != null) temp = temp.next; r = new Node(); r.row = row_index; r.col = col_index; r.data = x; r.next = null; temp.next = r; } } // Function prints contents of linked list // starting from start public static void printList(Node start) { Node ptr = start; Console.Write("row_position:"); while (ptr != null) { Console.Write(ptr.row + " "); ptr = ptr.next; } Console.WriteLine(""); Console.Write("column_position:"); ptr = start; while (ptr != null) { Console.Write(ptr.col + " "); ptr = ptr.next; } Console.WriteLine(""); Console.Write("Value:"); ptr = start; while (ptr != null) { Console.Write(ptr.data + " "); ptr = ptr.next; } }} // This code is contributed by Tapesh (tapeshdua420) row_position:0 0 1 1 3 3 column_position:2 4 2 3 1 2 Value:3 4 5 7 2 6 Other representations: As a Dictionary where row and column numbers are used as keys and values are matrix entries. This method saves space but sequential access of items is costly. As a list of list. The idea is to make a list of rows and every item of list contains values. We can keep list items sorted by column numbers.Sparse Matrix and its representations | Set 2 (Using List of Lists and Dictionary of keys) This article is contributed by Akash Gupta.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. princiraj1992 MRINALWALIA rathorenav123 ronaksuba shivanisinghss2110 tapeshdua420 hardikkoriintern c-array Matrix Matrix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n07 Jul, 2022" }, { "code": null, "e": 248, "s": 52, "text": "A matrix is a two-dimensional data object made of m rows and n columns, therefore having total m x n values. If most of the elements of the matrix have 0 value, then it is called a sparse matrix." }, { "code": null, "e": 300, "s": 248, "text": "Why to use Sparse Matrix instead of simple matrix ?" }, { "code": null, "e": 420, "s": 300, "text": "Storage: There are lesser non-zero elements than zeros and thus lesser memory can be used to store only those elements." }, { "code": null, "e": 540, "s": 420, "text": "Computing time: Computing time can be saved by logically designing a data structure traversing only non-zero elements.." }, { "code": null, "e": 550, "s": 540, "text": "Example: " }, { "code": null, "e": 602, "s": 550, "text": "0 0 3 0 4 \n0 0 5 7 0\n0 0 0 0 0\n0 2 6 0 0" }, { "code": null, "e": 901, "s": 602, "text": "Representing a sparse matrix by a 2D array leads to wastage of lots of memory as zeroes in the matrix are of no use in most of the cases. So, instead of storing zeroes with non-zero elements, we only store non-zero elements. This means storing non-zero elements with triples- (Row, Column, value). " }, { "code": null, "e": 999, "s": 901, "text": "Sparse Matrix Representations can be done in many ways following are two common representations: " }, { "code": null, "e": 1046, "s": 999, "text": "Array representationLinked list representation" }, { "code": null, "e": 1067, "s": 1046, "text": "Array representation" }, { "code": null, "e": 1094, "s": 1067, "text": "Linked list representation" }, { "code": null, "e": 1118, "s": 1094, "text": "Method 1: Using Arrays:" }, { "code": null, "e": 1204, "s": 1118, "text": "2D array is used to represent a sparse matrix in which there are three rows named as " }, { "code": null, "e": 1257, "s": 1204, "text": "Row: Index of row, where non-zero element is located" }, { "code": null, "e": 1316, "s": 1257, "text": "Column: Index of column, where non-zero element is located" }, { "code": null, "e": 1385, "s": 1316, "text": "Value: Value of the non zero element located at index – (row,column)" }, { "code": null, "e": 1401, "s": 1385, "text": "Implementation:" }, { "code": null, "e": 1405, "s": 1401, "text": "C++" }, { "code": null, "e": 1407, "s": 1405, "text": "C" }, { "code": null, "e": 1412, "s": 1407, "text": "Java" }, { "code": null, "e": 1420, "s": 1412, "text": "Python3" }, { "code": null, "e": 1423, "s": 1420, "text": "C#" }, { "code": "// C++ program for Sparse Matrix Representation// using Array#include <iostream>using namespace std; int main(){ // Assume 4x5 sparse matrix int sparseMatrix[4][5] = { {0 , 0 , 3 , 0 , 4 }, {0 , 0 , 5 , 7 , 0 }, {0 , 0 , 0 , 0 , 0 }, {0 , 2 , 6 , 0 , 0 } }; int size = 0; for (int i = 0; i < 4; i++) for (int j = 0; j < 5; j++) if (sparseMatrix[i][j] != 0) size++; // number of columns in compactMatrix (size) must be // equal to number of non - zero elements in // sparseMatrix int compactMatrix[3][size]; // Making of new matrix int k = 0; for (int i = 0; i < 4; i++) for (int j = 0; j < 5; j++) if (sparseMatrix[i][j] != 0) { compactMatrix[0][k] = i; compactMatrix[1][k] = j; compactMatrix[2][k] = sparseMatrix[i][j]; k++; } for (int i=0; i<3; i++) { for (int j=0; j<size; j++) cout <<\" \"<< compactMatrix[i][j]; cout <<\"\\n\"; } return 0;} // this code is contributed by shivanisinghss2110", "e": 2556, "s": 1423, "text": null }, { "code": "// C++ program for Sparse Matrix Representation// using Array#include<stdio.h> int main(){ // Assume 4x5 sparse matrix int sparseMatrix[4][5] = { {0 , 0 , 3 , 0 , 4 }, {0 , 0 , 5 , 7 , 0 }, {0 , 0 , 0 , 0 , 0 }, {0 , 2 , 6 , 0 , 0 } }; int size = 0; for (int i = 0; i < 4; i++) for (int j = 0; j < 5; j++) if (sparseMatrix[i][j] != 0) size++; // number of columns in compactMatrix (size) must be // equal to number of non - zero elements in // sparseMatrix int compactMatrix[3][size]; // Making of new matrix int k = 0; for (int i = 0; i < 4; i++) for (int j = 0; j < 5; j++) if (sparseMatrix[i][j] != 0) { compactMatrix[0][k] = i; compactMatrix[1][k] = j; compactMatrix[2][k] = sparseMatrix[i][j]; k++; } for (int i=0; i<3; i++) { for (int j=0; j<size; j++) printf(\"%d \", compactMatrix[i][j]); printf(\"\\n\"); } return 0;}", "e": 3620, "s": 2556, "text": null }, { "code": "// Java program for Sparse Matrix Representation// using Arrayclass GFG{ public static void main(String[] args) { int sparseMatrix[][] = { {0, 0, 3, 0, 4}, {0, 0, 5, 7, 0}, {0, 0, 0, 0, 0}, {0, 2, 6, 0, 0} }; int size = 0; for (int i = 0; i < 4; i++) { for (int j = 0; j < 5; j++) { if (sparseMatrix[i][j] != 0) { size++; } } } // number of columns in compactMatrix (size) must be // equal to number of non - zero elements in // sparseMatrix int compactMatrix[][] = new int[3][size]; // Making of new matrix int k = 0; for (int i = 0; i < 4; i++) { for (int j = 0; j < 5; j++) { if (sparseMatrix[i][j] != 0) { compactMatrix[0][k] = i; compactMatrix[1][k] = j; compactMatrix[2][k] = sparseMatrix[i][j]; k++; } } } for (int i = 0; i < 3; i++) { for (int j = 0; j < size; j++) { System.out.printf(\"%d \", compactMatrix[i][j]); } System.out.printf(\"\\n\"); } }} /* This code contributed by PrinciRaj1992 */", "e": 5069, "s": 3620, "text": null }, { "code": "# Python program for Sparse Matrix Representation# using arrays # assume a sparse matrix of order 4*5# let assume another matrix compactMatrix# now store the value,row,column of arr1 in sparse matrix compactMatrix sparseMatrix = [[0,0,3,0,4],[0,0,5,7,0],[0,0,0,0,0],[0,2,6,0,0]] # initialize size as 0size = 0 for i in range(4): for j in range(5): if (sparseMatrix[i][j] != 0): size += 1 # number of columns in compactMatrix(size) should# be equal to number of non-zero elements in sparseMatrixrows, cols = (3, size)compactMatrix = [[0 for i in range(cols)] for j in range(rows)] k = 0for i in range(4): for j in range(5): if (sparseMatrix[i][j] != 0): compactMatrix[0][k] = i compactMatrix[1][k] = j compactMatrix[2][k] = sparseMatrix[i][j] k += 1 for i in compactMatrix: print(i) # This code is contributed by MRINALWALIA", "e": 5971, "s": 5069, "text": null }, { "code": "// C# program for Sparse Matrix Representation// using Array using System; class Program { static void Main(string[] args) { // Assume 4x5 sparse matrix int[, ] sparseMatrix = new int[4, 5] { { 0, 0, 3, 0, 4 }, { 0, 0, 5, 7, 0 }, { 0, 0, 0, 0, 0 }, { 0, 2, 6, 0, 0 } }; int size = 0; for (int i = 0; i < 4; i++) for (int j = 0; j < 5; j++) if (sparseMatrix[i, j] != 0) size++; // number of columns in compactMatrix (size) must be // equal to number of non - zero elements in // sparseMatrix int[, ] compactMatrix = new int[3, size]; // Making of new matrix int k = 0; for (int i = 0; i < 4; i++) { for (int j = 0; j < 5; j++) if (sparseMatrix[i, j] != 0) { compactMatrix[0, k] = i; compactMatrix[1, k] = j; compactMatrix[2, k] = sparseMatrix[i, j]; k++; } } for (int i = 0; i < 3; i++) { for (int j = 0; j < size; j++) Console.Write(\" \" + compactMatrix[i, j]); Console.WriteLine(); } }}// This code is contributed by Tapesh(tapeshdua420)", "e": 7339, "s": 5971, "text": null }, { "code": null, "e": 7378, "s": 7339, "text": " 0 0 1 1 3 3\n 2 4 2 3 1 2\n 3 4 5 7 2 6" }, { "code": null, "e": 7484, "s": 7378, "text": "Method 2: Using Linked ListsIn linked list, each node has four fields. These four fields are defined as: " }, { "code": null, "e": 7537, "s": 7484, "text": "Row: Index of row, where non-zero element is located" }, { "code": null, "e": 7596, "s": 7537, "text": "Column: Index of column, where non-zero element is located" }, { "code": null, "e": 7665, "s": 7596, "text": "Value: Value of the non zero element located at index – (row,column)" }, { "code": null, "e": 7701, "s": 7665, "text": "Next node: Address of the next node" }, { "code": null, "e": 7705, "s": 7701, "text": "C++" }, { "code": null, "e": 7707, "s": 7705, "text": "C" }, { "code": null, "e": 7712, "s": 7707, "text": "Java" }, { "code": null, "e": 7720, "s": 7712, "text": "Python3" }, { "code": null, "e": 7723, "s": 7720, "text": "C#" }, { "code": "// C++ program for sparse matrix representation.// Using Link list#include<iostream>using namespace std; // Node class to represent link listclass Node{ public: int row; int col; int data; Node *next;}; // Function to create new nodevoid create_new_node(Node **p, int row_index, int col_index, int x){ Node *temp = *p; Node *r; // If link list is empty then // create first node and assign value. if (temp == NULL) { temp = new Node(); temp->row = row_index; temp->col = col_index; temp->data = x; temp->next = NULL; *p = temp; } // If link list is already created // then append newly created node else { while (temp->next != NULL) temp = temp->next; r = new Node(); r->row = row_index; r->col = col_index; r->data = x; r->next = NULL; temp->next = r; }} // Function prints contents of linked list// starting from startvoid printList(Node *start){ Node *ptr = start; cout << \"row_position:\"; while (ptr != NULL) { cout << ptr->row << \" \"; ptr = ptr->next; } cout << endl; cout << \"column_position:\"; ptr = start; while (ptr != NULL) { cout << ptr->col << \" \"; ptr = ptr->next; } cout << endl; cout << \"Value:\"; ptr = start; while (ptr != NULL) { cout << ptr->data << \" \"; ptr = ptr->next; }} // Driver Codeint main(){ // 4x5 sparse matrix int sparseMatrix[4][5] = { { 0 , 0 , 3 , 0 , 4 }, { 0 , 0 , 5 , 7 , 0 }, { 0 , 0 , 0 , 0 , 0 }, { 0 , 2 , 6 , 0 , 0 } }; // Creating head/first node of list as NULL Node *first = NULL; for(int i = 0; i < 4; i++) { for(int j = 0; j < 5; j++) { // Pass only those values which // are non - zero if (sparseMatrix[i][j] != 0) create_new_node(&first, i, j, sparseMatrix[i][j]); } } printList(first); return 0;} // This code is contributed by ronaksuba", "e": 9948, "s": 7723, "text": null }, { "code": "// C program for Sparse Matrix Representation// using Linked Lists#include<stdio.h>#include<stdlib.h> // Node to represent sparse matrixstruct Node{ int value; int row_position; int column_postion; struct Node *next;}; // Function to create new nodevoid create_new_node(struct Node** start, int non_zero_element, int row_index, int column_index ){ struct Node *temp, *r; temp = *start; if (temp == NULL) { // Create new node dynamically temp = (struct Node *) malloc (sizeof(struct Node)); temp->value = non_zero_element; temp->row_position = row_index; temp->column_postion = column_index; temp->next = NULL; *start = temp; } else { while (temp->next != NULL) temp = temp->next; // Create new node dynamically r = (struct Node *) malloc (sizeof(struct Node)); r->value = non_zero_element; r->row_position = row_index; r->column_postion = column_index; r->next = NULL; temp->next = r; }} // This function prints contents of linked list// starting from startvoid PrintList(struct Node* start){ struct Node *temp, *r, *s; temp = r = s = start; printf(\"row_position: \"); while(temp != NULL) { printf(\"%d \", temp->row_position); temp = temp->next; } printf(\"\\n\"); printf(\"column_postion: \"); while(r != NULL) { printf(\"%d \", r->column_postion); r = r->next; } printf(\"\\n\"); printf(\"Value: \"); while(s != NULL) { printf(\"%d \", s->value); s = s->next; } printf(\"\\n\");} // Driver of the programint main(){ // Assume 4x5 sparse matrix int sparseMatric[4][5] = { {0 , 0 , 3 , 0 , 4 }, {0 , 0 , 5 , 7 , 0 }, {0 , 0 , 0 , 0 , 0 }, {0 , 2 , 6 , 0 , 0 } }; /* Start with the empty list */ struct Node* start = NULL; for (int i = 0; i < 4; i++) for (int j = 0; j < 5; j++) // Pass only those values which are non - zero if (sparseMatric[i][j] != 0) create_new_node(&start, sparseMatric[i][j], i, j); PrintList(start); return 0;}", "e": 12138, "s": 9948, "text": null }, { "code": "// Java program for sparse matrix representation.// Using Link listimport java.util.*; public class SparseMatrix { // Creating head/first node of list as NULL static Node first = null; // Node class to represent link list public static class Node { int row; int col; int data; Node next; }; // Driver Code public static void main(String[] args) { // 4x5 sparse matrix int[][] sparseMatrix = { { 0, 0, 3, 0, 4 }, { 0, 0, 5, 7, 0 }, { 0, 0, 0, 0, 0 }, { 0, 2, 6, 0, 0 } }; for (int i = 0; i < 4; i++) { for (int j = 0; j < 5; j++) { // Pass only those values which // are non - zero if (sparseMatrix[i][j] != 0) { create_new_node(i, j, sparseMatrix[i][j]); } } } printList(first); } // Function to create new node private static void create_new_node(int row_index, int col_index, int x) { Node temp = first; Node r; // If link list is empty then // create first node and assign value. if (temp == null) { temp = new Node(); temp.row = row_index; temp.col = col_index; temp.data = x; temp.next = null; first = temp; } // If link list is already created // then append newly created node else { while (temp.next != null) temp = temp.next; r = new Node(); r.row = row_index; r.col = col_index; r.data = x; r.next = null; temp.next = r; } } // Function prints contents of linked list // starting from start public static void printList(Node start) { Node ptr = start; System.out.print(\"row_position:\"); while (ptr != null) { System.out.print(ptr.row + \" \"); ptr = ptr.next; } System.out.println(\"\"); System.out.print(\"column_position:\"); ptr = start; while (ptr != null) { System.out.print(ptr.col + \" \"); ptr = ptr.next; } System.out.println(\"\"); System.out.print(\"Value:\"); ptr = start; while (ptr != null) { System.out.print(ptr.data + \" \"); ptr = ptr.next; } }} // This code is contributed by Tapesh (tapeshdua420)", "e": 14704, "s": 12138, "text": null }, { "code": "# Python Program for Representation of# Sparse Matrix into Linked List # Node Class to represent Linked List Nodeclass Node: # Making the slots for storing row, # column, value, and address __slots__ = \"row\", \"col\", \"data\", \"next\" # Constructor to initialize the values def __init__(self, row=0, col=0, data=0, next=None): self.row = row self.col = col self.data = data self.next = next # Class to convert Sparse Matrix# into Linked Listclass Sparse: # Initialize Class Variables def __init__(self): self.head = None self.temp = None self.size = 0 # Function which returns the size # of the Linked List def __len__(self): return self.size # Check the Linked List is # Empty or not def isempty(self): return self.size == 0 # Responsible function to create # Linked List from Sparse Matrix def create_new_node(self, row, col, data): # Creating New Node newNode = Node(row, col, data, None) # Check whether the List is # empty or not if self.isempty(): self.head = newNode else: self.temp.next = newNode self.temp = newNode # Incrementing the size self.size += 1 # Function display the contents of # Linked List def PrintList(self): temp = r = s = self.head print(\"row_position:\", end=\" \") while temp != None: print(temp.row, end=\" \") temp = temp.next print() print(\"column_postion:\", end=\" \") while r != None: print(r.col, end=\" \") r = r.next print() print(\"Value:\", end=\" \") while s != None: print(s.data, end=\" \") s = s.next print() # Driver Codeif __name__ == \"__main__\": # Creating Object s = Sparse() # Assuming 4x5 Sparse Matrix sparseMatric = [[0, 0, 3, 0, 4], [0, 0, 5, 7, 0], [0, 0, 0, 0, 0], [0, 2, 6, 0, 0]] for i in range(4): for j in range(5): # Creating Linked List by only those # elements which are non-zero if sparseMatric[i][j] != 0: s.create_new_node(i, j, sparseMatric[i][j]) # Printing the Linked List Representation # of the sparse matrix s.PrintList() # This code is contributed by Naveen Rathore", "e": 17119, "s": 14704, "text": null }, { "code": "// C# program for sparse matrix representation.// Using Link listusing System; class Program{ // Creating head/first node of list as NULL static Node first = null; // Node class to represent link list public class Node { public int row; public int col; public int data; public Node next; }; // Driver Code static void Main(string[] args) { // 4x5 sparse matrix int[, ] sparseMatrix = { { 0, 0, 3, 0, 4 }, { 0, 0, 5, 7, 0 }, { 0, 0, 0, 0, 0 }, { 0, 2, 6, 0, 0 } }; for (int i = 0; i < 4; i++) { for (int j = 0; j < 5; j++) { // Pass only those values which // are non - zero if (sparseMatrix[i, j] != 0) { create_new_node(i, j, sparseMatrix[i, j]); } } } printList(first); } // Function to create new node private static void create_new_node(int row_index, int col_index, int x) { Node temp = first; Node r; // If link list is empty then // create first node and assign value. if (temp == null) { temp = new Node(); temp.row = row_index; temp.col = col_index; temp.data = x; temp.next = null; first = temp; } // If link list is already created // then append newly created node else { while (temp.next != null) temp = temp.next; r = new Node(); r.row = row_index; r.col = col_index; r.data = x; r.next = null; temp.next = r; } } // Function prints contents of linked list // starting from start public static void printList(Node start) { Node ptr = start; Console.Write(\"row_position:\"); while (ptr != null) { Console.Write(ptr.row + \" \"); ptr = ptr.next; } Console.WriteLine(\"\"); Console.Write(\"column_position:\"); ptr = start; while (ptr != null) { Console.Write(ptr.col + \" \"); ptr = ptr.next; } Console.WriteLine(\"\"); Console.Write(\"Value:\"); ptr = start; while (ptr != null) { Console.Write(ptr.data + \" \"); ptr = ptr.next; } }} // This code is contributed by Tapesh (tapeshdua420)", "e": 19668, "s": 17119, "text": null }, { "code": null, "e": 19742, "s": 19668, "text": "row_position:0 0 1 1 3 3 \ncolumn_position:2 4 2 3 1 2 \nValue:3 4 5 7 2 6 " }, { "code": null, "e": 19766, "s": 19742, "text": "Other representations: " }, { "code": null, "e": 19925, "s": 19766, "text": "As a Dictionary where row and column numbers are used as keys and values are matrix entries. This method saves space but sequential access of items is costly." }, { "code": null, "e": 20158, "s": 19925, "text": "As a list of list. The idea is to make a list of rows and every item of list contains values. We can keep list items sorted by column numbers.Sparse Matrix and its representations | Set 2 (Using List of Lists and Dictionary of keys)" }, { "code": null, "e": 20452, "s": 20158, "text": "This article is contributed by Akash Gupta.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": 20466, "s": 20452, "text": "princiraj1992" }, { "code": null, "e": 20478, "s": 20466, "text": "MRINALWALIA" }, { "code": null, "e": 20492, "s": 20478, "text": "rathorenav123" }, { "code": null, "e": 20502, "s": 20492, "text": "ronaksuba" }, { "code": null, "e": 20521, "s": 20502, "text": "shivanisinghss2110" }, { "code": null, "e": 20534, "s": 20521, "text": "tapeshdua420" }, { "code": null, "e": 20551, "s": 20534, "text": "hardikkoriintern" }, { "code": null, "e": 20559, "s": 20551, "text": "c-array" }, { "code": null, "e": 20566, "s": 20559, "text": "Matrix" }, { "code": null, "e": 20573, "s": 20566, "text": "Matrix" } ]
matplotlib.pyplot.imshow() in Python
22 Apr, 2020 Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. Pyplot is a state-based interface to a Matplotlib module which provides a MATLAB-like interface. The imshow() function in pyplot module of matplotlib library is used to display data as an image; i.e. on a 2D regular raster. Syntax: matplotlib.pyplot.imshow(X, cmap=None, norm=None, aspect=None, interpolation=None, alpha=None, vmin=None, vmax=None, origin=None, extent=None, shape=, filternorm=1, filterrad=4.0, imlim=, resample=None, url=None, \*, data=None, \*\*kwargs) Parameters: This method accept the following parameters that are described below: X: This parameter is the data of the image. cmap : This parameter is a colormap instance or registered colormap name. norm : This parameter is the Normalize instance scales the data values to the canonical colormap range [0, 1] for mapping to colors vmin, vmax : These parameter are optional in nature and they are colorbar range. alpha : This parameter is a intensity of the color. aspect : This parameter is used to controls the aspect ratio of the axes. interpolation : This parameter is the interpolation method which used to display an image. origin : This parameter is used to place the [0, 0] index of the array in the upper left or lower left corner of the axes. resample : This parameter is the method which is used for resembling. extent : This parameter is the bounding box in data coordinates. filternorm : This parameter is used for the antigrain image resize filter. filterrad : This parameter is the filter radius for filters that have a radius parameter. url : This parameter sets the url of the created AxesImage. Returns: This returns the following: image : This returns the AxesImage Below examples illustrate the matplotlib.pyplot.imshow() function in matplotlib.pyplot: Example #1: # Implementation of matplotlib functionimport matplotlib.pyplot as pltimport numpy as npfrom matplotlib.colors import LogNorm dx, dy = 0.015, 0.05y, x = np.mgrid[slice(-4, 4 + dy, dy), slice(-4, 4 + dx, dx)]z = (1 - x / 3. + x ** 5 + y ** 5) * np.exp(-x ** 2 - y ** 2)z = z[:-1, :-1]z_min, z_max = -np.abs(z).max(), np.abs(z).max() c = plt.imshow(z, cmap ='Greens', vmin = z_min, vmax = z_max, extent =[x.min(), x.max(), y.min(), y.max()], interpolation ='nearest', origin ='lower')plt.colorbar(c) plt.title('matplotlib.pyplot.imshow() function Example', fontweight ="bold")plt.show() Output: Example #2: # Implementation of matplotlib functionimport matplotlib.pyplot as pltimport numpy as npfrom matplotlib.colors import LogNorm dx, dy = 0.015, 0.05x = np.arange(-4.0, 4.0, dx)y = np.arange(-4.0, 4.0, dy)X, Y = np.meshgrid(x, y) extent = np.min(x), np.max(x), np.min(y), np.max(y) Z1 = np.add.outer(range(8), range(8)) % 2plt.imshow(Z1, cmap ="binary_r", interpolation ='nearest', extent = extent, alpha = 1) def geeks(x, y): return (1 - x / 2 + x**5 + y**6) * np.exp(-(x**2 + y**2)) Z2 = geeks(X, Y) plt.imshow(Z2, cmap ="Greens", alpha = 0.7, interpolation ='bilinear', extent = extent) plt.title('matplotlib.pyplot.imshow() function Example', fontweight ="bold")plt.show() Output: Python-matplotlib Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. 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 Convert integer to string in Python Python OOPs Concepts Python | os.path.join() method Introduction To PYTHON
[ { "code": null, "e": 52, "s": 24, "text": "\n22 Apr, 2020" }, { "code": null, "e": 247, "s": 52, "text": "Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. Pyplot is a state-based interface to a Matplotlib module which provides a MATLAB-like interface." }, { "code": null, "e": 374, "s": 247, "text": "The imshow() function in pyplot module of matplotlib library is used to display data as an image; i.e. on a 2D regular raster." }, { "code": null, "e": 622, "s": 374, "text": "Syntax: matplotlib.pyplot.imshow(X, cmap=None, norm=None, aspect=None, interpolation=None, alpha=None, vmin=None, vmax=None, origin=None, extent=None, shape=, filternorm=1, filterrad=4.0, imlim=, resample=None, url=None, \\*, data=None, \\*\\*kwargs)" }, { "code": null, "e": 704, "s": 622, "text": "Parameters: This method accept the following parameters that are described below:" }, { "code": null, "e": 748, "s": 704, "text": "X: This parameter is the data of the image." }, { "code": null, "e": 822, "s": 748, "text": "cmap : This parameter is a colormap instance or registered colormap name." }, { "code": null, "e": 954, "s": 822, "text": "norm : This parameter is the Normalize instance scales the data values to the canonical colormap range [0, 1] for mapping to colors" }, { "code": null, "e": 1035, "s": 954, "text": "vmin, vmax : These parameter are optional in nature and they are colorbar range." }, { "code": null, "e": 1087, "s": 1035, "text": "alpha : This parameter is a intensity of the color." }, { "code": null, "e": 1161, "s": 1087, "text": "aspect : This parameter is used to controls the aspect ratio of the axes." }, { "code": null, "e": 1252, "s": 1161, "text": "interpolation : This parameter is the interpolation method which used to display an image." }, { "code": null, "e": 1375, "s": 1252, "text": "origin : This parameter is used to place the [0, 0] index of the array in the upper left or lower left corner of the axes." }, { "code": null, "e": 1445, "s": 1375, "text": "resample : This parameter is the method which is used for resembling." }, { "code": null, "e": 1510, "s": 1445, "text": "extent : This parameter is the bounding box in data coordinates." }, { "code": null, "e": 1585, "s": 1510, "text": "filternorm : This parameter is used for the antigrain image resize filter." }, { "code": null, "e": 1675, "s": 1585, "text": "filterrad : This parameter is the filter radius for filters that have a radius parameter." }, { "code": null, "e": 1735, "s": 1675, "text": "url : This parameter sets the url of the created AxesImage." }, { "code": null, "e": 1772, "s": 1735, "text": "Returns: This returns the following:" }, { "code": null, "e": 1807, "s": 1772, "text": "image : This returns the AxesImage" }, { "code": null, "e": 1895, "s": 1807, "text": "Below examples illustrate the matplotlib.pyplot.imshow() function in matplotlib.pyplot:" }, { "code": null, "e": 1907, "s": 1895, "text": "Example #1:" }, { "code": "# Implementation of matplotlib functionimport matplotlib.pyplot as pltimport numpy as npfrom matplotlib.colors import LogNorm dx, dy = 0.015, 0.05y, x = np.mgrid[slice(-4, 4 + dy, dy), slice(-4, 4 + dx, dx)]z = (1 - x / 3. + x ** 5 + y ** 5) * np.exp(-x ** 2 - y ** 2)z = z[:-1, :-1]z_min, z_max = -np.abs(z).max(), np.abs(z).max() c = plt.imshow(z, cmap ='Greens', vmin = z_min, vmax = z_max, extent =[x.min(), x.max(), y.min(), y.max()], interpolation ='nearest', origin ='lower')plt.colorbar(c) plt.title('matplotlib.pyplot.imshow() function Example', fontweight =\"bold\")plt.show()", "e": 2586, "s": 1907, "text": null }, { "code": null, "e": 2594, "s": 2586, "text": "Output:" }, { "code": null, "e": 2606, "s": 2594, "text": "Example #2:" }, { "code": "# Implementation of matplotlib functionimport matplotlib.pyplot as pltimport numpy as npfrom matplotlib.colors import LogNorm dx, dy = 0.015, 0.05x = np.arange(-4.0, 4.0, dx)y = np.arange(-4.0, 4.0, dy)X, Y = np.meshgrid(x, y) extent = np.min(x), np.max(x), np.min(y), np.max(y) Z1 = np.add.outer(range(8), range(8)) % 2plt.imshow(Z1, cmap =\"binary_r\", interpolation ='nearest', extent = extent, alpha = 1) def geeks(x, y): return (1 - x / 2 + x**5 + y**6) * np.exp(-(x**2 + y**2)) Z2 = geeks(X, Y) plt.imshow(Z2, cmap =\"Greens\", alpha = 0.7, interpolation ='bilinear', extent = extent) plt.title('matplotlib.pyplot.imshow() function Example', fontweight =\"bold\")plt.show()", "e": 3377, "s": 2606, "text": null }, { "code": null, "e": 3385, "s": 3377, "text": "Output:" }, { "code": null, "e": 3403, "s": 3385, "text": "Python-matplotlib" }, { "code": null, "e": 3410, "s": 3403, "text": "Python" }, { "code": null, "e": 3508, "s": 3410, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3550, "s": 3508, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 3572, "s": 3550, "text": "Enumerate() in Python" }, { "code": null, "e": 3598, "s": 3572, "text": "Python String | replace()" }, { "code": null, "e": 3630, "s": 3598, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 3659, "s": 3630, "text": "*args and **kwargs in Python" }, { "code": null, "e": 3686, "s": 3659, "text": "Python Classes and Objects" }, { "code": null, "e": 3722, "s": 3686, "text": "Convert integer to string in Python" }, { "code": null, "e": 3743, "s": 3722, "text": "Python OOPs Concepts" }, { "code": null, "e": 3774, "s": 3743, "text": "Python | os.path.join() method" } ]
Python | Working with .docx module
07 Jul, 2018 Word documents contain formatted text wrapped within three object levels. Lowest level- Run objects, Middle level- Paragraph objects and Highest level- Document object.So, we cannot work with these documents using normal text editors. But, we can manipulate these word documents in python using the python-docx module. 1. The first step is to install this third-party module python-docx. You can use pip “pip install python-docx” or download the tarball from here. Here’s the Github repository. 2. After installation import “docx” NOT “python-docx”.3. Use “docx.Document” class to start working with the word document. Code #1: # import docx NOT python-docximport docx # create an instance of a word documentdoc = docx.Document() # add a heading of level 0 (largest heading)doc.add_heading('Heading for the document', 0) # add a paragraph and store # the object in a variabledoc_para = doc.add_paragraph('Your paragraph goes here, ') # add a run i.e, style like # bold, italic, underline, etc.doc_para.add_run('hey there, bold here').bold = Truedoc_para.add_run(', and ')doc_para.add_run('these words are italic').italic = True # add a page break to start a new pagedoc.add_page_break() # add a heading of level 2doc.add_heading('Heading level 2', 2) # pictures can also be added to our word document# width is optionaldoc.add_picture('path_to_picture') # now save the document to a locationdoc.save('path_to_document') Output: Notice the page break in the second page. Code #2: Now, to open a word document, create an instance along with passing the path to the document. # import the Document class # from the docx modulefrom docx import Document # create an instance of a # word document we want to opendoc = Document('path_to_the_document') # print the list of paragraphs in the documentprint('List of paragraph objects:->>>')print(doc.paragraphs) # print the list of the runs # in a specified paragraphprint('\nList of runs objects in 1st paragraph:->>>')print(doc.paragraphs[0].runs) # print the text in a paragraph print('\nText in the 1st paragraph:->>>')print(doc.paragraphs[0].text) # for printing the complete documentprint('\nThe whole content of the document:->>>\n')for para in doc.paragraphs: print(para.text) Output: List of paragraph objects:->>> [<docx.text.paragraph.Paragraph object at 0x7f45b22dc128>, <docx.text.paragraph.Paragraph object at 0x7f45b22dc5c0>, <docx.text.paragraph.Paragraph object at 0x7f45b22dc0b8>, <docx.text.paragraph.Paragraph object at 0x7f45b22dc198>, <docx.text.paragraph.Paragraph object at 0x7f45b22dc0f0>] List of runs objects in 1st paragraph:->>> [<docx.text.run.Run object at 0x7f45b22dc198>] Text in the 1st paragraph:->>> Heading for the document The whole content of the document:->>> Heading for the document Your paragraph goes here, hey there, bold here, and these words are italic Heading level 2 Reference: https://python-docx.readthedocs.io/en/latest/#user-guide. Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n07 Jul, 2018" }, { "code": null, "e": 373, "s": 54, "text": "Word documents contain formatted text wrapped within three object levels. Lowest level- Run objects, Middle level- Paragraph objects and Highest level- Document object.So, we cannot work with these documents using normal text editors. But, we can manipulate these word documents in python using the python-docx module." }, { "code": null, "e": 549, "s": 373, "text": "1. The first step is to install this third-party module python-docx. You can use pip “pip install python-docx” or download the tarball from here. Here’s the Github repository." }, { "code": null, "e": 673, "s": 549, "text": "2. After installation import “docx” NOT “python-docx”.3. Use “docx.Document” class to start working with the word document." }, { "code": null, "e": 682, "s": 673, "text": "Code #1:" }, { "code": "# import docx NOT python-docximport docx # create an instance of a word documentdoc = docx.Document() # add a heading of level 0 (largest heading)doc.add_heading('Heading for the document', 0) # add a paragraph and store # the object in a variabledoc_para = doc.add_paragraph('Your paragraph goes here, ') # add a run i.e, style like # bold, italic, underline, etc.doc_para.add_run('hey there, bold here').bold = Truedoc_para.add_run(', and ')doc_para.add_run('these words are italic').italic = True # add a page break to start a new pagedoc.add_page_break() # add a heading of level 2doc.add_heading('Heading level 2', 2) # pictures can also be added to our word document# width is optionaldoc.add_picture('path_to_picture') # now save the document to a locationdoc.save('path_to_document')", "e": 1482, "s": 682, "text": null }, { "code": null, "e": 1490, "s": 1482, "text": "Output:" }, { "code": null, "e": 1635, "s": 1490, "text": "Notice the page break in the second page. Code #2: Now, to open a word document, create an instance along with passing the path to the document." }, { "code": "# import the Document class # from the docx modulefrom docx import Document # create an instance of a # word document we want to opendoc = Document('path_to_the_document') # print the list of paragraphs in the documentprint('List of paragraph objects:->>>')print(doc.paragraphs) # print the list of the runs # in a specified paragraphprint('\\nList of runs objects in 1st paragraph:->>>')print(doc.paragraphs[0].runs) # print the text in a paragraph print('\\nText in the 1st paragraph:->>>')print(doc.paragraphs[0].text) # for printing the complete documentprint('\\nThe whole content of the document:->>>\\n')for para in doc.paragraphs: print(para.text)", "e": 2295, "s": 1635, "text": null }, { "code": null, "e": 2303, "s": 2295, "text": "Output:" }, { "code": null, "e": 2934, "s": 2303, "text": "List of paragraph objects:->>>\n[<docx.text.paragraph.Paragraph object at 0x7f45b22dc128>,\n<docx.text.paragraph.Paragraph object at 0x7f45b22dc5c0>,\n<docx.text.paragraph.Paragraph object at 0x7f45b22dc0b8>,\n<docx.text.paragraph.Paragraph object at 0x7f45b22dc198>,\n<docx.text.paragraph.Paragraph object at 0x7f45b22dc0f0>]\n\nList of runs objects in 1st paragraph:->>>\n[<docx.text.run.Run object at 0x7f45b22dc198>]\n\nText in the 1st paragraph:->>>\nHeading for the document\n\nThe whole content of the document:->>>\n\nHeading for the document\nYour paragraph goes here, hey there, bold here, and these words are italic\n\n\nHeading level 2\n\n" }, { "code": null, "e": 3003, "s": 2934, "text": "Reference: https://python-docx.readthedocs.io/en/latest/#user-guide." }, { "code": null, "e": 3019, "s": 3003, "text": "Python Programs" } ]
PHP | startsWith() and endsWith() Functions
31 Jul, 2021 startsWith() Function The StartsWith() function is used to test whether a string begins with the given string or not. This function is case insensitive and it returns boolean value. This function can be used with Filter function to search the data.Syntax bool startsWith( string, startString ) Parameters: This function accepts two parameters as mentioned above and described below: string: This parameter is used to hold the text which need to test. startString: The text to search at the beginning of String. If it is an empty string, then it returns true. Return Value: This function returns True on success or False on failure.Example 1: <?php // Function to check string starting// with given substringfunction startsWith ($string, $startString){ $len = strlen($startString); return (substr($string, 0, $len) === $startString);} // Main functionif(startsWith("abcde","c")) echo "True";else echo "False";?> False Example 2: <?php // Function to check string starting// with given substringfunction startsWith ($string, $startString){ $len = strlen($startString); return (substr($string, 0, $len) === $startString);} // Main functionif(startsWith("abcde","a")) echo "True";else echo "False";?> True endsWith() Function The endsWith() function is used to test whether a string ends with the given string or not. This function is case insensitive and it returns boolean value. The endsWith() function can be used with the Filter function to search the data. Syntax: bool endsWith( string, endString ) Parameter: string: This parameter holds the text which need to test. endString: The text to search at the end of given String. If is an empty string, it returns true. Return Value: This function returns True on success or False on failure. Example 1: <?php // Function to check the string is ends // with given substring or notfunction endsWith($string, $endString){ $len = strlen($endString); if ($len == 0) { return true; } return (substr($string, -$len) === $endString);} // Driver codeif(endsWith("abcde","de")) echo "True";else echo "False";?> True Example 2: <?php // Function to check the string is ends // with given substring or notfunction endsWith($string, $endString){ $len = strlen($endString); if ($len == 0) { return true; } return (substr($string, -$len) === $endString);} // Driver codeif(endsWith("abcde","dgfe")) echo "True";else echo "False";?> False PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples. snarfblam PHP-function Picked PHP Web Technologies PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Insert Form Data into Database using PHP ? How to convert array to string in PHP ? How to Upload Image into Database and Display it using PHP ? How to check whether an array is empty using PHP? PHP | Converting string to Date and DateTime Top 10 Projects For Beginners To Practice HTML and CSS Skills Installation of Node.js on Linux 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": "\n31 Jul, 2021" }, { "code": null, "e": 50, "s": 28, "text": "startsWith() Function" }, { "code": null, "e": 283, "s": 50, "text": "The StartsWith() function is used to test whether a string begins with the given string or not. This function is case insensitive and it returns boolean value. This function can be used with Filter function to search the data.Syntax" }, { "code": null, "e": 322, "s": 283, "text": "bool startsWith( string, startString )" }, { "code": null, "e": 411, "s": 322, "text": "Parameters: This function accepts two parameters as mentioned above and described below:" }, { "code": null, "e": 479, "s": 411, "text": "string: This parameter is used to hold the text which need to test." }, { "code": null, "e": 587, "s": 479, "text": "startString: The text to search at the beginning of String. If it is an empty string, then it returns true." }, { "code": null, "e": 670, "s": 587, "text": "Return Value: This function returns True on success or False on failure.Example 1:" }, { "code": "<?php // Function to check string starting// with given substringfunction startsWith ($string, $startString){ $len = strlen($startString); return (substr($string, 0, $len) === $startString);} // Main functionif(startsWith(\"abcde\",\"c\")) echo \"True\";else echo \"False\";?> ", "e": 954, "s": 670, "text": null }, { "code": null, "e": 961, "s": 954, "text": "False\n" }, { "code": null, "e": 972, "s": 961, "text": "Example 2:" }, { "code": "<?php // Function to check string starting// with given substringfunction startsWith ($string, $startString){ $len = strlen($startString); return (substr($string, 0, $len) === $startString);} // Main functionif(startsWith(\"abcde\",\"a\")) echo \"True\";else echo \"False\";?> ", "e": 1256, "s": 972, "text": null }, { "code": null, "e": 1262, "s": 1256, "text": "True\n" }, { "code": null, "e": 1282, "s": 1262, "text": "endsWith() Function" }, { "code": null, "e": 1519, "s": 1282, "text": "The endsWith() function is used to test whether a string ends with the given string or not. This function is case insensitive and it returns boolean value. The endsWith() function can be used with the Filter function to search the data." }, { "code": null, "e": 1527, "s": 1519, "text": "Syntax:" }, { "code": null, "e": 1562, "s": 1527, "text": "bool endsWith( string, endString )" }, { "code": null, "e": 1573, "s": 1562, "text": "Parameter:" }, { "code": null, "e": 1631, "s": 1573, "text": "string: This parameter holds the text which need to test." }, { "code": null, "e": 1729, "s": 1631, "text": "endString: The text to search at the end of given String. If is an empty string, it returns true." }, { "code": null, "e": 1802, "s": 1729, "text": "Return Value: This function returns True on success or False on failure." }, { "code": null, "e": 1813, "s": 1802, "text": "Example 1:" }, { "code": "<?php // Function to check the string is ends // with given substring or notfunction endsWith($string, $endString){ $len = strlen($endString); if ($len == 0) { return true; } return (substr($string, -$len) === $endString);} // Driver codeif(endsWith(\"abcde\",\"de\")) echo \"True\";else echo \"False\";?> ", "e": 2139, "s": 1813, "text": null }, { "code": null, "e": 2145, "s": 2139, "text": "True\n" }, { "code": null, "e": 2156, "s": 2145, "text": "Example 2:" }, { "code": "<?php // Function to check the string is ends // with given substring or notfunction endsWith($string, $endString){ $len = strlen($endString); if ($len == 0) { return true; } return (substr($string, -$len) === $endString);} // Driver codeif(endsWith(\"abcde\",\"dgfe\")) echo \"True\";else echo \"False\";?> ", "e": 2484, "s": 2156, "text": null }, { "code": null, "e": 2491, "s": 2484, "text": "False\n" }, { "code": null, "e": 2660, "s": 2491, "text": "PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples." }, { "code": null, "e": 2670, "s": 2660, "text": "snarfblam" }, { "code": null, "e": 2683, "s": 2670, "text": "PHP-function" }, { "code": null, "e": 2690, "s": 2683, "text": "Picked" }, { "code": null, "e": 2694, "s": 2690, "text": "PHP" }, { "code": null, "e": 2711, "s": 2694, "text": "Web Technologies" }, { "code": null, "e": 2715, "s": 2711, "text": "PHP" }, { "code": null, "e": 2813, "s": 2715, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2863, "s": 2813, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 2903, "s": 2863, "text": "How to convert array to string in PHP ?" }, { "code": null, "e": 2964, "s": 2903, "text": "How to Upload Image into Database and Display it using PHP ?" }, { "code": null, "e": 3014, "s": 2964, "text": "How to check whether an array is empty using PHP?" }, { "code": null, "e": 3059, "s": 3014, "text": "PHP | Converting string to Date and DateTime" }, { "code": null, "e": 3121, "s": 3059, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 3154, "s": 3121, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 3215, "s": 3154, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 3265, "s": 3215, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Rock, Paper and Scissor Game using Javascript
06 Jan, 2022 Introduction : Rock, paper, and scissors game is a simple fun game in which both the players have to make a rock, paper, or scissors. It has only two possible outcomes a draw, or a win for one player and a loss for the other player. We will be designing the game using JavaScript where a player will be playing against the computer. In total there will be 10 moves. The player has to choose one option among the rock, paper, and scissors. A random option will be generated from the computer’s side and the one who wins will get one point every time. After 10 moves are over the final result will be displayed on the screen with a button to restart the game. The game will be completely responsive so that it can be played on every device. The HTML Layout: HTML gives the basic structure of the game. styles.css file is linked in the head tag which will be used for styling the HTML. Description of elements use in code is below: A div with the class title is used to display the title on the screen. A div with a class score contains two more div which will display the score of the player and computer. Div with the class move just displays a text and div with class movesleft will show the number of moves left before the game ends. A div with a class option contains three button rock, paper, and scissors which the user can use to give the input. A div with the class result will display the result of every move and the final result after 10 moves and the button with class reload will allow reloading the game. Filename: index.html HTML <!-- index.html --> <!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="styles.css"> <title>Rock Paper Scissor</title></head><body> <section class="game"> <!--Title --> <div class="title">Rock Paper Scissor</div> <!--Display Score of player and computer --> <div class="score"> <div class="playerScore"> <h2>Player</h2> <p class="p-count count">0</p> </div> <div class="computerScore"> <h2>Computer</h2> <p class="c-count count">0</p> </div> </div> <div class="move">Choose your move</div> <!--Number of moves left before game ends --> <div class="movesleft">Moves Left: 10 </div> <!--Options available to player to play game --> <div class="options"> <button class="rock">Rock</button> <button class="paper">Paper</button> <button class="scissor">Scissors</button> </div> <!--Final result of game --> <div class="result"></div> <!--Reload the game --> <button class="reload"></button> </section> <script src="app.js"></script></body></html> The CSS Styling: This styling is used for the game. You can change the styles as per your needs. Filename: styles.css CSS /* styles.css *//* universal selector - Applies to whole document */*{ padding: 0; margin: 0; box-sizing: border-box; background: #082c6c; color: #fff;}/* To center everything in game */.game{ display: flex; flex-direction: column; height: 100vh; width: 100vw; justify-content: center; align-items: center;} /* Title of the game */.title{ position: absolute; top: 0; font-size: 4rem; z-index: 2;} /* Score Board */.score{ display: flex; width: 30vw; justify-content: space-evenly; position: absolute; top: 70px; z-index: 1;} /* Score */.p-count,.c-count{ text-align: center; font-size: 1.5rem; margin-top: 1rem;} /* displaying three buttons in one line */.options{ display: flex; width: 50vw; justify-content: space-evenly; margin-top: 2rem;} /* Styling on all three buttons */.rock, .paper, .scissor{ padding: 0.8rem; width: 100px; border-radius: 10px; background: green; outline: none; border-color: green; border: none; cursor: pointer;} .move{ font-size: 2rem; font-weight: bold;} /* Reload button style */.reload { display: none; margin-top: 2rem; padding: 1rem; background: green; outline: none; border: none; border-radius: 10px; cursor: pointer;} .result{ margin-top: 20px; font-size: 1.2rem;} /* Responsive Design */@media screen and (max-width: 612px){ .title{ text-align: center; } .score{ position: absolute; top: 200px; width: 100vw; } .options{ width: 100vw; } The logic using JavaScript: The main logic of the game is created by using JavaScript. We will be performing DOM manipulation so basic knowledge of JavaScript is enough to build the game. Follow steps Create a function game() that will contain all the logic of the game. Inside the function declare three variables playerScore, computerScore, moves which will keep the record of the player’s score, computer’s score, and moves completed respectively. Create a function playGame() and inside the function use DOM manipulation to get hold of all the three buttons we created in HTML for player input. Create an array playerOptions which will contain all three buttons as its elements. Similarly, create an array for computer options. Use forEach() loop on playerOptions so that we can add an event listener on all buttons with a single piece of code. Inside the loop increment moves counter by 1 display moves left on the screen by subtracting moves from 10. Generate a random value for the computer option and compare it with the player’s input. Create a function winner() which will receive two arguments one the player’s input and the other the computer’s option The function will decide who wins the point among the player and computer. Create a function gameOver() which will display the final result with reload button. The function will be called when moves will become equals to 10. Call the playGame() function inside the game() function. Now call the game() function at the end of the file. Below is the implementation: Filename: app.js Javascript // app.js // Complete logic of game inside this functionconst game = () => { let playerScore = 0; let computerScore = 0; let moves = 0; // Function to const playGame = () => { const rockBtn = document.querySelector('.rock'); const paperBtn = document.querySelector('.paper'); const scissorBtn = document.querySelector('.scissor'); const playerOptions = [rockBtn,paperBtn,scissorBtn]; const computerOptions = ['rock','paper','scissors'] // Function to start playing game playerOptions.forEach(option => { option.addEventListener('click',function(){ const movesLeft = document.querySelector('.movesleft'); moves++; movesLeft.innerText = `Moves Left: ${10-moves}`; const choiceNumber = Math.floor(Math.random()*3); const computerChoice = computerOptions[choiceNumber]; // Function to check who wins winner(this.innerText,computerChoice) // Calling gameOver function after 10 moves if(moves == 10){ gameOver(playerOptions,movesLeft); } }) }) } // Function to decide winner const winner = (player,computer) => { const result = document.querySelector('.result'); const playerScoreBoard = document.querySelector('.p-count'); const computerScoreBoard = document.querySelector('.c-count'); player = player.toLowerCase(); computer = computer.toLowerCase(); if(player === computer){ result.textContent = 'Tie' } else if(player == 'rock'){ if(computer == 'paper'){ result.textContent = 'Computer Won'; computerScore++; computerScoreBoard.textContent = computerScore; }else{ result.textContent = 'Player Won' playerScore++; playerScoreBoard.textContent = playerScore; } } else if(player == 'scissors'){ if(computer == 'rock'){ result.textContent = 'Computer Won'; computerScore++; computerScoreBoard.textContent = computerScore; }else{ result.textContent = 'Player Won'; playerScore++; playerScoreBoard.textContent = playerScore; } } else if(player == 'paper'){ if(computer == 'scissors'){ result.textContent = 'Computer Won'; computerScore++; computerScoreBoard.textContent = computerScore; }else{ result.textContent = 'Player Won'; playerScore++; playerScoreBoard.textContent = playerScore; } } } // Function to run when game is over const gameOver = (playerOptions,movesLeft) => { const chooseMove = document.querySelector('.move'); const result = document.querySelector('.result'); const reloadBtn = document.querySelector('.reload'); playerOptions.forEach(option => { option.style.display = 'none'; }) chooseMove.innerText = 'Game Over!!' movesLeft.style.display = 'none'; if(playerScore > computerScore){ result.style.fontSize = '2rem'; result.innerText = 'You Won The Game' result.style.color = '#308D46'; } else if(playerScore < computerScore){ result.style.fontSize = '2rem'; result.innerText = 'You Lost The Game'; result.style.color = 'red'; } else{ result.style.fontSize = '2rem'; result.innerText = 'Tie'; result.style.color = 'grey' } reloadBtn.innerText = 'Restart'; reloadBtn.style.display = 'flex' reloadBtn.addEventListener('click',() => { window.location.reload(); }) } // Calling playGame function inside game playGame(); } // Calling the game functiongame(); Output: surinderdawra388 JavaScript-Questions Picked Technical Scripter 2020 JavaScript Technical Scripter Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n06 Jan, 2022" }, { "code": null, "e": 68, "s": 52, "text": "Introduction : " }, { "code": null, "e": 792, "s": 68, "text": "Rock, paper, and scissors game is a simple fun game in which both the players have to make a rock, paper, or scissors. It has only two possible outcomes a draw, or a win for one player and a loss for the other player. We will be designing the game using JavaScript where a player will be playing against the computer. In total there will be 10 moves. The player has to choose one option among the rock, paper, and scissors. A random option will be generated from the computer’s side and the one who wins will get one point every time. After 10 moves are over the final result will be displayed on the screen with a button to restart the game. The game will be completely responsive so that it can be played on every device." }, { "code": null, "e": 809, "s": 792, "text": "The HTML Layout:" }, { "code": null, "e": 936, "s": 809, "text": "HTML gives the basic structure of the game. styles.css file is linked in the head tag which will be used for styling the HTML." }, { "code": null, "e": 982, "s": 936, "text": "Description of elements use in code is below:" }, { "code": null, "e": 1053, "s": 982, "text": "A div with the class title is used to display the title on the screen." }, { "code": null, "e": 1157, "s": 1053, "text": "A div with a class score contains two more div which will display the score of the player and computer." }, { "code": null, "e": 1288, "s": 1157, "text": "Div with the class move just displays a text and div with class movesleft will show the number of moves left before the game ends." }, { "code": null, "e": 1404, "s": 1288, "text": "A div with a class option contains three button rock, paper, and scissors which the user can use to give the input." }, { "code": null, "e": 1570, "s": 1404, "text": "A div with the class result will display the result of every move and the final result after 10 moves and the button with class reload will allow reloading the game." }, { "code": null, "e": 1591, "s": 1570, "text": "Filename: index.html" }, { "code": null, "e": 1596, "s": 1591, "text": "HTML" }, { "code": "<!-- index.html --> <!DOCTYPE html><html lang=\"en\"><head> <meta charset=\"UTF-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"> <link rel=\"stylesheet\" href=\"styles.css\"> <title>Rock Paper Scissor</title></head><body> <section class=\"game\"> <!--Title --> <div class=\"title\">Rock Paper Scissor</div> <!--Display Score of player and computer --> <div class=\"score\"> <div class=\"playerScore\"> <h2>Player</h2> <p class=\"p-count count\">0</p> </div> <div class=\"computerScore\"> <h2>Computer</h2> <p class=\"c-count count\">0</p> </div> </div> <div class=\"move\">Choose your move</div> <!--Number of moves left before game ends --> <div class=\"movesleft\">Moves Left: 10 </div> <!--Options available to player to play game --> <div class=\"options\"> <button class=\"rock\">Rock</button> <button class=\"paper\">Paper</button> <button class=\"scissor\">Scissors</button> </div> <!--Final result of game --> <div class=\"result\"></div> <!--Reload the game --> <button class=\"reload\"></button> </section> <script src=\"app.js\"></script></body></html>", "e": 3013, "s": 1596, "text": null }, { "code": null, "e": 3030, "s": 3013, "text": "The CSS Styling:" }, { "code": null, "e": 3110, "s": 3030, "text": "This styling is used for the game. You can change the styles as per your needs." }, { "code": null, "e": 3131, "s": 3110, "text": "Filename: styles.css" }, { "code": null, "e": 3135, "s": 3131, "text": "CSS" }, { "code": "/* styles.css *//* universal selector - Applies to whole document */*{ padding: 0; margin: 0; box-sizing: border-box; background: #082c6c; color: #fff;}/* To center everything in game */.game{ display: flex; flex-direction: column; height: 100vh; width: 100vw; justify-content: center; align-items: center;} /* Title of the game */.title{ position: absolute; top: 0; font-size: 4rem; z-index: 2;} /* Score Board */.score{ display: flex; width: 30vw; justify-content: space-evenly; position: absolute; top: 70px; z-index: 1;} /* Score */.p-count,.c-count{ text-align: center; font-size: 1.5rem; margin-top: 1rem;} /* displaying three buttons in one line */.options{ display: flex; width: 50vw; justify-content: space-evenly; margin-top: 2rem;} /* Styling on all three buttons */.rock, .paper, .scissor{ padding: 0.8rem; width: 100px; border-radius: 10px; background: green; outline: none; border-color: green; border: none; cursor: pointer;} .move{ font-size: 2rem; font-weight: bold;} /* Reload button style */.reload { display: none; margin-top: 2rem; padding: 1rem; background: green; outline: none; border: none; border-radius: 10px; cursor: pointer;} .result{ margin-top: 20px; font-size: 1.2rem;} /* Responsive Design */@media screen and (max-width: 612px){ .title{ text-align: center; } .score{ position: absolute; top: 200px; width: 100vw; } .options{ width: 100vw; }", "e": 4709, "s": 3135, "text": null }, { "code": null, "e": 4737, "s": 4709, "text": "The logic using JavaScript:" }, { "code": null, "e": 4897, "s": 4737, "text": "The main logic of the game is created by using JavaScript. We will be performing DOM manipulation so basic knowledge of JavaScript is enough to build the game." }, { "code": null, "e": 4911, "s": 4897, "text": "Follow steps " }, { "code": null, "e": 4981, "s": 4911, "text": "Create a function game() that will contain all the logic of the game." }, { "code": null, "e": 5161, "s": 4981, "text": "Inside the function declare three variables playerScore, computerScore, moves which will keep the record of the player’s score, computer’s score, and moves completed respectively." }, { "code": null, "e": 5442, "s": 5161, "text": "Create a function playGame() and inside the function use DOM manipulation to get hold of all the three buttons we created in HTML for player input. Create an array playerOptions which will contain all three buttons as its elements. Similarly, create an array for computer options." }, { "code": null, "e": 5755, "s": 5442, "text": "Use forEach() loop on playerOptions so that we can add an event listener on all buttons with a single piece of code. Inside the loop increment moves counter by 1 display moves left on the screen by subtracting moves from 10. Generate a random value for the computer option and compare it with the player’s input." }, { "code": null, "e": 5950, "s": 5755, "text": "Create a function winner() which will receive two arguments one the player’s input and the other the computer’s option The function will decide who wins the point among the player and computer." }, { "code": null, "e": 6100, "s": 5950, "text": "Create a function gameOver() which will display the final result with reload button. The function will be called when moves will become equals to 10." }, { "code": null, "e": 6157, "s": 6100, "text": "Call the playGame() function inside the game() function." }, { "code": null, "e": 6210, "s": 6157, "text": "Now call the game() function at the end of the file." }, { "code": null, "e": 6239, "s": 6210, "text": "Below is the implementation:" }, { "code": null, "e": 6256, "s": 6239, "text": "Filename: app.js" }, { "code": null, "e": 6267, "s": 6256, "text": "Javascript" }, { "code": "// app.js // Complete logic of game inside this functionconst game = () => { let playerScore = 0; let computerScore = 0; let moves = 0; // Function to const playGame = () => { const rockBtn = document.querySelector('.rock'); const paperBtn = document.querySelector('.paper'); const scissorBtn = document.querySelector('.scissor'); const playerOptions = [rockBtn,paperBtn,scissorBtn]; const computerOptions = ['rock','paper','scissors'] // Function to start playing game playerOptions.forEach(option => { option.addEventListener('click',function(){ const movesLeft = document.querySelector('.movesleft'); moves++; movesLeft.innerText = `Moves Left: ${10-moves}`; const choiceNumber = Math.floor(Math.random()*3); const computerChoice = computerOptions[choiceNumber]; // Function to check who wins winner(this.innerText,computerChoice) // Calling gameOver function after 10 moves if(moves == 10){ gameOver(playerOptions,movesLeft); } }) }) } // Function to decide winner const winner = (player,computer) => { const result = document.querySelector('.result'); const playerScoreBoard = document.querySelector('.p-count'); const computerScoreBoard = document.querySelector('.c-count'); player = player.toLowerCase(); computer = computer.toLowerCase(); if(player === computer){ result.textContent = 'Tie' } else if(player == 'rock'){ if(computer == 'paper'){ result.textContent = 'Computer Won'; computerScore++; computerScoreBoard.textContent = computerScore; }else{ result.textContent = 'Player Won' playerScore++; playerScoreBoard.textContent = playerScore; } } else if(player == 'scissors'){ if(computer == 'rock'){ result.textContent = 'Computer Won'; computerScore++; computerScoreBoard.textContent = computerScore; }else{ result.textContent = 'Player Won'; playerScore++; playerScoreBoard.textContent = playerScore; } } else if(player == 'paper'){ if(computer == 'scissors'){ result.textContent = 'Computer Won'; computerScore++; computerScoreBoard.textContent = computerScore; }else{ result.textContent = 'Player Won'; playerScore++; playerScoreBoard.textContent = playerScore; } } } // Function to run when game is over const gameOver = (playerOptions,movesLeft) => { const chooseMove = document.querySelector('.move'); const result = document.querySelector('.result'); const reloadBtn = document.querySelector('.reload'); playerOptions.forEach(option => { option.style.display = 'none'; }) chooseMove.innerText = 'Game Over!!' movesLeft.style.display = 'none'; if(playerScore > computerScore){ result.style.fontSize = '2rem'; result.innerText = 'You Won The Game' result.style.color = '#308D46'; } else if(playerScore < computerScore){ result.style.fontSize = '2rem'; result.innerText = 'You Lost The Game'; result.style.color = 'red'; } else{ result.style.fontSize = '2rem'; result.innerText = 'Tie'; result.style.color = 'grey' } reloadBtn.innerText = 'Restart'; reloadBtn.style.display = 'flex' reloadBtn.addEventListener('click',() => { window.location.reload(); }) } // Calling playGame function inside game playGame(); } // Calling the game functiongame();", "e": 10410, "s": 6267, "text": null }, { "code": null, "e": 10418, "s": 10410, "text": "Output:" }, { "code": null, "e": 10435, "s": 10418, "text": "surinderdawra388" }, { "code": null, "e": 10456, "s": 10435, "text": "JavaScript-Questions" }, { "code": null, "e": 10463, "s": 10456, "text": "Picked" }, { "code": null, "e": 10487, "s": 10463, "text": "Technical Scripter 2020" }, { "code": null, "e": 10498, "s": 10487, "text": "JavaScript" }, { "code": null, "e": 10517, "s": 10498, "text": "Technical Scripter" }, { "code": null, "e": 10534, "s": 10517, "text": "Web Technologies" } ]
Java.util.Arrays.parallelSetAll(), Arrays.setAll() in Java
28 Apr, 2022 Prerequisites : Lambda Expression in Java 8 IntUnaryOperator Interface parallelSetAll and setAll are introduced in Arrays class in java 8. parallelSetAll(): It set all the element in the specified array in parallel by the function which compute each element. Syntax: public static void parallelSetAll(double[] arr, IntToDoubleFunction g) Parameters : arr : Array to which the elements to be set g : It is a function that accepts index of an array and returns the computed value to that index Variations : parallelSetAll(double[] arr, IntToDoubleFunction g) parallelSetAll(int[] arr, IntUnaryOperator g) parallelSetAll(long[] arr, IntToLongFunction g) parallelSetAll(T[] arr, IntFunction g) setAll() : It set all the element in the specified array in by the function which compute each element. Syntax: public static void setAll(int[] arr, IntUnaryOperator g) Parameters : arr : Array to which the elements to be set g : It is a function that accepts index of an array and returns the computed value to that index Variations : setAll(double[] array, IntToDoubleFunction generator) setAll(int[] array, IntUnaryOperator generator) setAll(long[] array, IntToLongFunction generator) setAll(T[] array, IntFunction generator) parallelSetAll() vs setAll() Both functions produces same output as can be seen, but parallelSetAll() is consider faster as it performs the changes on the array parallel(i.e. at once) while setAll() updates each indices of the array(i.e. one after another). Though setAll() runs faster on smaller sized array but parallelSetAll() takes over setAll() when the size of array is larger. Examples Lets see an example of parallelSetAll(int[] arr, IntUnaryOperator g) and setAll(int[] array, IntUnaryOperator generator) Java // Java program to demonstrate setAll()// and ParallelSetAll()import java.util.Arrays;import java.util.function.IntUnaryOperator;class GFG{ public static void main(String[] args) { // Declaring arrays of integers int[] arr_parallel1 = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 }; int[] arr_parallel2 = Arrays.copyOf(arr_parallel1, arr_parallel1.length); int[] arr = Arrays.copyOf(arr_parallel1, arr_parallel1.length); // Applying parallelSetAll on Array arr_parallel1 IntUnaryOperator g = e-> { if (e % 2 == 0) return e * e; else return e; }; Arrays.parallelSetAll(arr_parallel1, g); /* Another way of passing the second argument. Uncomment to try . Arrays.parallelSetAll(arr_parallel1, e -> { if (e % 2 == 0) return e * e; else return e; }); */ System.out.println("Example 1: Modifying the values at even" + " index and storing the square of index"); // Printing the modified array Arrays.stream(arr_parallel1).forEach(e->System.out.print(e + " ")); // Applying parallelSetAll on Array arr_parallel2 Arrays.parallelSetAll(arr_parallel2, e-> { if (arr_parallel2[e] % 2 == 0) return arr_parallel2[e] * arr_parallel2[e]; else return arr_parallel2[e]; }); System.out.println("\n\nExample 2: Modifying the values when" + "even value is encountered"); // Printing the modified array Arrays.stream(arr_parallel2).forEach(e->System.out.print(e + " ")); // Applying setAll on Array arr Arrays.setAll(arr, e-> { if (e % 2 == 0) return e * e; else return e; }); System.out.println("\n\nExample 3:setAll gives exactly " + "same output as parallelSetAll"); // Printing the modified array Arrays.stream(arr).forEach(e->System.out.print(e + " ")); }} Output: Example 1: Modifying the values at even index and storing the square of index 0 1 4 3 16 5 36 7 64 9 100 11 144 13 196 15 256 17 324 19 Example 2: Modifying the values when even value is encountered 1 4 3 16 5 36 7 64 9 100 11 144 13 196 15 256 17 324 19 400 Example 3:setAll gives exactly same output as parallelSetAll 0 1 4 3 16 5 36 7 64 9 100 11 144 13 196 15 256 17 324 19 Example 2 : We can even even pass arrays of user defined data type. Lets see an example of setAll(T[] array, IntFunction generator) and parallelSetAll(T[] arr, IntFunction g) Java // Java program to demonstrate setAll()// and ParallelSetAllimport java.util.Arrays;class GFG { // User Defined class Person static class Person { String name; int age; // constructor public Person(String name, int age) { this.name = name; this.age = age; } } public static void main(String[] args) { // Declaring Arrays of person Person p[] = { new Person("samir", 20), new Person("anil", 25), new Person("amit", 10), new Person("rohit", 17), new Person("Geek5", 19), new Person("sumit", 22), new Person("gourav", 24), new Person("sunny", 27), new Person("ritu", 28) }; // Applying parallelSetAll on p array Arrays.parallelSetAll(p, e->{ if (p[e].name.startsWith("s")) return new Person("You are a geek", 100); else return new Person(p[e].name, p[e].age); }); System.out.println("Example 1; Modifying the name that starts with s"); // Printing array elements Arrays.stream(p).forEach(e->System.out.println(e.name + " " + e.age)); // Declaring another array of person Person p1[] = { new Person("samir", 16), new Person("anil", 25), new Person("amit", 10), new Person("rohit", 17), new Person("Geek5", 19), new Person("sumit", 16), new Person("gourav", 24), new Person("sunny", 11), new Person("ritu", 28) }; // Applying setAll on p1 Arrays.setAll(p1, e->{ if (p1[e].age < 18) return new Person("Teenager", p1[e].age); else return new Person(p1[e].name, p1[e].age); }); System.out.println("\n\nExample 2: Modifying name whose" + "age is less than 18"); // Printing array elements Arrays.stream(p1).forEach(e->System.out.println(e.name + " " + e.age)); }} Output: Example 1; Modifying the name that starts with s You are a geek 100 anil 25 amit 10 rohit 17 Geek5 19 You are a geek 100 gourav 24 You are a geek 100 ritu 28 Example 2: Modifying name whose age is less than 18 Teenager 16 anil 25 Teenager 10 Teenager 17 Geek5 19 Teenager 16 gourav 24 Teenager 11 ritu 28 Reference : https://docs.oracle.com/javase/8/docs/api/java/util/Arrays.html This article is contributed by Sumit Ghosh. 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. rajeev0719singh surinderdawra388 Java - util package Java-Arrays Java-Functions Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n28 Apr, 2022" }, { "code": null, "e": 69, "s": 52, "text": "Prerequisites : " }, { "code": null, "e": 97, "s": 69, "text": "Lambda Expression in Java 8" }, { "code": null, "e": 124, "s": 97, "text": "IntUnaryOperator Interface" }, { "code": null, "e": 193, "s": 124, "text": "parallelSetAll and setAll are introduced in Arrays class in java 8. " }, { "code": null, "e": 322, "s": 193, "text": "parallelSetAll(): It set all the element in the specified array in parallel by the function which compute each element. Syntax: " }, { "code": null, "e": 550, "s": 322, "text": "public static void parallelSetAll(double[] arr, IntToDoubleFunction g)\nParameters :\narr : Array to which the elements to be set \ng : It is a function that accepts index of an array \nand returns the computed value to that index" }, { "code": null, "e": 564, "s": 550, "text": "Variations : " }, { "code": null, "e": 749, "s": 564, "text": "parallelSetAll(double[] arr, IntToDoubleFunction g)\nparallelSetAll(int[] arr, IntUnaryOperator g)\nparallelSetAll(long[] arr, IntToLongFunction g)\nparallelSetAll(T[] arr, IntFunction g)" }, { "code": null, "e": 862, "s": 749, "text": "setAll() : It set all the element in the specified array in by the function which compute each element. Syntax: " }, { "code": null, "e": 1082, "s": 862, "text": "public static void setAll(int[] arr, IntUnaryOperator g)\nParameters :\n arr : Array to which the elements to be set\n g : It is a function that accepts index of an array \nand returns the computed value to that index" }, { "code": null, "e": 1096, "s": 1082, "text": "Variations : " }, { "code": null, "e": 1289, "s": 1096, "text": "setAll(double[] array, IntToDoubleFunction generator)\nsetAll(int[] array, IntUnaryOperator generator)\nsetAll(long[] array, IntToLongFunction generator)\nsetAll(T[] array, IntFunction generator)" }, { "code": null, "e": 1318, "s": 1289, "text": "parallelSetAll() vs setAll()" }, { "code": null, "e": 1675, "s": 1318, "text": "Both functions produces same output as can be seen, but parallelSetAll() is consider faster as it performs the changes on the array parallel(i.e. at once) while setAll() updates each indices of the array(i.e. one after another). Though setAll() runs faster on smaller sized array but parallelSetAll() takes over setAll() when the size of array is larger. " }, { "code": null, "e": 1684, "s": 1675, "text": "Examples" }, { "code": null, "e": 1807, "s": 1684, "text": "Lets see an example of parallelSetAll(int[] arr, IntUnaryOperator g) and setAll(int[] array, IntUnaryOperator generator) " }, { "code": null, "e": 1812, "s": 1807, "text": "Java" }, { "code": "// Java program to demonstrate setAll()// and ParallelSetAll()import java.util.Arrays;import java.util.function.IntUnaryOperator;class GFG{ public static void main(String[] args) { // Declaring arrays of integers int[] arr_parallel1 = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 }; int[] arr_parallel2 = Arrays.copyOf(arr_parallel1, arr_parallel1.length); int[] arr = Arrays.copyOf(arr_parallel1, arr_parallel1.length); // Applying parallelSetAll on Array arr_parallel1 IntUnaryOperator g = e-> { if (e % 2 == 0) return e * e; else return e; }; Arrays.parallelSetAll(arr_parallel1, g); /* Another way of passing the second argument. Uncomment to try . Arrays.parallelSetAll(arr_parallel1, e -> { if (e % 2 == 0) return e * e; else return e; }); */ System.out.println(\"Example 1: Modifying the values at even\" + \" index and storing the square of index\"); // Printing the modified array Arrays.stream(arr_parallel1).forEach(e->System.out.print(e + \" \")); // Applying parallelSetAll on Array arr_parallel2 Arrays.parallelSetAll(arr_parallel2, e-> { if (arr_parallel2[e] % 2 == 0) return arr_parallel2[e] * arr_parallel2[e]; else return arr_parallel2[e]; }); System.out.println(\"\\n\\nExample 2: Modifying the values when\" + \"even value is encountered\"); // Printing the modified array Arrays.stream(arr_parallel2).forEach(e->System.out.print(e + \" \")); // Applying setAll on Array arr Arrays.setAll(arr, e-> { if (e % 2 == 0) return e * e; else return e; }); System.out.println(\"\\n\\nExample 3:setAll gives exactly \" + \"same output as parallelSetAll\"); // Printing the modified array Arrays.stream(arr).forEach(e->System.out.print(e + \" \")); }}", "e": 3973, "s": 1812, "text": null }, { "code": null, "e": 3983, "s": 3973, "text": "Output: " }, { "code": null, "e": 4426, "s": 3983, "text": "Example 1: Modifying the values at even index and storing the square of index\n0 1 4 3 16 5 36 7 64 9 100 11 144 13 196 15 256 17 324 19 \n\nExample 2: Modifying the values when even value is encountered\n1 4 3 16 5 36 7 64 9 100 11 144 13 196 15 256 17 324 19 400 \n\nExample 3:setAll gives exactly same output as parallelSetAll\n0 1 4 3 16 5 36 7 64 9 100 11 144 13 196 15 256 17 324 19 " }, { "code": null, "e": 4602, "s": 4426, "text": "Example 2 : We can even even pass arrays of user defined data type. Lets see an example of setAll(T[] array, IntFunction generator) and parallelSetAll(T[] arr, IntFunction g) " }, { "code": null, "e": 4607, "s": 4602, "text": "Java" }, { "code": "// Java program to demonstrate setAll()// and ParallelSetAllimport java.util.Arrays;class GFG { // User Defined class Person static class Person { String name; int age; // constructor public Person(String name, int age) { this.name = name; this.age = age; } } public static void main(String[] args) { // Declaring Arrays of person Person p[] = { new Person(\"samir\", 20), new Person(\"anil\", 25), new Person(\"amit\", 10), new Person(\"rohit\", 17), new Person(\"Geek5\", 19), new Person(\"sumit\", 22), new Person(\"gourav\", 24), new Person(\"sunny\", 27), new Person(\"ritu\", 28) }; // Applying parallelSetAll on p array Arrays.parallelSetAll(p, e->{ if (p[e].name.startsWith(\"s\")) return new Person(\"You are a geek\", 100); else return new Person(p[e].name, p[e].age); }); System.out.println(\"Example 1; Modifying the name that starts with s\"); // Printing array elements Arrays.stream(p).forEach(e->System.out.println(e.name + \" \" + e.age)); // Declaring another array of person Person p1[] = { new Person(\"samir\", 16), new Person(\"anil\", 25), new Person(\"amit\", 10), new Person(\"rohit\", 17), new Person(\"Geek5\", 19), new Person(\"sumit\", 16), new Person(\"gourav\", 24), new Person(\"sunny\", 11), new Person(\"ritu\", 28) }; // Applying setAll on p1 Arrays.setAll(p1, e->{ if (p1[e].age < 18) return new Person(\"Teenager\", p1[e].age); else return new Person(p1[e].name, p1[e].age); }); System.out.println(\"\\n\\nExample 2: Modifying name whose\" + \"age is less than 18\"); // Printing array elements Arrays.stream(p1).forEach(e->System.out.println(e.name + \" \" + e.age)); }}", "e": 6674, "s": 4607, "text": null }, { "code": null, "e": 6684, "s": 6674, "text": "Output: " }, { "code": null, "e": 7027, "s": 6684, "text": "Example 1; Modifying the name that starts with s\nYou are a geek 100\nanil 25\namit 10\nrohit 17\nGeek5 19\nYou are a geek 100\ngourav 24\nYou are a geek 100\nritu 28\n\n\nExample 2: Modifying name whose age is less than 18\nTeenager 16\nanil 25\nTeenager 10\nTeenager 17\nGeek5 19\nTeenager 16\ngourav 24\nTeenager 11\nritu 28" }, { "code": null, "e": 7523, "s": 7027, "text": "Reference : https://docs.oracle.com/javase/8/docs/api/java/util/Arrays.html This article is contributed by Sumit Ghosh. 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": 7539, "s": 7523, "text": "rajeev0719singh" }, { "code": null, "e": 7556, "s": 7539, "text": "surinderdawra388" }, { "code": null, "e": 7576, "s": 7556, "text": "Java - util package" }, { "code": null, "e": 7588, "s": 7576, "text": "Java-Arrays" }, { "code": null, "e": 7603, "s": 7588, "text": "Java-Functions" }, { "code": null, "e": 7608, "s": 7603, "text": "Java" }, { "code": null, "e": 7613, "s": 7608, "text": "Java" } ]
Wand save() method in Python
22 Apr, 2020 Whenever we manipulate an image and want to preserve image for further image, we use save() function. save() function saves the image into the file or filename. It saves the final manipulated image in your disk. Syntax : # image manipulation codewand.image.save(file = file_object or filename='filename.format') Parameters :It has only two parameter and takes only one at a time. Now let’s see code to save image. Example #1: Save image to the disk. # import Image from wand.image modulefrom wand.image import Image # read image using with Image(filename ='koala.png') as img: # manipulate image img.rotate(90 * r) # save final image after img.save(filename ='final.png') Output : In output an image named koala.png will be saved in disk Example #2: We can save image to output stream using save() function too. For example, the following code converts koala.png image into JPEG, gzips it, and then saves it to koala.jpg.gz: # import gzipimport gzip # import Image from wand.image modulefrom wand.image import Image # create gz compressed filegz = gzip.open('koala.jpg.gz') # read image using Image() functionwith Image(filename ='pikachu.png') as img: # get format of image img.format = 'jpeg' # save image to output stream using save() function img.save(file = gz)gz.close() Output : A compressed file named koala.jpg.gz get saved in disk Image-Processing Python-wand 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 | os.path.join() method Python OOPs Concepts How to drop one or multiple columns in Pandas Dataframe Introduction To PYTHON How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | datetime.timedelta() function Python | Get unique values from a list
[ { "code": null, "e": 28, "s": 0, "text": "\n22 Apr, 2020" }, { "code": null, "e": 240, "s": 28, "text": "Whenever we manipulate an image and want to preserve image for further image, we use save() function. save() function saves the image into the file or filename. It saves the final manipulated image in your disk." }, { "code": null, "e": 249, "s": 240, "text": "Syntax :" }, { "code": "# image manipulation codewand.image.save(file = file_object or filename='filename.format')", "e": 356, "s": 249, "text": null }, { "code": null, "e": 424, "s": 356, "text": "Parameters :It has only two parameter and takes only one at a time." }, { "code": null, "e": 458, "s": 424, "text": "Now let’s see code to save image." }, { "code": null, "e": 494, "s": 458, "text": "Example #1: Save image to the disk." }, { "code": "# import Image from wand.image modulefrom wand.image import Image # read image using with Image(filename ='koala.png') as img: # manipulate image img.rotate(90 * r) # save final image after img.save(filename ='final.png')", "e": 731, "s": 494, "text": null }, { "code": null, "e": 740, "s": 731, "text": "Output :" }, { "code": null, "e": 797, "s": 740, "text": "In output an image named koala.png will be saved in disk" }, { "code": null, "e": 809, "s": 797, "text": "Example #2:" }, { "code": null, "e": 984, "s": 809, "text": "We can save image to output stream using save() function too. For example, the following code converts koala.png image into JPEG, gzips it, and then saves it to koala.jpg.gz:" }, { "code": "# import gzipimport gzip # import Image from wand.image modulefrom wand.image import Image # create gz compressed filegz = gzip.open('koala.jpg.gz') # read image using Image() functionwith Image(filename ='pikachu.png') as img: # get format of image img.format = 'jpeg' # save image to output stream using save() function img.save(file = gz)gz.close()", "e": 1353, "s": 984, "text": null }, { "code": null, "e": 1362, "s": 1353, "text": "Output :" }, { "code": null, "e": 1418, "s": 1362, "text": "A compressed file named koala.jpg.gz get saved in disk\n" }, { "code": null, "e": 1435, "s": 1418, "text": "Image-Processing" }, { "code": null, "e": 1447, "s": 1435, "text": "Python-wand" }, { "code": null, "e": 1454, "s": 1447, "text": "Python" }, { "code": null, "e": 1552, "s": 1454, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1584, "s": 1552, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 1611, "s": 1584, "text": "Python Classes and Objects" }, { "code": null, "e": 1642, "s": 1611, "text": "Python | os.path.join() method" }, { "code": null, "e": 1663, "s": 1642, "text": "Python OOPs Concepts" }, { "code": null, "e": 1719, "s": 1663, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 1742, "s": 1719, "text": "Introduction To PYTHON" }, { "code": null, "e": 1784, "s": 1742, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 1826, "s": 1784, "text": "Check if element exists in list in Python" }, { "code": null, "e": 1865, "s": 1826, "text": "Python | datetime.timedelta() function" } ]
Static and Dynamic Memory Allocation in C
23 Apr, 2021 Memory is divided into smaller addressable units called bytes. Assume that these are small boxes as bytes. Each byte has its own address as per the below table.For example: 0, 1, 2, 3, 4, 5, 6, etc. How program uses memory? The Memory is divided into three sections. Heap Memory: It is a part of the main memory. It is unorganized and treated as a resource when you require the use of it if not release. Heap memory can’t be used directly with the help of a pointer. Stack Memory: It stores temporary variables created by a function. In stack, variables are declared, stored, and initialized during runtime. It follows the First in last out method that means whatever element is going to store last is going to delete first when it’s not in use. Code Section: Whenever the program is executed it will be brought into the main memory. This program will get stored under the code section. Based upon the program it will decide whether to utilize the stack or heap sections. Below is the image to illustrate how the program uses memory: Static Memory Allocation In static memory allocation whenever the program executes it fixes the size that the program is going to take, and it can’t be changed further. So, the exact memory requirements must be known before. Allocation and deallocation of memory will be done by the compiler automatically. When everything is done at compile time (or) before run time, it is called static memory allocation. Key Features: Allocation and deallocation are done by the compiler. It uses a data structures stack for static memory allocation. Variables get allocated permanently. No reusability. Execution is faster than dynamic memory allocation. Memory is allocated before runtime. It is less efficient. For Example: C++ // C++ program to illustrate the// concept of memory allocation#include <iostream>using namespace std; // Driver Codevoid main(){ int a; // 2 bytes long b; // 4 bytes} Explanation: The above piece of code declared 2 variables. Here the assumption is that int takes 2 bytes and long takes 4 bytes of memory. How much memory is taken by variables is again depending upon the compiler. These variables will be stored in the stack section. For every function in the program it will take some part of the stack section it is known as the Activation record (or) stack frame and it will be deleted by the compiler when it is not in use. Below is the image to illustrate the same: Below is the C program to illustrate the Static Memory Allocation: C // C program to implement// static memory allocation#include <stdio.h>#include <stdlib.h> // Driver codeint main(){ int size; printf("Enter limit of the text: \n"); scanf("%d", &size); char str[size]; printf("Enter some text: \n"); scanf(" "); gets(str); printf("Inputted text is: %s\n", str); return 0;} Input: Output: Advantages: Simple usage. Allocation and deallocation are done by the compiler. Efficient execution time. It uses stack data structures. Disadvantages: Memory wastage problem. Exact memory requirements must be known. Memory can’t be resized once after initialization. Dynamic Memory Allocation In Dynamic memory allocation size initialization and allocation are done by the programmer. It is managed and served with pointers that point to the newly allocated memory space in an area which we call the heap. Heap memory is unorganized and it is treated as a resource when you require the use of it if not release it. When everything is done during run time or execution time it is known as Dynamic memory allocation. Key Features: Dynamic allocated at runtime We can also reallocate memory size if needed. Dynamic Allocation is done at run time. No memory wastage There are some functions available in the stdlib.h header which will help to allocate memory dynamically. malloc(): The simplest function that allocates memory at runtime is called malloc(). There is a need to specify the number of bytes of memory that are required to be allocated as the argument returns the address of the first byte of memory that is allocated because you get an address returned, a pointer is the only place to put it. Syntax: int *p = (int*)malloc(No of values*size(int)); The argument to malloc() above clearly indicates that sufficient bytes for accommodating the number of values of type int should be made available. Also notice the cast (int*), which converts the address returned by the function to the type pointer to int. malloc() function returns a pointer with the value NULL. calloc(): The calloc() function offers a couple of advantages over malloc(). It allocates memory as a number of elements of a given size. It initializes the memory that is allocated so that all bytes are zero. calloc() function requires two argument values: The number of data items for which space is required.Size of each data item. The number of data items for which space is required. Size of each data item. It is very similar to using malloc() but the big plus is that you know the memory area will be initialized to zero. Syntax: int *p = (int*)calloc(Number of data items, sizeof(int)); realloc(): The realloc() function enables you to reuse or extend the memory that you previously allocated using malloc() or calloc(). A pointer containing an address that was previously returned by a call to malloc(), calloc(). The size in bytes of the new memory that needs to be allocated. It allocates the memory specified by the second argument and transfers the contents of the previously allocated memory referenced by the pointer passed as the first argument to the newly allocated memory. Syntax: int *np = (type cast) realloc (previous pointer type, new number of elements * sizeof(int)); . free(): When memory is allocated dynamically it should always be released when it is no longer required. Memory allocated on the heap will be automatically released when the program ends but is always better to explicitly release the memory when done with it, even if it’s just before exiting from the program. A memory leak occurs memory is allocated dynamically and reference to it is not retained, due to which unable to release the memory. Syntax: free(pointer); For Example: C // C program to illustrate the concept// of memory allocation#include <iostream>using namespace std; // Driver Codevoid main(){ int* p; // 2 bytes P = (int*)malloc(5 * sizeof(int));} Examples: In the above piece of code, a pointer p is declared. Assume that pointer p will take 2 bytes of memory and again it depends upon the compiler. This pointer will store in the stack section and will point to the array address of the first index which is allocated in the heap. Heap memory cannot be used directly but with the help of the pointer, it can be accessed. When the program is not in use, the memory should be deallocated. Otherwise, it will cause a memory leak. After deallocating the memory allocated in the heap. Below is the image to illustrate the main memory after deallocation. Below is the C program to illustrate the Dynamic Memory Allocation: C // C program to illustrate the above// concepts of memory allocation#include <stdio.h>#include <stdlib.h> // Driver Codeint main(){ int size, resize; char* str = NULL; printf("Enter limit of the " "text: \n"); scanf("%d", &size); str = (char*)malloc(size * sizeof(char)); // If str is not NULL if (str != NULL) { printf("Enter some text: \n"); scanf(" "); gets(str); printf("Inputted text by allocating" "memory using malloc() is: " "%s\n", str); } // Free the memory free(str); str = (char*)calloc(50, sizeof(char)); // If str is not NULL if (str != NULL) { printf("Enter some text: \n"); scanf(" "); gets(str); printf("Inputted text by allocating " "memory using calloc() is: " "%s\n", str); } printf("Enter the new size: \n"); scanf("%d", &resize); str = (char*)realloc(str, resize * sizeof(char)); printf("Memory is successfully " "reallocated by using " "realloc() \n"); // If str is not NULL if (str != NULL) { printf("Enter some text: \n"); scanf(" "); gets(str); printf("Inputted text by reallocating" " memory using realloc()is: " "%s\n", str); } // Free the memory free(str); str = NULL; return 0;} Input: Output: Advantages: Dynamic Allocation is done at run time. We can allocate (create) additional storage whenever we need them. Memory can be deallocated (free/delete) dynamic space whenever we are done with them. Thus, one can always have exactly the amount of space required – no more, no less. Memory size can be reallocated if needed. Disadvantages: As the memory is allocated during runtime, it requires more time. Memory needs to be freed by the user when done. This is important as it is more likely to turn into bugs that are difficult to find. C Basics C-Dynamic Memory Allocation Dynamic Memory Allocation C Language C Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Unordered Sets in C++ Standard Template Library Operators in C / C++ Exception Handling in C++ What is the purpose of a function prototype? TCP Server-Client implementation in C Strings in C Arrow operator -> in C/C++ with Examples Basics of File Handling in C Header files in C/C++ and its uses UDP Server-Client implementation in C
[ { "code": null, "e": 52, "s": 24, "text": "\n23 Apr, 2021" }, { "code": null, "e": 251, "s": 52, "text": "Memory is divided into smaller addressable units called bytes. Assume that these are small boxes as bytes. Each byte has its own address as per the below table.For example: 0, 1, 2, 3, 4, 5, 6, etc." }, { "code": null, "e": 276, "s": 251, "text": "How program uses memory?" }, { "code": null, "e": 320, "s": 276, "text": "The Memory is divided into three sections. " }, { "code": null, "e": 520, "s": 320, "text": "Heap Memory: It is a part of the main memory. It is unorganized and treated as a resource when you require the use of it if not release. Heap memory can’t be used directly with the help of a pointer." }, { "code": null, "e": 799, "s": 520, "text": "Stack Memory: It stores temporary variables created by a function. In stack, variables are declared, stored, and initialized during runtime. It follows the First in last out method that means whatever element is going to store last is going to delete first when it’s not in use." }, { "code": null, "e": 1025, "s": 799, "text": "Code Section: Whenever the program is executed it will be brought into the main memory. This program will get stored under the code section. Based upon the program it will decide whether to utilize the stack or heap sections." }, { "code": null, "e": 1087, "s": 1025, "text": "Below is the image to illustrate how the program uses memory:" }, { "code": null, "e": 1112, "s": 1087, "text": "Static Memory Allocation" }, { "code": null, "e": 1496, "s": 1112, "text": "In static memory allocation whenever the program executes it fixes the size that the program is going to take, and it can’t be changed further. So, the exact memory requirements must be known before. Allocation and deallocation of memory will be done by the compiler automatically. When everything is done at compile time (or) before run time, it is called static memory allocation." }, { "code": null, "e": 1510, "s": 1496, "text": "Key Features:" }, { "code": null, "e": 1564, "s": 1510, "text": "Allocation and deallocation are done by the compiler." }, { "code": null, "e": 1626, "s": 1564, "text": "It uses a data structures stack for static memory allocation." }, { "code": null, "e": 1663, "s": 1626, "text": "Variables get allocated permanently." }, { "code": null, "e": 1679, "s": 1663, "text": "No reusability." }, { "code": null, "e": 1731, "s": 1679, "text": "Execution is faster than dynamic memory allocation." }, { "code": null, "e": 1767, "s": 1731, "text": "Memory is allocated before runtime." }, { "code": null, "e": 1789, "s": 1767, "text": "It is less efficient." }, { "code": null, "e": 1802, "s": 1789, "text": "For Example:" }, { "code": null, "e": 1806, "s": 1802, "text": "C++" }, { "code": "// C++ program to illustrate the// concept of memory allocation#include <iostream>using namespace std; // Driver Codevoid main(){ int a; // 2 bytes long b; // 4 bytes}", "e": 1981, "s": 1806, "text": null }, { "code": null, "e": 1994, "s": 1981, "text": "Explanation:" }, { "code": null, "e": 2196, "s": 1994, "text": "The above piece of code declared 2 variables. Here the assumption is that int takes 2 bytes and long takes 4 bytes of memory. How much memory is taken by variables is again depending upon the compiler." }, { "code": null, "e": 2443, "s": 2196, "text": "These variables will be stored in the stack section. For every function in the program it will take some part of the stack section it is known as the Activation record (or) stack frame and it will be deleted by the compiler when it is not in use." }, { "code": null, "e": 2486, "s": 2443, "text": "Below is the image to illustrate the same:" }, { "code": null, "e": 2553, "s": 2486, "text": "Below is the C program to illustrate the Static Memory Allocation:" }, { "code": null, "e": 2555, "s": 2553, "text": "C" }, { "code": "// C program to implement// static memory allocation#include <stdio.h>#include <stdlib.h> // Driver codeint main(){ int size; printf(\"Enter limit of the text: \\n\"); scanf(\"%d\", &size); char str[size]; printf(\"Enter some text: \\n\"); scanf(\" \"); gets(str); printf(\"Inputted text is: %s\\n\", str); return 0;}", "e": 2888, "s": 2555, "text": null }, { "code": null, "e": 2895, "s": 2888, "text": "Input:" }, { "code": null, "e": 2903, "s": 2895, "text": "Output:" }, { "code": null, "e": 2915, "s": 2903, "text": "Advantages:" }, { "code": null, "e": 2929, "s": 2915, "text": "Simple usage." }, { "code": null, "e": 2983, "s": 2929, "text": "Allocation and deallocation are done by the compiler." }, { "code": null, "e": 3009, "s": 2983, "text": "Efficient execution time." }, { "code": null, "e": 3040, "s": 3009, "text": "It uses stack data structures." }, { "code": null, "e": 3055, "s": 3040, "text": "Disadvantages:" }, { "code": null, "e": 3079, "s": 3055, "text": "Memory wastage problem." }, { "code": null, "e": 3120, "s": 3079, "text": "Exact memory requirements must be known." }, { "code": null, "e": 3171, "s": 3120, "text": "Memory can’t be resized once after initialization." }, { "code": null, "e": 3197, "s": 3171, "text": "Dynamic Memory Allocation" }, { "code": null, "e": 3620, "s": 3197, "text": "In Dynamic memory allocation size initialization and allocation are done by the programmer. It is managed and served with pointers that point to the newly allocated memory space in an area which we call the heap. Heap memory is unorganized and it is treated as a resource when you require the use of it if not release it. When everything is done during run time or execution time it is known as Dynamic memory allocation." }, { "code": null, "e": 3634, "s": 3620, "text": "Key Features:" }, { "code": null, "e": 3663, "s": 3634, "text": "Dynamic allocated at runtime" }, { "code": null, "e": 3709, "s": 3663, "text": "We can also reallocate memory size if needed." }, { "code": null, "e": 3749, "s": 3709, "text": "Dynamic Allocation is done at run time." }, { "code": null, "e": 3767, "s": 3749, "text": "No memory wastage" }, { "code": null, "e": 3873, "s": 3767, "text": "There are some functions available in the stdlib.h header which will help to allocate memory dynamically." }, { "code": null, "e": 4207, "s": 3873, "text": "malloc(): The simplest function that allocates memory at runtime is called malloc(). There is a need to specify the number of bytes of memory that are required to be allocated as the argument returns the address of the first byte of memory that is allocated because you get an address returned, a pointer is the only place to put it." }, { "code": null, "e": 4215, "s": 4207, "text": "Syntax:" }, { "code": null, "e": 4262, "s": 4215, "text": "int *p = (int*)malloc(No of values*size(int));" }, { "code": null, "e": 4576, "s": 4262, "text": "The argument to malloc() above clearly indicates that sufficient bytes for accommodating the number of values of type int should be made available. Also notice the cast (int*), which converts the address returned by the function to the type pointer to int. malloc() function returns a pointer with the value NULL." }, { "code": null, "e": 4911, "s": 4576, "text": "calloc(): The calloc() function offers a couple of advantages over malloc(). It allocates memory as a number of elements of a given size. It initializes the memory that is allocated so that all bytes are zero. calloc() function requires two argument values: The number of data items for which space is required.Size of each data item." }, { "code": null, "e": 4965, "s": 4911, "text": "The number of data items for which space is required." }, { "code": null, "e": 4989, "s": 4965, "text": "Size of each data item." }, { "code": null, "e": 5105, "s": 4989, "text": "It is very similar to using malloc() but the big plus is that you know the memory area will be initialized to zero." }, { "code": null, "e": 5114, "s": 5105, "text": "Syntax: " }, { "code": null, "e": 5172, "s": 5114, "text": "int *p = (int*)calloc(Number of data items, sizeof(int));" }, { "code": null, "e": 5669, "s": 5172, "text": "realloc(): The realloc() function enables you to reuse or extend the memory that you previously allocated using malloc() or calloc(). A pointer containing an address that was previously returned by a call to malloc(), calloc(). The size in bytes of the new memory that needs to be allocated. It allocates the memory specified by the second argument and transfers the contents of the previously allocated memory referenced by the pointer passed as the first argument to the newly allocated memory." }, { "code": null, "e": 5677, "s": 5669, "text": "Syntax:" }, { "code": null, "e": 5770, "s": 5677, "text": "int *np = (type cast) realloc (previous pointer type, new number of elements * sizeof(int));" }, { "code": null, "e": 6216, "s": 5770, "text": ". free(): When memory is allocated dynamically it should always be released when it is no longer required. Memory allocated on the heap will be automatically released when the program ends but is always better to explicitly release the memory when done with it, even if it’s just before exiting from the program. A memory leak occurs memory is allocated dynamically and reference to it is not retained, due to which unable to release the memory." }, { "code": null, "e": 6224, "s": 6216, "text": "Syntax:" }, { "code": null, "e": 6239, "s": 6224, "text": "free(pointer);" }, { "code": null, "e": 6252, "s": 6239, "text": "For Example:" }, { "code": null, "e": 6254, "s": 6252, "text": "C" }, { "code": "// C program to illustrate the concept// of memory allocation#include <iostream>using namespace std; // Driver Codevoid main(){ int* p; // 2 bytes P = (int*)malloc(5 * sizeof(int));}", "e": 6444, "s": 6254, "text": null }, { "code": null, "e": 6455, "s": 6444, "text": "Examples: " }, { "code": null, "e": 6598, "s": 6455, "text": "In the above piece of code, a pointer p is declared. Assume that pointer p will take 2 bytes of memory and again it depends upon the compiler." }, { "code": null, "e": 6820, "s": 6598, "text": "This pointer will store in the stack section and will point to the array address of the first index which is allocated in the heap. Heap memory cannot be used directly but with the help of the pointer, it can be accessed." }, { "code": null, "e": 6926, "s": 6820, "text": "When the program is not in use, the memory should be deallocated. Otherwise, it will cause a memory leak." }, { "code": null, "e": 7048, "s": 6926, "text": "After deallocating the memory allocated in the heap. Below is the image to illustrate the main memory after deallocation." }, { "code": null, "e": 7116, "s": 7048, "text": "Below is the C program to illustrate the Dynamic Memory Allocation:" }, { "code": null, "e": 7118, "s": 7116, "text": "C" }, { "code": "// C program to illustrate the above// concepts of memory allocation#include <stdio.h>#include <stdlib.h> // Driver Codeint main(){ int size, resize; char* str = NULL; printf(\"Enter limit of the \" \"text: \\n\"); scanf(\"%d\", &size); str = (char*)malloc(size * sizeof(char)); // If str is not NULL if (str != NULL) { printf(\"Enter some text: \\n\"); scanf(\" \"); gets(str); printf(\"Inputted text by allocating\" \"memory using malloc() is: \" \"%s\\n\", str); } // Free the memory free(str); str = (char*)calloc(50, sizeof(char)); // If str is not NULL if (str != NULL) { printf(\"Enter some text: \\n\"); scanf(\" \"); gets(str); printf(\"Inputted text by allocating \" \"memory using calloc() is: \" \"%s\\n\", str); } printf(\"Enter the new size: \\n\"); scanf(\"%d\", &resize); str = (char*)realloc(str, resize * sizeof(char)); printf(\"Memory is successfully \" \"reallocated by using \" \"realloc() \\n\"); // If str is not NULL if (str != NULL) { printf(\"Enter some text: \\n\"); scanf(\" \"); gets(str); printf(\"Inputted text by reallocating\" \" memory using realloc()is: \" \"%s\\n\", str); } // Free the memory free(str); str = NULL; return 0;}", "e": 8561, "s": 7118, "text": null }, { "code": null, "e": 8568, "s": 8561, "text": "Input:" }, { "code": null, "e": 8576, "s": 8568, "text": "Output:" }, { "code": null, "e": 8588, "s": 8576, "text": "Advantages:" }, { "code": null, "e": 8628, "s": 8588, "text": "Dynamic Allocation is done at run time." }, { "code": null, "e": 8695, "s": 8628, "text": "We can allocate (create) additional storage whenever we need them." }, { "code": null, "e": 8781, "s": 8695, "text": "Memory can be deallocated (free/delete) dynamic space whenever we are done with them." }, { "code": null, "e": 8864, "s": 8781, "text": "Thus, one can always have exactly the amount of space required – no more, no less." }, { "code": null, "e": 8906, "s": 8864, "text": "Memory size can be reallocated if needed." }, { "code": null, "e": 8921, "s": 8906, "text": "Disadvantages:" }, { "code": null, "e": 8987, "s": 8921, "text": "As the memory is allocated during runtime, it requires more time." }, { "code": null, "e": 9120, "s": 8987, "text": "Memory needs to be freed by the user when done. This is important as it is more likely to turn into bugs that are difficult to find." }, { "code": null, "e": 9129, "s": 9120, "text": "C Basics" }, { "code": null, "e": 9157, "s": 9129, "text": "C-Dynamic Memory Allocation" }, { "code": null, "e": 9183, "s": 9157, "text": "Dynamic Memory Allocation" }, { "code": null, "e": 9194, "s": 9183, "text": "C Language" }, { "code": null, "e": 9205, "s": 9194, "text": "C Programs" }, { "code": null, "e": 9303, "s": 9205, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 9351, "s": 9303, "text": "Unordered Sets in C++ Standard Template Library" }, { "code": null, "e": 9372, "s": 9351, "text": "Operators in C / C++" }, { "code": null, "e": 9398, "s": 9372, "text": "Exception Handling in C++" }, { "code": null, "e": 9443, "s": 9398, "text": "What is the purpose of a function prototype?" }, { "code": null, "e": 9481, "s": 9443, "text": "TCP Server-Client implementation in C" }, { "code": null, "e": 9494, "s": 9481, "text": "Strings in C" }, { "code": null, "e": 9535, "s": 9494, "text": "Arrow operator -> in C/C++ with Examples" }, { "code": null, "e": 9564, "s": 9535, "text": "Basics of File Handling in C" }, { "code": null, "e": 9599, "s": 9564, "text": "Header files in C/C++ and its uses" } ]
How to List All Tables in Oracle?
28 Oct, 2021 In this article, we will discuss all the methods to list all tables in the oracle SQL Database. We have three types of a subset of tables available to use as identifiers which in turn help us to sort the required table names. Here, are the following types of table identifiers in the Oracle SQL Database. 1. DBA_tables: If the user is SYSTEM or has access to dba_tables data dictionary view, then use the given below query: Query: SELECT owner, table_name FROM dba_tables; This query returns the following list of tables that contain all the tables that are there in the entire database. Output: 2. All_tables: If the user does not have access or privilege to view the dba_tables it can still get a list of all the tables that it has access to using the following SQL query. This SQL query gives the list of tables that can be accessed by the user along with its owner. Query: SELECT owner, table_name FROM all_tables; This query returns the following list of tables that contain all the tables that the user has access to in the entire database. Output: 3. User_tables If the user wants the list of all tables owned/created by him only, then use the following SQL query to get a list of tables. The following query does not return the name of the owner as it is the user itself for all the tables. Query: SELECT table_name FROM user_tables; This query returns the following list of tables that contain all the tables owned by the user in the entire database. Output: Oracle Picked SQL Oracle SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Update Multiple Columns in Single Update Statement in SQL? Window functions in SQL SQL | Sub queries in From Clause What is Temporary Table in SQL? SQL using Python SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter SQL Query to Convert VARCHAR to INT RANK() Function in SQL Server SQL Query to Compare Two Dates SQL Query to Insert Multiple Rows
[ { "code": null, "e": 28, "s": 0, "text": "\n28 Oct, 2021" }, { "code": null, "e": 124, "s": 28, "text": "In this article, we will discuss all the methods to list all tables in the oracle SQL Database." }, { "code": null, "e": 333, "s": 124, "text": "We have three types of a subset of tables available to use as identifiers which in turn help us to sort the required table names. Here, are the following types of table identifiers in the Oracle SQL Database." }, { "code": null, "e": 348, "s": 333, "text": "1. DBA_tables:" }, { "code": null, "e": 452, "s": 348, "text": "If the user is SYSTEM or has access to dba_tables data dictionary view, then use the given below query:" }, { "code": null, "e": 459, "s": 452, "text": "Query:" }, { "code": null, "e": 501, "s": 459, "text": "SELECT owner, table_name FROM dba_tables;" }, { "code": null, "e": 616, "s": 501, "text": "This query returns the following list of tables that contain all the tables that are there in the entire database." }, { "code": null, "e": 624, "s": 616, "text": "Output:" }, { "code": null, "e": 639, "s": 624, "text": "2. All_tables:" }, { "code": null, "e": 898, "s": 639, "text": "If the user does not have access or privilege to view the dba_tables it can still get a list of all the tables that it has access to using the following SQL query. This SQL query gives the list of tables that can be accessed by the user along with its owner." }, { "code": null, "e": 905, "s": 898, "text": "Query:" }, { "code": null, "e": 947, "s": 905, "text": "SELECT owner, table_name FROM all_tables;" }, { "code": null, "e": 1075, "s": 947, "text": "This query returns the following list of tables that contain all the tables that the user has access to in the entire database." }, { "code": null, "e": 1083, "s": 1075, "text": "Output:" }, { "code": null, "e": 1098, "s": 1083, "text": "3. User_tables" }, { "code": null, "e": 1327, "s": 1098, "text": "If the user wants the list of all tables owned/created by him only, then use the following SQL query to get a list of tables. The following query does not return the name of the owner as it is the user itself for all the tables." }, { "code": null, "e": 1334, "s": 1327, "text": "Query:" }, { "code": null, "e": 1370, "s": 1334, "text": "SELECT table_name FROM user_tables;" }, { "code": null, "e": 1488, "s": 1370, "text": "This query returns the following list of tables that contain all the tables owned by the user in the entire database." }, { "code": null, "e": 1496, "s": 1488, "text": "Output:" }, { "code": null, "e": 1503, "s": 1496, "text": "Oracle" }, { "code": null, "e": 1510, "s": 1503, "text": "Picked" }, { "code": null, "e": 1514, "s": 1510, "text": "SQL" }, { "code": null, "e": 1521, "s": 1514, "text": "Oracle" }, { "code": null, "e": 1525, "s": 1521, "text": "SQL" }, { "code": null, "e": 1623, "s": 1525, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1689, "s": 1623, "text": "How to Update Multiple Columns in Single Update Statement in SQL?" }, { "code": null, "e": 1713, "s": 1689, "text": "Window functions in SQL" }, { "code": null, "e": 1746, "s": 1713, "text": "SQL | Sub queries in From Clause" }, { "code": null, "e": 1778, "s": 1746, "text": "What is Temporary Table in SQL?" }, { "code": null, "e": 1795, "s": 1778, "text": "SQL using Python" }, { "code": null, "e": 1873, "s": 1795, "text": "SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter" }, { "code": null, "e": 1909, "s": 1873, "text": "SQL Query to Convert VARCHAR to INT" }, { "code": null, "e": 1939, "s": 1909, "text": "RANK() Function in SQL Server" }, { "code": null, "e": 1970, "s": 1939, "text": "SQL Query to Compare Two Dates" } ]
p5.js | point() Function
17 Jan, 2020 The point() function is an inbuilt function in p5.js which is used to draw the point in a given coordinate position. Syntax: point( x, y, [z]) Parameters: This function accept three parameters which are described below x: It is used to set the x-coordinate of point. y: It is used to set the y-coordinate of point. z: It is used to set the z-coordinate in WebGL mode. Example 1: function setup() { // Create Canvas of given size createCanvas(400, 300); } function draw() { // Use point() function to draw point point(50, 50); point(150, 50); point(50, 150); point(150, 150); // Use strokeWeight() function to set // the weight of point strokeWeight(10);} Output: Example 2: function setup() { // Create Canvas of given size createCanvas(400, 300); } function draw() { // Set the background color background('green'); // Set the stroke weight strokeWeight(10); // Set stroke color stroke('white'); // Draw point point(50, 50); point(50, 250); point(350, 50); point(350, 250); point(200, 150); } Output: Online editor: https://editor.p5js.org/Environment Setup: https://www.geeksforgeeks.org/p5-js-soundfile-object-installation-and-methods/ Reference: https://p5js.org/reference/#/p5/point JavaScript-p5.js JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n17 Jan, 2020" }, { "code": null, "e": 145, "s": 28, "text": "The point() function is an inbuilt function in p5.js which is used to draw the point in a given coordinate position." }, { "code": null, "e": 153, "s": 145, "text": "Syntax:" }, { "code": null, "e": 171, "s": 153, "text": "point( x, y, [z])" }, { "code": null, "e": 247, "s": 171, "text": "Parameters: This function accept three parameters which are described below" }, { "code": null, "e": 295, "s": 247, "text": "x: It is used to set the x-coordinate of point." }, { "code": null, "e": 343, "s": 295, "text": "y: It is used to set the y-coordinate of point." }, { "code": null, "e": 396, "s": 343, "text": "z: It is used to set the z-coordinate in WebGL mode." }, { "code": null, "e": 407, "s": 396, "text": "Example 1:" }, { "code": "function setup() { // Create Canvas of given size createCanvas(400, 300); } function draw() { // Use point() function to draw point point(50, 50); point(150, 50); point(50, 150); point(150, 150); // Use strokeWeight() function to set // the weight of point strokeWeight(10);}", "e": 722, "s": 407, "text": null }, { "code": null, "e": 730, "s": 722, "text": "Output:" }, { "code": null, "e": 741, "s": 730, "text": "Example 2:" }, { "code": "function setup() { // Create Canvas of given size createCanvas(400, 300); } function draw() { // Set the background color background('green'); // Set the stroke weight strokeWeight(10); // Set stroke color stroke('white'); // Draw point point(50, 50); point(50, 250); point(350, 50); point(350, 250); point(200, 150); } ", "e": 1150, "s": 741, "text": null }, { "code": null, "e": 1158, "s": 1150, "text": "Output:" }, { "code": null, "e": 1295, "s": 1158, "text": "Online editor: https://editor.p5js.org/Environment Setup: https://www.geeksforgeeks.org/p5-js-soundfile-object-installation-and-methods/" }, { "code": null, "e": 1344, "s": 1295, "text": "Reference: https://p5js.org/reference/#/p5/point" }, { "code": null, "e": 1361, "s": 1344, "text": "JavaScript-p5.js" }, { "code": null, "e": 1372, "s": 1361, "text": "JavaScript" }, { "code": null, "e": 1389, "s": 1372, "text": "Web Technologies" } ]
What is a pure functional component in ReactJS ?
02 Jul, 2021 What is a JavaScript function? A JavaScript function is a block of code designed to perform a particular task which is executed when it is called. How React functional components are similar to JavaScript functions? Conceptually, components are like JavaScript functions. A functional component is a JavaScript function that returns JSX in React. These functions accept arbitrary inputs (often called “props”) and return React elements describing what should appear on the screen. When a React Component is Pure? A function is said to be pure if the return value is determined by its input values only and the return value is always the same for the same input values. A React component is said to be pure if it renders the same output for the same state and props. For React pure class components, React provides the PureComponent base class. Class components that extend the React.PureComponent classes are treated as pure components. Create React Application: Step 1: Create a React application using the following command:npx create-react-app pure-react Step 1: Create a React application using the following command: npx create-react-app pure-react Step 2: After creating your project folder i.e. pure-react, move to it using the following command:cd pure-react Step 2: After creating your project folder i.e. pure-react, move to it using the following command: cd pure-react Project Structure: It will look like the following. Filename: App.js App.js import React from 'react';import GeeksScore from './geekscore'; export default function App() { return ( <div> <GeeksScore score="100" /> </div> );} geekscore.js import React from 'react'; class GeeksScore extends React.PureComponent { render() { const { score, total = Math.max(1, score) } = this.props; return ( <div> <h6>Geeks Score</h6> <span>{ Math.round(score / total * 100) }%</span> </div> ) } } export default GeeksScore; 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: Why Pure Components? Pure components have some performance improvements and render optimizations because React implements the shouldComponentUpdate() method for them with a shallow comparison for props and state. What is a pure functional component in React? Functional components are very useful in React, especially when we want to isolate state management from the React component. That’s why they are often called stateless components. However, functional components cannot leverage the performance improvements and render optimizations that come with React.PureComponent since they are not classes by definition. Optimizing a functional component, so that React can treat it as a pure component shouldn’t necessarily require that the component be converted to a class component. To create a pure functional component in React, React provides a React.memo() API. Using the React.memo() API, the React functional component can be wrapped as follows to get React Pure Functional Component. Some important things about React.memo() API are: React.memo() is a higher-order component that takes a React component as its first argument and returns a pure React component. React component type returned using React.memo() allows the renderer to render the component while memoizing the output. React.memo() also works with components w using ReactDOMServer. App.js import React from 'react';import GeeksScore from './geekscore'; export default function App() { return ( <div> <GeeksScore score="100" /> </div> );} geekscore.js import React, { memo } from 'react'; function GeeksScore({ score = 0, total = Math.max(1, score) }) { return ( <div> <h2>Geeks Score</h2> <span>{ Math.round(score / total * 100) }%</span> </div> )} export default memo(GeeksScore); 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: Picked React-Questions ReactJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n02 Jul, 2021" }, { "code": null, "e": 59, "s": 28, "text": "What is a JavaScript function?" }, { "code": null, "e": 175, "s": 59, "text": "A JavaScript function is a block of code designed to perform a particular task which is executed when it is called." }, { "code": null, "e": 244, "s": 175, "text": "How React functional components are similar to JavaScript functions?" }, { "code": null, "e": 510, "s": 244, "text": "Conceptually, components are like JavaScript functions. A functional component is a JavaScript function that returns JSX in React. These functions accept arbitrary inputs (often called “props”) and return React elements describing what should appear on the screen." }, { "code": null, "e": 544, "s": 512, "text": "When a React Component is Pure?" }, { "code": null, "e": 700, "s": 544, "text": "A function is said to be pure if the return value is determined by its input values only and the return value is always the same for the same input values." }, { "code": null, "e": 968, "s": 700, "text": "A React component is said to be pure if it renders the same output for the same state and props. For React pure class components, React provides the PureComponent base class. Class components that extend the React.PureComponent classes are treated as pure components." }, { "code": null, "e": 994, "s": 968, "text": "Create React Application:" }, { "code": null, "e": 1089, "s": 994, "text": "Step 1: Create a React application using the following command:npx create-react-app pure-react" }, { "code": null, "e": 1153, "s": 1089, "text": "Step 1: Create a React application using the following command:" }, { "code": null, "e": 1185, "s": 1153, "text": "npx create-react-app pure-react" }, { "code": null, "e": 1298, "s": 1185, "text": "Step 2: After creating your project folder i.e. pure-react, move to it using the following command:cd pure-react" }, { "code": null, "e": 1398, "s": 1298, "text": "Step 2: After creating your project folder i.e. pure-react, move to it using the following command:" }, { "code": null, "e": 1412, "s": 1398, "text": "cd pure-react" }, { "code": null, "e": 1464, "s": 1412, "text": "Project Structure: It will look like the following." }, { "code": null, "e": 1481, "s": 1464, "text": "Filename: App.js" }, { "code": null, "e": 1488, "s": 1481, "text": "App.js" }, { "code": "import React from 'react';import GeeksScore from './geekscore'; export default function App() { return ( <div> <GeeksScore score=\"100\" /> </div> );}", "e": 1651, "s": 1488, "text": null }, { "code": null, "e": 1664, "s": 1651, "text": "geekscore.js" }, { "code": "import React from 'react'; class GeeksScore extends React.PureComponent { render() { const { score, total = Math.max(1, score) } = this.props; return ( <div> <h6>Geeks Score</h6> <span>{ Math.round(score / total * 100) }%</span> </div> ) } } export default GeeksScore;", "e": 1975, "s": 1664, "text": null }, { "code": null, "e": 2088, "s": 1975, "text": "Step to Run Application: Run the application using the following command from the root directory of the project:" }, { "code": null, "e": 2098, "s": 2088, "text": "npm start" }, { "code": null, "e": 2197, "s": 2098, "text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output:" }, { "code": null, "e": 2218, "s": 2197, "text": "Why Pure Components?" }, { "code": null, "e": 2410, "s": 2218, "text": "Pure components have some performance improvements and render optimizations because React implements the shouldComponentUpdate() method for them with a shallow comparison for props and state." }, { "code": null, "e": 2456, "s": 2410, "text": "What is a pure functional component in React?" }, { "code": null, "e": 2637, "s": 2456, "text": "Functional components are very useful in React, especially when we want to isolate state management from the React component. That’s why they are often called stateless components." }, { "code": null, "e": 2815, "s": 2637, "text": "However, functional components cannot leverage the performance improvements and render optimizations that come with React.PureComponent since they are not classes by definition." }, { "code": null, "e": 3189, "s": 2815, "text": "Optimizing a functional component, so that React can treat it as a pure component shouldn’t necessarily require that the component be converted to a class component. To create a pure functional component in React, React provides a React.memo() API. Using the React.memo() API, the React functional component can be wrapped as follows to get React Pure Functional Component." }, { "code": null, "e": 3239, "s": 3189, "text": "Some important things about React.memo() API are:" }, { "code": null, "e": 3367, "s": 3239, "text": "React.memo() is a higher-order component that takes a React component as its first argument and returns a pure React component." }, { "code": null, "e": 3488, "s": 3367, "text": "React component type returned using React.memo() allows the renderer to render the component while memoizing the output." }, { "code": null, "e": 3552, "s": 3488, "text": "React.memo() also works with components w using ReactDOMServer." }, { "code": null, "e": 3559, "s": 3552, "text": "App.js" }, { "code": "import React from 'react';import GeeksScore from './geekscore'; export default function App() { return ( <div> <GeeksScore score=\"100\" /> </div> );}", "e": 3722, "s": 3559, "text": null }, { "code": null, "e": 3735, "s": 3722, "text": "geekscore.js" }, { "code": "import React, { memo } from 'react'; function GeeksScore({ score = 0, total = Math.max(1, score) }) { return ( <div> <h2>Geeks Score</h2> <span>{ Math.round(score / total * 100) }%</span> </div> )} export default memo(GeeksScore);", "e": 3986, "s": 3735, "text": null }, { "code": null, "e": 4099, "s": 3986, "text": "Step to Run Application: Run the application using the following command from the root directory of the project:" }, { "code": null, "e": 4109, "s": 4099, "text": "npm start" }, { "code": null, "e": 4208, "s": 4109, "text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output:" }, { "code": null, "e": 4215, "s": 4208, "text": "Picked" }, { "code": null, "e": 4231, "s": 4215, "text": "React-Questions" }, { "code": null, "e": 4239, "s": 4231, "text": "ReactJS" }, { "code": null, "e": 4256, "s": 4239, "text": "Web Technologies" } ]
Calculate sum of all nodes present in a level for each level of a Tree - GeeksforGeeks
29 Jun, 2021 Given a Generic Tree consisting of N nodes (rooted at 0) where each node is associated with a value, the task for each level of the Tree is to find the sum of all node values present at that level of the tree. Examples: Input: node_number = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }, node_values = { 2, 3, 4, 4, 7, 6, 2, 3, 9, 1 } Output: Sum of level 0 = 2Sum of level 1 = 7Sum of level 2 = 14Sum of level 3 = 18 Explanation : Nodes on level 0 = {1} with value is 2 Nodes on level 1 = {2, 3} and their respective values are {3, 4}. Sum = 7. Nodes on level 2 = {4, 5, 8} with values {4, 7, 3} respectively. Sum = 14. Nodes on level 3 = {6, 7, 9, 10} with values {6, 2, 9, 1} respectively. Sum = 18 Input: node_number = { 1 }, node_values = { 10 }Output: Sum of level 0 = 10 Approach: Follow the steps below to solve the problem: Traverse the tree using DFS or BFSStore the level of this node using this approach.Then, add the node values to the corresponding level of the node in an array, say sum[ ].Print the array sum[] showing the sum of all nodes on each level. Traverse the tree using DFS or BFS Store the level of this node using this approach. Then, add the node values to the corresponding level of the node in an array, say sum[ ]. Print the array sum[] showing the sum of all nodes on each level. Below is the implementation of the above approach : C++ Java Python3 C# Javascript // C++ implementation of// the above approach#include <bits/stdc++.h>using namespace std; // Function to add edges to the treevoid add_edge(int a, int b, vector<vector<int> >& tree){ // 0-based indexing a--, b--; tree[a].push_back(b); tree[b].push_back(a);} // Function to print sum of// nodes on all levels of a treevoid dfs(int u, int level, int par, int node_values[], vector<vector<int> >& tree, map<int, int>& sum, int& depth){ // update max depth of tree depth = max(depth, level); // Add value of current node // to its corresponding level sum[level] += node_values[u]; for (int child : tree[u]) { if (child == par) continue; // Recursive traverse child nodes dfs(child, level + 1, u, node_values, tree, sum, depth); }} // Function to calculate sum of// nodes of each level of the Treevoid getSum(int node_values[], vector<vector<int> >& tree){ // Depth of the tree int depth = 0; // Stores sum at each level map<int, int> sum; dfs(0, 0, -1, node_values, tree, sum, depth); // Print final sum for (int i = 0; i <= depth; i++) { cout << "Sum of level " << i << " = " << sum[i] << endl; }} // Driver Codeint32_t main(){ // Create a tree structure int N = 10; vector<vector<int> > tree(N); add_edge(1, 2, tree); add_edge(1, 3, tree); add_edge(2, 4, tree); add_edge(3, 5, tree); add_edge(3, 8, tree); add_edge(5, 6, tree); add_edge(5, 7, tree); add_edge(8, 9, tree); add_edge(8, 10, tree); int node_values[] = { 2, 3, 4, 4, 7, 6, 2, 3, 9, 1 }; // Function call to get the sum // of nodes of different level getSum(node_values, tree); return 0;} // Java implementation of// the above approachimport java.io.*;import java.util.*; class GFG{ static Map<Integer, Integer> sum = new HashMap<>();static int depth = 0; // Function to add edges to the treestatic void add_edge(int a, int b, ArrayList<ArrayList<Integer>> tree){ // 0-based indexing a--; b--; tree.get(a).add(b); tree.get(b).add(a);} // Function to print sum of// Nodes on all levels of a treestatic void dfs(int u, int level, int par, int []node_values, ArrayList<ArrayList<Integer>> tree){ // Update max depth of tree depth = Math.max(depth, level); // Add value of current node // to its corresponding level if (sum.containsKey(level)) { sum.put(level, sum.get(level) + node_values[u]); } else sum.put(level,node_values[u]); for(int child : tree.get(u)) { if (child == par) continue; // Recursive traverse child nodes dfs(child, level + 1, u, node_values, tree); }} // Function to calculate sum of// nodes of each level of the Treestatic void getSum(int []node_values, ArrayList<ArrayList<Integer>> tree){ dfs(0, 0, -1, node_values, tree); // Print final sum for(int i = 0; i <= depth; i++) { System.out.println("Sum of level " + (int) i + " = " + sum.get(i)); }} // Driver Codepublic static void main (String[] args){ // Create a tree structure int N = 10; ArrayList<ArrayList<Integer>> tree = new ArrayList<ArrayList<Integer>>(); for(int i = 0; i < N; i++) tree.add(new ArrayList<Integer>()); add_edge(1, 2, tree); add_edge(1, 3, tree); add_edge(2, 4, tree); add_edge(3, 5, tree); add_edge(3, 8, tree); add_edge(5, 6, tree); add_edge(5, 7, tree); add_edge(8, 9, tree); add_edge(8, 10, tree); int []node_values = { 2, 3, 4, 4, 7, 6, 2, 3, 9, 1 }; // Function call to get the sum // of nodes of different level getSum(node_values, tree);}} // This code is contributed by avanitrachhadiya2155 # Python3 implementation of# the above approach # Function to add edges to the treedef add_edge(a, b): global tree # 0-based indexing a, b = a - 1, b - 1 tree[a].append(b) tree[b].append(a) # Function to prsum of# nodes on all levels of a treedef dfs(u, level, par, node_values): global sum, tree, depth # update max depth of tree depth = max(depth, level) # Add value of current node # to its corresponding level sum[level] = sum.get(level, 0) + node_values[u] for child in tree[u]: if (child == par): continue # Recursive traverse child nodes dfs(child, level + 1, u, node_values) # Function to calculate sum of# nodes of each level of the Treedef getSum(node_values): global sum, depth, tree # Depth of the tree # depth = 0 # Stores sum at each level # map<int, int> sum dfs(0, 0, -1, node_values) # Prfinal sum for i in range(depth + 1): print("Sum of level", i, "=", sum[i]) # Driver Codeif __name__ == '__main__': # Create a tree structure N = 10 tree = [[] for i in range(N+1)] sum = {} depth = 0 add_edge(1, 2) add_edge(1, 3) add_edge(2, 4) add_edge(3, 5) add_edge(3, 8) add_edge(5, 6) add_edge(5, 7) add_edge(8, 9) add_edge(8, 10) node_values = [2, 3, 4, 4, 7, 6, 2, 3, 9, 1] # Function call to get the sum # of nodes of different level getSum(node_values) # This code is contributed by mohit kumar 29. // C# implementation of// the above approachusing System;using System.Collections.Generic;class GFG{ static Dictionary<int, int> sum = new Dictionary<int,int>(); static int depth = 0; // Function to add edges to the treestatic void add_edge(int a, int b, List<List<int>> tree){ // 0-based indexing a--; b--; tree[a].Add(b); tree[b].Add(a);} // Function to print sum of// Nodes on all levels of a treestatic void dfs(int u, int level, int par, int []node_values, List<List<int>> tree ){ // update max depth of tree depth = Math.Max(depth, level); // Add value of current node // to its corresponding level if(sum.ContainsKey(level)) sum[level] += node_values[u]; else sum[level] = node_values[u]; foreach (int child in tree[u]) { if (child == par) continue; // Recursive traverse child nodes dfs(child, level + 1, u, node_values, tree); }} // Function to calculate sum of// nodes of each level of the Treestatic void getSum(int []node_values, List<List<int>> tree){ dfs(0, 0, -1, node_values, tree); // Print final sum for (int i = 0; i <= depth; i++) { Console.WriteLine("Sum of level " + (int) i + " = "+ sum[i]); }} // Driver Codepublic static void Main(){ // Create a tree structure int N = 10; List<List<int> > tree = new List<List<int>>(); for(int i = 0; i < N; i++) tree.Add(new List<int>()); add_edge(1, 2, tree); add_edge(1, 3, tree); add_edge(2, 4, tree); add_edge(3, 5, tree); add_edge(3, 8, tree); add_edge(5, 6, tree); add_edge(5, 7, tree); add_edge(8, 9, tree); add_edge(8, 10, tree); int []node_values = {2, 3, 4, 4, 7,6, 2, 3, 9, 1}; // Function call to get the sum // of nodes of different level getSum(node_values, tree);}} // This code is contributed by bgangwar59. <script> // Javascript implementation of// the above approachvar sum = new Map();var depth = 0; // Function to add edges to the treefunction add_edge(a, b, tree){ // 0-based indexing a--; b--; tree[a].push(b); tree[b].push(a);} // Function to print sum of// Nodes on all levels of a treefunction dfs(u, level, par, node_values, tree){ // Update max depth of tree depth = Math.max(depth, level); // Push value of current node // to its corresponding level if (sum.has(level)) sum.set(level, sum.get(level) + node_values[u]); else sum.set(level, node_values[u]) for(var child of tree[u]) { if (child == par) continue; // Recursive traverse child nodes dfs(child, level + 1, u, node_values, tree); }} // Function to calculate sum of// nodes of each level of the Treefunction getSum(node_values, tree){ dfs(0, 0, -1, node_values, tree); // Print final sum for(var i = 0; i <= depth; i++) { document.write("Sum of level " + i + " = "+ sum.get(i) + "<br>"); }} // Driver Code // Create a tree structurevar N = 10;var tree = [];for(var i = 0; i < N; i++) tree.push([]); add_edge(1, 2, tree);add_edge(1, 3, tree);add_edge(2, 4, tree);add_edge(3, 5, tree);add_edge(3, 8, tree);add_edge(5, 6, tree);add_edge(5, 7, tree);add_edge(8, 9, tree);add_edge(8, 10, tree);var node_values = [ 2, 3, 4, 4, 7,6, 2, 3, 9, 1 ]; // Function call to get the sum// of nodes of different levelgetSum(node_values, tree); // This code is contributed by rrrtnx </script> Sum of level 0 = 2 Sum of level 1 = 7 Sum of level 2 = 14 Sum of level 3 = 18 Time Complexity: O(N)Auxiliary Space: O(N) mohit kumar 29 bgangwar59 avanitrachhadiya2155 rrrtnx DFS Tree Traversals Recursion Tree Recursion DFS Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Recursive Insertion Sort Decimal to binary number using recursion Sum of natural numbers using recursion Practice Questions for Recursion | Set 1 How will you print numbers from 1 to 100 without using loop? Tree Traversals (Inorder, Preorder and Postorder) Binary Tree | Set 1 (Introduction) Level Order Binary Tree Traversal AVL Tree | Set 1 (Insertion) Inorder Tree Traversal without Recursion
[ { "code": null, "e": 24978, "s": 24950, "text": "\n29 Jun, 2021" }, { "code": null, "e": 25188, "s": 24978, "text": "Given a Generic Tree consisting of N nodes (rooted at 0) where each node is associated with a value, the task for each level of the Tree is to find the sum of all node values present at that level of the tree." }, { "code": null, "e": 25198, "s": 25188, "text": "Examples:" }, { "code": null, "e": 25301, "s": 25198, "text": "Input: node_number = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }, node_values = { 2, 3, 4, 4, 7, 6, 2, 3, 9, 1 }" }, { "code": null, "e": 25398, "s": 25301, "text": "Output: Sum of level 0 = 2Sum of level 1 = 7Sum of level 2 = 14Sum of level 3 = 18 Explanation :" }, { "code": null, "e": 25437, "s": 25398, "text": "Nodes on level 0 = {1} with value is 2" }, { "code": null, "e": 25512, "s": 25437, "text": "Nodes on level 1 = {2, 3} and their respective values are {3, 4}. Sum = 7." }, { "code": null, "e": 25587, "s": 25512, "text": "Nodes on level 2 = {4, 5, 8} with values {4, 7, 3} respectively. Sum = 14." }, { "code": null, "e": 25668, "s": 25587, "text": "Nodes on level 3 = {6, 7, 9, 10} with values {6, 2, 9, 1} respectively. Sum = 18" }, { "code": null, "e": 25744, "s": 25668, "text": "Input: node_number = { 1 }, node_values = { 10 }Output: Sum of level 0 = 10" }, { "code": null, "e": 25799, "s": 25744, "text": "Approach: Follow the steps below to solve the problem:" }, { "code": null, "e": 26037, "s": 25799, "text": "Traverse the tree using DFS or BFSStore the level of this node using this approach.Then, add the node values to the corresponding level of the node in an array, say sum[ ].Print the array sum[] showing the sum of all nodes on each level." }, { "code": null, "e": 26072, "s": 26037, "text": "Traverse the tree using DFS or BFS" }, { "code": null, "e": 26122, "s": 26072, "text": "Store the level of this node using this approach." }, { "code": null, "e": 26212, "s": 26122, "text": "Then, add the node values to the corresponding level of the node in an array, say sum[ ]." }, { "code": null, "e": 26278, "s": 26212, "text": "Print the array sum[] showing the sum of all nodes on each level." }, { "code": null, "e": 26330, "s": 26278, "text": "Below is the implementation of the above approach :" }, { "code": null, "e": 26334, "s": 26330, "text": "C++" }, { "code": null, "e": 26339, "s": 26334, "text": "Java" }, { "code": null, "e": 26347, "s": 26339, "text": "Python3" }, { "code": null, "e": 26350, "s": 26347, "text": "C#" }, { "code": null, "e": 26361, "s": 26350, "text": "Javascript" }, { "code": "// C++ implementation of// the above approach#include <bits/stdc++.h>using namespace std; // Function to add edges to the treevoid add_edge(int a, int b, vector<vector<int> >& tree){ // 0-based indexing a--, b--; tree[a].push_back(b); tree[b].push_back(a);} // Function to print sum of// nodes on all levels of a treevoid dfs(int u, int level, int par, int node_values[], vector<vector<int> >& tree, map<int, int>& sum, int& depth){ // update max depth of tree depth = max(depth, level); // Add value of current node // to its corresponding level sum[level] += node_values[u]; for (int child : tree[u]) { if (child == par) continue; // Recursive traverse child nodes dfs(child, level + 1, u, node_values, tree, sum, depth); }} // Function to calculate sum of// nodes of each level of the Treevoid getSum(int node_values[], vector<vector<int> >& tree){ // Depth of the tree int depth = 0; // Stores sum at each level map<int, int> sum; dfs(0, 0, -1, node_values, tree, sum, depth); // Print final sum for (int i = 0; i <= depth; i++) { cout << \"Sum of level \" << i << \" = \" << sum[i] << endl; }} // Driver Codeint32_t main(){ // Create a tree structure int N = 10; vector<vector<int> > tree(N); add_edge(1, 2, tree); add_edge(1, 3, tree); add_edge(2, 4, tree); add_edge(3, 5, tree); add_edge(3, 8, tree); add_edge(5, 6, tree); add_edge(5, 7, tree); add_edge(8, 9, tree); add_edge(8, 10, tree); int node_values[] = { 2, 3, 4, 4, 7, 6, 2, 3, 9, 1 }; // Function call to get the sum // of nodes of different level getSum(node_values, tree); return 0;}", "e": 28164, "s": 26361, "text": null }, { "code": "// Java implementation of// the above approachimport java.io.*;import java.util.*; class GFG{ static Map<Integer, Integer> sum = new HashMap<>();static int depth = 0; // Function to add edges to the treestatic void add_edge(int a, int b, ArrayList<ArrayList<Integer>> tree){ // 0-based indexing a--; b--; tree.get(a).add(b); tree.get(b).add(a);} // Function to print sum of// Nodes on all levels of a treestatic void dfs(int u, int level, int par, int []node_values, ArrayList<ArrayList<Integer>> tree){ // Update max depth of tree depth = Math.max(depth, level); // Add value of current node // to its corresponding level if (sum.containsKey(level)) { sum.put(level, sum.get(level) + node_values[u]); } else sum.put(level,node_values[u]); for(int child : tree.get(u)) { if (child == par) continue; // Recursive traverse child nodes dfs(child, level + 1, u, node_values, tree); }} // Function to calculate sum of// nodes of each level of the Treestatic void getSum(int []node_values, ArrayList<ArrayList<Integer>> tree){ dfs(0, 0, -1, node_values, tree); // Print final sum for(int i = 0; i <= depth; i++) { System.out.println(\"Sum of level \" + (int) i + \" = \" + sum.get(i)); }} // Driver Codepublic static void main (String[] args){ // Create a tree structure int N = 10; ArrayList<ArrayList<Integer>> tree = new ArrayList<ArrayList<Integer>>(); for(int i = 0; i < N; i++) tree.add(new ArrayList<Integer>()); add_edge(1, 2, tree); add_edge(1, 3, tree); add_edge(2, 4, tree); add_edge(3, 5, tree); add_edge(3, 8, tree); add_edge(5, 6, tree); add_edge(5, 7, tree); add_edge(8, 9, tree); add_edge(8, 10, tree); int []node_values = { 2, 3, 4, 4, 7, 6, 2, 3, 9, 1 }; // Function call to get the sum // of nodes of different level getSum(node_values, tree);}} // This code is contributed by avanitrachhadiya2155", "e": 30359, "s": 28164, "text": null }, { "code": "# Python3 implementation of# the above approach # Function to add edges to the treedef add_edge(a, b): global tree # 0-based indexing a, b = a - 1, b - 1 tree[a].append(b) tree[b].append(a) # Function to prsum of# nodes on all levels of a treedef dfs(u, level, par, node_values): global sum, tree, depth # update max depth of tree depth = max(depth, level) # Add value of current node # to its corresponding level sum[level] = sum.get(level, 0) + node_values[u] for child in tree[u]: if (child == par): continue # Recursive traverse child nodes dfs(child, level + 1, u, node_values) # Function to calculate sum of# nodes of each level of the Treedef getSum(node_values): global sum, depth, tree # Depth of the tree # depth = 0 # Stores sum at each level # map<int, int> sum dfs(0, 0, -1, node_values) # Prfinal sum for i in range(depth + 1): print(\"Sum of level\", i, \"=\", sum[i]) # Driver Codeif __name__ == '__main__': # Create a tree structure N = 10 tree = [[] for i in range(N+1)] sum = {} depth = 0 add_edge(1, 2) add_edge(1, 3) add_edge(2, 4) add_edge(3, 5) add_edge(3, 8) add_edge(5, 6) add_edge(5, 7) add_edge(8, 9) add_edge(8, 10) node_values = [2, 3, 4, 4, 7, 6, 2, 3, 9, 1] # Function call to get the sum # of nodes of different level getSum(node_values) # This code is contributed by mohit kumar 29.", "e": 31849, "s": 30359, "text": null }, { "code": "// C# implementation of// the above approachusing System;using System.Collections.Generic;class GFG{ static Dictionary<int, int> sum = new Dictionary<int,int>(); static int depth = 0; // Function to add edges to the treestatic void add_edge(int a, int b, List<List<int>> tree){ // 0-based indexing a--; b--; tree[a].Add(b); tree[b].Add(a);} // Function to print sum of// Nodes on all levels of a treestatic void dfs(int u, int level, int par, int []node_values, List<List<int>> tree ){ // update max depth of tree depth = Math.Max(depth, level); // Add value of current node // to its corresponding level if(sum.ContainsKey(level)) sum[level] += node_values[u]; else sum[level] = node_values[u]; foreach (int child in tree[u]) { if (child == par) continue; // Recursive traverse child nodes dfs(child, level + 1, u, node_values, tree); }} // Function to calculate sum of// nodes of each level of the Treestatic void getSum(int []node_values, List<List<int>> tree){ dfs(0, 0, -1, node_values, tree); // Print final sum for (int i = 0; i <= depth; i++) { Console.WriteLine(\"Sum of level \" + (int) i + \" = \"+ sum[i]); }} // Driver Codepublic static void Main(){ // Create a tree structure int N = 10; List<List<int> > tree = new List<List<int>>(); for(int i = 0; i < N; i++) tree.Add(new List<int>()); add_edge(1, 2, tree); add_edge(1, 3, tree); add_edge(2, 4, tree); add_edge(3, 5, tree); add_edge(3, 8, tree); add_edge(5, 6, tree); add_edge(5, 7, tree); add_edge(8, 9, tree); add_edge(8, 10, tree); int []node_values = {2, 3, 4, 4, 7,6, 2, 3, 9, 1}; // Function call to get the sum // of nodes of different level getSum(node_values, tree);}} // This code is contributed by bgangwar59.", "e": 33738, "s": 31849, "text": null }, { "code": "<script> // Javascript implementation of// the above approachvar sum = new Map();var depth = 0; // Function to add edges to the treefunction add_edge(a, b, tree){ // 0-based indexing a--; b--; tree[a].push(b); tree[b].push(a);} // Function to print sum of// Nodes on all levels of a treefunction dfs(u, level, par, node_values, tree){ // Update max depth of tree depth = Math.max(depth, level); // Push value of current node // to its corresponding level if (sum.has(level)) sum.set(level, sum.get(level) + node_values[u]); else sum.set(level, node_values[u]) for(var child of tree[u]) { if (child == par) continue; // Recursive traverse child nodes dfs(child, level + 1, u, node_values, tree); }} // Function to calculate sum of// nodes of each level of the Treefunction getSum(node_values, tree){ dfs(0, 0, -1, node_values, tree); // Print final sum for(var i = 0; i <= depth; i++) { document.write(\"Sum of level \" + i + \" = \"+ sum.get(i) + \"<br>\"); }} // Driver Code // Create a tree structurevar N = 10;var tree = [];for(var i = 0; i < N; i++) tree.push([]); add_edge(1, 2, tree);add_edge(1, 3, tree);add_edge(2, 4, tree);add_edge(3, 5, tree);add_edge(3, 8, tree);add_edge(5, 6, tree);add_edge(5, 7, tree);add_edge(8, 9, tree);add_edge(8, 10, tree);var node_values = [ 2, 3, 4, 4, 7,6, 2, 3, 9, 1 ]; // Function call to get the sum// of nodes of different levelgetSum(node_values, tree); // This code is contributed by rrrtnx </script>", "e": 35365, "s": 33738, "text": null }, { "code": null, "e": 35443, "s": 35365, "text": "Sum of level 0 = 2\nSum of level 1 = 7\nSum of level 2 = 14\nSum of level 3 = 18" }, { "code": null, "e": 35488, "s": 35445, "text": "Time Complexity: O(N)Auxiliary Space: O(N)" }, { "code": null, "e": 35505, "s": 35490, "text": "mohit kumar 29" }, { "code": null, "e": 35516, "s": 35505, "text": "bgangwar59" }, { "code": null, "e": 35537, "s": 35516, "text": "avanitrachhadiya2155" }, { "code": null, "e": 35544, "s": 35537, "text": "rrrtnx" }, { "code": null, "e": 35548, "s": 35544, "text": "DFS" }, { "code": null, "e": 35564, "s": 35548, "text": "Tree Traversals" }, { "code": null, "e": 35574, "s": 35564, "text": "Recursion" }, { "code": null, "e": 35579, "s": 35574, "text": "Tree" }, { "code": null, "e": 35589, "s": 35579, "text": "Recursion" }, { "code": null, "e": 35593, "s": 35589, "text": "DFS" }, { "code": null, "e": 35598, "s": 35593, "text": "Tree" }, { "code": null, "e": 35696, "s": 35598, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 35705, "s": 35696, "text": "Comments" }, { "code": null, "e": 35718, "s": 35705, "text": "Old Comments" }, { "code": null, "e": 35743, "s": 35718, "text": "Recursive Insertion Sort" }, { "code": null, "e": 35784, "s": 35743, "text": "Decimal to binary number using recursion" }, { "code": null, "e": 35823, "s": 35784, "text": "Sum of natural numbers using recursion" }, { "code": null, "e": 35864, "s": 35823, "text": "Practice Questions for Recursion | Set 1" }, { "code": null, "e": 35925, "s": 35864, "text": "How will you print numbers from 1 to 100 without using loop?" }, { "code": null, "e": 35975, "s": 35925, "text": "Tree Traversals (Inorder, Preorder and Postorder)" }, { "code": null, "e": 36010, "s": 35975, "text": "Binary Tree | Set 1 (Introduction)" }, { "code": null, "e": 36044, "s": 36010, "text": "Level Order Binary Tree Traversal" }, { "code": null, "e": 36073, "s": 36044, "text": "AVL Tree | Set 1 (Insertion)" } ]
jQuery - Quick Guide
jQuery is a fast and concise JavaScript Library created by John Resig in 2006 with a nice motto: Write less, do more. jQuery simplifies HTML document traversing, event handling, animating, and Ajax interactions for rapid web development. jQuery is a JavaScript toolkit designed to simplify various tasks by writing less code. Here is the list of important core features supported by jQuery − DOM manipulation − The jQuery made it easy to select DOM elements, negotiate them and modifying their content by using cross-browser open source selector engine called Sizzle. DOM manipulation − The jQuery made it easy to select DOM elements, negotiate them and modifying their content by using cross-browser open source selector engine called Sizzle. Event handling − The jQuery offers an elegant way to capture a wide variety of events, such as a user clicking on a link, without the need to clutter the HTML code itself with event handlers. Event handling − The jQuery offers an elegant way to capture a wide variety of events, such as a user clicking on a link, without the need to clutter the HTML code itself with event handlers. AJAX Support − The jQuery helps you a lot to develop a responsive and featurerich site using AJAX technology. AJAX Support − The jQuery helps you a lot to develop a responsive and featurerich site using AJAX technology. Animations − The jQuery comes with plenty of built-in animation effects which you can use in your websites. Animations − The jQuery comes with plenty of built-in animation effects which you can use in your websites. Lightweight − The jQuery is very lightweight library - about 19KB in size (Minified and gzipped). Lightweight − The jQuery is very lightweight library - about 19KB in size (Minified and gzipped). Cross Browser Support − The jQuery has cross-browser support, and works well in IE 6.0+, FF 2.0+, Safari 3.0+, Chrome and Opera 9.0+ Cross Browser Support − The jQuery has cross-browser support, and works well in IE 6.0+, FF 2.0+, Safari 3.0+, Chrome and Opera 9.0+ Latest Technology − The jQuery supports CSS3 selectors and basic XPath syntax. Latest Technology − The jQuery supports CSS3 selectors and basic XPath syntax. There are two ways to use jQuery. Local Installation − You can download jQuery library on your local machine and include it in your HTML code. Local Installation − You can download jQuery library on your local machine and include it in your HTML code. CDN Based Version − You can include jQuery library into your HTML code directly from Content Delivery Network (CDN). CDN Based Version − You can include jQuery library into your HTML code directly from Content Delivery Network (CDN). Go to the https://jquery.com/download/ to download the latest version available. Go to the https://jquery.com/download/ to download the latest version available. Now put downloaded jquery-2.1.3.min.js file in a directory of your website, e.g. /jquery. Now put downloaded jquery-2.1.3.min.js file in a directory of your website, e.g. /jquery. Now you can include jquery library in your HTML file as follows − <html> <head> <title>The jQuery Example</title> <script type = "text/javascript" src = "/jquery/jquery-2.1.3.min.js"> </script> <script type = "text/javascript"> $(document).ready(function() { document.write("Hello, World!"); }); </script> </head> <body> <h1>Hello</h1> </body> </html> This will produce following result − You can include jQuery library into your HTML code directly from Content Delivery Network (CDN). Google and Microsoft provides content deliver for the latest version. Now let us rewrite above example using jQuery library from Google CDN. <html> <head> <title>The jQuery Example</title> <script type = "text/javascript" src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"> </script> <script type = "text/javascript"> $(document).ready(function() { document.write("Hello, World!"); }); </script> </head> <body> <h1>Hello</h1> </body> </html> This will produce following result − As almost everything, we do when using jQuery reads or manipulates the document object model (DOM), we need to make sure that we start adding events etc. as soon as the DOM is ready. If you want an event to work on your page, you should call it inside the $(document).ready() function. Everything inside it will load as soon as the DOM is loaded and before the page contents are loaded. To do this, we register a ready event for the document as follows − $(document).ready(function() { // do stuff when DOM is ready }); To call upon any jQuery library function, use HTML script tags as shown below − <html> <head> <title>The jQuery Example</title> <script type = "text/javascript" src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"> </script> <script type = "text/javascript" language = "javascript"> $(document).ready(function() { $("div").click(function() {alert("Hello, world!");}); }); </script> </head> <body> <div id = "mydiv"> Click on this to see a dialogue box. </div> </body> </html> This will produce following result − It is better to write our custom code in the custom JavaScript file : custom.js, as follows − /* Filename: custom.js */ $(document).ready(function() { $("div").click(function() { alert("Hello, world!"); }); }); Now we can include custom.js file in our HTML file as follows − <html> <head> <title>The jQuery Example</title> <script type = "text/javascript" src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"> </script> <script type = "text/javascript" src = "/jquery/custom.js"> </script> </head> <body> <div id = "mydiv"> Click on this to see a dialogue box. </div> </body> </html> This will produce following result − You can use multiple libraries all together without conflicting each others. For example, you can use jQuery and MooTool javascript libraries together. You can check jQuery noConflict Method for more detail. Do not worry too much if you did not understand above examples. You are going to grasp them very soon in subsequent chapters. Next chapter would try to cover few basic concepts which are coming from conventional JavaScript. jQuery is a framework built using JavaScript capabilities. So, you can use all the functions and other capabilities available in JavaScript. This chapter would explain most basic concepts but frequently used in jQuery. A string in JavaScript is an immutable object that contains none, one or many characters. Following are the valid examples of a JavaScript String − "This is JavaScript String" 'This is JavaScript String' 'This is "really" a JavaScript String' "This is 'really' a JavaScript String" Numbers in JavaScript are double-precision 64-bit format IEEE 754 values. They are immutable, just as strings. Following are the valid examples of a JavaScript Numbers − 5350 120.27 0.26 A boolean in JavaScript can be either true or false. If a number is zero, it defaults to false. If an empty string defaults to false. Following are the valid examples of a JavaScript Boolean − true // true false // false 0 // false 1 // true "" // false "hello" // true JavaScript supports Object concept very well. You can create an object using the object literal as follows − var emp = { name: "Zara", age: 10 }; You can write and read properties of an object using the dot notation as follows − // Getting object properties emp.name // ==> Zara emp.age // ==> 10 // Setting object properties emp.name = "Daisy" // <== Daisy emp.age = 20 // <== 20 You can define arrays using the array literal as follows − var x = []; var y = [1, 2, 3, 4, 5]; An array has a length property that is useful for iteration − var x = [1, 2, 3, 4, 5]; for (var i = 0; i < x.length; i++) { // Do something with x[i] } A function in JavaScript can be either named or anonymous. A named function can be defined using function keyword as follows − function named(){ // do some stuff here } An anonymous function can be defined in similar way as a normal function but it would not have any name. A anonymous function can be assigned to a variable or passed to a method as shown below. var handler = function (){ // do some stuff here } JQuery makes a use of anonymous functions very frequently as follows − $(document).ready(function(){ // do some stuff here }); JavaScript variable arguments is a kind of array which has length property. Following example explains it very well − function func(x){ console.log(typeof x, arguments.length); } func(); //==> "undefined", 0 func(1); //==> "number", 1 func("1", "2", "3"); //==> "string", 3 The arguments object also has a callee property, which refers to the function you're inside of. For example − function func() { return arguments.callee; } func(); // ==> func JavaScript famous keyword this always refers to the current context. Within a function this context can change, depending on how the function is called − $(document).ready(function() { // this refers to window.document }); $("div").click(function() { // this refers to a div DOM element }); You can specify the context for a function call using the function-built-in methods call() and apply() methods. The difference between them is how they pass arguments. Call passes all arguments through as arguments to the function, while apply accepts an array as the arguments. function scope() { console.log(this, arguments.length); } scope() // window, 0 scope.call("foobar", [1,2]); //==> "foobar", 1 scope.apply("foobar", [1,2]); //==> "foobar", 2 The scope of a variable is the region of your program in which it is defined. JavaScript variable will have only two scopes. Global Variables − A global variable has global scope which means it is defined everywhere in your JavaScript code. Global Variables − A global variable has global scope which means it is defined everywhere in your JavaScript code. Local Variables − A local variable will be visible only within a function where it is defined. Function parameters are always local to that function. Local Variables − A local variable will be visible only within a function where it is defined. Function parameters are always local to that function. Within the body of a function, a local variable takes precedence over a global variable with the same name − var myVar = "global"; // ==> Declare a global variable function ( ) { var myVar = "local"; // ==> Declare a local variable document.write(myVar); // ==> local } A callback is a plain JavaScript function passed to some method as an argument or option. Some callbacks are just events, called to give the user a chance to react when a certain state is triggered. jQuery's event system uses such callbacks everywhere for example − $("body").click(function(event) { console.log("clicked: " + event.target); }); Most callbacks provide arguments and a context. In the event-handler example, the callback is called with one argument, an Event. Some callbacks are required to return something, others make that return value optional. To prevent a form submission, a submit event handler can return false as follows − $("#myform").submit(function() { return false; }); Closures are created whenever a variable that is defined outside the current scope is accessed from within some inner scope. Following example shows how the variable counter is visible within the create, increment, and print functions, but not outside of them − function create() { var counter = 0; return { increment: function() { counter++; }, print: function() { console.log(counter); } } } var c = create(); c.increment(); c.print(); // ==> 1 This pattern allows you to create objects with methods that operate on data that isn't visible to the outside world. It should be noted that data hiding is the very basis of object-oriented programming. A proxy is an object that can be used to control access to another object. It implements the same interface as this other object and passes on any method invocations to it. This other object is often called the real subject. A proxy can be instantiated in place of this real subject and allow it to be accessed remotely. We can saves jQuery's setArray method in a closure and overwrites it as follows − (function() { // log all calls to setArray var proxied = jQuery.fn.setArray; jQuery.fn.setArray = function() { console.log(this, arguments); return proxied.apply(this, arguments); }; })(); The above wraps its code in a function to hide the proxied variable. The proxy then logs all calls to the method and delegates the call to the original method. Using apply(this, arguments) guarantees that the caller won't be able to notice the difference between the original and the proxied method. JavaScript comes along with a useful set of built-in functions. These methods can be used to manipulate Strings, Numbers and Dates. Following are important JavaScript functions − charAt() Returns the character at the specified index. concat() Combines the text of two strings and returns a new string. forEach() Calls a function for each element in the array. indexOf() Returns the index within the calling String object of the first occurrence of the specified value, or -1 if not found. length() Returns the length of the string. pop() Removes the last element from an array and returns that element. push() Adds one or more elements to the end of an array and returns the new length of the array. reverse() Reverses the order of the elements of an array -- the first becomes the last, and the last becomes the first. sort() Sorts the elements of an array. substr() Returns the characters in a string beginning at the specified location through the specified number of characters. toLowerCase() Returns the calling string value converted to lower case. toString() Returns the string representation of the number's value. toUpperCase() Returns the calling string value converted to uppercase. The Document Object Model is a tree structure of various elements of HTML as follows − <html> <head> <title>The jQuery Example</title> </head> <body> <div> <p>This is a paragraph.</p> <p>This is second paragraph.</p> <p>This is third paragraph.</p> </div> </body> </html> This will produce following result − This is a paragraph. This is second paragraph. This is third paragraph. Following are the important points about the above tree structure − The <html> is the ancestor of all the other elements; in other words, all the other elements are descendants of <html>. The <html> is the ancestor of all the other elements; in other words, all the other elements are descendants of <html>. The <head> and <body> elements are not only descendants, but children of <html>, as well. The <head> and <body> elements are not only descendants, but children of <html>, as well. Likewise, in addition to being the ancestor of <head> and <body>, <html> is also their parent. Likewise, in addition to being the ancestor of <head> and <body>, <html> is also their parent. The <p> elements are children (and descendants) of <div>, descendants of <body> and <html>, and siblings of each other <p> elements. The <p> elements are children (and descendants) of <div>, descendants of <body> and <html>, and siblings of each other <p> elements. While learning jQuery concepts, it will be helpful to have understanding on DOM, if you are not aware of DOM then I would suggest to go through our simple tutorial on DOM Tutorial. The jQuery library harnesses the power of Cascading Style Sheets (CSS) selectors to let us quickly and easily access elements or groups of elements in the Document Object Model (DOM). A jQuery Selector is a function which makes use of expressions to find out matching elements from a DOM based on the given criteria. Simply you can say, selectors are used to select one or more HTML elements using jQuery. Once an element is selected then we can perform various operations on that selected element. jQuery selectors start with the dollar sign and parentheses − $(). The factory function $() makes use of following three building blocks while selecting elements in a given document − Tag Name Represents a tag name available in the DOM. For example $('p') selects all paragraphs <p> in the document. Tag ID Represents a tag available with the given ID in the DOM. For example $('#some-id') selects the single element in the document that has an ID of some-id. Tag Class Represents a tag available with the given class in the DOM. For example $('.some-class') selects all elements in the document that have a class of some-class. All the above items can be used either on their own or in combination with other selectors. All the jQuery selectors are based on the same principle except some tweaking. NOTE − The factory function $() is a synonym of jQuery() function. So in case you are using any other JavaScript library where $ sign is conflicting with some thing else then you can replace $ sign by jQuery name and you can use function jQuery() instead of $(). Following is a simple example which makes use of Tag Selector. This would select all the elements with a tag name p. <html> <head> <title>The jQuery Example</title> <script type = "text/javascript" src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"> </script> <script type = "text/javascript" language = "javascript"> $(document).ready(function() { $("p").css("background-color", "yellow"); }); </script> </head> <body> <div> <p class = "myclass">This is a paragraph.</p> <p id = "myid">This is second paragraph.</p> <p>This is third paragraph.</p> </div> </body> </html> This will produce following result − This is a paragraph. This is second paragraph. This is third paragraph. The selectors are very useful and would be required at every step while using jQuery. They get the exact element that you want from your HTML document. Following table lists down few basic selectors and explains them with examples. Selects all elements which match with the given element Name. Selects a single element which matches with the given ID. Selects all elements which match with the given Class. Selects all elements available in a DOM. Selects the combined results of all the specified selectors E, F or G. Similar to above syntax and examples, following examples would give you understanding on using different type of other useful selectors − $('*') This selector selects all elements in the document. $("p > *") This selector selects all elements that are children of a paragraph element. $("#specialID") This selector function gets the element with id="specialID". $(".specialClass") This selector gets all the elements that have the class of specialClass. $("li:not(.myclass)") Selects all elements matched by <li> that do not have class = "myclass". $("a#specialID.specialClass") This selector matches links with an id of specialID and a class of specialClass. $("p a.specialClass") This selector matches links with a class of specialClass declared within <p> elements. $("ul li:first") This selector gets only the first <li> element of the <ul>. $("#container p") Selects all elements matched by <p> that are descendants of an element that has an id of container. $("li > ul") Selects all elements matched by <ul> that are children of an element matched by <li> $("strong + em") Selects all elements matched by <em> that immediately follow a sibling element matched by <strong>. $("p ~ ul") Selects all elements matched by <ul> that follow a sibling element matched by <p>. $("code, em, strong") Selects all elements matched by <code> or <em> or <strong>. $("p strong, .myclass") Selects all elements matched by <strong> that are descendants of an element matched by <p> as well as all elements that have a class of myclass. $(":empty") Selects all elements that have no children. $("p:empty") Selects all elements matched by <p> that have no children. $("div[p]") Selects all elements matched by <div> that contain an element matched by <p>. $("p[.myclass]") Selects all elements matched by <p> that contain an element with a class of myclass. $("a[@rel]") Selects all elements matched by <a> that have a rel attribute. $("input[@name = myname]") Selects all elements matched by <input> that have a name value exactly equal to myname. $("input[@name^=myname]") Selects all elements matched by <input> that have a name value beginning with myname. $("a[@rel$=self]") Selects all elements matched by <a> that have rel attribute value ending with self. $("a[@href*=domain.com]") Selects all elements matched by <a> that have an href value containing domain.com. $("li:even") Selects all elements matched by <li> that have an even index value. $("tr:odd") Selects all elements matched by <tr> that have an odd index value. $("li:first") Selects the first <li> element. $("li:last") Selects the last <li> element. $("li:visible") Selects all elements matched by <li> that are visible. $("li:hidden") Selects all elements matched by <li> that are hidden. $(":radio") Selects all radio buttons in the form. $(":checked") Selects all checked box in the form. $(":input") Selects only form elements (input, select, textarea, button). $(":text") Selects only text elements (input[type = text]). $("li:eq(2)") Selects the third <li> element. $("li:eq(4)") Selects the fifth <li> element. $("li:lt(2)") Selects all elements matched by <li> element before the third one; in other words, the first two <li> elements. $("p:lt(3)") selects all elements matched by <p> elements before the fourth one; in other words the first three <p> elements. $("li:gt(1)") Selects all elements matched by <li> after the second one. $("p:gt(2)") Selects all elements matched by <p> after the third one. $("div/p") Selects all elements matched by <p> that are children of an element matched by <div>. $("div//code") Selects all elements matched by <code>that are descendants of an element matched by <div>. $("//p//a") Selects all elements matched by <a> that are descendants of an element matched by <p> $("li:first-child") Selects all elements matched by <li> that are the first child of their parent. $("li:last-child") Selects all elements matched by <li> that are the last child of their parent. $(":parent") Selects all elements that are the parent of another element, including text. $("li:contains(second)") Selects all elements matched by <li> that contain the text second. You can use all the above selectors with any HTML/XML element in generic way. For example if selector $("li:first") works for <li> element then $("p:first") would also work for <p> element. Some of the most basic components we can manipulate when it comes to DOM elements are the properties and attributes assigned to those elements. Most of these attributes are available through JavaScript as DOM node properties. Some of the more common properties are − className tagName id href title rel src Consider the following HTML markup for an image element − <img id = "imageid" src = "image.gif" alt = "Image" class = "myclass" title = "This is an image"/> In this element's markup, the tag name is img, and the markup for id, src, alt, class, and title represents the element's attributes, each of which consists of a name and a value. jQuery gives us the means to easily manipulate an element's attributes and gives us access to the element so that we can also change its properties. The attr() method can be used to either fetch the value of an attribute from the first element in the matched set or set attribute values onto all matched elements. Following is a simple example which fetches title attribute of <em> tag and set <div id = "divid"> value with the same value − <html> <head> <title>The jQuery Example</title> <script type = "text/javascript" src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"> </script> <script type = "text/javascript" language = "javascript"> $(document).ready(function() { var title = $("em").attr("title"); $("#divid").text(title); }); </script> </head> <body> <div> <em title = "Bold and Brave">This is first paragraph.</em> <p id = "myid">This is second paragraph.</p> <div id = "divid"></div> </div> </body> </html> This will produce following result − This is second paragraph. The attr(name, value) method can be used to set the named attribute onto all elements in the wrapped set using the passed value. Following is a simple example which set src attribute of an image tag to a correct location − <html> <head> <title>The jQuery Example</title> <base href="https://www.tutorialspoint.com" /> <script type = "text/javascript" src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"> </script> <script type = "text/javascript" language = "javascript"> $(document).ready(function() { $("#myimg").attr("src", "/jquery/images/jquery.jpg"); }); </script> </head> <body> <div> <img id = "myimg" src = "/images/jquery.jpg" alt = "Sample image" /> </div> </body> </html> This will produce following result − The addClass( classes ) method can be used to apply defined style sheets onto all the matched elements. You can specify multiple classes separated by space. Following is a simple example which sets class attribute of a para <p> tag − <html> <head> <title>The jQuery Example</title> <script type = "text/javascript" src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"> </script> <script type = "text/javascript" language = "javascript"> $(document).ready(function() { $("em").addClass("selected"); $("#myid").addClass("highlight"); }); </script> <style> .selected { color:red; } .highlight { background:yellow; } </style> </head> <body> <em title = "Bold and Brave">This is first paragraph.</em> <p id = "myid">This is second paragraph.</p> </body> </html> This will produce following result − This is second paragraph. Following table lists down few useful methods which you can use to manipulate attributes and properties − Set a key/value object as properties to all matched elements. Set a single property to a computed value, on all matched elements. Remove an attribute from each of the matched elements. Returns true if the specified class is present on at least one of the set of matched elements. Removes all or the specified class(es) from the set of matched elements. Adds the specified class if it is not present, removes the specified class if it is present. Get the html contents (innerHTML) of the first matched element. Set the html contents of every matched element. Get the combined text contents of all matched elements. Set the text contents of all matched elements. Get the input value of the first matched element. Set the value attribute of every matched element if it is called on <input> but if it is called on <select> with the passed <option> value then passed option would be selected, if it is called on check box or radio box then all the matching check box and radiobox would be checked. Similar to above syntax and examples, following examples would give you understanding on using various attribute methods in different situation − $("#myID").attr("custom") This would return value of attribute custom for the first element matching with ID myID. $("img").attr("alt", "Sample Image") This sets the alt attribute of all the images to a new value "Sample Image". $("input").attr({ value: "", title: "Please enter a value" }); Sets the value of all <input> elements to the empty string, as well as sets The jQuery Example to the string Please enter a value. $("a[href^=https://]").attr("target","_blank") Selects all links with an href attribute starting with https:// and set its target attribute to _blank. $("a").removeAttr("target") This would remove target attribute of all the links. $("form").submit(function() {$(":submit",this).attr("disabled", "disabled");}); This would modify the disabled attribute to the value "disabled" while clicking Submit button. $("p:last").hasClass("selected") This return true if last <p> tag has associated classselected. $("p").text() Returns string that contains the combined text contents of all matched <p> elements. $("p").text("<i>Hello World</i>") This would set "<I>Hello World</I>" as text content of the matching <p> elements. $("p").html() This returns the HTML content of the all matching paragraphs. $("div").html("Hello World") This would set the HTML content of all matching <div> to Hello World. $("input:checkbox:checked").val() Get the first value from a checked checkbox. $("input:radio[name=bar]:checked").val() Get the first value from a set of radio buttons. $("button").val("Hello") Sets the value attribute of every matched element <button>. $("input").val("on") This would check all the radio or check box button whose value is "on". $("select").val("Orange") This would select Orange option in a dropdown box with options Orange, Mango and Banana. $("select").val("Orange", "Mango") This would select Orange and Mango options in a dropdown box with options Orange, Mango and Banana. jQuery is a very powerful tool which provides a variety of DOM traversal methods to help us select elements in a document randomly as well as in sequential method. Most of the DOM Traversal Methods do not modify the jQuery object and they are used to filter out elements from a document based on given conditions. Consider a simple document with the following HTML content − <html> <head> <title>The JQuery Example</title> </head> <body> <div> <ul> <li>list item 1</li> <li>list item 2</li> <li>list item 3</li> <li>list item 4</li> <li>list item 5</li> <li>list item 6</li> </ul> </div> </body> </html> This will produce following result − list item 1 list item 2 list item 3 list item 4 list item 5 list item 6 Above every list has its own index, and can be located directly by using eq(index) method as below example. Above every list has its own index, and can be located directly by using eq(index) method as below example. Every child element starts its index from zero, thus, list item 2 would be accessed by using $("li").eq(1) and so on. Every child element starts its index from zero, thus, list item 2 would be accessed by using $("li").eq(1) and so on. Following is a simple example which adds the color to second list item. <html> <head> <title>The JQuery Example</title> <script type = "text/javascript" src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"> </script> <script type = "text/javascript" language = "javascript"> $(document).ready(function() { $("li").eq(2).addClass("selected"); }); </script> <style> .selected { color:red; } </style> </head> <body> <div> <ul> <li>list item 1</li> <li>list item 2</li> <li>list item 3</li> <li>list item 4</li> <li>list item 5</li> <li>list item 6</li> </ul> </div> </body> </html> This will produce following result − list item 1 list item 2 list item 3 list item 4 list item 5 list item 6 The filter( selector ) method can be used to filter out all elements from the set of matched elements that do not match the specified selector(s). The selector can be written using any selector syntax. Following is a simple example which applies color to the lists associated with middle class − <html> <head> <title>The JQuery Example</title> <script type = "text/javascript" src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"> </script> <script type = "text/javascript" language = "javascript"> $(document).ready(function() { $("li").filter(".middle").addClass("selected"); }); </script> <style> .selected { color:red; } </style> </head> <body> <div> <ul> <li class = "top">list item 1</li> <li class = "top">list item 2</li> <li class = "middle">list item 3</li> <li class = "middle">list item 4</li> <li class = "bottom">list item 5</li> <li class = "bottom">list item 6</li> </ul> </div> </body> </html> This will produce following result − list item 1 list item 2 list item 3 list item 4 list item 5 list item 6 The find( selector ) method can be used to locate all the descendant elements of a particular type of elements. The selector can be written using any selector syntax. Following is an example which selects all the <span> elements available inside different <p> elements − <html> <head> <title>The JQuery Example</title> <script type = "text/javascript" src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"> </script> <script type = "text/javascript" language = "javascript"> $(document).ready(function() { $("p").find("span").addClass("selected"); }); </script> <style> .selected { color:red; } </style> </head> <body> <p>This is 1st paragraph and <span>THIS IS RED</span></p> <p>This is 2nd paragraph and <span>THIS IS ALSO RED</span></p> </body> </html> This will produce following result − This is 1st paragraph and THIS IS RED This is 2nd paragraph and THIS IS ALSO RED Following table lists down useful methods which you can use to filter out various elements from a list of DOM elements − Reduce the set of matched elements to a single element. Removes all elements from the set of matched elements that do not match the specified selector(s). Removes all elements from the set of matched elements that do not match the specified function. Checks the current selection against an expression and returns true, if at least one element of the selection fits the given selector. Translate a set of elements in the jQuery object into another set of values in a jQuery array (which may, or may not contain elements). Removes elements matching the specified selector from the set of matched elements. Selects a subset of the matched elements. Following table lists down other useful methods which you can use to locate various elements in a DOM − Adds more elements, matched by the given selector, to the set of matched elements. Add the previous selection to the current selection. Get a set of elements containing all of the unique immediate children of each of the matched set of elements. Get a set of elements containing the closest parent element that matches the specified selector, the starting element included. Find all the child nodes inside the matched elements (including text nodes), or the content document, if the element is an iframe. Revert the most recent 'destructive' operation, changing the set of matched elements to its previous state. Searches for descendant elements that match the specified selectors. Get a set of elements containing the unique next siblings of each of the given set of elements. Find all sibling elements after the current element. Returns a jQuery collection with the positioned parent of the first matched element. Get the direct parent of an element. If called on a set of elements, parent returns a set of their unique direct parent elements. Get a set of elements containing the unique ancestors of the matched set of elements (except for the root element). Get a set of elements containing the unique previous siblings of each of the matched set of elements. Find all sibling elements in front of the current element. Get a set of elements containing all of the unique siblings of each of the matched set of elements. The jQuery library supports nearly all of the selectors included in Cascading Style Sheet (CSS) specifications 1 through 3, as outlined on the World Wide Web Consortium's site. Using JQuery library developers can enhance their websites without worrying about browsers and their versions as long as the browsers have JavaScript enabled. Most of the JQuery CSS Methods do not modify the content of the jQuery object and they are used to apply CSS properties on DOM elements. This is very simple to apply any CSS property using JQuery method css( PropertyName, PropertyValue ). Here is the syntax for the method − selector.css( PropertyName, PropertyValue ); Here you can pass PropertyName as a javascript string and based on its value, PropertyValue could be string or integer. Following is an example which adds font color to the second list item. <html> <head> <title>The jQuery Example</title> <script type = "text/javascript" src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"> </script> <script type = "text/javascript" language = "javascript"> $(document).ready(function() { $("li").eq(2).css("color", "red"); }); </script> </head> <body> <div> <ul> <li>list item 1</li> <li>list item 2</li> <li>list item 3</li> <li>list item 4</li> <li>list item 5</li> <li>list item 6</li> </ul> </div> </body> </html> This will produce following result − list item 1 list item 2 list item 3 list item 4 list item 5 list item 6 You can apply multiple CSS properties using a single JQuery method CSS( {key1:val1, key2:val2....). You can apply as many properties as you like in a single call. Here is the syntax for the method − selector.css( {key1:val1, key2:val2....keyN:valN}) Here you can pass key as property and val as its value as described above. Following is an example which adds font color as well as background color to the second list item. <html> <head> <title>The jQuery Example</title> <script type = "text/javascript" src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"> </script> <script type = "text/javascript" language = "javascript"> $(document).ready(function() { $("li").eq(2).css({"color":"red", "background-color":"green"}); }); </script> </head> <body> <div> <ul> <li>list item 1</li> <li>list item 2</li> <li>list item 3</li> <li>list item 4</li> <li>list item 5</li> <li>list item 6</li> </ul> </div> </body> </html> This will produce following result − list item 1 list item 2 list item 3 list item 4 list item 5 list item 6 The width( val ) and height( val ) method can be used to set the width and height respectively of any element. Following is a simple example which sets the width of first division element where as rest of the elements have width set by style sheet <html> <head> <title>The jQuery Example</title> <script type = "text/javascript" src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"> </script> <script type = "text/javascript" language = "javascript"> $(document).ready(function() { $("div:first").width(100); $("div:first").css("background-color", "blue"); }); </script> <style> div { width:70px; height:50px; float:left; margin:5px; background:red; cursor:pointer; } </style> </head> <body> <div></div> <div>d</div> <div>d</div> <div>d</div> <div>d</div> </body> </html> This will produce following result − Following table lists down all the methods which you can use to play with CSS properties − Return a style property on the first matched element. Set a single style property to a value on all matched elements. Set a key/value object as style properties to all matched elements. Set the CSS height of every matched element. Get the current computed, pixel, height of the first matched element. Gets the inner height (excludes the border and includes the padding) for the first matched element. Gets the inner width (excludes the border and includes the padding) for the first matched element. Get the current offset of the first matched element, in pixels, relative to the document. Returns a jQuery collection with the positioned parent of the first matched element. Gets the outer height (includes the border and padding by default) for the first matched element. Get the outer width (includes the border and padding by default) for the first matched element. Gets the top and left position of an element relative to its offset parent. When a value is passed in, the scroll left offset is set to that value on all matched elements. Gets the scroll left offset of the first matched element. When a value is passed in, the scroll top offset is set to that value on all matched elements. Gets the scroll top offset of the first matched element. Set the CSS width of every matched element. Get the current computed, pixel, width of the first matched element. JQuery provides methods to manipulate DOM in efficient way. You do not need to write big code to modify the value of any element's attribute or to extract HTML code from a paragraph or division. JQuery provides methods such as .attr(), .html(), and .val() which act as getters, retrieving information from DOM elements for later use. The html( ) method gets the html contents (innerHTML) of the first matched element. Here is the syntax for the method − selector.html( ) Following is an example which makes use of .html() and .text(val) methods. Here .html() retrieves HTML content from the object and then .text( val ) method sets value of the object using passed parameter − <html> <head> <title>The jQuery Example</title> <script type = "text/javascript" src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"> </script> <script type = "text/javascript" language = "javascript"> $(document).ready(function() { $("div").click(function () { var content = $(this).html(); $("#result").text( content ); }); }); </script> <style> #division{ margin:10px;padding:12px; border:2px solid #666; width:60px;} </style> </head> <body> <p>Click on the square below:</p> <span id = "result"> </span> <div id = "division" style = "background-color:blue;"> This is Blue Square!! </div> </body> </html> This will produce following result − Click on the square below − You can replace a complete DOM element with the specified HTML or DOM elements. The replaceWith( content ) method serves this purpose very well. Here is the syntax for the method − selector.replaceWith( content ) Here content is what you want to have instead of original element. This could be HTML or simple text. Following is an example which would replace division element with "<h1>JQuery is Great </h1>" − <html> <head> <title>The jQuery Example</title> <script type = "text/javascript" src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"> </script> <script type = "text/javascript" language = "javascript"> $(document).ready(function() { $("div").click(function () { $(this).replaceWith("<h1>JQuery is Great</h1>"); }); }); </script> <style> #division{ margin:10px;padding:12px; border:2px solid #666; width:60px;} </style> </head> <body> <p>Click on the square below:</p> <span id = "result"> </span> <div id = "division" style = "background-color:blue;"> This is Blue Square!! </div> </body> </html> This will produce following result − Click on the square below − There may be a situation when you would like to remove one or more DOM elements from the document. JQuery provides two methods to handle the situation. The empty( ) method remove all child nodes from the set of matched elements where as the method remove( expr ) method removes all matched elements from the DOM. Here is the syntax for the method − selector.remove( [ expr ]) or selector.empty( ) You can pass optional parameter expr to filter the set of elements to be removed. Following is an example where elements are being removed as soon as they are clicked − <html> <head> <title>The jQuery Example</title> <script type = "text/javascript" src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"> </script> <script type = "text/javascript" language = "javascript"> $(document).ready(function() { $("div").click(function () { $(this).remove( ); }); }); </script> <style> .div{ margin:10px;padding:12px; border:2px solid #666; width:60px;} </style> </head> <body> <p>Click on any square below:</p> <span id = "result"> </span> <div class = "div" style = "background-color:blue;"></div> <div class = "div" style = "background-color:green;"></div> <div class = "div" style = "background-color:red;"></div> </body> </html> This will produce following result − Click on any square below − There may be a situation when you would like to insert new one or more DOM elements in your existing document. JQuery provides various methods to insert elements at various locations. The after( content ) method insert content after each of the matched elements where as the method before( content ) method inserts content before each of the matched elements. Here is the syntax for the method − selector.after( content ) or selector.before( content ) Here content is what you want to insert. This could be HTML or simple text. Following is an example where <div> elements are being inserted just before the clicked element − <html> <head> <title>The jQuery Example</title> <script type = "text/javascript" src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"> </script> <script type = "text/javascript" language = "javascript"> $(document).ready(function() { $("div").click(function () { $(this).before('<div class="div"></div>' ); }); }); </script> <style> .div{ margin:10px;padding:12px; border:2px solid #666; width:60px;} </style> </head> <body> <p>Click on any square below:</p> <span id = "result"> </span> <div class = "div" style = "background-color:blue;"></div> <div class = "div" style = "background-color:green;"></div> <div class = "div" style = "background-color:red;"></div> </body> </html> This will produce following result − Click on any square below − Following table lists down all the methods which you can use to manipulate DOM elements − Insert content after each of the matched elements. Append content to the inside of every matched element. Append all of the matched elements to another, specified, set of elements. Insert content before each of the matched elements. Clone matched DOM Elements, and all their event handlers, and select the clones. Clone matched DOM Elements and select the clones. Remove all child nodes from the set of matched elements. Set the html contents of every matched element. Get the html contents (innerHTML) of the first matched element. Insert all of the matched elements after another, specified, set of elements. Insert all of the matched elements before another, specified, set of elements. Prepend content to the inside of every matched element. Prepend all of the matched elements to another, specified, set of elements. Removes all matched elements from the DOM. Replaces the elements matched by the specified selector with the matched elements. Replaces all matched elements with the specified HTML or DOM elements. Set the text contents of all matched elements. Get the combined text contents of all matched elements. Wrap each matched element with the specified element. Wrap each matched element with the specified HTML content. Wrap all the elements in the matched set into a single wrapper element. Wrap all the elements in the matched set into a single wrapper element. Wrap the inner child contents of each matched element (including text nodes) with a DOM element. Wrap the inner child contents of each matched element (including text nodes) with an HTML structure. We have the ability to create dynamic web pages by using events. Events are actions that can be detected by your Web Application. Following are the examples events − A mouse click A web page loading Taking mouse over an element Submitting an HTML form A keystroke on your keyboard, etc. When these events are triggered, you can then use a custom function to do pretty much whatever you want with the event. These custom functions call Event Handlers. Using the jQuery Event Model, we can establish event handlers on DOM elements with the bind() method as follows − <html> <head> <title>The jQuery Example</title> <script type = "text/javascript" src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"> </script> <script type = "text/javascript" language = "javascript"> $(document).ready(function() { $('div').bind('click', function( event ){ alert('Hi there!'); }); }); </script> <style> .div{ margin:10px;padding:12px; border:2px solid #666; width:60px;} </style> </head> <body> <p>Click on any square below to see the result:</p> <div class = "div" style = "background-color:blue;">ONE</div> <div class = "div" style = "background-color:green;">TWO</div> <div class = "div" style = "background-color:red;">THREE</div> </body> </html> This code will cause the division element to respond to the click event; when a user clicks inside this division thereafter, the alert will be shown. This will produce following result − Click on any square below to see the result − The full syntax of the bind() command is as follows − selector.bind( eventType[, eventData], handler) Following is the description of the parameters − eventType − A string containing a JavaScript event type, such as click or submit. Refer to the next section for a complete list of event types. eventType − A string containing a JavaScript event type, such as click or submit. Refer to the next section for a complete list of event types. eventData − This is optional parameter is a map of data that will be passed to the event handler. eventData − This is optional parameter is a map of data that will be passed to the event handler. handler − A function to execute each time the event is triggered. handler − A function to execute each time the event is triggered. Typically, once an event handler is established, it remains in effect for the remainder of the life of the page. There may be a need when you would like to remove event handler. jQuery provides the unbind() command to remove an exiting event handler. The syntax of unbind() is as follows − selector.unbind(eventType, handler) or selector.unbind(eventType) Following is the description of the parameters − eventType − A string containing a JavaScript event type, such as click or submit. Refer to the next section for a complete list of event types. eventType − A string containing a JavaScript event type, such as click or submit. Refer to the next section for a complete list of event types. handler − If provided, identifies the specific listener that's to be removed. handler − If provided, identifies the specific listener that's to be removed. blur Occurs when the element loses focus. change Occurs when the element changes. click Occurs when a mouse click. dblclick Occurs when a mouse double-click. error Occurs when there is an error in loading or unloading etc. focus Occurs when the element gets focus. keydown Occurs when key is pressed. keypress Occurs when key is pressed and released. keyup Occurs when key is released. load Occurs when document is loaded. mousedown Occurs when mouse button is pressed. mouseenter Occurs when mouse enters in an element region. mouseleave Occurs when mouse leaves an element region. mousemove Occurs when mouse pointer moves. mouseout Occurs when mouse pointer moves out of an element. mouseover Occurs when mouse pointer moves over an element. mouseup Occurs when mouse button is released. resize Occurs when window is resized. scroll Occurs when window is scrolled. select Occurs when a text is selected. submit Occurs when form is submitted. unload Occurs when documents is unloaded. The callback function takes a single parameter; when the handler is called the JavaScript event object will be passed through it. The event object is often unnecessary and the parameter is omitted, as sufficient context is usually available when the handler is bound to know exactly what needs to be done when the handler is triggered, however there are certain attributes which you would need to be accessed. altKey Set to true if the Alt key was pressed when the event was triggered, false if not. The Alt key is labeled Option on most Mac keyboards. ctrlKey Set to true if the Ctrl key was pressed when the event was triggered, false if not. data The value, if any, passed as the second parameter to the bind() command when the handler was established. keyCode For keyup and keydown events, this returns the key that was pressed. metaKey Set to true if the Meta key was pressed when the event was triggered, false if not. The Meta key is the Ctrl key on PCs and the Command key on Macs. pageX For mouse events, specifies the horizontal coordinate of the event relative from the page origin. pageY For mouse events, specifies the vertical coordinate of the event relative from the page origin. relatedTarget For some mouse events, identifies the element that the cursor left or entered when the event was triggered. screenX For mouse events, specifies the horizontal coordinate of the event relative from the screen origin. screenY For mouse events, specifies the vertical coordinate of the event relative from the screen origin. shiftKey Set to true if the Shift key was pressed when the event was triggered, false if not. target Identifies the element for which the event was triggered. timeStamp The timestamp (in milliseconds) when the event was created. type For all events, specifies the type of event that was triggered (for example, click). which For keyboard events, specifies the numeric code for the key that caused the event, and for mouse events, specifies which button was pressed (1 for left, 2 for middle, 3 for right). <html> <head> <title>The jQuery Example</title> <script type = "text/javascript" src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"> </script> <script type = "text/javascript" language = "javascript"> $(document).ready(function() { $('div').bind('click', function( event ){ alert('Event type is ' + event.type); alert('pageX : ' + event.pageX); alert('pageY : ' + event.pageY); alert('Target : ' + event.target.innerHTML); }); }); </script> <style> .div{ margin:10px;padding:12px; border:2px solid #666; width:60px;} </style> </head> <body> <p>Click on any square below to see the result:</p> <div class = "div" style = "background-color:blue;">ONE</div> <div class = "div" style = "background-color:green;">TWO</div> <div class = "div" style = "background-color:red;">THREE</div> </body> </html> This will produce following result − Click on any square below to see the result − There is a list of methods which can be called on an Event Object − Prevents the browser from executing the default action. Returns whether event.preventDefault() was ever called on this event object. Stops the bubbling of an event to parent elements, preventing any parent handlers from being notified of the event. Returns whether event.stopPropagation() was ever called on this event object. Stops the rest of the handlers from being executed. Returns whether event.stopImmediatePropagation() was ever called on this event object. Following table lists down important event-related methods − Binds a handler to one or more events (like click) for each matched element. Can also bind custom events. This does the opposite of live, it removes a bound live event. Simulates hovering for example moving the mouse on, and off, an object. Binds a handler to an event (like click) for all current − and future − matched element. Can also bind custom events. Binds a handler to one or more events to be executed once for each matched element. Binds a function to be executed whenever the DOM is ready to be traversed and manipulated. Trigger an event on every matched element. Triggers all bound event handlers on an element. This does the opposite of bind, it removes bound events from each of the matched elements. jQuery also provides a set of event helper functions which can be used either to trigger an event to bind any event types mentioned above. Following is an example which would triggers the blur event on all paragraphs − $("p").blur(); Following is an example which would bind a click event on all the <div> − $("div").click( function () { // do something here }); blur( ) Triggers the blur event of each matched element. blur( fn ) Bind a function to the blur event of each matched element. change( ) Triggers the change event of each matched element. change( fn ) Binds a function to the change event of each matched element. click( ) Triggers the click event of each matched element. click( fn ) Binds a function to the click event of each matched element. dblclick( ) Triggers the dblclick event of each matched element. dblclick( fn ) Binds a function to the dblclick event of each matched element. error( ) Triggers the error event of each matched element. error( fn ) Binds a function to the error event of each matched element. focus( ) Triggers the focus event of each matched element. focus( fn ) Binds a function to the focus event of each matched element. keydown( ) Triggers the keydown event of each matched element. keydown( fn ) Bind a function to the keydown event of each matched element. keypress( ) Triggers the keypress event of each matched element. keypress( fn ) Binds a function to the keypress event of each matched element. keyup( ) Triggers the keyup event of each matched element. keyup( fn ) Bind a function to the keyup event of each matched element. load( fn ) Binds a function to the load event of each matched element. mousedown( fn ) Binds a function to the mousedown event of each matched element. mouseenter( fn ) Bind a function to the mouseenter event of each matched element. mouseleave( fn ) Bind a function to the mouseleave event of each matched element. mousemove( fn ) Bind a function to the mousemove event of each matched element. mouseout( fn ) Bind a function to the mouseout event of each matched element. mouseover( fn ) Bind a function to the mouseover event of each matched element. mouseup( fn ) Bind a function to the mouseup event of each matched element. resize( fn ) Bind a function to the resize event of each matched element. scroll( fn ) Bind a function to the scroll event of each matched element. select( ) Trigger the select event of each matched element. select( fn ) Bind a function to the select event of each matched element. submit( ) Trigger the submit event of each matched element. submit( fn ) Bind a function to the submit event of each matched element. unload( fn ) Binds a function to the unload event of each matched element. AJAX is an acronym standing for Asynchronous JavaScript and XML and this technology helps us to load data from the server without a browser page refresh. If you are new with AJAX, I would recommend you go through our Ajax Tutorial before proceeding further. JQuery is a great tool which provides a rich set of AJAX methods to develop next generation web application. This is very easy to load any static or dynamic data using JQuery AJAX. JQuery provides load() method to do the job − Here is the simple syntax for load() method − [selector].load( URL, [data], [callback] ); Here is the description of all the parameters − URL − The URL of the server-side resource to which the request is sent. It could be a CGI, ASP, JSP, or PHP script which generates data dynamically or out of a database. URL − The URL of the server-side resource to which the request is sent. It could be a CGI, ASP, JSP, or PHP script which generates data dynamically or out of a database. data − This optional parameter represents an object whose properties are serialized into properly encoded parameters to be passed to the request. If specified, the request is made using the POST method. If omitted, the GET method is used. data − This optional parameter represents an object whose properties are serialized into properly encoded parameters to be passed to the request. If specified, the request is made using the POST method. If omitted, the GET method is used. callback − A callback function invoked after the response data has been loaded into the elements of the matched set. The first parameter passed to this function is the response text received from the server and second parameter is the status code. callback − A callback function invoked after the response data has been loaded into the elements of the matched set. The first parameter passed to this function is the response text received from the server and second parameter is the status code. Consider the following HTML file with a small JQuery coding − <html> <head> <title>The jQuery Example</title> <script type = "text/javascript" src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"> </script> <script type = "text/javascript" language = "javascript"> $(document).ready(function() { $("#driver").click(function(event){ $('#stage').load('/jquery/result.html'); }); }); </script> </head> <body> <p>Click on the button to load /jquery/result.html file −</p> <div id = "stage" style = "background-color:cc0;"> STAGE </div> <input type = "button" id = "driver" value = "Load Data" /> </body> </html> Here load() initiates an Ajax request to the specified URL /jquery/result.html file. After loading this file, all the content would be populated inside <div> tagged with ID stage. Assuming, our /jquery/result.html file has just one HTML line − <h1>THIS IS RESULT...</h1> When you click the given button, then result.html file gets loaded. Click on the button to load result.html file − There would be a situation when server would return JSON string against your request. JQuery utility function getJSON() parses the returned JSON string and makes the resulting string available to the callback function as first parameter to take further action. Here is the simple syntax for getJSON() method − [selector].getJSON( URL, [data], [callback] ); Here is the description of all the parameters − URL − The URL of the server-side resource contacted via the GET method. URL − The URL of the server-side resource contacted via the GET method. data − An object whose properties serve as the name/value pairs used to construct a query string to be appended to the URL, or a preformatted and encoded query string. data − An object whose properties serve as the name/value pairs used to construct a query string to be appended to the URL, or a preformatted and encoded query string. callback − A function invoked when the request completes. The data value resulting from digesting the response body as a JSON string is passed as the first parameter to this callback, and the status as the second. callback − A function invoked when the request completes. The data value resulting from digesting the response body as a JSON string is passed as the first parameter to this callback, and the status as the second. Consider the following HTML file with a small JQuery coding − <html> <head> <title>The jQuery Example</title> <script type = "text/javascript" src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"> </script> <script type = "text/javascript" language = "javascript"> $(document).ready(function() { $("#driver").click(function(event){ $.getJSON('/jquery/result.json', function(jd) { $('#stage').html('<p> Name: ' + jd.name + '</p>'); $('#stage').append('<p>Age : ' + jd.age+ '</p>'); $('#stage').append('<p> Sex: ' + jd.sex+ '</p>'); }); }); }); </script> </head> <body> <p>Click on the button to load result.json file −</p> <div id = "stage" style = "background-color:#eee;"> STAGE </div> <input type = "button" id = "driver" value = "Load Data" /> </body> </html> Here JQuery utility method getJSON() initiates an Ajax request to the specified URL result.json file. After loading this file, all the content would be passed to the callback function which finally would be populated inside <div> tagged with ID stage. Assuming, our result.json file has following json formatted content − { "name": "Zara Ali", "age" : "67", "sex": "female" } When you click the given button, then result.json file gets loaded. Click on the button to load result.html file − Many times you collect input from the user and you pass that input to the server for further processing. JQuery AJAX made it easy enough to pass collected data to the server using data parameter of any available Ajax method. This example demonstrate how can pass user input to a web server script which would send the same result back and we would print it − <html> <head> <title>The jQuery Example</title> <script type = "text/javascript" src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"> </script> <script type = "text/javascript" language = "javascript"> $(document).ready(function() { $("#driver").click(function(event){ var name = $("#name").val(); $("#stage").load('/jquery/result.php', {"name":name} ); }); }); </script> </head> <body> <p>Enter your name and click on the button:</p> <input type = "input" id = "name" size = "40" /><br /> <div id = "stage" style = "background-color:cc0;"> STAGE </div> <input type = "button" id = "driver" value = "Show Result" /> </body> </html> Here is the code written in result.php script − <?php if( $_REQUEST["name"] ){ $name = $_REQUEST['name']; echo "Welcome ". $name; } ?> Now you can enter any text in the given input box and then click "Show Result" button to see what you have entered in the input box. Enter your name and click on the button − You have seen basic concept of AJAX using JQuery. Following table lists down all important JQuery AJAX methods which you can use based your programming need − Load a remote page using an HTTP request. Setup global settings for AJAX requests. Load a remote page using an HTTP GET request. Load JSON data using an HTTP GET request. Loads and executes a JavaScript file using an HTTP GET request. Load a remote page using an HTTP POST request. Load HTML from a remote file and inject it into the DOM. Serializes a set of input elements into a string of data. Serializes all forms and form elements like the .serialize() method but returns a JSON data structure for you to work with. You can call various JQuery methods during the life cycle of AJAX call progress. Based on different events/stages following methods are available − You can go through all the AJAX Events. Attach a function to be executed whenever an AJAX request completes. Attach a function to be executed whenever an AJAX request begins and there is none already active. Attach a function to be executed whenever an AJAX request fails. Attach a function to be executed before an AJAX request is sent. Attach a function to be executed whenever all AJAX requests have ended. Attach a function to be executed whenever an AJAX request completes successfully. jQuery provides a trivially simple interface for doing various kind of amazing effects. jQuery methods allow us to quickly apply commonly used effects with a minimum configuration. This tutorial covers all the important jQuery methods to create visual effects. The commands for showing and hiding elements are pretty much what we would expect − show() to show the elements in a wrapped set and hide() to hide them. Here is the simple syntax for show() method − [selector].show( speed, [callback] ); Here is the description of all the parameters − speed − A string representing one of the three predefined speeds ("slow", "normal", or "fast") or the number of milliseconds to run the animation (e.g. 1000). speed − A string representing one of the three predefined speeds ("slow", "normal", or "fast") or the number of milliseconds to run the animation (e.g. 1000). callback − This optional parameter represents a function to be executed whenever the animation completes; executes once for each element animated against. callback − This optional parameter represents a function to be executed whenever the animation completes; executes once for each element animated against. Following is the simple syntax for hide() method − [selector].hide( speed, [callback] ); Here is the description of all the parameters − speed − A string representing one of the three predefined speeds ("slow", "normal", or "fast") or the number of milliseconds to run the animation (e.g. 1000). speed − A string representing one of the three predefined speeds ("slow", "normal", or "fast") or the number of milliseconds to run the animation (e.g. 1000). callback − This optional parameter represents a function to be executed whenever the animation completes; executes once for each element animated against. callback − This optional parameter represents a function to be executed whenever the animation completes; executes once for each element animated against. Consider the following HTML file with a small JQuery coding − <html> <head> <title>The jQuery Example</title> <script type = "text/javascript" src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"> </script> <script type = "text/javascript" language = "javascript"> $(document).ready(function() { $("#show").click(function () { $(".mydiv").show( 1000 ); }); $("#hide").click(function () { $(".mydiv").hide( 1000 ); }); }); </script> <style> .mydiv{ margin:10px; padding:12px; border:2px solid #666; width:100px; height:100px; } </style> </head> <body> <div class = "mydiv"> This is a SQUARE </div> <input id = "hide" type = "button" value = "Hide" /> <input id = "show" type = "button" value = "Show" /> </body> </html> This will produce following result − jQuery provides methods to toggle the display state of elements between revealed or hidden. If the element is initially displayed, it will be hidden; if hidden, it will be shown. Here is the simple syntax for one of the toggle() methods − [selector]..toggle([speed][, callback]); Here is the description of all the parameters − speed − A string representing one of the three predefined speeds ("slow", "normal", or "fast") or the number of milliseconds to run the animation (e.g. 1000). speed − A string representing one of the three predefined speeds ("slow", "normal", or "fast") or the number of milliseconds to run the animation (e.g. 1000). callback − This optional parameter represents a function to be executed whenever the animation completes; executes once for each element animated against. callback − This optional parameter represents a function to be executed whenever the animation completes; executes once for each element animated against. We can animate any element, such as a simple <div> containing an image − <html> <head> <title>The jQuery Example</title> <script type = "text/javascript" src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"> </script> <script type = "text/javascript" language = "javascript"> $(document).ready(function() { $(".clickme").click(function(event){ $(".target").toggle('slow', function(){ $(".log").text('Transition Complete'); }); }); }); </script> <style> .clickme{ margin:10px; padding:12px; border:2px solid #666; width:100px; height:50px; } </style> </head> <body> <div class = "content"> <div class = "clickme">Click Me</div> <div class = "target"> <img src = "./images/jquery.jpg" alt = "jQuery" /> </div> <div class = "log"></div> </div> </body> </html> This will produce following result − You have seen basic concept of jQuery Effects. Following table lists down all the important methods to create different kind of effects − A function for making custom animations. Fade in all matched elements by adjusting their opacity and firing an optional callback after completion. Fade out all matched elements by adjusting their opacity to 0, then setting display to "none" and firing an optional callback after completion. Fade the opacity of all matched elements to a specified opacity and firing an optional callback after completion. Hides each of the set of matched elements if they are shown. Hide all matched elements using a graceful animation and firing an optional callback after completion. Displays each of the set of matched elements if they are hidden. Show all matched elements using a graceful animation and firing an optional callback after completion. Reveal all matched elements by adjusting their height and firing an optional callback after completion. Toggle the visibility of all matched elements by adjusting their height and firing an optional callback after completion. Hide all matched elements by adjusting their height and firing an optional callback after completion. Stops all the currently running animations on all the specified elements. Toggle displaying each of the set of matched elements. Toggle displaying each of the set of matched elements using a graceful animation and firing an optional callback after completion. Toggle displaying each of the set of matched elements based upon the switch (true shows all elements, false hides all elements). Globally disable all animations. To use these effects you can either download latest jQuery UI Library jquery-ui-1.11.4.custom.zip from jQuery UI Library or use Google CDN to use it in the similar way as we have done for jQuery. We have used Google CDN for jQuery UI using following code snippet in the HTML page so we can use jQuery UI − <head> <script src = "https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.3/jquery-ui.min.js"> </script> </head> Blinds the element away or shows it by blinding it in. Bounces the element vertically or horizontally n-times. Clips the element on or off, vertically or horizontally. Drops the element away or shows it by dropping it in. Explodes the element into multiple pieces. Folds the element like a piece of paper. Highlights the background with a defined color. Scale and fade out animations create the puff effect. Pulsates the opacity of the element multiple times. Shrink or grow an element by a percentage factor. Shakes the element vertically or horizontally n-times. Resize an element to a specified width and height. Slides the element out of the viewport. Transfers the outline of an element to another. Interactions could be added basic mouse-based behaviours to any element. Using with interactions, We can create sortable lists, resizeable elements, drag & drop behaviours.Interactions also make great building blocks for more complex widgets and applications. Enable drag able functionality on any DOM element. Enable any DOM element to be drop able. Enable any DOM element to be resize-able. Enable a DOM element (or group of elements) to be selectable. Enable a group of DOM elements to be sortable. a jQuery UI widget is a specialized jQuery plug-in.Using plug-in, we can apply behaviours to the elements. However, plug-ins lack some built-in capabilities, such as a way to associate data with its elements, expose methods, merge options with defaults, and control the plug-in's lifetime. Enable to collapse the content, that is broken into logical sections. Enable to provides the suggestions while you type into the field. Button is an input of type submit and an anchor. It is to open an interactive calendar in a small overlay. Dialog boxes are one of the nice ways of presenting information on an HTML page. Menu shows list of items. It shows the progress information. Enable a style able select element/elements. The basic slider is horizontal and has a single handle that can be moved with the mouse or by using the arrow keys. It provides a quick way to select one value from a set. It is used to swap between content that is broken into logical sections. Its provides the tips for the users. Jquery has two different styling themes as A And B.Each with different colors for buttons, bars, content blocks, and so on. The syntax of J query theming as shown below − <div data-role = "page" data-theme = "a|b"> A Simple of A theming Example as shown below − <!DOCTYPE html> <html> <head> <meta name = "viewport" content = "width = device-width, initial-scale = 1"> <link rel = "stylesheet" href = "https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css"> <script src = "https://code.jquery.com/jquery-1.11.3.min.js"> </script> <script src = "https://code.jquery.com/jquery-1.11.3.min.js"> </script> <script src = "https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"> </script> </head> <body> <div data-role = "page" id = "pageone" data-theme = "a"> <div data-role = "header"> <h1>Tutorials Point</h1> </div> <div data-role = "main" class = "ui-content"> <p>Text link</p> <a href = "#">A Standard Text Link</a> <a href = "#" class = "ui-btn">Link Button</a> <p>A List View:</p> <ul data-role = "listview" data-autodividers = "true" data-inset = "true"> <li><a href = "#">Android </a></li> <li><a href = "#">IOS</a></li> </ul> <label for = "fullname">Input Field:</label> <input type = "text" name = "fullname" id = "fullname" placeholder = "Name.."> <label for = "switch">Toggle Switch:</label> <select name = "switch" id = "switch" data-role = "slider"> <option value = "on">On</option> <option value = "off" selected>Off</option> </select> </div> <div data-role = "footer"> <h1>Tutorials point</h1> </div> </div> </body> </html> This should produce following result − Text link A List View − A Android I IOS A Simple of B theming Example as shown below − <!DOCTYPE html> <html> <head> <meta name = "viewport" content = "width = device-width, initial-scale = 1"> <link rel = "stylesheet" href = "https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css"> <script src = "https://code.jquery.com/jquery-1.11.3.min.js"> </script> <script src = "https://code.jquery.com/jquery-1.11.3.min.js"> </script> <script src = "https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"> </script> </head> <body> <div data-role = "page" id = "pageone" data-theme = "b"> <div data-role = "header"> <h1>Tutorials Point</h1> </div> <div data-role = "main" class = "ui-content"> <p>Text link</p> <a href = "#">A Standard Text Link</a> <a href = "#" class = "ui-btn">Link Button</a> <p>A List View:</p> <ul data-role = "listview" data-autodividers = "true" data-inset = "true"> <li><a href = "#">Android </a></li> <li><a href = "#">IOS</a></li> </ul> <label for = "fullname">Input Field:</label> <input type = "text" name = "fullname" id = "fullname" placeholder = "Name.."> <label for = "switch">Toggle Switch:</label> <select name = "switch" id = "switch" data-role = "slider"> <option value = "on">On</option> <option value = "off" selected>Off</option> </select> </div> <div data-role = "footer"> <h1>Tutorials point</h1> </div> </div> </body> </html> This should produce following result − Text link A List View − A Android I IOS Jquery provides serveral utilities in the formate of $(name space). These methods are helpful to complete the programming tasks.a few of the utility methods are as show below. $.trim() is used to Removes leading and trailing whitespace $.trim( " lots of extra whitespace " ); $.each() is used to Iterates over arrays and objects $.each([ "foo", "bar", "baz" ], function( idx, val ) { console.log( "element " + idx + " is " + val ); }); $.each({ foo: "bar", baz: "bim" }, function( k, v ) { console.log( k + " : " + v ); }); .each() can be called on a selection to iterate over the elements contained in the selection. .each(), not $.each(), should be used for iterating over elements in a selection. $.inArray() is used to Returns a value's index in an array, or -1 if the value is not in the array. var myArray = [ 1, 2, 3, 5 ]; if ( $.inArray( 4, myArray ) !== -1 ) { console.log( "found it!" ); } $.extend() is used to Changes the properties of the first object using the properties of subsequent objects. var firstObject = { foo: "bar", a: "b" }; var secondObject = { foo: "baz" }; var newObject = $.extend( firstObject, secondObject ); console.log( firstObject.foo ); console.log( newObject.foo ); $.proxy() is used to Returns a function that will always run in the provided scope — that is, sets the meaning of this inside the passed function to the second argument var myFunction = function() { console.log( this ); }; var myObject = { foo: "bar" }; myFunction(); // window var myProxyFunction = $.proxy( myFunction, myObject ); myProxyFunction(); $.browser is used to give the information about browsers jQuery.each( jQuery.browser, function( i, val ) { $( "<div>" + i + " : <span>" + val + "</span>" ) .appendTo( document.body ); }); $.contains() is used to returns true if the DOM element provided by the second argument is a descendant of the DOM element provided by the first argument, whether it is a direct child or nested more deeply. $.contains( document.documentElement, document.body ); $.contains( document.body, document.documentElement ); $.data() is used to give the information about data <html lang = "en"> <head> <title>jQuery.data demo</title> <script src = "https://code.jquery.com/jquery-1.10.2.js"> </script> </head> <body> <div> The values stored were <span></span> and <span></span> </div> <script> var div = $( "div" )[ 0 ]; jQuery.data( div, "test", { first: 25, last: "tutorials" }); $( "span:first" ).text( jQuery.data( div, "test" ).first ); $( "span:last" ).text( jQuery.data( div, "test" ).last ); </script> </body> </html> An output would be as follows The values stored were 25 and tutorials $.fn.extend() is used to extends the jQuery prototype <html lang = "en"> <head> <script src = "https://code.jquery.com/jquery-1.10.2.js"> </script> </head> <body> <label><input type = "checkbox" name = "android"> Android</label> <label><input type = "checkbox" name = "ios"> IOS</label> <script> jQuery.fn.extend({ check: function() { return this.each(function() { this.checked = true; }); }, uncheck: function() { return this.each(function() { this.checked = false; }); } }); // Use the newly created .check() method $( "input[type = 'checkbox']" ).check(); </script> </body> </html> It provides the output as shown below − $.isWindow() is used to recognise the window <!doctype html> <html lang = "en"> <head> <meta charset = "utf-8"> <title>jQuery.isWindow demo</title> <script src = "https://code.jquery.com/jquery-1.10.2.js"> </script> </head> <body> Is 'window' a window? <b></b> <script> $( "b" ).append( "" + $.isWindow( window ) ); </script> </body> </html> It provides the output as shown below − It returns a number which is representing the current time (new Date).getTime() $.isXMLDoc() checks whether a file is an xml or not jQuery.isXMLDoc( document ) jQuery.isXMLDoc( document.body ) $.globalEval() is used to execute the javascript globally function test() { jQuery.globalEval( "var newVar = true;" ) } test(); $.dequeue() is used to execute the next function in the queue <!doctype html> <html lang = "en"> <head> <meta charset = "utf-8"> <title>jQuery.dequeue demo</title> <style> div { margin: 3px; width: 50px; position: absolute; height: 50px; left: 10px; top: 30px; background-color: green; border-radius: 50px; } div.red { background-color: blue; } </style> <script src = "https://code.jquery.com/jquery-1.10.2.js"></script> </head> <body> <button>Start</button> <div></div> <script> $( "button" ).click(function() { $( "div" ) .animate({ left: '+ = 400px' }, 2000 ) .animate({ top: '0px' }, 600 ) .queue(function() { $( this ).toggleClass( "red" ); $.dequeue( this ); }) .animate({ left:'10px', top:'30px' }, 700 ); }); </script> </body> </html> It provides the output as shown below − 27 Lectures 1 hours Mahesh Kumar 27 Lectures 1.5 hours Pratik Singh 72 Lectures 4.5 hours Frahaan Hussain 60 Lectures 9 hours Eduonix Learning Solutions 17 Lectures 2 hours Sandip Bhattacharya 12 Lectures 53 mins Laurence Svekis Print Add Notes Bookmark this page
[ { "code": null, "e": 2714, "s": 2322, "text": "jQuery is a fast and concise JavaScript Library created by John Resig in 2006 with a nice motto: Write less, do more. jQuery simplifies HTML document traversing, event handling, animating, and Ajax interactions for rapid web development. jQuery is a JavaScript toolkit designed to simplify various tasks by writing less code. Here is the list of important core features supported by jQuery −" }, { "code": null, "e": 2890, "s": 2714, "text": "DOM manipulation − The jQuery made it easy to select DOM elements, negotiate them and modifying their content by using cross-browser open source selector engine called Sizzle." }, { "code": null, "e": 3066, "s": 2890, "text": "DOM manipulation − The jQuery made it easy to select DOM elements, negotiate them and modifying their content by using cross-browser open source selector engine called Sizzle." }, { "code": null, "e": 3258, "s": 3066, "text": "Event handling − The jQuery offers an elegant way to capture a wide variety of events, such as a user clicking on a link, without the need to clutter the HTML code itself with event handlers." }, { "code": null, "e": 3450, "s": 3258, "text": "Event handling − The jQuery offers an elegant way to capture a wide variety of events, such as a user clicking on a link, without the need to clutter the HTML code itself with event handlers." }, { "code": null, "e": 3560, "s": 3450, "text": "AJAX Support − The jQuery helps you a lot to develop a responsive and featurerich site using AJAX technology." }, { "code": null, "e": 3670, "s": 3560, "text": "AJAX Support − The jQuery helps you a lot to develop a responsive and featurerich site using AJAX technology." }, { "code": null, "e": 3778, "s": 3670, "text": "Animations − The jQuery comes with plenty of built-in animation effects which you can use in your websites." }, { "code": null, "e": 3886, "s": 3778, "text": "Animations − The jQuery comes with plenty of built-in animation effects which you can use in your websites." }, { "code": null, "e": 3984, "s": 3886, "text": "Lightweight − The jQuery is very lightweight library - about 19KB in size (Minified and gzipped)." }, { "code": null, "e": 4082, "s": 3984, "text": "Lightweight − The jQuery is very lightweight library - about 19KB in size (Minified and gzipped)." }, { "code": null, "e": 4215, "s": 4082, "text": "Cross Browser Support − The jQuery has cross-browser support, and works well in IE 6.0+, FF 2.0+, Safari 3.0+, Chrome and Opera 9.0+" }, { "code": null, "e": 4348, "s": 4215, "text": "Cross Browser Support − The jQuery has cross-browser support, and works well in IE 6.0+, FF 2.0+, Safari 3.0+, Chrome and Opera 9.0+" }, { "code": null, "e": 4427, "s": 4348, "text": "Latest Technology − The jQuery supports CSS3 selectors and basic XPath syntax." }, { "code": null, "e": 4506, "s": 4427, "text": "Latest Technology − The jQuery supports CSS3 selectors and basic XPath syntax." }, { "code": null, "e": 4540, "s": 4506, "text": "There are two ways to use jQuery." }, { "code": null, "e": 4649, "s": 4540, "text": "Local Installation − You can download jQuery library on your local machine and include it in your HTML code." }, { "code": null, "e": 4758, "s": 4649, "text": "Local Installation − You can download jQuery library on your local machine and include it in your HTML code." }, { "code": null, "e": 4875, "s": 4758, "text": "CDN Based Version − You can include jQuery library into your HTML code directly from Content Delivery Network (CDN)." }, { "code": null, "e": 4992, "s": 4875, "text": "CDN Based Version − You can include jQuery library into your HTML code directly from Content Delivery Network (CDN)." }, { "code": null, "e": 5073, "s": 4992, "text": "Go to the https://jquery.com/download/ to download the latest version available." }, { "code": null, "e": 5154, "s": 5073, "text": "Go to the https://jquery.com/download/ to download the latest version available." }, { "code": null, "e": 5244, "s": 5154, "text": "Now put downloaded jquery-2.1.3.min.js file in a directory of your website, e.g. /jquery." }, { "code": null, "e": 5334, "s": 5244, "text": "Now put downloaded jquery-2.1.3.min.js file in a directory of your website, e.g. /jquery." }, { "code": null, "e": 5400, "s": 5334, "text": "Now you can include jquery library in your HTML file as follows −" }, { "code": null, "e": 5769, "s": 5400, "text": "<html>\n <head>\n <title>The jQuery Example</title>\n <script type = \"text/javascript\" src = \"/jquery/jquery-2.1.3.min.js\">\n </script>\n\t\t\n <script type = \"text/javascript\">\n $(document).ready(function() {\n document.write(\"Hello, World!\");\n });\n </script>\n </head>\n\t\n <body>\n <h1>Hello</h1>\n </body>\n</html>" }, { "code": null, "e": 5806, "s": 5769, "text": "This will produce following result −" }, { "code": null, "e": 5973, "s": 5806, "text": "You can include jQuery library into your HTML code directly from Content Delivery Network (CDN). Google and Microsoft provides content deliver for the latest version." }, { "code": null, "e": 6044, "s": 5973, "text": "Now let us rewrite above example using jQuery library from Google CDN." }, { "code": null, "e": 6460, "s": 6044, "text": "<html>\n <head>\n <title>The jQuery Example</title>\n <script type = \"text/javascript\" \n src = \"https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js\">\n </script>\n\t\t\n <script type = \"text/javascript\">\n $(document).ready(function() {\n document.write(\"Hello, World!\");\n });\n </script>\n </head>\n\t\n <body>\n <h1>Hello</h1>\n </body>\n</html>" }, { "code": null, "e": 6497, "s": 6460, "text": "This will produce following result −" }, { "code": null, "e": 6680, "s": 6497, "text": "As almost everything, we do when using jQuery reads or manipulates the document object model (DOM), we need to make sure that we start adding events etc. as soon as the DOM is ready." }, { "code": null, "e": 6884, "s": 6680, "text": "If you want an event to work on your page, you should call it inside the $(document).ready() function. Everything inside it will load as soon as the DOM is loaded and before the page contents are loaded." }, { "code": null, "e": 6952, "s": 6884, "text": "To do this, we register a ready event for the document as follows −" }, { "code": null, "e": 7021, "s": 6952, "text": "$(document).ready(function() {\n // do stuff when DOM is ready\n});\n" }, { "code": null, "e": 7101, "s": 7021, "text": "To call upon any jQuery library function, use HTML script tags as shown below −" }, { "code": null, "e": 7623, "s": 7101, "text": "<html>\n <head>\n <title>The jQuery Example</title>\n <script type = \"text/javascript\" \n src = \"https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js\">\n </script>\n\n <script type = \"text/javascript\" language = \"javascript\">\n $(document).ready(function() {\n $(\"div\").click(function() {alert(\"Hello, world!\");});\n });\n </script>\n </head>\n\t\n <body>\n <div id = \"mydiv\">\n Click on this to see a dialogue box.\n </div>\n </body>\n</html>" }, { "code": null, "e": 7660, "s": 7623, "text": "This will produce following result −" }, { "code": null, "e": 7754, "s": 7660, "text": "It is better to write our custom code in the custom JavaScript file : custom.js, as follows −" }, { "code": null, "e": 7884, "s": 7754, "text": "/* Filename: custom.js */\n$(document).ready(function() {\n\n $(\"div\").click(function() {\n alert(\"Hello, world!\");\n });\n});" }, { "code": null, "e": 7948, "s": 7884, "text": "Now we can include custom.js file in our HTML file as follows −" }, { "code": null, "e": 8355, "s": 7948, "text": "<html>\n <head>\n <title>The jQuery Example</title>\n <script type = \"text/javascript\" \n src = \"https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js\">\n </script>\n\t\t\n <script type = \"text/javascript\" src = \"/jquery/custom.js\">\n </script>\n </head>\n\t\n <body>\n <div id = \"mydiv\">\n Click on this to see a dialogue box.\n </div>\n </body>\n</html>" }, { "code": null, "e": 8392, "s": 8355, "text": "This will produce following result −" }, { "code": null, "e": 8600, "s": 8392, "text": "You can use multiple libraries all together without conflicting each others. For example, you can use jQuery and MooTool javascript libraries together. You can check jQuery noConflict Method for more detail." }, { "code": null, "e": 8726, "s": 8600, "text": "Do not worry too much if you did not understand above examples. You are going to grasp them very soon in subsequent chapters." }, { "code": null, "e": 8824, "s": 8726, "text": "Next chapter would try to cover few basic concepts which are coming from conventional JavaScript." }, { "code": null, "e": 9043, "s": 8824, "text": "jQuery is a framework built using JavaScript capabilities. So, you can use all the functions and other capabilities available in JavaScript. This chapter would explain most basic concepts but frequently used in jQuery." }, { "code": null, "e": 9191, "s": 9043, "text": "A string in JavaScript is an immutable object that contains none, one or many characters. Following are the valid examples of a JavaScript String −" }, { "code": null, "e": 9326, "s": 9191, "text": "\"This is JavaScript String\"\n'This is JavaScript String'\n'This is \"really\" a JavaScript String'\n\"This is 'really' a JavaScript String\"\n" }, { "code": null, "e": 9496, "s": 9326, "text": "Numbers in JavaScript are double-precision 64-bit format IEEE 754 values. They are immutable, just as strings. Following are the valid examples of a JavaScript Numbers −" }, { "code": null, "e": 9514, "s": 9496, "text": "5350\n120.27\n0.26\n" }, { "code": null, "e": 9648, "s": 9514, "text": "A boolean in JavaScript can be either true or false. If a number is zero, it defaults to false. If an empty string defaults to false." }, { "code": null, "e": 9707, "s": 9648, "text": "Following are the valid examples of a JavaScript Boolean −" }, { "code": null, "e": 9819, "s": 9707, "text": "true // true\nfalse // false\n0 // false\n1 // true\n\"\" // false\n\"hello\" // true\n" }, { "code": null, "e": 9928, "s": 9819, "text": "JavaScript supports Object concept very well. You can create an object using the object literal as follows −" }, { "code": null, "e": 9972, "s": 9928, "text": "var emp = {\n name: \"Zara\",\n age: 10\n};\n" }, { "code": null, "e": 10055, "s": 9972, "text": "You can write and read properties of an object using the dot notation as follows −" }, { "code": null, "e": 10220, "s": 10055, "text": "// Getting object properties\nemp.name // ==> Zara\nemp.age // ==> 10\n\n// Setting object properties\nemp.name = \"Daisy\" // <== Daisy\nemp.age = 20 // <== 20\n" }, { "code": null, "e": 10279, "s": 10220, "text": "You can define arrays using the array literal as follows −" }, { "code": null, "e": 10317, "s": 10279, "text": "var x = [];\nvar y = [1, 2, 3, 4, 5];\n" }, { "code": null, "e": 10379, "s": 10317, "text": "An array has a length property that is useful for iteration −" }, { "code": null, "e": 10473, "s": 10379, "text": "var x = [1, 2, 3, 4, 5];\n\nfor (var i = 0; i < x.length; i++) {\n // Do something with x[i]\n}" }, { "code": null, "e": 10600, "s": 10473, "text": "A function in JavaScript can be either named or anonymous. A named function can be defined using function keyword as follows −" }, { "code": null, "e": 10645, "s": 10600, "text": "function named(){\n // do some stuff here\n}" }, { "code": null, "e": 10750, "s": 10645, "text": "An anonymous function can be defined in similar way as a normal function but it would not have any name." }, { "code": null, "e": 10839, "s": 10750, "text": "A anonymous function can be assigned to a variable or passed to a method as shown below." }, { "code": null, "e": 10893, "s": 10839, "text": "var handler = function (){\n // do some stuff here\n}" }, { "code": null, "e": 10964, "s": 10893, "text": "JQuery makes a use of anonymous functions very frequently as follows −" }, { "code": null, "e": 11023, "s": 10964, "text": "$(document).ready(function(){\n // do some stuff here\n});" }, { "code": null, "e": 11141, "s": 11023, "text": "JavaScript variable arguments is a kind of array which has length property. Following example explains it very well −" }, { "code": null, "e": 11332, "s": 11141, "text": "function func(x){\n console.log(typeof x, arguments.length);\n}\n\nfunc(); //==> \"undefined\", 0\nfunc(1); //==> \"number\", 1\nfunc(\"1\", \"2\", \"3\"); //==> \"string\", 3" }, { "code": null, "e": 11442, "s": 11332, "text": "The arguments object also has a callee property, which refers to the function you're inside of. For example −" }, { "code": null, "e": 11527, "s": 11442, "text": "function func() {\n return arguments.callee; \n}\n\nfunc(); // ==> func" }, { "code": null, "e": 11682, "s": 11527, "text": "JavaScript famous keyword this always refers to the current context. Within a function this context can change, depending on how the function is called −" }, { "code": null, "e": 11826, "s": 11682, "text": "$(document).ready(function() {\n // this refers to window.document\n});\n\n$(\"div\").click(function() {\n // this refers to a div DOM element\n});" }, { "code": null, "e": 11938, "s": 11826, "text": "You can specify the context for a function call using the function-built-in methods call() and apply() methods." }, { "code": null, "e": 12105, "s": 11938, "text": "The difference between them is how they pass arguments. Call passes all arguments through as arguments to the function, while apply accepts an array as the arguments." }, { "code": null, "e": 12284, "s": 12105, "text": "function scope() {\n console.log(this, arguments.length);\n}\n\nscope() // window, 0\nscope.call(\"foobar\", [1,2]); //==> \"foobar\", 1\nscope.apply(\"foobar\", [1,2]); //==> \"foobar\", 2" }, { "code": null, "e": 12409, "s": 12284, "text": "The scope of a variable is the region of your program in which it is defined. JavaScript variable will have only two scopes." }, { "code": null, "e": 12525, "s": 12409, "text": "Global Variables − A global variable has global scope which means it is defined everywhere in your JavaScript code." }, { "code": null, "e": 12641, "s": 12525, "text": "Global Variables − A global variable has global scope which means it is defined everywhere in your JavaScript code." }, { "code": null, "e": 12791, "s": 12641, "text": "Local Variables − A local variable will be visible only within a function where it is defined. Function parameters are always local to that function." }, { "code": null, "e": 12941, "s": 12791, "text": "Local Variables − A local variable will be visible only within a function where it is defined. Function parameters are always local to that function." }, { "code": null, "e": 13050, "s": 12941, "text": "Within the body of a function, a local variable takes precedence over a global variable with the same name −" }, { "code": null, "e": 13224, "s": 13050, "text": "var myVar = \"global\"; // ==> Declare a global variable\n\nfunction ( ) {\n var myVar = \"local\"; // ==> Declare a local variable\n document.write(myVar); // ==> local\n}" }, { "code": null, "e": 13423, "s": 13224, "text": "A callback is a plain JavaScript function passed to some method as an argument or option. Some callbacks are just events, called to give the user a chance to react when a certain state is triggered." }, { "code": null, "e": 13490, "s": 13423, "text": "jQuery's event system uses such callbacks everywhere for example −" }, { "code": null, "e": 13572, "s": 13490, "text": "$(\"body\").click(function(event) {\n console.log(\"clicked: \" + event.target);\n});" }, { "code": null, "e": 13702, "s": 13572, "text": "Most callbacks provide arguments and a context. In the event-handler example, the callback is called with one argument, an Event." }, { "code": null, "e": 13874, "s": 13702, "text": "Some callbacks are required to return something, others make that return value optional. To prevent a form submission, a submit event handler can return false as follows −" }, { "code": null, "e": 13929, "s": 13874, "text": "$(\"#myform\").submit(function() {\n return false;\n});\n" }, { "code": null, "e": 14054, "s": 13929, "text": "Closures are created whenever a variable that is defined outside the current scope is accessed from within some inner scope." }, { "code": null, "e": 14191, "s": 14054, "text": "Following example shows how the variable counter is visible within the create, increment, and print functions, but not outside of them −" }, { "code": null, "e": 14432, "s": 14191, "text": "function create() {\n var counter = 0;\n\t\n return {\n increment: function() {\n counter++;\n },\n\t print: function() {\n console.log(counter);\n }\n }\n}\n\nvar c = create();\nc.increment();\nc.print(); // ==> 1" }, { "code": null, "e": 14635, "s": 14432, "text": "This pattern allows you to create objects with methods that operate on data that isn't visible to the outside world. It should be noted that data hiding is the very basis of object-oriented programming." }, { "code": null, "e": 14860, "s": 14635, "text": "A proxy is an object that can be used to control access to another object. It implements the same interface as this other object and passes on any method invocations to it. This other object is often called the real subject." }, { "code": null, "e": 15038, "s": 14860, "text": "A proxy can be instantiated in place of this real subject and allow it to be accessed remotely. We can saves jQuery's setArray method in a closure and overwrites it as follows −" }, { "code": null, "e": 15254, "s": 15038, "text": "(function() {\n // log all calls to setArray\n var proxied = jQuery.fn.setArray;\n\n jQuery.fn.setArray = function() {\n console.log(this, arguments);\n return proxied.apply(this, arguments);\n };\n\t\n})();" }, { "code": null, "e": 15554, "s": 15254, "text": "The above wraps its code in a function to hide the proxied variable. The proxy then logs all calls to the method and delegates the call to the original method. Using apply(this, arguments) guarantees that the caller won't be able to notice the difference between the original and the proxied method." }, { "code": null, "e": 15686, "s": 15554, "text": "JavaScript comes along with a useful set of built-in functions. These methods can be used to manipulate Strings, Numbers and Dates." }, { "code": null, "e": 15733, "s": 15686, "text": "Following are important JavaScript functions −" }, { "code": null, "e": 15742, "s": 15733, "text": "charAt()" }, { "code": null, "e": 15788, "s": 15742, "text": "Returns the character at the specified index." }, { "code": null, "e": 15797, "s": 15788, "text": "concat()" }, { "code": null, "e": 15856, "s": 15797, "text": "Combines the text of two strings and returns a new string." }, { "code": null, "e": 15866, "s": 15856, "text": "forEach()" }, { "code": null, "e": 15914, "s": 15866, "text": "Calls a function for each element in the array." }, { "code": null, "e": 15924, "s": 15914, "text": "indexOf()" }, { "code": null, "e": 16043, "s": 15924, "text": "Returns the index within the calling String object of the first occurrence of the specified value, or -1 if not found." }, { "code": null, "e": 16052, "s": 16043, "text": "length()" }, { "code": null, "e": 16086, "s": 16052, "text": "Returns the length of the string." }, { "code": null, "e": 16092, "s": 16086, "text": "pop()" }, { "code": null, "e": 16157, "s": 16092, "text": "Removes the last element from an array and returns that element." }, { "code": null, "e": 16164, "s": 16157, "text": "push()" }, { "code": null, "e": 16254, "s": 16164, "text": "Adds one or more elements to the end of an array and returns the new length of the array." }, { "code": null, "e": 16264, "s": 16254, "text": "reverse()" }, { "code": null, "e": 16374, "s": 16264, "text": "Reverses the order of the elements of an array -- the first becomes the last, and the last becomes the first." }, { "code": null, "e": 16381, "s": 16374, "text": "sort()" }, { "code": null, "e": 16413, "s": 16381, "text": "Sorts the elements of an array." }, { "code": null, "e": 16422, "s": 16413, "text": "substr()" }, { "code": null, "e": 16537, "s": 16422, "text": "Returns the characters in a string beginning at the specified location through the specified number of characters." }, { "code": null, "e": 16551, "s": 16537, "text": "toLowerCase()" }, { "code": null, "e": 16609, "s": 16551, "text": "Returns the calling string value converted to lower case." }, { "code": null, "e": 16620, "s": 16609, "text": "toString()" }, { "code": null, "e": 16677, "s": 16620, "text": "Returns the string representation of the number's value." }, { "code": null, "e": 16691, "s": 16677, "text": "toUpperCase()" }, { "code": null, "e": 16748, "s": 16691, "text": "Returns the calling string value converted to uppercase." }, { "code": null, "e": 16835, "s": 16748, "text": "The Document Object Model is a tree structure of various elements of HTML as follows −" }, { "code": null, "e": 17079, "s": 16835, "text": "<html>\n <head>\n <title>The jQuery Example</title>\n </head>\n\t\n <body>\n <div>\n <p>This is a paragraph.</p>\n <p>This is second paragraph.</p>\n <p>This is third paragraph.</p>\n </div>\n </body>\n</html>" }, { "code": null, "e": 17116, "s": 17079, "text": "This will produce following result −" }, { "code": null, "e": 17137, "s": 17116, "text": "This is a paragraph." }, { "code": null, "e": 17163, "s": 17137, "text": "This is second paragraph." }, { "code": null, "e": 17188, "s": 17163, "text": "This is third paragraph." }, { "code": null, "e": 17256, "s": 17188, "text": "Following are the important points about the above tree structure −" }, { "code": null, "e": 17376, "s": 17256, "text": "The <html> is the ancestor of all the other elements; in other words, all the other elements are descendants of <html>." }, { "code": null, "e": 17496, "s": 17376, "text": "The <html> is the ancestor of all the other elements; in other words, all the other elements are descendants of <html>." }, { "code": null, "e": 17586, "s": 17496, "text": "The <head> and <body> elements are not only descendants, but children of <html>, as well." }, { "code": null, "e": 17676, "s": 17586, "text": "The <head> and <body> elements are not only descendants, but children of <html>, as well." }, { "code": null, "e": 17771, "s": 17676, "text": "Likewise, in addition to being the ancestor of <head> and <body>, <html> is also their parent." }, { "code": null, "e": 17866, "s": 17771, "text": "Likewise, in addition to being the ancestor of <head> and <body>, <html> is also their parent." }, { "code": null, "e": 17999, "s": 17866, "text": "The <p> elements are children (and descendants) of <div>, descendants of <body> and <html>, and siblings of each other <p> elements." }, { "code": null, "e": 18132, "s": 17999, "text": "The <p> elements are children (and descendants) of <div>, descendants of <body> and <html>, and siblings of each other <p> elements." }, { "code": null, "e": 18313, "s": 18132, "text": "While learning jQuery concepts, it will be helpful to have understanding on DOM, if you are not aware of DOM then I would suggest to go through our simple tutorial on DOM Tutorial." }, { "code": null, "e": 18497, "s": 18313, "text": "The jQuery library harnesses the power of Cascading Style Sheets (CSS) selectors to let us quickly and easily access elements or groups of elements in the Document Object Model (DOM)." }, { "code": null, "e": 18812, "s": 18497, "text": "A jQuery Selector is a function which makes use of expressions to find out matching elements from a DOM based on the given criteria. Simply you can say, selectors are used to select one or more HTML elements using jQuery. Once an element is selected then we can perform various operations on that selected element." }, { "code": null, "e": 18996, "s": 18812, "text": "jQuery selectors start with the dollar sign and parentheses − $(). The factory function $() makes use of following three building blocks while selecting elements in a given document −" }, { "code": null, "e": 19005, "s": 18996, "text": "Tag Name" }, { "code": null, "e": 19112, "s": 19005, "text": "Represents a tag name available in the DOM. For example $('p') selects all paragraphs <p> in the document." }, { "code": null, "e": 19119, "s": 19112, "text": "Tag ID" }, { "code": null, "e": 19272, "s": 19119, "text": "Represents a tag available with the given ID in the DOM. For example $('#some-id') selects the single element in the document that has an ID of some-id." }, { "code": null, "e": 19282, "s": 19272, "text": "Tag Class" }, { "code": null, "e": 19441, "s": 19282, "text": "Represents a tag available with the given class in the DOM. For example $('.some-class') selects all elements in the document that have a class of some-class." }, { "code": null, "e": 19612, "s": 19441, "text": "All the above items can be used either on their own or in combination with other selectors. All the jQuery selectors are based on the same principle except some tweaking." }, { "code": null, "e": 19875, "s": 19612, "text": "NOTE − The factory function $() is a synonym of jQuery() function. So in case you are using any other JavaScript library where $ sign is conflicting with some thing else then you can replace $ sign by jQuery name and you can use function jQuery() instead of $()." }, { "code": null, "e": 19992, "s": 19875, "text": "Following is a simple example which makes use of Tag Selector. This would select all the elements with a tag name p." }, { "code": null, "e": 20593, "s": 19992, "text": "<html>\n <head>\n <title>The jQuery Example</title>\n <script type = \"text/javascript\" \n src = \"https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js\">\n </script>\n\n <script type = \"text/javascript\" language = \"javascript\">\n $(document).ready(function() {\n $(\"p\").css(\"background-color\", \"yellow\");\n });\n </script>\n </head>\n\t\n <body>\n <div>\n <p class = \"myclass\">This is a paragraph.</p>\n <p id = \"myid\">This is second paragraph.</p>\n <p>This is third paragraph.</p>\n </div>\n </body>\n</html>" }, { "code": null, "e": 20630, "s": 20593, "text": "This will produce following result −" }, { "code": null, "e": 20651, "s": 20630, "text": "This is a paragraph." }, { "code": null, "e": 20677, "s": 20651, "text": "This is second paragraph." }, { "code": null, "e": 20702, "s": 20677, "text": "This is third paragraph." }, { "code": null, "e": 20854, "s": 20702, "text": "The selectors are very useful and would be required at every step while using jQuery. They get the exact element that you want from your HTML document." }, { "code": null, "e": 20934, "s": 20854, "text": "Following table lists down few basic selectors and explains them with examples." }, { "code": null, "e": 20996, "s": 20934, "text": "Selects all elements which match with the given element Name." }, { "code": null, "e": 21054, "s": 20996, "text": "Selects a single element which matches with the given ID." }, { "code": null, "e": 21109, "s": 21054, "text": "Selects all elements which match with the given Class." }, { "code": null, "e": 21150, "s": 21109, "text": "Selects all elements available in a DOM." }, { "code": null, "e": 21221, "s": 21150, "text": "Selects the combined results of all the specified selectors E, F or G." }, { "code": null, "e": 21359, "s": 21221, "text": "Similar to above syntax and examples, following examples would give you understanding on using different type of other useful selectors −" }, { "code": null, "e": 21366, "s": 21359, "text": "$('*')" }, { "code": null, "e": 21418, "s": 21366, "text": "This selector selects all elements in the document." }, { "code": null, "e": 21429, "s": 21418, "text": "$(\"p > *\")" }, { "code": null, "e": 21506, "s": 21429, "text": "This selector selects all elements that are children of a paragraph element." }, { "code": null, "e": 21522, "s": 21506, "text": "$(\"#specialID\")" }, { "code": null, "e": 21583, "s": 21522, "text": "This selector function gets the element with id=\"specialID\"." }, { "code": null, "e": 21602, "s": 21583, "text": "$(\".specialClass\")" }, { "code": null, "e": 21675, "s": 21602, "text": "This selector gets all the elements that have the class of specialClass." }, { "code": null, "e": 21697, "s": 21675, "text": "$(\"li:not(.myclass)\")" }, { "code": null, "e": 21770, "s": 21697, "text": "Selects all elements matched by <li> that do not have class = \"myclass\"." }, { "code": null, "e": 21800, "s": 21770, "text": "$(\"a#specialID.specialClass\")" }, { "code": null, "e": 21881, "s": 21800, "text": "This selector matches links with an id of specialID and a class of specialClass." }, { "code": null, "e": 21903, "s": 21881, "text": "$(\"p a.specialClass\")" }, { "code": null, "e": 21990, "s": 21903, "text": "This selector matches links with a class of specialClass declared within <p> elements." }, { "code": null, "e": 22007, "s": 21990, "text": "$(\"ul li:first\")" }, { "code": null, "e": 22067, "s": 22007, "text": "This selector gets only the first <li> element of the <ul>." }, { "code": null, "e": 22085, "s": 22067, "text": "$(\"#container p\")" }, { "code": null, "e": 22185, "s": 22085, "text": "Selects all elements matched by <p> that are descendants of an element that has an id of container." }, { "code": null, "e": 22198, "s": 22185, "text": "$(\"li > ul\")" }, { "code": null, "e": 22283, "s": 22198, "text": "Selects all elements matched by <ul> that are children of an element matched by <li>" }, { "code": null, "e": 22300, "s": 22283, "text": "$(\"strong + em\")" }, { "code": null, "e": 22400, "s": 22300, "text": "Selects all elements matched by <em> that immediately follow a sibling element matched by <strong>." }, { "code": null, "e": 22412, "s": 22400, "text": "$(\"p ~ ul\")" }, { "code": null, "e": 22495, "s": 22412, "text": "Selects all elements matched by <ul> that follow a sibling element matched by <p>." }, { "code": null, "e": 22517, "s": 22495, "text": "$(\"code, em, strong\")" }, { "code": null, "e": 22577, "s": 22517, "text": "Selects all elements matched by <code> or <em> or <strong>." }, { "code": null, "e": 22601, "s": 22577, "text": "$(\"p strong, .myclass\")" }, { "code": null, "e": 22746, "s": 22601, "text": "Selects all elements matched by <strong> that are descendants of an element matched by <p> as well as all elements that have a class of myclass." }, { "code": null, "e": 22758, "s": 22746, "text": "$(\":empty\")" }, { "code": null, "e": 22802, "s": 22758, "text": "Selects all elements that have no children." }, { "code": null, "e": 22815, "s": 22802, "text": "$(\"p:empty\")" }, { "code": null, "e": 22874, "s": 22815, "text": "Selects all elements matched by <p> that have no children." }, { "code": null, "e": 22886, "s": 22874, "text": "$(\"div[p]\")" }, { "code": null, "e": 22964, "s": 22886, "text": "Selects all elements matched by <div> that contain an element matched by <p>." }, { "code": null, "e": 22981, "s": 22964, "text": "$(\"p[.myclass]\")" }, { "code": null, "e": 23066, "s": 22981, "text": "Selects all elements matched by <p> that contain an element with a class of myclass." }, { "code": null, "e": 23079, "s": 23066, "text": "$(\"a[@rel]\")" }, { "code": null, "e": 23142, "s": 23079, "text": "Selects all elements matched by <a> that have a rel attribute." }, { "code": null, "e": 23169, "s": 23142, "text": "$(\"input[@name = myname]\")" }, { "code": null, "e": 23257, "s": 23169, "text": "Selects all elements matched by <input> that have a name value exactly equal to myname." }, { "code": null, "e": 23283, "s": 23257, "text": "$(\"input[@name^=myname]\")" }, { "code": null, "e": 23369, "s": 23283, "text": "Selects all elements matched by <input> that have a name value beginning with myname." }, { "code": null, "e": 23388, "s": 23369, "text": "$(\"a[@rel$=self]\")" }, { "code": null, "e": 23472, "s": 23388, "text": "Selects all elements matched by <a> that have rel attribute value ending with self." }, { "code": null, "e": 23498, "s": 23472, "text": "$(\"a[@href*=domain.com]\")" }, { "code": null, "e": 23581, "s": 23498, "text": "Selects all elements matched by <a> that have an href value containing domain.com." }, { "code": null, "e": 23594, "s": 23581, "text": "$(\"li:even\")" }, { "code": null, "e": 23662, "s": 23594, "text": "Selects all elements matched by <li> that have an even index value." }, { "code": null, "e": 23674, "s": 23662, "text": "$(\"tr:odd\")" }, { "code": null, "e": 23741, "s": 23674, "text": "Selects all elements matched by <tr> that have an odd index value." }, { "code": null, "e": 23755, "s": 23741, "text": "$(\"li:first\")" }, { "code": null, "e": 23787, "s": 23755, "text": "Selects the first <li> element." }, { "code": null, "e": 23800, "s": 23787, "text": "$(\"li:last\")" }, { "code": null, "e": 23831, "s": 23800, "text": "Selects the last <li> element." }, { "code": null, "e": 23847, "s": 23831, "text": "$(\"li:visible\")" }, { "code": null, "e": 23902, "s": 23847, "text": "Selects all elements matched by <li> that are visible." }, { "code": null, "e": 23917, "s": 23902, "text": "$(\"li:hidden\")" }, { "code": null, "e": 23971, "s": 23917, "text": "Selects all elements matched by <li> that are hidden." }, { "code": null, "e": 23983, "s": 23971, "text": "$(\":radio\")" }, { "code": null, "e": 24022, "s": 23983, "text": "Selects all radio buttons in the form." }, { "code": null, "e": 24036, "s": 24022, "text": "$(\":checked\")" }, { "code": null, "e": 24073, "s": 24036, "text": "Selects all checked box in the form." }, { "code": null, "e": 24085, "s": 24073, "text": "$(\":input\")" }, { "code": null, "e": 24147, "s": 24085, "text": "Selects only form elements (input, select, textarea, button)." }, { "code": null, "e": 24158, "s": 24147, "text": "$(\":text\")" }, { "code": null, "e": 24207, "s": 24158, "text": "Selects only text elements (input[type = text])." }, { "code": null, "e": 24221, "s": 24207, "text": "$(\"li:eq(2)\")" }, { "code": null, "e": 24253, "s": 24221, "text": "Selects the third <li> element." }, { "code": null, "e": 24267, "s": 24253, "text": "$(\"li:eq(4)\")" }, { "code": null, "e": 24299, "s": 24267, "text": "Selects the fifth <li> element." }, { "code": null, "e": 24313, "s": 24299, "text": "$(\"li:lt(2)\")" }, { "code": null, "e": 24425, "s": 24313, "text": "Selects all elements matched by <li> element before the third one; in other words, the first two <li> elements." }, { "code": null, "e": 24438, "s": 24425, "text": "$(\"p:lt(3)\")" }, { "code": null, "e": 24551, "s": 24438, "text": "selects all elements matched by <p> elements before the fourth one; in other words the first three <p> elements." }, { "code": null, "e": 24565, "s": 24551, "text": "$(\"li:gt(1)\")" }, { "code": null, "e": 24624, "s": 24565, "text": "Selects all elements matched by <li> after the second one." }, { "code": null, "e": 24637, "s": 24624, "text": "$(\"p:gt(2)\")" }, { "code": null, "e": 24694, "s": 24637, "text": "Selects all elements matched by <p> after the third one." }, { "code": null, "e": 24705, "s": 24694, "text": "$(\"div/p\")" }, { "code": null, "e": 24791, "s": 24705, "text": "Selects all elements matched by <p> that are children of an element matched by <div>." }, { "code": null, "e": 24806, "s": 24791, "text": "$(\"div//code\")" }, { "code": null, "e": 24897, "s": 24806, "text": "Selects all elements matched by <code>that are descendants of an element matched by <div>." }, { "code": null, "e": 24909, "s": 24897, "text": "$(\"//p//a\")" }, { "code": null, "e": 24995, "s": 24909, "text": "Selects all elements matched by <a> that are descendants of an element matched by <p>" }, { "code": null, "e": 25015, "s": 24995, "text": "$(\"li:first-child\")" }, { "code": null, "e": 25094, "s": 25015, "text": "Selects all elements matched by <li> that are the first child of their parent." }, { "code": null, "e": 25113, "s": 25094, "text": "$(\"li:last-child\")" }, { "code": null, "e": 25191, "s": 25113, "text": "Selects all elements matched by <li> that are the last child of their parent." }, { "code": null, "e": 25204, "s": 25191, "text": "$(\":parent\")" }, { "code": null, "e": 25281, "s": 25204, "text": "Selects all elements that are the parent of another element, including text." }, { "code": null, "e": 25306, "s": 25281, "text": "$(\"li:contains(second)\")" }, { "code": null, "e": 25373, "s": 25306, "text": "Selects all elements matched by <li> that contain the text second." }, { "code": null, "e": 25563, "s": 25373, "text": "You can use all the above selectors with any HTML/XML element in generic way. For example if selector $(\"li:first\") works for <li> element then $(\"p:first\") would also work for <p> element." }, { "code": null, "e": 25707, "s": 25563, "text": "Some of the most basic components we can manipulate when it comes to DOM elements are the properties and attributes assigned to those elements." }, { "code": null, "e": 25830, "s": 25707, "text": "Most of these attributes are available through JavaScript as DOM node properties. Some of the more common properties are −" }, { "code": null, "e": 25840, "s": 25830, "text": "className" }, { "code": null, "e": 25848, "s": 25840, "text": "tagName" }, { "code": null, "e": 25851, "s": 25848, "text": "id" }, { "code": null, "e": 25856, "s": 25851, "text": "href" }, { "code": null, "e": 25862, "s": 25856, "text": "title" }, { "code": null, "e": 25866, "s": 25862, "text": "rel" }, { "code": null, "e": 25870, "s": 25866, "text": "src" }, { "code": null, "e": 25928, "s": 25870, "text": "Consider the following HTML markup for an image element −" }, { "code": null, "e": 26032, "s": 25928, "text": "<img id = \"imageid\" src = \"image.gif\" alt = \"Image\" class = \"myclass\" \n title = \"This is an image\"/>\n" }, { "code": null, "e": 26212, "s": 26032, "text": "In this element's markup, the tag name is img, and the markup for id, src, alt, class, and title represents the element's attributes, each of which consists of a name and a value." }, { "code": null, "e": 26361, "s": 26212, "text": "jQuery gives us the means to easily manipulate an element's attributes and gives us access to the element so that we can also change its properties." }, { "code": null, "e": 26526, "s": 26361, "text": "The attr() method can be used to either fetch the value of an attribute from the first element in the matched set or set attribute values onto all matched elements." }, { "code": null, "e": 26653, "s": 26526, "text": "Following is a simple example which fetches title attribute of <em> tag and set <div id = \"divid\"> value with the same value −" }, { "code": null, "e": 27292, "s": 26653, "text": "<html>\n <head>\n <title>The jQuery Example</title>\n <script type = \"text/javascript\" \n src = \"https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js\">\n </script>\n\t\t\n <script type = \"text/javascript\" language = \"javascript\">\n $(document).ready(function() {\n var title = $(\"em\").attr(\"title\");\n $(\"#divid\").text(title);\n });\n </script>\n </head>\n\t\n <body>\n <div>\n <em title = \"Bold and Brave\">This is first paragraph.</em>\n <p id = \"myid\">This is second paragraph.</p>\n <div id = \"divid\"></div>\n </div>\n </body>\n</html>" }, { "code": null, "e": 27329, "s": 27292, "text": "This will produce following result −" }, { "code": null, "e": 27355, "s": 27329, "text": "This is second paragraph." }, { "code": null, "e": 27484, "s": 27355, "text": "The attr(name, value) method can be used to set the named attribute onto all elements in the wrapped set using the passed value." }, { "code": null, "e": 27578, "s": 27484, "text": "Following is a simple example which set src attribute of an image tag to a correct location −" }, { "code": null, "e": 28174, "s": 27578, "text": "<html>\n <head>\n <title>The jQuery Example</title>\n <base href=\"https://www.tutorialspoint.com\" />\n <script type = \"text/javascript\" \n src = \"https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js\">\n </script>\n\t\t\n <script type = \"text/javascript\" language = \"javascript\">\n $(document).ready(function() {\n $(\"#myimg\").attr(\"src\", \"/jquery/images/jquery.jpg\");\n });\n </script>\n </head>\n\t\n <body>\n <div>\n <img id = \"myimg\" src = \"/images/jquery.jpg\" alt = \"Sample image\" />\n </div>\n </body>\n</html>" }, { "code": null, "e": 28211, "s": 28174, "text": "This will produce following result −" }, { "code": null, "e": 28368, "s": 28211, "text": "The addClass( classes ) method can be used to apply defined style sheets onto all the matched elements. You can specify multiple classes separated by space." }, { "code": null, "e": 28445, "s": 28368, "text": "Following is a simple example which sets class attribute of a para <p> tag −" }, { "code": null, "e": 29133, "s": 28445, "text": "<html>\n <head>\n <title>The jQuery Example</title>\n <script type = \"text/javascript\" \n src = \"https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js\">\n </script>\n\t\t\n <script type = \"text/javascript\" language = \"javascript\">\n $(document).ready(function() {\n $(\"em\").addClass(\"selected\");\n $(\"#myid\").addClass(\"highlight\");\n });\n </script>\n\t\t\n <style>\n .selected { color:red; }\n .highlight { background:yellow; }\n </style>\t\n </head>\n\t\n <body>\n <em title = \"Bold and Brave\">This is first paragraph.</em>\n <p id = \"myid\">This is second paragraph.</p>\n </body>\n</html>" }, { "code": null, "e": 29170, "s": 29133, "text": "This will produce following result −" }, { "code": null, "e": 29196, "s": 29170, "text": "This is second paragraph." }, { "code": null, "e": 29302, "s": 29196, "text": "Following table lists down few useful methods which you can use to manipulate attributes and properties −" }, { "code": null, "e": 29364, "s": 29302, "text": "Set a key/value object as properties to all matched elements." }, { "code": null, "e": 29432, "s": 29364, "text": "Set a single property to a computed value, on all matched elements." }, { "code": null, "e": 29487, "s": 29432, "text": "Remove an attribute from each of the matched elements." }, { "code": null, "e": 29582, "s": 29487, "text": "Returns true if the specified class is present on at least one of the set of matched elements." }, { "code": null, "e": 29655, "s": 29582, "text": "Removes all or the specified class(es) from the set of matched elements." }, { "code": null, "e": 29748, "s": 29655, "text": "Adds the specified class if it is not present, removes the specified class if it is present." }, { "code": null, "e": 29812, "s": 29748, "text": "Get the html contents (innerHTML) of the first matched element." }, { "code": null, "e": 29860, "s": 29812, "text": "Set the html contents of every matched element." }, { "code": null, "e": 29916, "s": 29860, "text": "Get the combined text contents of all matched elements." }, { "code": null, "e": 29963, "s": 29916, "text": "Set the text contents of all matched elements." }, { "code": null, "e": 30013, "s": 29963, "text": "Get the input value of the first matched element." }, { "code": null, "e": 30295, "s": 30013, "text": "Set the value attribute of every matched element if it is called on <input> but if it is called on <select> with the passed <option> value then passed option would be selected, if it is called on check box or radio box then all the matching check box and radiobox would be checked." }, { "code": null, "e": 30441, "s": 30295, "text": "Similar to above syntax and examples, following examples would give you understanding on using various attribute methods in different situation −" }, { "code": null, "e": 30467, "s": 30441, "text": "$(\"#myID\").attr(\"custom\")" }, { "code": null, "e": 30556, "s": 30467, "text": "This would return value of attribute custom for the first element matching with ID myID." }, { "code": null, "e": 30593, "s": 30556, "text": "$(\"img\").attr(\"alt\", \"Sample Image\")" }, { "code": null, "e": 30670, "s": 30593, "text": "This sets the alt attribute of all the images to a new value \"Sample Image\"." }, { "code": null, "e": 30733, "s": 30670, "text": "$(\"input\").attr({ value: \"\", title: \"Please enter a value\" });" }, { "code": null, "e": 30864, "s": 30733, "text": "Sets the value of all <input> elements to the empty string, as well as sets The jQuery Example to the string Please enter a value." }, { "code": null, "e": 30911, "s": 30864, "text": "$(\"a[href^=https://]\").attr(\"target\",\"_blank\")" }, { "code": null, "e": 31015, "s": 30911, "text": "Selects all links with an href attribute starting with https:// and set its target attribute to _blank." }, { "code": null, "e": 31043, "s": 31015, "text": "$(\"a\").removeAttr(\"target\")" }, { "code": null, "e": 31096, "s": 31043, "text": "This would remove target attribute of all the links." }, { "code": null, "e": 31176, "s": 31096, "text": "$(\"form\").submit(function() {$(\":submit\",this).attr(\"disabled\", \"disabled\");});" }, { "code": null, "e": 31271, "s": 31176, "text": "This would modify the disabled attribute to the value \"disabled\" while clicking Submit button." }, { "code": null, "e": 31304, "s": 31271, "text": "$(\"p:last\").hasClass(\"selected\")" }, { "code": null, "e": 31367, "s": 31304, "text": "This return true if last <p> tag has associated classselected." }, { "code": null, "e": 31381, "s": 31367, "text": "$(\"p\").text()" }, { "code": null, "e": 31466, "s": 31381, "text": "Returns string that contains the combined text contents of all matched <p> elements." }, { "code": null, "e": 31500, "s": 31466, "text": "$(\"p\").text(\"<i>Hello World</i>\")" }, { "code": null, "e": 31583, "s": 31500, "text": "This would set \"<I>Hello World</I>\" as text content of the matching <p> elements." }, { "code": null, "e": 31597, "s": 31583, "text": "$(\"p\").html()" }, { "code": null, "e": 31659, "s": 31597, "text": "This returns the HTML content of the all matching paragraphs." }, { "code": null, "e": 31688, "s": 31659, "text": "$(\"div\").html(\"Hello World\")" }, { "code": null, "e": 31758, "s": 31688, "text": "This would set the HTML content of all matching <div> to Hello World." }, { "code": null, "e": 31792, "s": 31758, "text": "$(\"input:checkbox:checked\").val()" }, { "code": null, "e": 31837, "s": 31792, "text": "Get the first value from a checked checkbox." }, { "code": null, "e": 31878, "s": 31837, "text": "$(\"input:radio[name=bar]:checked\").val()" }, { "code": null, "e": 31927, "s": 31878, "text": "Get the first value from a set of radio buttons." }, { "code": null, "e": 31952, "s": 31927, "text": "$(\"button\").val(\"Hello\")" }, { "code": null, "e": 32012, "s": 31952, "text": "Sets the value attribute of every matched element <button>." }, { "code": null, "e": 32033, "s": 32012, "text": "$(\"input\").val(\"on\")" }, { "code": null, "e": 32105, "s": 32033, "text": "This would check all the radio or check box button whose value is \"on\"." }, { "code": null, "e": 32131, "s": 32105, "text": "$(\"select\").val(\"Orange\")" }, { "code": null, "e": 32220, "s": 32131, "text": "This would select Orange option in a dropdown box with options Orange, Mango and Banana." }, { "code": null, "e": 32255, "s": 32220, "text": "$(\"select\").val(\"Orange\", \"Mango\")" }, { "code": null, "e": 32355, "s": 32255, "text": "This would select Orange and Mango options in a dropdown box with options Orange, Mango and Banana." }, { "code": null, "e": 32669, "s": 32355, "text": "jQuery is a very powerful tool which provides a variety of DOM traversal methods to help us select elements in a document randomly as well as in sequential method. Most of the DOM Traversal Methods do not modify the jQuery object and they are used to filter out elements from a document based on given conditions." }, { "code": null, "e": 32730, "s": 32669, "text": "Consider a simple document with the following HTML content −" }, { "code": null, "e": 33081, "s": 32730, "text": "<html>\n <head>\n <title>The JQuery Example</title>\n </head>\n\t\n <body>\n <div>\n <ul>\n <li>list item 1</li>\n <li>list item 2</li>\n <li>list item 3</li>\n <li>list item 4</li>\n <li>list item 5</li>\n <li>list item 6</li>\n </ul>\n </div>\n </body>\n</html>" }, { "code": null, "e": 33118, "s": 33081, "text": "This will produce following result −" }, { "code": null, "e": 33130, "s": 33118, "text": "list item 1" }, { "code": null, "e": 33142, "s": 33130, "text": "list item 2" }, { "code": null, "e": 33154, "s": 33142, "text": "list item 3" }, { "code": null, "e": 33166, "s": 33154, "text": "list item 4" }, { "code": null, "e": 33178, "s": 33166, "text": "list item 5" }, { "code": null, "e": 33190, "s": 33178, "text": "list item 6" }, { "code": null, "e": 33298, "s": 33190, "text": "Above every list has its own index, and can be located directly by using eq(index) method as below example." }, { "code": null, "e": 33406, "s": 33298, "text": "Above every list has its own index, and can be located directly by using eq(index) method as below example." }, { "code": null, "e": 33524, "s": 33406, "text": "Every child element starts its index from zero, thus, list item 2 would be accessed by using $(\"li\").eq(1) and so on." }, { "code": null, "e": 33642, "s": 33524, "text": "Every child element starts its index from zero, thus, list item 2 would be accessed by using $(\"li\").eq(1) and so on." }, { "code": null, "e": 33714, "s": 33642, "text": "Following is a simple example which adds the color to second list item." }, { "code": null, "e": 34454, "s": 33714, "text": "<html>\n <head>\n <title>The JQuery Example</title>\n <script type = \"text/javascript\" \n src = \"https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js\">\n </script>\n\t\t\n <script type = \"text/javascript\" language = \"javascript\">\n $(document).ready(function() {\n $(\"li\").eq(2).addClass(\"selected\");\n });\n </script>\n\t\t\n <style>\n .selected { color:red; }\n </style>\n </head>\n\t\n <body>\n <div>\n <ul>\n <li>list item 1</li>\n <li>list item 2</li>\n <li>list item 3</li>\n <li>list item 4</li>\n <li>list item 5</li>\n <li>list item 6</li>\n </ul>\n </div>\n </body>\n</html>" }, { "code": null, "e": 34491, "s": 34454, "text": "This will produce following result −" }, { "code": null, "e": 34503, "s": 34491, "text": "list item 1" }, { "code": null, "e": 34515, "s": 34503, "text": "list item 2" }, { "code": null, "e": 34527, "s": 34515, "text": "list item 3" }, { "code": null, "e": 34539, "s": 34527, "text": "list item 4" }, { "code": null, "e": 34551, "s": 34539, "text": "list item 5" }, { "code": null, "e": 34563, "s": 34551, "text": "list item 6" }, { "code": null, "e": 34765, "s": 34563, "text": "The filter( selector ) method can be used to filter out all elements from the set of matched elements that do not match the specified selector(s). The selector can be written using any selector syntax." }, { "code": null, "e": 34860, "s": 34765, "text": "Following is a simple example which applies color to the lists associated with middle class −" }, { "code": null, "e": 35708, "s": 34860, "text": "<html>\n <head>\n <title>The JQuery Example</title>\n <script type = \"text/javascript\" \n src = \"https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js\">\n </script>\n\t\t\n <script type = \"text/javascript\" language = \"javascript\">\n $(document).ready(function() {\n $(\"li\").filter(\".middle\").addClass(\"selected\");\n });\n </script>\n\t\t\n <style>\n .selected { color:red; }\n </style>\n </head>\n\t\n <body>\n <div>\n <ul>\n <li class = \"top\">list item 1</li>\n <li class = \"top\">list item 2</li>\n <li class = \"middle\">list item 3</li>\n <li class = \"middle\">list item 4</li>\n <li class = \"bottom\">list item 5</li>\n <li class = \"bottom\">list item 6</li>\n </ul>\n </div>\n </body>\n</html>" }, { "code": null, "e": 35745, "s": 35708, "text": "This will produce following result −" }, { "code": null, "e": 35757, "s": 35745, "text": "list item 1" }, { "code": null, "e": 35769, "s": 35757, "text": "list item 2" }, { "code": null, "e": 35781, "s": 35769, "text": "list item 3" }, { "code": null, "e": 35793, "s": 35781, "text": "list item 4" }, { "code": null, "e": 35805, "s": 35793, "text": "list item 5" }, { "code": null, "e": 35817, "s": 35805, "text": "list item 6" }, { "code": null, "e": 35984, "s": 35817, "text": "The find( selector ) method can be used to locate all the descendant elements of a particular type of elements. The selector can be written using any selector syntax." }, { "code": null, "e": 36088, "s": 35984, "text": "Following is an example which selects all the <span> elements available inside different <p> elements −" }, { "code": null, "e": 36715, "s": 36088, "text": "<html>\n <head>\n <title>The JQuery Example</title>\n <script type = \"text/javascript\" \n src = \"https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js\">\n </script>\n\t\t\n <script type = \"text/javascript\" language = \"javascript\">\n $(document).ready(function() {\n $(\"p\").find(\"span\").addClass(\"selected\");\n });\n </script>\n\t\t\n <style>\n .selected { color:red; }\n </style>\n </head>\n\t\n <body>\n <p>This is 1st paragraph and <span>THIS IS RED</span></p>\n <p>This is 2nd paragraph and <span>THIS IS ALSO RED</span></p>\n </body>\n</html>" }, { "code": null, "e": 36752, "s": 36715, "text": "This will produce following result −" }, { "code": null, "e": 36790, "s": 36752, "text": "This is 1st paragraph and THIS IS RED" }, { "code": null, "e": 36833, "s": 36790, "text": "This is 2nd paragraph and THIS IS ALSO RED" }, { "code": null, "e": 36954, "s": 36833, "text": "Following table lists down useful methods which you can use to filter out various elements from a list of DOM elements −" }, { "code": null, "e": 37010, "s": 36954, "text": "Reduce the set of matched elements to a single element." }, { "code": null, "e": 37109, "s": 37010, "text": "Removes all elements from the set of matched elements that do not match the specified selector(s)." }, { "code": null, "e": 37205, "s": 37109, "text": "Removes all elements from the set of matched elements that do not match the specified function." }, { "code": null, "e": 37340, "s": 37205, "text": "Checks the current selection against an expression and returns true, if at least one element of the selection fits the given selector." }, { "code": null, "e": 37476, "s": 37340, "text": "Translate a set of elements in the jQuery object into another set of values in a jQuery array (which may, or may not contain elements)." }, { "code": null, "e": 37559, "s": 37476, "text": "Removes elements matching the specified selector from the set of matched elements." }, { "code": null, "e": 37601, "s": 37559, "text": "Selects a subset of the matched elements." }, { "code": null, "e": 37705, "s": 37601, "text": "Following table lists down other useful methods which you can use to locate various elements in a DOM −" }, { "code": null, "e": 37788, "s": 37705, "text": "Adds more elements, matched by the given selector, to the set of matched elements." }, { "code": null, "e": 37841, "s": 37788, "text": "Add the previous selection to the current selection." }, { "code": null, "e": 37951, "s": 37841, "text": "Get a set of elements containing all of the unique immediate children of each of the matched set of elements." }, { "code": null, "e": 38079, "s": 37951, "text": "Get a set of elements containing the closest parent element that matches the specified selector, the starting element included." }, { "code": null, "e": 38210, "s": 38079, "text": "Find all the child nodes inside the matched elements (including text nodes), or the content document, if the element is an iframe." }, { "code": null, "e": 38318, "s": 38210, "text": "Revert the most recent 'destructive' operation, changing the set of matched elements to its previous state." }, { "code": null, "e": 38387, "s": 38318, "text": "Searches for descendant elements that match the specified selectors." }, { "code": null, "e": 38483, "s": 38387, "text": "Get a set of elements containing the unique next siblings of each of the given set of elements." }, { "code": null, "e": 38536, "s": 38483, "text": "Find all sibling elements after the current element." }, { "code": null, "e": 38621, "s": 38536, "text": "Returns a jQuery collection with the positioned parent of the first matched element." }, { "code": null, "e": 38751, "s": 38621, "text": "Get the direct parent of an element. If called on a set of elements, parent returns a set of their unique direct parent elements." }, { "code": null, "e": 38867, "s": 38751, "text": "Get a set of elements containing the unique ancestors of the matched set of elements (except for the root element)." }, { "code": null, "e": 38969, "s": 38867, "text": "Get a set of elements containing the unique previous siblings of each of the matched set of elements." }, { "code": null, "e": 39028, "s": 38969, "text": "Find all sibling elements in front of the current element." }, { "code": null, "e": 39128, "s": 39028, "text": "Get a set of elements containing all of the unique siblings of each of the matched set of elements." }, { "code": null, "e": 39305, "s": 39128, "text": "The jQuery library supports nearly all of the selectors included in Cascading Style Sheet (CSS) specifications 1 through 3, as outlined on the World Wide Web Consortium's site." }, { "code": null, "e": 39464, "s": 39305, "text": "Using JQuery library developers can enhance their websites without worrying about browsers and their versions as long as the browsers have JavaScript enabled." }, { "code": null, "e": 39601, "s": 39464, "text": "Most of the JQuery CSS Methods do not modify the content of the jQuery object and they are used to apply CSS properties on DOM elements." }, { "code": null, "e": 39703, "s": 39601, "text": "This is very simple to apply any CSS property using JQuery method css( PropertyName, PropertyValue )." }, { "code": null, "e": 39739, "s": 39703, "text": "Here is the syntax for the method −" }, { "code": null, "e": 39785, "s": 39739, "text": "selector.css( PropertyName, PropertyValue );\n" }, { "code": null, "e": 39905, "s": 39785, "text": "Here you can pass PropertyName as a javascript string and based on its value, PropertyValue could be string or integer." }, { "code": null, "e": 39976, "s": 39905, "text": "Following is an example which adds font color to the second list item." }, { "code": null, "e": 40649, "s": 39976, "text": "<html>\n <head>\n <title>The jQuery Example</title>\n <script type = \"text/javascript\" \n src = \"https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js\">\n </script>\n\t\t\n <script type = \"text/javascript\" language = \"javascript\">\n $(document).ready(function() {\n $(\"li\").eq(2).css(\"color\", \"red\");\n });\n </script>\n </head>\n\t\n <body>\n <div>\n <ul>\n <li>list item 1</li>\n <li>list item 2</li>\n <li>list item 3</li>\n <li>list item 4</li>\n <li>list item 5</li>\n <li>list item 6</li>\n </ul>\n </div>\n </body>\n</html>" }, { "code": null, "e": 40686, "s": 40649, "text": "This will produce following result −" }, { "code": null, "e": 40698, "s": 40686, "text": "list item 1" }, { "code": null, "e": 40710, "s": 40698, "text": "list item 2" }, { "code": null, "e": 40722, "s": 40710, "text": "list item 3" }, { "code": null, "e": 40734, "s": 40722, "text": "list item 4" }, { "code": null, "e": 40746, "s": 40734, "text": "list item 5" }, { "code": null, "e": 40758, "s": 40746, "text": "list item 6" }, { "code": null, "e": 40922, "s": 40758, "text": "You can apply multiple CSS properties using a single JQuery method CSS( {key1:val1, key2:val2....). You can apply as many properties as you like in a single call." }, { "code": null, "e": 40958, "s": 40922, "text": "Here is the syntax for the method −" }, { "code": null, "e": 41010, "s": 40958, "text": "selector.css( {key1:val1, key2:val2....keyN:valN})\n" }, { "code": null, "e": 41085, "s": 41010, "text": "Here you can pass key as property and val as its value as described above." }, { "code": null, "e": 41184, "s": 41085, "text": "Following is an example which adds font color as well as background color to the second list item." }, { "code": null, "e": 41886, "s": 41184, "text": "<html>\n <head>\n <title>The jQuery Example</title>\n <script type = \"text/javascript\" \n src = \"https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js\">\n </script>\n\t\t\n <script type = \"text/javascript\" language = \"javascript\">\n $(document).ready(function() {\n $(\"li\").eq(2).css({\"color\":\"red\", \"background-color\":\"green\"});\n });\n </script>\n </head>\n\t\n <body>\n <div>\n <ul>\n <li>list item 1</li>\n <li>list item 2</li>\n <li>list item 3</li>\n <li>list item 4</li>\n <li>list item 5</li>\n <li>list item 6</li>\n </ul>\n </div>\n </body>\n</html>" }, { "code": null, "e": 41923, "s": 41886, "text": "This will produce following result −" }, { "code": null, "e": 41935, "s": 41923, "text": "list item 1" }, { "code": null, "e": 41947, "s": 41935, "text": "list item 2" }, { "code": null, "e": 41959, "s": 41947, "text": "list item 3" }, { "code": null, "e": 41971, "s": 41959, "text": "list item 4" }, { "code": null, "e": 41983, "s": 41971, "text": "list item 5" }, { "code": null, "e": 41995, "s": 41983, "text": "list item 6" }, { "code": null, "e": 42106, "s": 41995, "text": "The width( val ) and height( val ) method can be used to set the width and height respectively of any element." }, { "code": null, "e": 42244, "s": 42106, "text": "Following is a simple example which sets the width of first division element where as rest of the elements have width set by style sheet" }, { "code": null, "e": 42977, "s": 42244, "text": "<html>\n <head>\n <title>The jQuery Example</title>\n <script type = \"text/javascript\" \n src = \"https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js\">\n </script>\n\t\t\n <script type = \"text/javascript\" language = \"javascript\">\n $(document).ready(function() {\n $(\"div:first\").width(100);\n $(\"div:first\").css(\"background-color\", \"blue\");\n });\n </script>\n\t\t\n <style>\n div { \n width:70px; height:50px; float:left; \n margin:5px; background:red; cursor:pointer; \n }\n </style>\n </head>\n\t\n <body>\n <div></div>\n <div>d</div>\n <div>d</div>\n <div>d</div>\n <div>d</div>\n </body>\n</html>" }, { "code": null, "e": 43014, "s": 42977, "text": "This will produce following result −" }, { "code": null, "e": 43105, "s": 43014, "text": "Following table lists down all the methods which you can use to play with CSS properties −" }, { "code": null, "e": 43159, "s": 43105, "text": "Return a style property on the first matched element." }, { "code": null, "e": 43223, "s": 43159, "text": "Set a single style property to a value on all matched elements." }, { "code": null, "e": 43291, "s": 43223, "text": "Set a key/value object as style properties to all matched elements." }, { "code": null, "e": 43336, "s": 43291, "text": "Set the CSS height of every matched element." }, { "code": null, "e": 43406, "s": 43336, "text": "Get the current computed, pixel, height of the first matched element." }, { "code": null, "e": 43506, "s": 43406, "text": "Gets the inner height (excludes the border and includes the padding) for the first matched element." }, { "code": null, "e": 43605, "s": 43506, "text": "Gets the inner width (excludes the border and includes the padding) for the first matched element." }, { "code": null, "e": 43695, "s": 43605, "text": "Get the current offset of the first matched element, in pixels, relative to the document." }, { "code": null, "e": 43780, "s": 43695, "text": "Returns a jQuery collection with the positioned parent of the first matched element." }, { "code": null, "e": 43878, "s": 43780, "text": "Gets the outer height (includes the border and padding by default) for the first matched element." }, { "code": null, "e": 43974, "s": 43878, "text": "Get the outer width (includes the border and padding by default) for the first matched element." }, { "code": null, "e": 44050, "s": 43974, "text": "Gets the top and left position of an element relative to its offset parent." }, { "code": null, "e": 44146, "s": 44050, "text": "When a value is passed in, the scroll left offset is set to that value on all matched elements." }, { "code": null, "e": 44204, "s": 44146, "text": "Gets the scroll left offset of the first matched element." }, { "code": null, "e": 44299, "s": 44204, "text": "When a value is passed in, the scroll top offset is set to that value on all matched elements." }, { "code": null, "e": 44356, "s": 44299, "text": "Gets the scroll top offset of the first matched element." }, { "code": null, "e": 44400, "s": 44356, "text": "Set the CSS width of every matched element." }, { "code": null, "e": 44469, "s": 44400, "text": "Get the current computed, pixel, width of the first matched element." }, { "code": null, "e": 44664, "s": 44469, "text": "JQuery provides methods to manipulate DOM in efficient way. You do not need to write big code to modify the value of any element's attribute or to extract HTML code from a paragraph or division." }, { "code": null, "e": 44803, "s": 44664, "text": "JQuery provides methods such as .attr(), .html(), and .val() which act as getters, retrieving information from DOM elements for later use." }, { "code": null, "e": 44887, "s": 44803, "text": "The html( ) method gets the html contents (innerHTML) of the first matched element." }, { "code": null, "e": 44923, "s": 44887, "text": "Here is the syntax for the method −" }, { "code": null, "e": 44941, "s": 44923, "text": "selector.html( )\n" }, { "code": null, "e": 45147, "s": 44941, "text": "Following is an example which makes use of .html() and .text(val) methods. Here .html() retrieves HTML content from the object and then .text( val ) method sets value of the object using passed parameter −" }, { "code": null, "e": 45965, "s": 45147, "text": "<html>\n <head>\n <title>The jQuery Example</title>\n <script type = \"text/javascript\" \n src = \"https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js\">\n </script>\n\t\t\n <script type = \"text/javascript\" language = \"javascript\">\n $(document).ready(function() {\n $(\"div\").click(function () {\n var content = $(this).html();\n $(\"#result\").text( content );\n });\n });\n </script>\n\t\t\n <style>\n #division{ margin:10px;padding:12px; border:2px solid #666; width:60px;}\n </style>\n </head>\n\t\n <body>\n <p>Click on the square below:</p>\n <span id = \"result\"> </span>\n\t\t\n <div id = \"division\" style = \"background-color:blue;\">\n This is Blue Square!!\n </div>\n </body>\n</html>" }, { "code": null, "e": 46002, "s": 45965, "text": "This will produce following result −" }, { "code": null, "e": 46030, "s": 46002, "text": "Click on the square below −" }, { "code": null, "e": 46175, "s": 46030, "text": "You can replace a complete DOM element with the specified HTML or DOM elements. The replaceWith( content ) method serves this purpose very well." }, { "code": null, "e": 46211, "s": 46175, "text": "Here is the syntax for the method −" }, { "code": null, "e": 46244, "s": 46211, "text": "selector.replaceWith( content )\n" }, { "code": null, "e": 46346, "s": 46244, "text": "Here content is what you want to have instead of original element. This could be HTML or simple text." }, { "code": null, "e": 46442, "s": 46346, "text": "Following is an example which would replace division element with \"<h1>JQuery is Great </h1>\" −" }, { "code": null, "e": 47234, "s": 46442, "text": "<html>\n <head>\n <title>The jQuery Example</title>\n <script type = \"text/javascript\" \n src = \"https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js\">\n </script>\n\t\t\n <script type = \"text/javascript\" language = \"javascript\">\n $(document).ready(function() {\n $(\"div\").click(function () {\n $(this).replaceWith(\"<h1>JQuery is Great</h1>\");\n });\n });\n </script>\n\t\t\n <style>\n #division{ margin:10px;padding:12px; border:2px solid #666; width:60px;}\n </style>\n </head>\n\t\n <body>\n <p>Click on the square below:</p>\n <span id = \"result\"> </span>\n\t\t\n <div id = \"division\" style = \"background-color:blue;\">\n This is Blue Square!!\n </div>\n </body>\n</html>" }, { "code": null, "e": 47271, "s": 47234, "text": "This will produce following result −" }, { "code": null, "e": 47299, "s": 47271, "text": "Click on the square below −" }, { "code": null, "e": 47451, "s": 47299, "text": "There may be a situation when you would like to remove one or more DOM elements from the document. JQuery provides two methods to handle the situation." }, { "code": null, "e": 47612, "s": 47451, "text": "The empty( ) method remove all child nodes from the set of matched elements where as the method remove( expr ) method removes all matched elements from the DOM." }, { "code": null, "e": 47648, "s": 47612, "text": "Here is the syntax for the method −" }, { "code": null, "e": 47700, "s": 47648, "text": "selector.remove( [ expr ])\n\nor \n\nselector.empty( )\n" }, { "code": null, "e": 47782, "s": 47700, "text": "You can pass optional parameter expr to filter the set of elements to be removed." }, { "code": null, "e": 47870, "s": 47782, "text": "Following is an example where elements are being removed as soon as they are clicked −" }, { "code": null, "e": 48717, "s": 47870, "text": "<html>\n <head>\n <title>The jQuery Example</title>\n <script type = \"text/javascript\" \n src = \"https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js\">\n </script>\n\t\t\n <script type = \"text/javascript\" language = \"javascript\">\n $(document).ready(function() {\n $(\"div\").click(function () {\n $(this).remove( );\n });\n });\n </script>\n\t\t\n <style>\n .div{ margin:10px;padding:12px; border:2px solid #666; width:60px;}\n </style>\n </head>\n\t\n <body>\n <p>Click on any square below:</p>\n <span id = \"result\"> </span>\n\t\t\n <div class = \"div\" style = \"background-color:blue;\"></div>\n <div class = \"div\" style = \"background-color:green;\"></div>\n <div class = \"div\" style = \"background-color:red;\"></div>\n </body>\n</html>" }, { "code": null, "e": 48754, "s": 48717, "text": "This will produce following result −" }, { "code": null, "e": 48782, "s": 48754, "text": "Click on any square below −" }, { "code": null, "e": 48966, "s": 48782, "text": "There may be a situation when you would like to insert new one or more DOM elements in your existing document. JQuery provides various methods to insert elements at various locations." }, { "code": null, "e": 49142, "s": 48966, "text": "The after( content ) method insert content after each of the matched elements where as the method before( content ) method inserts content before each of the matched elements." }, { "code": null, "e": 49178, "s": 49142, "text": "Here is the syntax for the method −" }, { "code": null, "e": 49237, "s": 49178, "text": "selector.after( content )\n\nor\n\nselector.before( content )\n" }, { "code": null, "e": 49313, "s": 49237, "text": "Here content is what you want to insert. This could be HTML or simple text." }, { "code": null, "e": 49411, "s": 49313, "text": "Following is an example where <div> elements are being inserted just before the clicked element −" }, { "code": null, "e": 50283, "s": 49411, "text": "<html>\n <head>\n <title>The jQuery Example</title>\n <script type = \"text/javascript\" \n src = \"https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js\">\n </script>\n\t\t\n <script type = \"text/javascript\" language = \"javascript\">\n $(document).ready(function() {\n $(\"div\").click(function () {\n $(this).before('<div class=\"div\"></div>' );\n });\n });\n </script>\n\t\t\n <style>\n .div{ margin:10px;padding:12px; border:2px solid #666; width:60px;}\n </style>\n </head>\n\t\n <body>\n <p>Click on any square below:</p>\n <span id = \"result\"> </span>\n\t\t\n <div class = \"div\" style = \"background-color:blue;\"></div>\n <div class = \"div\" style = \"background-color:green;\"></div>\n <div class = \"div\" style = \"background-color:red;\"></div>\n </body>\n</html>" }, { "code": null, "e": 50320, "s": 50283, "text": "This will produce following result −" }, { "code": null, "e": 50348, "s": 50320, "text": "Click on any square below −" }, { "code": null, "e": 50438, "s": 50348, "text": "Following table lists down all the methods which you can use to manipulate DOM elements −" }, { "code": null, "e": 50489, "s": 50438, "text": "Insert content after each of the matched elements." }, { "code": null, "e": 50544, "s": 50489, "text": "Append content to the inside of every matched element." }, { "code": null, "e": 50619, "s": 50544, "text": "Append all of the matched elements to another, specified, set of elements." }, { "code": null, "e": 50671, "s": 50619, "text": "Insert content before each of the matched elements." }, { "code": null, "e": 50752, "s": 50671, "text": "Clone matched DOM Elements, and all their event handlers, and select the clones." }, { "code": null, "e": 50802, "s": 50752, "text": "Clone matched DOM Elements and select the clones." }, { "code": null, "e": 50859, "s": 50802, "text": "Remove all child nodes from the set of matched elements." }, { "code": null, "e": 50907, "s": 50859, "text": "Set the html contents of every matched element." }, { "code": null, "e": 50971, "s": 50907, "text": "Get the html contents (innerHTML) of the first matched element." }, { "code": null, "e": 51049, "s": 50971, "text": "Insert all of the matched elements after another, specified, set of elements." }, { "code": null, "e": 51128, "s": 51049, "text": "Insert all of the matched elements before another, specified, set of elements." }, { "code": null, "e": 51184, "s": 51128, "text": "Prepend content to the inside of every matched element." }, { "code": null, "e": 51260, "s": 51184, "text": "Prepend all of the matched elements to another, specified, set of elements." }, { "code": null, "e": 51303, "s": 51260, "text": "Removes all matched elements from the DOM." }, { "code": null, "e": 51386, "s": 51303, "text": "Replaces the elements matched by the specified selector with the matched elements." }, { "code": null, "e": 51457, "s": 51386, "text": "Replaces all matched elements with the specified HTML or DOM elements." }, { "code": null, "e": 51504, "s": 51457, "text": "Set the text contents of all matched elements." }, { "code": null, "e": 51560, "s": 51504, "text": "Get the combined text contents of all matched elements." }, { "code": null, "e": 51614, "s": 51560, "text": "Wrap each matched element with the specified element." }, { "code": null, "e": 51673, "s": 51614, "text": "Wrap each matched element with the specified HTML content." }, { "code": null, "e": 51745, "s": 51673, "text": "Wrap all the elements in the matched set into a single wrapper element." }, { "code": null, "e": 51817, "s": 51745, "text": "Wrap all the elements in the matched set into a single wrapper element." }, { "code": null, "e": 51914, "s": 51817, "text": "Wrap the inner child contents of each matched element (including text nodes) with a DOM element." }, { "code": null, "e": 52015, "s": 51914, "text": "Wrap the inner child contents of each matched element (including text nodes) with an HTML structure." }, { "code": null, "e": 52145, "s": 52015, "text": "We have the ability to create dynamic web pages by using events. Events are actions that can be detected by your Web Application." }, { "code": null, "e": 52181, "s": 52145, "text": "Following are the examples events −" }, { "code": null, "e": 52195, "s": 52181, "text": "A mouse click" }, { "code": null, "e": 52214, "s": 52195, "text": "A web page loading" }, { "code": null, "e": 52243, "s": 52214, "text": "Taking mouse over an element" }, { "code": null, "e": 52267, "s": 52243, "text": "Submitting an HTML form" }, { "code": null, "e": 52302, "s": 52267, "text": "A keystroke on your keyboard, etc." }, { "code": null, "e": 52466, "s": 52302, "text": "When these events are triggered, you can then use a custom function to do pretty much whatever you want with the event. These custom functions call Event Handlers." }, { "code": null, "e": 52580, "s": 52466, "text": "Using the jQuery Event Model, we can establish event handlers on DOM elements with the bind() method as follows −" }, { "code": null, "e": 53435, "s": 52580, "text": "<html>\n <head>\n <title>The jQuery Example</title>\n <script type = \"text/javascript\" \n src = \"https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js\">\n </script>\n\t\t\n <script type = \"text/javascript\" language = \"javascript\">\n $(document).ready(function() {\n $('div').bind('click', function( event ){\n alert('Hi there!');\n });\n });\n </script>\n\t\t\n <style>\n .div{ margin:10px;padding:12px; border:2px solid #666; width:60px;}\n </style>\n </head>\n\t\n <body>\n <p>Click on any square below to see the result:</p>\n\t\t\n <div class = \"div\" style = \"background-color:blue;\">ONE</div>\n <div class = \"div\" style = \"background-color:green;\">TWO</div>\n <div class = \"div\" style = \"background-color:red;\">THREE</div>\n </body>\n</html>" }, { "code": null, "e": 53585, "s": 53435, "text": "This code will cause the division element to respond to the click event; when a user clicks inside this division thereafter, the alert will be shown." }, { "code": null, "e": 53622, "s": 53585, "text": "This will produce following result −" }, { "code": null, "e": 53668, "s": 53622, "text": "Click on any square below to see the result −" }, { "code": null, "e": 53722, "s": 53668, "text": "The full syntax of the bind() command is as follows −" }, { "code": null, "e": 53771, "s": 53722, "text": "selector.bind( eventType[, eventData], handler)\n" }, { "code": null, "e": 53820, "s": 53771, "text": "Following is the description of the parameters −" }, { "code": null, "e": 53964, "s": 53820, "text": "eventType − A string containing a JavaScript event type, such as click or submit. Refer to the next section for a complete list of event types." }, { "code": null, "e": 54108, "s": 53964, "text": "eventType − A string containing a JavaScript event type, such as click or submit. Refer to the next section for a complete list of event types." }, { "code": null, "e": 54206, "s": 54108, "text": "eventData − This is optional parameter is a map of data that will be passed to the event handler." }, { "code": null, "e": 54304, "s": 54206, "text": "eventData − This is optional parameter is a map of data that will be passed to the event handler." }, { "code": null, "e": 54370, "s": 54304, "text": "handler − A function to execute each time the event is triggered." }, { "code": null, "e": 54436, "s": 54370, "text": "handler − A function to execute each time the event is triggered." }, { "code": null, "e": 54614, "s": 54436, "text": "Typically, once an event handler is established, it remains in effect for the remainder of the life of the page. There may be a need when you would like to remove event handler." }, { "code": null, "e": 54726, "s": 54614, "text": "jQuery provides the unbind() command to remove an exiting event handler. The syntax of unbind() is as follows −" }, { "code": null, "e": 54796, "s": 54726, "text": "selector.unbind(eventType, handler)\n\nor \n\nselector.unbind(eventType)\n" }, { "code": null, "e": 54845, "s": 54796, "text": "Following is the description of the parameters −" }, { "code": null, "e": 54989, "s": 54845, "text": "eventType − A string containing a JavaScript event type, such as click or submit. Refer to the next section for a complete list of event types." }, { "code": null, "e": 55133, "s": 54989, "text": "eventType − A string containing a JavaScript event type, such as click or submit. Refer to the next section for a complete list of event types." }, { "code": null, "e": 55211, "s": 55133, "text": "handler − If provided, identifies the specific listener that's to be removed." }, { "code": null, "e": 55289, "s": 55211, "text": "handler − If provided, identifies the specific listener that's to be removed." }, { "code": null, "e": 55294, "s": 55289, "text": "blur" }, { "code": null, "e": 55331, "s": 55294, "text": "Occurs when the element loses focus." }, { "code": null, "e": 55338, "s": 55331, "text": "change" }, { "code": null, "e": 55371, "s": 55338, "text": "Occurs when the element changes." }, { "code": null, "e": 55377, "s": 55371, "text": "click" }, { "code": null, "e": 55404, "s": 55377, "text": "Occurs when a mouse click." }, { "code": null, "e": 55413, "s": 55404, "text": "dblclick" }, { "code": null, "e": 55447, "s": 55413, "text": "Occurs when a mouse double-click." }, { "code": null, "e": 55453, "s": 55447, "text": "error" }, { "code": null, "e": 55512, "s": 55453, "text": "Occurs when there is an error in loading or unloading etc." }, { "code": null, "e": 55518, "s": 55512, "text": "focus" }, { "code": null, "e": 55554, "s": 55518, "text": "Occurs when the element gets focus." }, { "code": null, "e": 55562, "s": 55554, "text": "keydown" }, { "code": null, "e": 55590, "s": 55562, "text": "Occurs when key is pressed." }, { "code": null, "e": 55599, "s": 55590, "text": "keypress" }, { "code": null, "e": 55640, "s": 55599, "text": "Occurs when key is pressed and released." }, { "code": null, "e": 55646, "s": 55640, "text": "keyup" }, { "code": null, "e": 55675, "s": 55646, "text": "Occurs when key is released." }, { "code": null, "e": 55680, "s": 55675, "text": "load" }, { "code": null, "e": 55712, "s": 55680, "text": "Occurs when document is loaded." }, { "code": null, "e": 55722, "s": 55712, "text": "mousedown" }, { "code": null, "e": 55759, "s": 55722, "text": "Occurs when mouse button is pressed." }, { "code": null, "e": 55770, "s": 55759, "text": "mouseenter" }, { "code": null, "e": 55817, "s": 55770, "text": "Occurs when mouse enters in an element region." }, { "code": null, "e": 55828, "s": 55817, "text": "mouseleave" }, { "code": null, "e": 55872, "s": 55828, "text": "Occurs when mouse leaves an element region." }, { "code": null, "e": 55882, "s": 55872, "text": "mousemove" }, { "code": null, "e": 55915, "s": 55882, "text": "Occurs when mouse pointer moves." }, { "code": null, "e": 55924, "s": 55915, "text": "mouseout" }, { "code": null, "e": 55975, "s": 55924, "text": "Occurs when mouse pointer moves out of an element." }, { "code": null, "e": 55985, "s": 55975, "text": "mouseover" }, { "code": null, "e": 56034, "s": 55985, "text": "Occurs when mouse pointer moves over an element." }, { "code": null, "e": 56042, "s": 56034, "text": "mouseup" }, { "code": null, "e": 56080, "s": 56042, "text": "Occurs when mouse button is released." }, { "code": null, "e": 56087, "s": 56080, "text": "resize" }, { "code": null, "e": 56118, "s": 56087, "text": "Occurs when window is resized." }, { "code": null, "e": 56125, "s": 56118, "text": "scroll" }, { "code": null, "e": 56157, "s": 56125, "text": "Occurs when window is scrolled." }, { "code": null, "e": 56164, "s": 56157, "text": "select" }, { "code": null, "e": 56196, "s": 56164, "text": "Occurs when a text is selected." }, { "code": null, "e": 56203, "s": 56196, "text": "submit" }, { "code": null, "e": 56234, "s": 56203, "text": "Occurs when form is submitted." }, { "code": null, "e": 56241, "s": 56234, "text": "unload" }, { "code": null, "e": 56276, "s": 56241, "text": "Occurs when documents is unloaded." }, { "code": null, "e": 56406, "s": 56276, "text": "The callback function takes a single parameter; when the handler is called the JavaScript event object will be passed through it." }, { "code": null, "e": 56686, "s": 56406, "text": "The event object is often unnecessary and the parameter is omitted, as sufficient context is usually available when the handler is bound to know exactly what needs to be done when the handler is triggered, however there are certain attributes which you would need to be accessed." }, { "code": null, "e": 56693, "s": 56686, "text": "altKey" }, { "code": null, "e": 56829, "s": 56693, "text": "Set to true if the Alt key was pressed when the event was triggered, false if not. The Alt key is labeled Option on most Mac keyboards." }, { "code": null, "e": 56837, "s": 56829, "text": "ctrlKey" }, { "code": null, "e": 56921, "s": 56837, "text": "Set to true if the Ctrl key was pressed when the event was triggered, false if not." }, { "code": null, "e": 56926, "s": 56921, "text": "data" }, { "code": null, "e": 57032, "s": 56926, "text": "The value, if any, passed as the second parameter to the bind() command when the handler was established." }, { "code": null, "e": 57040, "s": 57032, "text": "keyCode" }, { "code": null, "e": 57109, "s": 57040, "text": "For keyup and keydown events, this returns the key that was pressed." }, { "code": null, "e": 57117, "s": 57109, "text": "metaKey" }, { "code": null, "e": 57266, "s": 57117, "text": "Set to true if the Meta key was pressed when the event was triggered, false if not. The Meta key is the Ctrl key on PCs and the Command key on Macs." }, { "code": null, "e": 57272, "s": 57266, "text": "pageX" }, { "code": null, "e": 57370, "s": 57272, "text": "For mouse events, specifies the horizontal coordinate of the event relative from the page origin." }, { "code": null, "e": 57376, "s": 57370, "text": "pageY" }, { "code": null, "e": 57472, "s": 57376, "text": "For mouse events, specifies the vertical coordinate of the event relative from the page origin." }, { "code": null, "e": 57486, "s": 57472, "text": "relatedTarget" }, { "code": null, "e": 57594, "s": 57486, "text": "For some mouse events, identifies the element that the cursor left or entered when the event was triggered." }, { "code": null, "e": 57602, "s": 57594, "text": "screenX" }, { "code": null, "e": 57702, "s": 57602, "text": "For mouse events, specifies the horizontal coordinate of the event relative from the screen origin." }, { "code": null, "e": 57710, "s": 57702, "text": "screenY" }, { "code": null, "e": 57808, "s": 57710, "text": "For mouse events, specifies the vertical coordinate of the event relative from the screen origin." }, { "code": null, "e": 57817, "s": 57808, "text": "shiftKey" }, { "code": null, "e": 57902, "s": 57817, "text": "Set to true if the Shift key was pressed when the event was triggered, false if not." }, { "code": null, "e": 57909, "s": 57902, "text": "target" }, { "code": null, "e": 57967, "s": 57909, "text": "Identifies the element for which the event was triggered." }, { "code": null, "e": 57977, "s": 57967, "text": "timeStamp" }, { "code": null, "e": 58037, "s": 57977, "text": "The timestamp (in milliseconds) when the event was created." }, { "code": null, "e": 58042, "s": 58037, "text": "type" }, { "code": null, "e": 58127, "s": 58042, "text": "For all events, specifies the type of event that was triggered (for example, click)." }, { "code": null, "e": 58133, "s": 58127, "text": "which" }, { "code": null, "e": 58314, "s": 58133, "text": "For keyboard events, specifies the numeric code for the key that caused the event, and for mouse events, specifies which button was pressed (1 for left, 2 for middle, 3 for right)." }, { "code": null, "e": 59343, "s": 58314, "text": "<html>\n <head>\n <title>The jQuery Example</title>\n <script type = \"text/javascript\" \n src = \"https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js\">\n </script>\n\t\t\n <script type = \"text/javascript\" language = \"javascript\">\n $(document).ready(function() {\n $('div').bind('click', function( event ){\n alert('Event type is ' + event.type);\n alert('pageX : ' + event.pageX);\n alert('pageY : ' + event.pageY);\n alert('Target : ' + event.target.innerHTML);\n });\n });\n </script>\n\t\t\n <style>\n .div{ margin:10px;padding:12px; border:2px solid #666; width:60px;}\n </style>\n </head>\n\t\n <body>\n <p>Click on any square below to see the result:</p>\n\t\t\n <div class = \"div\" style = \"background-color:blue;\">ONE</div>\n <div class = \"div\" style = \"background-color:green;\">TWO</div>\n <div class = \"div\" style = \"background-color:red;\">THREE</div>\n </body>\n</html>" }, { "code": null, "e": 59380, "s": 59343, "text": "This will produce following result −" }, { "code": null, "e": 59426, "s": 59380, "text": "Click on any square below to see the result −" }, { "code": null, "e": 59494, "s": 59426, "text": "There is a list of methods which can be called on an Event Object −" }, { "code": null, "e": 59550, "s": 59494, "text": "Prevents the browser from executing the default action." }, { "code": null, "e": 59627, "s": 59550, "text": "Returns whether event.preventDefault() was ever called on this event object." }, { "code": null, "e": 59743, "s": 59627, "text": "Stops the bubbling of an event to parent elements, preventing any parent handlers from being notified of the event." }, { "code": null, "e": 59821, "s": 59743, "text": "Returns whether event.stopPropagation() was ever called on this event object." }, { "code": null, "e": 59873, "s": 59821, "text": "Stops the rest of the handlers from being executed." }, { "code": null, "e": 59960, "s": 59873, "text": "Returns whether event.stopImmediatePropagation() was ever called on this event object." }, { "code": null, "e": 60021, "s": 59960, "text": "Following table lists down important event-related methods −" }, { "code": null, "e": 60127, "s": 60021, "text": "Binds a handler to one or more events (like click) for each matched element. Can also bind custom events." }, { "code": null, "e": 60190, "s": 60127, "text": "This does the opposite of live, it removes a bound live event." }, { "code": null, "e": 60262, "s": 60190, "text": "Simulates hovering for example moving the mouse on, and off, an object." }, { "code": null, "e": 60380, "s": 60262, "text": "Binds a handler to an event (like click) for all current − and future − matched element. Can also bind custom events." }, { "code": null, "e": 60464, "s": 60380, "text": "Binds a handler to one or more events to be executed once for each matched element." }, { "code": null, "e": 60555, "s": 60464, "text": "Binds a function to be executed whenever the DOM is ready to be traversed and manipulated." }, { "code": null, "e": 60598, "s": 60555, "text": "Trigger an event on every matched element." }, { "code": null, "e": 60647, "s": 60598, "text": "Triggers all bound event handlers on an element." }, { "code": null, "e": 60738, "s": 60647, "text": "This does the opposite of bind, it removes bound events from each of the matched elements." }, { "code": null, "e": 60877, "s": 60738, "text": "jQuery also provides a set of event helper functions which can be used either to trigger an event to bind any event types mentioned above." }, { "code": null, "e": 60957, "s": 60877, "text": "Following is an example which would triggers the blur event on all paragraphs −" }, { "code": null, "e": 60973, "s": 60957, "text": "$(\"p\").blur();\n" }, { "code": null, "e": 61047, "s": 60973, "text": "Following is an example which would bind a click event on all the <div> −" }, { "code": null, "e": 61107, "s": 61047, "text": "$(\"div\").click( function () { \n // do something here\n});\n" }, { "code": null, "e": 61115, "s": 61107, "text": "blur( )" }, { "code": null, "e": 61164, "s": 61115, "text": "Triggers the blur event of each matched element." }, { "code": null, "e": 61175, "s": 61164, "text": "blur( fn )" }, { "code": null, "e": 61234, "s": 61175, "text": "Bind a function to the blur event of each matched element." }, { "code": null, "e": 61244, "s": 61234, "text": "change( )" }, { "code": null, "e": 61295, "s": 61244, "text": "Triggers the change event of each matched element." }, { "code": null, "e": 61308, "s": 61295, "text": "change( fn )" }, { "code": null, "e": 61370, "s": 61308, "text": "Binds a function to the change event of each matched element." }, { "code": null, "e": 61379, "s": 61370, "text": "click( )" }, { "code": null, "e": 61429, "s": 61379, "text": "Triggers the click event of each matched element." }, { "code": null, "e": 61441, "s": 61429, "text": "click( fn )" }, { "code": null, "e": 61502, "s": 61441, "text": "Binds a function to the click event of each matched element." }, { "code": null, "e": 61514, "s": 61502, "text": "dblclick( )" }, { "code": null, "e": 61567, "s": 61514, "text": "Triggers the dblclick event of each matched element." }, { "code": null, "e": 61582, "s": 61567, "text": "dblclick( fn )" }, { "code": null, "e": 61646, "s": 61582, "text": "Binds a function to the dblclick event of each matched element." }, { "code": null, "e": 61655, "s": 61646, "text": "error( )" }, { "code": null, "e": 61705, "s": 61655, "text": "Triggers the error event of each matched element." }, { "code": null, "e": 61717, "s": 61705, "text": "error( fn )" }, { "code": null, "e": 61778, "s": 61717, "text": "Binds a function to the error event of each matched element." }, { "code": null, "e": 61787, "s": 61778, "text": "focus( )" }, { "code": null, "e": 61837, "s": 61787, "text": "Triggers the focus event of each matched element." }, { "code": null, "e": 61849, "s": 61837, "text": "focus( fn )" }, { "code": null, "e": 61910, "s": 61849, "text": "Binds a function to the focus event of each matched element." }, { "code": null, "e": 61921, "s": 61910, "text": "keydown( )" }, { "code": null, "e": 61973, "s": 61921, "text": "Triggers the keydown event of each matched element." }, { "code": null, "e": 61987, "s": 61973, "text": "keydown( fn )" }, { "code": null, "e": 62049, "s": 61987, "text": "Bind a function to the keydown event of each matched element." }, { "code": null, "e": 62061, "s": 62049, "text": "keypress( )" }, { "code": null, "e": 62114, "s": 62061, "text": "Triggers the keypress event of each matched element." }, { "code": null, "e": 62129, "s": 62114, "text": "keypress( fn )" }, { "code": null, "e": 62193, "s": 62129, "text": "Binds a function to the keypress event of each matched element." }, { "code": null, "e": 62202, "s": 62193, "text": "keyup( )" }, { "code": null, "e": 62252, "s": 62202, "text": "Triggers the keyup event of each matched element." }, { "code": null, "e": 62264, "s": 62252, "text": "keyup( fn )" }, { "code": null, "e": 62324, "s": 62264, "text": "Bind a function to the keyup event of each matched element." }, { "code": null, "e": 62335, "s": 62324, "text": "load( fn )" }, { "code": null, "e": 62395, "s": 62335, "text": "Binds a function to the load event of each matched element." }, { "code": null, "e": 62411, "s": 62395, "text": "mousedown( fn )" }, { "code": null, "e": 62476, "s": 62411, "text": "Binds a function to the mousedown event of each matched element." }, { "code": null, "e": 62493, "s": 62476, "text": "mouseenter( fn )" }, { "code": null, "e": 62558, "s": 62493, "text": "Bind a function to the mouseenter event of each matched element." }, { "code": null, "e": 62575, "s": 62558, "text": "mouseleave( fn )" }, { "code": null, "e": 62640, "s": 62575, "text": "Bind a function to the mouseleave event of each matched element." }, { "code": null, "e": 62656, "s": 62640, "text": "mousemove( fn )" }, { "code": null, "e": 62720, "s": 62656, "text": "Bind a function to the mousemove event of each matched element." }, { "code": null, "e": 62735, "s": 62720, "text": "mouseout( fn )" }, { "code": null, "e": 62798, "s": 62735, "text": "Bind a function to the mouseout event of each matched element." }, { "code": null, "e": 62814, "s": 62798, "text": "mouseover( fn )" }, { "code": null, "e": 62878, "s": 62814, "text": "Bind a function to the mouseover event of each matched element." }, { "code": null, "e": 62892, "s": 62878, "text": "mouseup( fn )" }, { "code": null, "e": 62954, "s": 62892, "text": "Bind a function to the mouseup event of each matched element." }, { "code": null, "e": 62967, "s": 62954, "text": "resize( fn )" }, { "code": null, "e": 63028, "s": 62967, "text": "Bind a function to the resize event of each matched element." }, { "code": null, "e": 63041, "s": 63028, "text": "scroll( fn )" }, { "code": null, "e": 63102, "s": 63041, "text": "Bind a function to the scroll event of each matched element." }, { "code": null, "e": 63112, "s": 63102, "text": "select( )" }, { "code": null, "e": 63162, "s": 63112, "text": "Trigger the select event of each matched element." }, { "code": null, "e": 63175, "s": 63162, "text": "select( fn )" }, { "code": null, "e": 63236, "s": 63175, "text": "Bind a function to the select event of each matched element." }, { "code": null, "e": 63246, "s": 63236, "text": "submit( )" }, { "code": null, "e": 63296, "s": 63246, "text": "Trigger the submit event of each matched element." }, { "code": null, "e": 63309, "s": 63296, "text": "submit( fn )" }, { "code": null, "e": 63370, "s": 63309, "text": "Bind a function to the submit event of each matched element." }, { "code": null, "e": 63383, "s": 63370, "text": "unload( fn )" }, { "code": null, "e": 63445, "s": 63383, "text": "Binds a function to the unload event of each matched element." }, { "code": null, "e": 63599, "s": 63445, "text": "AJAX is an acronym standing for Asynchronous JavaScript and XML and this technology helps us to load data from the server without a browser page refresh." }, { "code": null, "e": 63703, "s": 63599, "text": "If you are new with AJAX, I would recommend you go through our Ajax Tutorial before proceeding further." }, { "code": null, "e": 63812, "s": 63703, "text": "JQuery is a great tool which provides a rich set of AJAX methods to develop next generation web application." }, { "code": null, "e": 63930, "s": 63812, "text": "This is very easy to load any static or dynamic data using JQuery AJAX. JQuery provides load() method to do the job −" }, { "code": null, "e": 63976, "s": 63930, "text": "Here is the simple syntax for load() method −" }, { "code": null, "e": 64021, "s": 63976, "text": "[selector].load( URL, [data], [callback] );\n" }, { "code": null, "e": 64069, "s": 64021, "text": "Here is the description of all the parameters −" }, { "code": null, "e": 64239, "s": 64069, "text": "URL − The URL of the server-side resource to which the request is sent. It could be a CGI, ASP, JSP, or PHP script which generates data dynamically or out of a database." }, { "code": null, "e": 64409, "s": 64239, "text": "URL − The URL of the server-side resource to which the request is sent. It could be a CGI, ASP, JSP, or PHP script which generates data dynamically or out of a database." }, { "code": null, "e": 64648, "s": 64409, "text": "data − This optional parameter represents an object whose properties are serialized into properly encoded parameters to be passed to the request. If specified, the request is made using the POST method. If omitted, the GET method is used." }, { "code": null, "e": 64887, "s": 64648, "text": "data − This optional parameter represents an object whose properties are serialized into properly encoded parameters to be passed to the request. If specified, the request is made using the POST method. If omitted, the GET method is used." }, { "code": null, "e": 65135, "s": 64887, "text": "callback − A callback function invoked after the response data has been loaded into the elements of the matched set. The first parameter passed to this function is the response text received from the server and second parameter is the status code." }, { "code": null, "e": 65383, "s": 65135, "text": "callback − A callback function invoked after the response data has been loaded into the elements of the matched set. The first parameter passed to this function is the response text received from the server and second parameter is the status code." }, { "code": null, "e": 65445, "s": 65383, "text": "Consider the following HTML file with a small JQuery coding −" }, { "code": null, "e": 66164, "s": 65445, "text": "<html>\n <head>\n <title>The jQuery Example</title>\n <script type = \"text/javascript\" \n src = \"https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js\">\n </script>\n\t\t\n <script type = \"text/javascript\" language = \"javascript\">\n $(document).ready(function() {\n $(\"#driver\").click(function(event){\n $('#stage').load('/jquery/result.html');\n });\n });\n </script>\n </head>\n\t\n <body>\n <p>Click on the button to load /jquery/result.html file −</p>\n\t\t\n <div id = \"stage\" style = \"background-color:cc0;\">\n STAGE\n </div>\n\t\t\n <input type = \"button\" id = \"driver\" value = \"Load Data\" />\n </body>\n</html>" }, { "code": null, "e": 66408, "s": 66164, "text": "Here load() initiates an Ajax request to the specified URL /jquery/result.html file. After loading this file, all the content would be populated inside <div> tagged with ID stage. Assuming, our /jquery/result.html file has just one HTML line −" }, { "code": null, "e": 66436, "s": 66408, "text": "<h1>THIS IS RESULT...</h1>\n" }, { "code": null, "e": 66504, "s": 66436, "text": "When you click the given button, then result.html file gets loaded." }, { "code": null, "e": 66551, "s": 66504, "text": "Click on the button to load result.html file −" }, { "code": null, "e": 66812, "s": 66551, "text": "There would be a situation when server would return JSON string against your request. JQuery utility function getJSON() parses the returned JSON string and makes the resulting string available to the callback function as first parameter to take further action." }, { "code": null, "e": 66861, "s": 66812, "text": "Here is the simple syntax for getJSON() method −" }, { "code": null, "e": 66909, "s": 66861, "text": "[selector].getJSON( URL, [data], [callback] );\n" }, { "code": null, "e": 66957, "s": 66909, "text": "Here is the description of all the parameters −" }, { "code": null, "e": 67029, "s": 66957, "text": "URL − The URL of the server-side resource contacted via the GET method." }, { "code": null, "e": 67101, "s": 67029, "text": "URL − The URL of the server-side resource contacted via the GET method." }, { "code": null, "e": 67269, "s": 67101, "text": "data − An object whose properties serve as the name/value pairs used to construct a query string to be appended to the URL, or a preformatted and encoded query string." }, { "code": null, "e": 67437, "s": 67269, "text": "data − An object whose properties serve as the name/value pairs used to construct a query string to be appended to the URL, or a preformatted and encoded query string." }, { "code": null, "e": 67651, "s": 67437, "text": "callback − A function invoked when the request completes. The data value resulting from digesting the response body as a JSON string is passed as the first parameter to this callback, and the status as the second." }, { "code": null, "e": 67865, "s": 67651, "text": "callback − A function invoked when the request completes. The data value resulting from digesting the response body as a JSON string is passed as the first parameter to this callback, and the status as the second." }, { "code": null, "e": 67927, "s": 67865, "text": "Consider the following HTML file with a small JQuery coding −" }, { "code": null, "e": 68881, "s": 67927, "text": "<html>\n <head>\n <title>The jQuery Example</title>\n <script type = \"text/javascript\" \n src = \"https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js\">\n </script>\n\t\t\n <script type = \"text/javascript\" language = \"javascript\">\n $(document).ready(function() {\n $(\"#driver\").click(function(event){\n\t\t\t\t\n $.getJSON('/jquery/result.json', function(jd) {\n $('#stage').html('<p> Name: ' + jd.name + '</p>');\n $('#stage').append('<p>Age : ' + jd.age+ '</p>');\n $('#stage').append('<p> Sex: ' + jd.sex+ '</p>');\n });\n\t\t\t\t\t\n });\n });\n </script>\n </head>\n\t\n <body>\n <p>Click on the button to load result.json file −</p>\n\t\t\n <div id = \"stage\" style = \"background-color:#eee;\">\n STAGE\n </div>\n\t\t\n <input type = \"button\" id = \"driver\" value = \"Load Data\" />\n </body>\n</html>" }, { "code": null, "e": 69203, "s": 68881, "text": "Here JQuery utility method getJSON() initiates an Ajax request to the specified URL result.json file. After loading this file, all the content would be passed to the callback function which finally would be populated inside <div> tagged with ID stage. Assuming, our result.json file has following json formatted content −" }, { "code": null, "e": 69267, "s": 69203, "text": "{\n \"name\": \"Zara Ali\",\n \"age\" : \"67\",\n \"sex\": \"female\"\n}\n" }, { "code": null, "e": 69335, "s": 69267, "text": "When you click the given button, then result.json file gets loaded." }, { "code": null, "e": 69382, "s": 69335, "text": "Click on the button to load result.html file −" }, { "code": null, "e": 69607, "s": 69382, "text": "Many times you collect input from the user and you pass that input to the server for further processing. JQuery AJAX made it easy enough to pass collected data to the server using data parameter of any available Ajax method." }, { "code": null, "e": 69741, "s": 69607, "text": "This example demonstrate how can pass user input to a web server script which would send the same result back and we would print it −" }, { "code": null, "e": 70568, "s": 69741, "text": "<html>\n <head>\n <title>The jQuery Example</title>\n <script type = \"text/javascript\" \n src = \"https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js\">\n </script>\n\t\t\n <script type = \"text/javascript\" language = \"javascript\">\n $(document).ready(function() {\n $(\"#driver\").click(function(event){\n var name = $(\"#name\").val();\n $(\"#stage\").load('/jquery/result.php', {\"name\":name} );\n });\n });\n </script>\n </head>\n\t\n <body>\n <p>Enter your name and click on the button:</p>\n <input type = \"input\" id = \"name\" size = \"40\" /><br />\n\t\t\n <div id = \"stage\" style = \"background-color:cc0;\">\n STAGE\n </div>\n\t\t\n <input type = \"button\" id = \"driver\" value = \"Show Result\" />\n </body>\n</html>" }, { "code": null, "e": 70616, "s": 70568, "text": "Here is the code written in result.php script −" }, { "code": null, "e": 70722, "s": 70616, "text": "<?php\n if( $_REQUEST[\"name\"] ){\n $name = $_REQUEST['name'];\n echo \"Welcome \". $name;\n }\n?> " }, { "code": null, "e": 70855, "s": 70722, "text": "Now you can enter any text in the given input box and then click \"Show Result\" button to see what you have entered in the input box." }, { "code": null, "e": 70897, "s": 70855, "text": "Enter your name and click on the button −" }, { "code": null, "e": 71056, "s": 70897, "text": "You have seen basic concept of AJAX using JQuery. Following table lists down all important JQuery AJAX methods which you can use based your programming need −" }, { "code": null, "e": 71098, "s": 71056, "text": "Load a remote page using an HTTP request." }, { "code": null, "e": 71139, "s": 71098, "text": "Setup global settings for AJAX requests." }, { "code": null, "e": 71185, "s": 71139, "text": "Load a remote page using an HTTP GET request." }, { "code": null, "e": 71227, "s": 71185, "text": "Load JSON data using an HTTP GET request." }, { "code": null, "e": 71291, "s": 71227, "text": "Loads and executes a JavaScript file using an HTTP GET request." }, { "code": null, "e": 71338, "s": 71291, "text": "Load a remote page using an HTTP POST request." }, { "code": null, "e": 71395, "s": 71338, "text": "Load HTML from a remote file and inject it into the DOM." }, { "code": null, "e": 71453, "s": 71395, "text": "Serializes a set of input elements into a string of data." }, { "code": null, "e": 71577, "s": 71453, "text": "Serializes all forms and form elements like the .serialize() method but returns a JSON data structure for you to work with." }, { "code": null, "e": 71725, "s": 71577, "text": "You can call various JQuery methods during the life cycle of AJAX call progress. Based on different events/stages following methods are available −" }, { "code": null, "e": 71765, "s": 71725, "text": "You can go through all the AJAX Events." }, { "code": null, "e": 71834, "s": 71765, "text": "Attach a function to be executed whenever an AJAX request completes." }, { "code": null, "e": 71933, "s": 71834, "text": "Attach a function to be executed whenever an AJAX request begins and there is none already active." }, { "code": null, "e": 71998, "s": 71933, "text": "Attach a function to be executed whenever an AJAX request fails." }, { "code": null, "e": 72063, "s": 71998, "text": "Attach a function to be executed before an AJAX request is sent." }, { "code": null, "e": 72135, "s": 72063, "text": "Attach a function to be executed whenever all AJAX requests have ended." }, { "code": null, "e": 72217, "s": 72135, "text": "Attach a function to be executed whenever an AJAX request completes successfully." }, { "code": null, "e": 72478, "s": 72217, "text": "jQuery provides a trivially simple interface for doing various kind of amazing effects. jQuery methods allow us to quickly apply commonly used effects with a minimum configuration. This tutorial covers all the important jQuery methods to create visual effects." }, { "code": null, "e": 72632, "s": 72478, "text": "The commands for showing and hiding elements are pretty much what we would expect − show() to show the elements in a wrapped set and hide() to hide them." }, { "code": null, "e": 72678, "s": 72632, "text": "Here is the simple syntax for show() method −" }, { "code": null, "e": 72717, "s": 72678, "text": "[selector].show( speed, [callback] );\n" }, { "code": null, "e": 72765, "s": 72717, "text": "Here is the description of all the parameters −" }, { "code": null, "e": 72924, "s": 72765, "text": "speed − A string representing one of the three predefined speeds (\"slow\", \"normal\", or \"fast\") or the number of milliseconds to run the animation (e.g. 1000)." }, { "code": null, "e": 73083, "s": 72924, "text": "speed − A string representing one of the three predefined speeds (\"slow\", \"normal\", or \"fast\") or the number of milliseconds to run the animation (e.g. 1000)." }, { "code": null, "e": 73238, "s": 73083, "text": "callback − This optional parameter represents a function to be executed whenever the animation completes; executes once for each element animated against." }, { "code": null, "e": 73393, "s": 73238, "text": "callback − This optional parameter represents a function to be executed whenever the animation completes; executes once for each element animated against." }, { "code": null, "e": 73444, "s": 73393, "text": "Following is the simple syntax for hide() method −" }, { "code": null, "e": 73483, "s": 73444, "text": "[selector].hide( speed, [callback] );\n" }, { "code": null, "e": 73531, "s": 73483, "text": "Here is the description of all the parameters −" }, { "code": null, "e": 73690, "s": 73531, "text": "speed − A string representing one of the three predefined speeds (\"slow\", \"normal\", or \"fast\") or the number of milliseconds to run the animation (e.g. 1000)." }, { "code": null, "e": 73849, "s": 73690, "text": "speed − A string representing one of the three predefined speeds (\"slow\", \"normal\", or \"fast\") or the number of milliseconds to run the animation (e.g. 1000)." }, { "code": null, "e": 74004, "s": 73849, "text": "callback − This optional parameter represents a function to be executed whenever the animation completes; executes once for each element animated against." }, { "code": null, "e": 74159, "s": 74004, "text": "callback − This optional parameter represents a function to be executed whenever the animation completes; executes once for each element animated against." }, { "code": null, "e": 74221, "s": 74159, "text": "Consider the following HTML file with a small JQuery coding −" }, { "code": null, "e": 75192, "s": 74221, "text": "<html>\n <head>\n <title>The jQuery Example</title>\n <script type = \"text/javascript\" \n src = \"https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js\">\n </script>\n\t\t\n <script type = \"text/javascript\" language = \"javascript\">\n $(document).ready(function() {\n\n $(\"#show\").click(function () {\n $(\".mydiv\").show( 1000 );\n });\n\n $(\"#hide\").click(function () {\n $(\".mydiv\").hide( 1000 );\n });\n\t\t\t\t\n });\n </script>\n\t\t\n <style>\n .mydiv{ \n margin:10px;\n padding:12px; \n border:2px solid #666; \n width:100px; \n height:100px;\n }\n </style>\n </head>\n\t\n <body>\n <div class = \"mydiv\">\n This is a SQUARE\n </div>\n\n <input id = \"hide\" type = \"button\" value = \"Hide\" /> \n <input id = \"show\" type = \"button\" value = \"Show\" />\n </body>\n</html>" }, { "code": null, "e": 75229, "s": 75192, "text": "This will produce following result −" }, { "code": null, "e": 75408, "s": 75229, "text": "jQuery provides methods to toggle the display state of elements between revealed or hidden. If the element is initially displayed, it will be hidden; if hidden, it will be shown." }, { "code": null, "e": 75468, "s": 75408, "text": "Here is the simple syntax for one of the toggle() methods −" }, { "code": null, "e": 75510, "s": 75468, "text": "[selector]..toggle([speed][, callback]);\n" }, { "code": null, "e": 75558, "s": 75510, "text": "Here is the description of all the parameters −" }, { "code": null, "e": 75717, "s": 75558, "text": "speed − A string representing one of the three predefined speeds (\"slow\", \"normal\", or \"fast\") or the number of milliseconds to run the animation (e.g. 1000)." }, { "code": null, "e": 75876, "s": 75717, "text": "speed − A string representing one of the three predefined speeds (\"slow\", \"normal\", or \"fast\") or the number of milliseconds to run the animation (e.g. 1000)." }, { "code": null, "e": 76031, "s": 75876, "text": "callback − This optional parameter represents a function to be executed whenever the animation completes; executes once for each element animated against." }, { "code": null, "e": 76186, "s": 76031, "text": "callback − This optional parameter represents a function to be executed whenever the animation completes; executes once for each element animated against." }, { "code": null, "e": 76259, "s": 76186, "text": "We can animate any element, such as a simple <div> containing an image −" }, { "code": null, "e": 77267, "s": 76259, "text": "<html>\n <head>\n <title>The jQuery Example</title>\n <script type = \"text/javascript\" \n src = \"https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js\">\n </script>\n\t\t\n <script type = \"text/javascript\" language = \"javascript\">\n $(document).ready(function() {\n $(\".clickme\").click(function(event){\n $(\".target\").toggle('slow', function(){\n $(\".log\").text('Transition Complete');\n });\n });\n });\n </script>\n\t\t\n <style>\n .clickme{ \n margin:10px;\n padding:12px; \n border:2px solid #666; \n width:100px; \n height:50px;\n }\n </style>\n </head>\n\t\n <body>\n <div class = \"content\">\n <div class = \"clickme\">Click Me</div>\n <div class = \"target\">\n <img src = \"./images/jquery.jpg\" alt = \"jQuery\" />\n </div>\n <div class = \"log\"></div>\n </div>\n </body>\n</html>" }, { "code": null, "e": 77304, "s": 77267, "text": "This will produce following result −" }, { "code": null, "e": 77442, "s": 77304, "text": "You have seen basic concept of jQuery Effects. Following table lists down all the important methods to create different kind of effects −" }, { "code": null, "e": 77483, "s": 77442, "text": "A function for making custom animations." }, { "code": null, "e": 77589, "s": 77483, "text": "Fade in all matched elements by adjusting their opacity and firing an optional callback after completion." }, { "code": null, "e": 77733, "s": 77589, "text": "Fade out all matched elements by adjusting their opacity to 0, then setting display to \"none\" and firing an optional callback after completion." }, { "code": null, "e": 77847, "s": 77733, "text": "Fade the opacity of all matched elements to a specified opacity and firing an optional callback after completion." }, { "code": null, "e": 77908, "s": 77847, "text": "Hides each of the set of matched elements if they are shown." }, { "code": null, "e": 78011, "s": 77908, "text": "Hide all matched elements using a graceful animation and firing an optional callback after completion." }, { "code": null, "e": 78076, "s": 78011, "text": "Displays each of the set of matched elements if they are hidden." }, { "code": null, "e": 78179, "s": 78076, "text": "Show all matched elements using a graceful animation and firing an optional callback after completion." }, { "code": null, "e": 78283, "s": 78179, "text": "Reveal all matched elements by adjusting their height and firing an optional callback after completion." }, { "code": null, "e": 78405, "s": 78283, "text": "Toggle the visibility of all matched elements by adjusting their height and firing an optional callback after completion." }, { "code": null, "e": 78507, "s": 78405, "text": "Hide all matched elements by adjusting their height and firing an optional callback after completion." }, { "code": null, "e": 78581, "s": 78507, "text": "Stops all the currently running animations on all the specified elements." }, { "code": null, "e": 78636, "s": 78581, "text": "Toggle displaying each of the set of matched elements." }, { "code": null, "e": 78767, "s": 78636, "text": "Toggle displaying each of the set of matched elements using a graceful animation and firing an optional callback after completion." }, { "code": null, "e": 78896, "s": 78767, "text": "Toggle displaying each of the set of matched elements based upon the switch (true shows all elements, false hides all elements)." }, { "code": null, "e": 78929, "s": 78896, "text": "Globally disable all animations." }, { "code": null, "e": 79125, "s": 78929, "text": "To use these effects you can either download latest jQuery UI Library jquery-ui-1.11.4.custom.zip from jQuery UI Library or use Google CDN to use it in the similar way as we have done for jQuery." }, { "code": null, "e": 79235, "s": 79125, "text": "We have used Google CDN for jQuery UI using following code snippet in the HTML page so we can use jQuery UI −" }, { "code": null, "e": 79354, "s": 79235, "text": "<head>\n <script src = \"https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.3/jquery-ui.min.js\">\n </script>\n</head>" }, { "code": null, "e": 79409, "s": 79354, "text": "Blinds the element away or shows it by blinding it in." }, { "code": null, "e": 79465, "s": 79409, "text": "Bounces the element vertically or horizontally n-times." }, { "code": null, "e": 79522, "s": 79465, "text": "Clips the element on or off, vertically or horizontally." }, { "code": null, "e": 79576, "s": 79522, "text": "Drops the element away or shows it by dropping it in." }, { "code": null, "e": 79619, "s": 79576, "text": "Explodes the element into multiple pieces." }, { "code": null, "e": 79660, "s": 79619, "text": "Folds the element like a piece of paper." }, { "code": null, "e": 79708, "s": 79660, "text": "Highlights the background with a defined color." }, { "code": null, "e": 79762, "s": 79708, "text": "Scale and fade out animations create the puff effect." }, { "code": null, "e": 79814, "s": 79762, "text": "Pulsates the opacity of the element multiple times." }, { "code": null, "e": 79864, "s": 79814, "text": "Shrink or grow an element by a percentage factor." }, { "code": null, "e": 79919, "s": 79864, "text": "Shakes the element vertically or horizontally n-times." }, { "code": null, "e": 79970, "s": 79919, "text": "Resize an element to a specified width and height." }, { "code": null, "e": 80010, "s": 79970, "text": "Slides the element out of the viewport." }, { "code": null, "e": 80058, "s": 80010, "text": "Transfers the outline of an element to another." }, { "code": null, "e": 80318, "s": 80058, "text": "Interactions could be added basic mouse-based behaviours to any element. Using with interactions, We can create sortable lists, resizeable elements, drag & drop behaviours.Interactions also make great building blocks for more complex widgets and applications." }, { "code": null, "e": 80369, "s": 80318, "text": "Enable drag able functionality on any DOM element." }, { "code": null, "e": 80409, "s": 80369, "text": "Enable any DOM element to be drop able." }, { "code": null, "e": 80451, "s": 80409, "text": "Enable any DOM element to be resize-able." }, { "code": null, "e": 80513, "s": 80451, "text": "Enable a DOM element (or group of elements) to be selectable." }, { "code": null, "e": 80560, "s": 80513, "text": "Enable a group of DOM elements to be sortable." }, { "code": null, "e": 80850, "s": 80560, "text": "a jQuery UI widget is a specialized jQuery plug-in.Using plug-in, we can apply behaviours to the elements. However, plug-ins lack some built-in capabilities, such as a way to associate data with its elements, expose methods, merge options with defaults, and control the plug-in's lifetime." }, { "code": null, "e": 80920, "s": 80850, "text": "Enable to collapse the content, that is broken into logical sections." }, { "code": null, "e": 80986, "s": 80920, "text": "Enable to provides the suggestions while you type into the field." }, { "code": null, "e": 81035, "s": 80986, "text": "Button is an input of type submit and an anchor." }, { "code": null, "e": 81093, "s": 81035, "text": "It is to open an interactive calendar in a small overlay." }, { "code": null, "e": 81174, "s": 81093, "text": "Dialog boxes are one of the nice ways of presenting information on an HTML page." }, { "code": null, "e": 81200, "s": 81174, "text": "Menu shows list of items." }, { "code": null, "e": 81235, "s": 81200, "text": "It shows the progress information." }, { "code": null, "e": 81280, "s": 81235, "text": "Enable a style able select element/elements." }, { "code": null, "e": 81396, "s": 81280, "text": "The basic slider is horizontal and has a single handle that can be moved with the mouse or by using the arrow keys." }, { "code": null, "e": 81452, "s": 81396, "text": "It provides a quick way to select one value from a set." }, { "code": null, "e": 81525, "s": 81452, "text": "It is used to swap between content that is broken into logical sections." }, { "code": null, "e": 81562, "s": 81525, "text": "Its provides the tips for the users." }, { "code": null, "e": 81686, "s": 81562, "text": "Jquery has two different styling themes as A And B.Each with different colors for buttons, bars, content blocks, and so on." }, { "code": null, "e": 81733, "s": 81686, "text": "The syntax of J query theming as shown below −" }, { "code": null, "e": 81778, "s": 81733, "text": "<div data-role = \"page\" data-theme = \"a|b\">\n" }, { "code": null, "e": 81825, "s": 81778, "text": "A Simple of A theming Example as shown below −" }, { "code": null, "e": 83533, "s": 81825, "text": "<!DOCTYPE html>\n<html>\n <head>\n <meta name = \"viewport\" content = \"width = device-width, initial-scale = 1\">\n <link rel = \"stylesheet\" \n href = \"https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css\">\n\t\t\t\n <script src = \"https://code.jquery.com/jquery-1.11.3.min.js\">\n </script>\n <script src = \"https://code.jquery.com/jquery-1.11.3.min.js\">\n </script>\n <script \n src = \"https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js\">\n </script>\n </head>\n\t\n <body>\n <div data-role = \"page\" id = \"pageone\" data-theme = \"a\">\n <div data-role = \"header\">\n <h1>Tutorials Point</h1>\n </div>\n\n <div data-role = \"main\" class = \"ui-content\">\n\t\t\t\n <p>Text link</p>\n <a href = \"#\">A Standard Text Link</a>\n <a href = \"#\" class = \"ui-btn\">Link Button</a>\n <p>A List View:</p>\n\t\t\t\t\n <ul data-role = \"listview\" data-autodividers = \"true\" data-inset = \"true\">\n <li><a href = \"#\">Android </a></li>\n <li><a href = \"#\">IOS</a></li>\n </ul>\n\t\t\t\t\n <label for = \"fullname\">Input Field:</label>\n <input type = \"text\" name = \"fullname\" id = \"fullname\" \n placeholder = \"Name..\"> \n <label for = \"switch\">Toggle Switch:</label>\n\t\t\t\t\n <select name = \"switch\" id = \"switch\" data-role = \"slider\">\n <option value = \"on\">On</option>\n <option value = \"off\" selected>Off</option>\n </select>\n\t\t\t\t\n </div>\n\n <div data-role = \"footer\">\n <h1>Tutorials point</h1>\n </div>\n </div>\n </body>\n</html>" }, { "code": null, "e": 83572, "s": 83533, "text": "This should produce following result −" }, { "code": null, "e": 83582, "s": 83572, "text": "Text link" }, { "code": null, "e": 83596, "s": 83582, "text": "A List View −" }, { "code": null, "e": 83598, "s": 83596, "text": "A" }, { "code": null, "e": 83607, "s": 83598, "text": "Android " }, { "code": null, "e": 83609, "s": 83607, "text": "I" }, { "code": null, "e": 83613, "s": 83609, "text": "IOS" }, { "code": null, "e": 83660, "s": 83613, "text": "A Simple of B theming Example as shown below −" }, { "code": null, "e": 85360, "s": 83660, "text": "<!DOCTYPE html>\n<html>\n <head>\n <meta name = \"viewport\" content = \"width = device-width, initial-scale = 1\">\n <link rel = \"stylesheet\" \n href = \"https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css\">\n <script src = \"https://code.jquery.com/jquery-1.11.3.min.js\">\n </script>\n <script src = \"https://code.jquery.com/jquery-1.11.3.min.js\">\n </script>\n <script \n src = \"https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js\">\n </script>\n </head>\n\t\n <body>\n <div data-role = \"page\" id = \"pageone\" data-theme = \"b\">\n <div data-role = \"header\">\n <h1>Tutorials Point</h1>\n </div>\n\n <div data-role = \"main\" class = \"ui-content\">\n <p>Text link</p>\n <a href = \"#\">A Standard Text Link</a>\n <a href = \"#\" class = \"ui-btn\">Link Button</a>\n <p>A List View:</p>\n\t\t\t\t\n <ul data-role = \"listview\" data-autodividers = \"true\" data-inset = \"true\">\n <li><a href = \"#\">Android </a></li>\n <li><a href = \"#\">IOS</a></li>\n </ul>\n\t\t\t\t\n <label for = \"fullname\">Input Field:</label>\n <input type = \"text\" name = \"fullname\" id = \"fullname\" \n placeholder = \"Name..\"> \n <label for = \"switch\">Toggle Switch:</label>\n\t\t\t\t\n <select name = \"switch\" id = \"switch\" data-role = \"slider\">\n <option value = \"on\">On</option>\n <option value = \"off\" selected>Off</option>\n </select>\n\t\t\t\t\n </div>\n\n <div data-role = \"footer\">\n <h1>Tutorials point</h1>\n </div>\n </div>\n </body>\n</html>" }, { "code": null, "e": 85399, "s": 85360, "text": "This should produce following result −" }, { "code": null, "e": 85409, "s": 85399, "text": "Text link" }, { "code": null, "e": 85423, "s": 85409, "text": "A List View −" }, { "code": null, "e": 85425, "s": 85423, "text": "A" }, { "code": null, "e": 85434, "s": 85425, "text": "Android " }, { "code": null, "e": 85436, "s": 85434, "text": "I" }, { "code": null, "e": 85440, "s": 85436, "text": "IOS" }, { "code": null, "e": 85616, "s": 85440, "text": "Jquery provides serveral utilities in the formate of $(name space). These methods are helpful to complete the programming tasks.a few of the utility methods are as show below." }, { "code": null, "e": 85676, "s": 85616, "text": "$.trim() is used to Removes leading and trailing whitespace" }, { "code": null, "e": 85723, "s": 85676, "text": "$.trim( \" lots of extra whitespace \" );\n" }, { "code": null, "e": 85777, "s": 85723, "text": "$.each() is used to Iterates over arrays and objects" }, { "code": null, "e": 85980, "s": 85777, "text": "$.each([ \"foo\", \"bar\", \"baz\" ], function( idx, val ) {\n console.log( \"element \" + idx + \" is \" + val );\n});\n \n$.each({ foo: \"bar\", baz: \"bim\" }, function( k, v ) {\n console.log( k + \" : \" + v );\n});" }, { "code": null, "e": 86156, "s": 85980, "text": ".each() can be called on a selection to iterate over the elements contained in the selection. .each(), not $.each(), should be used for iterating over elements in a selection." }, { "code": null, "e": 86256, "s": 86156, "text": "$.inArray() is used to Returns a value's index in an array, or -1 if the value is not in the array." }, { "code": null, "e": 86361, "s": 86256, "text": "var myArray = [ 1, 2, 3, 5 ];\n \nif ( $.inArray( 4, myArray ) !== -1 ) {\n console.log( \"found it!\" );\n}" }, { "code": null, "e": 86470, "s": 86361, "text": "$.extend() is used to Changes the properties of the first object using the properties of subsequent objects." }, { "code": null, "e": 86670, "s": 86470, "text": "var firstObject = { foo: \"bar\", a: \"b\" };\nvar secondObject = { foo: \"baz\" };\n \nvar newObject = $.extend( firstObject, secondObject );\n \nconsole.log( firstObject.foo ); \nconsole.log( newObject.foo );\n" }, { "code": null, "e": 86839, "s": 86670, "text": "$.proxy() is used to Returns a function that will always run in the provided scope — that is, sets the meaning of this inside the passed function to the second argument" }, { "code": null, "e": 87035, "s": 86839, "text": "var myFunction = function() {\n console.log( this );\n};\n\nvar myObject = {\n foo: \"bar\"\n};\n \nmyFunction(); // window\n \nvar myProxyFunction = $.proxy( myFunction, myObject );\n \nmyProxyFunction();" }, { "code": null, "e": 87092, "s": 87035, "text": "$.browser is used to give the information about browsers" }, { "code": null, "e": 87229, "s": 87092, "text": "jQuery.each( jQuery.browser, function( i, val ) {\n $( \"<div>\" + i + \" : <span>\" + val + \"</span>\" )\n .appendTo( document.body );\n});" }, { "code": null, "e": 87436, "s": 87229, "text": "$.contains() is used to returns true if the DOM element provided by the second argument is a descendant of the DOM element provided by the first argument, whether it is a direct child or nested more deeply." }, { "code": null, "e": 87547, "s": 87436, "text": "$.contains( document.documentElement, document.body );\n$.contains( document.body, document.documentElement );\n" }, { "code": null, "e": 87599, "s": 87547, "text": "$.data() is used to give the information about data" }, { "code": null, "e": 88205, "s": 87599, "text": "<html lang = \"en\">\n <head>\n <title>jQuery.data demo</title>\n <script src = \"https://code.jquery.com/jquery-1.10.2.js\">\n </script>\n </head>\n\t\n <body>\n <div>\n The values stored were <span></span>\n and <span></span>\n </div>\n \n <script>\n var div = $( \"div\" )[ 0 ];\n\t\t\t\n jQuery.data( div, \"test\", {\n first: 25,\n last: \"tutorials\"\n });\n\t\t\t\n $( \"span:first\" ).text( jQuery.data( div, \"test\" ).first );\n $( \"span:last\" ).text( jQuery.data( div, \"test\" ).last );\n </script>\n </body>\n</html>" }, { "code": null, "e": 88236, "s": 88205, "text": "An output would be as follows " }, { "code": null, "e": 88277, "s": 88236, "text": "The values stored were 25 and tutorials\n" }, { "code": null, "e": 88331, "s": 88277, "text": "$.fn.extend() is used to extends the jQuery prototype" }, { "code": null, "e": 89114, "s": 88331, "text": "<html lang = \"en\">\n <head>\n <script src = \"https://code.jquery.com/jquery-1.10.2.js\">\n </script>\n </head>\n\t\n <body>\n <label><input type = \"checkbox\" name = \"android\"> \n Android</label>\n <label><input type = \"checkbox\" name = \"ios\"> IOS</label>\n \n <script>\n jQuery.fn.extend({\n\t\t\t\n check: function() {\n return this.each(function() {\n this.checked = true;\n });\n },\n uncheck: function() {\n return this.each(function() {\n this.checked = false;\n });\n }\n });\n \n // Use the newly created .check() method\n $( \"input[type = 'checkbox']\" ).check();\n\t\t\t\n </script>\n </body>\n</html>" }, { "code": null, "e": 89154, "s": 89114, "text": "It provides the output as shown below −" }, { "code": null, "e": 89199, "s": 89154, "text": "$.isWindow() is used to recognise the window" }, { "code": null, "e": 89563, "s": 89199, "text": "<!doctype html>\n<html lang = \"en\">\n <head>\n <meta charset = \"utf-8\">\n <title>jQuery.isWindow demo</title>\n <script src = \"https://code.jquery.com/jquery-1.10.2.js\">\n </script>\n </head>\n\t\n <body>\n Is 'window' a window? <b></b>\n \n <script>\n $( \"b\" ).append( \"\" + $.isWindow( window ) );\n </script>\n </body>\n</html>" }, { "code": null, "e": 89603, "s": 89563, "text": "It provides the output as shown below −" }, { "code": null, "e": 89662, "s": 89603, "text": "It returns a number which is representing the current time" }, { "code": null, "e": 89684, "s": 89662, "text": "(new Date).getTime()\n" }, { "code": null, "e": 89736, "s": 89684, "text": "$.isXMLDoc() checks whether a file is an xml or not" }, { "code": null, "e": 89798, "s": 89736, "text": "jQuery.isXMLDoc( document )\njQuery.isXMLDoc( document.body )\n" }, { "code": null, "e": 89856, "s": 89798, "text": "$.globalEval() is used to execute the javascript globally" }, { "code": null, "e": 89929, "s": 89856, "text": "function test() {\n jQuery.globalEval( \"var newVar = true;\" )\n}\ntest();" }, { "code": null, "e": 89991, "s": 89929, "text": "$.dequeue() is used to execute the next function in the queue" }, { "code": null, "e": 91021, "s": 89991, "text": "<!doctype html>\n<html lang = \"en\">\n <head>\n <meta charset = \"utf-8\">\n <title>jQuery.dequeue demo</title>\n\t\t\n <style>\n div {\n margin: 3px;\n width: 50px;\n position: absolute;\n height: 50px;\n left: 10px;\n top: 30px;\n background-color: green;\n border-radius: 50px;\n }\n div.red {\n background-color: blue;\n }\n </style>\n\t\t\n <script src = \"https://code.jquery.com/jquery-1.10.2.js\"></script>\n </head>\n\n <body>\n <button>Start</button>\n <div></div>\n \n <script>\n $( \"button\" ).click(function() {\n $( \"div\" )\n .animate({ left: '+ = 400px' }, 2000 )\n .animate({ top: '0px' }, 600 )\n\t\t\t\t\n .queue(function() {\n $( this ).toggleClass( \"red\" );\n $.dequeue( this );\n })\n\t\t\t\t\n .animate({ left:'10px', top:'30px' }, 700 );\n });\n </script>\n </body>\n</html>" }, { "code": null, "e": 91061, "s": 91021, "text": "It provides the output as shown below −" }, { "code": null, "e": 91094, "s": 91061, "text": "\n 27 Lectures \n 1 hours \n" }, { "code": null, "e": 91108, "s": 91094, "text": " Mahesh Kumar" }, { "code": null, "e": 91143, "s": 91108, "text": "\n 27 Lectures \n 1.5 hours \n" }, { "code": null, "e": 91157, "s": 91143, "text": " Pratik Singh" }, { "code": null, "e": 91192, "s": 91157, "text": "\n 72 Lectures \n 4.5 hours \n" }, { "code": null, "e": 91209, "s": 91192, "text": " Frahaan Hussain" }, { "code": null, "e": 91242, "s": 91209, "text": "\n 60 Lectures \n 9 hours \n" }, { "code": null, "e": 91270, "s": 91242, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 91303, "s": 91270, "text": "\n 17 Lectures \n 2 hours \n" }, { "code": null, "e": 91324, "s": 91303, "text": " Sandip Bhattacharya" }, { "code": null, "e": 91356, "s": 91324, "text": "\n 12 Lectures \n 53 mins\n" }, { "code": null, "e": 91373, "s": 91356, "text": " Laurence Svekis" }, { "code": null, "e": 91380, "s": 91373, "text": " Print" }, { "code": null, "e": 91391, "s": 91380, "text": " Add Notes" } ]
An Introduction to GPU Optimization | by Anuradha Wickramarachchi | Towards Data Science
Most of the tasks that involve heavy computations take time and it becomes further time consuming as the datasets get bigger and bigger. One way of addressing this problem is using threads. In this article, I will be introducing GPU acceleration, how it is done and a simple API for GPU tasks along with a code. To start with, let us consider the example of a matrix multiplication. In the above scenario, there are 2 matrices one of size 3 x 6 and another of size 6 x 6. The resulting matrix will be of size 3 x 6. Therefore, for each cell of the matrix there will be 6 calculations. In total, there will be 3 x 6 x 6 many multiplications. Hence, we can conclude that the task takes O(mn2) amount of time for the calculation. This implies that, for a matrix of size 2000 x 2000 there will be 8,000,000,000 calculations done. This is a LOOOOT of CPU time!!!. Usually GPUs contain a large number of processing cores. Generally varying from 384 up to several thousands. Below is a simple comparison of some of the latest graphics cards of nvidia. (Source) CUDA stands for Compute Unified Device Architecture. These are running at relatively low speeds but provides greater parallelism by employing a large number of ALUs (Arithmetic and Logical Units). Read more here. This diagram demonstrates the threading model in CUDA (this is quite the same as other architectures in the market such as AMD). To make it simple to start with, we may assume that each CUDA core or a GPU core can run a thread at a time. If we have a large data set, we can break it into pieces. A Grid contains several Blocks, and Block is another matrix which contains a number of threads equal to the size of it. Anyhow, as this is the introduction let’s focus on the bigger picture with a simpler API developed using JAVA. As we have discussed, each GPU core is capable of running a separate thread. The simplest way to start the analogy is assuming that each cell of the matrix will be calculated by a single GPU core. And since all the cores are running in parallel, all the cells will be computed in parallel. Therefore, our time complexity suddenly drops to O(n). Now, for the 2000 x 2000 matrix we just need 2,000 runs, which is quite easy for a computer to compute. Usually each the threads we discussed before, knows its identity, which is the Block and the Grid it belongs to. Or in more simpler words the cell location of the matrix. Also, the matrix will be loaded into the shared memory of the GPU where we can directly access cell data by indices and process in parallel. Easy right? Let’s check on the code. What? Well, APARAPI (A-PARallel-API) is a JAVA wrapper for OpenCL which is the Open Computing Language used for programming GPUs. This supports both CUDA architecture and AMD devices. Also, the API bring in the greater object orientation of JAVA into the picture, which might look like a mess if we directly jump in to the task with C++. Getting started is quite easy. There is a maven dependency. But make sure you have correctly setup OpenCL or CUDA. Simple googling should help you with how. Most of the devices come with them bundled in (OSX and Windows devices). Kernel is the part of the code that is being executed with the GPU. The variables that are visible to the Kernel will be copied to the GPU RAM. We are feeding data in terms of linear arrays rather than 2D arrays as this is the way supported by the GPUs. Not that they are not capable of handling 2D arrays, but the way they are handled is through the concept of dimensions (We won’t talk it just yet). Range range = Range.create(SIZE * SIZE); The above code allocates memory in the GPU so that SIZE x SIZE amount of threads or less (As available) running in the GPU. int row = getGlobalId() / SIZE;int col = getGlobalId() % SIZE; The above code obtains the Id of the thread from its private memory. With this for that particular thread, we can identify the thread’s cell location. For each cell we would do the following. for (int i = 0; i < SIZE; i++) { d[row * SIZE + col] += a[row * SIZE + i] * b[i * SIZE + col];} This is the simple sum of multiples of the corresponding cells of the two matrices. We just define the Kernel for a single thread using thread indices, which will be run in parallel for all the threads. It is fast. But how fast?. This is the output of the above program. 1200 x 1200 Starting single threaded computationTask finished in 25269ms Starting GPU computationTask finished in 1535ms Following was run only for the GPU component since times were quite large for CPU to compute. 2000 x 2000 Task finished in 3757ms5000 x 5000 Task finished in 5402ms Hope you enjoyed reading. Please do try!! Cheers!!
[ { "code": null, "e": 555, "s": 172, "text": "Most of the tasks that involve heavy computations take time and it becomes further time consuming as the datasets get bigger and bigger. One way of addressing this problem is using threads. In this article, I will be introducing GPU acceleration, how it is done and a simple API for GPU tasks along with a code. To start with, let us consider the example of a matrix multiplication." }, { "code": null, "e": 1031, "s": 555, "text": "In the above scenario, there are 2 matrices one of size 3 x 6 and another of size 6 x 6. The resulting matrix will be of size 3 x 6. Therefore, for each cell of the matrix there will be 6 calculations. In total, there will be 3 x 6 x 6 many multiplications. Hence, we can conclude that the task takes O(mn2) amount of time for the calculation. This implies that, for a matrix of size 2000 x 2000 there will be 8,000,000,000 calculations done. This is a LOOOOT of CPU time!!!." }, { "code": null, "e": 1226, "s": 1031, "text": "Usually GPUs contain a large number of processing cores. Generally varying from 384 up to several thousands. Below is a simple comparison of some of the latest graphics cards of nvidia. (Source)" }, { "code": null, "e": 1439, "s": 1226, "text": "CUDA stands for Compute Unified Device Architecture. These are running at relatively low speeds but provides greater parallelism by employing a large number of ALUs (Arithmetic and Logical Units). Read more here." }, { "code": null, "e": 1966, "s": 1439, "text": "This diagram demonstrates the threading model in CUDA (this is quite the same as other architectures in the market such as AMD). To make it simple to start with, we may assume that each CUDA core or a GPU core can run a thread at a time. If we have a large data set, we can break it into pieces. A Grid contains several Blocks, and Block is another matrix which contains a number of threads equal to the size of it. Anyhow, as this is the introduction let’s focus on the bigger picture with a simpler API developed using JAVA." }, { "code": null, "e": 2764, "s": 1966, "text": "As we have discussed, each GPU core is capable of running a separate thread. The simplest way to start the analogy is assuming that each cell of the matrix will be calculated by a single GPU core. And since all the cores are running in parallel, all the cells will be computed in parallel. Therefore, our time complexity suddenly drops to O(n). Now, for the 2000 x 2000 matrix we just need 2,000 runs, which is quite easy for a computer to compute. Usually each the threads we discussed before, knows its identity, which is the Block and the Grid it belongs to. Or in more simpler words the cell location of the matrix. Also, the matrix will be loaded into the shared memory of the GPU where we can directly access cell data by indices and process in parallel. Easy right? Let’s check on the code." }, { "code": null, "e": 3332, "s": 2764, "text": "What? Well, APARAPI (A-PARallel-API) is a JAVA wrapper for OpenCL which is the Open Computing Language used for programming GPUs. This supports both CUDA architecture and AMD devices. Also, the API bring in the greater object orientation of JAVA into the picture, which might look like a mess if we directly jump in to the task with C++. Getting started is quite easy. There is a maven dependency. But make sure you have correctly setup OpenCL or CUDA. Simple googling should help you with how. Most of the devices come with them bundled in (OSX and Windows devices)." }, { "code": null, "e": 3734, "s": 3332, "text": "Kernel is the part of the code that is being executed with the GPU. The variables that are visible to the Kernel will be copied to the GPU RAM. We are feeding data in terms of linear arrays rather than 2D arrays as this is the way supported by the GPUs. Not that they are not capable of handling 2D arrays, but the way they are handled is through the concept of dimensions (We won’t talk it just yet)." }, { "code": null, "e": 3775, "s": 3734, "text": "Range range = Range.create(SIZE * SIZE);" }, { "code": null, "e": 3899, "s": 3775, "text": "The above code allocates memory in the GPU so that SIZE x SIZE amount of threads or less (As available) running in the GPU." }, { "code": null, "e": 3962, "s": 3899, "text": "int row = getGlobalId() / SIZE;int col = getGlobalId() % SIZE;" }, { "code": null, "e": 4154, "s": 3962, "text": "The above code obtains the Id of the thread from its private memory. With this for that particular thread, we can identify the thread’s cell location. For each cell we would do the following." }, { "code": null, "e": 4253, "s": 4154, "text": "for (int i = 0; i < SIZE; i++) { d[row * SIZE + col] += a[row * SIZE + i] * b[i * SIZE + col];}" }, { "code": null, "e": 4456, "s": 4253, "text": "This is the simple sum of multiples of the corresponding cells of the two matrices. We just define the Kernel for a single thread using thread indices, which will be run in parallel for all the threads." }, { "code": null, "e": 4524, "s": 4456, "text": "It is fast. But how fast?. This is the output of the above program." }, { "code": null, "e": 4536, "s": 4524, "text": "1200 x 1200" }, { "code": null, "e": 4645, "s": 4536, "text": "Starting single threaded computationTask finished in 25269ms Starting GPU computationTask finished in 1535ms" }, { "code": null, "e": 4739, "s": 4645, "text": "Following was run only for the GPU component since times were quite large for CPU to compute." }, { "code": null, "e": 4810, "s": 4739, "text": "2000 x 2000 Task finished in 3757ms5000 x 5000 Task finished in 5402ms" } ]
Set JavaScript object values to null?
In order to set object values to null, you need to get all the keys from the object and need to set null. You can use for loop or forEach() loop. Following is the JavaScript code with name records. We will set the object value to null − const object=[ { FirstName:"John" }, { FirstName:"David" }, { FirstName:"Bob" } ] Object.keys(object).forEach(key => object[key]=null); console.log(object); To run the above program, you need to use the following command − node fileName.js. Here, my file name is demo31.js. This will produce the following output − PS C:\Users\Amit\JavaScript-code> node demo31.js [ null, null, null ] Above, all the values are now set to NULL.
[ { "code": null, "e": 1208, "s": 1062, "text": "In order to set object values to null, you need to get all the keys from the object and need to set\nnull. You can use for loop or forEach() loop." }, { "code": null, "e": 1299, "s": 1208, "text": "Following is the JavaScript code with name records. We will set the object value to null −" }, { "code": null, "e": 1492, "s": 1299, "text": "const object=[\n {\n FirstName:\"John\"\n },\n {\n FirstName:\"David\"\n },\n {\n FirstName:\"Bob\"\n }\n]\nObject.keys(object).forEach(key => object[key]=null);\nconsole.log(object);" }, { "code": null, "e": 1558, "s": 1492, "text": "To run the above program, you need to use the following command −" }, { "code": null, "e": 1576, "s": 1558, "text": "node fileName.js." }, { "code": null, "e": 1609, "s": 1576, "text": "Here, my file name is demo31.js." }, { "code": null, "e": 1650, "s": 1609, "text": "This will produce the following output −" }, { "code": null, "e": 1720, "s": 1650, "text": "PS C:\\Users\\Amit\\JavaScript-code> node demo31.js\n[ null, null, null ]" }, { "code": null, "e": 1763, "s": 1720, "text": "Above, all the values are now set to NULL." } ]
How to remove decimal in MATLAB? - GeeksforGeeks
29 Jul, 2021 In this article, we are going to discuss the “Removal of decimal point” in MATLAB which can be done using sprintf(), fix(), floor(), round() and num2str() functions which are illustrated below. The sprintf() function is used to write formatted data to a string. Syntax: sprintf(format, A) Here, sprintf(format, A) is used to format the data in A over the specified format string. Example: Matlab % MATLAB code for removal of % decimal points using sprintf()% Initializing some valuesA = 3.000;B = 1.420;C = 0.023; % Calling the sprintf() function over% the above valuessprintf('%.f', A)sprintf('%.f', B)sprintf('%.f', C) Output: ans = 3 ans = 1 ans = 0 The fix() function is used to round the specified values towards zero. Syntax: fix(A) Here, fix(A) is used to round the specified elements of A toward zero which results in an array of integers. Example: Matlab % MATLAB code for removal% of decimal points with fix()% Initializing some valuesA = 3.000;B = 1.420;C = 0.023; % Calling the fix() function over% the above valuesfix(A)fix(B)fix(C) Output: ans = 3 ans = 1 ans = 0 The floor() function is used to round the specified values towards minus infinity. Syntax: floor(A) Here, floor(A) function is used to round the specified elements of A to the nearest integers less than or equal to A. Example: Matlab % MATLAB code for removal of % decimal points using floor()% Initializing some valuesA = 2.000;B = 1.790;C = 0.9093; % Calling the floor() function over% the above valuesfloor(A)floor(B)floor(C) Output: ans = 2 ans = 1 ans = 0 The round() function is used to round the specified values to their nearest integer. Syntax: round(X) Here, round(X) function is used to round the specified elements of X to their nearest integers. Example1: Matlab % MATLAB code for removal of% decimal points using round()% Initializing some valuesA = 2.300;B = 1.790;C = 0.9093;D = 0.093; % Calling the round() function over% the above valuesround(A)round(B)round(C)round(D) Output: ans = 2 ans = 2 ans = 1 ans = 0 Now we see how to remove decimal places without rounding. For this, we can use num2str, which converts numbers to a character array. The num2str() function is used to convert the specified numbers to a character array. Syntax: num2str(num) Parameters: This function accepts a parameter. num: This is the specified number. Example: Matlab % MATLAB code for removal of% decimal points without rounding% Initializing some values num2str(3.1455567, '%.0f') Output: ans = 3 MATLAB-Maths MATLAB-programs MATLAB Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Remove Noise from Digital Image in Frequency Domain Using MATLAB? Boundary Extraction of image using MATLAB Laplacian of Gaussian Filter in MATLAB Forward and Inverse Fourier Transform of an Image in MATLAB How to Solve Histogram Equalization Numerical Problem in MATLAB? MRI Image Segmentation in MATLAB How to Remove Salt and Pepper Noise from Image Using MATLAB? Adaptive Histogram Equalization in Image Processing Using MATLAB How to Normalize a Histogram in MATLAB? How to Convert Three Channels of Colored Image into Grayscale Image in MATLAB?
[ { "code": null, "e": 24646, "s": 24618, "text": "\n29 Jul, 2021" }, { "code": null, "e": 24840, "s": 24646, "text": "In this article, we are going to discuss the “Removal of decimal point” in MATLAB which can be done using sprintf(), fix(), floor(), round() and num2str() functions which are illustrated below." }, { "code": null, "e": 24908, "s": 24840, "text": "The sprintf() function is used to write formatted data to a string." }, { "code": null, "e": 24916, "s": 24908, "text": "Syntax:" }, { "code": null, "e": 24935, "s": 24916, "text": "sprintf(format, A)" }, { "code": null, "e": 25026, "s": 24935, "text": "Here, sprintf(format, A) is used to format the data in A over the specified format string." }, { "code": null, "e": 25035, "s": 25026, "text": "Example:" }, { "code": null, "e": 25042, "s": 25035, "text": "Matlab" }, { "code": "% MATLAB code for removal of % decimal points using sprintf()% Initializing some valuesA = 3.000;B = 1.420;C = 0.023; % Calling the sprintf() function over% the above valuessprintf('%.f', A)sprintf('%.f', B)sprintf('%.f', C)", "e": 25268, "s": 25042, "text": null }, { "code": null, "e": 25276, "s": 25268, "text": "Output:" }, { "code": null, "e": 25300, "s": 25276, "text": "ans = 3\nans = 1\nans = 0" }, { "code": null, "e": 25371, "s": 25300, "text": "The fix() function is used to round the specified values towards zero." }, { "code": null, "e": 25379, "s": 25371, "text": "Syntax:" }, { "code": null, "e": 25386, "s": 25379, "text": "fix(A)" }, { "code": null, "e": 25495, "s": 25386, "text": "Here, fix(A) is used to round the specified elements of A toward zero which results in an array of integers." }, { "code": null, "e": 25504, "s": 25495, "text": "Example:" }, { "code": null, "e": 25511, "s": 25504, "text": "Matlab" }, { "code": "% MATLAB code for removal% of decimal points with fix()% Initializing some valuesA = 3.000;B = 1.420;C = 0.023; % Calling the fix() function over% the above valuesfix(A)fix(B)fix(C)", "e": 25694, "s": 25511, "text": null }, { "code": null, "e": 25702, "s": 25694, "text": "Output:" }, { "code": null, "e": 25728, "s": 25702, "text": "ans = 3\nans = 1\nans = 0" }, { "code": null, "e": 25811, "s": 25728, "text": "The floor() function is used to round the specified values towards minus infinity." }, { "code": null, "e": 25819, "s": 25811, "text": "Syntax:" }, { "code": null, "e": 25828, "s": 25819, "text": "floor(A)" }, { "code": null, "e": 25946, "s": 25828, "text": "Here, floor(A) function is used to round the specified elements of A to the nearest integers less than or equal to A." }, { "code": null, "e": 25955, "s": 25946, "text": "Example:" }, { "code": null, "e": 25962, "s": 25955, "text": "Matlab" }, { "code": "% MATLAB code for removal of % decimal points using floor()% Initializing some valuesA = 2.000;B = 1.790;C = 0.9093; % Calling the floor() function over% the above valuesfloor(A)floor(B)floor(C)", "e": 26158, "s": 25962, "text": null }, { "code": null, "e": 26166, "s": 26158, "text": "Output:" }, { "code": null, "e": 26192, "s": 26166, "text": "ans = 2\nans = 1\nans = 0" }, { "code": null, "e": 26277, "s": 26192, "text": "The round() function is used to round the specified values to their nearest integer." }, { "code": null, "e": 26285, "s": 26277, "text": "Syntax:" }, { "code": null, "e": 26294, "s": 26285, "text": "round(X)" }, { "code": null, "e": 26390, "s": 26294, "text": "Here, round(X) function is used to round the specified elements of X to their nearest integers." }, { "code": null, "e": 26400, "s": 26390, "text": "Example1:" }, { "code": null, "e": 26407, "s": 26400, "text": "Matlab" }, { "code": "% MATLAB code for removal of% decimal points using round()% Initializing some valuesA = 2.300;B = 1.790;C = 0.9093;D = 0.093; % Calling the round() function over% the above valuesround(A)round(B)round(C)round(D)", "e": 26621, "s": 26407, "text": null }, { "code": null, "e": 26629, "s": 26621, "text": "Output:" }, { "code": null, "e": 26664, "s": 26629, "text": "ans = 2\nans = 2\nans = 1\nans = 0" }, { "code": null, "e": 26797, "s": 26664, "text": "Now we see how to remove decimal places without rounding. For this, we can use num2str, which converts numbers to a character array." }, { "code": null, "e": 26883, "s": 26797, "text": "The num2str() function is used to convert the specified numbers to a character array." }, { "code": null, "e": 26904, "s": 26883, "text": "Syntax: num2str(num)" }, { "code": null, "e": 26951, "s": 26904, "text": "Parameters: This function accepts a parameter." }, { "code": null, "e": 26986, "s": 26951, "text": "num: This is the specified number." }, { "code": null, "e": 26995, "s": 26986, "text": "Example:" }, { "code": null, "e": 27002, "s": 26995, "text": "Matlab" }, { "code": "% MATLAB code for removal of% decimal points without rounding% Initializing some values num2str(3.1455567, '%.0f')", "e": 27119, "s": 27002, "text": null }, { "code": null, "e": 27127, "s": 27119, "text": "Output:" }, { "code": null, "e": 27135, "s": 27127, "text": "ans = 3" }, { "code": null, "e": 27148, "s": 27135, "text": "MATLAB-Maths" }, { "code": null, "e": 27164, "s": 27148, "text": "MATLAB-programs" }, { "code": null, "e": 27171, "s": 27164, "text": "MATLAB" }, { "code": null, "e": 27269, "s": 27171, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27342, "s": 27269, "text": "How to Remove Noise from Digital Image in Frequency Domain Using MATLAB?" }, { "code": null, "e": 27384, "s": 27342, "text": "Boundary Extraction of image using MATLAB" }, { "code": null, "e": 27423, "s": 27384, "text": "Laplacian of Gaussian Filter in MATLAB" }, { "code": null, "e": 27483, "s": 27423, "text": "Forward and Inverse Fourier Transform of an Image in MATLAB" }, { "code": null, "e": 27548, "s": 27483, "text": "How to Solve Histogram Equalization Numerical Problem in MATLAB?" }, { "code": null, "e": 27581, "s": 27548, "text": "MRI Image Segmentation in MATLAB" }, { "code": null, "e": 27642, "s": 27581, "text": "How to Remove Salt and Pepper Noise from Image Using MATLAB?" }, { "code": null, "e": 27707, "s": 27642, "text": "Adaptive Histogram Equalization in Image Processing Using MATLAB" }, { "code": null, "e": 27747, "s": 27707, "text": "How to Normalize a Histogram in MATLAB?" } ]
Normal Forms in DBMS - GeeksforGeeks
12 Nov, 2021 Prerequisite – Database normalization and functional dependency concept. Normalization is the process of minimizing redundancy from a relation or set of relations. Redundancy in relation may cause insertion, deletion, and update anomalies. So, it helps to minimize the redundancy in relations. Normal forms are used to eliminate or reduce redundancy in database tables. If a relation contain composite or multi-valued attribute, it violates first normal form or a relation is in first normal form if it does not contain any composite or multi-valued attribute. A relation is in first normal form if every attribute in that relation is singled valued attribute. Example 1 – Relation STUDENT in table 1 is not in 1NF because of multi-valued attribute STUD_PHONE. Its decomposition into 1NF has been shown in table 2. Example 2 – ID Name Courses ------------------ 1 A c1, c2 2 E c3 3 M C2, c3 In the above table Course is a multi-valued attribute so it is not in 1NF.Below Table is in 1NF as there is no multi-valued attributeID Name Course ------------------ 1 A c1 1 A c2 2 E c3 3 M c2 3 M c3 ID Name Courses ------------------ 1 A c1, c2 2 E c3 3 M C2, c3 In the above table Course is a multi-valued attribute so it is not in 1NF. Below Table is in 1NF as there is no multi-valued attribute ID Name Course ------------------ 1 A c1 1 A c2 2 E c3 3 M c2 3 M c3 To be in second normal form, a relation must be in first normal form and relation must not contain any partial dependency. A relation is in 2NF if it has No Partial Dependency, i.e., no non-prime attribute (attributes which are not part of any candidate key) is dependent on any proper subset of any candidate key of the table. Partial Dependency – If the proper subset of candidate key determines non-prime attribute, it is called partial dependency. Example 1 – Consider table-3 as following below.STUD_NO COURSE_NO COURSE_FEE 1 C1 1000 2 C2 1500 1 C4 2000 4 C3 1000 4 C1 1000 2 C5 2000 {Note that, there are many courses having the same course fee. }Here,COURSE_FEE cannot alone decide the value of COURSE_NO or STUD_NO;COURSE_FEE together with STUD_NO cannot decide the value of COURSE_NO;COURSE_FEE together with COURSE_NO cannot decide the value of STUD_NO;Hence,COURSE_FEE would be a non-prime attribute, as it does not belong to the one only candidate key {STUD_NO, COURSE_NO} ;But, COURSE_NO -> COURSE_FEE, i.e., COURSE_FEE is dependent on COURSE_NO, which is a proper subset of the candidate key. Non-prime attribute COURSE_FEE is dependent on a proper subset of the candidate key, which is a partial dependency and so this relation is not in 2NF.To convert the above relation to 2NF,we need to split the table into two tables such as :Table 1: STUD_NO, COURSE_NOTable 2: COURSE_NO, COURSE_FEE Table 1 Table 2 STUD_NO COURSE_NO COURSE_NO COURSE_FEE 1 C1 C1 1000 2 C2 C2 1500 1 C4 C3 1000 4 C3 C4 2000 4 C1 C5 2000 2 C5NOTE: 2NF tries to reduce the redundant data getting stored in memory. For instance, if there are 100 students taking C1 course, we don’t need to store its Fee as 1000 for all the 100 records, instead, once we can store it in the second table as the course fee for C1 is 1000. STUD_NO COURSE_NO COURSE_FEE 1 C1 1000 2 C2 1500 1 C4 2000 4 C3 1000 4 C1 1000 2 C5 2000 {Note that, there are many courses having the same course fee. } Here,COURSE_FEE cannot alone decide the value of COURSE_NO or STUD_NO;COURSE_FEE together with STUD_NO cannot decide the value of COURSE_NO;COURSE_FEE together with COURSE_NO cannot decide the value of STUD_NO;Hence,COURSE_FEE would be a non-prime attribute, as it does not belong to the one only candidate key {STUD_NO, COURSE_NO} ;But, COURSE_NO -> COURSE_FEE, i.e., COURSE_FEE is dependent on COURSE_NO, which is a proper subset of the candidate key. Non-prime attribute COURSE_FEE is dependent on a proper subset of the candidate key, which is a partial dependency and so this relation is not in 2NF. To convert the above relation to 2NF,we need to split the table into two tables such as :Table 1: STUD_NO, COURSE_NOTable 2: COURSE_NO, COURSE_FEE Table 1 Table 2 STUD_NO COURSE_NO COURSE_NO COURSE_FEE 1 C1 C1 1000 2 C2 C2 1500 1 C4 C3 1000 4 C3 C4 2000 4 C1 C5 2000 2 C5 NOTE: 2NF tries to reduce the redundant data getting stored in memory. For instance, if there are 100 students taking C1 course, we don’t need to store its Fee as 1000 for all the 100 records, instead, once we can store it in the second table as the course fee for C1 is 1000. Example 2 – Consider following functional dependencies in relation R (A, B , C, D )AB -> C [A and B together determine C] BC -> D [B and C together determine D]In the above relation, AB is the only candidate key and there is no partial dependency, i.e., any proper subset of AB doesn’t determine any non-prime attribute.3. Third Normal Form –A relation is in third normal form, if there is no transitive dependency for non-prime attributes as well as it is in second normal form.A relation is in 3NF if at least one of the following condition holds in every non-trivial function dependency X –> YX is a super key.Y is a prime attribute (each element of Y is part of some candidate key).Transitive dependency – If A->B and B->C are two FDs then A->C is called transitive dependency.Example 1 – In relation STUDENT given in Table 4,FD set: {STUD_NO -> STUD_NAME, STUD_NO -> STUD_STATE, STUD_STATE -> STUD_COUNTRY, STUD_NO -> STUD_AGE}Candidate Key: {STUD_NO}For this relation in table 4, STUD_NO -> STUD_STATE and STUD_STATE -> STUD_COUNTRY are true. So STUD_COUNTRY is transitively dependent on STUD_NO. It violates the third normal form. To convert it in third normal form, we will decompose the relation STUDENT (STUD_NO, STUD_NAME, STUD_PHONE, STUD_STATE, STUD_COUNTRY_STUD_AGE) as:STUDENT (STUD_NO, STUD_NAME, STUD_PHONE, STUD_STATE, STUD_AGE)STATE_COUNTRY (STATE, COUNTRY)Example 2 – Consider relation R(A, B, C, D, E)A -> BC,CD -> E,B -> D,E -> AAll possible candidate keys in above relation are {A, E, CD, BC} All attributes are on right sides of all functional dependencies are prime.4. Boyce-Codd Normal Form (BCNF) –A relation R is in BCNF if R is in Third Normal Form and for every FD, LHS is super key. A relation is in BCNF iff in every non-trivial functional dependency X –> Y, X is a super key.Example 1 – Find the highest normal form of a relation R(A,B,C,D,E) with FD set as {BC->D, AC->BE, B->E}Step 1. As we can see, (AC)+ ={A,C,B,E,D} but none of its subset can determine all attribute of relation, So AC will be candidate key. A or C can’t be derived from any other attribute of the relation, so there will be only 1 candidate key {AC}.Step 2. Prime attributes are those attributes that are part of candidate key {A, C} in this example and others will be non-prime {B, D, E} in this example.Step 3. The relation R is in 1st normal form as a relational DBMS does not allow multi-valued or composite attribute.The relation is in 2nd normal form because BC->D is in 2nd normal form (BC is not a proper subset of candidate key AC) and AC->BE is in 2nd normal form (AC is candidate key) and B->E is in 2nd normal form (B is not a proper subset of candidate key AC).The relation is not in 3rd normal form because in BC->D (neither BC is a super key nor D is a prime attribute) and in B->E (neither B is a super key nor E is a prime attribute) but to satisfy 3rd normal for, either LHS of an FD should be super key or RHS should be prime attribute.So the highest normal form of relation will be 2nd Normal form.Example 2 –For example consider relation R(A, B, C)A -> BC,B ->A and B both are super keys so above relation is in BCNF.Key Points –BCNF is free from redundancy.If a relation is in BCNF, then 3NF is also satisfied. If all attributes of relation are prime attribute, then the relation is always in 3NF.A relation in a Relational Database is always and at least in 1NF form.Every Binary Relation ( a Relation with only 2 attributes ) is always in BCNF.If a Relation has only singleton candidate keys( i.e. every candidate key consists of only 1 attribute), then the Relation is always in 2NF( because no Partial functional dependency possible).Sometimes going for BCNF form may not preserve functional dependency. In that case go for BCNF only if the lost FD(s) is not required, else normalize till 3NF only.There are many more Normal forms that exist after BCNF, like 4NF and more. But in real world database systems it’s generally not required to go beyond BCNF. Exercise 1: Find the highest normal form in R (A, B, C, D, E) under following functional dependencies. ABC --> D CD --> AE Important Points for solving above type of question.1) It is always a good idea to start checking from BCNF, then 3 NF, and so on.2) If any functional dependency satisfied a normal form then there is no need to check for lower normal form. For example, ABC –> D is in BCNF (Note that ABC is a superkey), so no need to check this dependency for lower normal forms.Candidate keys in the given relation are {ABC, BCD}BCNF: ABC -> D is in BCNF. Let us check CD -> AE, CD is not a super key so this dependency is not in BCNF. So, R is not in BCNF.3NF: ABC -> D we don’t need to check for this dependency as it already satisfied BCNF. Let us consider CD -> AE. Since E is not a prime attribute, so the relation is not in 3NF.2NF: In 2NF, we need to check for partial dependency. CD is a proper subset of a candidate key and it determines E, which is non-prime attribute. So, given relation is also not in 2 NF. So, the highest normal form is 1 NF.GATE CS Corner QuestionsPracticing the following questions will help you test your knowledge. All questions have been asked in GATE in previous years or in GATE Mock Tests. It is highly recommended that you practice them.GATE CS 2012, Question 2GATE CS 2013, Question 54GATE CS 2013, Question 55GATE CS 2005, Question 29GATE CS 2002, Question 23GATE CS 2002, Question 50GATE CS 2001, Question 48GATE CS 1999, Question 32GATE IT 2005, Question 22GATE IT 2008, Question 60GATE CS 2016 (Set 1), Question 31See Quiz on Database Normal Forms for all previous year questions.This article is contributed by Sonal Tuteja. 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.My Personal Notes arrow_drop_upSave AB -> C [A and B together determine C] BC -> D [B and C together determine D] In the above relation, AB is the only candidate key and there is no partial dependency, i.e., any proper subset of AB doesn’t determine any non-prime attribute. A relation is in third normal form, if there is no transitive dependency for non-prime attributes as well as it is in second normal form.A relation is in 3NF if at least one of the following condition holds in every non-trivial function dependency X –> Y X is a super key.Y is a prime attribute (each element of Y is part of some candidate key). X is a super key. Y is a prime attribute (each element of Y is part of some candidate key). Transitive dependency – If A->B and B->C are two FDs then A->C is called transitive dependency. Example 1 – In relation STUDENT given in Table 4,FD set: {STUD_NO -> STUD_NAME, STUD_NO -> STUD_STATE, STUD_STATE -> STUD_COUNTRY, STUD_NO -> STUD_AGE}Candidate Key: {STUD_NO}For this relation in table 4, STUD_NO -> STUD_STATE and STUD_STATE -> STUD_COUNTRY are true. So STUD_COUNTRY is transitively dependent on STUD_NO. It violates the third normal form. To convert it in third normal form, we will decompose the relation STUDENT (STUD_NO, STUD_NAME, STUD_PHONE, STUD_STATE, STUD_COUNTRY_STUD_AGE) as:STUDENT (STUD_NO, STUD_NAME, STUD_PHONE, STUD_STATE, STUD_AGE)STATE_COUNTRY (STATE, COUNTRY) FD set: {STUD_NO -> STUD_NAME, STUD_NO -> STUD_STATE, STUD_STATE -> STUD_COUNTRY, STUD_NO -> STUD_AGE}Candidate Key: {STUD_NO} For this relation in table 4, STUD_NO -> STUD_STATE and STUD_STATE -> STUD_COUNTRY are true. So STUD_COUNTRY is transitively dependent on STUD_NO. It violates the third normal form. To convert it in third normal form, we will decompose the relation STUDENT (STUD_NO, STUD_NAME, STUD_PHONE, STUD_STATE, STUD_COUNTRY_STUD_AGE) as:STUDENT (STUD_NO, STUD_NAME, STUD_PHONE, STUD_STATE, STUD_AGE)STATE_COUNTRY (STATE, COUNTRY) Example 2 – Consider relation R(A, B, C, D, E)A -> BC,CD -> E,B -> D,E -> AAll possible candidate keys in above relation are {A, E, CD, BC} All attributes are on right sides of all functional dependencies are prime.4. Boyce-Codd Normal Form (BCNF) –A relation R is in BCNF if R is in Third Normal Form and for every FD, LHS is super key. A relation is in BCNF iff in every non-trivial functional dependency X –> Y, X is a super key.Example 1 – Find the highest normal form of a relation R(A,B,C,D,E) with FD set as {BC->D, AC->BE, B->E}Step 1. As we can see, (AC)+ ={A,C,B,E,D} but none of its subset can determine all attribute of relation, So AC will be candidate key. A or C can’t be derived from any other attribute of the relation, so there will be only 1 candidate key {AC}.Step 2. Prime attributes are those attributes that are part of candidate key {A, C} in this example and others will be non-prime {B, D, E} in this example.Step 3. The relation R is in 1st normal form as a relational DBMS does not allow multi-valued or composite attribute.The relation is in 2nd normal form because BC->D is in 2nd normal form (BC is not a proper subset of candidate key AC) and AC->BE is in 2nd normal form (AC is candidate key) and B->E is in 2nd normal form (B is not a proper subset of candidate key AC).The relation is not in 3rd normal form because in BC->D (neither BC is a super key nor D is a prime attribute) and in B->E (neither B is a super key nor E is a prime attribute) but to satisfy 3rd normal for, either LHS of an FD should be super key or RHS should be prime attribute.So the highest normal form of relation will be 2nd Normal form.Example 2 –For example consider relation R(A, B, C)A -> BC,B ->A and B both are super keys so above relation is in BCNF.Key Points –BCNF is free from redundancy.If a relation is in BCNF, then 3NF is also satisfied. If all attributes of relation are prime attribute, then the relation is always in 3NF.A relation in a Relational Database is always and at least in 1NF form.Every Binary Relation ( a Relation with only 2 attributes ) is always in BCNF.If a Relation has only singleton candidate keys( i.e. every candidate key consists of only 1 attribute), then the Relation is always in 2NF( because no Partial functional dependency possible).Sometimes going for BCNF form may not preserve functional dependency. In that case go for BCNF only if the lost FD(s) is not required, else normalize till 3NF only.There are many more Normal forms that exist after BCNF, like 4NF and more. But in real world database systems it’s generally not required to go beyond BCNF. Exercise 1: Find the highest normal form in R (A, B, C, D, E) under following functional dependencies. ABC --> D CD --> AE Important Points for solving above type of question.1) It is always a good idea to start checking from BCNF, then 3 NF, and so on.2) If any functional dependency satisfied a normal form then there is no need to check for lower normal form. For example, ABC –> D is in BCNF (Note that ABC is a superkey), so no need to check this dependency for lower normal forms.Candidate keys in the given relation are {ABC, BCD}BCNF: ABC -> D is in BCNF. Let us check CD -> AE, CD is not a super key so this dependency is not in BCNF. So, R is not in BCNF.3NF: ABC -> D we don’t need to check for this dependency as it already satisfied BCNF. Let us consider CD -> AE. Since E is not a prime attribute, so the relation is not in 3NF.2NF: In 2NF, we need to check for partial dependency. CD is a proper subset of a candidate key and it determines E, which is non-prime attribute. So, given relation is also not in 2 NF. So, the highest normal form is 1 NF.GATE CS Corner QuestionsPracticing the following questions will help you test your knowledge. All questions have been asked in GATE in previous years or in GATE Mock Tests. It is highly recommended that you practice them.GATE CS 2012, Question 2GATE CS 2013, Question 54GATE CS 2013, Question 55GATE CS 2005, Question 29GATE CS 2002, Question 23GATE CS 2002, Question 50GATE CS 2001, Question 48GATE CS 1999, Question 32GATE IT 2005, Question 22GATE IT 2008, Question 60GATE CS 2016 (Set 1), Question 31See Quiz on Database Normal Forms for all previous year questions.This article is contributed by Sonal Tuteja. 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.My Personal Notes arrow_drop_upSave A relation R is in BCNF if R is in Third Normal Form and for every FD, LHS is super key. A relation is in BCNF iff in every non-trivial functional dependency X –> Y, X is a super key. Example 1 – Find the highest normal form of a relation R(A,B,C,D,E) with FD set as {BC->D, AC->BE, B->E}Step 1. As we can see, (AC)+ ={A,C,B,E,D} but none of its subset can determine all attribute of relation, So AC will be candidate key. A or C can’t be derived from any other attribute of the relation, so there will be only 1 candidate key {AC}.Step 2. Prime attributes are those attributes that are part of candidate key {A, C} in this example and others will be non-prime {B, D, E} in this example.Step 3. The relation R is in 1st normal form as a relational DBMS does not allow multi-valued or composite attribute.The relation is in 2nd normal form because BC->D is in 2nd normal form (BC is not a proper subset of candidate key AC) and AC->BE is in 2nd normal form (AC is candidate key) and B->E is in 2nd normal form (B is not a proper subset of candidate key AC).The relation is not in 3rd normal form because in BC->D (neither BC is a super key nor D is a prime attribute) and in B->E (neither B is a super key nor E is a prime attribute) but to satisfy 3rd normal for, either LHS of an FD should be super key or RHS should be prime attribute.So the highest normal form of relation will be 2nd Normal form. Example 2 –For example consider relation R(A, B, C)A -> BC,B ->A and B both are super keys so above relation is in BCNF. Key Points – BCNF is free from redundancy.If a relation is in BCNF, then 3NF is also satisfied. If all attributes of relation are prime attribute, then the relation is always in 3NF.A relation in a Relational Database is always and at least in 1NF form.Every Binary Relation ( a Relation with only 2 attributes ) is always in BCNF.If a Relation has only singleton candidate keys( i.e. every candidate key consists of only 1 attribute), then the Relation is always in 2NF( because no Partial functional dependency possible).Sometimes going for BCNF form may not preserve functional dependency. In that case go for BCNF only if the lost FD(s) is not required, else normalize till 3NF only.There are many more Normal forms that exist after BCNF, like 4NF and more. But in real world database systems it’s generally not required to go beyond BCNF. BCNF is free from redundancy. If a relation is in BCNF, then 3NF is also satisfied. If all attributes of relation are prime attribute, then the relation is always in 3NF. A relation in a Relational Database is always and at least in 1NF form. Every Binary Relation ( a Relation with only 2 attributes ) is always in BCNF. If a Relation has only singleton candidate keys( i.e. every candidate key consists of only 1 attribute), then the Relation is always in 2NF( because no Partial functional dependency possible). Sometimes going for BCNF form may not preserve functional dependency. In that case go for BCNF only if the lost FD(s) is not required, else normalize till 3NF only. There are many more Normal forms that exist after BCNF, like 4NF and more. But in real world database systems it’s generally not required to go beyond BCNF. Exercise 1: Find the highest normal form in R (A, B, C, D, E) under following functional dependencies. ABC --> D CD --> AE Important Points for solving above type of question.1) It is always a good idea to start checking from BCNF, then 3 NF, and so on.2) If any functional dependency satisfied a normal form then there is no need to check for lower normal form. For example, ABC –> D is in BCNF (Note that ABC is a superkey), so no need to check this dependency for lower normal forms. Candidate keys in the given relation are {ABC, BCD} BCNF: ABC -> D is in BCNF. Let us check CD -> AE, CD is not a super key so this dependency is not in BCNF. So, R is not in BCNF. 3NF: ABC -> D we don’t need to check for this dependency as it already satisfied BCNF. Let us consider CD -> AE. Since E is not a prime attribute, so the relation is not in 3NF. 2NF: In 2NF, we need to check for partial dependency. CD is a proper subset of a candidate key and it determines E, which is non-prime attribute. So, given relation is also not in 2 NF. So, the highest normal form is 1 NF. GATE CS Corner QuestionsPracticing the following questions will help you test your knowledge. All questions have been asked in GATE in previous years or in GATE Mock Tests. It is highly recommended that you practice them. GATE CS 2012, Question 2GATE CS 2013, Question 54GATE CS 2013, Question 55GATE CS 2005, Question 29GATE CS 2002, Question 23GATE CS 2002, Question 50GATE CS 2001, Question 48GATE CS 1999, Question 32GATE IT 2005, Question 22GATE IT 2008, Question 60GATE CS 2016 (Set 1), Question 31 GATE CS 2012, Question 2 GATE CS 2013, Question 54 GATE CS 2013, Question 55 GATE CS 2005, Question 29 GATE CS 2002, Question 23 GATE CS 2002, Question 50 GATE CS 2001, Question 48 GATE CS 1999, Question 32 GATE IT 2005, Question 22 GATE IT 2008, Question 60 GATE CS 2016 (Set 1), Question 31 See Quiz on Database Normal Forms for all previous year questions. This article is contributed by Sonal Tuteja. 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. PratiyushSah Hasanul Islam TapanMeena 23603vaibhav2021 DBMS-Normalization DBMS GATE CS DBMS Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. SQL | WITH clause SQL | Join (Inner, Left, Right and Full Joins) SQL query to find second highest salary? CTE in SQL SQL Interview Questions Layers of OSI Model TCP/IP Model Types of Operating Systems Page Replacement Algorithms in Operating Systems Differences between TCP and UDP
[ { "code": null, "e": 30871, "s": 30843, "text": "\n12 Nov, 2021" }, { "code": null, "e": 30944, "s": 30871, "text": "Prerequisite – Database normalization and functional dependency concept." }, { "code": null, "e": 31241, "s": 30944, "text": "Normalization is the process of minimizing redundancy from a relation or set of relations. Redundancy in relation may cause insertion, deletion, and update anomalies. So, it helps to minimize the redundancy in relations. Normal forms are used to eliminate or reduce redundancy in database tables." }, { "code": null, "e": 31532, "s": 31241, "text": "If a relation contain composite or multi-valued attribute, it violates first normal form or a relation is in first normal form if it does not contain any composite or multi-valued attribute. A relation is in first normal form if every attribute in that relation is singled valued attribute." }, { "code": null, "e": 31686, "s": 31532, "text": "Example 1 – Relation STUDENT in table 1 is not in 1NF because of multi-valued attribute STUD_PHONE. Its decomposition into 1NF has been shown in table 2." }, { "code": null, "e": 32044, "s": 31686, "text": "Example 2 – \nID Name Courses\n------------------\n1 A c1, c2\n2 E c3\n3 M C2, c3\nIn the above table Course is a multi-valued attribute so it is not in 1NF.Below Table is in 1NF as there is no multi-valued attributeID Name Course\n------------------\n1 A c1\n1 A c2\n2 E c3\n3 M c2\n3 M c3\n " }, { "code": null, "e": 32139, "s": 32044, "text": " \nID Name Courses\n------------------\n1 A c1, c2\n2 E c3\n3 M C2, c3\n" }, { "code": null, "e": 32214, "s": 32139, "text": "In the above table Course is a multi-valued attribute so it is not in 1NF." }, { "code": null, "e": 32274, "s": 32214, "text": "Below Table is in 1NF as there is no multi-valued attribute" }, { "code": null, "e": 32393, "s": 32274, "text": "ID Name Course\n------------------\n1 A c1\n1 A c2\n2 E c3\n3 M c2\n3 M c3\n" }, { "code": null, "e": 32723, "s": 32395, "text": "To be in second normal form, a relation must be in first normal form and relation must not contain any partial dependency. A relation is in 2NF if it has No Partial Dependency, i.e., no non-prime attribute (attributes which are not part of any candidate key) is dependent on any proper subset of any candidate key of the table." }, { "code": null, "e": 32847, "s": 32723, "text": "Partial Dependency – If the proper subset of candidate key determines non-prime attribute, it is called partial dependency." }, { "code": null, "e": 34808, "s": 32847, "text": "Example 1 – Consider table-3 as following below.STUD_NO COURSE_NO COURSE_FEE\n1 C1 1000\n2 C2 1500\n1 C4 2000\n4 C3 1000\n4 C1 1000\n2 C5 2000\n{Note that, there are many courses having the same course fee. }Here,COURSE_FEE cannot alone decide the value of COURSE_NO or STUD_NO;COURSE_FEE together with STUD_NO cannot decide the value of COURSE_NO;COURSE_FEE together with COURSE_NO cannot decide the value of STUD_NO;Hence,COURSE_FEE would be a non-prime attribute, as it does not belong to the one only candidate key {STUD_NO, COURSE_NO} ;But, COURSE_NO -> COURSE_FEE, i.e., COURSE_FEE is dependent on COURSE_NO, which is a proper subset of the candidate key. Non-prime attribute COURSE_FEE is dependent on a proper subset of the candidate key, which is a partial dependency and so this relation is not in 2NF.To convert the above relation to 2NF,we need to split the table into two tables such as :Table 1: STUD_NO, COURSE_NOTable 2: COURSE_NO, COURSE_FEE Table 1 Table 2\nSTUD_NO COURSE_NO COURSE_NO COURSE_FEE \n1 C1 C1 1000\n2 C2 C2 1500\n1 C4 C3 1000\n4 C3 C4 2000\n4 C1 C5 2000 2 C5NOTE: 2NF tries to reduce the redundant data getting stored in memory. For instance, if there are 100 students taking C1 course, we don’t need to store its Fee as 1000 for all the 100 records, instead, once we can store it in the second table as the course fee for C1 is 1000." }, { "code": null, "e": 35138, "s": 34808, "text": "STUD_NO COURSE_NO COURSE_FEE\n1 C1 1000\n2 C2 1500\n1 C4 2000\n4 C3 1000\n4 C1 1000\n2 C5 2000\n" }, { "code": null, "e": 35203, "s": 35138, "text": "{Note that, there are many courses having the same course fee. }" }, { "code": null, "e": 35808, "s": 35203, "text": "Here,COURSE_FEE cannot alone decide the value of COURSE_NO or STUD_NO;COURSE_FEE together with STUD_NO cannot decide the value of COURSE_NO;COURSE_FEE together with COURSE_NO cannot decide the value of STUD_NO;Hence,COURSE_FEE would be a non-prime attribute, as it does not belong to the one only candidate key {STUD_NO, COURSE_NO} ;But, COURSE_NO -> COURSE_FEE, i.e., COURSE_FEE is dependent on COURSE_NO, which is a proper subset of the candidate key. Non-prime attribute COURSE_FEE is dependent on a proper subset of the candidate key, which is a partial dependency and so this relation is not in 2NF." }, { "code": null, "e": 35955, "s": 35808, "text": "To convert the above relation to 2NF,we need to split the table into two tables such as :Table 1: STUD_NO, COURSE_NOTable 2: COURSE_NO, COURSE_FEE" }, { "code": null, "e": 36445, "s": 35955, "text": " Table 1 Table 2\nSTUD_NO COURSE_NO COURSE_NO COURSE_FEE \n1 C1 C1 1000\n2 C2 C2 1500\n1 C4 C3 1000\n4 C3 C4 2000\n4 C1 C5 2000 " }, { "code": null, "e": 36450, "s": 36445, "text": "2 C5" }, { "code": null, "e": 36727, "s": 36450, "text": "NOTE: 2NF tries to reduce the redundant data getting stored in memory. For instance, if there are 100 students taking C1 course, we don’t need to store its Fee as 1000 for all the 100 records, instead, once we can store it in the second table as the course fee for C1 is 1000." }, { "code": null, "e": 42810, "s": 36727, "text": "Example 2 – Consider following functional dependencies in relation R (A, B , C, D )AB -> C [A and B together determine C]\nBC -> D [B and C together determine D]In the above relation, AB is the only candidate key and there is no partial dependency, i.e., any proper subset of AB doesn’t determine any non-prime attribute.3. Third Normal Form –A relation is in third normal form, if there is no transitive dependency for non-prime attributes as well as it is in second normal form.A relation is in 3NF if at least one of the following condition holds in every non-trivial function dependency X –> YX is a super key.Y is a prime attribute (each element of Y is part of some candidate key).Transitive dependency – If A->B and B->C are two FDs then A->C is called transitive dependency.Example 1 – In relation STUDENT given in Table 4,FD set: {STUD_NO -> STUD_NAME, STUD_NO -> STUD_STATE, STUD_STATE -> STUD_COUNTRY, STUD_NO -> STUD_AGE}Candidate Key: {STUD_NO}For this relation in table 4, STUD_NO -> STUD_STATE and STUD_STATE -> STUD_COUNTRY are true. So STUD_COUNTRY is transitively dependent on STUD_NO. It violates the third normal form. To convert it in third normal form, we will decompose the relation STUDENT (STUD_NO, STUD_NAME, STUD_PHONE, STUD_STATE, STUD_COUNTRY_STUD_AGE) as:STUDENT (STUD_NO, STUD_NAME, STUD_PHONE, STUD_STATE, STUD_AGE)STATE_COUNTRY (STATE, COUNTRY)Example 2 – Consider relation R(A, B, C, D, E)A -> BC,CD -> E,B -> D,E -> AAll possible candidate keys in above relation are {A, E, CD, BC} All attributes are on right sides of all functional dependencies are prime.4. Boyce-Codd Normal Form (BCNF) –A relation R is in BCNF if R is in Third Normal Form and for every FD, LHS is super key. A relation is in BCNF iff in every non-trivial functional dependency X –> Y, X is a super key.Example 1 – Find the highest normal form of a relation R(A,B,C,D,E) with FD set as {BC->D, AC->BE, B->E}Step 1. As we can see, (AC)+ ={A,C,B,E,D} but none of its subset can determine all attribute of relation, So AC will be candidate key. A or C can’t be derived from any other attribute of the relation, so there will be only 1 candidate key {AC}.Step 2. Prime attributes are those attributes that are part of candidate key {A, C} in this example and others will be non-prime {B, D, E} in this example.Step 3. The relation R is in 1st normal form as a relational DBMS does not allow multi-valued or composite attribute.The relation is in 2nd normal form because BC->D is in 2nd normal form (BC is not a proper subset of candidate key AC) and AC->BE is in 2nd normal form (AC is candidate key) and B->E is in 2nd normal form (B is not a proper subset of candidate key AC).The relation is not in 3rd normal form because in BC->D (neither BC is a super key nor D is a prime attribute) and in B->E (neither B is a super key nor E is a prime attribute) but to satisfy 3rd normal for, either LHS of an FD should be super key or RHS should be prime attribute.So the highest normal form of relation will be 2nd Normal form.Example 2 –For example consider relation R(A, B, C)A -> BC,B ->A and B both are super keys so above relation is in BCNF.Key Points –BCNF is free from redundancy.If a relation is in BCNF, then 3NF is also satisfied. If all attributes of relation are prime attribute, then the relation is always in 3NF.A relation in a Relational Database is always and at least in 1NF form.Every Binary Relation ( a Relation with only 2 attributes ) is always in BCNF.If a Relation has only singleton candidate keys( i.e. every candidate key consists of only 1 attribute), then the Relation is always in 2NF( because no Partial functional dependency possible).Sometimes going for BCNF form may not preserve functional dependency. In that case go for BCNF only if the lost FD(s) is not required, else normalize till 3NF only.There are many more Normal forms that exist after BCNF, like 4NF and more. But in real world database systems it’s generally not required to go beyond BCNF. Exercise 1: Find the highest normal form in R (A, B, C, D, E) under following functional dependencies. ABC --> D\n CD --> AE Important Points for solving above type of question.1) It is always a good idea to start checking from BCNF, then 3 NF, and so on.2) If any functional dependency satisfied a normal form then there is no need to check for lower normal form. For example, ABC –> D is in BCNF (Note that ABC is a superkey), so no need to check this dependency for lower normal forms.Candidate keys in the given relation are {ABC, BCD}BCNF: ABC -> D is in BCNF. Let us check CD -> AE, CD is not a super key so this dependency is not in BCNF. So, R is not in BCNF.3NF: ABC -> D we don’t need to check for this dependency as it already satisfied BCNF. Let us consider CD -> AE. Since E is not a prime attribute, so the relation is not in 3NF.2NF: In 2NF, we need to check for partial dependency. CD is a proper subset of a candidate key and it determines E, which is non-prime attribute. So, given relation is also not in 2 NF. So, the highest normal form is 1 NF.GATE CS Corner QuestionsPracticing the following questions will help you test your knowledge. All questions have been asked in GATE in previous years or in GATE Mock Tests. It is highly recommended that you practice them.GATE CS 2012, Question 2GATE CS 2013, Question 54GATE CS 2013, Question 55GATE CS 2005, Question 29GATE CS 2002, Question 23GATE CS 2002, Question 50GATE CS 2001, Question 48GATE CS 1999, Question 32GATE IT 2005, Question 22GATE IT 2008, Question 60GATE CS 2016 (Set 1), Question 31See Quiz on Database Normal Forms for all previous year questions.This article is contributed by Sonal Tuteja. 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.My Personal Notes\narrow_drop_upSave" }, { "code": null, "e": 42890, "s": 42810, "text": "AB -> C [A and B together determine C]\nBC -> D [B and C together determine D]" }, { "code": null, "e": 43051, "s": 42890, "text": "In the above relation, AB is the only candidate key and there is no partial dependency, i.e., any proper subset of AB doesn’t determine any non-prime attribute." }, { "code": null, "e": 43306, "s": 43051, "text": "A relation is in third normal form, if there is no transitive dependency for non-prime attributes as well as it is in second normal form.A relation is in 3NF if at least one of the following condition holds in every non-trivial function dependency X –> Y" }, { "code": null, "e": 43397, "s": 43306, "text": "X is a super key.Y is a prime attribute (each element of Y is part of some candidate key)." }, { "code": null, "e": 43415, "s": 43397, "text": "X is a super key." }, { "code": null, "e": 43489, "s": 43415, "text": "Y is a prime attribute (each element of Y is part of some candidate key)." }, { "code": null, "e": 43585, "s": 43489, "text": "Transitive dependency – If A->B and B->C are two FDs then A->C is called transitive dependency." }, { "code": null, "e": 44181, "s": 43585, "text": "Example 1 – In relation STUDENT given in Table 4,FD set: {STUD_NO -> STUD_NAME, STUD_NO -> STUD_STATE, STUD_STATE -> STUD_COUNTRY, STUD_NO -> STUD_AGE}Candidate Key: {STUD_NO}For this relation in table 4, STUD_NO -> STUD_STATE and STUD_STATE -> STUD_COUNTRY are true. So STUD_COUNTRY is transitively dependent on STUD_NO. It violates the third normal form. To convert it in third normal form, we will decompose the relation STUDENT (STUD_NO, STUD_NAME, STUD_PHONE, STUD_STATE, STUD_COUNTRY_STUD_AGE) as:STUDENT (STUD_NO, STUD_NAME, STUD_PHONE, STUD_STATE, STUD_AGE)STATE_COUNTRY (STATE, COUNTRY)" }, { "code": null, "e": 44308, "s": 44181, "text": "FD set: {STUD_NO -> STUD_NAME, STUD_NO -> STUD_STATE, STUD_STATE -> STUD_COUNTRY, STUD_NO -> STUD_AGE}Candidate Key: {STUD_NO}" }, { "code": null, "e": 44729, "s": 44308, "text": "For this relation in table 4, STUD_NO -> STUD_STATE and STUD_STATE -> STUD_COUNTRY are true. So STUD_COUNTRY is transitively dependent on STUD_NO. It violates the third normal form. To convert it in third normal form, we will decompose the relation STUDENT (STUD_NO, STUD_NAME, STUD_PHONE, STUD_STATE, STUD_COUNTRY_STUD_AGE) as:STUDENT (STUD_NO, STUD_NAME, STUD_PHONE, STUD_STATE, STUD_AGE)STATE_COUNTRY (STATE, COUNTRY)" }, { "code": null, "e": 49431, "s": 44729, "text": "Example 2 – Consider relation R(A, B, C, D, E)A -> BC,CD -> E,B -> D,E -> AAll possible candidate keys in above relation are {A, E, CD, BC} All attributes are on right sides of all functional dependencies are prime.4. Boyce-Codd Normal Form (BCNF) –A relation R is in BCNF if R is in Third Normal Form and for every FD, LHS is super key. A relation is in BCNF iff in every non-trivial functional dependency X –> Y, X is a super key.Example 1 – Find the highest normal form of a relation R(A,B,C,D,E) with FD set as {BC->D, AC->BE, B->E}Step 1. As we can see, (AC)+ ={A,C,B,E,D} but none of its subset can determine all attribute of relation, So AC will be candidate key. A or C can’t be derived from any other attribute of the relation, so there will be only 1 candidate key {AC}.Step 2. Prime attributes are those attributes that are part of candidate key {A, C} in this example and others will be non-prime {B, D, E} in this example.Step 3. The relation R is in 1st normal form as a relational DBMS does not allow multi-valued or composite attribute.The relation is in 2nd normal form because BC->D is in 2nd normal form (BC is not a proper subset of candidate key AC) and AC->BE is in 2nd normal form (AC is candidate key) and B->E is in 2nd normal form (B is not a proper subset of candidate key AC).The relation is not in 3rd normal form because in BC->D (neither BC is a super key nor D is a prime attribute) and in B->E (neither B is a super key nor E is a prime attribute) but to satisfy 3rd normal for, either LHS of an FD should be super key or RHS should be prime attribute.So the highest normal form of relation will be 2nd Normal form.Example 2 –For example consider relation R(A, B, C)A -> BC,B ->A and B both are super keys so above relation is in BCNF.Key Points –BCNF is free from redundancy.If a relation is in BCNF, then 3NF is also satisfied. If all attributes of relation are prime attribute, then the relation is always in 3NF.A relation in a Relational Database is always and at least in 1NF form.Every Binary Relation ( a Relation with only 2 attributes ) is always in BCNF.If a Relation has only singleton candidate keys( i.e. every candidate key consists of only 1 attribute), then the Relation is always in 2NF( because no Partial functional dependency possible).Sometimes going for BCNF form may not preserve functional dependency. In that case go for BCNF only if the lost FD(s) is not required, else normalize till 3NF only.There are many more Normal forms that exist after BCNF, like 4NF and more. But in real world database systems it’s generally not required to go beyond BCNF. Exercise 1: Find the highest normal form in R (A, B, C, D, E) under following functional dependencies. ABC --> D\n CD --> AE Important Points for solving above type of question.1) It is always a good idea to start checking from BCNF, then 3 NF, and so on.2) If any functional dependency satisfied a normal form then there is no need to check for lower normal form. For example, ABC –> D is in BCNF (Note that ABC is a superkey), so no need to check this dependency for lower normal forms.Candidate keys in the given relation are {ABC, BCD}BCNF: ABC -> D is in BCNF. Let us check CD -> AE, CD is not a super key so this dependency is not in BCNF. So, R is not in BCNF.3NF: ABC -> D we don’t need to check for this dependency as it already satisfied BCNF. Let us consider CD -> AE. Since E is not a prime attribute, so the relation is not in 3NF.2NF: In 2NF, we need to check for partial dependency. CD is a proper subset of a candidate key and it determines E, which is non-prime attribute. So, given relation is also not in 2 NF. So, the highest normal form is 1 NF.GATE CS Corner QuestionsPracticing the following questions will help you test your knowledge. All questions have been asked in GATE in previous years or in GATE Mock Tests. It is highly recommended that you practice them.GATE CS 2012, Question 2GATE CS 2013, Question 54GATE CS 2013, Question 55GATE CS 2005, Question 29GATE CS 2002, Question 23GATE CS 2002, Question 50GATE CS 2001, Question 48GATE CS 1999, Question 32GATE IT 2005, Question 22GATE IT 2008, Question 60GATE CS 2016 (Set 1), Question 31See Quiz on Database Normal Forms for all previous year questions.This article is contributed by Sonal Tuteja. 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.My Personal Notes\narrow_drop_upSave" }, { "code": null, "e": 49615, "s": 49431, "text": "A relation R is in BCNF if R is in Third Normal Form and for every FD, LHS is super key. A relation is in BCNF iff in every non-trivial functional dependency X –> Y, X is a super key." }, { "code": null, "e": 50832, "s": 49615, "text": "Example 1 – Find the highest normal form of a relation R(A,B,C,D,E) with FD set as {BC->D, AC->BE, B->E}Step 1. As we can see, (AC)+ ={A,C,B,E,D} but none of its subset can determine all attribute of relation, So AC will be candidate key. A or C can’t be derived from any other attribute of the relation, so there will be only 1 candidate key {AC}.Step 2. Prime attributes are those attributes that are part of candidate key {A, C} in this example and others will be non-prime {B, D, E} in this example.Step 3. The relation R is in 1st normal form as a relational DBMS does not allow multi-valued or composite attribute.The relation is in 2nd normal form because BC->D is in 2nd normal form (BC is not a proper subset of candidate key AC) and AC->BE is in 2nd normal form (AC is candidate key) and B->E is in 2nd normal form (B is not a proper subset of candidate key AC).The relation is not in 3rd normal form because in BC->D (neither BC is a super key nor D is a prime attribute) and in B->E (neither B is a super key nor E is a prime attribute) but to satisfy 3rd normal for, either LHS of an FD should be super key or RHS should be prime attribute.So the highest normal form of relation will be 2nd Normal form." }, { "code": null, "e": 50953, "s": 50832, "text": "Example 2 –For example consider relation R(A, B, C)A -> BC,B ->A and B both are super keys so above relation is in BCNF." }, { "code": null, "e": 50966, "s": 50953, "text": "Key Points –" }, { "code": null, "e": 51797, "s": 50966, "text": "BCNF is free from redundancy.If a relation is in BCNF, then 3NF is also satisfied. If all attributes of relation are prime attribute, then the relation is always in 3NF.A relation in a Relational Database is always and at least in 1NF form.Every Binary Relation ( a Relation with only 2 attributes ) is always in BCNF.If a Relation has only singleton candidate keys( i.e. every candidate key consists of only 1 attribute), then the Relation is always in 2NF( because no Partial functional dependency possible).Sometimes going for BCNF form may not preserve functional dependency. In that case go for BCNF only if the lost FD(s) is not required, else normalize till 3NF only.There are many more Normal forms that exist after BCNF, like 4NF and more. But in real world database systems it’s generally not required to go beyond BCNF." }, { "code": null, "e": 51827, "s": 51797, "text": "BCNF is free from redundancy." }, { "code": null, "e": 51881, "s": 51827, "text": "If a relation is in BCNF, then 3NF is also satisfied." }, { "code": null, "e": 51969, "s": 51881, "text": " If all attributes of relation are prime attribute, then the relation is always in 3NF." }, { "code": null, "e": 52041, "s": 51969, "text": "A relation in a Relational Database is always and at least in 1NF form." }, { "code": null, "e": 52120, "s": 52041, "text": "Every Binary Relation ( a Relation with only 2 attributes ) is always in BCNF." }, { "code": null, "e": 52313, "s": 52120, "text": "If a Relation has only singleton candidate keys( i.e. every candidate key consists of only 1 attribute), then the Relation is always in 2NF( because no Partial functional dependency possible)." }, { "code": null, "e": 52478, "s": 52313, "text": "Sometimes going for BCNF form may not preserve functional dependency. In that case go for BCNF only if the lost FD(s) is not required, else normalize till 3NF only." }, { "code": null, "e": 52635, "s": 52478, "text": "There are many more Normal forms that exist after BCNF, like 4NF and more. But in real world database systems it’s generally not required to go beyond BCNF." }, { "code": null, "e": 52740, "s": 52637, "text": "Exercise 1: Find the highest normal form in R (A, B, C, D, E) under following functional dependencies." }, { "code": null, "e": 52765, "s": 52740, "text": " ABC --> D\n CD --> AE " }, { "code": null, "e": 53129, "s": 52765, "text": "Important Points for solving above type of question.1) It is always a good idea to start checking from BCNF, then 3 NF, and so on.2) If any functional dependency satisfied a normal form then there is no need to check for lower normal form. For example, ABC –> D is in BCNF (Note that ABC is a superkey), so no need to check this dependency for lower normal forms." }, { "code": null, "e": 53181, "s": 53129, "text": "Candidate keys in the given relation are {ABC, BCD}" }, { "code": null, "e": 53310, "s": 53181, "text": "BCNF: ABC -> D is in BCNF. Let us check CD -> AE, CD is not a super key so this dependency is not in BCNF. So, R is not in BCNF." }, { "code": null, "e": 53488, "s": 53310, "text": "3NF: ABC -> D we don’t need to check for this dependency as it already satisfied BCNF. Let us consider CD -> AE. Since E is not a prime attribute, so the relation is not in 3NF." }, { "code": null, "e": 53711, "s": 53488, "text": "2NF: In 2NF, we need to check for partial dependency. CD is a proper subset of a candidate key and it determines E, which is non-prime attribute. So, given relation is also not in 2 NF. So, the highest normal form is 1 NF." }, { "code": null, "e": 53933, "s": 53711, "text": "GATE CS Corner QuestionsPracticing the following questions will help you test your knowledge. All questions have been asked in GATE in previous years or in GATE Mock Tests. It is highly recommended that you practice them." }, { "code": null, "e": 54216, "s": 53933, "text": "GATE CS 2012, Question 2GATE CS 2013, Question 54GATE CS 2013, Question 55GATE CS 2005, Question 29GATE CS 2002, Question 23GATE CS 2002, Question 50GATE CS 2001, Question 48GATE CS 1999, Question 32GATE IT 2005, Question 22GATE IT 2008, Question 60GATE CS 2016 (Set 1), Question 31" }, { "code": null, "e": 54241, "s": 54216, "text": "GATE CS 2012, Question 2" }, { "code": null, "e": 54267, "s": 54241, "text": "GATE CS 2013, Question 54" }, { "code": null, "e": 54293, "s": 54267, "text": "GATE CS 2013, Question 55" }, { "code": null, "e": 54319, "s": 54293, "text": "GATE CS 2005, Question 29" }, { "code": null, "e": 54345, "s": 54319, "text": "GATE CS 2002, Question 23" }, { "code": null, "e": 54371, "s": 54345, "text": "GATE CS 2002, Question 50" }, { "code": null, "e": 54397, "s": 54371, "text": "GATE CS 2001, Question 48" }, { "code": null, "e": 54423, "s": 54397, "text": "GATE CS 1999, Question 32" }, { "code": null, "e": 54449, "s": 54423, "text": "GATE IT 2005, Question 22" }, { "code": null, "e": 54475, "s": 54449, "text": "GATE IT 2008, Question 60" }, { "code": null, "e": 54509, "s": 54475, "text": "GATE CS 2016 (Set 1), Question 31" }, { "code": null, "e": 54576, "s": 54509, "text": "See Quiz on Database Normal Forms for all previous year questions." }, { "code": null, "e": 54872, "s": 54576, "text": "This article is contributed by Sonal Tuteja. 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": 54997, "s": 54872, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 55010, "s": 54997, "text": "PratiyushSah" }, { "code": null, "e": 55024, "s": 55010, "text": "Hasanul Islam" }, { "code": null, "e": 55035, "s": 55024, "text": "TapanMeena" }, { "code": null, "e": 55052, "s": 55035, "text": "23603vaibhav2021" }, { "code": null, "e": 55071, "s": 55052, "text": "DBMS-Normalization" }, { "code": null, "e": 55076, "s": 55071, "text": "DBMS" }, { "code": null, "e": 55084, "s": 55076, "text": "GATE CS" }, { "code": null, "e": 55089, "s": 55084, "text": "DBMS" }, { "code": null, "e": 55187, "s": 55089, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 55205, "s": 55187, "text": "SQL | WITH clause" }, { "code": null, "e": 55252, "s": 55205, "text": "SQL | Join (Inner, Left, Right and Full Joins)" }, { "code": null, "e": 55293, "s": 55252, "text": "SQL query to find second highest salary?" }, { "code": null, "e": 55304, "s": 55293, "text": "CTE in SQL" }, { "code": null, "e": 55328, "s": 55304, "text": "SQL Interview Questions" }, { "code": null, "e": 55348, "s": 55328, "text": "Layers of OSI Model" }, { "code": null, "e": 55361, "s": 55348, "text": "TCP/IP Model" }, { "code": null, "e": 55388, "s": 55361, "text": "Types of Operating Systems" }, { "code": null, "e": 55437, "s": 55388, "text": "Page Replacement Algorithms in Operating Systems" } ]
SortedMap comparator() method in Java with Examples - GeeksforGeeks
08 Jun, 2021 The comparator() method of java.util.SortedMap interface is used to return the comparator used to order the keys in this map, or null if this map uses the natural ordering of its keys.Syntax: public Comparator comparator() Return Value: This method returns the comparator used to order the keys in this map, or null if this map uses the natural ordering of its keys.Below programs illustrate the comparator() method:Example 1: For Natural ordering. Java // Java program to demonstrate// comparator() method for natural ordering import java.util.*; public class GFG1 { public static void main(String[] argv) throws Exception { try { // Creating object of SortedTreeMap SortedMap<Integer, String> sotreemap = new TreeMap<Integer, String>(); // Populating tree map sotreemap.put(1, "one"); sotreemap.put(2, "two"); sotreemap.put(3, "three"); sotreemap.put(4, "four"); sotreemap.put(5, "five"); // Printing the SortedTreeMap System.out.println("SortedTreeMap: " + sotreemap); // Getting used Comparator in the map // using comparator() method Comparator comp = sotreemap.comparator(); // Printing the comparator value System.out.println("Comparator value: " + comp); } catch (NullPointerException e) { System.out.println("Exception thrown : " + e); } }} SortedTreeMap: {1=one, 2=two, 3=three, 4=four, 5=five} Comparator value: null Example 2: For Reverse ordering. Java // Java program to demonstrate// comparator() method// for reverse ordering import java.util.*; public class GFG1 { public static void main(String[] argv) throws Exception<div class="code-output"><b>Output:</b><pre>Initial Mappings are: {10=Geeks, 15=4, 20=Geeks, 25=Welcomes, 30=You}The set is: [10=Geeks, 15=4, 20=Geeks, 25=Welcomes, 30=You]</pre></div> { try { // Creating object of TreeMap SortedMap<Integer, String> sotreemap = new TreeMap<Integer, String>( Collections.reverseOrder()); // Populating tree map sotreemap.put(1, "one"); sotreemap.put(2, "two"); sotreemap.put(3, "three"); sotreemap.put(4, "four"); sotreemap.put(5, "five"); // Printing the TreeMap System.out.println("SortedTreeMap: " + sotreemap); // Getting used Comparator in the map // using comparator() method Comparator comp = sotreemap.comparator(); // Printing the comparator value System.out.println("Comparator value: " + comp); } catch (NullPointerException e) { System.out.println("Exception thrown : " + e); } }} SortedTreeMap: {5=five, 4=four, 3=three, 2=two, 1=one} Comparator value: java.util.Collections$ReverseComparator@232204a1 anikakapoor Java - util package Java-Collections Java-Functions Java-SortedMap Java Java Java-Collections Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Arrays in Java Split() String method in Java with examples For-each loop in Java Object Oriented Programming (OOPs) Concept in Java Arrays.sort() in Java with examples HashMap in Java with Examples Reverse a string in Java Stream In Java Interfaces in Java How to iterate any Map in Java
[ { "code": null, "e": 24207, "s": 24179, "text": "\n08 Jun, 2021" }, { "code": null, "e": 24401, "s": 24207, "text": "The comparator() method of java.util.SortedMap interface is used to return the comparator used to order the keys in this map, or null if this map uses the natural ordering of its keys.Syntax: " }, { "code": null, "e": 24432, "s": 24401, "text": "public Comparator comparator()" }, { "code": null, "e": 24660, "s": 24432, "text": "Return Value: This method returns the comparator used to order the keys in this map, or null if this map uses the natural ordering of its keys.Below programs illustrate the comparator() method:Example 1: For Natural ordering. " }, { "code": null, "e": 24665, "s": 24660, "text": "Java" }, { "code": "// Java program to demonstrate// comparator() method for natural ordering import java.util.*; public class GFG1 { public static void main(String[] argv) throws Exception { try { // Creating object of SortedTreeMap SortedMap<Integer, String> sotreemap = new TreeMap<Integer, String>(); // Populating tree map sotreemap.put(1, \"one\"); sotreemap.put(2, \"two\"); sotreemap.put(3, \"three\"); sotreemap.put(4, \"four\"); sotreemap.put(5, \"five\"); // Printing the SortedTreeMap System.out.println(\"SortedTreeMap: \" + sotreemap); // Getting used Comparator in the map // using comparator() method Comparator comp = sotreemap.comparator(); // Printing the comparator value System.out.println(\"Comparator value: \" + comp); } catch (NullPointerException e) { System.out.println(\"Exception thrown : \" + e); } }}", "e": 25733, "s": 24665, "text": null }, { "code": null, "e": 25811, "s": 25733, "text": "SortedTreeMap: {1=one, 2=two, 3=three, 4=four, 5=five}\nComparator value: null" }, { "code": null, "e": 25848, "s": 25813, "text": "Example 2: For Reverse ordering. " }, { "code": null, "e": 25853, "s": 25848, "text": "Java" }, { "code": "// Java program to demonstrate// comparator() method// for reverse ordering import java.util.*; public class GFG1 { public static void main(String[] argv) throws Exception<div class=\"code-output\"><b>Output:</b><pre>Initial Mappings are: {10=Geeks, 15=4, 20=Geeks, 25=Welcomes, 30=You}The set is: [10=Geeks, 15=4, 20=Geeks, 25=Welcomes, 30=You]</pre></div> { try { // Creating object of TreeMap SortedMap<Integer, String> sotreemap = new TreeMap<Integer, String>( Collections.reverseOrder()); // Populating tree map sotreemap.put(1, \"one\"); sotreemap.put(2, \"two\"); sotreemap.put(3, \"three\"); sotreemap.put(4, \"four\"); sotreemap.put(5, \"five\"); // Printing the TreeMap System.out.println(\"SortedTreeMap: \" + sotreemap); // Getting used Comparator in the map // using comparator() method Comparator comp = sotreemap.comparator(); // Printing the comparator value System.out.println(\"Comparator value: \" + comp); } catch (NullPointerException e) { System.out.println(\"Exception thrown : \" + e); } }}", "e": 27112, "s": 25853, "text": null }, { "code": null, "e": 27234, "s": 27112, "text": "SortedTreeMap: {5=five, 4=four, 3=three, 2=two, 1=one}\nComparator value: java.util.Collections$ReverseComparator@232204a1" }, { "code": null, "e": 27248, "s": 27236, "text": "anikakapoor" }, { "code": null, "e": 27268, "s": 27248, "text": "Java - util package" }, { "code": null, "e": 27285, "s": 27268, "text": "Java-Collections" }, { "code": null, "e": 27300, "s": 27285, "text": "Java-Functions" }, { "code": null, "e": 27315, "s": 27300, "text": "Java-SortedMap" }, { "code": null, "e": 27320, "s": 27315, "text": "Java" }, { "code": null, "e": 27325, "s": 27320, "text": "Java" }, { "code": null, "e": 27342, "s": 27325, "text": "Java-Collections" }, { "code": null, "e": 27440, "s": 27342, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27455, "s": 27440, "text": "Arrays in Java" }, { "code": null, "e": 27499, "s": 27455, "text": "Split() String method in Java with examples" }, { "code": null, "e": 27521, "s": 27499, "text": "For-each loop in Java" }, { "code": null, "e": 27572, "s": 27521, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 27608, "s": 27572, "text": "Arrays.sort() in Java with examples" }, { "code": null, "e": 27638, "s": 27608, "text": "HashMap in Java with Examples" }, { "code": null, "e": 27663, "s": 27638, "text": "Reverse a string in Java" }, { "code": null, "e": 27678, "s": 27663, "text": "Stream In Java" }, { "code": null, "e": 27697, "s": 27678, "text": "Interfaces in Java" } ]
Minimum product pair an array of positive Integers - GeeksforGeeks
17 Mar, 2022 Given an array of positive integers. We are required to write a program to print the minimum product of any two numbers of the given array.Examples: Input : 11 8 5 7 5 100 Output : 25 Explanation : The minimum product of any two numbers will be 5 * 5 = 25. Input : 198 76 544 123 154 675 Output : 7448 Explanation : The minimum product of any two numbers will be 76 * 123 = 7448. Simple Approach : A simple approach will be to run two nested loops to generate all possible pair of elements and keep track of the minimum product. Time Complexity: O( n * n) Auxiliary Space: O( 1 )Better Approach: An efficient approach will be to first sort the given array and print the product of first two numbers, sorting will take O(n log n). Answer will be then a[0] * a[1] Time Complexity: O( n * log(n)) Auxiliary Space: O( 1 )Best Approach: The idea is linearly traverse given array and keep track of minimum two elements. Finally return product of two minimum elements.Below is the implementation of above approach. C++ Java Python3 C# PHP Javascript // C++ program to calculate minimum// product of a pair#include <bits/stdc++.h>using namespace std; // Function to calculate minimum product// of pairint printMinimumProduct(int arr[], int n){ // Initialize first and second // minimums. It is assumed that the // array has at least two elements. int first_min = min(arr[0], arr[1]); int second_min = max(arr[0], arr[1]); // Traverse remaining array and keep // track of two minimum elements (Note // that the two minimum elements may // be same if minimum element appears // more than once) // more than once) for (int i=2; i<n; i++) { if (arr[i] < first_min) { second_min = first_min; first_min = arr[i]; } else if (arr[i] < second_min) second_min = arr[i]; } return first_min * second_min;} // Driver program to test above functionint main(){ int a[] = { 11, 8 , 5 , 7 , 5 , 100 }; int n = sizeof(a) / sizeof(a[0]); cout << printMinimumProduct(a,n); return 0;} // Java program to calculate minimum// product of a pairimport java.util.*; class GFG { // Function to calculate minimum product // of pair static int printMinimumProduct(int arr[], int n) { // Initialize first and second // minimums. It is assumed that the // array has at least two elements. int first_min = Math.min(arr[0], arr[1]); int second_min = Math.max(arr[0], arr[1]); // Traverse remaining array and keep // track of two minimum elements (Note // that the two minimum elements may // be same if minimum element appears // more than once) // more than once) for (int i = 2; i < n; i++) { if (arr[i] < first_min) { second_min = first_min; first_min = arr[i]; } else if (arr[i] < second_min) second_min = arr[i]; } return first_min * second_min; } /* Driver program to test above function */ public static void main(String[] args) { int a[] = { 11, 8 , 5 , 7 , 5 , 100 }; int n = a.length; System.out.print(printMinimumProduct(a,n)); }} // This code is contributed by Arnav Kr. Mandal. # Python program to# calculate minimum# product of a pair # Function to calculate# minimum product# of pairdef printMinimumProduct(arr,n): # Initialize first and second # minimums. It is assumed that the # array has at least two elements. first_min = min(arr[0], arr[1]) second_min = max(arr[0], arr[1]) # Traverse remaining array and keep # track of two minimum elements (Note # that the two minimum elements may # be same if minimum element appears # more than once) # more than once) for i in range(2,n): if (arr[i] < first_min): second_min = first_min first_min = arr[i] else if (arr[i] < second_min): second_min = arr[i] return first_min * second_min # Driver code a= [ 11, 8 , 5 , 7 , 5 , 100 ]n = len(a) print(printMinimumProduct(a,n)) # This code is contributed# by Anant Agarwal. // C# program to calculate minimum// product of a pairusing System; class GFG { // Function to calculate minimum // product of pair static int printMinimumProduct(int []arr, int n) { // Initialize first and second // minimums. It is assumed that // the array has at least two // elements. int first_min = Math.Min(arr[0], arr[1]); int second_min = Math.Max(arr[0], arr[1]); // Traverse remaining array and // keep track of two minimum // elements (Note that the two // minimum elements may be same // if minimum element appears // more than once) for (int i = 2; i < n; i++) { if (arr[i] < first_min) { second_min = first_min; first_min = arr[i]; } else if (arr[i] < second_min) second_min = arr[i]; } return first_min * second_min; } /* Driver program to test above function */ public static void Main() { int []a = { 11, 8 , 5 , 7 , 5 , 100 }; int n = a.Length; Console.WriteLine( printMinimumProduct(a, n)); }} // This code is contributed by vt_m. <?php// PHP program to calculate minimum// product of a pair // Function to calculate minimum// product of pairfunction printMinimumProduct($arr, $n){ // Initialize first and second // minimums. It is assumed that the // array has at least two elements. $first_min = min($arr[0], $arr[1]); $second_min = max($arr[0], $arr[1]); // Traverse remaining array and keep // track of two minimum elements (Note // that the two minimum elements may // be same if minimum element appears // more than once) // more than once) for ($i = 2; $i < $n; $i++) { if ($arr[$i] < $first_min) { $second_min = $first_min; $first_min = $arr[$i]; } else if ($arr[$i] < $second_min) $second_min = $arr[$i]; } return $first_min * $second_min;} // Driver Code$a = array(11, 8 , 5 , 7 , 5 , 100);$n = sizeof($a);echo(printMinimumProduct($a, $n)); // This code is contributed by Ajit.?> <script> // Javascript program to calculate minimum// product of a pair // Function to calculate minimum product// of pairfunction printMinimumProduct(arr, n){ // Initialize first and second // minimums. It is assumed that the // array has at least two elements. let first_min = Math.min(arr[0], arr[1]); let second_min = Math.max(arr[0], arr[1]); // Traverse remaining array and keep // track of two minimum elements (Note // that the two minimum elements may // be same if minimum element appears // more than once) // more than once) for (let i=2; i<n; i++) { if (arr[i] < first_min) { second_min = first_min; first_min = arr[i]; } else if (arr[i] < second_min) second_min = arr[i]; } return first_min * second_min;} // Driver program to test above function let a = [ 11, 8 , 5 , 7 , 5 , 100 ]; let n = a.length; document.write(printMinimumProduct(a,n)); // This code is contributed by Mayank Tyagi </script> Output: 25 Time Complexity: O(n) Auxiliary Space: O(1) This article is contributed by Raja Vikramaditya. 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. vt_m jit_t mayanktyagi1709 surinderdawra388 Arrays Searching Sorting Arrays Searching Sorting Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Chocolate Distribution Problem Window Sliding Technique Reversal algorithm for array rotation Next Greater Element Find duplicates in O(n) time and O(1) extra space | Set 1 Binary Search Median of two sorted arrays of different sizes Find the index of an array element in Java Two Pointers Technique Count number of occurrences (or frequency) in a sorted array
[ { "code": null, "e": 26065, "s": 26037, "text": "\n17 Mar, 2022" }, { "code": null, "e": 26216, "s": 26065, "text": "Given an array of positive integers. We are required to write a program to print the minimum product of any two numbers of the given array.Examples: " }, { "code": null, "e": 26452, "s": 26216, "text": "Input : 11 8 5 7 5 100\nOutput : 25 \nExplanation : The minimum product of any \ntwo numbers will be 5 * 5 = 25.\n\nInput : 198 76 544 123 154 675 \nOutput : 7448\nExplanation : The minimum product of any \ntwo numbers will be 76 * 123 = 7448." }, { "code": null, "e": 27084, "s": 26454, "text": "Simple Approach : A simple approach will be to run two nested loops to generate all possible pair of elements and keep track of the minimum product. Time Complexity: O( n * n) Auxiliary Space: O( 1 )Better Approach: An efficient approach will be to first sort the given array and print the product of first two numbers, sorting will take O(n log n). Answer will be then a[0] * a[1] Time Complexity: O( n * log(n)) Auxiliary Space: O( 1 )Best Approach: The idea is linearly traverse given array and keep track of minimum two elements. Finally return product of two minimum elements.Below is the implementation of above approach. " }, { "code": null, "e": 27088, "s": 27084, "text": "C++" }, { "code": null, "e": 27093, "s": 27088, "text": "Java" }, { "code": null, "e": 27101, "s": 27093, "text": "Python3" }, { "code": null, "e": 27104, "s": 27101, "text": "C#" }, { "code": null, "e": 27108, "s": 27104, "text": "PHP" }, { "code": null, "e": 27119, "s": 27108, "text": "Javascript" }, { "code": "// C++ program to calculate minimum// product of a pair#include <bits/stdc++.h>using namespace std; // Function to calculate minimum product// of pairint printMinimumProduct(int arr[], int n){ // Initialize first and second // minimums. It is assumed that the // array has at least two elements. int first_min = min(arr[0], arr[1]); int second_min = max(arr[0], arr[1]); // Traverse remaining array and keep // track of two minimum elements (Note // that the two minimum elements may // be same if minimum element appears // more than once) // more than once) for (int i=2; i<n; i++) { if (arr[i] < first_min) { second_min = first_min; first_min = arr[i]; } else if (arr[i] < second_min) second_min = arr[i]; } return first_min * second_min;} // Driver program to test above functionint main(){ int a[] = { 11, 8 , 5 , 7 , 5 , 100 }; int n = sizeof(a) / sizeof(a[0]); cout << printMinimumProduct(a,n); return 0;}", "e": 28142, "s": 27119, "text": null }, { "code": "// Java program to calculate minimum// product of a pairimport java.util.*; class GFG { // Function to calculate minimum product // of pair static int printMinimumProduct(int arr[], int n) { // Initialize first and second // minimums. It is assumed that the // array has at least two elements. int first_min = Math.min(arr[0], arr[1]); int second_min = Math.max(arr[0], arr[1]); // Traverse remaining array and keep // track of two minimum elements (Note // that the two minimum elements may // be same if minimum element appears // more than once) // more than once) for (int i = 2; i < n; i++) { if (arr[i] < first_min) { second_min = first_min; first_min = arr[i]; } else if (arr[i] < second_min) second_min = arr[i]; } return first_min * second_min; } /* Driver program to test above function */ public static void main(String[] args) { int a[] = { 11, 8 , 5 , 7 , 5 , 100 }; int n = a.length; System.out.print(printMinimumProduct(a,n)); }} // This code is contributed by Arnav Kr. Mandal.", "e": 29396, "s": 28142, "text": null }, { "code": "# Python program to# calculate minimum# product of a pair # Function to calculate# minimum product# of pairdef printMinimumProduct(arr,n): # Initialize first and second # minimums. It is assumed that the # array has at least two elements. first_min = min(arr[0], arr[1]) second_min = max(arr[0], arr[1]) # Traverse remaining array and keep # track of two minimum elements (Note # that the two minimum elements may # be same if minimum element appears # more than once) # more than once) for i in range(2,n): if (arr[i] < first_min): second_min = first_min first_min = arr[i] else if (arr[i] < second_min): second_min = arr[i] return first_min * second_min # Driver code a= [ 11, 8 , 5 , 7 , 5 , 100 ]n = len(a) print(printMinimumProduct(a,n)) # This code is contributed# by Anant Agarwal.", "e": 30302, "s": 29396, "text": null }, { "code": "// C# program to calculate minimum// product of a pairusing System; class GFG { // Function to calculate minimum // product of pair static int printMinimumProduct(int []arr, int n) { // Initialize first and second // minimums. It is assumed that // the array has at least two // elements. int first_min = Math.Min(arr[0], arr[1]); int second_min = Math.Max(arr[0], arr[1]); // Traverse remaining array and // keep track of two minimum // elements (Note that the two // minimum elements may be same // if minimum element appears // more than once) for (int i = 2; i < n; i++) { if (arr[i] < first_min) { second_min = first_min; first_min = arr[i]; } else if (arr[i] < second_min) second_min = arr[i]; } return first_min * second_min; } /* Driver program to test above function */ public static void Main() { int []a = { 11, 8 , 5 , 7 , 5 , 100 }; int n = a.Length; Console.WriteLine( printMinimumProduct(a, n)); }} // This code is contributed by vt_m.", "e": 31726, "s": 30302, "text": null }, { "code": "<?php// PHP program to calculate minimum// product of a pair // Function to calculate minimum// product of pairfunction printMinimumProduct($arr, $n){ // Initialize first and second // minimums. It is assumed that the // array has at least two elements. $first_min = min($arr[0], $arr[1]); $second_min = max($arr[0], $arr[1]); // Traverse remaining array and keep // track of two minimum elements (Note // that the two minimum elements may // be same if minimum element appears // more than once) // more than once) for ($i = 2; $i < $n; $i++) { if ($arr[$i] < $first_min) { $second_min = $first_min; $first_min = $arr[$i]; } else if ($arr[$i] < $second_min) $second_min = $arr[$i]; } return $first_min * $second_min;} // Driver Code$a = array(11, 8 , 5 , 7 , 5 , 100);$n = sizeof($a);echo(printMinimumProduct($a, $n)); // This code is contributed by Ajit.?>", "e": 32698, "s": 31726, "text": null }, { "code": "<script> // Javascript program to calculate minimum// product of a pair // Function to calculate minimum product// of pairfunction printMinimumProduct(arr, n){ // Initialize first and second // minimums. It is assumed that the // array has at least two elements. let first_min = Math.min(arr[0], arr[1]); let second_min = Math.max(arr[0], arr[1]); // Traverse remaining array and keep // track of two minimum elements (Note // that the two minimum elements may // be same if minimum element appears // more than once) // more than once) for (let i=2; i<n; i++) { if (arr[i] < first_min) { second_min = first_min; first_min = arr[i]; } else if (arr[i] < second_min) second_min = arr[i]; } return first_min * second_min;} // Driver program to test above function let a = [ 11, 8 , 5 , 7 , 5 , 100 ]; let n = a.length; document.write(printMinimumProduct(a,n)); // This code is contributed by Mayank Tyagi </script>", "e": 33700, "s": 32698, "text": null }, { "code": null, "e": 33710, "s": 33700, "text": "Output: " }, { "code": null, "e": 33713, "s": 33710, "text": "25" }, { "code": null, "e": 34183, "s": 33713, "text": "Time Complexity: O(n) Auxiliary Space: O(1) This article is contributed by Raja Vikramaditya. 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": 34188, "s": 34183, "text": "vt_m" }, { "code": null, "e": 34194, "s": 34188, "text": "jit_t" }, { "code": null, "e": 34210, "s": 34194, "text": "mayanktyagi1709" }, { "code": null, "e": 34227, "s": 34210, "text": "surinderdawra388" }, { "code": null, "e": 34234, "s": 34227, "text": "Arrays" }, { "code": null, "e": 34244, "s": 34234, "text": "Searching" }, { "code": null, "e": 34252, "s": 34244, "text": "Sorting" }, { "code": null, "e": 34259, "s": 34252, "text": "Arrays" }, { "code": null, "e": 34269, "s": 34259, "text": "Searching" }, { "code": null, "e": 34277, "s": 34269, "text": "Sorting" }, { "code": null, "e": 34375, "s": 34277, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34406, "s": 34375, "text": "Chocolate Distribution Problem" }, { "code": null, "e": 34431, "s": 34406, "text": "Window Sliding Technique" }, { "code": null, "e": 34469, "s": 34431, "text": "Reversal algorithm for array rotation" }, { "code": null, "e": 34490, "s": 34469, "text": "Next Greater Element" }, { "code": null, "e": 34548, "s": 34490, "text": "Find duplicates in O(n) time and O(1) extra space | Set 1" }, { "code": null, "e": 34562, "s": 34548, "text": "Binary Search" }, { "code": null, "e": 34609, "s": 34562, "text": "Median of two sorted arrays of different sizes" }, { "code": null, "e": 34652, "s": 34609, "text": "Find the index of an array element in Java" }, { "code": null, "e": 34675, "s": 34652, "text": "Two Pointers Technique" } ]
How to select a random element from array in JavaScript ? - GeeksforGeeks
14 Jan, 2022 The task is to select the random element from the array using JavaScript.Approach 1: Use Math.random() function to get the random number between(0-1, 1 exclusive). Multiply it by the array length to get the numbers between(0-arrayLength). Use Math.floor() to get the index ranging from(0 to arrayLength-1). Example: This example implements the above approach. html <!DOCTYPE HTML><html> <head> <title> How to select a random element from array in JavaScript ? </title></head> <body style = "text-align:center;"> <h1 style = "color:green;"> GeeksForGeeks </h1> <p id = "GFG_UP" style = "font-size: 15px; font-weight: bold;"> </p> <button id = "button" onclick = "GFG_Fun()"> click here </button> <p id = "GFG_DOWN" style = "font-size: 24px; font-weight: bold; color: green;"> </p> <script> var up = document.getElementById('GFG_UP'); var down = document.getElementById('GFG_DOWN'); var arr = ["GFG_1", "GeeksForGeeks", "Geeks", "Computer Science Portal"]; up.innerHTML = "Click on the button to check " + "the type of element.<br><br>" + arr; function GFG_Fun() { down.innerHTML = arr[Math.floor(Math.random() * arr.length)]; } </script></body> </html> Output: Before clicking on the button: After clicking on the button: Approach 2: The random(a, b) method is used to generates a number between(a to b, b exclusive). Taking the floor value to range the numbers from (1 to arrayLength). Subtract 1 to get the index ranging from(0 to arrayLength-1). Example: This example implements the above approach. html <!DOCTYPE HTML><html> <head> <title> How to select a random element from array in JavaScript ? </title></head> <body style = "text-align:center;"> <h1 style = "color:green;"> GeeksForGeeks </h1> <p id = "GFG_UP" style = "font-size: 15px; font-weight: bold;"> </p> <button id = "button" onclick = "GFG_Fun()"> click here </button> <p id = "GFG_DOWN" style = "font-size: 24px; font-weight: bold; color: green;"> </p> <script> var up = document.getElementById('GFG_UP'); var down = document.getElementById('GFG_DOWN'); var arr = ["GFG_1", "GeeksForGeeks", "Geeks", "Computer Science Portal"]; up.innerHTML = "Click on the button to select" + " random element from the" + " array.<br><br>" + arr; function random(mn, mx) { return Math.random() * (mx - mn) + mn; } function GFG_Fun() { down.innerHTML = arr[Math.floor(random(1, 5))-1]; } </script></body> </html> Output: Before clicking on the button: After clicking on the button: JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples. sumitgumber28 javascript-array JavaScript Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. 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? 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 ? Top 10 Projects For Beginners To Practice HTML and CSS Skills
[ { "code": null, "e": 31331, "s": 31303, "text": "\n14 Jan, 2022" }, { "code": null, "e": 31417, "s": 31331, "text": "The task is to select the random element from the array using JavaScript.Approach 1: " }, { "code": null, "e": 31496, "s": 31417, "text": "Use Math.random() function to get the random number between(0-1, 1 exclusive)." }, { "code": null, "e": 31571, "s": 31496, "text": "Multiply it by the array length to get the numbers between(0-arrayLength)." }, { "code": null, "e": 31639, "s": 31571, "text": "Use Math.floor() to get the index ranging from(0 to arrayLength-1)." }, { "code": null, "e": 31694, "s": 31639, "text": "Example: This example implements the above approach. " }, { "code": null, "e": 31699, "s": 31694, "text": "html" }, { "code": "<!DOCTYPE HTML><html> <head> <title> How to select a random element from array in JavaScript ? </title></head> <body style = \"text-align:center;\"> <h1 style = \"color:green;\"> GeeksForGeeks </h1> <p id = \"GFG_UP\" style = \"font-size: 15px; font-weight: bold;\"> </p> <button id = \"button\" onclick = \"GFG_Fun()\"> click here </button> <p id = \"GFG_DOWN\" style = \"font-size: 24px; font-weight: bold; color: green;\"> </p> <script> var up = document.getElementById('GFG_UP'); var down = document.getElementById('GFG_DOWN'); var arr = [\"GFG_1\", \"GeeksForGeeks\", \"Geeks\", \"Computer Science Portal\"]; up.innerHTML = \"Click on the button to check \" + \"the type of element.<br><br>\" + arr; function GFG_Fun() { down.innerHTML = arr[Math.floor(Math.random() * arr.length)]; } </script></body> </html>", "e": 32713, "s": 31699, "text": null }, { "code": null, "e": 32722, "s": 32713, "text": "Output: " }, { "code": null, "e": 32753, "s": 32722, "text": "Before clicking on the button:" }, { "code": null, "e": 32784, "s": 32753, "text": "After clicking on the button: " }, { "code": null, "e": 32798, "s": 32784, "text": "Approach 2: " }, { "code": null, "e": 32882, "s": 32798, "text": "The random(a, b) method is used to generates a number between(a to b, b exclusive)." }, { "code": null, "e": 32951, "s": 32882, "text": "Taking the floor value to range the numbers from (1 to arrayLength)." }, { "code": null, "e": 33013, "s": 32951, "text": "Subtract 1 to get the index ranging from(0 to arrayLength-1)." }, { "code": null, "e": 33067, "s": 33013, "text": "Example: This example implements the above approach. " }, { "code": null, "e": 33072, "s": 33067, "text": "html" }, { "code": "<!DOCTYPE HTML><html> <head> <title> How to select a random element from array in JavaScript ? </title></head> <body style = \"text-align:center;\"> <h1 style = \"color:green;\"> GeeksForGeeks </h1> <p id = \"GFG_UP\" style = \"font-size: 15px; font-weight: bold;\"> </p> <button id = \"button\" onclick = \"GFG_Fun()\"> click here </button> <p id = \"GFG_DOWN\" style = \"font-size: 24px; font-weight: bold; color: green;\"> </p> <script> var up = document.getElementById('GFG_UP'); var down = document.getElementById('GFG_DOWN'); var arr = [\"GFG_1\", \"GeeksForGeeks\", \"Geeks\", \"Computer Science Portal\"]; up.innerHTML = \"Click on the button to select\" + \" random element from the\" + \" array.<br><br>\" + arr; function random(mn, mx) { return Math.random() * (mx - mn) + mn; } function GFG_Fun() { down.innerHTML = arr[Math.floor(random(1, 5))-1]; } </script></body> </html>", "e": 34208, "s": 33072, "text": null }, { "code": null, "e": 34217, "s": 34208, "text": "Output: " }, { "code": null, "e": 34249, "s": 34217, "text": "Before clicking on the button: " }, { "code": null, "e": 34280, "s": 34249, "text": "After clicking on the button: " }, { "code": null, "e": 34499, "s": 34280, "text": "JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples." }, { "code": null, "e": 34513, "s": 34499, "text": "sumitgumber28" }, { "code": null, "e": 34530, "s": 34513, "text": "javascript-array" }, { "code": null, "e": 34541, "s": 34530, "text": "JavaScript" }, { "code": null, "e": 34558, "s": 34541, "text": "Web Technologies" }, { "code": null, "e": 34585, "s": 34558, "text": "Web technologies Questions" }, { "code": null, "e": 34683, "s": 34585, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34723, "s": 34683, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 34768, "s": 34723, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 34829, "s": 34768, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 34901, "s": 34829, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 34970, "s": 34901, "text": "How to calculate the number of days between two dates in javascript?" }, { "code": null, "e": 35010, "s": 34970, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 35043, "s": 35010, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 35088, "s": 35043, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 35131, "s": 35088, "text": "How to fetch data from an API in ReactJS ?" } ]
Height of binary tree considering even level leaves only - GeeksforGeeks
27 Sep, 2021 Find the height of the binary tree given that only the nodes on the even levels are considered as the valid leaf nodes. The height of a binary tree is the number of edges between the tree’s root and its furthest leaf. But what if we bring a twist and change the definition of a leaf node. Let us define a valid leaf node as the node that has no children and is at an even level (considering root node as an odd level node). Output :Height of tree is 4 Solution : The approach to this problem is slightly different from the normal height finding approach. In the return step, we check if the node is a valid root node or not. If it is valid, return 1, else we return 0. Now in the recursive step- if the left and the right sub-tree both yield 0, the current node yields 0 too, because in that case there is no path from current node to a valid leaf node. But in case at least one of the values returned by the children is non-zero, it means the leaf node on that path is a valid leaf node, and hence that path can contribute to the final result, so we return max of the values returned + 1 for the current node. C++ Java Python3 C# Javascript /* Program to find height of the tree considering only even level leaves. */#include <bits/stdc++.h>using namespace std; /* A binary tree node has data, pointer to left child and a pointer to right child */struct Node { int data; struct Node* left; struct Node* right;}; int heightOfTreeUtil(Node* root, bool isEven){ // Base Case if (!root) return 0; if (!root->left && !root->right) { if (isEven) return 1; else return 0; } /*left stores the result of left subtree, and right stores the result of right subtree*/ int left = heightOfTreeUtil(root->left, !isEven); int right = heightOfTreeUtil(root->right, !isEven); /*If both left and right returns 0, it means there is no valid path till leaf node*/ if (left == 0 && right == 0) return 0; return (1 + max(left, right));} /* Helper function that allocates a new node with the given data and NULL left and right pointers. */struct Node* newNode(int data){ struct Node* node = (struct Node*)malloc(sizeof(struct Node)); node->data = data; node->left = NULL; node->right = NULL; return (node);} int heightOfTree(Node* root){ return heightOfTreeUtil(root, false);} /* Driver program to test above functions*/int main(){ // Let us create binary tree shown in above diagram struct Node* root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); root->left->right->left = newNode(6); cout << "Height of tree is " << heightOfTree(root); return 0;} /* Java Program to find height of the tree consideringonly even level leaves. */class GfG { /* A binary tree node has data, pointer toleft child and a pointer to right child */static class Node { int data; Node left; Node right;} static int heightOfTreeUtil(Node root, boolean isEven){ // Base Case if (root == null) return 0; if (root.left == null && root.right == null) { if (isEven == true) return 1; else return 0; } /*left stores the result of left subtree, and right stores the result of right subtree*/ int left = heightOfTreeUtil(root.left, !isEven); int right = heightOfTreeUtil(root.right, !isEven); /*If both left and right returns 0, it means there is no valid path till leaf node*/ if (left == 0 && right == 0) return 0; return (1 + Math.max(left, right));} /* Helper function that allocates a new node with thegiven data and NULL left and right pointers. */static Node newNode(int data){ Node node = new Node(); node.data = data; node.left = null; node.right = null; return (node);} static int heightOfTree(Node root){ return heightOfTreeUtil(root, false);} /* Driver program to test above functions*/public static void main(String[] args){ // Let us create binary tree shown in above diagram Node root = newNode(1); root.left = newNode(2); root.right = newNode(3); root.left.left = newNode(4); root.left.right = newNode(5); root.left.right.left = newNode(6); System.out.println("Height of tree is " + heightOfTree(root));}} # Program to find height of the tree considering# only even level leaves. # Helper class that allocates a new node with the# given data and None left and right pointers.class newNode: def __init__(self, data): self.data = data self.left = None self.right = None def heightOfTreeUtil(root, isEven): # Base Case if (not root): return 0 if (not root.left and not root.right): if (isEven): return 1 else: return 0 # left stores the result of left subtree, # and right stores the result of right subtree left = heightOfTreeUtil(root.left, not isEven) right = heightOfTreeUtil(root.right, not isEven) #If both left and right returns 0, it means # there is no valid path till leaf node if (left == 0 and right == 0): return 0 return (1 + max(left, right)) def heightOfTree(root): return heightOfTreeUtil(root, False) # Driver Codeif __name__ == '__main__': # Let us create binary tree shown # in above diagram root = newNode(1) root.left = newNode(2) root.right = newNode(3) root.left.left = newNode(4) root.left.right = newNode(5) root.left.right.left = newNode(6) print("Height of tree is", heightOfTree(root)) # This code is contributed by PranchalK /* C# Program to find height of the tree consideringonly even level leaves. */using System; class GfG{ /* A binary tree node has data, pointer to left child and a pointer to right child */ class Node { public int data; public Node left; public Node right; } static int heightOfTreeUtil(Node root, bool isEven) { // Base Case if (root == null) return 0; if (root.left == null && root.right == null) { if (isEven == true) return 1; else return 0; } /*left stores the result of left subtree, and right stores the result of right subtree*/ int left = heightOfTreeUtil(root.left, !isEven); int right = heightOfTreeUtil(root.right, !isEven); /*If both left and right returns 0, it means there is no valid path till leaf node*/ if (left == 0 && right == 0) return 0; return (1 + Math.Max(left, right)); } /* Helper function that allocates a new node with the given data and NULL left and right pointers. */ static Node newNode(int data) { Node node = new Node(); node.data = data; node.left = null; node.right = null; return (node); } static int heightOfTree(Node root) { return heightOfTreeUtil(root, false); } /* Driver code*/ public static void Main(String[] args) { // Let us create binary tree // shown in above diagram Node root = newNode(1); root.left = newNode(2); root.right = newNode(3); root.left.left = newNode(4); root.left.right = newNode(5); root.left.right.left = newNode(6); Console.WriteLine("Height of tree is " + heightOfTree(root)); }} /* This code is contributed by Rajput-Ji*/ <script>/* javascript Program to find height of the tree consideringonly even level leaves. */ /* * A binary tree node has data, pointer to left child and a pointer to right * child */ class Node { constructor(val) { this.data = val; this.left = null; this.right = null; } } function heightOfTreeUtil(root, isEven) { // Base Case if (root == null) return 0; if (root.left == null && root.right == null) { if (isEven == true) return 1; else return 0; } /* * left stores the result of left subtree, and right stores the result of right * subtree */ var left = heightOfTreeUtil(root.left, !isEven); var right = heightOfTreeUtil(root.right, !isEven); /* * If both left and right returns 0, it means there is no valid path till leaf * node */ if (left == 0 && right == 0) return 0; return (1 + Math.max(left, right)); } /* * Helper function that allocates a new node with the given data and NULL left * and right pointers. */ function newNode(data) {var node = new Node(); node.data = data; node.left = null; node.right = null; return (node); } function heightOfTree(root) { return heightOfTreeUtil(root, false); } /* Driver program to test above functions */ // Let us create binary tree shown in above diagramvar root = newNode(1); root.left = newNode(2); root.right = newNode(3); root.left.left = newNode(4); root.left.right = newNode(5); root.left.right.left = newNode(6); document.write("Height of tree is " + heightOfTree(root)); // This code is contributed by umadevi9616</script> Output: Height of tree is 4 Time Complexity:O(n) where n is number of nodes in given binary tree. YouTubeGeeksforGeeks507K subscribersHeight of binary tree considering even level leaves only | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 5:11•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=WpbCv5XoP9U" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> ?list=PLqM7alHXFySHCXD7r1J0ky9Zg_GBB1dbk prerna saini Rajput-Ji PranchalKatiyar umadevi9616 Tree Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Introduction to Tree Data Structure DFS traversal of a tree using recursion Top 50 Tree Coding Problems for Interviews Find the node with minimum value in a Binary Search Tree Real-time application of Data Structures Print Binary Tree in 2-Dimensions Find maximum (or minimum) in Binary Tree Difference between Min Heap and Max Heap Iterative Postorder Traversal | Set 2 (Using One Stack) Threaded Binary Tree
[ { "code": null, "e": 26185, "s": 26157, "text": "\n27 Sep, 2021" }, { "code": null, "e": 26611, "s": 26185, "text": "Find the height of the binary tree given that only the nodes on the even levels are considered as the valid leaf nodes. The height of a binary tree is the number of edges between the tree’s root and its furthest leaf. But what if we bring a twist and change the definition of a leaf node. Let us define a valid leaf node as the node that has no children and is at an even level (considering root node as an odd level node). " }, { "code": null, "e": 26640, "s": 26611, "text": "Output :Height of tree is 4 " }, { "code": null, "e": 27301, "s": 26640, "text": "Solution : The approach to this problem is slightly different from the normal height finding approach. In the return step, we check if the node is a valid root node or not. If it is valid, return 1, else we return 0. Now in the recursive step- if the left and the right sub-tree both yield 0, the current node yields 0 too, because in that case there is no path from current node to a valid leaf node. But in case at least one of the values returned by the children is non-zero, it means the leaf node on that path is a valid leaf node, and hence that path can contribute to the final result, so we return max of the values returned + 1 for the current node. " }, { "code": null, "e": 27307, "s": 27303, "text": "C++" }, { "code": null, "e": 27312, "s": 27307, "text": "Java" }, { "code": null, "e": 27320, "s": 27312, "text": "Python3" }, { "code": null, "e": 27323, "s": 27320, "text": "C#" }, { "code": null, "e": 27334, "s": 27323, "text": "Javascript" }, { "code": "/* Program to find height of the tree considering only even level leaves. */#include <bits/stdc++.h>using namespace std; /* A binary tree node has data, pointer to left child and a pointer to right child */struct Node { int data; struct Node* left; struct Node* right;}; int heightOfTreeUtil(Node* root, bool isEven){ // Base Case if (!root) return 0; if (!root->left && !root->right) { if (isEven) return 1; else return 0; } /*left stores the result of left subtree, and right stores the result of right subtree*/ int left = heightOfTreeUtil(root->left, !isEven); int right = heightOfTreeUtil(root->right, !isEven); /*If both left and right returns 0, it means there is no valid path till leaf node*/ if (left == 0 && right == 0) return 0; return (1 + max(left, right));} /* Helper function that allocates a new node with the given data and NULL left and right pointers. */struct Node* newNode(int data){ struct Node* node = (struct Node*)malloc(sizeof(struct Node)); node->data = data; node->left = NULL; node->right = NULL; return (node);} int heightOfTree(Node* root){ return heightOfTreeUtil(root, false);} /* Driver program to test above functions*/int main(){ // Let us create binary tree shown in above diagram struct Node* root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); root->left->right->left = newNode(6); cout << \"Height of tree is \" << heightOfTree(root); return 0;}", "e": 28969, "s": 27334, "text": null }, { "code": "/* Java Program to find height of the tree consideringonly even level leaves. */class GfG { /* A binary tree node has data, pointer toleft child and a pointer to right child */static class Node { int data; Node left; Node right;} static int heightOfTreeUtil(Node root, boolean isEven){ // Base Case if (root == null) return 0; if (root.left == null && root.right == null) { if (isEven == true) return 1; else return 0; } /*left stores the result of left subtree, and right stores the result of right subtree*/ int left = heightOfTreeUtil(root.left, !isEven); int right = heightOfTreeUtil(root.right, !isEven); /*If both left and right returns 0, it means there is no valid path till leaf node*/ if (left == 0 && right == 0) return 0; return (1 + Math.max(left, right));} /* Helper function that allocates a new node with thegiven data and NULL left and right pointers. */static Node newNode(int data){ Node node = new Node(); node.data = data; node.left = null; node.right = null; return (node);} static int heightOfTree(Node root){ return heightOfTreeUtil(root, false);} /* Driver program to test above functions*/public static void main(String[] args){ // Let us create binary tree shown in above diagram Node root = newNode(1); root.left = newNode(2); root.right = newNode(3); root.left.left = newNode(4); root.left.right = newNode(5); root.left.right.left = newNode(6); System.out.println(\"Height of tree is \" + heightOfTree(root));}}", "e": 30548, "s": 28969, "text": null }, { "code": "# Program to find height of the tree considering# only even level leaves. # Helper class that allocates a new node with the# given data and None left and right pointers.class newNode: def __init__(self, data): self.data = data self.left = None self.right = None def heightOfTreeUtil(root, isEven): # Base Case if (not root): return 0 if (not root.left and not root.right): if (isEven): return 1 else: return 0 # left stores the result of left subtree, # and right stores the result of right subtree left = heightOfTreeUtil(root.left, not isEven) right = heightOfTreeUtil(root.right, not isEven) #If both left and right returns 0, it means # there is no valid path till leaf node if (left == 0 and right == 0): return 0 return (1 + max(left, right)) def heightOfTree(root): return heightOfTreeUtil(root, False) # Driver Codeif __name__ == '__main__': # Let us create binary tree shown # in above diagram root = newNode(1) root.left = newNode(2) root.right = newNode(3) root.left.left = newNode(4) root.left.right = newNode(5) root.left.right.left = newNode(6) print(\"Height of tree is\", heightOfTree(root)) # This code is contributed by PranchalK", "e": 31856, "s": 30548, "text": null }, { "code": "/* C# Program to find height of the tree consideringonly even level leaves. */using System; class GfG{ /* A binary tree node has data, pointer to left child and a pointer to right child */ class Node { public int data; public Node left; public Node right; } static int heightOfTreeUtil(Node root, bool isEven) { // Base Case if (root == null) return 0; if (root.left == null && root.right == null) { if (isEven == true) return 1; else return 0; } /*left stores the result of left subtree, and right stores the result of right subtree*/ int left = heightOfTreeUtil(root.left, !isEven); int right = heightOfTreeUtil(root.right, !isEven); /*If both left and right returns 0, it means there is no valid path till leaf node*/ if (left == 0 && right == 0) return 0; return (1 + Math.Max(left, right)); } /* Helper function that allocates a new node with the given data and NULL left and right pointers. */ static Node newNode(int data) { Node node = new Node(); node.data = data; node.left = null; node.right = null; return (node); } static int heightOfTree(Node root) { return heightOfTreeUtil(root, false); } /* Driver code*/ public static void Main(String[] args) { // Let us create binary tree // shown in above diagram Node root = newNode(1); root.left = newNode(2); root.right = newNode(3); root.left.left = newNode(4); root.left.right = newNode(5); root.left.right.left = newNode(6); Console.WriteLine(\"Height of tree is \" + heightOfTree(root)); }} /* This code is contributed by Rajput-Ji*/", "e": 33779, "s": 31856, "text": null }, { "code": "<script>/* javascript Program to find height of the tree consideringonly even level leaves. */ /* * A binary tree node has data, pointer to left child and a pointer to right * child */ class Node { constructor(val) { this.data = val; this.left = null; this.right = null; } } function heightOfTreeUtil(root, isEven) { // Base Case if (root == null) return 0; if (root.left == null && root.right == null) { if (isEven == true) return 1; else return 0; } /* * left stores the result of left subtree, and right stores the result of right * subtree */ var left = heightOfTreeUtil(root.left, !isEven); var right = heightOfTreeUtil(root.right, !isEven); /* * If both left and right returns 0, it means there is no valid path till leaf * node */ if (left == 0 && right == 0) return 0; return (1 + Math.max(left, right)); } /* * Helper function that allocates a new node with the given data and NULL left * and right pointers. */ function newNode(data) {var node = new Node(); node.data = data; node.left = null; node.right = null; return (node); } function heightOfTree(root) { return heightOfTreeUtil(root, false); } /* Driver program to test above functions */ // Let us create binary tree shown in above diagramvar root = newNode(1); root.left = newNode(2); root.right = newNode(3); root.left.left = newNode(4); root.left.right = newNode(5); root.left.right.left = newNode(6); document.write(\"Height of tree is \" + heightOfTree(root)); // This code is contributed by umadevi9616</script>", "e": 35690, "s": 33779, "text": null }, { "code": null, "e": 35700, "s": 35690, "text": "Output: " }, { "code": null, "e": 35720, "s": 35700, "text": "Height of tree is 4" }, { "code": null, "e": 35792, "s": 35720, "text": "Time Complexity:O(n) where n is number of nodes in given binary tree. " }, { "code": null, "e": 36647, "s": 35792, "text": "YouTubeGeeksforGeeks507K subscribersHeight of binary tree considering even level leaves only | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 5:11•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=WpbCv5XoP9U\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>" }, { "code": null, "e": 36689, "s": 36647, "text": "?list=PLqM7alHXFySHCXD7r1J0ky9Zg_GBB1dbk " }, { "code": null, "e": 36702, "s": 36689, "text": "prerna saini" }, { "code": null, "e": 36712, "s": 36702, "text": "Rajput-Ji" }, { "code": null, "e": 36728, "s": 36712, "text": "PranchalKatiyar" }, { "code": null, "e": 36740, "s": 36728, "text": "umadevi9616" }, { "code": null, "e": 36745, "s": 36740, "text": "Tree" }, { "code": null, "e": 36750, "s": 36745, "text": "Tree" }, { "code": null, "e": 36848, "s": 36750, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 36884, "s": 36848, "text": "Introduction to Tree Data Structure" }, { "code": null, "e": 36924, "s": 36884, "text": "DFS traversal of a tree using recursion" }, { "code": null, "e": 36967, "s": 36924, "text": "Top 50 Tree Coding Problems for Interviews" }, { "code": null, "e": 37024, "s": 36967, "text": "Find the node with minimum value in a Binary Search Tree" }, { "code": null, "e": 37065, "s": 37024, "text": "Real-time application of Data Structures" }, { "code": null, "e": 37099, "s": 37065, "text": "Print Binary Tree in 2-Dimensions" }, { "code": null, "e": 37140, "s": 37099, "text": "Find maximum (or minimum) in Binary Tree" }, { "code": null, "e": 37181, "s": 37140, "text": "Difference between Min Heap and Max Heap" }, { "code": null, "e": 37237, "s": 37181, "text": "Iterative Postorder Traversal | Set 2 (Using One Stack)" } ]
p5.js | square() Function - GeeksforGeeks
17 Jan, 2020 The square() function is an inbuilt function in p5.js which is used to draw the square on the screen. A square contains four equal sides and four angles each of 90 degrees. It is the special case of a rectangle where width and height are equal. Syntax: square( x, y, s, tl, tr, br, bl ) Parameters: This function accept many parameters as mentioned above and described below: x: It is used to set the x-coordinate of square. y: It is used to set the y-coordinate of square. s: It is used to set the size of side of square. tl: It is optional parameter and used to set the radius of top-left corner. tr: It is optional parameter and used to set the radius of top-right corner. br: It is optional parameter and used to set the radius of bottom-right corner. bl: It is optional parameter and used to set the radius of bottom-left corner. Example 1: function setup() { // Create Canvas of given size createCanvas(300, 300); } function draw() { background(220); // Use color() function let c = color('green'); // Use fill() function to fill color fill(c); // Draw a square square(50, 50, 200); } Output: Example 2: function setup() { // Create Canvas of given size createCanvas(300, 300); } function draw() { background(220); // Use color() function let c = color('green'); // Use fill() function to fill color fill(c); // Draw a square square(50, 50, 200, 20); } Output: Example 3: function setup() { // Create Canvas of given size createCanvas(300, 300); } function draw() { background(220); // Use color() function let c = color('green'); // Use fill() function to fill color fill(c); // Draw a square square(50, 50, 200, 10, 20, 30, 40); } Output: Online editor: https://editor.p5js.org/Environment Setup: https://www.geeksforgeeks.org/p5-js-soundfile-object-installation-and-methods/ Reference: https://p5js.org/reference/#/p5/square JavaScript-p5.js JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Remove elements from a JavaScript Array Difference between var, let and const keywords in JavaScript Difference Between PUT and PATCH Request How to Use the JavaScript Fetch API to Get Data? JavaScript | Promises Remove elements from a JavaScript Array Installation of Node.js on Linux How to fetch data from an API in ReactJS ? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 25947, "s": 25919, "text": "\n17 Jan, 2020" }, { "code": null, "e": 26192, "s": 25947, "text": "The square() function is an inbuilt function in p5.js which is used to draw the square on the screen. A square contains four equal sides and four angles each of 90 degrees. It is the special case of a rectangle where width and height are equal." }, { "code": null, "e": 26200, "s": 26192, "text": "Syntax:" }, { "code": null, "e": 26234, "s": 26200, "text": "square( x, y, s, tl, tr, br, bl )" }, { "code": null, "e": 26323, "s": 26234, "text": "Parameters: This function accept many parameters as mentioned above and described below:" }, { "code": null, "e": 26372, "s": 26323, "text": "x: It is used to set the x-coordinate of square." }, { "code": null, "e": 26421, "s": 26372, "text": "y: It is used to set the y-coordinate of square." }, { "code": null, "e": 26470, "s": 26421, "text": "s: It is used to set the size of side of square." }, { "code": null, "e": 26546, "s": 26470, "text": "tl: It is optional parameter and used to set the radius of top-left corner." }, { "code": null, "e": 26623, "s": 26546, "text": "tr: It is optional parameter and used to set the radius of top-right corner." }, { "code": null, "e": 26703, "s": 26623, "text": "br: It is optional parameter and used to set the radius of bottom-right corner." }, { "code": null, "e": 26782, "s": 26703, "text": "bl: It is optional parameter and used to set the radius of bottom-left corner." }, { "code": null, "e": 26793, "s": 26782, "text": "Example 1:" }, { "code": "function setup() { // Create Canvas of given size createCanvas(300, 300); } function draw() { background(220); // Use color() function let c = color('green'); // Use fill() function to fill color fill(c); // Draw a square square(50, 50, 200); } ", "e": 27108, "s": 26793, "text": null }, { "code": null, "e": 27116, "s": 27108, "text": "Output:" }, { "code": null, "e": 27127, "s": 27116, "text": "Example 2:" }, { "code": "function setup() { // Create Canvas of given size createCanvas(300, 300); } function draw() { background(220); // Use color() function let c = color('green'); // Use fill() function to fill color fill(c); // Draw a square square(50, 50, 200, 20); } ", "e": 27446, "s": 27127, "text": null }, { "code": null, "e": 27454, "s": 27446, "text": "Output:" }, { "code": null, "e": 27465, "s": 27454, "text": "Example 3:" }, { "code": "function setup() { // Create Canvas of given size createCanvas(300, 300); } function draw() { background(220); // Use color() function let c = color('green'); // Use fill() function to fill color fill(c); // Draw a square square(50, 50, 200, 10, 20, 30, 40); } ", "e": 27796, "s": 27465, "text": null }, { "code": null, "e": 27804, "s": 27796, "text": "Output:" }, { "code": null, "e": 27941, "s": 27804, "text": "Online editor: https://editor.p5js.org/Environment Setup: https://www.geeksforgeeks.org/p5-js-soundfile-object-installation-and-methods/" }, { "code": null, "e": 27991, "s": 27941, "text": "Reference: https://p5js.org/reference/#/p5/square" }, { "code": null, "e": 28008, "s": 27991, "text": "JavaScript-p5.js" }, { "code": null, "e": 28019, "s": 28008, "text": "JavaScript" }, { "code": null, "e": 28036, "s": 28019, "text": "Web Technologies" }, { "code": null, "e": 28134, "s": 28036, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28174, "s": 28134, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 28235, "s": 28174, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 28276, "s": 28235, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 28325, "s": 28276, "text": "How to Use the JavaScript Fetch API to Get Data?" }, { "code": null, "e": 28347, "s": 28325, "text": "JavaScript | Promises" }, { "code": null, "e": 28387, "s": 28347, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 28420, "s": 28387, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 28463, "s": 28420, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 28525, "s": 28463, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" } ]
Lodash _.entries() Method - GeeksforGeeks
13 Apr, 2021 The _.entries() method is used to create an array of keyed-value pairs for the specified object. If object is a map or set, its entries are returned. Syntax: _.entries(object) Parameters: This method accepts single parameter as mentioned above and described below: object: This parameter holds the object to query. Return Value: This method returns the key-value pairs. Example 1: Javascript // Defining Lodash variableconst _ = require('lodash'); // Specifying a functionfunction gfg() { this.A = 5; this.B = 10; this.C = 15;} // Calling the _.entries() function_.entries(new gfg); Output: [ [ 'A', 5 ], [ 'B', 10 ], [ 'C', 15 ] ] Example 2: In the below code, a set is taken as the object, hence the function _.entries() returns its entries. Javascript // Defining Lodash variableconst _ = require('lodash'); // Initializing a setconst object = {a: {b: 1}}; // Calling the _.entries() function_.entries(object); Output: [ [ 'a', { b: 1 } ] ] Note: This will not work in normal JavaScript because it requires the lodash library to be installed. arorakashish0911 JavaScript-Lodash JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. 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? 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 ? Top 10 Projects For Beginners To Practice HTML and CSS Skills
[ { "code": null, "e": 38681, "s": 38653, "text": "\n13 Apr, 2021" }, { "code": null, "e": 38831, "s": 38681, "text": "The _.entries() method is used to create an array of keyed-value pairs for the specified object. If object is a map or set, its entries are returned." }, { "code": null, "e": 38839, "s": 38831, "text": "Syntax:" }, { "code": null, "e": 38857, "s": 38839, "text": "_.entries(object)" }, { "code": null, "e": 38946, "s": 38857, "text": "Parameters: This method accepts single parameter as mentioned above and described below:" }, { "code": null, "e": 38996, "s": 38946, "text": "object: This parameter holds the object to query." }, { "code": null, "e": 39051, "s": 38996, "text": "Return Value: This method returns the key-value pairs." }, { "code": null, "e": 39062, "s": 39051, "text": "Example 1:" }, { "code": null, "e": 39073, "s": 39062, "text": "Javascript" }, { "code": "// Defining Lodash variableconst _ = require('lodash'); // Specifying a functionfunction gfg() { this.A = 5; this.B = 10; this.C = 15;} // Calling the _.entries() function_.entries(new gfg);", "e": 39267, "s": 39073, "text": null }, { "code": null, "e": 39279, "s": 39271, "text": "Output:" }, { "code": null, "e": 39322, "s": 39281, "text": "[ [ 'A', 5 ], [ 'B', 10 ], [ 'C', 15 ] ]" }, { "code": null, "e": 39436, "s": 39324, "text": "Example 2: In the below code, a set is taken as the object, hence the function _.entries() returns its entries." }, { "code": null, "e": 39449, "s": 39438, "text": "Javascript" }, { "code": "// Defining Lodash variableconst _ = require('lodash'); // Initializing a setconst object = {a: {b: 1}}; // Calling the _.entries() function_.entries(object);", "e": 39608, "s": 39449, "text": null }, { "code": null, "e": 39620, "s": 39612, "text": "Output:" }, { "code": null, "e": 39644, "s": 39622, "text": "[ [ 'a', { b: 1 } ] ]" }, { "code": null, "e": 39748, "s": 39646, "text": "Note: This will not work in normal JavaScript because it requires the lodash library to be installed." }, { "code": null, "e": 39767, "s": 39750, "text": "arorakashish0911" }, { "code": null, "e": 39785, "s": 39767, "text": "JavaScript-Lodash" }, { "code": null, "e": 39796, "s": 39785, "text": "JavaScript" }, { "code": null, "e": 39813, "s": 39796, "text": "Web Technologies" }, { "code": null, "e": 39911, "s": 39813, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 39951, "s": 39911, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 39996, "s": 39951, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 40057, "s": 39996, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 40129, "s": 40057, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 40198, "s": 40129, "text": "How to calculate the number of days between two dates in javascript?" }, { "code": null, "e": 40238, "s": 40198, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 40271, "s": 40238, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 40316, "s": 40271, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 40359, "s": 40316, "text": "How to fetch data from an API in ReactJS ?" } ]
LinkedList remove() Method in Java - GeeksforGeeks
23 Nov, 2021 LinkedList as we all know is a way of storing data that contains sets of nodes where each node contains data and address part where address part is responsible for linking of nodes and hence forming a List over which now we can perform operations. Now here we want to remove a node/s using the remove() method of LinkedList class only. Illustration: Types of remove() method present inside this class: With no arguments insidePassing index as in argumentsPassing object as in arguments With no arguments inside Passing index as in arguments Passing object as in arguments let us discuss each of them alongside implementing by providing a clean java program which is as follows: It is used to remove an element from a linked list. The element is removed from the beginning or head of the linked list. Syntax: LinkedList.remove() Parameters: This function does not take any parameter. Return Value: This method returns the head of the list or the element present at the head of the list. Example: Java // Java Program to Illustrate remove() method// of LinkedList class// Default removal from the last of List // Importing required classesimport java.io.*;import java.util.LinkedList; // Main classpublic class GFG { // Main driver method public static void main(String args[]) { // Creating an empty LinkedList of String type LinkedList<String> list = new LinkedList<String>(); // Adding elements in the list // Using add() method list.add("Geeks"); list.add("for"); list.add("Geeks"); list.add("10"); list.add("20"); // Printing the elements inside LinkedList System.out.println("LinkedList:" + list); // Removing the head from List // using remove() method list.remove(); // Printing the final elements inside Linkedlist System.out.println("Final LinkedList:" + list); }} LinkedList:[Geeks, for, Geeks, 10, 20] Final LinkedList:[for, Geeks, 10, 20] It is used to remove an element from a linked list from a specific position or index. Syntax: LinkedList.remove(int index) Parameters: The parameter index is of integer data type and specifies the position of the element to be removed from the LinkedList. Return Value: The element that has just been removed from the list. Example Java // Java Program to Illustrate remove() when position of// element is passed as parameterimport java.io.*;import java.util.LinkedList; public class LinkedListDemo { public static void main(String args[]) { // Creating an empty LinkedList LinkedList<String> list = new LinkedList<String>(); // Use add() method to add elements in the list list.add("Geeks"); list.add("for"); list.add("Geeks"); list.add("10"); list.add("20"); // Output the list System.out.println("LinkedList:" + list); // Remove the head using remove() list.remove(4); // Print the final list System.out.println("Final LinkedList:" + list); }} LinkedList:[Geeks, for, Geeks, 10, 20] Final LinkedList:[Geeks, for, Geeks, 10] It is used to remove any particular element from the linked list. Syntax: LinkedList.remove(Object O) Parameters: The parameter O is of the object type of linked list and specifies the element to be removed from the list. Return Value: Returns true if the specified element is found in the list. Example Java // Java Program to Illustrate remove() method // Importing required classesimport java.io.*;import java.util.LinkedList; // Main classpublic class GFG { // Main driver method public static void main(String args[]) { // Creating an empty LinkedList of string type LinkedList<String> list = new LinkedList<String>(); // Adding elements in the list // using add() method list.add("Geeks"); list.add("for"); list.add("Geeks"); list.add("10"); list.add("20"); // Printing the elements before removal // inside above created LinkedList object System.out.println("LinkedList:" + list); // Removing the head // using remove() method list.remove("Geeks"); list.remove("20"); // Printing the final elements after removal // inside above LinkedList object System.out.println("Final LinkedList:" + list); }} LinkedList:[Geeks, for, Geeks, 10, 20] Final LinkedList:[for, Geeks, 10] solankimayank Java - util package Java-Collections Java-Functions java-LinkedList Java Java Java-Collections Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Object Oriented Programming (OOPs) Concept in Java HashMap in Java with Examples Stream In Java Interfaces in Java How to iterate any Map in Java Initialize an ArrayList in Java ArrayList in Java Stack Class in Java Singleton Class in Java Multidimensional Arrays in Java
[ { "code": null, "e": 26305, "s": 26277, "text": "\n23 Nov, 2021" }, { "code": null, "e": 26641, "s": 26305, "text": "LinkedList as we all know is a way of storing data that contains sets of nodes where each node contains data and address part where address part is responsible for linking of nodes and hence forming a List over which now we can perform operations. Now here we want to remove a node/s using the remove() method of LinkedList class only." }, { "code": null, "e": 26655, "s": 26641, "text": "Illustration:" }, { "code": null, "e": 26707, "s": 26655, "text": "Types of remove() method present inside this class:" }, { "code": null, "e": 26791, "s": 26707, "text": "With no arguments insidePassing index as in argumentsPassing object as in arguments" }, { "code": null, "e": 26816, "s": 26791, "text": "With no arguments inside" }, { "code": null, "e": 26846, "s": 26816, "text": "Passing index as in arguments" }, { "code": null, "e": 26877, "s": 26846, "text": "Passing object as in arguments" }, { "code": null, "e": 26984, "s": 26877, "text": "let us discuss each of them alongside implementing by providing a clean java program which is as follows: " }, { "code": null, "e": 27106, "s": 26984, "text": "It is used to remove an element from a linked list. The element is removed from the beginning or head of the linked list." }, { "code": null, "e": 27115, "s": 27106, "text": "Syntax: " }, { "code": null, "e": 27135, "s": 27115, "text": "LinkedList.remove()" }, { "code": null, "e": 27190, "s": 27135, "text": "Parameters: This function does not take any parameter." }, { "code": null, "e": 27293, "s": 27190, "text": "Return Value: This method returns the head of the list or the element present at the head of the list." }, { "code": null, "e": 27302, "s": 27293, "text": "Example:" }, { "code": null, "e": 27307, "s": 27302, "text": "Java" }, { "code": "// Java Program to Illustrate remove() method// of LinkedList class// Default removal from the last of List // Importing required classesimport java.io.*;import java.util.LinkedList; // Main classpublic class GFG { // Main driver method public static void main(String args[]) { // Creating an empty LinkedList of String type LinkedList<String> list = new LinkedList<String>(); // Adding elements in the list // Using add() method list.add(\"Geeks\"); list.add(\"for\"); list.add(\"Geeks\"); list.add(\"10\"); list.add(\"20\"); // Printing the elements inside LinkedList System.out.println(\"LinkedList:\" + list); // Removing the head from List // using remove() method list.remove(); // Printing the final elements inside Linkedlist System.out.println(\"Final LinkedList:\" + list); }}", "e": 28218, "s": 27307, "text": null }, { "code": null, "e": 28295, "s": 28218, "text": "LinkedList:[Geeks, for, Geeks, 10, 20]\nFinal LinkedList:[for, Geeks, 10, 20]" }, { "code": null, "e": 28383, "s": 28297, "text": "It is used to remove an element from a linked list from a specific position or index." }, { "code": null, "e": 28392, "s": 28383, "text": "Syntax: " }, { "code": null, "e": 28421, "s": 28392, "text": "LinkedList.remove(int index)" }, { "code": null, "e": 28554, "s": 28421, "text": "Parameters: The parameter index is of integer data type and specifies the position of the element to be removed from the LinkedList." }, { "code": null, "e": 28622, "s": 28554, "text": "Return Value: The element that has just been removed from the list." }, { "code": null, "e": 28630, "s": 28622, "text": "Example" }, { "code": null, "e": 28635, "s": 28630, "text": "Java" }, { "code": "// Java Program to Illustrate remove() when position of// element is passed as parameterimport java.io.*;import java.util.LinkedList; public class LinkedListDemo { public static void main(String args[]) { // Creating an empty LinkedList LinkedList<String> list = new LinkedList<String>(); // Use add() method to add elements in the list list.add(\"Geeks\"); list.add(\"for\"); list.add(\"Geeks\"); list.add(\"10\"); list.add(\"20\"); // Output the list System.out.println(\"LinkedList:\" + list); // Remove the head using remove() list.remove(4); // Print the final list System.out.println(\"Final LinkedList:\" + list); }}", "e": 29363, "s": 28635, "text": null }, { "code": null, "e": 29443, "s": 29363, "text": "LinkedList:[Geeks, for, Geeks, 10, 20]\nFinal LinkedList:[Geeks, for, Geeks, 10]" }, { "code": null, "e": 29511, "s": 29445, "text": "It is used to remove any particular element from the linked list." }, { "code": null, "e": 29520, "s": 29511, "text": "Syntax: " }, { "code": null, "e": 29548, "s": 29520, "text": "LinkedList.remove(Object O)" }, { "code": null, "e": 29668, "s": 29548, "text": "Parameters: The parameter O is of the object type of linked list and specifies the element to be removed from the list." }, { "code": null, "e": 29743, "s": 29668, "text": "Return Value: Returns true if the specified element is found in the list. " }, { "code": null, "e": 29751, "s": 29743, "text": "Example" }, { "code": null, "e": 29756, "s": 29751, "text": "Java" }, { "code": "// Java Program to Illustrate remove() method // Importing required classesimport java.io.*;import java.util.LinkedList; // Main classpublic class GFG { // Main driver method public static void main(String args[]) { // Creating an empty LinkedList of string type LinkedList<String> list = new LinkedList<String>(); // Adding elements in the list // using add() method list.add(\"Geeks\"); list.add(\"for\"); list.add(\"Geeks\"); list.add(\"10\"); list.add(\"20\"); // Printing the elements before removal // inside above created LinkedList object System.out.println(\"LinkedList:\" + list); // Removing the head // using remove() method list.remove(\"Geeks\"); list.remove(\"20\"); // Printing the final elements after removal // inside above LinkedList object System.out.println(\"Final LinkedList:\" + list); }}", "e": 30709, "s": 29756, "text": null }, { "code": null, "e": 30782, "s": 30709, "text": "LinkedList:[Geeks, for, Geeks, 10, 20]\nFinal LinkedList:[for, Geeks, 10]" }, { "code": null, "e": 30798, "s": 30784, "text": "solankimayank" }, { "code": null, "e": 30818, "s": 30798, "text": "Java - util package" }, { "code": null, "e": 30835, "s": 30818, "text": "Java-Collections" }, { "code": null, "e": 30850, "s": 30835, "text": "Java-Functions" }, { "code": null, "e": 30866, "s": 30850, "text": "java-LinkedList" }, { "code": null, "e": 30871, "s": 30866, "text": "Java" }, { "code": null, "e": 30876, "s": 30871, "text": "Java" }, { "code": null, "e": 30893, "s": 30876, "text": "Java-Collections" }, { "code": null, "e": 30991, "s": 30893, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31042, "s": 30991, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 31072, "s": 31042, "text": "HashMap in Java with Examples" }, { "code": null, "e": 31087, "s": 31072, "text": "Stream In Java" }, { "code": null, "e": 31106, "s": 31087, "text": "Interfaces in Java" }, { "code": null, "e": 31137, "s": 31106, "text": "How to iterate any Map in Java" }, { "code": null, "e": 31169, "s": 31137, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 31187, "s": 31169, "text": "ArrayList in Java" }, { "code": null, "e": 31207, "s": 31187, "text": "Stack Class in Java" }, { "code": null, "e": 31231, "s": 31207, "text": "Singleton Class in Java" } ]
Sum of the series 1 + (1+3) + (1+3+5) + (1+3+5+7) + ...... + (1+3+5+7+...+(2n-1))
20 Apr, 2021 Given a positive integer n. The problem is to find the sum of the given series 1 + (1+2) + (1+2+3) + (1+2+3+4) + ...... + (1+2+3+4+...+n), where i-th term in the series is the sum of first i odd natural numbers.Examples: Input : n = 2 Output : 5 (1) + (1+3) = 5 Input : n = 5 Output : 55 (1) + (1+3) + (1+3+5) + (1+3+5+7) + (1+3+5+7+9) = 55 Naive Approach: Using two loops get the sum of each i-th term and then add those sum to the final sum. C++ Java Python3 C# php Javascript // C++ implementation to find the// sum of the given series#include <bits/stdc++.h> using namespace std; // functionn to find the// sum of the given seriesint sumOfTheSeries(int n){ int sum = 0; for (int i = 1; i <= n; i++) { // first term of each i-th term int k = 1; for (int j = 1; j <= i; j++) { sum += k; // next term k += 2; } } // required sum return sum;} // Driver programint main(){ int n = 5; cout << "Sum = " << sumOfTheSeries(n); return 0;} // Java implementation to find// the sum of the given seriesimport java.util.*; class GFG { // functionn to find the sum // of the given series static int sumOfTheSeries(int n) { int sum = 0; for (int i = 1; i <= n; i++) { // first term of each // i-th term int k = 1; for (int j = 1; j <= i; j++) { sum += k; // next term k += 2; } } // required sum return sum; } /* Driver program */ public static void main(String[] args) { int n = 5; System.out.println("Sum = " + sumOfTheSeries(n)); }} // This code is contributed by Arnav Kr. Mandal. # Python3 implementation to find# the sum of the given series # functionn to find the sum# of the given seriesdef sumOfTheSeries( n ): sum = 0 for i in range(1, n + 1): # first term of each i-th term k = 1 for j in range(1,i+1): sum += k # next term k += 2 # required sum return sum # Driver programn = 5print("Sum =", sumOfTheSeries(n)) # This code is contributed by "Sharad_Bhardwaj". // C# implementation to find// the sum of the given seriesusing System; class GFG { // functionn to find the sum // of the given series static int sumOfTheSeries(int n) { int sum = 0; for (int i = 1; i <= n; i++) { // first term of each // i-th term int k = 1; for (int j = 1; j <= i; j++) { sum += k; // next term k += 2; } } // required sum return sum; } /* Driver program */ public static void Main() { int n = 5; Console.Write("Sum = " + sumOfTheSeries(n)); }} // This code is contributed by vt_m. <?php // php implementation to find the// sum of the given series // functionn to find the// sum of the given seriesfunction sumOfTheSeries($n){ $sum = 0; for ($i = 1; $i <= $n; $i++) { // first term of each i-th term $k = 1; for ($j = 1; $j <= $i; $j++) { $sum += $k; // next term $k += 2; } } // required sum return $sum;} // Driver program $n = 5; echo "Sum = " . sumOfTheSeries($n); // This code is contributed by Sam007?> <script> // Javascript implementation to find the// sum of the given series // functionn to find the// sum of the given seriesfunction sumOfTheSeries(n){ let sum = 0; for (let i = 1; i <= n; i++) { // first term of each i-th term let k = 1; for (let j = 1; j <= i; j++) { sum += k; // next term k += 2; } } // required sum return sum;} // Driver program let n = 5; document.write("Sum = " + sumOfTheSeries(n)); // This code is contributed by gfgking </script> Output: Sum = 55 Efficient Approach: Let an be the n-th term of the given series. an = (1 + 3 + 5 + 7 + (2n-1)) = sum of first n odd numbers = n2 Refer this post for the proof of above formula.Now, Refer this post for the proof of above formula. C++ Java Python3 C# PHP Javascript // C++ implementation to find the sum// of the given series#include <bits/stdc++.h>using namespace std; // functionn to find the sum// of the given seriesint sumOfTheSeries(int n){ // required sum return (n * (n + 1) / 2) * (2 * n + 1) / 3;} // Driver program to test aboveint main(){ int n = 5; cout << "Sum = " << sumOfTheSeries(n); return 0;} // Java implementation to find// the sum of the given seriesimport java.io.*; class GfG { // function to find the sum// of the given seriesstatic int sumOfTheSeries(int n){ // required sum return (n * (n + 1) / 2) * (2 * n + 1) / 3;} // Driver program to test abovepublic static void main (String[] args){ int n = 5; System.out.println("Sum = "+ sumOfTheSeries(n)); } } // This code is contributed by Gitanjali. # Python3 implementation to find# the sum of the given series # functionn to find the sum# of the given seriesdef sumOfTheSeries( n ): # required sum return int((n * (n + 1) / 2) * (2 * n + 1) / 3) # Driver program to test aboven = 5print("Sum =", sumOfTheSeries(n)) # This code is contributed by "Sharad_Bhardwaj". // C# implementation to find// the sum of the given seriesusing System; class GfG { // function to find the sum // of the given series static int sumOfTheSeries(int n) { // required sum return (n * (n + 1) / 2) * (2 * n + 1) / 3; } // Driver program to test above public static void Main() { int n = 5; Console.Write("Sum = " + sumOfTheSeries(n)); }} // This code is contributed by vt_m. <?php// PHP implementation to find the sum// of the given series // functionn to find the sum// of the given seriesfunction sumOfTheSeries($n){ // required sum return ($n * ($n + 1) / 2) * (2 * $n + 1) / 3;} // Driver Code $n = 5; echo "Sum = " . sumOfTheSeries($n); // This code is contributed by Sam007?> <script> // JavaScript program to find// the sum of the given series // function to find the sum // of the given series function sumOfTheSeries(n) { // required sum return (n * (n + 1) / 2) * (2 * n + 1) / 3; } // Driver Code let n = 5; document.write("Sum = " + sumOfTheSeries(n)); // This code is contributed by avijitmondal1998.</script> Output: Sum = 55 Sam007 avijitmondal1998 gfgking number-theory series Mathematical number-theory Mathematical series Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n20 Apr, 2021" }, { "code": null, "e": 275, "s": 52, "text": "Given a positive integer n. The problem is to find the sum of the given series 1 + (1+2) + (1+2+3) + (1+2+3+4) + ...... + (1+2+3+4+...+n), where i-th term in the series is the sum of first i odd natural numbers.Examples: " }, { "code": null, "e": 396, "s": 275, "text": "Input : n = 2\nOutput : 5\n(1) + (1+3) = 5\n\nInput : n = 5\nOutput : 55\n(1) + (1+3) + (1+3+5) + (1+3+5+7) + (1+3+5+7+9) = 55" }, { "code": null, "e": 502, "s": 398, "text": "Naive Approach: Using two loops get the sum of each i-th term and then add those sum to the final sum. " }, { "code": null, "e": 506, "s": 502, "text": "C++" }, { "code": null, "e": 511, "s": 506, "text": "Java" }, { "code": null, "e": 519, "s": 511, "text": "Python3" }, { "code": null, "e": 522, "s": 519, "text": "C#" }, { "code": null, "e": 526, "s": 522, "text": "php" }, { "code": null, "e": 537, "s": 526, "text": "Javascript" }, { "code": "// C++ implementation to find the// sum of the given series#include <bits/stdc++.h> using namespace std; // functionn to find the// sum of the given seriesint sumOfTheSeries(int n){ int sum = 0; for (int i = 1; i <= n; i++) { // first term of each i-th term int k = 1; for (int j = 1; j <= i; j++) { sum += k; // next term k += 2; } } // required sum return sum;} // Driver programint main(){ int n = 5; cout << \"Sum = \" << sumOfTheSeries(n); return 0;}", "e": 1087, "s": 537, "text": null }, { "code": "// Java implementation to find// the sum of the given seriesimport java.util.*; class GFG { // functionn to find the sum // of the given series static int sumOfTheSeries(int n) { int sum = 0; for (int i = 1; i <= n; i++) { // first term of each // i-th term int k = 1; for (int j = 1; j <= i; j++) { sum += k; // next term k += 2; } } // required sum return sum; } /* Driver program */ public static void main(String[] args) { int n = 5; System.out.println(\"Sum = \" + sumOfTheSeries(n)); }} // This code is contributed by Arnav Kr. Mandal.", "e": 1870, "s": 1087, "text": null }, { "code": "# Python3 implementation to find# the sum of the given series # functionn to find the sum# of the given seriesdef sumOfTheSeries( n ): sum = 0 for i in range(1, n + 1): # first term of each i-th term k = 1 for j in range(1,i+1): sum += k # next term k += 2 # required sum return sum # Driver programn = 5print(\"Sum =\", sumOfTheSeries(n)) # This code is contributed by \"Sharad_Bhardwaj\".", "e": 2362, "s": 1870, "text": null }, { "code": "// C# implementation to find// the sum of the given seriesusing System; class GFG { // functionn to find the sum // of the given series static int sumOfTheSeries(int n) { int sum = 0; for (int i = 1; i <= n; i++) { // first term of each // i-th term int k = 1; for (int j = 1; j <= i; j++) { sum += k; // next term k += 2; } } // required sum return sum; } /* Driver program */ public static void Main() { int n = 5; Console.Write(\"Sum = \" + sumOfTheSeries(n)); }} // This code is contributed by vt_m.", "e": 3065, "s": 2362, "text": null }, { "code": "<?php // php implementation to find the// sum of the given series // functionn to find the// sum of the given seriesfunction sumOfTheSeries($n){ $sum = 0; for ($i = 1; $i <= $n; $i++) { // first term of each i-th term $k = 1; for ($j = 1; $j <= $i; $j++) { $sum += $k; // next term $k += 2; } } // required sum return $sum;} // Driver program $n = 5; echo \"Sum = \" . sumOfTheSeries($n); // This code is contributed by Sam007?>", "e": 3589, "s": 3065, "text": null }, { "code": "<script> // Javascript implementation to find the// sum of the given series // functionn to find the// sum of the given seriesfunction sumOfTheSeries(n){ let sum = 0; for (let i = 1; i <= n; i++) { // first term of each i-th term let k = 1; for (let j = 1; j <= i; j++) { sum += k; // next term k += 2; } } // required sum return sum;} // Driver program let n = 5; document.write(\"Sum = \" + sumOfTheSeries(n)); // This code is contributed by gfgking </script>", "e": 4138, "s": 3589, "text": null }, { "code": null, "e": 4148, "s": 4138, "text": "Output: " }, { "code": null, "e": 4157, "s": 4148, "text": "Sum = 55" }, { "code": null, "e": 4224, "s": 4157, "text": "Efficient Approach: Let an be the n-th term of the given series. " }, { "code": null, "e": 4294, "s": 4224, "text": "an = (1 + 3 + 5 + 7 + (2n-1))\n = sum of first n odd numbers\n = n2" }, { "code": null, "e": 4348, "s": 4294, "text": "Refer this post for the proof of above formula.Now, " }, { "code": null, "e": 4397, "s": 4348, "text": "Refer this post for the proof of above formula. " }, { "code": null, "e": 4401, "s": 4397, "text": "C++" }, { "code": null, "e": 4406, "s": 4401, "text": "Java" }, { "code": null, "e": 4414, "s": 4406, "text": "Python3" }, { "code": null, "e": 4417, "s": 4414, "text": "C#" }, { "code": null, "e": 4421, "s": 4417, "text": "PHP" }, { "code": null, "e": 4432, "s": 4421, "text": "Javascript" }, { "code": "// C++ implementation to find the sum// of the given series#include <bits/stdc++.h>using namespace std; // functionn to find the sum// of the given seriesint sumOfTheSeries(int n){ // required sum return (n * (n + 1) / 2) * (2 * n + 1) / 3;} // Driver program to test aboveint main(){ int n = 5; cout << \"Sum = \" << sumOfTheSeries(n); return 0;}", "e": 4812, "s": 4432, "text": null }, { "code": "// Java implementation to find// the sum of the given seriesimport java.io.*; class GfG { // function to find the sum// of the given seriesstatic int sumOfTheSeries(int n){ // required sum return (n * (n + 1) / 2) * (2 * n + 1) / 3;} // Driver program to test abovepublic static void main (String[] args){ int n = 5; System.out.println(\"Sum = \"+ sumOfTheSeries(n)); } } // This code is contributed by Gitanjali.", "e": 5276, "s": 4812, "text": null }, { "code": "# Python3 implementation to find# the sum of the given series # functionn to find the sum# of the given seriesdef sumOfTheSeries( n ): # required sum return int((n * (n + 1) / 2) * (2 * n + 1) / 3) # Driver program to test aboven = 5print(\"Sum =\", sumOfTheSeries(n)) # This code is contributed by \"Sharad_Bhardwaj\".", "e": 5626, "s": 5276, "text": null }, { "code": "// C# implementation to find// the sum of the given seriesusing System; class GfG { // function to find the sum // of the given series static int sumOfTheSeries(int n) { // required sum return (n * (n + 1) / 2) * (2 * n + 1) / 3; } // Driver program to test above public static void Main() { int n = 5; Console.Write(\"Sum = \" + sumOfTheSeries(n)); }} // This code is contributed by vt_m.", "e": 6111, "s": 5626, "text": null }, { "code": "<?php// PHP implementation to find the sum// of the given series // functionn to find the sum// of the given seriesfunction sumOfTheSeries($n){ // required sum return ($n * ($n + 1) / 2) * (2 * $n + 1) / 3;} // Driver Code $n = 5; echo \"Sum = \" . sumOfTheSeries($n); // This code is contributed by Sam007?>", "e": 6467, "s": 6111, "text": null }, { "code": "<script> // JavaScript program to find// the sum of the given series // function to find the sum // of the given series function sumOfTheSeries(n) { // required sum return (n * (n + 1) / 2) * (2 * n + 1) / 3; } // Driver Code let n = 5; document.write(\"Sum = \" + sumOfTheSeries(n)); // This code is contributed by avijitmondal1998.</script>", "e": 6907, "s": 6467, "text": null }, { "code": null, "e": 6917, "s": 6907, "text": "Output: " }, { "code": null, "e": 6926, "s": 6917, "text": "Sum = 55" }, { "code": null, "e": 6935, "s": 6928, "text": "Sam007" }, { "code": null, "e": 6952, "s": 6935, "text": "avijitmondal1998" }, { "code": null, "e": 6960, "s": 6952, "text": "gfgking" }, { "code": null, "e": 6974, "s": 6960, "text": "number-theory" }, { "code": null, "e": 6981, "s": 6974, "text": "series" }, { "code": null, "e": 6994, "s": 6981, "text": "Mathematical" }, { "code": null, "e": 7008, "s": 6994, "text": "number-theory" }, { "code": null, "e": 7021, "s": 7008, "text": "Mathematical" }, { "code": null, "e": 7028, "s": 7021, "text": "series" } ]
Maximum number of prime factors a number can have with exactly x factors
05 Nov, 2021 Given an integer X, denoting the number of factors of a positive integer N can have. The task is to find the maximum number of distinct prime factors the number N can have. Examples: Input: X = 9 Output: 2 Explanation: Some of the possible numbers having 9 factors are: 256: 1, 2, 4, 8, 16, 32, 64, 128, 256 Number of prime factors = 1 36: 1, 2, 3, 4, 6, 9, 12, 18, 36 Number of prime factors = 2 Input: X = 8 Output: 3 Some of the numbers having 8 factors are: 128 : 1, 2, 4, 8, 16, 32, 64, 128 Number of prime factors = 1 24 : 1, 2, 3, 4, 6, 8, 12, 24 Number of prime factors = 2 30 : 1, 2, 3, 5, 6, 10, 15, 30 Number of prime factors = 3 Approach: The key observation in the problem is, any positive natural number can be represented as product of its prime factors as follows: // Number can be represented as product // prime factors as follows // Total number of factors of N can be // defined as follows Number of Factors = (p+1) * (q+1) * (r+1).. In the above problem, the number of factors are given which can be used to find the maximum prime factors possible for a number with the given count of factors as follows: If X can be expressed as product of K numbers then we have at most K primes in X. In Order to split X as product of maximum number of values, all the values should be prime. X = (p+1) * (q+1) * (r+1) // So the maximum number of prime // factors of the given number greater // than 1 can lead to a number N. Let's say X = 12 X = 2 * 2 * 3 Then possible N can be: N = a(2-1) * b(2-1) * c(3-1) N = a1 * b1 * c2 // Here a, b, and c can be any distinct prime // numbers to get the possible value of N N = 21 * 31 * 52 N = 150 let's say X = 8 X = 2 * 2 * 2 N = 21 * 31 * 51 N = 30 Therefore, the maximum count of prime divisors of a number can have is the count of the prime factors (can be repetitive also) in the factorization of the count of factors of the number. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ implementation to find the// maximum count of the prime factors// by the count of factors of number #include <iostream>#include <math.h> using namespace std; // Function to count number// of prime factors of xint countPrimeFactors(int n){ if (n == 1) return 0; // Count variable is // incremented for every // prime factor of x int cnt = 0; while (n % 2 == 0) { cnt++; n = n / 2; } // Loop to count the number // of the prime factors of // the given number for (int i = 3; i <= sqrt(n); i += 2) { while (n % i == 0) { cnt++; n = n / i; } } if (n > 2) cnt++; return cnt;} // Driver Codeint main(){ int x = 8; int prime_factor_cnt = countPrimeFactors(x); cout << prime_factor_cnt << endl; return 0;} // Java implementation to find the// maximum count of the prime factors// by the count of factors of numberclass GFG { // Function to count number // of prime factors of x static int countPrimeFactors(int n) { if (n == 1) return 0; // Count variable is // incremented form every // prime factor of x int cnt = 0; while (n % 2 == 0) { cnt++; n = n / 2; } // Loop to count the number // of the prime factors of // the given number for (int i = 3; i <= Math.sqrt(n); i += 2) { while (n % i == 0) { cnt++; n = n / i; } } if (n > 2) cnt++; return cnt; } // Driver Code public static void main(String[] args) { int x = 8; int prime_factor_cnt = countPrimeFactors(x); System.out.print(prime_factor_cnt + "\n"); }} // This code is contributed by Princi Singh # Python3 implementation to find the# maximum count of the prime factors# by the count of factors of numberimport math # Function to count number# of prime factors of xdef countPrimeFactors(n): if (n == 1): return 0 # Count variable is # incremented form every # prime factor of x cnt = 0 while (n % 2 == 0): cnt += 1 n = n // 2 # Loop to count the number # of the prime factors of # the given number for i in range(3, int(math.sqrt(n)) + 1, 2): while (n % i == 0): cnt += 1 n = n // i if (n > 2): cnt += 1 return cnt # Driver Codex = 8prime_factor_cnt = countPrimeFactors(x) print(prime_factor_cnt) # This code is contributed by ShubhamCoder // C# implementation to find the// maximum count of the prime factors// by the count of factors of numberusing System; class GFG { // Function to count number // of prime factors of x static int countPrimeFactors(int n) { if (n == 1) return 0; // Count variable is // incremented form every // prime factor of x int cnt = 0; while (n % 2 == 0) { cnt++; n = n / 2; } // Loop to count the number // of the prime factors of // the given number for (int i = 3; i <= Math.Sqrt(n); i += 2) { while (n % i == 0) { cnt++; n = n / i; } } if (n > 2) cnt++; return cnt; } // Driver Code static public void Main() { int x = 8; int prime_factor_cnt = countPrimeFactors(x); Console.Write(prime_factor_cnt); }} // This code is contributed by ShubhamCoder <script> // Javascript implementation to find the// maximum count of the prime factors// by the count of factors of number // Function to count number// of prime factors of xfunction countPrimeFactors(n){ if (n == 1) return 0; // Count variable is // incremented for every // prime factor of x let cnt = 0; while (n % 2 == 0) { cnt++; n = parseInt(n / 2); } // Loop to count the number // of the prime factors of // the given number for(let i = 3; i <= Math.sqrt(n); i += 2) { while (n % i == 0) { cnt++; n = parseInt(n / i); } } if (n > 2) cnt++; return cnt;} // Driver Codelet x = 8;let prime_factor_cnt = countPrimeFactors(x); document.write(prime_factor_cnt); // This code is contributed by souravmahato348 </script> 3 Time Complexity: O(N1/2) Auxiliary Space: O(1) princi singh shubhamsingh84100 aishwary191 souravmahato348 simmytarika5 rohitsingh07052 prime-factor Algorithms Combinatorial Competitive Programming Mathematical Mathematical Combinatorial Algorithms Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n05 Nov, 2021" }, { "code": null, "e": 202, "s": 28, "text": "Given an integer X, denoting the number of factors of a positive integer N can have. The task is to find the maximum number of distinct prime factors the number N can have. " }, { "code": null, "e": 213, "s": 202, "text": "Examples: " }, { "code": null, "e": 427, "s": 213, "text": "Input: X = 9 Output: 2 Explanation: Some of the possible numbers having 9 factors are: 256: 1, 2, 4, 8, 16, 32, 64, 128, 256 Number of prime factors = 1 36: 1, 2, 3, 4, 6, 9, 12, 18, 36 Number of prime factors = 2" }, { "code": null, "e": 673, "s": 427, "text": "Input: X = 8 Output: 3 Some of the numbers having 8 factors are: 128 : 1, 2, 4, 8, 16, 32, 64, 128 Number of prime factors = 1 24 : 1, 2, 3, 4, 6, 8, 12, 24 Number of prime factors = 2 30 : 1, 2, 3, 5, 6, 10, 15, 30 Number of prime factors = 3 " }, { "code": null, "e": 815, "s": 673, "text": "Approach: The key observation in the problem is, any positive natural number can be represented as product of its prime factors as follows: " }, { "code": null, "e": 991, "s": 815, "text": "// Number can be represented as product\n// prime factors as follows\n\n\n// Total number of factors of N can be \n// defined as follows\nNumber of Factors = (p+1) * (q+1) * (r+1).." }, { "code": null, "e": 1165, "s": 991, "text": "In the above problem, the number of factors are given which can be used to find the maximum prime factors possible for a number with the given count of factors as follows: " }, { "code": null, "e": 1745, "s": 1165, "text": "If X can be expressed as product of K numbers then we have at most K primes in X.\nIn Order to split X as product of maximum number of values,\nall the values should be prime.\n\nX = (p+1) * (q+1) * (r+1)\n\n// So the maximum number of prime\n// factors of the given number greater\n// than 1 can lead to a number N.\nLet's say X = 12\nX = 2 * 2 * 3\nThen possible N can be:\nN = a(2-1) * b(2-1) * c(3-1)\nN = a1 * b1 * c2\n\n// Here a, b, and c can be any distinct prime\n// numbers to get the possible value of N\nN = 21 * 31 * 52\nN = 150\n\nlet's say X = 8\nX = 2 * 2 * 2\nN = 21 * 31 * 51\nN = 30" }, { "code": null, "e": 1932, "s": 1745, "text": "Therefore, the maximum count of prime divisors of a number can have is the count of the prime factors (can be repetitive also) in the factorization of the count of factors of the number." }, { "code": null, "e": 1985, "s": 1932, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 1989, "s": 1985, "text": "C++" }, { "code": null, "e": 1994, "s": 1989, "text": "Java" }, { "code": null, "e": 2002, "s": 1994, "text": "Python3" }, { "code": null, "e": 2005, "s": 2002, "text": "C#" }, { "code": null, "e": 2016, "s": 2005, "text": "Javascript" }, { "code": "// C++ implementation to find the// maximum count of the prime factors// by the count of factors of number #include <iostream>#include <math.h> using namespace std; // Function to count number// of prime factors of xint countPrimeFactors(int n){ if (n == 1) return 0; // Count variable is // incremented for every // prime factor of x int cnt = 0; while (n % 2 == 0) { cnt++; n = n / 2; } // Loop to count the number // of the prime factors of // the given number for (int i = 3; i <= sqrt(n); i += 2) { while (n % i == 0) { cnt++; n = n / i; } } if (n > 2) cnt++; return cnt;} // Driver Codeint main(){ int x = 8; int prime_factor_cnt = countPrimeFactors(x); cout << prime_factor_cnt << endl; return 0;}", "e": 2851, "s": 2016, "text": null }, { "code": "// Java implementation to find the// maximum count of the prime factors// by the count of factors of numberclass GFG { // Function to count number // of prime factors of x static int countPrimeFactors(int n) { if (n == 1) return 0; // Count variable is // incremented form every // prime factor of x int cnt = 0; while (n % 2 == 0) { cnt++; n = n / 2; } // Loop to count the number // of the prime factors of // the given number for (int i = 3; i <= Math.sqrt(n); i += 2) { while (n % i == 0) { cnt++; n = n / i; } } if (n > 2) cnt++; return cnt; } // Driver Code public static void main(String[] args) { int x = 8; int prime_factor_cnt = countPrimeFactors(x); System.out.print(prime_factor_cnt + \"\\n\"); }} // This code is contributed by Princi Singh", "e": 3849, "s": 2851, "text": null }, { "code": "# Python3 implementation to find the# maximum count of the prime factors# by the count of factors of numberimport math # Function to count number# of prime factors of xdef countPrimeFactors(n): if (n == 1): return 0 # Count variable is # incremented form every # prime factor of x cnt = 0 while (n % 2 == 0): cnt += 1 n = n // 2 # Loop to count the number # of the prime factors of # the given number for i in range(3, int(math.sqrt(n)) + 1, 2): while (n % i == 0): cnt += 1 n = n // i if (n > 2): cnt += 1 return cnt # Driver Codex = 8prime_factor_cnt = countPrimeFactors(x) print(prime_factor_cnt) # This code is contributed by ShubhamCoder", "e": 4623, "s": 3849, "text": null }, { "code": "// C# implementation to find the// maximum count of the prime factors// by the count of factors of numberusing System; class GFG { // Function to count number // of prime factors of x static int countPrimeFactors(int n) { if (n == 1) return 0; // Count variable is // incremented form every // prime factor of x int cnt = 0; while (n % 2 == 0) { cnt++; n = n / 2; } // Loop to count the number // of the prime factors of // the given number for (int i = 3; i <= Math.Sqrt(n); i += 2) { while (n % i == 0) { cnt++; n = n / i; } } if (n > 2) cnt++; return cnt; } // Driver Code static public void Main() { int x = 8; int prime_factor_cnt = countPrimeFactors(x); Console.Write(prime_factor_cnt); }} // This code is contributed by ShubhamCoder", "e": 5623, "s": 4623, "text": null }, { "code": "<script> // Javascript implementation to find the// maximum count of the prime factors// by the count of factors of number // Function to count number// of prime factors of xfunction countPrimeFactors(n){ if (n == 1) return 0; // Count variable is // incremented for every // prime factor of x let cnt = 0; while (n % 2 == 0) { cnt++; n = parseInt(n / 2); } // Loop to count the number // of the prime factors of // the given number for(let i = 3; i <= Math.sqrt(n); i += 2) { while (n % i == 0) { cnt++; n = parseInt(n / i); } } if (n > 2) cnt++; return cnt;} // Driver Codelet x = 8;let prime_factor_cnt = countPrimeFactors(x); document.write(prime_factor_cnt); // This code is contributed by souravmahato348 </script>", "e": 6472, "s": 5623, "text": null }, { "code": null, "e": 6474, "s": 6472, "text": "3" }, { "code": null, "e": 6502, "s": 6476, "text": "Time Complexity: O(N1/2)" }, { "code": null, "e": 6524, "s": 6502, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 6537, "s": 6524, "text": "princi singh" }, { "code": null, "e": 6555, "s": 6537, "text": "shubhamsingh84100" }, { "code": null, "e": 6567, "s": 6555, "text": "aishwary191" }, { "code": null, "e": 6583, "s": 6567, "text": "souravmahato348" }, { "code": null, "e": 6596, "s": 6583, "text": "simmytarika5" }, { "code": null, "e": 6612, "s": 6596, "text": "rohitsingh07052" }, { "code": null, "e": 6625, "s": 6612, "text": "prime-factor" }, { "code": null, "e": 6636, "s": 6625, "text": "Algorithms" }, { "code": null, "e": 6650, "s": 6636, "text": "Combinatorial" }, { "code": null, "e": 6674, "s": 6650, "text": "Competitive Programming" }, { "code": null, "e": 6687, "s": 6674, "text": "Mathematical" }, { "code": null, "e": 6700, "s": 6687, "text": "Mathematical" }, { "code": null, "e": 6714, "s": 6700, "text": "Combinatorial" }, { "code": null, "e": 6725, "s": 6714, "text": "Algorithms" } ]
Implementing of strtok() function in C++
12 Dec, 2021 The strtok() function is used in tokenizing a string based on a delimiter. It is present in the header file “string.h” and returns a pointer to the next token if present, if the next token is not present it returns NULL. To get all the tokens the idea is to call this function in a loop. Header File: #include <string.h> Syntax: char *strtok(char *s1, const char *s2); In this article, we will discuss the implementation of this function in which two things must be taken into consideration: Maintain the state of the string to make sure how many tokens we have already extracted. Secondly, maintain the list of extracted tokens in an array to return it. Steps: Create a function strtok() which accepts string and delimiter as an argument and return char pointer. Create a static variable input to maintain the state of the string. Check if extracting the tokens for the first time then initialize the input with it. If the input is NULL and all the tokens are extracted then return NULL. In this step, start extracting tokens and store them in the array result[]. Now, iterate a loop until NULL occurs or the delimiter then return the result by including ‘\0’. When the end of the string is reached and if it requires then manually add a ‘\0‘ and include this corner case in the end. Below is the implementation of the same: C++ // C++ program to demonstrate the function// strtok() to tokenized the string#include <bits/stdc++.h>using namespace std;char* mystrtok(char* s, char d){ // Stores the state of string static char* input = NULL; // Initialize the input string if (s != NULL) input = s; // Case for final token if (input == NULL) return NULL; // Stores the extracted string char* result = new char[strlen(input) + 1]; int i = 0; // Start extracting string and // store it in array for (; input[i] != '\0'; i++) { // If delimiter is not reached // then add the current character // to result[i] if (input[i] != d) result[i] = input[i]; // Else store the string formed else { result[i] = '\0'; input = input + i + 1; return result; } } // Case when loop ends result[i] = '\0'; input = NULL; // Return the resultant pointer // to the string return result;} // Driver Codeint main(){ // Given string str char str[90] = "It, is my, day"; // Tokenized the first string char* ptr = mystrtok(str, ' '); // Print current tokenized string cout << ptr << endl; // While ptr is not NULL while (ptr != NULL) { // Tokenize the string ptr = mystrtok(NULL, ' '); // Print the string cout << ptr << endl; } return 0;} It, is my, day saurabh1990aror CPP-Library cpp-string C++ C++ Programs Strings Strings CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n12 Dec, 2021" }, { "code": null, "e": 342, "s": 54, "text": "The strtok() function is used in tokenizing a string based on a delimiter. It is present in the header file “string.h” and returns a pointer to the next token if present, if the next token is not present it returns NULL. To get all the tokens the idea is to call this function in a loop." }, { "code": null, "e": 355, "s": 342, "text": "Header File:" }, { "code": null, "e": 375, "s": 355, "text": "#include <string.h>" }, { "code": null, "e": 384, "s": 375, "text": "Syntax: " }, { "code": null, "e": 424, "s": 384, "text": "char *strtok(char *s1, const char *s2);" }, { "code": null, "e": 547, "s": 424, "text": "In this article, we will discuss the implementation of this function in which two things must be taken into consideration:" }, { "code": null, "e": 636, "s": 547, "text": "Maintain the state of the string to make sure how many tokens we have already extracted." }, { "code": null, "e": 710, "s": 636, "text": "Secondly, maintain the list of extracted tokens in an array to return it." }, { "code": null, "e": 717, "s": 710, "text": "Steps:" }, { "code": null, "e": 819, "s": 717, "text": "Create a function strtok() which accepts string and delimiter as an argument and return char pointer." }, { "code": null, "e": 887, "s": 819, "text": "Create a static variable input to maintain the state of the string." }, { "code": null, "e": 972, "s": 887, "text": "Check if extracting the tokens for the first time then initialize the input with it." }, { "code": null, "e": 1044, "s": 972, "text": "If the input is NULL and all the tokens are extracted then return NULL." }, { "code": null, "e": 1120, "s": 1044, "text": "In this step, start extracting tokens and store them in the array result[]." }, { "code": null, "e": 1217, "s": 1120, "text": "Now, iterate a loop until NULL occurs or the delimiter then return the result by including ‘\\0’." }, { "code": null, "e": 1340, "s": 1217, "text": "When the end of the string is reached and if it requires then manually add a ‘\\0‘ and include this corner case in the end." }, { "code": null, "e": 1381, "s": 1340, "text": "Below is the implementation of the same:" }, { "code": null, "e": 1385, "s": 1381, "text": "C++" }, { "code": "// C++ program to demonstrate the function// strtok() to tokenized the string#include <bits/stdc++.h>using namespace std;char* mystrtok(char* s, char d){ // Stores the state of string static char* input = NULL; // Initialize the input string if (s != NULL) input = s; // Case for final token if (input == NULL) return NULL; // Stores the extracted string char* result = new char[strlen(input) + 1]; int i = 0; // Start extracting string and // store it in array for (; input[i] != '\\0'; i++) { // If delimiter is not reached // then add the current character // to result[i] if (input[i] != d) result[i] = input[i]; // Else store the string formed else { result[i] = '\\0'; input = input + i + 1; return result; } } // Case when loop ends result[i] = '\\0'; input = NULL; // Return the resultant pointer // to the string return result;} // Driver Codeint main(){ // Given string str char str[90] = \"It, is my, day\"; // Tokenized the first string char* ptr = mystrtok(str, ' '); // Print current tokenized string cout << ptr << endl; // While ptr is not NULL while (ptr != NULL) { // Tokenize the string ptr = mystrtok(NULL, ' '); // Print the string cout << ptr << endl; } return 0;}", "e": 2801, "s": 1385, "text": null }, { "code": null, "e": 2816, "s": 2801, "text": "It,\nis\nmy,\nday" }, { "code": null, "e": 2834, "s": 2818, "text": "saurabh1990aror" }, { "code": null, "e": 2846, "s": 2834, "text": "CPP-Library" }, { "code": null, "e": 2857, "s": 2846, "text": "cpp-string" }, { "code": null, "e": 2861, "s": 2857, "text": "C++" }, { "code": null, "e": 2874, "s": 2861, "text": "C++ Programs" }, { "code": null, "e": 2882, "s": 2874, "text": "Strings" }, { "code": null, "e": 2890, "s": 2882, "text": "Strings" }, { "code": null, "e": 2894, "s": 2890, "text": "CPP" } ]
Find a specific pair in Matrix
30 Jun, 2022 Given an n x n matrix mat[n][n] of integers, find the maximum value of mat(c, d) – mat(a, b) over all choices of indexes such that both c > a and d > b. Example: Input: mat[N][N] = {{ 1, 2, -1, -4, -20 }, { -8, -3, 4, 2, 1 }, { 3, 8, 6, 1, 3 }, { -4, -1, 1, 7, -6 }, { 0, -4, 10, -5, 1 }}; Output: 18 The maximum value is 18 as mat[4][2] - mat[1][0] = 18 has maximum difference. The program should do only ONE traversal of the matrix. i.e. expected time complexity is O(n2)A simple solution would be to apply Brute-Force. For all values mat(a, b) in the matrix, we find mat(c, d) that has maximum value such that c > a and d > b and keeps on updating maximum value found so far. We finally return the maximum value. Below is its implementation. C++ Java Python 3 C# PHP Javascript // A Naive method to find maximum value of mat[d][e]// - ma[a][b] such that d > a and e > b#include <bits/stdc++.h>using namespace std;#define N 5 // The function returns maximum value A(d,e) - A(a,b)// over all choices of indexes such that both d > a// and e > b.int findMaxValue(int mat[][N]){ // stores maximum value int maxValue = INT_MIN; // Consider all possible pairs mat[a][b] and // mat[d][e] for (int a = 0; a < N - 1; a++) for (int b = 0; b < N - 1; b++) for (int d = a + 1; d < N; d++) for (int e = b + 1; e < N; e++) if (maxValue < (mat[d][e] - mat[a][b])) maxValue = mat[d][e] - mat[a][b]; return maxValue;} // Driver program to test above functionint main(){int mat[N][N] = { { 1, 2, -1, -4, -20 }, { -8, -3, 4, 2, 1 }, { 3, 8, 6, 1, 3 }, { -4, -1, 1, 7, -6 }, { 0, -4, 10, -5, 1 } }; cout << "Maximum Value is " << findMaxValue(mat); return 0;} // A Naive method to find maximum value of mat1[d][e]// - ma[a][b] such that d > a and e > bimport java.io.*;import java.util.*; class GFG{ // The function returns maximum value A(d,e) - A(a,b) // over all choices of indexes such that both d > a // and e > b. static int findMaxValue(int N,int mat[][]) { // stores maximum value int maxValue = Integer.MIN_VALUE; // Consider all possible pairs mat[a][b] and // mat1[d][e] for (int a = 0; a < N - 1; a++) for (int b = 0; b < N - 1; b++) for (int d = a + 1; d < N; d++) for (int e = b + 1; e < N; e++) if (maxValue < (mat[d][e] - mat[a][b])) maxValue = mat[d][e] - mat[a][b]; return maxValue; } // Driver code public static void main (String[] args) { int N = 5; int mat[][] = { { 1, 2, -1, -4, -20 }, { -8, -3, 4, 2, 1 }, { 3, 8, 6, 1, 3 }, { -4, -1, 1, 7, -6 }, { 0, -4, 10, -5, 1 } }; System.out.print("Maximum Value is " + findMaxValue(N,mat)); }} // This code is contributed// by Prakriti Gupta # A Naive method to find maximum# value of mat[d][e] - mat[a][b]# such that d > a and e > bN = 5 # The function returns maximum# value A(d,e) - A(a,b) over# all choices of indexes such# that both d > a and e > b.def findMaxValue(mat): # stores maximum value maxValue = 0 # Consider all possible pairs # mat[a][b] and mat[d][e] for a in range(N - 1): for b in range(N - 1): for d in range(a + 1, N): for e in range(b + 1, N): if maxValue < int (mat[d][e] - mat[a][b]): maxValue = int(mat[d][e] - mat[a][b]); return maxValue; # Driver Codemat = [[ 1, 2, -1, -4, -20 ], [ -8, -3, 4, 2, 1 ], [ 3, 8, 6, 1, 3 ], [ -4, -1, 1, 7, -6 ], [ 0, -4, 10, -5, 1 ]]; print("Maximum Value is " + str(findMaxValue(mat))) # This code is contributed# by ChitraNayal // A Naive method to find maximum// value of mat[d][e] - mat[a][b]// such that d > a and e > busing System;class GFG{ // The function returns // maximum value A(d,e) - A(a,b) // over all choices of indexes // such that both d > a // and e > b. static int findMaxValue(int N, int [,]mat) { //stores maximum value int maxValue = int.MinValue; // Consider all possible pairs // mat[a][b] and mat[d][e] for (int a = 0; a< N - 1; a++) for (int b = 0; b < N - 1; b++) for (int d = a + 1; d < N; d++) for (int e = b + 1; e < N; e++) if (maxValue < (mat[d, e] - mat[a, b])) maxValue = mat[d, e] - mat[a, b]; return maxValue; } // Driver code public static void Main () { int N = 5; int [,]mat = {{1, 2, -1, -4, -20}, {-8, -3, 4, 2, 1}, {3, 8, 6, 1, 3}, {-4, -1, 1, 7, -6}, {0, -4, 10, -5, 1}}; Console.Write("Maximum Value is " + findMaxValue(N,mat)); }} // This code is contributed// by ChitraNayal <?php// A Naive method to find maximum// value of $mat[d][e] - ma[a][b]// such that $d > $a and $e > $b$N = 5; // The function returns maximum// value A(d,e) - A(a,b) over// all choices of indexes such// that both $d > $a and $e > $b.function findMaxValue(&$mat){ global $N; // stores maximum value $maxValue = PHP_INT_MIN; // Consider all possible // pairs $mat[$a][$b] and // $mat[$d][$e] for ($a = 0; $a < $N - 1; $a++) for ($b = 0; $b < $N - 1; $b++) for ($d = $a + 1; $d < $N; $d++) for ($e = $b + 1; $e < $N; $e++) if ($maxValue < ($mat[$d][$e] - $mat[$a][$b])) $maxValue = $mat[$d][$e] - $mat[$a][$b]; return $maxValue;} // Driver Code$mat = array(array(1, 2, -1, -4, -20), array(-8, -3, 4, 2, 1), array(3, 8, 6, 1, 3), array(-4, -1, 1, 7, -6), array(0, -4, 10, -5, 1)); echo "Maximum Value is " . findMaxValue($mat); // This code is contributed// by ChitraNayal?> <script>// A Naive method to find maximum value of mat1[d][e]// - ma[a][b] such that d > a and e > b // The function returns maximum value A(d,e) - A(a,b) // over all choices of indexes such that both d > a // and e > b. function findMaxValue(N,mat) { // stores maximum value let maxValue = Number.MIN_VALUE; // Consider all possible pairs mat[a][b] and // mat1[d][e] for (let a = 0; a < N - 1; a++) for (let b = 0; b < N - 1; b++) for (let d = a + 1; d < N; d++) for (let e = b + 1; e < N; e++) if (maxValue < (mat[d][e] - mat[a][b])) maxValue = mat[d][e] - mat[a][b]; return maxValue; } // Driver code let N = 5; let mat=[[ 1, 2, -1, -4, -20],[-8, -3, 4, 2, 1],[3, 8, 6, 1, 3],[ -4, -1, 1, 7, -6 ],[ 0, -4, 10, -5, 1 ]]; document.write("Maximum Value is " +findMaxValue(N,mat)); // This code is contributed by rag2127</script> Maximum Value is 18 Time complexity: O(N4).Auxiliary Space: O(1) The above program runs in O(n^4) time which is nowhere close to expected time complexity of O(n^2) An efficient solution uses extra space. We pre-process the matrix such that index(i, j) stores max of elements in matrix from (i, j) to (N-1, N-1) and in the process keeps on updating maximum value found so far. We finally return the maximum value. Implementation: C++ Java Python3 C# PHP Javascript // An efficient method to find maximum value of mat[d]// - ma[a][b] such that c > a and d > b#include <bits/stdc++.h>using namespace std;#define N 5 // The function returns maximum value A(c,d) - A(a,b)// over all choices of indexes such that both c > a// and d > b.int findMaxValue(int mat[][N]){ //stores maximum value int maxValue = INT_MIN; // maxArr[i][j] stores max of elements in matrix // from (i, j) to (N-1, N-1) int maxArr[N][N]; // last element of maxArr will be same's as of // the input matrix maxArr[N-1][N-1] = mat[N-1][N-1]; // preprocess last row int maxv = mat[N-1][N-1]; // Initialize max for (int j = N - 2; j >= 0; j--) { if (mat[N-1][j] > maxv) maxv = mat[N - 1][j]; maxArr[N-1][j] = maxv; } // preprocess last column maxv = mat[N - 1][N - 1]; // Initialize max for (int i = N - 2; i >= 0; i--) { if (mat[i][N - 1] > maxv) maxv = mat[i][N - 1]; maxArr[i][N - 1] = maxv; } // preprocess rest of the matrix from bottom for (int i = N-2; i >= 0; i--) { for (int j = N-2; j >= 0; j--) { // Update maxValue if (maxArr[i+1][j+1] - mat[i][j] > maxValue) maxValue = maxArr[i + 1][j + 1] - mat[i][j]; // set maxArr (i, j) maxArr[i][j] = max(mat[i][j], max(maxArr[i][j + 1], maxArr[i + 1][j]) ); } } return maxValue;} // Driver program to test above functionint main(){ int mat[N][N] = { { 1, 2, -1, -4, -20 }, { -8, -3, 4, 2, 1 }, { 3, 8, 6, 1, 3 }, { -4, -1, 1, 7, -6 }, { 0, -4, 10, -5, 1 } }; cout << "Maximum Value is " << findMaxValue(mat); return 0;} // An efficient method to find maximum value of mat1[d]// - ma[a][b] such that c > a and d > bimport java.io.*;import java.util.*; class GFG{ // The function returns maximum value A(c,d) - A(a,b) // over all choices of indexes such that both c > a // and d > b. static int findMaxValue(int N,int mat[][]) { //stores maximum value int maxValue = Integer.MIN_VALUE; // maxArr[i][j] stores max of elements in matrix // from (i, j) to (N-1, N-1) int maxArr[][] = new int[N][N]; // last element of maxArr will be same's as of // the input matrix maxArr[N-1][N-1] = mat[N-1][N-1]; // preprocess last row int maxv = mat[N-1][N-1]; // Initialize max for (int j = N - 2; j >= 0; j--) { if (mat[N-1][j] > maxv) maxv = mat[N - 1][j]; maxArr[N-1][j] = maxv; } // preprocess last column maxv = mat[N - 1][N - 1]; // Initialize max for (int i = N - 2; i >= 0; i--) { if (mat[i][N - 1] > maxv) maxv = mat[i][N - 1]; maxArr[i][N - 1] = maxv; } // preprocess rest of the matrix from bottom for (int i = N-2; i >= 0; i--) { for (int j = N-2; j >= 0; j--) { // Update maxValue if (maxArr[i+1][j+1] - mat[i][j] > maxValue) maxValue = maxArr[i + 1][j + 1] - mat[i][j]; // set maxArr (i, j) maxArr[i][j] = Math.max(mat[i][j], Math.max(maxArr[i][j + 1], maxArr[i + 1][j]) ); } } return maxValue; } // Driver code public static void main (String[] args) { int N = 5; int mat[][] = { { 1, 2, -1, -4, -20 }, { -8, -3, 4, 2, 1 }, { 3, 8, 6, 1, 3 }, { -4, -1, 1, 7, -6 }, { 0, -4, 10, -5, 1 } }; System.out.print("Maximum Value is " + findMaxValue(N,mat)); }} // Contributed by Prakriti Gupta # An efficient method to find maximum value# of mat[d] - ma[a][b] such that c > a and d > b import sysN = 5 # The function returns maximum value# A(c,d) - A(a,b) over all choices of# indexes such that both c > a and d > b.def findMaxValue(mat): # stores maximum value maxValue = -sys.maxsize -1 # maxArr[i][j] stores max of elements # in matrix from (i, j) to (N-1, N-1) maxArr = [[0 for x in range(N)] for y in range(N)] # last element of maxArr will be # same's as of the input matrix maxArr[N - 1][N - 1] = mat[N - 1][N - 1] # preprocess last row maxv = mat[N - 1][N - 1]; # Initialize max for j in range (N - 2, -1, -1): if (mat[N - 1][j] > maxv): maxv = mat[N - 1][j] maxArr[N - 1][j] = maxv # preprocess last column maxv = mat[N - 1][N - 1] # Initialize max for i in range (N - 2, -1, -1): if (mat[i][N - 1] > maxv): maxv = mat[i][N - 1] maxArr[i][N - 1] = maxv # preprocess rest of the matrix # from bottom for i in range (N - 2, -1, -1): for j in range (N - 2, -1, -1): # Update maxValue if (maxArr[i + 1][j + 1] - mat[i][j] > maxValue): maxValue = (maxArr[i + 1][j + 1] - mat[i][j]) # set maxArr (i, j) maxArr[i][j] = max(mat[i][j], max(maxArr[i][j + 1], maxArr[i + 1][j])) return maxValue # Driver Codemat = [[ 1, 2, -1, -4, -20 ], [-8, -3, 4, 2, 1 ], [ 3, 8, 6, 1, 3 ], [ -4, -1, 1, 7, -6] , [0, -4, 10, -5, 1 ]] print ("Maximum Value is", findMaxValue(mat)) # This code is contributed by iAyushRaj // An efficient method to find// maximum value of mat1[d]// - ma[a][b] such that c > a// and d > busing System;class GFG { // The function returns // maximum value A(c,d) - A(a,b) // over all choices of indexes // such that both c > a // and d > b. static int findMaxValue(int N, int [,]mat) { //stores maximum value int maxValue = int.MinValue; // maxArr[i][j] stores max // of elements in matrix // from (i, j) to (N-1, N-1) int [,]maxArr = new int[N, N]; // last element of maxArr // will be same's as of // the input matrix maxArr[N - 1, N - 1] = mat[N - 1,N - 1]; // preprocess last row // Initialize max int maxv = mat[N - 1, N - 1]; for (int j = N - 2; j >= 0; j--) { if (mat[N - 1, j] > maxv) maxv = mat[N - 1, j]; maxArr[N - 1, j] = maxv; } // preprocess last column // Initialize max maxv = mat[N - 1,N - 1]; for (int i = N - 2; i >= 0; i--) { if (mat[i, N - 1] > maxv) maxv = mat[i,N - 1]; maxArr[i,N - 1] = maxv; } // preprocess rest of the // matrix from bottom for (int i = N - 2; i >= 0; i--) { for (int j = N - 2; j >= 0; j--) { // Update maxValue if (maxArr[i + 1,j + 1] - mat[i, j] > maxValue) maxValue = maxArr[i + 1,j + 1] - mat[i, j]; // set maxArr (i, j) maxArr[i,j] = Math.Max(mat[i, j], Math.Max(maxArr[i, j + 1], maxArr[i + 1, j]) ); } } return maxValue; } // Driver code public static void Main () { int N = 5; int [,]mat = {{ 1, 2, -1, -4, -20 }, { -8, -3, 4, 2, 1 }, { 3, 8, 6, 1, 3 }, { -4, -1, 1, 7, -6 }, { 0, -4, 10, -5, 1 }}; Console.Write("Maximum Value is " + findMaxValue(N,mat)); }} // This code is contributed by nitin mittal. <?php// An efficient method to find// maximum value of mat[d] - ma[a][b]// such that c > a and d > b$N = 5; // The function returns maximum// value A(c,d) - A(a,b) over// all choices of indexes such// that both c > a and d > b.function findMaxValue($mat){ global $N; // stores maximum value $maxValue = PHP_INT_MIN; // maxArr[i][j] stores max // of elements in matrix // from (i, j) to (N-1, N-1) $maxArr[$N][$N] = array(); // last element of maxArr // will be same's as of // the input matrix $maxArr[$N - 1][$N - 1] = $mat[$N - 1][$N - 1]; // preprocess last row $maxv = $mat[$N - 1][$N - 1]; // Initialize max for ($j = $N - 2; $j >= 0; $j--) { if ($mat[$N - 1][$j] > $maxv) $maxv = $mat[$N - 1][$j]; $maxArr[$N - 1][$j] = $maxv; } // preprocess last column $maxv = $mat[$N - 1][$N - 1]; // Initialize max for ($i = $N - 2; $i >= 0; $i--) { if ($mat[$i][$N - 1] > $maxv) $maxv = $mat[$i][$N - 1]; $maxArr[$i][$N - 1] = $maxv; } // preprocess rest of the // matrix from bottom for ($i = $N - 2; $i >= 0; $i--) { for ($j = $N - 2; $j >= 0; $j--) { // Update maxValue if ($maxArr[$i + 1][$j + 1] - $mat[$i][$j] > $maxValue) $maxValue = $maxArr[$i + 1][$j + 1] - $mat[$i][$j]; // set maxArr (i, j) $maxArr[$i][$j] = max($mat[$i][$j], max($maxArr[$i][$j + 1], $maxArr[$i + 1][$j])); } } return $maxValue;} // Driver Code$mat = array(array(1, 2, -1, -4, -20), array(-8, -3, 4, 2, 1), array(3, 8, 6, 1, 3), array(-4, -1, 1, 7, -6), array(0, -4, 10, -5, 1) );echo "Maximum Value is ". findMaxValue($mat); // This code is contributed// by ChitraNayal?> <script>// An efficient method to find maximum value of mat1[d]// - ma[a][b] such that c > a and d > b // The function returns maximum value A(c,d) - A(a,b) // over all choices of indexes such that both c > a // and d > b. function findMaxValue(N,mat) { // stores maximum value let maxValue = Number.MIN_VALUE; // maxArr[i][j] stores max of elements in matrix // from (i, j) to (N-1, N-1) let maxArr=new Array(N); for(let i = 0; i < N; i++) { maxArr[i]=new Array(N); } // last element of maxArr will be same's as of // the input matrix maxArr[N - 1][N - 1] = mat[N - 1][N - 1]; // preprocess last row let maxv = mat[N-1][N-1]; // Initialize max for (let j = N - 2; j >= 0; j--) { if (mat[N - 1][j] > maxv) maxv = mat[N - 1][j]; maxArr[N - 1][j] = maxv; } // preprocess last column maxv = mat[N - 1][N - 1]; // Initialize max for (let i = N - 2; i >= 0; i--) { if (mat[i][N - 1] > maxv) maxv = mat[i][N - 1]; maxArr[i][N - 1] = maxv; } // preprocess rest of the matrix from bottom for (let i = N-2; i >= 0; i--) { for (let j = N-2; j >= 0; j--) { // Update maxValue if (maxArr[i+1][j+1] - mat[i][j] > maxValue) maxValue = maxArr[i + 1][j + 1] - mat[i][j]; // set maxArr (i, j) maxArr[i][j] = Math.max(mat[i][j], Math.max(maxArr[i][j + 1], maxArr[i + 1][j]) ); } } return maxValue; } // Driver code let N = 5; let mat = [[ 1, 2, -1, -4, -20 ], [-8, -3, 4, 2, 1 ], [ 3, 8, 6, 1, 3 ], [ -4, -1, 1, 7, -6] , [0, -4, 10, -5, 1 ]]; document.write("Maximum Value is " + findMaxValue(N,mat)); // This code is contributed by avanitrachhadiya2155</script> Maximum Value is 18 Time complexity: O(N2).Auxiliary Space: O(N2) If we are allowed to modify of the matrix, we can avoid using extra space and use input matrix instead. Exercise: Print index (a, b) and (c, d) as well. This article is contributed by Aarti_Rathi and 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. nitin mittal ukasp iAyushRaj rag2127 avanitrachhadiya2155 codewithmini hardikkoriintern Matrix Matrix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Unique paths in a Grid with Obstacles Traverse a given Matrix using Recursion Find median in row wise sorted matrix Zigzag (or diagonal) traversal of Matrix A Boolean Matrix Question Python program to add two Matrices Common elements in all rows of a given matrix Find shortest safe route in a path with landmines Flood fill Algorithm - how to implement fill() in paint? Print all possible paths from top left to bottom right of a mXn matrix
[ { "code": null, "e": 52, "s": 24, "text": "\n30 Jun, 2022" }, { "code": null, "e": 205, "s": 52, "text": "Given an n x n matrix mat[n][n] of integers, find the maximum value of mat(c, d) – mat(a, b) over all choices of indexes such that both c > a and d > b." }, { "code": null, "e": 215, "s": 205, "text": "Example: " }, { "code": null, "e": 487, "s": 215, "text": "Input:\nmat[N][N] = {{ 1, 2, -1, -4, -20 },\n { -8, -3, 4, 2, 1 }, \n { 3, 8, 6, 1, 3 },\n { -4, -1, 1, 7, -6 },\n { 0, -4, 10, -5, 1 }};\nOutput: 18\nThe maximum value is 18 as mat[4][2] \n- mat[1][0] = 18 has maximum difference. " }, { "code": null, "e": 824, "s": 487, "text": "The program should do only ONE traversal of the matrix. i.e. expected time complexity is O(n2)A simple solution would be to apply Brute-Force. For all values mat(a, b) in the matrix, we find mat(c, d) that has maximum value such that c > a and d > b and keeps on updating maximum value found so far. We finally return the maximum value." }, { "code": null, "e": 854, "s": 824, "text": "Below is its implementation. " }, { "code": null, "e": 858, "s": 854, "text": "C++" }, { "code": null, "e": 863, "s": 858, "text": "Java" }, { "code": null, "e": 872, "s": 863, "text": "Python 3" }, { "code": null, "e": 875, "s": 872, "text": "C#" }, { "code": null, "e": 879, "s": 875, "text": "PHP" }, { "code": null, "e": 890, "s": 879, "text": "Javascript" }, { "code": "// A Naive method to find maximum value of mat[d][e]// - ma[a][b] such that d > a and e > b#include <bits/stdc++.h>using namespace std;#define N 5 // The function returns maximum value A(d,e) - A(a,b)// over all choices of indexes such that both d > a// and e > b.int findMaxValue(int mat[][N]){ // stores maximum value int maxValue = INT_MIN; // Consider all possible pairs mat[a][b] and // mat[d][e] for (int a = 0; a < N - 1; a++) for (int b = 0; b < N - 1; b++) for (int d = a + 1; d < N; d++) for (int e = b + 1; e < N; e++) if (maxValue < (mat[d][e] - mat[a][b])) maxValue = mat[d][e] - mat[a][b]; return maxValue;} // Driver program to test above functionint main(){int mat[N][N] = { { 1, 2, -1, -4, -20 }, { -8, -3, 4, 2, 1 }, { 3, 8, 6, 1, 3 }, { -4, -1, 1, 7, -6 }, { 0, -4, 10, -5, 1 } }; cout << \"Maximum Value is \" << findMaxValue(mat); return 0;}", "e": 1914, "s": 890, "text": null }, { "code": "// A Naive method to find maximum value of mat1[d][e]// - ma[a][b] such that d > a and e > bimport java.io.*;import java.util.*; class GFG{ // The function returns maximum value A(d,e) - A(a,b) // over all choices of indexes such that both d > a // and e > b. static int findMaxValue(int N,int mat[][]) { // stores maximum value int maxValue = Integer.MIN_VALUE; // Consider all possible pairs mat[a][b] and // mat1[d][e] for (int a = 0; a < N - 1; a++) for (int b = 0; b < N - 1; b++) for (int d = a + 1; d < N; d++) for (int e = b + 1; e < N; e++) if (maxValue < (mat[d][e] - mat[a][b])) maxValue = mat[d][e] - mat[a][b]; return maxValue; } // Driver code public static void main (String[] args) { int N = 5; int mat[][] = { { 1, 2, -1, -4, -20 }, { -8, -3, 4, 2, 1 }, { 3, 8, 6, 1, 3 }, { -4, -1, 1, 7, -6 }, { 0, -4, 10, -5, 1 } }; System.out.print(\"Maximum Value is \" + findMaxValue(N,mat)); }} // This code is contributed// by Prakriti Gupta", "e": 3197, "s": 1914, "text": null }, { "code": "# A Naive method to find maximum# value of mat[d][e] - mat[a][b]# such that d > a and e > bN = 5 # The function returns maximum# value A(d,e) - A(a,b) over# all choices of indexes such# that both d > a and e > b.def findMaxValue(mat): # stores maximum value maxValue = 0 # Consider all possible pairs # mat[a][b] and mat[d][e] for a in range(N - 1): for b in range(N - 1): for d in range(a + 1, N): for e in range(b + 1, N): if maxValue < int (mat[d][e] - mat[a][b]): maxValue = int(mat[d][e] - mat[a][b]); return maxValue; # Driver Codemat = [[ 1, 2, -1, -4, -20 ], [ -8, -3, 4, 2, 1 ], [ 3, 8, 6, 1, 3 ], [ -4, -1, 1, 7, -6 ], [ 0, -4, 10, -5, 1 ]]; print(\"Maximum Value is \" + str(findMaxValue(mat))) # This code is contributed# by ChitraNayal", "e": 4163, "s": 3197, "text": null }, { "code": "// A Naive method to find maximum// value of mat[d][e] - mat[a][b]// such that d > a and e > busing System;class GFG{ // The function returns // maximum value A(d,e) - A(a,b) // over all choices of indexes // such that both d > a // and e > b. static int findMaxValue(int N, int [,]mat) { //stores maximum value int maxValue = int.MinValue; // Consider all possible pairs // mat[a][b] and mat[d][e] for (int a = 0; a< N - 1; a++) for (int b = 0; b < N - 1; b++) for (int d = a + 1; d < N; d++) for (int e = b + 1; e < N; e++) if (maxValue < (mat[d, e] - mat[a, b])) maxValue = mat[d, e] - mat[a, b]; return maxValue; } // Driver code public static void Main () { int N = 5; int [,]mat = {{1, 2, -1, -4, -20}, {-8, -3, 4, 2, 1}, {3, 8, 6, 1, 3}, {-4, -1, 1, 7, -6}, {0, -4, 10, -5, 1}}; Console.Write(\"Maximum Value is \" + findMaxValue(N,mat)); }} // This code is contributed// by ChitraNayal", "e": 5436, "s": 4163, "text": null }, { "code": "<?php// A Naive method to find maximum// value of $mat[d][e] - ma[a][b]// such that $d > $a and $e > $b$N = 5; // The function returns maximum// value A(d,e) - A(a,b) over// all choices of indexes such// that both $d > $a and $e > $b.function findMaxValue(&$mat){ global $N; // stores maximum value $maxValue = PHP_INT_MIN; // Consider all possible // pairs $mat[$a][$b] and // $mat[$d][$e] for ($a = 0; $a < $N - 1; $a++) for ($b = 0; $b < $N - 1; $b++) for ($d = $a + 1; $d < $N; $d++) for ($e = $b + 1; $e < $N; $e++) if ($maxValue < ($mat[$d][$e] - $mat[$a][$b])) $maxValue = $mat[$d][$e] - $mat[$a][$b]; return $maxValue;} // Driver Code$mat = array(array(1, 2, -1, -4, -20), array(-8, -3, 4, 2, 1), array(3, 8, 6, 1, 3), array(-4, -1, 1, 7, -6), array(0, -4, 10, -5, 1)); echo \"Maximum Value is \" . findMaxValue($mat); // This code is contributed// by ChitraNayal?>", "e": 6503, "s": 5436, "text": null }, { "code": "<script>// A Naive method to find maximum value of mat1[d][e]// - ma[a][b] such that d > a and e > b // The function returns maximum value A(d,e) - A(a,b) // over all choices of indexes such that both d > a // and e > b. function findMaxValue(N,mat) { // stores maximum value let maxValue = Number.MIN_VALUE; // Consider all possible pairs mat[a][b] and // mat1[d][e] for (let a = 0; a < N - 1; a++) for (let b = 0; b < N - 1; b++) for (let d = a + 1; d < N; d++) for (let e = b + 1; e < N; e++) if (maxValue < (mat[d][e] - mat[a][b])) maxValue = mat[d][e] - mat[a][b]; return maxValue; } // Driver code let N = 5; let mat=[[ 1, 2, -1, -4, -20],[-8, -3, 4, 2, 1],[3, 8, 6, 1, 3],[ -4, -1, 1, 7, -6 ],[ 0, -4, 10, -5, 1 ]]; document.write(\"Maximum Value is \" +findMaxValue(N,mat)); // This code is contributed by rag2127</script>", "e": 7520, "s": 6503, "text": null }, { "code": null, "e": 7540, "s": 7520, "text": "Maximum Value is 18" }, { "code": null, "e": 7585, "s": 7540, "text": "Time complexity: O(N4).Auxiliary Space: O(1)" }, { "code": null, "e": 7684, "s": 7585, "text": "The above program runs in O(n^4) time which is nowhere close to expected time complexity of O(n^2)" }, { "code": null, "e": 7933, "s": 7684, "text": "An efficient solution uses extra space. We pre-process the matrix such that index(i, j) stores max of elements in matrix from (i, j) to (N-1, N-1) and in the process keeps on updating maximum value found so far. We finally return the maximum value." }, { "code": null, "e": 7949, "s": 7933, "text": "Implementation:" }, { "code": null, "e": 7953, "s": 7949, "text": "C++" }, { "code": null, "e": 7958, "s": 7953, "text": "Java" }, { "code": null, "e": 7966, "s": 7958, "text": "Python3" }, { "code": null, "e": 7969, "s": 7966, "text": "C#" }, { "code": null, "e": 7973, "s": 7969, "text": "PHP" }, { "code": null, "e": 7984, "s": 7973, "text": "Javascript" }, { "code": "// An efficient method to find maximum value of mat[d]// - ma[a][b] such that c > a and d > b#include <bits/stdc++.h>using namespace std;#define N 5 // The function returns maximum value A(c,d) - A(a,b)// over all choices of indexes such that both c > a// and d > b.int findMaxValue(int mat[][N]){ //stores maximum value int maxValue = INT_MIN; // maxArr[i][j] stores max of elements in matrix // from (i, j) to (N-1, N-1) int maxArr[N][N]; // last element of maxArr will be same's as of // the input matrix maxArr[N-1][N-1] = mat[N-1][N-1]; // preprocess last row int maxv = mat[N-1][N-1]; // Initialize max for (int j = N - 2; j >= 0; j--) { if (mat[N-1][j] > maxv) maxv = mat[N - 1][j]; maxArr[N-1][j] = maxv; } // preprocess last column maxv = mat[N - 1][N - 1]; // Initialize max for (int i = N - 2; i >= 0; i--) { if (mat[i][N - 1] > maxv) maxv = mat[i][N - 1]; maxArr[i][N - 1] = maxv; } // preprocess rest of the matrix from bottom for (int i = N-2; i >= 0; i--) { for (int j = N-2; j >= 0; j--) { // Update maxValue if (maxArr[i+1][j+1] - mat[i][j] > maxValue) maxValue = maxArr[i + 1][j + 1] - mat[i][j]; // set maxArr (i, j) maxArr[i][j] = max(mat[i][j], max(maxArr[i][j + 1], maxArr[i + 1][j]) ); } } return maxValue;} // Driver program to test above functionint main(){ int mat[N][N] = { { 1, 2, -1, -4, -20 }, { -8, -3, 4, 2, 1 }, { 3, 8, 6, 1, 3 }, { -4, -1, 1, 7, -6 }, { 0, -4, 10, -5, 1 } }; cout << \"Maximum Value is \" << findMaxValue(mat); return 0;}", "e": 9912, "s": 7984, "text": null }, { "code": "// An efficient method to find maximum value of mat1[d]// - ma[a][b] such that c > a and d > bimport java.io.*;import java.util.*; class GFG{ // The function returns maximum value A(c,d) - A(a,b) // over all choices of indexes such that both c > a // and d > b. static int findMaxValue(int N,int mat[][]) { //stores maximum value int maxValue = Integer.MIN_VALUE; // maxArr[i][j] stores max of elements in matrix // from (i, j) to (N-1, N-1) int maxArr[][] = new int[N][N]; // last element of maxArr will be same's as of // the input matrix maxArr[N-1][N-1] = mat[N-1][N-1]; // preprocess last row int maxv = mat[N-1][N-1]; // Initialize max for (int j = N - 2; j >= 0; j--) { if (mat[N-1][j] > maxv) maxv = mat[N - 1][j]; maxArr[N-1][j] = maxv; } // preprocess last column maxv = mat[N - 1][N - 1]; // Initialize max for (int i = N - 2; i >= 0; i--) { if (mat[i][N - 1] > maxv) maxv = mat[i][N - 1]; maxArr[i][N - 1] = maxv; } // preprocess rest of the matrix from bottom for (int i = N-2; i >= 0; i--) { for (int j = N-2; j >= 0; j--) { // Update maxValue if (maxArr[i+1][j+1] - mat[i][j] > maxValue) maxValue = maxArr[i + 1][j + 1] - mat[i][j]; // set maxArr (i, j) maxArr[i][j] = Math.max(mat[i][j], Math.max(maxArr[i][j + 1], maxArr[i + 1][j]) ); } } return maxValue; } // Driver code public static void main (String[] args) { int N = 5; int mat[][] = { { 1, 2, -1, -4, -20 }, { -8, -3, 4, 2, 1 }, { 3, 8, 6, 1, 3 }, { -4, -1, 1, 7, -6 }, { 0, -4, 10, -5, 1 } }; System.out.print(\"Maximum Value is \" + findMaxValue(N,mat)); }} // Contributed by Prakriti Gupta", "e": 12149, "s": 9912, "text": null }, { "code": "# An efficient method to find maximum value# of mat[d] - ma[a][b] such that c > a and d > b import sysN = 5 # The function returns maximum value# A(c,d) - A(a,b) over all choices of# indexes such that both c > a and d > b.def findMaxValue(mat): # stores maximum value maxValue = -sys.maxsize -1 # maxArr[i][j] stores max of elements # in matrix from (i, j) to (N-1, N-1) maxArr = [[0 for x in range(N)] for y in range(N)] # last element of maxArr will be # same's as of the input matrix maxArr[N - 1][N - 1] = mat[N - 1][N - 1] # preprocess last row maxv = mat[N - 1][N - 1]; # Initialize max for j in range (N - 2, -1, -1): if (mat[N - 1][j] > maxv): maxv = mat[N - 1][j] maxArr[N - 1][j] = maxv # preprocess last column maxv = mat[N - 1][N - 1] # Initialize max for i in range (N - 2, -1, -1): if (mat[i][N - 1] > maxv): maxv = mat[i][N - 1] maxArr[i][N - 1] = maxv # preprocess rest of the matrix # from bottom for i in range (N - 2, -1, -1): for j in range (N - 2, -1, -1): # Update maxValue if (maxArr[i + 1][j + 1] - mat[i][j] > maxValue): maxValue = (maxArr[i + 1][j + 1] - mat[i][j]) # set maxArr (i, j) maxArr[i][j] = max(mat[i][j], max(maxArr[i][j + 1], maxArr[i + 1][j])) return maxValue # Driver Codemat = [[ 1, 2, -1, -4, -20 ], [-8, -3, 4, 2, 1 ], [ 3, 8, 6, 1, 3 ], [ -4, -1, 1, 7, -6] , [0, -4, 10, -5, 1 ]] print (\"Maximum Value is\", findMaxValue(mat)) # This code is contributed by iAyushRaj", "e": 13949, "s": 12149, "text": null }, { "code": "// An efficient method to find// maximum value of mat1[d]// - ma[a][b] such that c > a// and d > busing System;class GFG { // The function returns // maximum value A(c,d) - A(a,b) // over all choices of indexes // such that both c > a // and d > b. static int findMaxValue(int N, int [,]mat) { //stores maximum value int maxValue = int.MinValue; // maxArr[i][j] stores max // of elements in matrix // from (i, j) to (N-1, N-1) int [,]maxArr = new int[N, N]; // last element of maxArr // will be same's as of // the input matrix maxArr[N - 1, N - 1] = mat[N - 1,N - 1]; // preprocess last row // Initialize max int maxv = mat[N - 1, N - 1]; for (int j = N - 2; j >= 0; j--) { if (mat[N - 1, j] > maxv) maxv = mat[N - 1, j]; maxArr[N - 1, j] = maxv; } // preprocess last column // Initialize max maxv = mat[N - 1,N - 1]; for (int i = N - 2; i >= 0; i--) { if (mat[i, N - 1] > maxv) maxv = mat[i,N - 1]; maxArr[i,N - 1] = maxv; } // preprocess rest of the // matrix from bottom for (int i = N - 2; i >= 0; i--) { for (int j = N - 2; j >= 0; j--) { // Update maxValue if (maxArr[i + 1,j + 1] - mat[i, j] > maxValue) maxValue = maxArr[i + 1,j + 1] - mat[i, j]; // set maxArr (i, j) maxArr[i,j] = Math.Max(mat[i, j], Math.Max(maxArr[i, j + 1], maxArr[i + 1, j]) ); } } return maxValue; } // Driver code public static void Main () { int N = 5; int [,]mat = {{ 1, 2, -1, -4, -20 }, { -8, -3, 4, 2, 1 }, { 3, 8, 6, 1, 3 }, { -4, -1, 1, 7, -6 }, { 0, -4, 10, -5, 1 }}; Console.Write(\"Maximum Value is \" + findMaxValue(N,mat)); }} // This code is contributed by nitin mittal.", "e": 16252, "s": 13949, "text": null }, { "code": "<?php// An efficient method to find// maximum value of mat[d] - ma[a][b]// such that c > a and d > b$N = 5; // The function returns maximum// value A(c,d) - A(a,b) over// all choices of indexes such// that both c > a and d > b.function findMaxValue($mat){ global $N; // stores maximum value $maxValue = PHP_INT_MIN; // maxArr[i][j] stores max // of elements in matrix // from (i, j) to (N-1, N-1) $maxArr[$N][$N] = array(); // last element of maxArr // will be same's as of // the input matrix $maxArr[$N - 1][$N - 1] = $mat[$N - 1][$N - 1]; // preprocess last row $maxv = $mat[$N - 1][$N - 1]; // Initialize max for ($j = $N - 2; $j >= 0; $j--) { if ($mat[$N - 1][$j] > $maxv) $maxv = $mat[$N - 1][$j]; $maxArr[$N - 1][$j] = $maxv; } // preprocess last column $maxv = $mat[$N - 1][$N - 1]; // Initialize max for ($i = $N - 2; $i >= 0; $i--) { if ($mat[$i][$N - 1] > $maxv) $maxv = $mat[$i][$N - 1]; $maxArr[$i][$N - 1] = $maxv; } // preprocess rest of the // matrix from bottom for ($i = $N - 2; $i >= 0; $i--) { for ($j = $N - 2; $j >= 0; $j--) { // Update maxValue if ($maxArr[$i + 1][$j + 1] - $mat[$i][$j] > $maxValue) $maxValue = $maxArr[$i + 1][$j + 1] - $mat[$i][$j]; // set maxArr (i, j) $maxArr[$i][$j] = max($mat[$i][$j], max($maxArr[$i][$j + 1], $maxArr[$i + 1][$j])); } } return $maxValue;} // Driver Code$mat = array(array(1, 2, -1, -4, -20), array(-8, -3, 4, 2, 1), array(3, 8, 6, 1, 3), array(-4, -1, 1, 7, -6), array(0, -4, 10, -5, 1) );echo \"Maximum Value is \". findMaxValue($mat); // This code is contributed// by ChitraNayal?>", "e": 18198, "s": 16252, "text": null }, { "code": "<script>// An efficient method to find maximum value of mat1[d]// - ma[a][b] such that c > a and d > b // The function returns maximum value A(c,d) - A(a,b) // over all choices of indexes such that both c > a // and d > b. function findMaxValue(N,mat) { // stores maximum value let maxValue = Number.MIN_VALUE; // maxArr[i][j] stores max of elements in matrix // from (i, j) to (N-1, N-1) let maxArr=new Array(N); for(let i = 0; i < N; i++) { maxArr[i]=new Array(N); } // last element of maxArr will be same's as of // the input matrix maxArr[N - 1][N - 1] = mat[N - 1][N - 1]; // preprocess last row let maxv = mat[N-1][N-1]; // Initialize max for (let j = N - 2; j >= 0; j--) { if (mat[N - 1][j] > maxv) maxv = mat[N - 1][j]; maxArr[N - 1][j] = maxv; } // preprocess last column maxv = mat[N - 1][N - 1]; // Initialize max for (let i = N - 2; i >= 0; i--) { if (mat[i][N - 1] > maxv) maxv = mat[i][N - 1]; maxArr[i][N - 1] = maxv; } // preprocess rest of the matrix from bottom for (let i = N-2; i >= 0; i--) { for (let j = N-2; j >= 0; j--) { // Update maxValue if (maxArr[i+1][j+1] - mat[i][j] > maxValue) maxValue = maxArr[i + 1][j + 1] - mat[i][j]; // set maxArr (i, j) maxArr[i][j] = Math.max(mat[i][j], Math.max(maxArr[i][j + 1], maxArr[i + 1][j]) ); } } return maxValue; } // Driver code let N = 5; let mat = [[ 1, 2, -1, -4, -20 ], [-8, -3, 4, 2, 1 ], [ 3, 8, 6, 1, 3 ], [ -4, -1, 1, 7, -6] , [0, -4, 10, -5, 1 ]]; document.write(\"Maximum Value is \" + findMaxValue(N,mat)); // This code is contributed by avanitrachhadiya2155</script>", "e": 20390, "s": 18198, "text": null }, { "code": null, "e": 20410, "s": 20390, "text": "Maximum Value is 18" }, { "code": null, "e": 20456, "s": 20410, "text": "Time complexity: O(N2).Auxiliary Space: O(N2)" }, { "code": null, "e": 20560, "s": 20456, "text": "If we are allowed to modify of the matrix, we can avoid using extra space and use input matrix instead." }, { "code": null, "e": 20609, "s": 20560, "text": "Exercise: Print index (a, b) and (c, d) as well." }, { "code": null, "e": 20891, "s": 20609, "text": "This article is contributed by Aarti_Rathi and 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." }, { "code": null, "e": 20904, "s": 20891, "text": "nitin mittal" }, { "code": null, "e": 20910, "s": 20904, "text": "ukasp" }, { "code": null, "e": 20920, "s": 20910, "text": "iAyushRaj" }, { "code": null, "e": 20928, "s": 20920, "text": "rag2127" }, { "code": null, "e": 20949, "s": 20928, "text": "avanitrachhadiya2155" }, { "code": null, "e": 20962, "s": 20949, "text": "codewithmini" }, { "code": null, "e": 20979, "s": 20962, "text": "hardikkoriintern" }, { "code": null, "e": 20986, "s": 20979, "text": "Matrix" }, { "code": null, "e": 20993, "s": 20986, "text": "Matrix" }, { "code": null, "e": 21091, "s": 20993, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 21129, "s": 21091, "text": "Unique paths in a Grid with Obstacles" }, { "code": null, "e": 21169, "s": 21129, "text": "Traverse a given Matrix using Recursion" }, { "code": null, "e": 21207, "s": 21169, "text": "Find median in row wise sorted matrix" }, { "code": null, "e": 21248, "s": 21207, "text": "Zigzag (or diagonal) traversal of Matrix" }, { "code": null, "e": 21274, "s": 21248, "text": "A Boolean Matrix Question" }, { "code": null, "e": 21309, "s": 21274, "text": "Python program to add two Matrices" }, { "code": null, "e": 21355, "s": 21309, "text": "Common elements in all rows of a given matrix" }, { "code": null, "e": 21405, "s": 21355, "text": "Find shortest safe route in a path with landmines" }, { "code": null, "e": 21462, "s": 21405, "text": "Flood fill Algorithm - how to implement fill() in paint?" } ]
Check if both halves of the string have same set of characters
26 May, 2022 Given a string of lowercase characters only, the task is to check if it is possible to split a string from the middle which will give two halves having the same characters and same frequency of each character. If the length of the given string is ODD then ignore the middle element and check for the rest. Examples: Input: abbaab Output: NO The two halves contain the same characters but their frequencies do not match so they are NOT CORRECT Input : abccab Output : YES Algorithm: Declare two counter arrays for keeping count of characters in two half of the string, each of size 26.Now run a loop and take two variables i and j, where i starts from 0 and j starts from (length of string – 1).For each character in the string, go to the corresponding index in the counter arrays and increment the value by 1 and increment i and decrement j. Do this until i is less than j.After finishing STEP 3, again run a loop and compare values of counter arrays. If value of first array if not equal to value of second array, then return false.If all counts matched, return true. Declare two counter arrays for keeping count of characters in two half of the string, each of size 26. Now run a loop and take two variables i and j, where i starts from 0 and j starts from (length of string – 1). For each character in the string, go to the corresponding index in the counter arrays and increment the value by 1 and increment i and decrement j. Do this until i is less than j. After finishing STEP 3, again run a loop and compare values of counter arrays. If value of first array if not equal to value of second array, then return false. If all counts matched, return true. Below is the implementation of above idea: C++ Java Python3 C# PHP Javascript // C++ program to check if it is// possible to split string or not#include <bits/stdc++.h>using namespace std;const int MAX_CHAR = 26; // function to check if we can split// string or notbool checkCorrectOrNot(string s){ // Counter array initialized with 0 int count1[MAX_CHAR] = {0}; int count2[MAX_CHAR] = {0}; // Length of the string int n = s.length(); if (n == 1) return true; // traverse till the middle element // is reached for (int i=0,j=n-1; i<j; i++,j--) { // First half count1[s[i]-'a']++; // Second half count2[s[j]-'a']++; } // Checking if values are different // set flag to 1 for (int i = 0; i<MAX_CHAR; i++) if (count1[i] != count2[i]) return false; return true;} // Driver program to test above functionint main(){ // String to be checked string s = "abab"; if (checkCorrectOrNot(s)) cout << "Yes\n"; else cout << "No\n"; return 0;} // Java program to check if it two// half of string contain same Character// set or notpublic class GFG { static final int MAX_CHAR = 26; // function to check both halves // for equality static boolean checkCorrectOrNot(String s) { // Counter array initialized with 0 int[] count1 = new int[MAX_CHAR]; int[] count2 = new int[MAX_CHAR]; // Length of the string int n = s.length(); if (n == 1) return true; // traverse till the middle element // is reached for (int i = 0, j = n - 1; i < j; i++, j--) { // First half count1[s.charAt(i) - 'a']++; // Second half count2[s.charAt(j) - 'a']++; } // Checking if values are different // set flag to 1 for (int i = 0; i < MAX_CHAR; i++) if (count1[i] != count2[i]) return false; return true; } // Driver program to test above function public static void main(String args[]) { // String to be checked String s = "abab"; if (checkCorrectOrNot(s)) System.out.println("Yes"); else System.out.println("No"); }}// This code is contributed by Sumit Ghosh # Python3 program to check if it is# possible to split string or notMAX_CHAR = 26 # Function to check if we# can split string or notdef checkCorrectOrNot(s): global MAX_CHAR # Counter array initialized with 0 count1 = [0] * MAX_CHAR count2 = [0] * MAX_CHAR # Length of the string n = len(s) if n == 1: return true # Traverse till the middle # element is reached i = 0; j = n - 1 while (i < j): # First half count1[ord(s[i]) - ord('a')] += 1 # Second half count2[ord(s[j]) - ord('a')] += 1 i += 1; j -= 1 # Checking if values are # different set flag to 1 for i in range(MAX_CHAR): if count1[i] != count2[i]: return False return True # Driver Code # String to be checkeds = "ababc" print("Yes" if checkCorrectOrNot(s) else "No") # This code is contributed by Ansu Kumari. // C# program to check if it two half of// string contain same Character set or notusing System; class GFG { static int MAX_CHAR = 26; // function to check both halves for // equality static bool checkCorrectOrNot(string s) { // Counter array initialized with 0 int []count1 = new int[MAX_CHAR]; int []count2 = new int[MAX_CHAR]; // Length of the string int n = s.Length; if (n == 1) return true; // traverse till the middle element // is reached for (int i = 0, j = n - 1; i < j; i++, j--) { // First half count1[s[i] - 'a']++; // Second half count2[s[j] - 'a']++; } // Checking if values are different // set flag to 1 for (int i = 0; i < MAX_CHAR; i++) if (count1[i] != count2[i]) return false; return true; } // Driver program to test above function public static void Main() { // String to be checked string s = "abab"; if (checkCorrectOrNot(s)) Console.Write("Yes"); else Console.Write("No"); }} // This code is contributed by nitin mittal <?php// PHP program to check if it is// possible to split string or not$MAX_CHAR = 26; // function to check if we// can split string or notfunction checkCorrectOrNot($s){ global $MAX_CHAR; // Counter array initialized with 0 $count1 = array_fill(0, $MAX_CHAR, NULL); $count2 = array_fill(0, $MAX_CHAR, NULL); // Length of the string $n = strlen($s); if ($n == 1) return true; // traverse till the middle // element is reached for ($i = 0, $j = $n - 1; $i < $j; $i++, $j--) { // First half $count1[$s[$i] - 'a']++; // Second half $count2[$s[$j] - 'a']++; } // Checking if values are // different set flag to 1 for ($i = 0; $i < $MAX_CHAR; $i++) if ($count1[$i] != $count2[$i]) return false; return true;} // Driver Code // String to be checked$s = "abab";if (checkCorrectOrNot($s)) echo "Yes\n";else echo "No\n"; // This code is contributed// by ChitraNayal?> <script>// Javascript program to check if it two// half of string contain same Character// set or not let MAX_CHAR = 26; // function to check both halves // for equality function checkCorrectOrNot(s) { // Counter array initialized with 0 let count1 = new Array(MAX_CHAR); let count2 = new Array(MAX_CHAR); for(let i=0;i<MAX_CHAR;i++) { count1[i]=0; count2[i]=0; } // Length of the string let n = s.length; if (n == 1) return true; // traverse till the middle element // is reached for (let i = 0, j = n - 1; i < j; i++, j--) { // First half count1[s[i] - 'a']++; // Second half count2[s[j] - 'a']++; } // Checking if values are different // set flag to 1 for (let i = 0; i < MAX_CHAR; i++) if (count1[i] != count2[i]) return false; return true; } // Driver program to test above function // String to be checked let s = "abab"; if (checkCorrectOrNot(s)) document.write("Yes"); else document.write("No"); //This code is contributed by avanitrachhadiya2155 </script> Output : YES Time Complexity : O(n), where n is the length of the string. Auxiliary Space : O(1) Space optimized solution: Below is the space optimized solution of the above approach. We can solve this problem by using only 1 counter array.Take a string and increment counts for first half and then decrement counts for second half.If final counter array is 0, then return true, Else False. We can solve this problem by using only 1 counter array. Take a string and increment counts for first half and then decrement counts for second half. If final counter array is 0, then return true, Else False. Below is the implementation of above idea: C++ Java Python3 C# PHP Javascript // C++ program to check if it is// possible to split string or not#include <bits/stdc++.h>using namespace std;const int MAX_CHAR = 26; // function to check if we can split// string or notbool checkCorrectOrNot(string s){ // Counter array initialized with 0 int count[MAX_CHAR] = {0}; // Length of the string int n = s.length(); if (n == 1) return true; // traverse till the middle element // is reached for (int i=0,j=n-1; i<j; i++,j--) { // First half count[s[i]-'a']++; // Second half count[s[j]-'a']--; } // Checking if values are different // set flag to 1 for (int i = 0; i<MAX_CHAR; i++) if (count[i] != 0) return false; return true;} // Driver program to test above functionint main(){ // String to be checked string s = "abab"; if (checkCorrectOrNot(s)) cout << "Yes\n"; else cout << "No\n"; return 0;} // Java program to check if it two// half of string contain same Character// set or notpublic class GFG { static final int MAX_CHAR = 26; // function to check both halves // for equality static boolean checkCorrectOrNot(String s) { // Counter array initialized with 0 int[] count = new int[MAX_CHAR]; // Length of the string int n = s.length(); if (n == 1) return true; // traverse till the middle element // is reached for (int i = 0,j = n - 1; i < j; i++, j--) { // First half count[s.charAt(i) - 'a']++; // Second half count[s.charAt(j) - 'a']--; } // Checking if values are different // set flag to 1 for (int i = 0; i < MAX_CHAR; i++) if (count[i] != 0) return false; return true; } // Driver program to test above function public static void main(String args[]) { // String to be checked String s = "abab"; if (checkCorrectOrNot(s)) System.out.println("Yes"); else System.out.println("No"); }}// This code is contributed by Sumit Ghosh # Python3 program to check if it is# possible to split string or notMAX_CHAR = 26 # Function to check if we # can split string or notdef checkCorrectOrNot(s): global MAX_CHAR # Counter array initialized with 0 count = [0] * MAX_CHAR # Length of the string n = len(s) if n == 1: return true # Traverse till the middle # element is reached i = 0; j = n-1 while i < j: # First half count[ord(s[i]) - ord('a')] += 1 # Second half count[ord(s[j])-ord('a')] -= 1 i += 1; j -= 1 # Checking if values are # different, set flag to 1 for i in range(MAX_CHAR): if count[i] != 0: return False return True # Driver Code # String to be checkeds = "abab" print("Yes" if checkCorrectOrNot(s) else "No") # This code is contributed by Ansu Kumari. // C# program to check if it two// half of string contain same Character// set or notusing System; public class GFG { static int MAX_CHAR = 26; // function to check both halves // for equality static bool checkCorrectOrNot(String s) { // Counter array initialized with 0 int[] count = new int[MAX_CHAR]; // Length of the string int n = s.Length; if (n == 1) return true; // traverse till the middle element // is reached for (int i = 0, j = n - 1; i < j; i++, j--) { // First half count[s[i] - 'a']++; // Second half count[s[j] - 'a']--; } // Checking if values are different // set flag to 1 for (int i = 0; i < MAX_CHAR; i++) if (count[i] != 0) return false; return true; } // Driver program to test above function public static void Main(String []args) { // String to be checked String s = "abab"; if (checkCorrectOrNot(s)) Console.Write("Yes"); else Console.Write("No"); }} // This code is contributed by parashar. <?PHP// PHP program to check if it is// possible to split string or not$MAX_CHAR = 26; // function to check if we// can split string or notfunction checkCorrectOrNot($s){ global $MAX_CHAR; // Counter array initialized with 0 $count = array_fill(0, $MAX_CHAR, NULL); // Length of the string $n = strlen($s); if ($n == 1) return true; // traverse till the middle // element is reached for ($i = 0, $j = $n - 1; $i < $j; $i++, $j--) { // First half $count[$s[$i] - 'a']++; // Second half $count[$s[$j] - 'a']--; } // Checking if values are // different set flag to 1 for ($i = 0; $i < $MAX_CHAR; $i++) if ($count[$i] != 0) return false; return true;} // Driver Code // String to be checked$s = "abab";if (checkCorrectOrNot($s)) echo "Yes\n";else echo "No\n"; // This code is contributed// by ChitraNayal?> <script> // Javascript program to check if it two// half of string contain same Character// set or not let MAX_CHAR = 26; // Function to check both halves// for equalityfunction checkCorrectOrNot(s){ // Counter array initialized with 0 let count = new Array(MAX_CHAR); for(let i = 0; i < count.length; i++) { count[i] = 0; } // Length of the string let n = s.length; if (n == 1) return true; // Traverse till the middle element // is reached for(let i = 0, j = n - 1; i < j; i++, j--) { // First half count[s[i] - 'a']++; // Second half count[s[j] - 'a']--; } // Checking if values are different // set flag to 1 for(let i = 0; i < MAX_CHAR; i++) if (count[i] != 0) return false; return true;} // Driver Codelet s = "abab"; if (checkCorrectOrNot(s)) document.write("Yes");else document.write("No"); // This code is contributed by rag2127 </script> Output: YES Time Complexity : O(n) Auxiliary Space: O(1)This article is contributed by Sahil Rajput. 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. parashar nitin mittal ukasp shubham_singh avanitrachhadiya2155 rag2127 akshaysingh98088 adnanirshad158 shivamanandrj9 Strings Strings Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Write a program to reverse an array or string Reverse a string in Java Write a program to print all permutations of a given string C++ Data Types Different Methods to Reverse a String in C++ Python program to check if a string is palindrome or not Longest Common Subsequence | DP-4 Check for Balanced Brackets in an expression (well-formedness) using Stack Length of the longest substring without repeating characters Top 50 String Coding Problems for Interviews
[ { "code": null, "e": 52, "s": 24, "text": "\n26 May, 2022" }, { "code": null, "e": 358, "s": 52, "text": "Given a string of lowercase characters only, the task is to check if it is possible to split a string from the middle which will give two halves having the same characters and same frequency of each character. If the length of the given string is ODD then ignore the middle element and check for the rest." }, { "code": null, "e": 369, "s": 358, "text": "Examples: " }, { "code": null, "e": 525, "s": 369, "text": "Input: abbaab\nOutput: NO\nThe two halves contain the same characters\nbut their frequencies do not match so they\nare NOT CORRECT\n\nInput : abccab\nOutput : YES" }, { "code": null, "e": 537, "s": 525, "text": "Algorithm: " }, { "code": null, "e": 1124, "s": 537, "text": "Declare two counter arrays for keeping count of characters in two half of the string, each of size 26.Now run a loop and take two variables i and j, where i starts from 0 and j starts from (length of string – 1).For each character in the string, go to the corresponding index in the counter arrays and increment the value by 1 and increment i and decrement j. Do this until i is less than j.After finishing STEP 3, again run a loop and compare values of counter arrays. If value of first array if not equal to value of second array, then return false.If all counts matched, return true." }, { "code": null, "e": 1227, "s": 1124, "text": "Declare two counter arrays for keeping count of characters in two half of the string, each of size 26." }, { "code": null, "e": 1338, "s": 1227, "text": "Now run a loop and take two variables i and j, where i starts from 0 and j starts from (length of string – 1)." }, { "code": null, "e": 1518, "s": 1338, "text": "For each character in the string, go to the corresponding index in the counter arrays and increment the value by 1 and increment i and decrement j. Do this until i is less than j." }, { "code": null, "e": 1679, "s": 1518, "text": "After finishing STEP 3, again run a loop and compare values of counter arrays. If value of first array if not equal to value of second array, then return false." }, { "code": null, "e": 1715, "s": 1679, "text": "If all counts matched, return true." }, { "code": null, "e": 1759, "s": 1715, "text": "Below is the implementation of above idea: " }, { "code": null, "e": 1763, "s": 1759, "text": "C++" }, { "code": null, "e": 1768, "s": 1763, "text": "Java" }, { "code": null, "e": 1776, "s": 1768, "text": "Python3" }, { "code": null, "e": 1779, "s": 1776, "text": "C#" }, { "code": null, "e": 1783, "s": 1779, "text": "PHP" }, { "code": null, "e": 1794, "s": 1783, "text": "Javascript" }, { "code": "// C++ program to check if it is// possible to split string or not#include <bits/stdc++.h>using namespace std;const int MAX_CHAR = 26; // function to check if we can split// string or notbool checkCorrectOrNot(string s){ // Counter array initialized with 0 int count1[MAX_CHAR] = {0}; int count2[MAX_CHAR] = {0}; // Length of the string int n = s.length(); if (n == 1) return true; // traverse till the middle element // is reached for (int i=0,j=n-1; i<j; i++,j--) { // First half count1[s[i]-'a']++; // Second half count2[s[j]-'a']++; } // Checking if values are different // set flag to 1 for (int i = 0; i<MAX_CHAR; i++) if (count1[i] != count2[i]) return false; return true;} // Driver program to test above functionint main(){ // String to be checked string s = \"abab\"; if (checkCorrectOrNot(s)) cout << \"Yes\\n\"; else cout << \"No\\n\"; return 0;}", "e": 2778, "s": 1794, "text": null }, { "code": "// Java program to check if it two// half of string contain same Character// set or notpublic class GFG { static final int MAX_CHAR = 26; // function to check both halves // for equality static boolean checkCorrectOrNot(String s) { // Counter array initialized with 0 int[] count1 = new int[MAX_CHAR]; int[] count2 = new int[MAX_CHAR]; // Length of the string int n = s.length(); if (n == 1) return true; // traverse till the middle element // is reached for (int i = 0, j = n - 1; i < j; i++, j--) { // First half count1[s.charAt(i) - 'a']++; // Second half count2[s.charAt(j) - 'a']++; } // Checking if values are different // set flag to 1 for (int i = 0; i < MAX_CHAR; i++) if (count1[i] != count2[i]) return false; return true; } // Driver program to test above function public static void main(String args[]) { // String to be checked String s = \"abab\"; if (checkCorrectOrNot(s)) System.out.println(\"Yes\"); else System.out.println(\"No\"); }}// This code is contributed by Sumit Ghosh", "e": 4082, "s": 2778, "text": null }, { "code": "# Python3 program to check if it is# possible to split string or notMAX_CHAR = 26 # Function to check if we# can split string or notdef checkCorrectOrNot(s): global MAX_CHAR # Counter array initialized with 0 count1 = [0] * MAX_CHAR count2 = [0] * MAX_CHAR # Length of the string n = len(s) if n == 1: return true # Traverse till the middle # element is reached i = 0; j = n - 1 while (i < j): # First half count1[ord(s[i]) - ord('a')] += 1 # Second half count2[ord(s[j]) - ord('a')] += 1 i += 1; j -= 1 # Checking if values are # different set flag to 1 for i in range(MAX_CHAR): if count1[i] != count2[i]: return False return True # Driver Code # String to be checkeds = \"ababc\" print(\"Yes\" if checkCorrectOrNot(s) else \"No\") # This code is contributed by Ansu Kumari.", "e": 5016, "s": 4082, "text": null }, { "code": "// C# program to check if it two half of// string contain same Character set or notusing System; class GFG { static int MAX_CHAR = 26; // function to check both halves for // equality static bool checkCorrectOrNot(string s) { // Counter array initialized with 0 int []count1 = new int[MAX_CHAR]; int []count2 = new int[MAX_CHAR]; // Length of the string int n = s.Length; if (n == 1) return true; // traverse till the middle element // is reached for (int i = 0, j = n - 1; i < j; i++, j--) { // First half count1[s[i] - 'a']++; // Second half count2[s[j] - 'a']++; } // Checking if values are different // set flag to 1 for (int i = 0; i < MAX_CHAR; i++) if (count1[i] != count2[i]) return false; return true; } // Driver program to test above function public static void Main() { // String to be checked string s = \"abab\"; if (checkCorrectOrNot(s)) Console.Write(\"Yes\"); else Console.Write(\"No\"); }} // This code is contributed by nitin mittal", "e": 6325, "s": 5016, "text": null }, { "code": "<?php// PHP program to check if it is// possible to split string or not$MAX_CHAR = 26; // function to check if we// can split string or notfunction checkCorrectOrNot($s){ global $MAX_CHAR; // Counter array initialized with 0 $count1 = array_fill(0, $MAX_CHAR, NULL); $count2 = array_fill(0, $MAX_CHAR, NULL); // Length of the string $n = strlen($s); if ($n == 1) return true; // traverse till the middle // element is reached for ($i = 0, $j = $n - 1; $i < $j; $i++, $j--) { // First half $count1[$s[$i] - 'a']++; // Second half $count2[$s[$j] - 'a']++; } // Checking if values are // different set flag to 1 for ($i = 0; $i < $MAX_CHAR; $i++) if ($count1[$i] != $count2[$i]) return false; return true;} // Driver Code // String to be checked$s = \"abab\";if (checkCorrectOrNot($s)) echo \"Yes\\n\";else echo \"No\\n\"; // This code is contributed// by ChitraNayal?>", "e": 7309, "s": 6325, "text": null }, { "code": "<script>// Javascript program to check if it two// half of string contain same Character// set or not let MAX_CHAR = 26; // function to check both halves // for equality function checkCorrectOrNot(s) { // Counter array initialized with 0 let count1 = new Array(MAX_CHAR); let count2 = new Array(MAX_CHAR); for(let i=0;i<MAX_CHAR;i++) { count1[i]=0; count2[i]=0; } // Length of the string let n = s.length; if (n == 1) return true; // traverse till the middle element // is reached for (let i = 0, j = n - 1; i < j; i++, j--) { // First half count1[s[i] - 'a']++; // Second half count2[s[j] - 'a']++; } // Checking if values are different // set flag to 1 for (let i = 0; i < MAX_CHAR; i++) if (count1[i] != count2[i]) return false; return true; } // Driver program to test above function // String to be checked let s = \"abab\"; if (checkCorrectOrNot(s)) document.write(\"Yes\"); else document.write(\"No\"); //This code is contributed by avanitrachhadiya2155 </script>", "e": 8626, "s": 7309, "text": null }, { "code": null, "e": 8636, "s": 8626, "text": "Output : " }, { "code": null, "e": 8640, "s": 8636, "text": "YES" }, { "code": null, "e": 8701, "s": 8640, "text": "Time Complexity : O(n), where n is the length of the string." }, { "code": null, "e": 8725, "s": 8701, "text": "Auxiliary Space : O(1)" }, { "code": null, "e": 8813, "s": 8725, "text": "Space optimized solution: Below is the space optimized solution of the above approach. " }, { "code": null, "e": 9020, "s": 8813, "text": "We can solve this problem by using only 1 counter array.Take a string and increment counts for first half and then decrement counts for second half.If final counter array is 0, then return true, Else False." }, { "code": null, "e": 9077, "s": 9020, "text": "We can solve this problem by using only 1 counter array." }, { "code": null, "e": 9170, "s": 9077, "text": "Take a string and increment counts for first half and then decrement counts for second half." }, { "code": null, "e": 9229, "s": 9170, "text": "If final counter array is 0, then return true, Else False." }, { "code": null, "e": 9274, "s": 9229, "text": "Below is the implementation of above idea: " }, { "code": null, "e": 9278, "s": 9274, "text": "C++" }, { "code": null, "e": 9283, "s": 9278, "text": "Java" }, { "code": null, "e": 9291, "s": 9283, "text": "Python3" }, { "code": null, "e": 9294, "s": 9291, "text": "C#" }, { "code": null, "e": 9298, "s": 9294, "text": "PHP" }, { "code": null, "e": 9309, "s": 9298, "text": "Javascript" }, { "code": "// C++ program to check if it is// possible to split string or not#include <bits/stdc++.h>using namespace std;const int MAX_CHAR = 26; // function to check if we can split// string or notbool checkCorrectOrNot(string s){ // Counter array initialized with 0 int count[MAX_CHAR] = {0}; // Length of the string int n = s.length(); if (n == 1) return true; // traverse till the middle element // is reached for (int i=0,j=n-1; i<j; i++,j--) { // First half count[s[i]-'a']++; // Second half count[s[j]-'a']--; } // Checking if values are different // set flag to 1 for (int i = 0; i<MAX_CHAR; i++) if (count[i] != 0) return false; return true;} // Driver program to test above functionint main(){ // String to be checked string s = \"abab\"; if (checkCorrectOrNot(s)) cout << \"Yes\\n\"; else cout << \"No\\n\"; return 0;}", "e": 10250, "s": 9309, "text": null }, { "code": "// Java program to check if it two// half of string contain same Character// set or notpublic class GFG { static final int MAX_CHAR = 26; // function to check both halves // for equality static boolean checkCorrectOrNot(String s) { // Counter array initialized with 0 int[] count = new int[MAX_CHAR]; // Length of the string int n = s.length(); if (n == 1) return true; // traverse till the middle element // is reached for (int i = 0,j = n - 1; i < j; i++, j--) { // First half count[s.charAt(i) - 'a']++; // Second half count[s.charAt(j) - 'a']--; } // Checking if values are different // set flag to 1 for (int i = 0; i < MAX_CHAR; i++) if (count[i] != 0) return false; return true; } // Driver program to test above function public static void main(String args[]) { // String to be checked String s = \"abab\"; if (checkCorrectOrNot(s)) System.out.println(\"Yes\"); else System.out.println(\"No\"); }}// This code is contributed by Sumit Ghosh", "e": 11499, "s": 10250, "text": null }, { "code": "# Python3 program to check if it is# possible to split string or notMAX_CHAR = 26 # Function to check if we # can split string or notdef checkCorrectOrNot(s): global MAX_CHAR # Counter array initialized with 0 count = [0] * MAX_CHAR # Length of the string n = len(s) if n == 1: return true # Traverse till the middle # element is reached i = 0; j = n-1 while i < j: # First half count[ord(s[i]) - ord('a')] += 1 # Second half count[ord(s[j])-ord('a')] -= 1 i += 1; j -= 1 # Checking if values are # different, set flag to 1 for i in range(MAX_CHAR): if count[i] != 0: return False return True # Driver Code # String to be checkeds = \"abab\" print(\"Yes\" if checkCorrectOrNot(s) else \"No\") # This code is contributed by Ansu Kumari.", "e": 12377, "s": 11499, "text": null }, { "code": "// C# program to check if it two// half of string contain same Character// set or notusing System; public class GFG { static int MAX_CHAR = 26; // function to check both halves // for equality static bool checkCorrectOrNot(String s) { // Counter array initialized with 0 int[] count = new int[MAX_CHAR]; // Length of the string int n = s.Length; if (n == 1) return true; // traverse till the middle element // is reached for (int i = 0, j = n - 1; i < j; i++, j--) { // First half count[s[i] - 'a']++; // Second half count[s[j] - 'a']--; } // Checking if values are different // set flag to 1 for (int i = 0; i < MAX_CHAR; i++) if (count[i] != 0) return false; return true; } // Driver program to test above function public static void Main(String []args) { // String to be checked String s = \"abab\"; if (checkCorrectOrNot(s)) Console.Write(\"Yes\"); else Console.Write(\"No\"); }} // This code is contributed by parashar.", "e": 13614, "s": 12377, "text": null }, { "code": "<?PHP// PHP program to check if it is// possible to split string or not$MAX_CHAR = 26; // function to check if we// can split string or notfunction checkCorrectOrNot($s){ global $MAX_CHAR; // Counter array initialized with 0 $count = array_fill(0, $MAX_CHAR, NULL); // Length of the string $n = strlen($s); if ($n == 1) return true; // traverse till the middle // element is reached for ($i = 0, $j = $n - 1; $i < $j; $i++, $j--) { // First half $count[$s[$i] - 'a']++; // Second half $count[$s[$j] - 'a']--; } // Checking if values are // different set flag to 1 for ($i = 0; $i < $MAX_CHAR; $i++) if ($count[$i] != 0) return false; return true;} // Driver Code // String to be checked$s = \"abab\";if (checkCorrectOrNot($s)) echo \"Yes\\n\";else echo \"No\\n\"; // This code is contributed// by ChitraNayal?>", "e": 14539, "s": 13614, "text": null }, { "code": "<script> // Javascript program to check if it two// half of string contain same Character// set or not let MAX_CHAR = 26; // Function to check both halves// for equalityfunction checkCorrectOrNot(s){ // Counter array initialized with 0 let count = new Array(MAX_CHAR); for(let i = 0; i < count.length; i++) { count[i] = 0; } // Length of the string let n = s.length; if (n == 1) return true; // Traverse till the middle element // is reached for(let i = 0, j = n - 1; i < j; i++, j--) { // First half count[s[i] - 'a']++; // Second half count[s[j] - 'a']--; } // Checking if values are different // set flag to 1 for(let i = 0; i < MAX_CHAR; i++) if (count[i] != 0) return false; return true;} // Driver Codelet s = \"abab\"; if (checkCorrectOrNot(s)) document.write(\"Yes\");else document.write(\"No\"); // This code is contributed by rag2127 </script>", "e": 15541, "s": 14539, "text": null }, { "code": null, "e": 15550, "s": 15541, "text": "Output: " }, { "code": null, "e": 15554, "s": 15550, "text": "YES" }, { "code": null, "e": 15578, "s": 15554, "text": " Time Complexity : O(n)" }, { "code": null, "e": 16020, "s": 15578, "text": "Auxiliary Space: O(1)This article is contributed by Sahil Rajput. 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": 16029, "s": 16020, "text": "parashar" }, { "code": null, "e": 16042, "s": 16029, "text": "nitin mittal" }, { "code": null, "e": 16048, "s": 16042, "text": "ukasp" }, { "code": null, "e": 16062, "s": 16048, "text": "shubham_singh" }, { "code": null, "e": 16083, "s": 16062, "text": "avanitrachhadiya2155" }, { "code": null, "e": 16091, "s": 16083, "text": "rag2127" }, { "code": null, "e": 16108, "s": 16091, "text": "akshaysingh98088" }, { "code": null, "e": 16123, "s": 16108, "text": "adnanirshad158" }, { "code": null, "e": 16138, "s": 16123, "text": "shivamanandrj9" }, { "code": null, "e": 16146, "s": 16138, "text": "Strings" }, { "code": null, "e": 16154, "s": 16146, "text": "Strings" }, { "code": null, "e": 16252, "s": 16154, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 16298, "s": 16252, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 16323, "s": 16298, "text": "Reverse a string in Java" }, { "code": null, "e": 16383, "s": 16323, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 16398, "s": 16383, "text": "C++ Data Types" }, { "code": null, "e": 16443, "s": 16398, "text": "Different Methods to Reverse a String in C++" }, { "code": null, "e": 16500, "s": 16443, "text": "Python program to check if a string is palindrome or not" }, { "code": null, "e": 16534, "s": 16500, "text": "Longest Common Subsequence | DP-4" }, { "code": null, "e": 16609, "s": 16534, "text": "Check for Balanced Brackets in an expression (well-formedness) using Stack" }, { "code": null, "e": 16670, "s": 16609, "text": "Length of the longest substring without repeating characters" } ]
title driver method – Selenium Python
15 May, 2020 Selenium’s Python Module is built to perform automated testing with Python. Selenium Python bindings provides a simple API to write functional/acceptance tests using Selenium WebDriver. To open a webpage using Selenium Python, checkout – Navigating links using get method – Selenium Python. Just being able to go to places isn’t terribly useful. What we’d really like to do is to interact with the pages, or, more specifically, the HTML elements within a page. There are multiple strategies to find an element using Selenium, checkout – Locating Strategies. Selenium WebDriver offers various useful methods to control the session, or in other words, browser. For example, adding a cookie, pressing back button, navigating among tabs, etc. This article revolves around title driver method in Selenium. title method gets the title of the current page. Syntax – driver.title Example –Now one can use title method as a driver method as below – diver.get("https://www.geeksforgeeks.org/") driver.title To demonstrate, title method of WebDriver in Selenium Python. Let’ s visit https://www.geeksforgeeks.org/ and operate on driver object. Let’s get title, Program – # import webdriverfrom selenium import webdriver # create webdriver objectdriver = webdriver.Firefox() # get geeksforgeeks.orgdriver.get("https://www.geeksforgeeks.org/") # get titleprint(driver.title) Output –Screenshot added – Terminal output – Python-selenium selenium Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n15 May, 2020" }, { "code": null, "e": 767, "s": 28, "text": "Selenium’s Python Module is built to perform automated testing with Python. Selenium Python bindings provides a simple API to write functional/acceptance tests using Selenium WebDriver. To open a webpage using Selenium Python, checkout – Navigating links using get method – Selenium Python. Just being able to go to places isn’t terribly useful. What we’d really like to do is to interact with the pages, or, more specifically, the HTML elements within a page. There are multiple strategies to find an element using Selenium, checkout – Locating Strategies. Selenium WebDriver offers various useful methods to control the session, or in other words, browser. For example, adding a cookie, pressing back button, navigating among tabs, etc." }, { "code": null, "e": 878, "s": 767, "text": "This article revolves around title driver method in Selenium. title method gets the title of the current page." }, { "code": null, "e": 887, "s": 878, "text": "Syntax –" }, { "code": null, "e": 900, "s": 887, "text": "driver.title" }, { "code": null, "e": 968, "s": 900, "text": "Example –Now one can use title method as a driver method as below –" }, { "code": null, "e": 1026, "s": 968, "text": "diver.get(\"https://www.geeksforgeeks.org/\")\ndriver.title\n" }, { "code": null, "e": 1179, "s": 1026, "text": "To demonstrate, title method of WebDriver in Selenium Python. Let’ s visit https://www.geeksforgeeks.org/ and operate on driver object. Let’s get title," }, { "code": null, "e": 1189, "s": 1179, "text": "Program –" }, { "code": "# import webdriverfrom selenium import webdriver # create webdriver objectdriver = webdriver.Firefox() # get geeksforgeeks.orgdriver.get(\"https://www.geeksforgeeks.org/\") # get titleprint(driver.title)", "e": 1394, "s": 1189, "text": null }, { "code": null, "e": 1421, "s": 1394, "text": "Output –Screenshot added –" }, { "code": null, "e": 1439, "s": 1421, "text": "Terminal output –" }, { "code": null, "e": 1455, "s": 1439, "text": "Python-selenium" }, { "code": null, "e": 1464, "s": 1455, "text": "selenium" }, { "code": null, "e": 1471, "s": 1464, "text": "Python" } ]
Multiple linear regression using ggplot2 in R
24 Jun, 2021 A regression line is basically used in statistical models which help to estimate the relationship between a dependent variable and at least one independent variable. There are two types of regression lines : Single Regression Line. Multiple Regression Lines. In this article, we are going to discuss how to plot multiple regression lines in R programming language using ggplot2 scatter plot. Dataset Used: Here we are using a built-in data frame “Orange” which consists of details about the growth of five different types of orange trees. The data frame has 35 rows and 3 columns. The columns in this data frame are : Tree: The ordering of trees on which experiment is made on the basis of increasing diameter values of the orange. Age: The age of the trees since when they were planted. Circumference: The circumference of the orange. We first create a scatter plot. We will use the function geom_point( ) to plot the scatter plot which comes under the ggplot2 library. Syntax: geom_point( mapping=NULL, data=NULL, stat=identity, position=”identity”) Basically, we are doing a comparative analysis of the circumference vs age of the oranges. The function used is geom_smooth( ) to plot a smooth line or regression line. Syntax: geom_smooth(method=”auto”,se=FALSE,fullrange=TRUE,level=0.95) Parameter : method : The smoothing method is assigned using the keyword loess, lm, glm etc lm : linear model, loess : default for smooth lines during small data set observations. formula : You can also use formulas for smooth lines. For example : y~poly(x,4) which will plot a smooth line of degree 4. Higher the degree more bends the smooth line will have. se : It takes logical values either “TRUE” or “FALSE”. fullrange : It takes logical value either “TRUE” or “FALSE”. level : By default level is 0.95 for the confidence interval. Let us first draw a simple single-line regression and then increase the complexity to multiple lines. Example: R # Scatter Plotlibrary(ggplot2) ggplt <- ggplot(Orange,aes(x=circumference,y=age))+ geom_point()+ theme_classic() ggplt # Plotting a single Regression Lineggplt+geom_smooth(method=lm,se=FALSE,fullrange=TRUE) Output: This is a single smooth line or popularly known as a regression line. Here, the points are combined and are not segregated on the basis of any groups. Multiple linear regression will deal with the same parameter, but each line will represent a different group. So, if we want to plot the points on the basis of the group they belong to, we need multiple regression lines. Each regression line will be associated with a group. Basic Formula for Multiple Regression Lines : The syntax in R to calculate the coefficients and other parameters related to multiple regression lines is : var <- lm(formula, data = data_set_name) summary(var) lm : linear model var : variable name To compute multiple regression lines on the same graph set the attribute on basis of which groups should be formed to shape parameter. Syntax: shape = attribute A single regression line is associated with a single group which can be seen in the legends of the plot. Now, to assign different colors to every regression lines write the command : color = attribute Example: R library(ggplot2) ggplt <- ggplot(Orange,aes(x=circumference,y=age,shape=Tree))+ geom_point()+ theme_classic() ggplt # Plotting multiple Regression Linesggplt+geom_smooth(method=lm,se=FALSE,fullrange=TRUE, aes(color=Tree)) Output: Picked R Machine-Learning R-ggplot R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n24 Jun, 2021" }, { "code": null, "e": 236, "s": 28, "text": "A regression line is basically used in statistical models which help to estimate the relationship between a dependent variable and at least one independent variable. There are two types of regression lines :" }, { "code": null, "e": 260, "s": 236, "text": "Single Regression Line." }, { "code": null, "e": 287, "s": 260, "text": "Multiple Regression Lines." }, { "code": null, "e": 420, "s": 287, "text": "In this article, we are going to discuss how to plot multiple regression lines in R programming language using ggplot2 scatter plot." }, { "code": null, "e": 646, "s": 420, "text": "Dataset Used: Here we are using a built-in data frame “Orange” which consists of details about the growth of five different types of orange trees. The data frame has 35 rows and 3 columns. The columns in this data frame are :" }, { "code": null, "e": 760, "s": 646, "text": "Tree: The ordering of trees on which experiment is made on the basis of increasing diameter values of the orange." }, { "code": null, "e": 816, "s": 760, "text": "Age: The age of the trees since when they were planted." }, { "code": null, "e": 864, "s": 816, "text": "Circumference: The circumference of the orange." }, { "code": null, "e": 1000, "s": 864, "text": "We first create a scatter plot. We will use the function geom_point( ) to plot the scatter plot which comes under the ggplot2 library. " }, { "code": null, "e": 1008, "s": 1000, "text": "Syntax:" }, { "code": null, "e": 1081, "s": 1008, "text": "geom_point( mapping=NULL, data=NULL, stat=identity, position=”identity”)" }, { "code": null, "e": 1251, "s": 1081, "text": "Basically, we are doing a comparative analysis of the circumference vs age of the oranges. The function used is geom_smooth( ) to plot a smooth line or regression line. " }, { "code": null, "e": 1321, "s": 1251, "text": "Syntax: geom_smooth(method=”auto”,se=FALSE,fullrange=TRUE,level=0.95)" }, { "code": null, "e": 1333, "s": 1321, "text": "Parameter :" }, { "code": null, "e": 1412, "s": 1333, "text": "method : The smoothing method is assigned using the keyword loess, lm, glm etc" }, { "code": null, "e": 1500, "s": 1412, "text": "lm : linear model, loess : default for smooth lines during small data set observations." }, { "code": null, "e": 1679, "s": 1500, "text": "formula : You can also use formulas for smooth lines. For example : y~poly(x,4) which will plot a smooth line of degree 4. Higher the degree more bends the smooth line will have." }, { "code": null, "e": 1734, "s": 1679, "text": "se : It takes logical values either “TRUE” or “FALSE”." }, { "code": null, "e": 1795, "s": 1734, "text": "fullrange : It takes logical value either “TRUE” or “FALSE”." }, { "code": null, "e": 1857, "s": 1795, "text": "level : By default level is 0.95 for the confidence interval." }, { "code": null, "e": 1959, "s": 1857, "text": "Let us first draw a simple single-line regression and then increase the complexity to multiple lines." }, { "code": null, "e": 1968, "s": 1959, "text": "Example:" }, { "code": null, "e": 1970, "s": 1968, "text": "R" }, { "code": "# Scatter Plotlibrary(ggplot2) ggplt <- ggplot(Orange,aes(x=circumference,y=age))+ geom_point()+ theme_classic() ggplt # Plotting a single Regression Lineggplt+geom_smooth(method=lm,se=FALSE,fullrange=TRUE)", "e": 2196, "s": 1970, "text": null }, { "code": null, "e": 2204, "s": 2196, "text": "Output:" }, { "code": null, "e": 2355, "s": 2204, "text": "This is a single smooth line or popularly known as a regression line. Here, the points are combined and are not segregated on the basis of any groups." }, { "code": null, "e": 2631, "s": 2355, "text": "Multiple linear regression will deal with the same parameter, but each line will represent a different group. So, if we want to plot the points on the basis of the group they belong to, we need multiple regression lines. Each regression line will be associated with a group. " }, { "code": null, "e": 2677, "s": 2631, "text": "Basic Formula for Multiple Regression Lines :" }, { "code": null, "e": 2786, "s": 2677, "text": "The syntax in R to calculate the coefficients and other parameters related to multiple regression lines is :" }, { "code": null, "e": 2827, "s": 2786, "text": "var <- lm(formula, data = data_set_name)" }, { "code": null, "e": 2840, "s": 2827, "text": "summary(var)" }, { "code": null, "e": 2859, "s": 2840, "text": "lm : linear model " }, { "code": null, "e": 2880, "s": 2859, "text": "var : variable name " }, { "code": null, "e": 3015, "s": 2880, "text": "To compute multiple regression lines on the same graph set the attribute on basis of which groups should be formed to shape parameter." }, { "code": null, "e": 3023, "s": 3015, "text": "Syntax:" }, { "code": null, "e": 3045, "s": 3023, "text": "shape = attribute " }, { "code": null, "e": 3228, "s": 3045, "text": "A single regression line is associated with a single group which can be seen in the legends of the plot. Now, to assign different colors to every regression lines write the command :" }, { "code": null, "e": 3246, "s": 3228, "text": "color = attribute" }, { "code": null, "e": 3255, "s": 3246, "text": "Example:" }, { "code": null, "e": 3257, "s": 3255, "text": "R" }, { "code": "library(ggplot2) ggplt <- ggplot(Orange,aes(x=circumference,y=age,shape=Tree))+ geom_point()+ theme_classic() ggplt # Plotting multiple Regression Linesggplt+geom_smooth(method=lm,se=FALSE,fullrange=TRUE, aes(color=Tree))", "e": 3515, "s": 3257, "text": null }, { "code": null, "e": 3523, "s": 3515, "text": "Output:" }, { "code": null, "e": 3530, "s": 3523, "text": "Picked" }, { "code": null, "e": 3549, "s": 3530, "text": "R Machine-Learning" }, { "code": null, "e": 3558, "s": 3549, "text": "R-ggplot" }, { "code": null, "e": 3569, "s": 3558, "text": "R Language" } ]
Find Intersection of all Intervals
11 May, 2021 Given N intervals of the form of [l, r], the task is to find the intersection of all the intervals. An intersection is an interval that lies within all of the given intervals. If no such intersection exists then print -1.Examples: Input: arr[] = {{1, 6}, {2, 8}, {3, 10}, {5, 8}} Output: [5, 6] [5, 6] is the common interval that lies in all the given intervals.Input: arr[] = {{1, 6}, {8, 18}} Output: -1 No intersection exists between the two given ranges. Approach: Start by considering first interval as the required answer. Now, starting from the second interval, try searching for the intersection. Two cases can arise: There exists no intersection between [l1, r1] and [l2, r2]. Possible only when r1 < l2 or r2 < l1. In such a case answer will be 0 i.e. no intersection exists.There exists an intersection between [l1, r1] and [l2, r2]. Then the required intersection will be [max(l1, l2), min(r1, r2)]. There exists no intersection between [l1, r1] and [l2, r2]. Possible only when r1 < l2 or r2 < l1. In such a case answer will be 0 i.e. no intersection exists.There exists an intersection between [l1, r1] and [l2, r2]. Then the required intersection will be [max(l1, l2), min(r1, r2)]. There exists no intersection between [l1, r1] and [l2, r2]. Possible only when r1 < l2 or r2 < l1. In such a case answer will be 0 i.e. no intersection exists. There exists an intersection between [l1, r1] and [l2, r2]. Then the required intersection will be [max(l1, l2), min(r1, r2)]. Below is the implementation of the above approach: C++ Java Python C# PHP Javascript // C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to print the intersectionvoid findIntersection(int intervals[][2], int N){ // First interval int l = intervals[0][0]; int r = intervals[0][1]; // Check rest of the intervals and find the intersection for (int i = 1; i < N; i++) { // If no intersection exists if (intervals[i][0] > r || intervals[i][1] < l) { cout << -1; return; } // Else update the intersection else { l = max(l, intervals[i][0]); r = min(r, intervals[i][1]); } } cout << "[" << l << ", " << r << "]";} // Driver codeint main(){ int intervals[][2] = { { 1, 6 }, { 2, 8 }, { 3, 10 }, { 5, 8 } }; int N = sizeof(intervals) / sizeof(intervals[0]); findIntersection(intervals, N);} // Java implementation of the approachimport java.io.*; class GFG{ // Function to print the intersectionstatic void findIntersection(int intervals[][], int N){ // First interval int l = intervals[0][0]; int r = intervals[0][1]; // Check rest of the intervals // and find the intersection for (int i = 1; i < N; i++) { // If no intersection exists if (intervals[i][0] > r || intervals[i][1] < l) { System.out.println(-1); return; } // Else update the intersection else { l = Math.max(l, intervals[i][0]); r = Math.min(r, intervals[i][1]); } } System.out.println ("[" + l +", " + r + "]");} // Driver code public static void main (String[] args) { int intervals[][] = {{ 1, 6 }, { 2, 8 }, { 3, 10 }, { 5, 8 }}; int N = intervals.length; findIntersection(intervals, N); }} // This Code is contributed by ajit.. # Python3 implementation of the approach # Function to print the intersectiondef findIntersection(intervals,N): # First interval l = intervals[0][0] r = intervals[0][1] # Check rest of the intervals # and find the intersection for i in range(1,N): # If no intersection exists if (intervals[i][0] > r or intervals[i][1] < l): print(-1) # Else update the intersection else: l = max(l, intervals[i][0]) r = min(r, intervals[i][1]) print("[",l,", ",r,"]") # Driver code intervals= [ [ 1, 6 ], [ 2, 8 ], [ 3, 10 ], [ 5, 8 ] ]N =len(intervals)findIntersection(intervals, N) # this code is contributed by mohit kumar // C# implementation of the approachusing System; class GFG{ // Function to print the intersectionstatic void findIntersection(int [,]intervals, int N){ // First interval int l = intervals[0, 0]; int r = intervals[0, 1]; // Check rest of the intervals // and find the intersection for (int i = 1; i < N; i++) { // If no intersection exists if (intervals[i, 0] > r || intervals[i, 1] < l) { Console.WriteLine(-1); return; } // Else update the intersection else { l = Math.Max(l, intervals[i, 0]); r = Math.Min(r, intervals[i, 1]); } } Console.WriteLine("[" + l + ", " + r + "]");} // Driver codepublic static void Main(){ int [,]intervals = {{ 1, 6 }, { 2, 8 }, { 3, 10 }, { 5, 8 }}; int N = intervals.GetLength(0); findIntersection(intervals, N);}} // This code is contributed by Ryuga <?php// PHP implementation of the approach // Function to print the intersectionfunction findIntersection($intervals, $N){ // First interval $l = $intervals[0][0]; $r = $intervals[0][1]; // Check rest of the intervals and // find the intersection for ($i = 1; $i < $N; $i++) { // If no intersection exists if ($intervals[$i][0] > $r || $intervals[$i][1] < $l) { echo -1; return; } // Else update the intersection else { $l = max($l, $intervals[$i][0]); $r = min($r, $intervals[$i][1]); } } echo "[" . $l . ", " . $r . "]";} // Driver code$intervals = array(array(1, 6), array(2, 8), array(3, 10), array(5, 8));$N = sizeof($intervals);findIntersection($intervals, $N); // This code is contributed// by Akanksha Rai?> <script> // Javascript implementation of the approach // Function to print the intersection function findIntersection(intervals, N) { // First interval let l = intervals[0][0]; let r = intervals[0][1]; // Check rest of the intervals // and find the intersection for (let i = 1; i < N; i++) { // If no intersection exists if (intervals[i][0] > r || intervals[i][1] < l) { document.write(-1 + "</br>"); return; } // Else update the intersection else { l = Math.max(l, intervals[i][0]); r = Math.min(r, intervals[i][1]); } } document.write("[" + l +", " + r + "]" + "</br>"); } let intervals = [[ 1, 6 ], [ 2, 8 ], [ 3, 10], [ 5, 8 ]]; let N = intervals.length; findIntersection(intervals, N); </script> [5, 6] jit_t ankthon Akanksha_Rai mohit kumar 29 divyeshrabadiya07 Arrays Competitive Programming Greedy Arrays Greedy Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n11 May, 2021" }, { "code": null, "e": 287, "s": 54, "text": "Given N intervals of the form of [l, r], the task is to find the intersection of all the intervals. An intersection is an interval that lies within all of the given intervals. If no such intersection exists then print -1.Examples: " }, { "code": null, "e": 517, "s": 287, "text": "Input: arr[] = {{1, 6}, {2, 8}, {3, 10}, {5, 8}} Output: [5, 6] [5, 6] is the common interval that lies in all the given intervals.Input: arr[] = {{1, 6}, {8, 18}} Output: -1 No intersection exists between the two given ranges. " }, { "code": null, "e": 531, "s": 519, "text": "Approach: " }, { "code": null, "e": 591, "s": 531, "text": "Start by considering first interval as the required answer." }, { "code": null, "e": 974, "s": 591, "text": "Now, starting from the second interval, try searching for the intersection. Two cases can arise: There exists no intersection between [l1, r1] and [l2, r2]. Possible only when r1 < l2 or r2 < l1. In such a case answer will be 0 i.e. no intersection exists.There exists an intersection between [l1, r1] and [l2, r2]. Then the required intersection will be [max(l1, l2), min(r1, r2)]." }, { "code": null, "e": 1260, "s": 974, "text": "There exists no intersection between [l1, r1] and [l2, r2]. Possible only when r1 < l2 or r2 < l1. In such a case answer will be 0 i.e. no intersection exists.There exists an intersection between [l1, r1] and [l2, r2]. Then the required intersection will be [max(l1, l2), min(r1, r2)]." }, { "code": null, "e": 1420, "s": 1260, "text": "There exists no intersection between [l1, r1] and [l2, r2]. Possible only when r1 < l2 or r2 < l1. In such a case answer will be 0 i.e. no intersection exists." }, { "code": null, "e": 1547, "s": 1420, "text": "There exists an intersection between [l1, r1] and [l2, r2]. Then the required intersection will be [max(l1, l2), min(r1, r2)]." }, { "code": null, "e": 1599, "s": 1547, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 1603, "s": 1599, "text": "C++" }, { "code": null, "e": 1608, "s": 1603, "text": "Java" }, { "code": null, "e": 1615, "s": 1608, "text": "Python" }, { "code": null, "e": 1618, "s": 1615, "text": "C#" }, { "code": null, "e": 1622, "s": 1618, "text": "PHP" }, { "code": null, "e": 1633, "s": 1622, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to print the intersectionvoid findIntersection(int intervals[][2], int N){ // First interval int l = intervals[0][0]; int r = intervals[0][1]; // Check rest of the intervals and find the intersection for (int i = 1; i < N; i++) { // If no intersection exists if (intervals[i][0] > r || intervals[i][1] < l) { cout << -1; return; } // Else update the intersection else { l = max(l, intervals[i][0]); r = min(r, intervals[i][1]); } } cout << \"[\" << l << \", \" << r << \"]\";} // Driver codeint main(){ int intervals[][2] = { { 1, 6 }, { 2, 8 }, { 3, 10 }, { 5, 8 } }; int N = sizeof(intervals) / sizeof(intervals[0]); findIntersection(intervals, N);}", "e": 2524, "s": 1633, "text": null }, { "code": "// Java implementation of the approachimport java.io.*; class GFG{ // Function to print the intersectionstatic void findIntersection(int intervals[][], int N){ // First interval int l = intervals[0][0]; int r = intervals[0][1]; // Check rest of the intervals // and find the intersection for (int i = 1; i < N; i++) { // If no intersection exists if (intervals[i][0] > r || intervals[i][1] < l) { System.out.println(-1); return; } // Else update the intersection else { l = Math.max(l, intervals[i][0]); r = Math.min(r, intervals[i][1]); } } System.out.println (\"[\" + l +\", \" + r + \"]\");} // Driver code public static void main (String[] args) { int intervals[][] = {{ 1, 6 }, { 2, 8 }, { 3, 10 }, { 5, 8 }}; int N = intervals.length; findIntersection(intervals, N); }} // This Code is contributed by ajit..", "e": 3593, "s": 2524, "text": null }, { "code": "# Python3 implementation of the approach # Function to print the intersectiondef findIntersection(intervals,N): # First interval l = intervals[0][0] r = intervals[0][1] # Check rest of the intervals # and find the intersection for i in range(1,N): # If no intersection exists if (intervals[i][0] > r or intervals[i][1] < l): print(-1) # Else update the intersection else: l = max(l, intervals[i][0]) r = min(r, intervals[i][1]) print(\"[\",l,\", \",r,\"]\") # Driver code intervals= [ [ 1, 6 ], [ 2, 8 ], [ 3, 10 ], [ 5, 8 ] ]N =len(intervals)findIntersection(intervals, N) # this code is contributed by mohit kumar", "e": 4359, "s": 3593, "text": null }, { "code": "// C# implementation of the approachusing System; class GFG{ // Function to print the intersectionstatic void findIntersection(int [,]intervals, int N){ // First interval int l = intervals[0, 0]; int r = intervals[0, 1]; // Check rest of the intervals // and find the intersection for (int i = 1; i < N; i++) { // If no intersection exists if (intervals[i, 0] > r || intervals[i, 1] < l) { Console.WriteLine(-1); return; } // Else update the intersection else { l = Math.Max(l, intervals[i, 0]); r = Math.Min(r, intervals[i, 1]); } } Console.WriteLine(\"[\" + l + \", \" + r + \"]\");} // Driver codepublic static void Main(){ int [,]intervals = {{ 1, 6 }, { 2, 8 }, { 3, 10 }, { 5, 8 }}; int N = intervals.GetLength(0); findIntersection(intervals, N);}} // This code is contributed by Ryuga", "e": 5322, "s": 4359, "text": null }, { "code": "<?php// PHP implementation of the approach // Function to print the intersectionfunction findIntersection($intervals, $N){ // First interval $l = $intervals[0][0]; $r = $intervals[0][1]; // Check rest of the intervals and // find the intersection for ($i = 1; $i < $N; $i++) { // If no intersection exists if ($intervals[$i][0] > $r || $intervals[$i][1] < $l) { echo -1; return; } // Else update the intersection else { $l = max($l, $intervals[$i][0]); $r = min($r, $intervals[$i][1]); } } echo \"[\" . $l . \", \" . $r . \"]\";} // Driver code$intervals = array(array(1, 6), array(2, 8), array(3, 10), array(5, 8));$N = sizeof($intervals);findIntersection($intervals, $N); // This code is contributed// by Akanksha Rai?>", "e": 6198, "s": 5322, "text": null }, { "code": "<script> // Javascript implementation of the approach // Function to print the intersection function findIntersection(intervals, N) { // First interval let l = intervals[0][0]; let r = intervals[0][1]; // Check rest of the intervals // and find the intersection for (let i = 1; i < N; i++) { // If no intersection exists if (intervals[i][0] > r || intervals[i][1] < l) { document.write(-1 + \"</br>\"); return; } // Else update the intersection else { l = Math.max(l, intervals[i][0]); r = Math.min(r, intervals[i][1]); } } document.write(\"[\" + l +\", \" + r + \"]\" + \"</br>\"); } let intervals = [[ 1, 6 ], [ 2, 8 ], [ 3, 10], [ 5, 8 ]]; let N = intervals.length; findIntersection(intervals, N); </script>", "e": 7222, "s": 6198, "text": null }, { "code": null, "e": 7229, "s": 7222, "text": "[5, 6]" }, { "code": null, "e": 7237, "s": 7231, "text": "jit_t" }, { "code": null, "e": 7245, "s": 7237, "text": "ankthon" }, { "code": null, "e": 7258, "s": 7245, "text": "Akanksha_Rai" }, { "code": null, "e": 7273, "s": 7258, "text": "mohit kumar 29" }, { "code": null, "e": 7291, "s": 7273, "text": "divyeshrabadiya07" }, { "code": null, "e": 7298, "s": 7291, "text": "Arrays" }, { "code": null, "e": 7322, "s": 7298, "text": "Competitive Programming" }, { "code": null, "e": 7329, "s": 7322, "text": "Greedy" }, { "code": null, "e": 7336, "s": 7329, "text": "Arrays" }, { "code": null, "e": 7343, "s": 7336, "text": "Greedy" } ]
Reshape Wide DataFrame to Tidy with identifiers using Pandas Melt
02 Feb, 2021 Sometimes we need to reshape the Pandas data frame to perform analysis in a better way. Reshaping plays a crucial role in data analysis. Pandas provide functions like melt and unmelt for reshaping. In this article, we will see what is Pandas Melt and how to use it to reshape wide to Tidy with identifiers. Pandas Melt(): Pandas.melt() unpivots a DataFrame from wide format to long format. Pandas melt() function is utilized to change the DataFrame design from wide to long. It is utilized to make a particular configuration of the DataFrame object where at least one segments fill in as identifiers. All the rest of the sections are treated as qualities and unpivoted to the line pivot and just two segments, variable and worth. Syntax: Pandas.melt(column_level=None, variable_name=None, Value_name=’value’, value_vars=None, id_vars=None, frame) Parameters: frame : DataFrame id_vars[tuple, list, or ndarray, optional]: Column(s) to use as identifier variables. value_vars[tuple, list, or ndarray, optional]: Column(s) to unpivot. If not specified, uses all columns that are not set as id_vars. var_name[scalar]: Name to use for the ‘variable’ column. If None it uses frame.columns.name or ‘variable’. value_name[scalar, default ‘value’]: Name to use for the ‘value’ column. col_level[int or string, optional]: If columns are a MultiIndex then use this level to melt. Example 1: Python3 # Load the librariesimport numpy as npimport pandas as pdfrom scipy.stats import poisson # We will use scipy.stats to create# random numbers from Poisson distribution.np.random.seed(seed = 128)p1 = poisson.rvs(mu = 10, size = 3)p2 = poisson.rvs(mu = 15, size = 3)p3 = poisson.rvs(mu = 20, size = 3) # Declaring the dataframedata = pd.DataFrame({"P1":p1, "P2":p2, "P3":p3}) # Dataframeprint(" Wide Dataframe")display(data) data.melt() # Change the names of the columnsdata.melt(var_name = ["Sample"]).head() # Specify a name for the valuesprint("\n Tidy Dataframe")data.melt(var_name = "Sample", value_name = "Count").head() Output: Explanation: In this example, we create three datasets using Poisson distribution and create a data frame using pandas. Then using the melt() function we reshape the data in long-form in two columns and rename the two columns. The first column is called “variable” by default and it contains the column/variable names. And the second column is named “value” and it contains the data from the wide form data frame. Example 2: Python3 import pandas as pd data = pd.DataFrame({'Name': {0: 'Samrat', 1: 'Tomar', 2: 'Verma'}, 'Score': {0: '99', 1: '98', 2: '97'}, 'Age': {0: 22, 1: 31, 2: 33}}) pd.melt(data, id_vars=['Name'], value_vars=['Score']) display(pd.melt(data, id_vars=['Name'], value_vars=['Score'])) Output: Explanation: In this example, we create a data frame using pandas. Then using the melt() function we reshape the data in long-form in three columns and specify the Name as the id and variable as Score the person and the value as their scores. Apart from the “id” column, The first column is called “variable” by default and it contains the column/variable names. And the second column is named “value” and it contains the data from the wide form data frame. Picked Python pandas-dataFrame Python Pandas-exercise Python-pandas 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": 28, "s": 0, "text": "\n02 Feb, 2021" }, { "code": null, "e": 335, "s": 28, "text": "Sometimes we need to reshape the Pandas data frame to perform analysis in a better way. Reshaping plays a crucial role in data analysis. Pandas provide functions like melt and unmelt for reshaping. In this article, we will see what is Pandas Melt and how to use it to reshape wide to Tidy with identifiers." }, { "code": null, "e": 759, "s": 335, "text": "Pandas Melt(): Pandas.melt() unpivots a DataFrame from wide format to long format. Pandas melt() function is utilized to change the DataFrame design from wide to long. It is utilized to make a particular configuration of the DataFrame object where at least one segments fill in as identifiers. All the rest of the sections are treated as qualities and unpivoted to the line pivot and just two segments, variable and worth. " }, { "code": null, "e": 876, "s": 759, "text": "Syntax: Pandas.melt(column_level=None, variable_name=None, Value_name=’value’, value_vars=None, id_vars=None, frame)" }, { "code": null, "e": 888, "s": 876, "text": "Parameters:" }, { "code": null, "e": 906, "s": 888, "text": "frame : DataFrame" }, { "code": null, "e": 992, "s": 906, "text": "id_vars[tuple, list, or ndarray, optional]: Column(s) to use as identifier variables." }, { "code": null, "e": 1125, "s": 992, "text": "value_vars[tuple, list, or ndarray, optional]: Column(s) to unpivot. If not specified, uses all columns that are not set as id_vars." }, { "code": null, "e": 1232, "s": 1125, "text": "var_name[scalar]: Name to use for the ‘variable’ column. If None it uses frame.columns.name or ‘variable’." }, { "code": null, "e": 1305, "s": 1232, "text": "value_name[scalar, default ‘value’]: Name to use for the ‘value’ column." }, { "code": null, "e": 1398, "s": 1305, "text": "col_level[int or string, optional]: If columns are a MultiIndex then use this level to melt." }, { "code": null, "e": 1410, "s": 1398, "text": "Example 1: " }, { "code": null, "e": 1418, "s": 1410, "text": "Python3" }, { "code": "# Load the librariesimport numpy as npimport pandas as pdfrom scipy.stats import poisson # We will use scipy.stats to create# random numbers from Poisson distribution.np.random.seed(seed = 128)p1 = poisson.rvs(mu = 10, size = 3)p2 = poisson.rvs(mu = 15, size = 3)p3 = poisson.rvs(mu = 20, size = 3) # Declaring the dataframedata = pd.DataFrame({\"P1\":p1, \"P2\":p2, \"P3\":p3}) # Dataframeprint(\" Wide Dataframe\")display(data) data.melt() # Change the names of the columnsdata.melt(var_name = [\"Sample\"]).head() # Specify a name for the valuesprint(\"\\n Tidy Dataframe\")data.melt(var_name = \"Sample\", value_name = \"Count\").head()", "e": 2089, "s": 1418, "text": null }, { "code": null, "e": 2097, "s": 2089, "text": "Output:" }, { "code": null, "e": 2511, "s": 2097, "text": "Explanation: In this example, we create three datasets using Poisson distribution and create a data frame using pandas. Then using the melt() function we reshape the data in long-form in two columns and rename the two columns. The first column is called “variable” by default and it contains the column/variable names. And the second column is named “value” and it contains the data from the wide form data frame." }, { "code": null, "e": 2523, "s": 2511, "text": "Example 2: " }, { "code": null, "e": 2531, "s": 2523, "text": "Python3" }, { "code": "import pandas as pd data = pd.DataFrame({'Name': {0: 'Samrat', 1: 'Tomar', 2: 'Verma'}, 'Score': {0: '99', 1: '98', 2: '97'}, 'Age': {0: 22, 1: 31, 2: 33}}) pd.melt(data, id_vars=['Name'], value_vars=['Score']) display(pd.melt(data, id_vars=['Name'], value_vars=['Score']))", "e": 2850, "s": 2531, "text": null }, { "code": null, "e": 2860, "s": 2850, "text": "Output: " }, { "code": null, "e": 3319, "s": 2860, "text": "Explanation: In this example, we create a data frame using pandas. Then using the melt() function we reshape the data in long-form in three columns and specify the Name as the id and variable as Score the person and the value as their scores. Apart from the “id” column, The first column is called “variable” by default and it contains the column/variable names. And the second column is named “value” and it contains the data from the wide form data frame. " }, { "code": null, "e": 3326, "s": 3319, "text": "Picked" }, { "code": null, "e": 3350, "s": 3326, "text": "Python pandas-dataFrame" }, { "code": null, "e": 3373, "s": 3350, "text": "Python Pandas-exercise" }, { "code": null, "e": 3387, "s": 3373, "text": "Python-pandas" }, { "code": null, "e": 3411, "s": 3387, "text": "Technical Scripter 2020" }, { "code": null, "e": 3418, "s": 3411, "text": "Python" }, { "code": null, "e": 3437, "s": 3418, "text": "Technical Scripter" } ]
Flip Binary Tree
05 Jul, 2022 AGiven a binary tree, the task is to flip the binary tree towards the right direction that is clockwise. See the below examples to see the transformation. In the flip operation, the leftmost node becomes the root of the flipped tree and its parent becomes its right child and the right sibling becomes its left child and the same should be done for all left most nodes recursively. Chapters descriptions off, selected captions settings, opens captions settings dialog captions off, selected English This is a modal window. Beginning of dialog window. Escape will cancel and close the window. End of dialog window. Below is the main rotation code of a subtree root->left->left = root->right; root->left->right = root; root->left = NULL; root->right = NULL; The above code can be understood by the following diagram – As we are storing root->left in the flipped root, flipped subtree gets stored in each recursive call. Implementation: C++ Java Python3 C# Javascript /* C/C++ program to flip a binary tree */#include <bits/stdc++.h>using namespace std; /* A binary tree node structure */struct Node{ int data; Node *left, *right;}; /* Utility function to create a new Binary Tree Node */struct Node* newNode(int data){ struct Node *temp = new struct Node; temp->data = data; temp->left = temp->right = NULL; return temp;} // method to flip the binary treeNode* flipBinaryTree(Node* root){ // Base cases if (root == NULL) return root; if (root->left == NULL && root->right == NULL) return root; // recursively call the same method Node* flippedRoot = flipBinaryTree(root->left); // rearranging main root Node after returning // from recursive call root->left->left = root->right; root->left->right = root; root->left = root->right = NULL; return flippedRoot;} // Iterative method to do level order traversal// line by linevoid printLevelOrder(Node *root){ // Base Case if (root == NULL) return; // Create an empty queue for level order traversal queue<Node *> q; // Enqueue Root and initialize height q.push(root); while (1) { // nodeCount (queue size) indicates number // of nodes at current level. int nodeCount = q.size(); if (nodeCount == 0) break; // Dequeue all nodes of current level and // Enqueue all nodes of next level while (nodeCount > 0) { Node *node = q.front(); cout << node->data << " "; q.pop(); if (node->left != NULL) q.push(node->left); if (node->right != NULL) q.push(node->right); nodeCount--; } cout << endl; }} // Driver codeint main(){ Node* root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->right->left = newNode(4); root->right->right = newNode(5); cout << "Level order traversal of given tree\n"; printLevelOrder(root); root = flipBinaryTree(root); cout << "\nLevel order traversal of the flipped" " tree\n"; printLevelOrder(root); return 0;} /* Java program to flip a binary tree */import java.util.Queue;import java.util.LinkedList;public class FlipTree { // method to flip the binary tree public static Node flipBinaryTree(Node root) { if (root == null) return root; if (root.left == null && root.right ==null) return root; // recursively call the same method Node flippedRoot=flipBinaryTree(root.left); // rearranging main root Node after returning // from recursive call root.left.left=root.right; root.left.right=root; root.left=root.right=null; return flippedRoot; } // Iterative method to do level order traversal // line by line public static void printLevelOrder(Node root) { // Base Case if(root==null) return ; // Create an empty queue for level order traversal Queue<Node> q=new LinkedList<>(); // Enqueue Root and initialize height q.add(root); while(true) { // nodeCount (queue size) indicates number // of nodes at current level. int nodeCount = q.size(); if (nodeCount == 0) break; // Dequeue all nodes of current level and // Enqueue all nodes of next level while (nodeCount > 0) { Node node = q.remove(); System.out.print(node.data+" "); if (node.left != null) q.add(node.left); if (node.right != null) q.add(node.right); nodeCount--; } System.out.println(); } } public static void main(String args[]) { Node root=new Node(1); root.left=new Node(2); root.right=new Node(1); root.right.left = new Node(4); root.right.right = new Node(5); System.out.println("Level order traversal of given tree"); printLevelOrder(root); root = flipBinaryTree(root); System.out.println("Level order traversal of flipped tree"); printLevelOrder(root); }} /* A binary tree node structure */class Node{ int data; Node left, right; Node(int data) { this.data=data; }}; //This code is contributed by Gaurav Tiwari # Python3 program to flip# a binary tree # A binary tree nodeclass Node: # Constructor to create # a new node def __init__(self, data): self.data = data self.right = None self.left = None def flipBinaryTree(root): # Base Cases if root is None: return root if (root.left is None and root.right is None): return root # Recursively call the # same method flippedRoot = flipBinaryTree(root.left) # Rearranging main root Node # after returning from # recursive call root.left.left = root.right root.left.right = root root.left = root.right = None return flippedRoot # Iterative method to do the level# order traversal line by linedef printLevelOrder(root): # Base Case if root is None: return # Create an empty queue for # level order traversal from Queue import Queue q = Queue() # Enqueue root and initialize # height q.put(root) while(True): # nodeCount (queue size) indicates # number of nodes at current level nodeCount = q.qsize() if nodeCount == 0: break # Dequeue all nodes of current # level and Enqueue all nodes # of next level while nodeCount > 0: node = q.get() print node.data, if node.left is not None: q.put(node.left) if node.right is not None: q.put(node.right) nodeCount -= 1 print # Driver coderoot = Node(1)root.left = Node(2)root.right = Node(3)root.right.left = Node(4)root.right.right = Node(5) print "Level order traversal of given tree"printLevelOrder(root) root = flipBinaryTree(root) print "\nLevel order traversal of the flipped tree"printLevelOrder(root) # This code is contributed by Nikhil Kumar Singh(nickzuck_007) // C# program to flip a binary treeusing System;using System.Collections.Generic; public class FlipTree{ // method to flip the binary tree public static Node flipBinaryTree(Node root) { if (root == null) return root; if (root.left == null && root.right ==null) return root; // recursively call the same method Node flippedRoot = flipBinaryTree(root.left); // rearranging main root Node after returning // from recursive call root.left.left = root.right; root.left.right = root; root.left = root.right = null; return flippedRoot; } // Iterative method to do level order traversal // line by line public static void printLevelOrder(Node root) { // Base Case if(root == null) return ; // Create an empty queue for level order traversal Queue<Node> q = new Queue<Node>(); // Enqueue Root and initialize height q.Enqueue(root); while(true) { // nodeCount (queue size) indicates number // of nodes at current level. int nodeCount = q.Count; if (nodeCount == 0) break; // Dequeue all nodes of current level and // Enqueue all nodes of next level while (nodeCount > 0) { Node node = q.Dequeue(); Console.Write(node.data+" "); if (node.left != null) q.Enqueue(node.left); if (node.right != null) q.Enqueue(node.right); nodeCount--; } Console.WriteLine(); } } // Driver code public static void Main(String []args) { Node root = new Node(1); root.left = new Node(2); root.right = new Node(1); root.right.left = new Node(4); root.right.right = new Node(5); Console.WriteLine("Level order traversal of given tree"); printLevelOrder(root); root = flipBinaryTree(root); Console.WriteLine("Level order traversal of flipped tree"); printLevelOrder(root); }} /* A binary tree node structure */public class Node{ public int data; public Node left, right; public Node(int data) { this.data = data; }}; // This code is contributed by Princi Singh <script>/* Javascript program to flip a binary tree */ /* A binary tree node structure */ class Node { constructor( data) { this.data = data; this.left=this.right=null; } }; // method to flip the binary tree function flipBinaryTree(root) { if (root == null) return root; if (root.left == null && root.right ==null) return root; // recursively call the same method let flippedRoot=flipBinaryTree(root.left); // rearranging main root Node after returning // from recursive call root.left.left=root.right; root.left.right=root; root.left=root.right=null; return flippedRoot; } // Iterative method to do level order traversal // line by line function printLevelOrder(root) { // Base Case if(root==null) return ; // Create an empty queue for level order traversal let q=[]; // Enqueue Root and initialize height q.push(root); while(true) { // nodeCount (queue size) indicates number // of nodes at current level. let nodeCount = q.length; if (nodeCount == 0) break; // Dequeue all nodes of current level and // Enqueue all nodes of next level while (nodeCount > 0) { let node = q.shift(); document.write(node.data+" "); if (node.left != null) q.push(node.left); if (node.right != null) q.push(node.right); nodeCount--; } document.write("<br>"); } } let root=new Node(1); root.left=new Node(2); root.right=new Node(3); root.right.left = new Node(4); root.right.right = new Node(5); document.write("Level order traversal of given tree<br>"); printLevelOrder(root); root = flipBinaryTree(root); document.write("Level order traversal of flipped tree<br>"); printLevelOrder(root); // This code is contributed by unknown2108</script> Level order traversal of given tree 1 2 3 4 5 Level order traversal of the flipped tree 2 3 1 4 5 Iterative Approach: This approach is contributed by Pal13. The iterative solution follows the same approach as the recursive one, the only thing we need to pay attention to is to save the node information that will be overwritten. Implementation: C++ Java Python3 C# Javascript // C/C++ program to flip a binary tree#include <bits/stdc++.h>using namespace std; // A binary tree node structurestruct Node{ int data; Node *left, *right;}; // Utility function to create a new Binary// Tree Nodestruct Node* newNode(int data){ struct Node *temp = new struct Node; temp->data = data; temp->left = temp->right = NULL; return temp;} // method to flip the binary treeNode* flipBinaryTree(Node* root){ // Initialization of pointers Node *curr = root; Node *next = NULL; Node *temp = NULL; Node *prev = NULL; // Iterate through all left nodes while(curr) { next = curr->left; // Swapping nodes now, need temp to keep the previous right child // Making prev's right as curr's left child curr->left = temp; // Storing curr's right child temp = curr->right; // Making prev as curr's right child curr->right = prev; prev = curr; curr = next; } return prev;} // Iterative method to do level order traversal// line by linevoid printLevelOrder(Node *root){ // Base Case if (root == NULL) return; // Create an empty queue for level order traversal queue<Node *> q; // Enqueue Root and initialize height q.push(root); while (1) { // nodeCount (queue size) indicates number // of nodes at current level. int nodeCount = q.size(); if (nodeCount == 0) break; // Dequeue all nodes of current level and // Enqueue all nodes of next level while (nodeCount > 0) { Node *node = q.front(); cout << node->data << " "; q.pop(); if (node->left != NULL) q.push(node->left); if (node->right != NULL) q.push(node->right); nodeCount--; } cout << endl; }} // Driver codeint main(){ Node* root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->right->left = newNode(4); root->right->right = newNode(5); cout << "Level order traversal of given tree\n"; printLevelOrder(root); root = flipBinaryTree(root); cout << "\nLevel order traversal of the flipped" " tree\n"; printLevelOrder(root); return 0;} // This article is contributed by Pal13 // Java program to flip a binary treeimport java.util.*;class GFG{ // A binary tree nodestatic class Node{ int data; Node left, right;}; // Utility function to create// a new Binary Tree Node static Node newNode(int data){ Node temp = new Node(); temp.data = data; temp.left = temp.right = null; return temp;} // method to flip the binary treestatic Node flipBinaryTree(Node root){ // Initialization of pointers Node curr = root; Node next = null; Node temp = null; Node prev = null; // Iterate through all left nodes while(curr != null) { next = curr.left; // Swapping nodes now, need // temp to keep the previous // right child // Making prev's right // as curr's left child curr.left = temp; // Storing curr's right child temp = curr.right; // Making prev as curr's // right child curr.right = prev; prev = curr; curr = next; } return prev;} // Iterative method to do// level order traversal// line by linestatic void printLevelOrder(Node root){ // Base Case if (root == null) return; // Create an empty queue for // level order traversal Queue<Node> q = new LinkedList<Node>(); // Enqueue Root and // initialize height q.add(root); while (true) { // nodeCount (queue size) // indicates number of nodes // at current level. int nodeCount = q.size(); if (nodeCount == 0) break; // Dequeue all nodes of current // level and Enqueue all nodes // of next level while (nodeCount > 0) { Node node = q.peek(); System.out.print(node.data + " "); q.remove(); if (node.left != null) q.add(node.left); if (node.right != null) q.add(node.right); nodeCount--; } System.out.println(); }} // Driver codepublic static void main(String args[]){ Node root = newNode(1); root.left = newNode(2); root.right = newNode(3); root.right.left = newNode(4); root.right.right = newNode(5); System.out.print("Level order traversal " + "of given tree\n"); printLevelOrder(root); root = flipBinaryTree(root); System.out.print("\nLevel order traversal " + "of the flipped tree\n"); printLevelOrder(root);}} // This code is contributed// by Arnab Kundu # Python3 program to flip# a binary treefrom collections import deque # A binary tree node structureclass Node: def __init__(self, key): self.data = key self.left = None self.right = None # method to flip the# binary treedef flipBinaryTree(root): # Initialization of # pointers curr = root next = None temp = None prev = None # Iterate through all # left nodes while(curr): next = curr.left # Swapping nodes now, need temp # to keep the previous right child # Making prev's right as curr's # left child curr.left = temp # Storing curr's right child temp = curr.right # Making prev as curr's right # child curr.right = prev prev = curr curr = next return prev # Iterative method to do level# order traversal line by linedef printLevelOrder(root): # Base Case if (root == None): return # Create an empty queue for # level order traversal q = deque() # Enqueue Root and initialize # height q.append(root) while (1): # nodeCount (queue size) indicates # number of nodes at current level. nodeCount = len(q) if (nodeCount == 0): break # Dequeue all nodes of current # level and Enqueue all nodes # of next level while (nodeCount > 0): node = q.popleft() print(node.data, end = " ") if (node.left != None): q.append(node.left) if (node.right != None): q.append(node.right) nodeCount -= 1 print() # Driver codeif __name__ == '__main__': root = Node(1) root.left = Node(2) root.right = Node(3) root.right.left = Node(4) root.right.right = Node(5) print("Level order traversal of given tree") printLevelOrder(root) root = flipBinaryTree(root) print("\nLevel order traversal of the flipped" " tree") printLevelOrder(root) # This code is contributed by Mohit Kumar 29 // C# program to flip a binary treeusing System;using System.Collections.Generic; class GFG{ // A binary tree nodepublic class Node{ public int data; public Node left, right;} // Utility function to create// a new Binary Tree Nodepublic static Node newNode(int data){ Node temp = new Node(); temp.data = data; temp.left = temp.right = null; return temp;} // method to flip the binary treepublic static Node flipBinaryTree(Node root){ // Initialization of pointers Node curr = root; Node next = null; Node temp = null; Node prev = null; // Iterate through all left nodes while (curr != null) { next = curr.left; // Swapping nodes now, need // temp to keep the previous // right child // Making prev's right // as curr's left child curr.left = temp; // Storing curr's right child temp = curr.right; // Making prev as curr's // right child curr.right = prev; prev = curr; curr = next; } return prev;} // Iterative method to do level// order traversal line by linepublic static void printLevelOrder(Node root){ // Base Case if (root == null) { return; } // Create an empty queue for // level order traversal LinkedList<Node> q = new LinkedList<Node>(); // Enqueue Root and // initialize height q.AddLast(root); while (true) { // nodeCount (queue size) // indicates number of nodes // at current level. int nodeCount = q.Count; if (nodeCount == 0) { break; } // Dequeue all nodes of current // level and Enqueue all nodes // of next level while (nodeCount > 0) { Node node = q.First.Value; Console.Write(node.data + " "); q.RemoveFirst(); if (node.left != null) { q.AddLast(node.left); } if (node.right != null) { q.AddLast(node.right); } nodeCount--; } Console.WriteLine(); }} // Driver codepublic static void Main(string[] args){ Node root = newNode(1); root.left = newNode(2); root.right = newNode(3); root.right.left = newNode(4); root.right.right = newNode(5); Console.Write("Level order traversal " + "of given tree\n"); printLevelOrder(root); root = flipBinaryTree(root); Console.Write("\nLevel order traversal " + "of the flipped tree\n"); printLevelOrder(root);}} // This code is contributed by Shrikant13 <script> // JavaScript program to flip a binary tree class Node { constructor(data) { this.left = null; this.right = null; this.data = data; } } // Utility function to create // a new Binary Tree Node function newNode(data) { let temp = new Node(data); return temp; } // method to flip the binary tree function flipBinaryTree(root) { // Initialization of pointers let curr = root; let next = null; let temp = null; let prev = null; // Iterate through all left nodes while(curr != null) { next = curr.left; // Swapping nodes now, need // temp to keep the previous // right child // Making prev's right // as curr's left child curr.left = temp; // Storing curr's right child temp = curr.right; // Making prev as curr's // right child curr.right = prev; prev = curr; curr = next; } return prev; } // Iterative method to do // level order traversal // line by line function printLevelOrder(root) { // Base Case if (root == null) return; // Create an empty queue for // level order traversal let q = []; // Enqueue Root and // initialize height q.push(root); while (true) { // nodeCount (queue size) // indicates number of nodes // at current level. let nodeCount = q.length; if (nodeCount == 0) break; // Dequeue all nodes of current // level and Enqueue all nodes // of next level while (nodeCount > 0) { let node = q[0]; document.write(node.data + " "); q.shift(); if (node.left != null) q.push(node.left); if (node.right != null) q.push(node.right); nodeCount--; } document.write("</br>"); } } let root = newNode(1); root.left = newNode(2); root.right = newNode(3); root.right.left = newNode(4); root.right.right = newNode(5); document.write("Level order traversal " + "of given tree" + "</br>"); printLevelOrder(root); root = flipBinaryTree(root); document.write("</br>" + "Level order traversal " + "of the flipped tree" + "</br>"); printLevelOrder(root); </script> Level order traversal of given tree 1 2 3 4 5 Level order traversal of the flipped tree 2 3 1 4 5 Complexity Analysis: Time complexity: O(n) as in the worst case, depth of binary tree will be n. Auxiliary Space: O(1). 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. andrew1234 shrikanth13 _Gaurav_Tiwari princi singh mohit kumar 29 unknown2108 anikakapoor suresh07 sweetyty hardikkoriintern 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": "\n05 Jul, 2022" }, { "code": null, "e": 207, "s": 52, "text": "AGiven a binary tree, the task is to flip the binary tree towards the right direction that is clockwise. See the below examples to see the transformation." }, { "code": null, "e": 435, "s": 207, "text": "In the flip operation, the leftmost node becomes the root of the flipped tree and its parent becomes its right child and the right sibling becomes its left child and the same should be done for all left most nodes recursively. " }, { "code": null, "e": 444, "s": 435, "text": "Chapters" }, { "code": null, "e": 471, "s": 444, "text": "descriptions off, selected" }, { "code": null, "e": 521, "s": 471, "text": "captions settings, opens captions settings dialog" }, { "code": null, "e": 544, "s": 521, "text": "captions off, selected" }, { "code": null, "e": 552, "s": 544, "text": "English" }, { "code": null, "e": 576, "s": 552, "text": "This is a modal window." }, { "code": null, "e": 645, "s": 576, "text": "Beginning of dialog window. Escape will cancel and close the window." }, { "code": null, "e": 667, "s": 645, "text": "End of dialog window." }, { "code": null, "e": 713, "s": 667, "text": "Below is the main rotation code of a subtree " }, { "code": null, "e": 827, "s": 713, "text": " root->left->left = root->right;\n root->left->right = root;\n root->left = NULL;\n root->right = NULL; " }, { "code": null, "e": 888, "s": 827, "text": "The above code can be understood by the following diagram – " }, { "code": null, "e": 990, "s": 888, "text": "As we are storing root->left in the flipped root, flipped subtree gets stored in each recursive call." }, { "code": null, "e": 1006, "s": 990, "text": "Implementation:" }, { "code": null, "e": 1010, "s": 1006, "text": "C++" }, { "code": null, "e": 1015, "s": 1010, "text": "Java" }, { "code": null, "e": 1023, "s": 1015, "text": "Python3" }, { "code": null, "e": 1026, "s": 1023, "text": "C#" }, { "code": null, "e": 1037, "s": 1026, "text": "Javascript" }, { "code": "/* C/C++ program to flip a binary tree */#include <bits/stdc++.h>using namespace std; /* A binary tree node structure */struct Node{ int data; Node *left, *right;}; /* Utility function to create a new Binary Tree Node */struct Node* newNode(int data){ struct Node *temp = new struct Node; temp->data = data; temp->left = temp->right = NULL; return temp;} // method to flip the binary treeNode* flipBinaryTree(Node* root){ // Base cases if (root == NULL) return root; if (root->left == NULL && root->right == NULL) return root; // recursively call the same method Node* flippedRoot = flipBinaryTree(root->left); // rearranging main root Node after returning // from recursive call root->left->left = root->right; root->left->right = root; root->left = root->right = NULL; return flippedRoot;} // Iterative method to do level order traversal// line by linevoid printLevelOrder(Node *root){ // Base Case if (root == NULL) return; // Create an empty queue for level order traversal queue<Node *> q; // Enqueue Root and initialize height q.push(root); while (1) { // nodeCount (queue size) indicates number // of nodes at current level. int nodeCount = q.size(); if (nodeCount == 0) break; // Dequeue all nodes of current level and // Enqueue all nodes of next level while (nodeCount > 0) { Node *node = q.front(); cout << node->data << \" \"; q.pop(); if (node->left != NULL) q.push(node->left); if (node->right != NULL) q.push(node->right); nodeCount--; } cout << endl; }} // Driver codeint main(){ Node* root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->right->left = newNode(4); root->right->right = newNode(5); cout << \"Level order traversal of given tree\\n\"; printLevelOrder(root); root = flipBinaryTree(root); cout << \"\\nLevel order traversal of the flipped\" \" tree\\n\"; printLevelOrder(root); return 0;}", "e": 3197, "s": 1037, "text": null }, { "code": "/* Java program to flip a binary tree */import java.util.Queue;import java.util.LinkedList;public class FlipTree { // method to flip the binary tree public static Node flipBinaryTree(Node root) { if (root == null) return root; if (root.left == null && root.right ==null) return root; // recursively call the same method Node flippedRoot=flipBinaryTree(root.left); // rearranging main root Node after returning // from recursive call root.left.left=root.right; root.left.right=root; root.left=root.right=null; return flippedRoot; } // Iterative method to do level order traversal // line by line public static void printLevelOrder(Node root) { // Base Case if(root==null) return ; // Create an empty queue for level order traversal Queue<Node> q=new LinkedList<>(); // Enqueue Root and initialize height q.add(root); while(true) { // nodeCount (queue size) indicates number // of nodes at current level. int nodeCount = q.size(); if (nodeCount == 0) break; // Dequeue all nodes of current level and // Enqueue all nodes of next level while (nodeCount > 0) { Node node = q.remove(); System.out.print(node.data+\" \"); if (node.left != null) q.add(node.left); if (node.right != null) q.add(node.right); nodeCount--; } System.out.println(); } } public static void main(String args[]) { Node root=new Node(1); root.left=new Node(2); root.right=new Node(1); root.right.left = new Node(4); root.right.right = new Node(5); System.out.println(\"Level order traversal of given tree\"); printLevelOrder(root); root = flipBinaryTree(root); System.out.println(\"Level order traversal of flipped tree\"); printLevelOrder(root); }} /* A binary tree node structure */class Node{ int data; Node left, right; Node(int data) { this.data=data; }}; //This code is contributed by Gaurav Tiwari", "e": 5525, "s": 3197, "text": null }, { "code": "# Python3 program to flip# a binary tree # A binary tree nodeclass Node: # Constructor to create # a new node def __init__(self, data): self.data = data self.right = None self.left = None def flipBinaryTree(root): # Base Cases if root is None: return root if (root.left is None and root.right is None): return root # Recursively call the # same method flippedRoot = flipBinaryTree(root.left) # Rearranging main root Node # after returning from # recursive call root.left.left = root.right root.left.right = root root.left = root.right = None return flippedRoot # Iterative method to do the level# order traversal line by linedef printLevelOrder(root): # Base Case if root is None: return # Create an empty queue for # level order traversal from Queue import Queue q = Queue() # Enqueue root and initialize # height q.put(root) while(True): # nodeCount (queue size) indicates # number of nodes at current level nodeCount = q.qsize() if nodeCount == 0: break # Dequeue all nodes of current # level and Enqueue all nodes # of next level while nodeCount > 0: node = q.get() print node.data, if node.left is not None: q.put(node.left) if node.right is not None: q.put(node.right) nodeCount -= 1 print # Driver coderoot = Node(1)root.left = Node(2)root.right = Node(3)root.right.left = Node(4)root.right.right = Node(5) print \"Level order traversal of given tree\"printLevelOrder(root) root = flipBinaryTree(root) print \"\\nLevel order traversal of the flipped tree\"printLevelOrder(root) # This code is contributed by Nikhil Kumar Singh(nickzuck_007)", "e": 7412, "s": 5525, "text": null }, { "code": "// C# program to flip a binary treeusing System;using System.Collections.Generic; public class FlipTree{ // method to flip the binary tree public static Node flipBinaryTree(Node root) { if (root == null) return root; if (root.left == null && root.right ==null) return root; // recursively call the same method Node flippedRoot = flipBinaryTree(root.left); // rearranging main root Node after returning // from recursive call root.left.left = root.right; root.left.right = root; root.left = root.right = null; return flippedRoot; } // Iterative method to do level order traversal // line by line public static void printLevelOrder(Node root) { // Base Case if(root == null) return ; // Create an empty queue for level order traversal Queue<Node> q = new Queue<Node>(); // Enqueue Root and initialize height q.Enqueue(root); while(true) { // nodeCount (queue size) indicates number // of nodes at current level. int nodeCount = q.Count; if (nodeCount == 0) break; // Dequeue all nodes of current level and // Enqueue all nodes of next level while (nodeCount > 0) { Node node = q.Dequeue(); Console.Write(node.data+\" \"); if (node.left != null) q.Enqueue(node.left); if (node.right != null) q.Enqueue(node.right); nodeCount--; } Console.WriteLine(); } } // Driver code public static void Main(String []args) { Node root = new Node(1); root.left = new Node(2); root.right = new Node(1); root.right.left = new Node(4); root.right.right = new Node(5); Console.WriteLine(\"Level order traversal of given tree\"); printLevelOrder(root); root = flipBinaryTree(root); Console.WriteLine(\"Level order traversal of flipped tree\"); printLevelOrder(root); }} /* A binary tree node structure */public class Node{ public int data; public Node left, right; public Node(int data) { this.data = data; }}; // This code is contributed by Princi Singh", "e": 9814, "s": 7412, "text": null }, { "code": "<script>/* Javascript program to flip a binary tree */ /* A binary tree node structure */ class Node { constructor( data) { this.data = data; this.left=this.right=null; } }; // method to flip the binary tree function flipBinaryTree(root) { if (root == null) return root; if (root.left == null && root.right ==null) return root; // recursively call the same method let flippedRoot=flipBinaryTree(root.left); // rearranging main root Node after returning // from recursive call root.left.left=root.right; root.left.right=root; root.left=root.right=null; return flippedRoot; } // Iterative method to do level order traversal // line by line function printLevelOrder(root) { // Base Case if(root==null) return ; // Create an empty queue for level order traversal let q=[]; // Enqueue Root and initialize height q.push(root); while(true) { // nodeCount (queue size) indicates number // of nodes at current level. let nodeCount = q.length; if (nodeCount == 0) break; // Dequeue all nodes of current level and // Enqueue all nodes of next level while (nodeCount > 0) { let node = q.shift(); document.write(node.data+\" \"); if (node.left != null) q.push(node.left); if (node.right != null) q.push(node.right); nodeCount--; } document.write(\"<br>\"); } } let root=new Node(1); root.left=new Node(2); root.right=new Node(3); root.right.left = new Node(4); root.right.right = new Node(5); document.write(\"Level order traversal of given tree<br>\"); printLevelOrder(root); root = flipBinaryTree(root); document.write(\"Level order traversal of flipped tree<br>\"); printLevelOrder(root); // This code is contributed by unknown2108</script>", "e": 12067, "s": 9814, "text": null }, { "code": null, "e": 12172, "s": 12067, "text": "Level order traversal of given tree\n1 \n2 3 \n4 5 \n\nLevel order traversal of the flipped tree\n2 \n3 1 \n4 5 " }, { "code": null, "e": 12404, "s": 12172, "text": "Iterative Approach: This approach is contributed by Pal13. The iterative solution follows the same approach as the recursive one, the only thing we need to pay attention to is to save the node information that will be overwritten. " }, { "code": null, "e": 12420, "s": 12404, "text": "Implementation:" }, { "code": null, "e": 12424, "s": 12420, "text": "C++" }, { "code": null, "e": 12429, "s": 12424, "text": "Java" }, { "code": null, "e": 12437, "s": 12429, "text": "Python3" }, { "code": null, "e": 12440, "s": 12437, "text": "C#" }, { "code": null, "e": 12451, "s": 12440, "text": "Javascript" }, { "code": "// C/C++ program to flip a binary tree#include <bits/stdc++.h>using namespace std; // A binary tree node structurestruct Node{ int data; Node *left, *right;}; // Utility function to create a new Binary// Tree Nodestruct Node* newNode(int data){ struct Node *temp = new struct Node; temp->data = data; temp->left = temp->right = NULL; return temp;} // method to flip the binary treeNode* flipBinaryTree(Node* root){ // Initialization of pointers Node *curr = root; Node *next = NULL; Node *temp = NULL; Node *prev = NULL; // Iterate through all left nodes while(curr) { next = curr->left; // Swapping nodes now, need temp to keep the previous right child // Making prev's right as curr's left child curr->left = temp; // Storing curr's right child temp = curr->right; // Making prev as curr's right child curr->right = prev; prev = curr; curr = next; } return prev;} // Iterative method to do level order traversal// line by linevoid printLevelOrder(Node *root){ // Base Case if (root == NULL) return; // Create an empty queue for level order traversal queue<Node *> q; // Enqueue Root and initialize height q.push(root); while (1) { // nodeCount (queue size) indicates number // of nodes at current level. int nodeCount = q.size(); if (nodeCount == 0) break; // Dequeue all nodes of current level and // Enqueue all nodes of next level while (nodeCount > 0) { Node *node = q.front(); cout << node->data << \" \"; q.pop(); if (node->left != NULL) q.push(node->left); if (node->right != NULL) q.push(node->right); nodeCount--; } cout << endl; }} // Driver codeint main(){ Node* root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->right->left = newNode(4); root->right->right = newNode(5); cout << \"Level order traversal of given tree\\n\"; printLevelOrder(root); root = flipBinaryTree(root); cout << \"\\nLevel order traversal of the flipped\" \" tree\\n\"; printLevelOrder(root); return 0;} // This article is contributed by Pal13", "e": 14874, "s": 12451, "text": null }, { "code": "// Java program to flip a binary treeimport java.util.*;class GFG{ // A binary tree nodestatic class Node{ int data; Node left, right;}; // Utility function to create// a new Binary Tree Node static Node newNode(int data){ Node temp = new Node(); temp.data = data; temp.left = temp.right = null; return temp;} // method to flip the binary treestatic Node flipBinaryTree(Node root){ // Initialization of pointers Node curr = root; Node next = null; Node temp = null; Node prev = null; // Iterate through all left nodes while(curr != null) { next = curr.left; // Swapping nodes now, need // temp to keep the previous // right child // Making prev's right // as curr's left child curr.left = temp; // Storing curr's right child temp = curr.right; // Making prev as curr's // right child curr.right = prev; prev = curr; curr = next; } return prev;} // Iterative method to do// level order traversal// line by linestatic void printLevelOrder(Node root){ // Base Case if (root == null) return; // Create an empty queue for // level order traversal Queue<Node> q = new LinkedList<Node>(); // Enqueue Root and // initialize height q.add(root); while (true) { // nodeCount (queue size) // indicates number of nodes // at current level. int nodeCount = q.size(); if (nodeCount == 0) break; // Dequeue all nodes of current // level and Enqueue all nodes // of next level while (nodeCount > 0) { Node node = q.peek(); System.out.print(node.data + \" \"); q.remove(); if (node.left != null) q.add(node.left); if (node.right != null) q.add(node.right); nodeCount--; } System.out.println(); }} // Driver codepublic static void main(String args[]){ Node root = newNode(1); root.left = newNode(2); root.right = newNode(3); root.right.left = newNode(4); root.right.right = newNode(5); System.out.print(\"Level order traversal \" + \"of given tree\\n\"); printLevelOrder(root); root = flipBinaryTree(root); System.out.print(\"\\nLevel order traversal \" + \"of the flipped tree\\n\"); printLevelOrder(root);}} // This code is contributed// by Arnab Kundu", "e": 17458, "s": 14874, "text": null }, { "code": "# Python3 program to flip# a binary treefrom collections import deque # A binary tree node structureclass Node: def __init__(self, key): self.data = key self.left = None self.right = None # method to flip the# binary treedef flipBinaryTree(root): # Initialization of # pointers curr = root next = None temp = None prev = None # Iterate through all # left nodes while(curr): next = curr.left # Swapping nodes now, need temp # to keep the previous right child # Making prev's right as curr's # left child curr.left = temp # Storing curr's right child temp = curr.right # Making prev as curr's right # child curr.right = prev prev = curr curr = next return prev # Iterative method to do level# order traversal line by linedef printLevelOrder(root): # Base Case if (root == None): return # Create an empty queue for # level order traversal q = deque() # Enqueue Root and initialize # height q.append(root) while (1): # nodeCount (queue size) indicates # number of nodes at current level. nodeCount = len(q) if (nodeCount == 0): break # Dequeue all nodes of current # level and Enqueue all nodes # of next level while (nodeCount > 0): node = q.popleft() print(node.data, end = \" \") if (node.left != None): q.append(node.left) if (node.right != None): q.append(node.right) nodeCount -= 1 print() # Driver codeif __name__ == '__main__': root = Node(1) root.left = Node(2) root.right = Node(3) root.right.left = Node(4) root.right.right = Node(5) print(\"Level order traversal of given tree\") printLevelOrder(root) root = flipBinaryTree(root) print(\"\\nLevel order traversal of the flipped\" \" tree\") printLevelOrder(root) # This code is contributed by Mohit Kumar 29", "e": 19527, "s": 17458, "text": null }, { "code": "// C# program to flip a binary treeusing System;using System.Collections.Generic; class GFG{ // A binary tree nodepublic class Node{ public int data; public Node left, right;} // Utility function to create// a new Binary Tree Nodepublic static Node newNode(int data){ Node temp = new Node(); temp.data = data; temp.left = temp.right = null; return temp;} // method to flip the binary treepublic static Node flipBinaryTree(Node root){ // Initialization of pointers Node curr = root; Node next = null; Node temp = null; Node prev = null; // Iterate through all left nodes while (curr != null) { next = curr.left; // Swapping nodes now, need // temp to keep the previous // right child // Making prev's right // as curr's left child curr.left = temp; // Storing curr's right child temp = curr.right; // Making prev as curr's // right child curr.right = prev; prev = curr; curr = next; } return prev;} // Iterative method to do level// order traversal line by linepublic static void printLevelOrder(Node root){ // Base Case if (root == null) { return; } // Create an empty queue for // level order traversal LinkedList<Node> q = new LinkedList<Node>(); // Enqueue Root and // initialize height q.AddLast(root); while (true) { // nodeCount (queue size) // indicates number of nodes // at current level. int nodeCount = q.Count; if (nodeCount == 0) { break; } // Dequeue all nodes of current // level and Enqueue all nodes // of next level while (nodeCount > 0) { Node node = q.First.Value; Console.Write(node.data + \" \"); q.RemoveFirst(); if (node.left != null) { q.AddLast(node.left); } if (node.right != null) { q.AddLast(node.right); } nodeCount--; } Console.WriteLine(); }} // Driver codepublic static void Main(string[] args){ Node root = newNode(1); root.left = newNode(2); root.right = newNode(3); root.right.left = newNode(4); root.right.right = newNode(5); Console.Write(\"Level order traversal \" + \"of given tree\\n\"); printLevelOrder(root); root = flipBinaryTree(root); Console.Write(\"\\nLevel order traversal \" + \"of the flipped tree\\n\"); printLevelOrder(root);}} // This code is contributed by Shrikant13", "e": 22167, "s": 19527, "text": null }, { "code": "<script> // JavaScript program to flip a binary tree class Node { constructor(data) { this.left = null; this.right = null; this.data = data; } } // Utility function to create // a new Binary Tree Node function newNode(data) { let temp = new Node(data); return temp; } // method to flip the binary tree function flipBinaryTree(root) { // Initialization of pointers let curr = root; let next = null; let temp = null; let prev = null; // Iterate through all left nodes while(curr != null) { next = curr.left; // Swapping nodes now, need // temp to keep the previous // right child // Making prev's right // as curr's left child curr.left = temp; // Storing curr's right child temp = curr.right; // Making prev as curr's // right child curr.right = prev; prev = curr; curr = next; } return prev; } // Iterative method to do // level order traversal // line by line function printLevelOrder(root) { // Base Case if (root == null) return; // Create an empty queue for // level order traversal let q = []; // Enqueue Root and // initialize height q.push(root); while (true) { // nodeCount (queue size) // indicates number of nodes // at current level. let nodeCount = q.length; if (nodeCount == 0) break; // Dequeue all nodes of current // level and Enqueue all nodes // of next level while (nodeCount > 0) { let node = q[0]; document.write(node.data + \" \"); q.shift(); if (node.left != null) q.push(node.left); if (node.right != null) q.push(node.right); nodeCount--; } document.write(\"</br>\"); } } let root = newNode(1); root.left = newNode(2); root.right = newNode(3); root.right.left = newNode(4); root.right.right = newNode(5); document.write(\"Level order traversal \" + \"of given tree\" + \"</br>\"); printLevelOrder(root); root = flipBinaryTree(root); document.write(\"</br>\" + \"Level order traversal \" + \"of the flipped tree\" + \"</br>\"); printLevelOrder(root); </script>", "e": 24863, "s": 22167, "text": null }, { "code": null, "e": 24968, "s": 24863, "text": "Level order traversal of given tree\n1 \n2 3 \n4 5 \n\nLevel order traversal of the flipped tree\n2 \n3 1 \n4 5 " }, { "code": null, "e": 24990, "s": 24968, "text": "Complexity Analysis: " }, { "code": null, "e": 25067, "s": 24990, "text": "Time complexity: O(n) as in the worst case, depth of binary tree will be n. " }, { "code": null, "e": 25090, "s": 25067, "text": "Auxiliary Space: O(1)." }, { "code": null, "e": 25389, "s": 25090, "text": "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": 25400, "s": 25389, "text": "andrew1234" }, { "code": null, "e": 25412, "s": 25400, "text": "shrikanth13" }, { "code": null, "e": 25427, "s": 25412, "text": "_Gaurav_Tiwari" }, { "code": null, "e": 25440, "s": 25427, "text": "princi singh" }, { "code": null, "e": 25455, "s": 25440, "text": "mohit kumar 29" }, { "code": null, "e": 25467, "s": 25455, "text": "unknown2108" }, { "code": null, "e": 25479, "s": 25467, "text": "anikakapoor" }, { "code": null, "e": 25488, "s": 25479, "text": "suresh07" }, { "code": null, "e": 25497, "s": 25488, "text": "sweetyty" }, { "code": null, "e": 25514, "s": 25497, "text": "hardikkoriintern" }, { "code": null, "e": 25519, "s": 25514, "text": "Tree" }, { "code": null, "e": 25524, "s": 25519, "text": "Tree" } ]
ReactJS - JSX
As we learned earlier, React JSX is an extension to JavaScript. It enables developer to create virtual DOM using XML syntax. It compiles down to pure JavaScript (React.createElement function calls). Since it compiles to JavaScript, it can be used inside any valid JavaScript code. For example, below codes are perfectly valid. Assign to a variable. var greeting = <h1>Hello React!</h1> Assign to a variable based on a condition. var canGreet = true; if(canGreet) { greeting = <h1>Hello React!</h1> } Can be used as return value of a function. function Greeting() { return <h1>Hello React!</h1> } greeting = Greeting() Can be used as argument of a function. function Greet(message) { ReactDOM.render(message, document.getElementById('react-app') } Greet(<h1>Hello React!</h1>) JSX supports expression in pure JavaScript syntax. Expression has to be enclosed inside the curly braces, { }. Expression can contain all variables available in the context, where the JSX is defined. Let us create simple JSX with expression. <script type="text/babel"> var cTime = new Date().toTimeString(); ReactDOM.render( <div><p>The current time is {cTime}</p></div>, document.getElementById('react-app') ); </script> Here, cTime used in the JSX using expression. The output of the above code is as follows, The Current time is 21:19:56 GMT+0530(India Standard Time) One of the positive side effects of using expression in JSX is that it prevents Injection attacks as it converts any string into html safe string. JSX supports user defined JavaScript function. Function usage is similar to expression. Let us create a simple function and use it inside JSX. <script type="text/babel"> var cTime = new Date().toTimeString(); ReactDOM.render( <div><p>The current time is {cTime}</p></div>, document.getElementById('react-app') ); </script> Here, getCurrentTime() is used get the current time and the output is similar as specified below − The Current time is 21:19:56 GMT+0530(India Standard Time) JSX supports HTML like attributes. All HTML tags and its attributes are supported. Attributes has to be specified using camelCase convention (and it follows JavaScript DOM API) instead of normal HTML attribute name. For example, class attribute in HTML has to be defined as className. The following are few other examples − htmlFor instead of for tabIndex instead of tabindex onClick instead of onclick <style> .red { color: red } </style> <script type="text/babel"> function getCurrentTime() { return new Date().toTimeString(); } ReactDOM.render( <div> <p>The current time is <span className="red">{getCurrentTime()}</span></p> </div>, document.getElementById('react-app') ); </script> The output is as follows − The Current time is 22:36:55 GMT+0530(India Standard Time) JSX supports expression to be specified inside the attributes. In attributes, double quote should not be used along with expression. Either expression or string using double quote has to be used. The above example can be changed to use expression in attributes. <style> .red { color: red } </style> <script type="text/babel"> function getCurrentTime() { return new Date().toTimeString(); } var class_name = "red"; ReactDOM.render( <div> <p>The current time is <span className={class_name}>{getCurrentTime()}</span></p> </div>, document.getElementById('react-app') ); </script> 20 Lectures 1.5 hours Anadi Sharma 60 Lectures 4.5 hours Skillbakerystudios 165 Lectures 13 hours Paul Carlo Tordecilla 63 Lectures 9.5 hours TELCOMA Global 17 Lectures 2 hours Mohd Raqif Warsi Print Add Notes Bookmark this page
[ { "code": null, "e": 2360, "s": 2033, "text": "As we learned earlier, React JSX is an extension to JavaScript. It enables developer to create virtual DOM using XML syntax. It compiles down to pure JavaScript (React.createElement function calls). Since it compiles to JavaScript, it can be used inside any valid JavaScript code. For example, below codes are perfectly valid." }, { "code": null, "e": 2382, "s": 2360, "text": "Assign to a variable." }, { "code": null, "e": 2420, "s": 2382, "text": "var greeting = <h1>Hello React!</h1>\n" }, { "code": null, "e": 2463, "s": 2420, "text": "Assign to a variable based on a condition." }, { "code": null, "e": 2541, "s": 2463, "text": "var canGreet = true; \nif(canGreet) { \n greeting = <h1>Hello React!</h1> \n}\n" }, { "code": null, "e": 2584, "s": 2541, "text": "Can be used as return value of a function." }, { "code": null, "e": 2670, "s": 2584, "text": "function Greeting() { \n return <h1>Hello React!</h1> \n \n} \ngreeting = Greeting()\n" }, { "code": null, "e": 2709, "s": 2670, "text": "Can be used as argument of a function." }, { "code": null, "e": 2835, "s": 2709, "text": "function Greet(message) { \n ReactDOM.render(message, document.getElementById('react-app') \n} \nGreet(<h1>Hello React!</h1>)\n" }, { "code": null, "e": 3077, "s": 2835, "text": "JSX supports expression in pure JavaScript syntax. Expression has to be enclosed inside the curly braces, { }. Expression can contain all variables available in the context, where the JSX is defined. Let us create simple JSX with expression." }, { "code": null, "e": 3276, "s": 3077, "text": "<script type=\"text/babel\">\n var cTime = new Date().toTimeString();\n ReactDOM.render(\n <div><p>The current time is {cTime}</p></div>, \n document.getElementById('react-app') );\n</script>" }, { "code": null, "e": 3366, "s": 3276, "text": "Here, cTime used in the JSX using expression. The output of the above code is as follows," }, { "code": null, "e": 3426, "s": 3366, "text": "The Current time is 21:19:56 GMT+0530(India Standard Time)\n" }, { "code": null, "e": 3573, "s": 3426, "text": "One of the positive side effects of using expression in JSX is that it prevents Injection attacks as it converts any string into html safe string." }, { "code": null, "e": 3716, "s": 3573, "text": "JSX supports user defined JavaScript function. Function usage is similar to expression. Let us create a simple function and use it inside JSX." }, { "code": null, "e": 3919, "s": 3716, "text": "<script type=\"text/babel\">\n var cTime = new Date().toTimeString();\n ReactDOM.render(\n <div><p>The current time is {cTime}</p></div>, \n document.getElementById('react-app') \n );\n</script>" }, { "code": null, "e": 4018, "s": 3919, "text": "Here, getCurrentTime() is used get the current time and the output is similar as specified below −" }, { "code": null, "e": 4078, "s": 4018, "text": "The Current time is 21:19:56 GMT+0530(India Standard Time)\n" }, { "code": null, "e": 4402, "s": 4078, "text": "JSX supports HTML like attributes. All HTML tags and its attributes are supported. Attributes has to be specified using camelCase convention (and it follows JavaScript DOM API) instead of normal HTML attribute name. For example, class attribute in HTML has to be defined as className. The following are few other examples −" }, { "code": null, "e": 4425, "s": 4402, "text": "htmlFor instead of for" }, { "code": null, "e": 4454, "s": 4425, "text": "tabIndex instead of tabindex" }, { "code": null, "e": 4481, "s": 4454, "text": "onClick instead of onclick" }, { "code": null, "e": 4814, "s": 4481, "text": "<style>\n .red { color: red }\n</style>\n<script type=\"text/babel\">\n function getCurrentTime() {\n return new Date().toTimeString();\n }\n ReactDOM.render(\n <div>\n <p>The current time is <span className=\"red\">{getCurrentTime()}</span></p>\n </div>,\n document.getElementById('react-app') \n );\n</script>" }, { "code": null, "e": 4841, "s": 4814, "text": "The output is as follows −" }, { "code": null, "e": 4901, "s": 4841, "text": "The Current time is 22:36:55 GMT+0530(India Standard Time)\n" }, { "code": null, "e": 5163, "s": 4901, "text": "JSX supports expression to be specified inside the attributes. In attributes, double quote should not be used along with expression. Either expression or string using double quote has to be used. The above example can be changed to use expression in attributes." }, { "code": null, "e": 5532, "s": 5163, "text": "<style>\n .red { color: red }\n</style>\n\n<script type=\"text/babel\">\n function getCurrentTime() {\n return new Date().toTimeString();\n }\n var class_name = \"red\";\n ReactDOM.render(\n <div>\n <p>The current time is <span className={class_name}>{getCurrentTime()}</span></p>\n </div>, \n document.getElementById('react-app') \n );\n</script>" }, { "code": null, "e": 5567, "s": 5532, "text": "\n 20 Lectures \n 1.5 hours \n" }, { "code": null, "e": 5581, "s": 5567, "text": " Anadi Sharma" }, { "code": null, "e": 5616, "s": 5581, "text": "\n 60 Lectures \n 4.5 hours \n" }, { "code": null, "e": 5636, "s": 5616, "text": " Skillbakerystudios" }, { "code": null, "e": 5671, "s": 5636, "text": "\n 165 Lectures \n 13 hours \n" }, { "code": null, "e": 5694, "s": 5671, "text": " Paul Carlo Tordecilla" }, { "code": null, "e": 5729, "s": 5694, "text": "\n 63 Lectures \n 9.5 hours \n" }, { "code": null, "e": 5745, "s": 5729, "text": " TELCOMA Global" }, { "code": null, "e": 5778, "s": 5745, "text": "\n 17 Lectures \n 2 hours \n" }, { "code": null, "e": 5796, "s": 5778, "text": " Mohd Raqif Warsi" }, { "code": null, "e": 5803, "s": 5796, "text": " Print" }, { "code": null, "e": 5814, "s": 5803, "text": " Add Notes" } ]
Arden's Theorem
Theory of Computation Arden's Theorem is basically used to find out regular expression with properties of a Finite Automaton. The Arden's Theorem is also called Arden's Lemma. It is a mathematical statement. As we know, a language is a set of strings. These sets can be specified by the meaning of some language expression. This is evaluated by language operations. It is valuable for checking the equivalence of two regular expressions along with the conversion of DFA to a regular expression. The main applications of Arden's Theorem are as follows: To determine the regular expression of finite automata. It helps in checking the equivalence of two regular expressions. Suppose, an alphabet Σ having two regular expressions P and Q. If P does not contain a null string, then - It means, whenever the equation is in the form of R=Q+RP, we can directly replace this with R=QP∗. Here, we have proved that R=QP∗ is the unique solution of R=Q+RP. R=Q+RP R=Q+[Q+RP]P // Put R = Q+RP R = Q + QP + RPP // Let's put the value R = Q+RP, repeatedly in place of R R = Q + QP +[Q+RP]PP R = Q + QP + QPP + RPPP R = Q + QP + QP2 + QP3 + QP4 + .. .. R = Q(1 + P + P2 + P3 + ....) // Hence Proved R = QP∗ Here is the following DFA state diagram, we will construct the regular expression using Arden's theorem- The state equations of the above DFA are- A = ∈ + A0 + B0 B = A1 + B1 //substitute the value of B B = A1 + (A1 + B1)1 B = A1 + A11 + B11 //.. Arden's theorem B = A11* Now, substitute the value for B in A - A = ∈ + A0 + B0 A = ∈ + A0 + (A11*)0 A = ∈ + A0 + A11*0 A = ∈ + A(0 + 11*0) //..Using Arden's theorem A = ∈(0 + 11*0)* // Hence Proved A = (0 + 11*0)*
[ { "code": null, "e": 112, "s": 90, "text": "Theory of Computation" }, { "code": null, "e": 585, "s": 112, "text": "Arden's Theorem is basically used to find out regular expression with properties of a Finite Automaton. The Arden's Theorem is also called Arden's Lemma. It is a mathematical statement. As we know, a language is a set of strings. These sets can be specified by the meaning of some language expression. This is evaluated by language operations. It is valuable for checking the equivalence of two regular expressions along with the conversion of DFA to a regular expression." }, { "code": null, "e": 642, "s": 585, "text": "The main applications of Arden's Theorem are as follows:" }, { "code": null, "e": 698, "s": 642, "text": "To determine the regular expression of finite automata." }, { "code": null, "e": 763, "s": 698, "text": "It helps in checking the equivalence of two regular expressions." }, { "code": null, "e": 870, "s": 763, "text": "Suppose, an alphabet Σ having two regular expressions P and Q. If P does not contain a null string, then -" }, { "code": null, "e": 969, "s": 870, "text": "It means, whenever the equation is in the form of R=Q+RP, we can directly replace this with R=QP∗." }, { "code": null, "e": 1035, "s": 969, "text": "Here, we have proved that R=QP∗ is the unique solution of R=Q+RP." }, { "code": null, "e": 1295, "s": 1035, "text": "R=Q+RP\n\nR=Q+[Q+RP]P \n\n// Put R = Q+RP \nR = Q + QP + RPP \n\n// Let's put the value R = Q+RP, repeatedly in place of R \nR = Q + QP +[Q+RP]PP \nR = Q + QP + QPP + RPPP \nR = Q + QP + QP2 + QP3 + QP4 + .. .. \nR = Q(1 + P + P2 + P3 + ....) \n\n// Hence Proved\nR = QP∗ \n" }, { "code": null, "e": 1400, "s": 1295, "text": "Here is the following DFA state diagram, we will construct the regular expression using Arden's theorem-" }, { "code": null, "e": 1442, "s": 1400, "text": "The state equations of the above DFA are-" }, { "code": null, "e": 1576, "s": 1442, "text": "A = ∈ + A0 + B0 \nB = A1 + B1 \n\n//substitute the value of B \nB = A1 + (A1 + B1)1 \nB = A1 + A11 + B11 \n\n//.. Arden's theorem\nB = A11* \n" }, { "code": null, "e": 1615, "s": 1576, "text": "Now, substitute the value for B in A -" } ]
VBScript LCase Function
The LCase Function returns the string after converting the entered string into lower case letters. Lcase(String) <!DOCTYPE html> <html> <body> <script language = "vbscript" type = "text/vbscript"> var = "Microsoft VBScript" document.write("Line 1 : " & LCase(var) & "<br />") var = "MS VBSCRIPT" document.write("Line 2 : " & LCase(var) & "<br />") var = "microsoft" document.write("Line 3 : " & LCase(var) & "<br />") </script> </body> </html> When you save it as .html and execute it in Internet Explorer, then the above script will produce the following result − Line 1 : microsoft vbscript Line 2 : ms vbscript Line 3 : microsoft 63 Lectures 4 hours Frahaan Hussain Print Add Notes Bookmark this page
[ { "code": null, "e": 2179, "s": 2080, "text": "The LCase Function returns the string after converting the entered string into lower case letters." }, { "code": null, "e": 2194, "s": 2179, "text": "Lcase(String)\n" }, { "code": null, "e": 2617, "s": 2194, "text": "<!DOCTYPE html>\n<html>\n <body>\n <script language = \"vbscript\" type = \"text/vbscript\">\n var = \"Microsoft VBScript\"\n document.write(\"Line 1 : \" & LCase(var) & \"<br />\")\n \n var = \"MS VBSCRIPT\"\n document.write(\"Line 2 : \" & LCase(var) & \"<br />\")\n \n var = \"microsoft\"\n document.write(\"Line 3 : \" & LCase(var) & \"<br />\")\n </script>\n </body>\n</html>" }, { "code": null, "e": 2738, "s": 2617, "text": "When you save it as .html and execute it in Internet Explorer, then the above script will produce the following result −" }, { "code": null, "e": 2807, "s": 2738, "text": "Line 1 : microsoft vbscript\nLine 2 : ms vbscript\nLine 3 : microsoft\n" }, { "code": null, "e": 2840, "s": 2807, "text": "\n 63 Lectures \n 4 hours \n" }, { "code": null, "e": 2857, "s": 2840, "text": " Frahaan Hussain" }, { "code": null, "e": 2864, "s": 2857, "text": " Print" }, { "code": null, "e": 2875, "s": 2864, "text": " Add Notes" } ]
Copy Constructor in Java - GeeksforGeeks
17 May, 2021 Prerequisite – Constructors in Java Like C++, Java also supports copy constructor. But, unlike C++, Java doesn’t create a default copy constructor if you don’t write your own. Following is an example Java program that shows a simple use of copy constructor. Java // filename: Main.java class Complex { private double re, im; // A normal parameterized constructor public Complex(double re, double im) { this.re = re; this.im = im; } // copy constructor Complex(Complex c) { System.out.println("Copy constructor called"); re = c.re; im = c.im; } // Overriding the toString of Object class @Override public String toString() { return "(" + re + " + " + im + "i)"; }} public class Main { public static void main(String[] args) { Complex c1 = new Complex(10, 15); // Following involves a copy constructor call Complex c2 = new Complex(c1); // Note that following doesn't involve a copy constructor call as // non-primitive variables are just references. Complex c3 = c2; System.out.println(c2); // toString() of c2 is called here }} Output: Copy constructor called (10.0 + 15.0i) Now try the following Java program: Java // filename: Main.java class Complex { private double re, im; public Complex(double re, double im) { this.re = re; this.im = im; }} public class Main { public static void main(String[] args) { Complex c1 = new Complex(10, 15); Complex c2 = new Complex(c1); // compiler error here }} Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. gabaa406 Java School Programming Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Split() String method in Java with examples Arrays.sort() in Java with examples Reverse a string in Java Initialize an ArrayList in Java How to iterate any Map in Java Python Dictionary Arrays in C/C++ Inheritance in C++ Reverse a string in Java C++ Classes and Objects
[ { "code": null, "e": 28950, "s": 28922, "text": "\n17 May, 2021" }, { "code": null, "e": 29127, "s": 28950, "text": "Prerequisite – Constructors in Java Like C++, Java also supports copy constructor. But, unlike C++, Java doesn’t create a default copy constructor if you don’t write your own. " }, { "code": null, "e": 29210, "s": 29127, "text": "Following is an example Java program that shows a simple use of copy constructor. " }, { "code": null, "e": 29215, "s": 29210, "text": "Java" }, { "code": "// filename: Main.java class Complex { private double re, im; // A normal parameterized constructor public Complex(double re, double im) { this.re = re; this.im = im; } // copy constructor Complex(Complex c) { System.out.println(\"Copy constructor called\"); re = c.re; im = c.im; } // Overriding the toString of Object class @Override public String toString() { return \"(\" + re + \" + \" + im + \"i)\"; }} public class Main { public static void main(String[] args) { Complex c1 = new Complex(10, 15); // Following involves a copy constructor call Complex c2 = new Complex(c1); // Note that following doesn't involve a copy constructor call as // non-primitive variables are just references. Complex c3 = c2; System.out.println(c2); // toString() of c2 is called here }}", "e": 30143, "s": 29215, "text": null }, { "code": null, "e": 30152, "s": 30143, "text": "Output: " }, { "code": null, "e": 30191, "s": 30152, "text": "Copy constructor called\n(10.0 + 15.0i)" }, { "code": null, "e": 30228, "s": 30191, "text": "Now try the following Java program: " }, { "code": null, "e": 30233, "s": 30228, "text": "Java" }, { "code": "// filename: Main.java class Complex { private double re, im; public Complex(double re, double im) { this.re = re; this.im = im; }} public class Main { public static void main(String[] args) { Complex c1 = new Complex(10, 15); Complex c2 = new Complex(c1); // compiler error here }}", "e": 30568, "s": 30233, "text": null }, { "code": null, "e": 30694, "s": 30568, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 30703, "s": 30694, "text": "gabaa406" }, { "code": null, "e": 30708, "s": 30703, "text": "Java" }, { "code": null, "e": 30727, "s": 30708, "text": "School Programming" }, { "code": null, "e": 30732, "s": 30727, "text": "Java" }, { "code": null, "e": 30830, "s": 30732, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30839, "s": 30830, "text": "Comments" }, { "code": null, "e": 30852, "s": 30839, "text": "Old Comments" }, { "code": null, "e": 30896, "s": 30852, "text": "Split() String method in Java with examples" }, { "code": null, "e": 30932, "s": 30896, "text": "Arrays.sort() in Java with examples" }, { "code": null, "e": 30957, "s": 30932, "text": "Reverse a string in Java" }, { "code": null, "e": 30989, "s": 30957, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 31020, "s": 30989, "text": "How to iterate any Map in Java" }, { "code": null, "e": 31038, "s": 31020, "text": "Python Dictionary" }, { "code": null, "e": 31054, "s": 31038, "text": "Arrays in C/C++" }, { "code": null, "e": 31073, "s": 31054, "text": "Inheritance in C++" }, { "code": null, "e": 31098, "s": 31073, "text": "Reverse a string in Java" } ]
Dart - String toUpperCase() Function with Examples - GeeksforGeeks
14 Jul, 2020 The string toUpperCase() method converts all characters of the string into an uppercase letter. The string toUpperCase() function returns the string after converting all characters of the string into the uppercase letter. Syntax: Str.toUpperCase() Parameter: The string toUpperCase() function doesn’t accept any parameter. Return Value: The string toUpperCase() function returns the string afterconverting all characters of the string into the uppercase letter. Example1: Dart void main() { // str1 stores the string "geeks" String Str1 = "geeks"; // str2 stores the string "fOr GEeks" String Str2 = "fOr GEeks"; // print str1 in uppercase letter print(Str1.toUpperCase()); // print str2 in uppercase letter print(Str2.toUpperCase()); } Output: GEEKS FOR GEEKS Example 2: Dart void main() { // str1 stores the string "COMPUTER" String Str1 = "COMPUTER"; // str2 stores the string "laPToP" String Str2 = "laPToP"; // print str1 in uppercase letter print(Str1.toUpperCase()); // print str2 in uppercase letter print(Str2.toUpperCase()); } Output: COMPUTER LAPTOP Dart-String Dart Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Flutter - Custom Bottom Navigation Bar ListView Class in Flutter Android Studio Setup for Flutter Development Flutter - Flexible Widget Flutter - Stack Widget Flutter - BorderRadius Widget What is widgets in Flutter? Flutter - Dialogs Format Dates in Flutter Dart - Static Keyword
[ { "code": null, "e": 24010, "s": 23982, "text": "\n14 Jul, 2020" }, { "code": null, "e": 24233, "s": 24010, "text": "The string toUpperCase() method converts all characters of the string into an uppercase letter. The string toUpperCase() function returns the string after converting all characters of the string into the uppercase letter. " }, { "code": null, "e": 24259, "s": 24233, "text": "Syntax: Str.toUpperCase()" }, { "code": null, "e": 24334, "s": 24259, "text": "Parameter: The string toUpperCase() function doesn’t accept any parameter." }, { "code": null, "e": 24473, "s": 24334, "text": "Return Value: The string toUpperCase() function returns the string afterconverting all characters of the string into the uppercase letter." }, { "code": null, "e": 24485, "s": 24473, "text": "Example1: " }, { "code": null, "e": 24490, "s": 24485, "text": "Dart" }, { "code": "void main() { // str1 stores the string \"geeks\" String Str1 = \"geeks\"; // str2 stores the string \"fOr GEeks\" String Str2 = \"fOr GEeks\"; // print str1 in uppercase letter print(Str1.toUpperCase()); // print str2 in uppercase letter print(Str2.toUpperCase()); }", "e": 24787, "s": 24490, "text": null }, { "code": null, "e": 24796, "s": 24787, "text": "Output: " }, { "code": null, "e": 24813, "s": 24796, "text": "GEEKS\nFOR GEEKS\n" }, { "code": null, "e": 24826, "s": 24813, "text": "Example 2: " }, { "code": null, "e": 24831, "s": 24826, "text": "Dart" }, { "code": "void main() { // str1 stores the string \"COMPUTER\" String Str1 = \"COMPUTER\"; // str2 stores the string \"laPToP\" String Str2 = \"laPToP\"; // print str1 in uppercase letter print(Str1.toUpperCase()); // print str2 in uppercase letter print(Str2.toUpperCase()); }", "e": 25125, "s": 24831, "text": null }, { "code": null, "e": 25134, "s": 25125, "text": "Output: " }, { "code": null, "e": 25151, "s": 25134, "text": "COMPUTER\nLAPTOP\n" }, { "code": null, "e": 25163, "s": 25151, "text": "Dart-String" }, { "code": null, "e": 25168, "s": 25163, "text": "Dart" }, { "code": null, "e": 25266, "s": 25168, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25275, "s": 25266, "text": "Comments" }, { "code": null, "e": 25288, "s": 25275, "text": "Old Comments" }, { "code": null, "e": 25327, "s": 25288, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 25353, "s": 25327, "text": "ListView Class in Flutter" }, { "code": null, "e": 25398, "s": 25353, "text": "Android Studio Setup for Flutter Development" }, { "code": null, "e": 25424, "s": 25398, "text": "Flutter - Flexible Widget" }, { "code": null, "e": 25447, "s": 25424, "text": "Flutter - Stack Widget" }, { "code": null, "e": 25477, "s": 25447, "text": "Flutter - BorderRadius Widget" }, { "code": null, "e": 25505, "s": 25477, "text": "What is widgets in Flutter?" }, { "code": null, "e": 25523, "s": 25505, "text": "Flutter - Dialogs" }, { "code": null, "e": 25547, "s": 25523, "text": "Format Dates in Flutter" } ]
Doing and Reporting a Serial Mediation Model with Two Mediators in R with Lavaan | by Matthieu Renard | Towards Data Science
Doing serial mediation is exciting. Most of the time, it means you know how to run standard mediation or moderation models and are now ready to delve deeper into the world of process models. And an exciting world it is! One can find out so much more using mediation models! This tutorial shows you how to run, interpret, and report a serial mediation model. At the same time, it provides the first step into the world of running structural equation models. It will not go deeper on what a mediation exactly is, but if you are interested in that, check out my other article on mediation analysis. Let’s get going! In our serial mediation. There are an independent variable and a dependent variable, and two mediators. The two mediators do an increasingly better job at predicting the dependent variable. The schematic below depicts how it works. In everyday research, one should deduct this serial mediation model from theory or previous findings. Before we start with the analysis, let’s simulate our data. Above, we wrote that the closer the variable is to the dependent variable (DV), the better it is at predicting the DV. This is reflected in our simulated data. set.seed(1234) #enter this command to get the same "random" results as I do here.iv=rnorm(n=1000,mean=50, sd=10)m1=.6*rnorm(n=1000,mean=50, sd=10)+.4*ivm2=.6*rnorm(n=1000,mean=50, sd=10)+.4*m1dv=.6*rnorm(n=1000,mean=50, sd=10)+.4*m2cv1=rnorm(n=1000,mean=50, sd=10)cv2=rnorm(n=1000,mean=50, sd=10) As you can see, the independent variable (IV) is 1000 random observations, as are our two covariates (cv1 and cv2). The first mediator (M1) is 60% random noise and 40% IV. The second mediator (M2) is again 60% random noise and 40% M1. Lastly, the DV is 60% random noise and 40% M2. There is 6.4% IV (0.43) in the DV. This can be demonstrated when we regress the IV on the DV. fit=lm(dv~iv)summary(fit) As you can see, the regression coefficient of the IV for the regression onto the DV is close to 6.4 (b=.07, t(998)=3.48, p<.001). We begin by installing and loading the “lavaan” package. install.packages("lavaan")library(lavaan) Also, we need to fuse all the separate lists of variables we have so far into one data frame. Lavaan only accepts variables within data frames. df=as.data.frame(cbind(iv,dv,m1,m2)) Now, we need to communicate our model configuration to Lavaan. Therefore, we create a new object, “model,” in which we save the configuration. model=" #Regressions m1 ~ a*iv m2 ~ b*m1 + iv dv ~ c*m2 + m1 + d*iv + cv1 + cv2 #Defined Parameters: ie := a*b*c de := d" You can see that we first communicate the individual regressions. The syntax is quite similar to the standard R “lm()” function, bar one thing: Whenever we want to use a specific coefficient later, we give it a name. In this case, I gave them the names a, b, c, and d. If we do not specifically name a coefficient, it is still there, but it cannot be picked up and be worked with later on. Then, we define parameters within the SEM model using the “:=” operator. We first define the indirect effect (ie) by multiplying the three coefficients a, b, and c. Those are the three coefficients that connect the IV to the DV via M1 and M2. Then we extract the direct effect, which is simply the one coefficient d. Using the following “sem()” command, we run the SEM. We then run the familiar “summary()” on the resulting object, which yields the below output (relevant excerpt). fit=sem(model,df)summary(fit) As in the model, you can see individual regressions presented in a pretty familiar way. The named/saved coefficients (a-d) are highlighted in brackets. At the very end, we see our defined parameters: We have our indirect effect and the direct effect. The convenient thing is that lavaan also tests the significance of our parameters. The indirect effect (ie) is significant (b=.06, p<.001), and the direct effect (de) are insignificant (b=-.002, p>.05) — implying that the effect is fully mediated. We already knew this because we simulated it to be in this way. You could report the model in the following way. IV had a significant positive effect on DV (b=.07, t(998)=3.48, p<.001). As theorized, this effect was serially mediated by M1 and M2. The indirect pathway of the effect of IV on DV via M1 and M2 was significant (b[indirect]= .06, z=7.8, p<.001). This pathways fully accounted for the overall impact of IV on DV with the direct effect being insignificant (bdirect= -.002, z=-.07, p>.05). You would like to find out more? Follow me on Medium to see my other stories!
[ { "code": null, "e": 446, "s": 172, "text": "Doing serial mediation is exciting. Most of the time, it means you know how to run standard mediation or moderation models and are now ready to delve deeper into the world of process models. And an exciting world it is! One can find out so much more using mediation models!" }, { "code": null, "e": 785, "s": 446, "text": "This tutorial shows you how to run, interpret, and report a serial mediation model. At the same time, it provides the first step into the world of running structural equation models. It will not go deeper on what a mediation exactly is, but if you are interested in that, check out my other article on mediation analysis. Let’s get going!" }, { "code": null, "e": 1119, "s": 785, "text": "In our serial mediation. There are an independent variable and a dependent variable, and two mediators. The two mediators do an increasingly better job at predicting the dependent variable. The schematic below depicts how it works. In everyday research, one should deduct this serial mediation model from theory or previous findings." }, { "code": null, "e": 1339, "s": 1119, "text": "Before we start with the analysis, let’s simulate our data. Above, we wrote that the closer the variable is to the dependent variable (DV), the better it is at predicting the DV. This is reflected in our simulated data." }, { "code": null, "e": 1636, "s": 1339, "text": "set.seed(1234) #enter this command to get the same \"random\" results as I do here.iv=rnorm(n=1000,mean=50, sd=10)m1=.6*rnorm(n=1000,mean=50, sd=10)+.4*ivm2=.6*rnorm(n=1000,mean=50, sd=10)+.4*m1dv=.6*rnorm(n=1000,mean=50, sd=10)+.4*m2cv1=rnorm(n=1000,mean=50, sd=10)cv2=rnorm(n=1000,mean=50, sd=10)" }, { "code": null, "e": 2012, "s": 1636, "text": "As you can see, the independent variable (IV) is 1000 random observations, as are our two covariates (cv1 and cv2). The first mediator (M1) is 60% random noise and 40% IV. The second mediator (M2) is again 60% random noise and 40% M1. Lastly, the DV is 60% random noise and 40% M2. There is 6.4% IV (0.43) in the DV. This can be demonstrated when we regress the IV on the DV." }, { "code": null, "e": 2038, "s": 2012, "text": "fit=lm(dv~iv)summary(fit)" }, { "code": null, "e": 2168, "s": 2038, "text": "As you can see, the regression coefficient of the IV for the regression onto the DV is close to 6.4 (b=.07, t(998)=3.48, p<.001)." }, { "code": null, "e": 2225, "s": 2168, "text": "We begin by installing and loading the “lavaan” package." }, { "code": null, "e": 2267, "s": 2225, "text": "install.packages(\"lavaan\")library(lavaan)" }, { "code": null, "e": 2411, "s": 2267, "text": "Also, we need to fuse all the separate lists of variables we have so far into one data frame. Lavaan only accepts variables within data frames." }, { "code": null, "e": 2448, "s": 2411, "text": "df=as.data.frame(cbind(iv,dv,m1,m2))" }, { "code": null, "e": 2591, "s": 2448, "text": "Now, we need to communicate our model configuration to Lavaan. Therefore, we create a new object, “model,” in which we save the configuration." }, { "code": null, "e": 2722, "s": 2591, "text": "model=\" #Regressions m1 ~ a*iv m2 ~ b*m1 + iv dv ~ c*m2 + m1 + d*iv + cv1 + cv2 #Defined Parameters: ie := a*b*c de := d\"" }, { "code": null, "e": 3112, "s": 2722, "text": "You can see that we first communicate the individual regressions. The syntax is quite similar to the standard R “lm()” function, bar one thing: Whenever we want to use a specific coefficient later, we give it a name. In this case, I gave them the names a, b, c, and d. If we do not specifically name a coefficient, it is still there, but it cannot be picked up and be worked with later on." }, { "code": null, "e": 3429, "s": 3112, "text": "Then, we define parameters within the SEM model using the “:=” operator. We first define the indirect effect (ie) by multiplying the three coefficients a, b, and c. Those are the three coefficients that connect the IV to the DV via M1 and M2. Then we extract the direct effect, which is simply the one coefficient d." }, { "code": null, "e": 3594, "s": 3429, "text": "Using the following “sem()” command, we run the SEM. We then run the familiar “summary()” on the resulting object, which yields the below output (relevant excerpt)." }, { "code": null, "e": 3624, "s": 3594, "text": "fit=sem(model,df)summary(fit)" }, { "code": null, "e": 4187, "s": 3624, "text": "As in the model, you can see individual regressions presented in a pretty familiar way. The named/saved coefficients (a-d) are highlighted in brackets. At the very end, we see our defined parameters: We have our indirect effect and the direct effect. The convenient thing is that lavaan also tests the significance of our parameters. The indirect effect (ie) is significant (b=.06, p<.001), and the direct effect (de) are insignificant (b=-.002, p>.05) — implying that the effect is fully mediated. We already knew this because we simulated it to be in this way." }, { "code": null, "e": 4236, "s": 4187, "text": "You could report the model in the following way." }, { "code": null, "e": 4624, "s": 4236, "text": "IV had a significant positive effect on DV (b=.07, t(998)=3.48, p<.001). As theorized, this effect was serially mediated by M1 and M2. The indirect pathway of the effect of IV on DV via M1 and M2 was significant (b[indirect]= .06, z=7.8, p<.001). This pathways fully accounted for the overall impact of IV on DV with the direct effect being insignificant (bdirect= -.002, z=-.07, p>.05)." } ]
Sorting Algorithm Visualization : Merge Sort - GeeksforGeeks
12 Jul, 2020 The human brain can easily process visuals instead of long codes to understand the algorithms. In this article, a program that program visualizes the Merge sort Algorithm has been implemented. The GUI(Graphical User Interface) is implemented using pygame package in python. Approach: An array of random values is generated and are drawn as lines(bars) in the window . Different colors are used to indicate which elements being compared, sorted and unsorted. Since the algorithm performs the operation very fast, pygame.time.delay() has been used to slow down the process. New array can be generated by pressing ‘r’ key. The actions are performed using ‘pygame.event.get()’ method, which stores all the events which user performs.Examples:Input :Press “Enter” key to Perform Visualization.Press “r” key to generate new array.Output :Initial:Visualizing:Final:Recommended: Please try your approach on {IDE} first, before moving on to the solution.Below is the program to visualize the Merge Sort algorithm:# Python implementation for visualizing merge sort. import pygameimport randompygame.font.init()# Total windowscreen = pygame.display.set_mode((900, 650)) # Title and Icon pygame.display.set_caption("SORTING VISUALISER")# Place any custom png file in same folder as the source code# and mention it below and uncomment below two lines.# img = pygame.image.load# ('E:/Projects / Sorting Visualiser / sorticon.png')# pygame.display.set_icon(img) # Boolean variable to run the program in while looprun = True # Window sizewidth = 900length = 600array =[0]*151arr_clr =[(0, 204, 102)]*151clr_ind = 0clr =[(0, 204, 102), (255, 0, 0), (0, 0, 153), (255, 102, 0)]fnt = pygame.font.SysFont("comicsans", 30)fnt1 = pygame.font.SysFont("comicsans", 20)# Generate new Arraydef generate_arr(): for i in range(1, 151): arr_clr[i]= clr[0] array[i]= random.randrange(1, 100)generate_arr() def refill(): screen.fill((255, 255, 255)) draw() pygame.display.update() pygame.time.delay(20) # Sorting Algo:Merge sortdef mergesort(array, l, r): mid =(l + r)//2 if l<r: mergesort(array, l, mid) mergesort(array, mid + 1, r) merge(array, l, mid, mid + 1, r)def merge(array, x1, y1, x2, y2): i = x1 j = x2 temp =[] pygame.event.pump() while i<= y1 and j<= y2: arr_clr[i]= clr[1] arr_clr[j]= clr[1] refill() arr_clr[i]= clr[0] arr_clr[j]= clr[0] if array[i]<array[j]: temp.append(array[i]) i+= 1 else: temp.append(array[j]) j+= 1 while i<= y1: arr_clr[i]= clr[1] refill() arr_clr[i]= clr[0] temp.append(array[i]) i+= 1 while j<= y2: arr_clr[j]= clr[1] refill() arr_clr[j]= clr[0] temp.append(array[j]) j+= 1 j = 0 for i in range(x1, y2 + 1): pygame.event.pump() array[i]= temp[j] j+= 1 arr_clr[i]= clr[2] refill() if y2-x1 == len(array)-2: arr_clr[i]= clr[3] else: arr_clr[i]= clr[0] # Draw the array valuesdef draw(): # Text should be rendered txt = fnt.render("PRESS"\ " 'ENTER' TO PERFORM SORTING.", 1, (0, 0, 0)) # Position where text is placed screen.blit(txt, (20, 20)) txt1 = fnt.render("PRESS 'R' FOR NEW ARRAY.", 1, (0, 0, 0)) screen.blit(txt1, (20, 40)) txt2 = fnt1.render("ALGORITHM USED: "\ "MERGE SORT", 1, (0, 0, 0)) screen.blit(txt2, (600, 60)) element_width =(width-150)//150 boundry_arr = 900 / 150 boundry_grp = 550 / 100 pygame.draw.line(screen, (0, 0, 0), (0, 95), (900, 95), 6) for i in range(1, 100): pygame.draw.line(screen, (224, 224, 224), (0, boundry_grp * i + 100), (900, boundry_grp * i + 100), 1) # Drawing the array values as lines for i in range(1, 151): pygame.draw.line(screen, arr_clr[i],\ (boundry_arr * i-3, 100),\ (boundry_arr * i-3, array[i]*boundry_grp + 100),\ element_width) # Infinite loop to keep the window openwhile run: # background screen.fill((255, 255, 255)) # Event handler stores all event for event in pygame.event.get(): # If we click Close button in window if event.type == pygame.QUIT: run = False if event.type == pygame.KEYDOWN: if event.key == pygame.K_r: generate_arr() if event.key == pygame.K_RETURN: mergesort(array, 1, len(array)-1) draw() pygame.display.update() pygame.quit()Output: Video Playerhttps://media.geeksforgeeks.org/wp-content/uploads/20200619162211/visualiser15-2020-06-19_16.16.37.mp400:0000:0000:52Use Up/Down Arrow keys to increase or decrease volume. My Personal Notes arrow_drop_upSave Examples: Input :Press “Enter” key to Perform Visualization.Press “r” key to generate new array.Output :Initial: Visualizing: Final: Below is the program to visualize the Merge Sort algorithm: # Python implementation for visualizing merge sort. import pygameimport randompygame.font.init()# Total windowscreen = pygame.display.set_mode((900, 650)) # Title and Icon pygame.display.set_caption("SORTING VISUALISER")# Place any custom png file in same folder as the source code# and mention it below and uncomment below two lines.# img = pygame.image.load# ('E:/Projects / Sorting Visualiser / sorticon.png')# pygame.display.set_icon(img) # Boolean variable to run the program in while looprun = True # Window sizewidth = 900length = 600array =[0]*151arr_clr =[(0, 204, 102)]*151clr_ind = 0clr =[(0, 204, 102), (255, 0, 0), (0, 0, 153), (255, 102, 0)]fnt = pygame.font.SysFont("comicsans", 30)fnt1 = pygame.font.SysFont("comicsans", 20)# Generate new Arraydef generate_arr(): for i in range(1, 151): arr_clr[i]= clr[0] array[i]= random.randrange(1, 100)generate_arr() def refill(): screen.fill((255, 255, 255)) draw() pygame.display.update() pygame.time.delay(20) # Sorting Algo:Merge sortdef mergesort(array, l, r): mid =(l + r)//2 if l<r: mergesort(array, l, mid) mergesort(array, mid + 1, r) merge(array, l, mid, mid + 1, r)def merge(array, x1, y1, x2, y2): i = x1 j = x2 temp =[] pygame.event.pump() while i<= y1 and j<= y2: arr_clr[i]= clr[1] arr_clr[j]= clr[1] refill() arr_clr[i]= clr[0] arr_clr[j]= clr[0] if array[i]<array[j]: temp.append(array[i]) i+= 1 else: temp.append(array[j]) j+= 1 while i<= y1: arr_clr[i]= clr[1] refill() arr_clr[i]= clr[0] temp.append(array[i]) i+= 1 while j<= y2: arr_clr[j]= clr[1] refill() arr_clr[j]= clr[0] temp.append(array[j]) j+= 1 j = 0 for i in range(x1, y2 + 1): pygame.event.pump() array[i]= temp[j] j+= 1 arr_clr[i]= clr[2] refill() if y2-x1 == len(array)-2: arr_clr[i]= clr[3] else: arr_clr[i]= clr[0] # Draw the array valuesdef draw(): # Text should be rendered txt = fnt.render("PRESS"\ " 'ENTER' TO PERFORM SORTING.", 1, (0, 0, 0)) # Position where text is placed screen.blit(txt, (20, 20)) txt1 = fnt.render("PRESS 'R' FOR NEW ARRAY.", 1, (0, 0, 0)) screen.blit(txt1, (20, 40)) txt2 = fnt1.render("ALGORITHM USED: "\ "MERGE SORT", 1, (0, 0, 0)) screen.blit(txt2, (600, 60)) element_width =(width-150)//150 boundry_arr = 900 / 150 boundry_grp = 550 / 100 pygame.draw.line(screen, (0, 0, 0), (0, 95), (900, 95), 6) for i in range(1, 100): pygame.draw.line(screen, (224, 224, 224), (0, boundry_grp * i + 100), (900, boundry_grp * i + 100), 1) # Drawing the array values as lines for i in range(1, 151): pygame.draw.line(screen, arr_clr[i],\ (boundry_arr * i-3, 100),\ (boundry_arr * i-3, array[i]*boundry_grp + 100),\ element_width) # Infinite loop to keep the window openwhile run: # background screen.fill((255, 255, 255)) # Event handler stores all event for event in pygame.event.get(): # If we click Close button in window if event.type == pygame.QUIT: run = False if event.type == pygame.KEYDOWN: if event.key == pygame.K_r: generate_arr() if event.key == pygame.K_RETURN: mergesort(array, 1, len(array)-1) draw() pygame.display.update() pygame.quit() Output: Video Playerhttps://media.geeksforgeeks.org/wp-content/uploads/20200619162211/visualiser15-2020-06-19_16.16.37.mp400:0000:0000:52Use Up/Down Arrow keys to increase or decrease volume. Archit_Dwevedi0 Merge Sort Divide and Conquer Python Sorting Divide and Conquer Sorting Merge Sort Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Program for Tower of Hanoi Divide and Conquer Algorithm | Introduction Median of two sorted arrays of different sizes Divide and Conquer | Set 5 (Strassen's Matrix Multiplication) Closest Pair of Points using Divide and Conquer algorithm Read JSON file using Python Adding new column to existing DataFrame in Pandas Python map() function How to get column names in Pandas dataframe
[ { "code": null, "e": 24075, "s": 24047, "text": "\n12 Jul, 2020" }, { "code": null, "e": 24268, "s": 24075, "text": "The human brain can easily process visuals instead of long codes to understand the algorithms. In this article, a program that program visualizes the Merge sort Algorithm has been implemented." }, { "code": null, "e": 24349, "s": 24268, "text": "The GUI(Graphical User Interface) is implemented using pygame package in python." }, { "code": null, "e": 24359, "s": 24349, "text": "Approach:" }, { "code": null, "e": 24443, "s": 24359, "text": "An array of random values is generated and are drawn as lines(bars) in the window ." }, { "code": null, "e": 24533, "s": 24443, "text": "Different colors are used to indicate which elements being compared, sorted and unsorted." }, { "code": null, "e": 24647, "s": 24533, "text": "Since the algorithm performs the operation very fast, pygame.time.delay() has been used to slow down the process." }, { "code": null, "e": 24695, "s": 24647, "text": "New array can be generated by pressing ‘r’ key." }, { "code": null, "e": 29022, "s": 24695, "text": "The actions are performed using ‘pygame.event.get()’ method, which stores all the events which user performs.Examples:Input :Press “Enter” key to Perform Visualization.Press “r” key to generate new array.Output :Initial:Visualizing:Final:Recommended: Please try your approach on {IDE} first, before moving on to the solution.Below is the program to visualize the Merge Sort algorithm:# Python implementation for visualizing merge sort. import pygameimport randompygame.font.init()# Total windowscreen = pygame.display.set_mode((900, 650)) # Title and Icon pygame.display.set_caption(\"SORTING VISUALISER\")# Place any custom png file in same folder as the source code# and mention it below and uncomment below two lines.# img = pygame.image.load# ('E:/Projects / Sorting Visualiser / sorticon.png')# pygame.display.set_icon(img) # Boolean variable to run the program in while looprun = True # Window sizewidth = 900length = 600array =[0]*151arr_clr =[(0, 204, 102)]*151clr_ind = 0clr =[(0, 204, 102), (255, 0, 0), (0, 0, 153), (255, 102, 0)]fnt = pygame.font.SysFont(\"comicsans\", 30)fnt1 = pygame.font.SysFont(\"comicsans\", 20)# Generate new Arraydef generate_arr(): for i in range(1, 151): arr_clr[i]= clr[0] array[i]= random.randrange(1, 100)generate_arr() def refill(): screen.fill((255, 255, 255)) draw() pygame.display.update() pygame.time.delay(20) # Sorting Algo:Merge sortdef mergesort(array, l, r): mid =(l + r)//2 if l<r: mergesort(array, l, mid) mergesort(array, mid + 1, r) merge(array, l, mid, mid + 1, r)def merge(array, x1, y1, x2, y2): i = x1 j = x2 temp =[] pygame.event.pump() while i<= y1 and j<= y2: arr_clr[i]= clr[1] arr_clr[j]= clr[1] refill() arr_clr[i]= clr[0] arr_clr[j]= clr[0] if array[i]<array[j]: temp.append(array[i]) i+= 1 else: temp.append(array[j]) j+= 1 while i<= y1: arr_clr[i]= clr[1] refill() arr_clr[i]= clr[0] temp.append(array[i]) i+= 1 while j<= y2: arr_clr[j]= clr[1] refill() arr_clr[j]= clr[0] temp.append(array[j]) j+= 1 j = 0 for i in range(x1, y2 + 1): pygame.event.pump() array[i]= temp[j] j+= 1 arr_clr[i]= clr[2] refill() if y2-x1 == len(array)-2: arr_clr[i]= clr[3] else: arr_clr[i]= clr[0] # Draw the array valuesdef draw(): # Text should be rendered txt = fnt.render(\"PRESS\"\\ \" 'ENTER' TO PERFORM SORTING.\", 1, (0, 0, 0)) # Position where text is placed screen.blit(txt, (20, 20)) txt1 = fnt.render(\"PRESS 'R' FOR NEW ARRAY.\", 1, (0, 0, 0)) screen.blit(txt1, (20, 40)) txt2 = fnt1.render(\"ALGORITHM USED: \"\\ \"MERGE SORT\", 1, (0, 0, 0)) screen.blit(txt2, (600, 60)) element_width =(width-150)//150 boundry_arr = 900 / 150 boundry_grp = 550 / 100 pygame.draw.line(screen, (0, 0, 0), (0, 95), (900, 95), 6) for i in range(1, 100): pygame.draw.line(screen, (224, 224, 224), (0, boundry_grp * i + 100), (900, boundry_grp * i + 100), 1) # Drawing the array values as lines for i in range(1, 151): pygame.draw.line(screen, arr_clr[i],\\ (boundry_arr * i-3, 100),\\ (boundry_arr * i-3, array[i]*boundry_grp + 100),\\ element_width) # Infinite loop to keep the window openwhile run: # background screen.fill((255, 255, 255)) # Event handler stores all event for event in pygame.event.get(): # If we click Close button in window if event.type == pygame.QUIT: run = False if event.type == pygame.KEYDOWN: if event.key == pygame.K_r: generate_arr() if event.key == pygame.K_RETURN: mergesort(array, 1, len(array)-1) draw() pygame.display.update() pygame.quit()Output:\nVideo Playerhttps://media.geeksforgeeks.org/wp-content/uploads/20200619162211/visualiser15-2020-06-19_16.16.37.mp400:0000:0000:52Use Up/Down Arrow keys to increase or decrease volume.\nMy Personal Notes\narrow_drop_upSave" }, { "code": null, "e": 29032, "s": 29022, "text": "Examples:" }, { "code": null, "e": 29135, "s": 29032, "text": "Input :Press “Enter” key to Perform Visualization.Press “r” key to generate new array.Output :Initial:" }, { "code": null, "e": 29148, "s": 29135, "text": "Visualizing:" }, { "code": null, "e": 29155, "s": 29148, "text": "Final:" }, { "code": null, "e": 29215, "s": 29155, "text": "Below is the program to visualize the Merge Sort algorithm:" }, { "code": "# Python implementation for visualizing merge sort. import pygameimport randompygame.font.init()# Total windowscreen = pygame.display.set_mode((900, 650)) # Title and Icon pygame.display.set_caption(\"SORTING VISUALISER\")# Place any custom png file in same folder as the source code# and mention it below and uncomment below two lines.# img = pygame.image.load# ('E:/Projects / Sorting Visualiser / sorticon.png')# pygame.display.set_icon(img) # Boolean variable to run the program in while looprun = True # Window sizewidth = 900length = 600array =[0]*151arr_clr =[(0, 204, 102)]*151clr_ind = 0clr =[(0, 204, 102), (255, 0, 0), (0, 0, 153), (255, 102, 0)]fnt = pygame.font.SysFont(\"comicsans\", 30)fnt1 = pygame.font.SysFont(\"comicsans\", 20)# Generate new Arraydef generate_arr(): for i in range(1, 151): arr_clr[i]= clr[0] array[i]= random.randrange(1, 100)generate_arr() def refill(): screen.fill((255, 255, 255)) draw() pygame.display.update() pygame.time.delay(20) # Sorting Algo:Merge sortdef mergesort(array, l, r): mid =(l + r)//2 if l<r: mergesort(array, l, mid) mergesort(array, mid + 1, r) merge(array, l, mid, mid + 1, r)def merge(array, x1, y1, x2, y2): i = x1 j = x2 temp =[] pygame.event.pump() while i<= y1 and j<= y2: arr_clr[i]= clr[1] arr_clr[j]= clr[1] refill() arr_clr[i]= clr[0] arr_clr[j]= clr[0] if array[i]<array[j]: temp.append(array[i]) i+= 1 else: temp.append(array[j]) j+= 1 while i<= y1: arr_clr[i]= clr[1] refill() arr_clr[i]= clr[0] temp.append(array[i]) i+= 1 while j<= y2: arr_clr[j]= clr[1] refill() arr_clr[j]= clr[0] temp.append(array[j]) j+= 1 j = 0 for i in range(x1, y2 + 1): pygame.event.pump() array[i]= temp[j] j+= 1 arr_clr[i]= clr[2] refill() if y2-x1 == len(array)-2: arr_clr[i]= clr[3] else: arr_clr[i]= clr[0] # Draw the array valuesdef draw(): # Text should be rendered txt = fnt.render(\"PRESS\"\\ \" 'ENTER' TO PERFORM SORTING.\", 1, (0, 0, 0)) # Position where text is placed screen.blit(txt, (20, 20)) txt1 = fnt.render(\"PRESS 'R' FOR NEW ARRAY.\", 1, (0, 0, 0)) screen.blit(txt1, (20, 40)) txt2 = fnt1.render(\"ALGORITHM USED: \"\\ \"MERGE SORT\", 1, (0, 0, 0)) screen.blit(txt2, (600, 60)) element_width =(width-150)//150 boundry_arr = 900 / 150 boundry_grp = 550 / 100 pygame.draw.line(screen, (0, 0, 0), (0, 95), (900, 95), 6) for i in range(1, 100): pygame.draw.line(screen, (224, 224, 224), (0, boundry_grp * i + 100), (900, boundry_grp * i + 100), 1) # Drawing the array values as lines for i in range(1, 151): pygame.draw.line(screen, arr_clr[i],\\ (boundry_arr * i-3, 100),\\ (boundry_arr * i-3, array[i]*boundry_grp + 100),\\ element_width) # Infinite loop to keep the window openwhile run: # background screen.fill((255, 255, 255)) # Event handler stores all event for event in pygame.event.get(): # If we click Close button in window if event.type == pygame.QUIT: run = False if event.type == pygame.KEYDOWN: if event.key == pygame.K_r: generate_arr() if event.key == pygame.K_RETURN: mergesort(array, 1, len(array)-1) draw() pygame.display.update() pygame.quit()", "e": 32931, "s": 29215, "text": null }, { "code": null, "e": 32939, "s": 32931, "text": "Output:" }, { "code": null, "e": 33125, "s": 32939, "text": "\nVideo Playerhttps://media.geeksforgeeks.org/wp-content/uploads/20200619162211/visualiser15-2020-06-19_16.16.37.mp400:0000:0000:52Use Up/Down Arrow keys to increase or decrease volume.\n" }, { "code": null, "e": 33141, "s": 33125, "text": "Archit_Dwevedi0" }, { "code": null, "e": 33152, "s": 33141, "text": "Merge Sort" }, { "code": null, "e": 33171, "s": 33152, "text": "Divide and Conquer" }, { "code": null, "e": 33178, "s": 33171, "text": "Python" }, { "code": null, "e": 33186, "s": 33178, "text": "Sorting" }, { "code": null, "e": 33205, "s": 33186, "text": "Divide and Conquer" }, { "code": null, "e": 33213, "s": 33205, "text": "Sorting" }, { "code": null, "e": 33224, "s": 33213, "text": "Merge Sort" }, { "code": null, "e": 33322, "s": 33224, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33349, "s": 33322, "text": "Program for Tower of Hanoi" }, { "code": null, "e": 33393, "s": 33349, "text": "Divide and Conquer Algorithm | Introduction" }, { "code": null, "e": 33440, "s": 33393, "text": "Median of two sorted arrays of different sizes" }, { "code": null, "e": 33502, "s": 33440, "text": "Divide and Conquer | Set 5 (Strassen's Matrix Multiplication)" }, { "code": null, "e": 33560, "s": 33502, "text": "Closest Pair of Points using Divide and Conquer algorithm" }, { "code": null, "e": 33588, "s": 33560, "text": "Read JSON file using Python" }, { "code": null, "e": 33638, "s": 33588, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 33660, "s": 33638, "text": "Python map() function" } ]
HTML | DOM Input Month Object - GeeksforGeeks
14 Feb, 2022 The Input Month Object in HTML DOM is used to represent an HTML input element with type= “month” attribute. The input element with type= “month” attribute can be accessed by using getElementById() method. Syntax: It is used to access <input> element with type=”month” attribute. document.getElementById("id"); It is used to create <input> element with type=”month” attribute. document.createElement("input"); Property Values: Input Month Object Methods: Example 1: This example use getElementById() method to access <input> element with type=”month” attribute. html <!DOCTYPE html><html> <head> <title> HTML DOM Input Month Object </title></head> <body> <h1>GeeksforGeeks</h1> <h2>DOM Input Month Object</h2> <input type = "month" id = "month" value = "2018-02"> <button onclick = "myGeeks()">Click Here!</button> <p id = "GFG"></p> <!-- script to access input element of type month attribute --> <script> function myGeeks() { var val = document.getElementById("month").value; document.getElementById("GFG").innerHTML = val; } </script></body> </html> Output: Before click on the button: After click on the button: Example 2: This example use document.createElement() method to create <input> element with type=”month” attribute. html <!DOCTYPE html><html> <head> <title> HTML DOM Input Month Object </title></head> <body> <h1>GeeksforGeeks</h1> <h2>DOM Input Month Object</h2> <button onclick = "myGeeks()">Click Here!</button> <!-- script to create input element of type month attribute --> <script> function myGeeks() { /* Create an input element */ var x = document.createElement("INPUT"); /* Set the type attribute */ x.setAttribute("type", "month"); /* Set the value to type attribute */ x.setAttribute("value", "2018-02"); /* Append the element to body tag */ document.body.appendChild(x); } </script></body> </html> Output: Before click on the button: After click on the button: Supported Browsers: Google Chrome Internet Explorer (after IE 11) Opera Safari Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. ManasChhabra2 hritikbhatnagar2182 HTML-DOM Picked HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to insert spaces/tabs in text using HTML/CSS? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to set the default value for an HTML <select> element ? How to update Node.js and NPM to next version ? How to set input type date in dd-mm-yyyy format using HTML ? Roadmap to Become a Web Developer in 2022 Installation of Node.js on Linux How to fetch data from an API in ReactJS ? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 23928, "s": 23900, "text": "\n14 Feb, 2022" }, { "code": null, "e": 24133, "s": 23928, "text": "The Input Month Object in HTML DOM is used to represent an HTML input element with type= “month” attribute. The input element with type= “month” attribute can be accessed by using getElementById() method." }, { "code": null, "e": 24143, "s": 24133, "text": "Syntax: " }, { "code": null, "e": 24209, "s": 24143, "text": "It is used to access <input> element with type=”month” attribute." }, { "code": null, "e": 24240, "s": 24209, "text": "document.getElementById(\"id\");" }, { "code": null, "e": 24306, "s": 24240, "text": "It is used to create <input> element with type=”month” attribute." }, { "code": null, "e": 24339, "s": 24306, "text": "document.createElement(\"input\");" }, { "code": null, "e": 24357, "s": 24339, "text": "Property Values: " }, { "code": null, "e": 24387, "s": 24357, "text": "Input Month Object Methods: " }, { "code": null, "e": 24496, "s": 24387, "text": "Example 1: This example use getElementById() method to access <input> element with type=”month” attribute. " }, { "code": null, "e": 24501, "s": 24496, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <title> HTML DOM Input Month Object </title></head> <body> <h1>GeeksforGeeks</h1> <h2>DOM Input Month Object</h2> <input type = \"month\" id = \"month\" value = \"2018-02\"> <button onclick = \"myGeeks()\">Click Here!</button> <p id = \"GFG\"></p> <!-- script to access input element of type month attribute --> <script> function myGeeks() { var val = document.getElementById(\"month\").value; document.getElementById(\"GFG\").innerHTML = val; } </script></body> </html> ", "e": 25102, "s": 24501, "text": null }, { "code": null, "e": 25140, "s": 25102, "text": "Output: Before click on the button: " }, { "code": null, "e": 25169, "s": 25140, "text": "After click on the button: " }, { "code": null, "e": 25286, "s": 25169, "text": "Example 2: This example use document.createElement() method to create <input> element with type=”month” attribute. " }, { "code": null, "e": 25291, "s": 25286, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <title> HTML DOM Input Month Object </title></head> <body> <h1>GeeksforGeeks</h1> <h2>DOM Input Month Object</h2> <button onclick = \"myGeeks()\">Click Here!</button> <!-- script to create input element of type month attribute --> <script> function myGeeks() { /* Create an input element */ var x = document.createElement(\"INPUT\"); /* Set the type attribute */ x.setAttribute(\"type\", \"month\"); /* Set the value to type attribute */ x.setAttribute(\"value\", \"2018-02\"); /* Append the element to body tag */ document.body.appendChild(x); } </script></body> </html> ", "e": 26099, "s": 25291, "text": null }, { "code": null, "e": 26137, "s": 26099, "text": "Output: Before click on the button: " }, { "code": null, "e": 26166, "s": 26137, "text": "After click on the button: " }, { "code": null, "e": 26186, "s": 26166, "text": "Supported Browsers:" }, { "code": null, "e": 26200, "s": 26186, "text": "Google Chrome" }, { "code": null, "e": 26232, "s": 26200, "text": "Internet Explorer (after IE 11)" }, { "code": null, "e": 26238, "s": 26232, "text": "Opera" }, { "code": null, "e": 26245, "s": 26238, "text": "Safari" }, { "code": null, "e": 26384, "s": 26247, "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": 26398, "s": 26384, "text": "ManasChhabra2" }, { "code": null, "e": 26418, "s": 26398, "text": "hritikbhatnagar2182" }, { "code": null, "e": 26427, "s": 26418, "text": "HTML-DOM" }, { "code": null, "e": 26434, "s": 26427, "text": "Picked" }, { "code": null, "e": 26439, "s": 26434, "text": "HTML" }, { "code": null, "e": 26456, "s": 26439, "text": "Web Technologies" }, { "code": null, "e": 26461, "s": 26456, "text": "HTML" }, { "code": null, "e": 26559, "s": 26461, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26609, "s": 26559, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 26671, "s": 26609, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 26731, "s": 26671, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 26779, "s": 26731, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 26840, "s": 26779, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" }, { "code": null, "e": 26882, "s": 26840, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 26915, "s": 26882, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 26958, "s": 26915, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 27020, "s": 26958, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" } ]
Program to check if the points are parallel to X axis or Y axis - GeeksforGeeks
22 Mar, 2022 Given n points, we need to check if these n points are parallel to X axis or Y axis or to No axis. Examples: Input : x[] = {0, 0, 0, 0, 0| y[] = {9, 2, 1, 3, 4} Output : Parallel to Y Axis Input : x[] = {1, 2, 3| y[] = {9, 2, 1} Output : Not Parallel to X or Y Axis Approach To find the points parallel to X or Y axis just check if the points are same for any axis or not. If all the points on X axis are same then the line is parallel to Y axis. If all the points on Y axis are same so the line is parallel to X axis. If none of the cases is true, then it is not parallel to any axis. Input the value N. And then Input the value of points in a C++ Java Python3 C# PHP Javascript // CPP program to check for parallel// to X and Y Axis#include <bits/stdc++.h>using namespace std; // To check for parallel linevoid parallel(int n, int a[][2]){ bool x = true, y = true; // checking for parallel to X and Y // axis condition for (int i = 0; i < n - 1; i++) { if (a[i][0] != a[i + 1][0]) x = false; if (a[i][1] != a[i + 1][1]) y = false; } // To display the output if (x) cout << "parallel to Y Axis" << endl; else if (y) cout << "parallel to X Axis" << endl; else cout << "Not parallel to X" << " and Y Axis" << endl;} // Driver's Codeint main(){ int a[][2] = { { 1, 2 }, { 1, 4 }, { 1, 6 }, { 1, 0 } }; int n = sizeof(a) / sizeof(a[0]); parallel(n, a); return 0;} // Java program to illustrate..// To check for parallel// To X and Y Axis import java.io.*;import java.util.*; class GFG { // To check for parallel line static void parallel(int a[][]) { boolean x = true, y = true; // checking for parallel to X and Y // axis condition for (int i = 0; i < a.length - 1; i++) { if (a[i][0] != a[i + 1][0]) x = false; if (a[i][1] != a[i + 1][1]) y = false; } // To display the output if (x) System.out.println("Parallel to Y Axis"); else if (y) System.out.println("Parallel to X Axis"); else System.out.println("Not parallel to X" + " and Y axis"); } public static void main(String[] args) { int a[][] = { { 1, 2 }, { 1, 4 }, { 1, 6 }, { 1, 0 } }; parallel(a); }} # Python3 program to check for parallel# to X and Y Axis # To check for parallel linedef parallel(n, a): x = True; y = True; # checking for parallel # to X and Y axis condition for i in range(n - 1): if (a[i][0] != a[i + 1][0]): x = False; if (a[i][1] != a[i + 1][1]): y = False; # To display the output if (x): print("Parallel to Y Axis"); elif (y): print("Parallel to X Axis"); else: print("Not Parallel to X and Y Axis"); # Driver's Codea = [[1, 2], [1, 4], [1, 6], [1, 0]]; n = len(a);parallel(n, a); # This code is contributed by mits // C# program to illustrate..// To check for parallel// To X and Y Axis class GFG { // To check for parallel line static void parallel(int[, ] a) { bool x = true, y = true; // checking for parallel to X and Y // axis condition for (int i = 0; i < a.Rank - 1; i++) { if (a[i, 0] != a[i + 1, 0]) x = false; if (a[i, 1] != a[i + 1, 1]) y = false; } // To display the output if (x) System.Console.WriteLine("Parallel to Y Axis"); else if (y) System.Console.WriteLine("Parallel to X Axis"); else System.Console.WriteLine("Not parallel to X" + " and Y axis"); } public static void Main() { int[, ] a = { { 1, 2 }, { 1, 4 }, { 1, 6 }, { 1, 0 } }; parallel(a); }}// This code is contributed by mits <?php// PHP program to check for parallel// to X and Y Axis // To check for parallel linefunction parallel($n, $a){ $x = true; $y = true; // checking for parallel // to X and Y axis condition for ($i = 0; $i < $n - 1; $i++) { if ($a[$i][0] != $a[$i + 1][0]) $x = false; if ($a[$i][1] != $a[$i + 1][1]) $y = false; } // To display the output if ($x) echo "parallel to Y Axis" ; else if (y) echo "parallel to X Axis" ; else echo "Not parallel to X", " and Y Axis";} // Driver's Code $a = array(array(1, 2), array(1, 4), array(1, 6), array(1, 0)); $n = count($a); parallel($n, $a); //This code is contributed by anuj_67?> <script> // Javascript program to check for parallel// to X and Y Axis // To check for parallel linefunction parallel(n, a){ let x = true, y = true; // Checking for parallel to X and Y // axis condition for(let i = 0; i < n - 1; i++) { if (a[i][0] != a[i + 1][0]) x = false; if (a[i][1] != a[i + 1][1]) y = false; } // To display the output if (x) document.write("parallel to Y Axis" + "</br>"); else if (y) document.write("parallel to X Axis" + "</br>"); else document.write("Not parallel to X" + " and Y Axis" + "</br>");} // Driver codelet a = [ [ 1, 2 ], [ 1, 4 ], [ 1, 6 ], [ 1, 0 ] ];let n = a.length; parallel(n, a); // This code is contributed by jana_sayantan </script> Parallel to Y Axis Time Complexity: O(n) Auxiliary Space: O(1) vt_m Mithun Kumar shilpiaggarwal25 jana_sayantan rohitkumarsinghcna Geometric Mathematical School Programming Mathematical Geometric Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Convex Hull using Divide and Conquer Algorithm Orientation of 3 ordered points Equation of circle when three points on the circle are given Program to find slope of a line Program to find line passing through 2 Points Program for Fibonacci numbers Write a program to print all permutations of a given string C++ Data Types Set in C++ Standard Template Library (STL) Coin Change | DP-7
[ { "code": null, "e": 25380, "s": 25352, "text": "\n22 Mar, 2022" }, { "code": null, "e": 25479, "s": 25380, "text": "Given n points, we need to check if these n points are parallel to X axis or Y axis or to No axis." }, { "code": null, "e": 25491, "s": 25479, "text": "Examples: " }, { "code": null, "e": 25665, "s": 25491, "text": "Input : x[] = {0, 0, 0, 0, 0|\n y[] = {9, 2, 1, 3, 4}\nOutput : Parallel to Y Axis\n\nInput : x[] = {1, 2, 3|\n y[] = {9, 2, 1}\nOutput : Not Parallel to X or Y Axis" }, { "code": null, "e": 25674, "s": 25665, "text": "Approach" }, { "code": null, "e": 26046, "s": 25674, "text": "To find the points parallel to X or Y axis just check if the points are same for any axis or not. If all the points on X axis are same then the line is parallel to Y axis. If all the points on Y axis are same so the line is parallel to X axis. If none of the cases is true, then it is not parallel to any axis. Input the value N. And then Input the value of points in a " }, { "code": null, "e": 26050, "s": 26046, "text": "C++" }, { "code": null, "e": 26055, "s": 26050, "text": "Java" }, { "code": null, "e": 26063, "s": 26055, "text": "Python3" }, { "code": null, "e": 26066, "s": 26063, "text": "C#" }, { "code": null, "e": 26070, "s": 26066, "text": "PHP" }, { "code": null, "e": 26081, "s": 26070, "text": "Javascript" }, { "code": "// CPP program to check for parallel// to X and Y Axis#include <bits/stdc++.h>using namespace std; // To check for parallel linevoid parallel(int n, int a[][2]){ bool x = true, y = true; // checking for parallel to X and Y // axis condition for (int i = 0; i < n - 1; i++) { if (a[i][0] != a[i + 1][0]) x = false; if (a[i][1] != a[i + 1][1]) y = false; } // To display the output if (x) cout << \"parallel to Y Axis\" << endl; else if (y) cout << \"parallel to X Axis\" << endl; else cout << \"Not parallel to X\" << \" and Y Axis\" << endl;} // Driver's Codeint main(){ int a[][2] = { { 1, 2 }, { 1, 4 }, { 1, 6 }, { 1, 0 } }; int n = sizeof(a) / sizeof(a[0]); parallel(n, a); return 0;}", "e": 26927, "s": 26081, "text": null }, { "code": "// Java program to illustrate..// To check for parallel// To X and Y Axis import java.io.*;import java.util.*; class GFG { // To check for parallel line static void parallel(int a[][]) { boolean x = true, y = true; // checking for parallel to X and Y // axis condition for (int i = 0; i < a.length - 1; i++) { if (a[i][0] != a[i + 1][0]) x = false; if (a[i][1] != a[i + 1][1]) y = false; } // To display the output if (x) System.out.println(\"Parallel to Y Axis\"); else if (y) System.out.println(\"Parallel to X Axis\"); else System.out.println(\"Not parallel to X\" + \" and Y axis\"); } public static void main(String[] args) { int a[][] = { { 1, 2 }, { 1, 4 }, { 1, 6 }, { 1, 0 } }; parallel(a); }}", "e": 27902, "s": 26927, "text": null }, { "code": "# Python3 program to check for parallel# to X and Y Axis # To check for parallel linedef parallel(n, a): x = True; y = True; # checking for parallel # to X and Y axis condition for i in range(n - 1): if (a[i][0] != a[i + 1][0]): x = False; if (a[i][1] != a[i + 1][1]): y = False; # To display the output if (x): print(\"Parallel to Y Axis\"); elif (y): print(\"Parallel to X Axis\"); else: print(\"Not Parallel to X and Y Axis\"); # Driver's Codea = [[1, 2], [1, 4], [1, 6], [1, 0]]; n = len(a);parallel(n, a); # This code is contributed by mits", "e": 28548, "s": 27902, "text": null }, { "code": "// C# program to illustrate..// To check for parallel// To X and Y Axis class GFG { // To check for parallel line static void parallel(int[, ] a) { bool x = true, y = true; // checking for parallel to X and Y // axis condition for (int i = 0; i < a.Rank - 1; i++) { if (a[i, 0] != a[i + 1, 0]) x = false; if (a[i, 1] != a[i + 1, 1]) y = false; } // To display the output if (x) System.Console.WriteLine(\"Parallel to Y Axis\"); else if (y) System.Console.WriteLine(\"Parallel to X Axis\"); else System.Console.WriteLine(\"Not parallel to X\" + \" and Y axis\"); } public static void Main() { int[, ] a = { { 1, 2 }, { 1, 4 }, { 1, 6 }, { 1, 0 } }; parallel(a); }}// This code is contributed by mits", "e": 29525, "s": 28548, "text": null }, { "code": "<?php// PHP program to check for parallel// to X and Y Axis // To check for parallel linefunction parallel($n, $a){ $x = true; $y = true; // checking for parallel // to X and Y axis condition for ($i = 0; $i < $n - 1; $i++) { if ($a[$i][0] != $a[$i + 1][0]) $x = false; if ($a[$i][1] != $a[$i + 1][1]) $y = false; } // To display the output if ($x) echo \"parallel to Y Axis\" ; else if (y) echo \"parallel to X Axis\" ; else echo \"Not parallel to X\", \" and Y Axis\";} // Driver's Code $a = array(array(1, 2), array(1, 4), array(1, 6), array(1, 0)); $n = count($a); parallel($n, $a); //This code is contributed by anuj_67?>", "e": 30305, "s": 29525, "text": null }, { "code": "<script> // Javascript program to check for parallel// to X and Y Axis // To check for parallel linefunction parallel(n, a){ let x = true, y = true; // Checking for parallel to X and Y // axis condition for(let i = 0; i < n - 1; i++) { if (a[i][0] != a[i + 1][0]) x = false; if (a[i][1] != a[i + 1][1]) y = false; } // To display the output if (x) document.write(\"parallel to Y Axis\" + \"</br>\"); else if (y) document.write(\"parallel to X Axis\" + \"</br>\"); else document.write(\"Not parallel to X\" + \" and Y Axis\" + \"</br>\");} // Driver codelet a = [ [ 1, 2 ], [ 1, 4 ], [ 1, 6 ], [ 1, 0 ] ];let n = a.length; parallel(n, a); // This code is contributed by jana_sayantan </script>", "e": 31130, "s": 30305, "text": null }, { "code": null, "e": 31149, "s": 31130, "text": "Parallel to Y Axis" }, { "code": null, "e": 31173, "s": 31151, "text": "Time Complexity: O(n)" }, { "code": null, "e": 31195, "s": 31173, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 31200, "s": 31195, "text": "vt_m" }, { "code": null, "e": 31213, "s": 31200, "text": "Mithun Kumar" }, { "code": null, "e": 31230, "s": 31213, "text": "shilpiaggarwal25" }, { "code": null, "e": 31244, "s": 31230, "text": "jana_sayantan" }, { "code": null, "e": 31263, "s": 31244, "text": "rohitkumarsinghcna" }, { "code": null, "e": 31273, "s": 31263, "text": "Geometric" }, { "code": null, "e": 31286, "s": 31273, "text": "Mathematical" }, { "code": null, "e": 31305, "s": 31286, "text": "School Programming" }, { "code": null, "e": 31318, "s": 31305, "text": "Mathematical" }, { "code": null, "e": 31328, "s": 31318, "text": "Geometric" }, { "code": null, "e": 31426, "s": 31328, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31473, "s": 31426, "text": "Convex Hull using Divide and Conquer Algorithm" }, { "code": null, "e": 31505, "s": 31473, "text": "Orientation of 3 ordered points" }, { "code": null, "e": 31566, "s": 31505, "text": "Equation of circle when three points on the circle are given" }, { "code": null, "e": 31598, "s": 31566, "text": "Program to find slope of a line" }, { "code": null, "e": 31644, "s": 31598, "text": "Program to find line passing through 2 Points" }, { "code": null, "e": 31674, "s": 31644, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 31734, "s": 31674, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 31749, "s": 31734, "text": "C++ Data Types" }, { "code": null, "e": 31792, "s": 31749, "text": "Set in C++ Standard Template Library (STL)" } ]
Python | Cloning or Copying a list - GeeksforGeeks
06 Jan, 2022 In this article we will go through various ways of copying or cloning a list in Python. These various ways of copying takes different execution time, so we can compare them on the basis of time. 1. Using slicing technique This is the easiest and the fastest way to clone a list. This method is considered when we want to modify a list and also keep a copy of the original. In this we make a copy of the list itself, along with the reference. This process is also called cloning. This technique takes about 0.039 seconds and is the fastest technique. Python3 # Python program to copy or clone a list# Using the Slice Operatordef Cloning(li1): li_copy = li1[:] return li_copy # Driver Codeli1 = [4, 8, 2, 10, 15, 18]li2 = Cloning(li1)print("Original List:", li1)print("After Cloning:", li2) Output: Original List: [4, 8, 2, 10, 15, 18] After Cloning: [4, 8, 2, 10, 15, 18] 2. Using the extend() method The lists can be copied into a new list by using the extend() function. This appends each element of the iterable object (e.g., another list) to the end of the new list. This takes around 0.053 second to complete. Example: Python3 # Python code to clone or copy a list# Using the in-built function extend()def Cloning(li1): li_copy = [] li_copy.extend(li1) return li_copy # Driver Codeli1 = [4, 8, 2, 10, 15, 18]li2 = Cloning(li1)print("Original List:", li1)print("After Cloning:", li2) Output: Original List: [4, 8, 2, 10, 15, 18] After Cloning: [4, 8, 2, 10, 15, 18] 3. Using the list() method This is the simplest method of cloning a list by using the built-in function list(). This takes about 0.075 seconds to complete. Example: Python3 # Python code to clone or copy a list# Using the in-built function list()def Cloning(li1): li_copy = list(li1) return li_copy # Driver Codeli1 = [4, 8, 2, 10, 15, 18]li2 = Cloning(li1)print("Original List:", li1)print("After Cloning:", li2) Output: Original List: [4, 8, 2, 10, 15, 18] After Cloning: [4, 8, 2, 10, 15, 18] 4. Using the method of Shallow Copy This method of copying using copy.copy is well explained in the article Shallow Copy. This takes around 0.186 seconds to complete. 5. Using list comprehension The method of list comprehension can be used to copy all the elements individually from one list to another. This takes around 0.217 seconds to complete. Python3 # Python code to clone or copy a list# Using list comprehensiondef Cloning(li1): li_copy = [i for i in li1] return li_copy # Driver Codeli1 = [4, 8, 2, 10, 15, 18]li2 = Cloning(li1)print("Original List:", li1)print("After Cloning:", li2) Output: Original List: [4, 8, 2, 10, 15, 18] After Cloning: [4, 8, 2, 10, 15, 18] 6. Using the append() method This can be used for appending and adding elements to list or copying them to a new list. It is used to add elements to the last position of list. This takes around 0.325 seconds to complete and is the slowest method of cloning. Python3 # Python code to clone or copy a list# Using append()def Cloning(li1): li_copy =[] for item in li1: li_copy.append(item) return li_copy # Driver Codeli1 = [4, 8, 2, 10, 15, 18]li2 = Cloning(li1)print("Original List:", li1)print("After Cloning:", li2) Output: Original List: [4, 8, 2, 10, 15, 18] After Cloning: [4, 8, 2, 10, 15, 18] 7. Using the copy() method The inbuilt method copy is used to copy all the elements from one list to another. This takes around 1.488 seconds to complete. Example: Python3 # Python code to clone or copy a list# Using bilt-in method copy()def Cloning(li1): li_copy =[] li_copy = li1.copy() return li_copy # Driver Codeli1 = [4, 8, 2, 10, 15, 18]li2 = Cloning(li1)print("Original List:", li1)print("After Cloning:", li2) Output: Original List: [4, 8, 2, 10, 15, 18] After Cloning: [4, 8, 2, 10, 15, 18] 8. Using the method of Deep Copy This method of copying is well explained in the article Deep Copy. This takes around 10.59 seconds to complete and is the slowest method of cloning. Referred to Stack Overflow. germanshephered48 Python list-programs python-list Python python-list Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. 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() Create a Pandas DataFrame from Lists Python program to convert a list to string Reading and Writing to text files in Python
[ { "code": null, "e": 24141, "s": 24113, "text": "\n06 Jan, 2022" }, { "code": null, "e": 24337, "s": 24141, "text": "In this article we will go through various ways of copying or cloning a list in Python. These various ways of copying takes different execution time, so we can compare them on the basis of time. " }, { "code": null, "e": 24693, "s": 24337, "text": "1. Using slicing technique This is the easiest and the fastest way to clone a list. This method is considered when we want to modify a list and also keep a copy of the original. In this we make a copy of the list itself, along with the reference. This process is also called cloning. This technique takes about 0.039 seconds and is the fastest technique. " }, { "code": null, "e": 24701, "s": 24693, "text": "Python3" }, { "code": "# Python program to copy or clone a list# Using the Slice Operatordef Cloning(li1): li_copy = li1[:] return li_copy # Driver Codeli1 = [4, 8, 2, 10, 15, 18]li2 = Cloning(li1)print(\"Original List:\", li1)print(\"After Cloning:\", li2)", "e": 24940, "s": 24701, "text": null }, { "code": null, "e": 24949, "s": 24940, "text": "Output: " }, { "code": null, "e": 25026, "s": 24949, "text": "Original List: [4, 8, 2, 10, 15, 18] \nAfter Cloning: [4, 8, 2, 10, 15, 18] \n" }, { "code": null, "e": 25270, "s": 25026, "text": "2. Using the extend() method The lists can be copied into a new list by using the extend() function. This appends each element of the iterable object (e.g., another list) to the end of the new list. This takes around 0.053 second to complete. " }, { "code": null, "e": 25280, "s": 25270, "text": "Example: " }, { "code": null, "e": 25288, "s": 25280, "text": "Python3" }, { "code": "# Python code to clone or copy a list# Using the in-built function extend()def Cloning(li1): li_copy = [] li_copy.extend(li1) return li_copy # Driver Codeli1 = [4, 8, 2, 10, 15, 18]li2 = Cloning(li1)print(\"Original List:\", li1)print(\"After Cloning:\", li2)", "e": 25555, "s": 25288, "text": null }, { "code": null, "e": 25564, "s": 25555, "text": "Output: " }, { "code": null, "e": 25638, "s": 25564, "text": "Original List: [4, 8, 2, 10, 15, 18]\nAfter Cloning: [4, 8, 2, 10, 15, 18]" }, { "code": null, "e": 25795, "s": 25638, "text": "3. Using the list() method This is the simplest method of cloning a list by using the built-in function list(). This takes about 0.075 seconds to complete. " }, { "code": null, "e": 25805, "s": 25795, "text": "Example: " }, { "code": null, "e": 25813, "s": 25805, "text": "Python3" }, { "code": "# Python code to clone or copy a list# Using the in-built function list()def Cloning(li1): li_copy = list(li1) return li_copy # Driver Codeli1 = [4, 8, 2, 10, 15, 18]li2 = Cloning(li1)print(\"Original List:\", li1)print(\"After Cloning:\", li2)", "e": 26062, "s": 25813, "text": null }, { "code": null, "e": 26071, "s": 26062, "text": "Output: " }, { "code": null, "e": 26145, "s": 26071, "text": "Original List: [4, 8, 2, 10, 15, 18]\nAfter Cloning: [4, 8, 2, 10, 15, 18]" }, { "code": null, "e": 26313, "s": 26145, "text": "4. Using the method of Shallow Copy This method of copying using copy.copy is well explained in the article Shallow Copy. This takes around 0.186 seconds to complete. " }, { "code": null, "e": 26496, "s": 26313, "text": "5. Using list comprehension The method of list comprehension can be used to copy all the elements individually from one list to another. This takes around 0.217 seconds to complete. " }, { "code": null, "e": 26504, "s": 26496, "text": "Python3" }, { "code": "# Python code to clone or copy a list# Using list comprehensiondef Cloning(li1): li_copy = [i for i in li1] return li_copy # Driver Codeli1 = [4, 8, 2, 10, 15, 18]li2 = Cloning(li1)print(\"Original List:\", li1)print(\"After Cloning:\", li2)", "e": 26750, "s": 26504, "text": null }, { "code": null, "e": 26759, "s": 26750, "text": "Output: " }, { "code": null, "e": 26833, "s": 26759, "text": "Original List: [4, 8, 2, 10, 15, 18]\nAfter Cloning: [4, 8, 2, 10, 15, 18]" }, { "code": null, "e": 27092, "s": 26833, "text": "6. Using the append() method This can be used for appending and adding elements to list or copying them to a new list. It is used to add elements to the last position of list. This takes around 0.325 seconds to complete and is the slowest method of cloning. " }, { "code": null, "e": 27100, "s": 27092, "text": "Python3" }, { "code": "# Python code to clone or copy a list# Using append()def Cloning(li1): li_copy =[] for item in li1: li_copy.append(item) return li_copy # Driver Codeli1 = [4, 8, 2, 10, 15, 18]li2 = Cloning(li1)print(\"Original List:\", li1)print(\"After Cloning:\", li2)", "e": 27362, "s": 27100, "text": null }, { "code": null, "e": 27371, "s": 27362, "text": "Output: " }, { "code": null, "e": 27445, "s": 27371, "text": "Original List: [4, 8, 2, 10, 15, 18]\nAfter Cloning: [4, 8, 2, 10, 15, 18]" }, { "code": null, "e": 27600, "s": 27445, "text": "7. Using the copy() method The inbuilt method copy is used to copy all the elements from one list to another. This takes around 1.488 seconds to complete." }, { "code": null, "e": 27611, "s": 27600, "text": " Example: " }, { "code": null, "e": 27619, "s": 27611, "text": "Python3" }, { "code": "# Python code to clone or copy a list# Using bilt-in method copy()def Cloning(li1): li_copy =[] li_copy = li1.copy() return li_copy # Driver Codeli1 = [4, 8, 2, 10, 15, 18]li2 = Cloning(li1)print(\"Original List:\", li1)print(\"After Cloning:\", li2)", "e": 27877, "s": 27619, "text": null }, { "code": null, "e": 27886, "s": 27877, "text": "Output: " }, { "code": null, "e": 27960, "s": 27886, "text": "Original List: [4, 8, 2, 10, 15, 18]\nAfter Cloning: [4, 8, 2, 10, 15, 18]" }, { "code": null, "e": 28143, "s": 27960, "text": "8. Using the method of Deep Copy This method of copying is well explained in the article Deep Copy. This takes around 10.59 seconds to complete and is the slowest method of cloning. " }, { "code": null, "e": 28172, "s": 28143, "text": "Referred to Stack Overflow. " }, { "code": null, "e": 28190, "s": 28172, "text": "germanshephered48" }, { "code": null, "e": 28211, "s": 28190, "text": "Python list-programs" }, { "code": null, "e": 28223, "s": 28211, "text": "python-list" }, { "code": null, "e": 28230, "s": 28223, "text": "Python" }, { "code": null, "e": 28242, "s": 28230, "text": "python-list" }, { "code": null, "e": 28340, "s": 28242, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28358, "s": 28340, "text": "Python Dictionary" }, { "code": null, "e": 28393, "s": 28358, "text": "Read a file line by line in Python" }, { "code": null, "e": 28415, "s": 28393, "text": "Enumerate() in Python" }, { "code": null, "e": 28447, "s": 28415, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28477, "s": 28447, "text": "Iterate over a list in Python" }, { "code": null, "e": 28519, "s": 28477, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 28545, "s": 28519, "text": "Python String | replace()" }, { "code": null, "e": 28582, "s": 28545, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 28625, "s": 28582, "text": "Python program to convert a list to string" } ]
Reverse all the words of sentence JavaScript
We are required to write a JavaScript function that takes in a string and returns a new string which has all the words reversed from the original string. For example − If the original string is − "Hello World how is it outside" Then the output should be − "olleH dlroW woH si ti edistuo" Now, let's write the code for this function − const str = 'Hello World how is it outside'; const reverseSentence = str => { const arr = str.split(" "); const reversed = arr.map(el => { return el.split('').reverse().join(""); }); return reversed.join(" "); }; console.log(reverseSentence(str)); The output in the console will be − olleH dlroW woh si ti edistuo
[ { "code": null, "e": 1216, "s": 1062, "text": "We are required to write a JavaScript function that takes in a string and returns a new string\nwhich has all the words reversed from the original string." }, { "code": null, "e": 1230, "s": 1216, "text": "For example −" }, { "code": null, "e": 1258, "s": 1230, "text": "If the original string is −" }, { "code": null, "e": 1290, "s": 1258, "text": "\"Hello World how is it outside\"" }, { "code": null, "e": 1318, "s": 1290, "text": "Then the output should be −" }, { "code": null, "e": 1350, "s": 1318, "text": "\"olleH dlroW woH si ti edistuo\"" }, { "code": null, "e": 1396, "s": 1350, "text": "Now, let's write the code for this function −" }, { "code": null, "e": 1662, "s": 1396, "text": "const str = 'Hello World how is it outside';\nconst reverseSentence = str => {\n const arr = str.split(\" \");\n const reversed = arr.map(el => {\n return el.split('').reverse().join(\"\");\n });\n return reversed.join(\" \");\n};\nconsole.log(reverseSentence(str));" }, { "code": null, "e": 1698, "s": 1662, "text": "The output in the console will be −" }, { "code": null, "e": 1728, "s": 1698, "text": "olleH dlroW woh si ti edistuo" } ]
Unity - The Button
In this chapter, we will earn how to insert UI elements into our scene and go about working with them. Let us start off with a Button. To insert a button, right click in the Scene Hierarchy and go to Create → UI → Button. If you do not have an existing Canvas and an EventSystem, Unity will automatically create one for you, and place the button inside the Canvas as well. Remember that in Overlay rendering mode, which is the default mode, the size of the Canvas is independent of the size of the camera. You can test this by clicking on the Game tab. If you play the scene, you will notice the button already has some standard functionality such as detecting when the mouse is hovering over it, and changing color when pressed. A Button requires functionality to be actually useful in the UI. This functionality can be added through its properties. Let us create a new script, and call it ButtonBehaviour. public class ButtonBehaviour : MonoBehaviour { int n; public void OnButtonPress(){ n++; Debug.Log("Button clicked " + n + " times."); } } We have made a simple method that logs how many times we have hit the button. Note − This method has to be public; it will not be noticed by the Button’s functionality otherwise. Let us create an empty GameObject and attach this script to it. We do this because a button will not do anything on its own; it only calls the specified method in its scripting. Now, go into the Button’s properties, and find the OnClick() property. Hit the + icon on the bottom tab, and a new entry should show up in the list. This entry defines what object the button press acts on, and what function of that object’s script is called. Because of the event system used in the button press, you can trigger multiple functions simply by adding them to the list. Drag and drop the empty GameObject, which contains the ButtonManager script we created, onto the None (Object) slot. Navigate the No Function dropdown list, and look for our OnButtonPress method. (Remember that it can be named anything you want, OnButtonPress is simply a standardized naming convention.) You should find it in the ButtonBehaviour section. If you play the game now, you can test the button and surely enough, the console prints out how many times you have pressed the button. 119 Lectures 23.5 hours Raja Biswas 58 Lectures 10 hours Three Millennials 16 Lectures 1 hours Peter Jepson 23 Lectures 2.5 hours Zenva 21 Lectures 2 hours Zenva 43 Lectures 9.5 hours Raja Biswas Print Add Notes Bookmark this page
[ { "code": null, "e": 2318, "s": 2215, "text": "In this chapter, we will earn how to insert UI elements into our scene and go about working with them." }, { "code": null, "e": 2588, "s": 2318, "text": "Let us start off with a Button. To insert a button, right click in the Scene Hierarchy and go to Create → UI → Button. If you do not have an existing Canvas and an EventSystem, Unity will automatically create one for you, and place the button inside the Canvas as well." }, { "code": null, "e": 2768, "s": 2588, "text": "Remember that in Overlay rendering mode, which is the default mode, the size of the Canvas is independent of the size of the camera. You can test this by clicking on the Game tab." }, { "code": null, "e": 2945, "s": 2768, "text": "If you play the scene, you will notice the button already has some standard functionality such as detecting when the mouse is hovering over it, and changing color when pressed." }, { "code": null, "e": 3066, "s": 2945, "text": "A Button requires functionality to be actually useful in the UI. This functionality can be added through its properties." }, { "code": null, "e": 3123, "s": 3066, "text": "Let us create a new script, and call it ButtonBehaviour." }, { "code": null, "e": 3282, "s": 3123, "text": "public class ButtonBehaviour : MonoBehaviour {\n int n;\n public void OnButtonPress(){\n n++;\n Debug.Log(\"Button clicked \" + n + \" times.\");\n }\n}" }, { "code": null, "e": 3360, "s": 3282, "text": "We have made a simple method that logs how many times we have hit the button." }, { "code": null, "e": 3461, "s": 3360, "text": "Note − This method has to be public; it will not be noticed by the Button’s functionality otherwise." }, { "code": null, "e": 3639, "s": 3461, "text": "Let us create an empty GameObject and attach this script to it. We do this because a button will not do anything on its own; it only calls the specified method in its scripting." }, { "code": null, "e": 3710, "s": 3639, "text": "Now, go into the Button’s properties, and find the OnClick() property." }, { "code": null, "e": 3788, "s": 3710, "text": "Hit the + icon on the bottom tab, and a new entry should show up in the list." }, { "code": null, "e": 4022, "s": 3788, "text": "This entry defines what object the button press acts on, and what function of that object’s script is called. Because of the event system used in the button press, you can trigger multiple functions simply by adding them to the list." }, { "code": null, "e": 4139, "s": 4022, "text": "Drag and drop the empty GameObject, which contains the ButtonManager script we created, onto the None (Object) slot." }, { "code": null, "e": 4378, "s": 4139, "text": "Navigate the No Function dropdown list, and look for our OnButtonPress method. (Remember that it can be named anything you want, OnButtonPress is simply a standardized naming convention.) You should find it in the ButtonBehaviour section." }, { "code": null, "e": 4514, "s": 4378, "text": "If you play the game now, you can test the button and surely enough, the console prints out how many times you have pressed the button." }, { "code": null, "e": 4551, "s": 4514, "text": "\n 119 Lectures \n 23.5 hours \n" }, { "code": null, "e": 4564, "s": 4551, "text": " Raja Biswas" }, { "code": null, "e": 4598, "s": 4564, "text": "\n 58 Lectures \n 10 hours \n" }, { "code": null, "e": 4617, "s": 4598, "text": " Three Millennials" }, { "code": null, "e": 4650, "s": 4617, "text": "\n 16 Lectures \n 1 hours \n" }, { "code": null, "e": 4664, "s": 4650, "text": " Peter Jepson" }, { "code": null, "e": 4699, "s": 4664, "text": "\n 23 Lectures \n 2.5 hours \n" }, { "code": null, "e": 4706, "s": 4699, "text": " Zenva" }, { "code": null, "e": 4739, "s": 4706, "text": "\n 21 Lectures \n 2 hours \n" }, { "code": null, "e": 4746, "s": 4739, "text": " Zenva" }, { "code": null, "e": 4781, "s": 4746, "text": "\n 43 Lectures \n 9.5 hours \n" }, { "code": null, "e": 4794, "s": 4781, "text": " Raja Biswas" }, { "code": null, "e": 4801, "s": 4794, "text": " Print" }, { "code": null, "e": 4812, "s": 4801, "text": " Add Notes" } ]
Get all the Documents of the Collection using PyMongo - GeeksforGeeks
10 Jul, 2020 To get all the Documents of the Collection use find() method. The find() method takes a query object as a parameter if we want to find all documents then pass none in the find() method. 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. Note: If we pass no parameter in find() method .it works like select * in MYSQL . Sample Database:Let’s suppose the database looks like this Example 1: import pymongo # establishing connection # to the databaseclient = pymongo.MongoClient("mongodb://localhost:27017/") # Database name db = client["mydatabase"] # Collection name col = db["gfg"] # if we don't want to print id then pass _id:0for x in col.find({}, {"_id":0, "coursename": 1, "price": 1 }): print(x) Output: Example 2: import pymongo # establishing connection # to the databaseclient = pymongo.MongoClient("mongodb://localhost:27017/") # Database name db = client["mydatabase"] # Collection name col = db["gfg"] # if we don't want to print id then pass _id:0 and price :0for x in col.find({}, {"_id":0, "coursename": 1, "price": 0 }): print(x) Output: Python-mongoDB 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 Create a Pandas DataFrame from Lists Reading and Writing to text files in Python
[ { "code": null, "e": 25266, "s": 25238, "text": "\n10 Jul, 2020" }, { "code": null, "e": 25594, "s": 25266, "text": "To get all the Documents of the Collection use find() method. The find() method takes a query object as a parameter if we want to find all documents then pass none in the find() method. 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": 25676, "s": 25594, "text": "Note: If we pass no parameter in find() method .it works like select * in MYSQL ." }, { "code": null, "e": 25735, "s": 25676, "text": "Sample Database:Let’s suppose the database looks like this" }, { "code": null, "e": 25746, "s": 25735, "text": "Example 1:" }, { "code": "import pymongo # establishing connection # to the databaseclient = pymongo.MongoClient(\"mongodb://localhost:27017/\") # Database name db = client[\"mydatabase\"] # Collection name col = db[\"gfg\"] # if we don't want to print id then pass _id:0for x in col.find({}, {\"_id\":0, \"coursename\": 1, \"price\": 1 }): print(x)", "e": 26080, "s": 25746, "text": null }, { "code": null, "e": 26088, "s": 26080, "text": "Output:" }, { "code": null, "e": 26099, "s": 26088, "text": "Example 2:" }, { "code": "import pymongo # establishing connection # to the databaseclient = pymongo.MongoClient(\"mongodb://localhost:27017/\") # Database name db = client[\"mydatabase\"] # Collection name col = db[\"gfg\"] # if we don't want to print id then pass _id:0 and price :0for x in col.find({}, {\"_id\":0, \"coursename\": 1, \"price\": 0 }): print(x)", "e": 26446, "s": 26099, "text": null }, { "code": null, "e": 26454, "s": 26446, "text": "Output:" }, { "code": null, "e": 26469, "s": 26454, "text": "Python-mongoDB" }, { "code": null, "e": 26476, "s": 26469, "text": "Python" }, { "code": null, "e": 26574, "s": 26476, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26583, "s": 26574, "text": "Comments" }, { "code": null, "e": 26596, "s": 26583, "text": "Old Comments" }, { "code": null, "e": 26614, "s": 26596, "text": "Python Dictionary" }, { "code": null, "e": 26649, "s": 26614, "text": "Read a file line by line in Python" }, { "code": null, "e": 26671, "s": 26649, "text": "Enumerate() in Python" }, { "code": null, "e": 26703, "s": 26671, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26733, "s": 26703, "text": "Iterate over a list in Python" }, { "code": null, "e": 26775, "s": 26733, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 26801, "s": 26775, "text": "Python String | replace()" }, { "code": null, "e": 26844, "s": 26801, "text": "Python program to convert a list to string" }, { "code": null, "e": 26881, "s": 26844, "text": "Create a Pandas DataFrame from Lists" } ]
Skin cancer classification with machine learning | by Nyla Pirani | Towards Data Science
Skin cancer is the most common type of skin cancer is the US. More than 4 million cases of skin cancer are diagnosed in the US a year. This is huge! 4 million people possibly dying a year just from skin cancer. How crazy is that to think about. Now all those people are dying but guess what! About half of those people, maybe even more, don’t even go to the doctor during the early stages when it can be prevented. Even if people are getting symptoms, they still don’t want to go to the doctor. This is crazy. Especially because skin cancer is much easier to treat in the early stages and it grows super fast. Now I can’t magically make people go to the doctor. Or can I... No, you got me. I’m not a wizard. But what I can do is get people to detect the skin cancer themselves at home. All you need is a laptop and some lines of code. So as I said skin cancer is a huge killer in the US and all over the world really. But the thing is it’s preventable in the early stages but people just don’t want to go to the doctors. So, I used machine learning to come up with a way for people to be able to check if they have skin cancer from the comfort of their own home. Data set: I used PyTorch to code this. First, you need to import the data set. For this part, I used some code from this kernel that had all the data in it. base_skin_dir = os.path.join('..', 'input')imageid_path_dict = {os.path.splitext(os.path.basename(x))[0]: x for x in glob(os.path.join(base_skin_dir, '*', '*.jpg'))}lesion_type_dict = { 'nv': 'Melanocytic nevi', 'mel': 'dermatofibroma', 'bkl': 'Benign keratosis-like lesions ', 'bcc': 'Basal cell carcinoma', 'akiec': 'Actinic keratoses', 'vasc': 'Vascular lesions', 'df': 'Dermatofibroma'tile_df = pd.read_csv(os.path.join(base_skin_dir, 'HAM10000_metadata.csv'))tile_df['path'] = tile_df['image_id'].map(imageid_path_dict.get)tile_df['cell_type'] = tile_df['dx'].map(lesion_type_dict.get) tile_df['cell_type_idx'] = pd.Categorical(tile_df['cell_type']).codestile_df[['cell_type_idx', 'cell_type']].sort_values('cell_type_idx').drop_duplicates() Then you should get an output that looks like this. As you can see we have a nice overview of our ground truth data. The only part we need is the column ‘cell_type_idx’, because this data is what we need for the model training. Even though only the one column is what we really need it can still be a good idea to learn what everything means. So let's look quickly at how often these other tumors that are in our table actually occur in the dataset. tile_df['cell_type'].value_counts() After you put in that code you should get an output that looks like this: As you can see, the Melanocytic nevi occur nearly 58 times as often as the Dermatofibroma. It can happen that the Melanocytic nevi are preferred in the prediction compared to the Dermatofibroma. One solution could be to show less frequent classes more often in the training. But this isn't a huge problem that needs to be solved right now and we can do just fine without it. Let’s look more at the complete table: tile_df.sample(3) The table above can be used to get the input data using the path. The corresponding ground truth label is already given in the same line by the column ‘cell_type_idx’. Later we will create an input batch X of several loaded images and a corresponding ground-truth value y given by the corresponding ground-truth labels. But, before we get to that we need to do something else first. Choosing a model. PyTorch has a feature that has well-established models. These models can optionally already be trained on the ImageNet dataset, causing the training time to be lower in general. So, let's load a pre-trained ResNet50 and adjust the last layer a little bit. import torchvision.models as modelsmodel_conv = models.resnet50(pretrained=True) Downloading: "https://download.pytorch.org/models/resnet50- 19c8e357.pth" to /tmp/.torch/models/resnet50-19c8e357.pth 100% ██████████| 102502400/102502400 [00:01<00:00, 83469977.65it/s]print(model_conv) ResNet( (conv1): Conv2d(3, 64, kernel_size=(7, 7), stride=(2, 2), padding=(3, 3), bias=False) (bn1): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (relu): ReLU(inplace) (maxpool): MaxPool2d(kernel_size=3, stride=2, padding=1, dilation=1, ceil_mode=False) (layer1): Sequential( (0): Bottleneck( (conv1): Conv2d(64, 64, kernel_size=(1, 1), stride=(1, 1), bias=False) (bn1): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (conv2): Conv2d(64, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False) (bn2): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (conv3): Conv2d(64, 256, kernel_size=(1, 1), stride=(1, 1), bias=False) (bn3): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (relu): ReLU(inplace) (downsample): Sequential( (0): Conv2d(64, 256, kernel_size=(1, 1), stride=(1, 1), bias=False) (1): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) ) ) (1): Bottleneck( (conv1): Conv2d(256, 64, kernel_size=(1, 1), stride=(1, 1), bias=False) (bn1): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (conv2): Conv2d(64, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False) (bn2): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (conv3): Conv2d(64, 256, kernel_size=(1, 1), stride=(1, 1), bias=False) (bn3): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (relu): ReLU(inplace) ) (2): Bottleneck( (conv1): Conv2d(256, 64, kernel_size=(1, 1), stride=(1, 1), bias=False) (bn1): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (conv2): Conv2d(64, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False) (bn2): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (conv3): Conv2d(64, 256, kernel_size=(1, 1), stride=(1, 1), bias=False) (bn3): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (relu): ReLU(inplace) ) ) (layer2): Sequential( (0): Bottleneck( (conv1): Conv2d(256, 128, kernel_size=(1, 1), stride=(1, 1), bias=False) (bn1): BatchNorm2d(128, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (conv2): Conv2d(128, 128, kernel_size=(3, 3), stride=(2, 2), padding=(1, 1), bias=False) (bn2): BatchNorm2d(128, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (conv3): Conv2d(128, 512, kernel_size=(1, 1), stride=(1, 1), bias=False) (bn3): BatchNorm2d(512, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (relu): ReLU(inplace) (downsample): Sequential( (0): Conv2d(256, 512, kernel_size=(1, 1), stride=(2, 2), bias=False) (1): BatchNorm2d(512, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) ) ) (1): Bottleneck( (conv1): Conv2d(512, 128, kernel_size=(1, 1), stride=(1, 1), bias=False) (bn1): BatchNorm2d(128, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (conv2): Conv2d(128, 128, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False) (bn2): BatchNorm2d(128, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (conv3): Conv2d(128, 512, kernel_size=(1, 1), stride=(1, 1), bias=False) (bn3): BatchNorm2d(512, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (relu): ReLU(inplace) ) (2): Bottleneck( (conv1): Conv2d(512, 128, kernel_size=(1, 1), stride=(1, 1), bias=False) (bn1): BatchNorm2d(128, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (conv2): Conv2d(128, 128, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False) (bn2): BatchNorm2d(128, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (conv3): Conv2d(128, 512, kernel_size=(1, 1), stride=(1, 1), bias=False) (bn3): BatchNorm2d(512, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (relu): ReLU(inplace) ) (3): Bottleneck( (conv1): Conv2d(512, 128, kernel_size=(1, 1), stride=(1, 1), bias=False) (bn1): BatchNorm2d(128, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (conv2): Conv2d(128, 128, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False) (bn2): BatchNorm2d(128, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (conv3): Conv2d(128, 512, kernel_size=(1, 1), stride=(1, 1), bias=False) (bn3): BatchNorm2d(512, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (relu): ReLU(inplace) ) ) (layer3): Sequential( (0): Bottleneck( (conv1): Conv2d(512, 256, kernel_size=(1, 1), stride=(1, 1), bias=False) (bn1): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (conv2): Conv2d(256, 256, kernel_size=(3, 3), stride=(2, 2), padding=(1, 1), bias=False) (bn2): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (conv3): Conv2d(256, 1024, kernel_size=(1, 1), stride=(1, 1), bias=False) (bn3): BatchNorm2d(1024, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (relu): ReLU(inplace) (downsample): Sequential( (0): Conv2d(512, 1024, kernel_size=(1, 1), stride=(2, 2), bias=False) (1): BatchNorm2d(1024, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) ) ) (1): Bottleneck( (conv1): Conv2d(1024, 256, kernel_size=(1, 1), stride=(1, 1), bias=False) (bn1): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (conv2): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False) (bn2): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (conv3): Conv2d(256, 1024, kernel_size=(1, 1), stride=(1, 1), bias=False) (bn3): BatchNorm2d(1024, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (relu): ReLU(inplace) ) (2): Bottleneck( (conv1): Conv2d(1024, 256, kernel_size=(1, 1), stride=(1, 1), bias=False) (bn1): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (conv2): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False) (bn2): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (conv3): Conv2d(256, 1024, kernel_size=(1, 1), stride=(1, 1), bias=False) (bn3): BatchNorm2d(1024, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (relu): ReLU(inplace) ) (3): Bottleneck( (conv1): Conv2d(1024, 256, kernel_size=(1, 1), stride=(1, 1), bias=False) (bn1): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (conv2): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False) (bn2): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (conv3): Conv2d(256, 1024, kernel_size=(1, 1), stride=(1, 1), bias=False) (bn3): BatchNorm2d(1024, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (relu): ReLU(inplace) ) (4): Bottleneck( (conv1): Conv2d(1024, 256, kernel_size=(1, 1), stride=(1, 1), bias=False) (bn1): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (conv2): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False) (bn2): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (conv3): Conv2d(256, 1024, kernel_size=(1, 1), stride=(1, 1), bias=False) (bn3): BatchNorm2d(1024, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (relu): ReLU(inplace) ) (5): Bottleneck( (conv1): Conv2d(1024, 256, kernel_size=(1, 1), stride=(1, 1), bias=False) (bn1): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (conv2): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False) (bn2): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (conv3): Conv2d(256, 1024, kernel_size=(1, 1), stride=(1, 1), bias=False) (bn3): BatchNorm2d(1024, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (relu): ReLU(inplace) ) ) (layer4): Sequential( (0): Bottleneck( (conv1): Conv2d(1024, 512, kernel_size=(1, 1), stride=(1, 1), bias=False) (bn1): BatchNorm2d(512, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (conv2): Conv2d(512, 512, kernel_size=(3, 3), stride=(2, 2), padding=(1, 1), bias=False) (bn2): BatchNorm2d(512, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (conv3): Conv2d(512, 2048, kernel_size=(1, 1), stride=(1, 1), bias=False) (bn3): BatchNorm2d(2048, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (relu): ReLU(inplace) (downsample): Sequential( (0): Conv2d(1024, 2048, kernel_size=(1, 1), stride=(2, 2), bias=False) (1): BatchNorm2d(2048, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) ) ) (1): Bottleneck( (conv1): Conv2d(2048, 512, kernel_size=(1, 1), stride=(1, 1), bias=False) (bn1): BatchNorm2d(512, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (conv2): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False) (bn2): BatchNorm2d(512, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (conv3): Conv2d(512, 2048, kernel_size=(1, 1), stride=(1, 1), bias=False) (bn3): BatchNorm2d(2048, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (relu): ReLU(inplace) ) (2): Bottleneck( (conv1): Conv2d(2048, 512, kernel_size=(1, 1), stride=(1, 1), bias=False) (bn1): BatchNorm2d(512, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (conv2): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False) (bn2): BatchNorm2d(512, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (conv3): Conv2d(512, 2048, kernel_size=(1, 1), stride=(1, 1), bias=False) (bn3): BatchNorm2d(2048, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (relu): ReLU(inplace) ) ) (avgpool): AvgPool2d(kernel_size=7, stride=1, padding=0) (fc): Linear(in_features=2048, out_features=1000, bias=True))print(model_conv.fc) Linear(in_features=2048, out_features=1000, bias=True) So what we have to adjust the last layer (FC). The last layer is a linear layer, that has 2048 input neurons and having 1000 output neurons. This is useful if you have 1000 different classes. However, we only have to deal with 7 different classes — the 7 different tumor types — so we need to change the last layer. num_ftrs = model_conv.fc.in_featuresmodel_conv.fc = torch.nn.Linear(num_ftrs, 7)print(model_conv.fc)Linear(in_features=2048, out_features=7, bias=True) So now after it’s adjusted we need to move the model to the GPU because that’s where the model will be trained in the end. Training and validation set from sklearn.model_selection import train_test_splittrain_df, test_df = train_test_split(tile_df, test_size=0.1)# We can split the test set again in a validation set and a true test set:validation_df, test_df = train_test_split(test_df, test_size=0.5)train_df = train_df.reset_index()validation_df = validation_df.reset_index()test_df = test_df.reset_index() Create a Class ‘Dataset’ The dataset class will allow us to easily load and transform batches of data in the background on multiple CPUs. class Dataset(data.Dataset): 'Characterizes a dataset for PyTorch' def __init__(self, df, transform=None): 'Initialization' self.df = df self.transform = transform def __len__(self): 'Denotes the total number of samples' return len(self.df) def __getitem__(self, index): 'Generates one sample of data' # Load data and get label X = Image.open(self.df['path'][index]) y = torch.tensor(int(self.df['cell_type_idx'][index])) if self.transform: X = self.transform(X) return X, y# Define the parameters for the dataloaderparams = {'batch_size': 4, 'shuffle': True, 'num_workers': 6} Another nice thing about using the dataset class is that we can easily perform preprocessing of the data and/or data augmentation. In this example, we only perform mirroring (RandomHorizontalFlip, RandomVerticalFlip), Crop the image to the image center, where the melanoma is most often located (CenterCrop), randomly crop from the center of the image (RandomCrop) and normalize the image according to what the pre-trained model needs (Normalize). We then transform the image to a tensor using, which is required to use it for learning with PyTorch, with the function ToTensor: define the transformation of the images.import torchvision.transforms as trfcomposed = trf.Compose([trf.RandomHorizontalFlip(), trf.RandomVerticalFlip(), trf.CenterCrop(256), trf.RandomCrop(224), trf.ToTensor(), trf.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])])# Define the trainingsset using the table train_df and using our defined transitions (composed)training_set = Dataset(train_df, transform=composed)training_generator = data.DataLoader(training_set, **params)# Same for the validation set:validation_set = Dataset(validation_df, transform=composed)validation_generator = data.DataLoader(validation_set, **params) Now we have to define the optimizer we want to use. In this case, it will be an Adam optimizer with a learning rate of 1e−61e−6. The loss function that we will use is CrossEntropyLoss. This is the typical one chosen for multiclass classification problems. optimizer = torch.optim.Adam(model.parameters(), lr=1e-6)criterion = torch.nn.CrossEntropyLoss() We now have a data loader for the data in the training set, a data loader for the data in the validation set and we have the optimizer and the criterion defined. We can now start on training and testing the model. Training and testing the model is the main part of machine learning and in my opinion the best. This is where the real stuff happens. All through the data preparation and data collection stuff are important this is the fun part and it is also super important as well. To train the model just input this code: max_epochs = 20trainings_error = []validation_error = []for epoch in range(max_epochs): print('epoch:', epoch) count_train = 0 trainings_error_tmp = [] model.train() for data_sample, y in training_generator: data_gpu = data_sample.to(device) y_gpu = y.to(device) output = model(data_gpu) err = criterion(output, y_gpu) err.backward() optimizer.step() trainings_error_tmp.append(err.item()) count_train += 1 if count_train >= 100: count_train = 0 mean_trainings_error = np.mean(trainings_error_tmp) trainings_error.append(mean_trainings_error) print('trainings error:', mean_trainings_error) break with torch.set_grad_enabled(False): validation_error_tmp = [] count_val = 0 model.eval() for data_sample, y in validation_generator: data_gpu = data_sample.to(device) y_gpu = y.to(device) output = model(data_gpu) err = criterion(output, y_gpu) validation_error_tmp.append(err.item()) count_val += 1 if count_val >= 10: count_val = 0 mean_val_error = np.mean(validation_error_tmp) validation_error.append(mean_val_error) print('validation error:', mean_val_error) breakplt.plot(trainings_error, label = 'training error')plt.plot(validation_error, label = 'validation error')plt.legend()plt.show() Testing the model: To test the actual ability of the model import this code: model.eval()test_set = Dataset(validation_df, transform=composed)test_generator = data.SequentialSampler(validation_set)result_array = []gt_array = []for i in test_generator: data_sample, y = validation_set.__getitem__(i) data_gpu = data_sample.unsqueeze(0).to(device) output = model(data_gpu) result = torch.argmax(output) result_array.append(result.item()) gt_array.append(y.item())correct_results = np.array(result_array)==np.array(gt_array)sum_correct = np.sum(correct_results)accuracy = sum_correct/test_generator.__len__()print(accuracy)0.8403193612774451 So now you can see our accuracy is pretty high but it isn’t perfect. The model isn't going to be 100% perfect yet either but it's definitely close and will get there soon. Now with this people don’t have to go into the doctor every time they get some symptoms of skin cancer and test just test it themselves with the comfort of their own home. And now people won’t be dying from skin cancer just because they didn’t want to go to the doctor. If you have any questions leave them in the comments below and don’t forget to leave a clap!
[ { "code": null, "e": 307, "s": 172, "text": "Skin cancer is the most common type of skin cancer is the US. More than 4 million cases of skin cancer are diagnosed in the US a year." }, { "code": null, "e": 417, "s": 307, "text": "This is huge! 4 million people possibly dying a year just from skin cancer. How crazy is that to think about." }, { "code": null, "e": 587, "s": 417, "text": "Now all those people are dying but guess what! About half of those people, maybe even more, don’t even go to the doctor during the early stages when it can be prevented." }, { "code": null, "e": 782, "s": 587, "text": "Even if people are getting symptoms, they still don’t want to go to the doctor. This is crazy. Especially because skin cancer is much easier to treat in the early stages and it grows super fast." }, { "code": null, "e": 846, "s": 782, "text": "Now I can’t magically make people go to the doctor. Or can I..." }, { "code": null, "e": 1007, "s": 846, "text": "No, you got me. I’m not a wizard. But what I can do is get people to detect the skin cancer themselves at home. All you need is a laptop and some lines of code." }, { "code": null, "e": 1193, "s": 1007, "text": "So as I said skin cancer is a huge killer in the US and all over the world really. But the thing is it’s preventable in the early stages but people just don’t want to go to the doctors." }, { "code": null, "e": 1335, "s": 1193, "text": "So, I used machine learning to come up with a way for people to be able to check if they have skin cancer from the comfort of their own home." }, { "code": null, "e": 1345, "s": 1335, "text": "Data set:" }, { "code": null, "e": 1414, "s": 1345, "text": "I used PyTorch to code this. First, you need to import the data set." }, { "code": null, "e": 1492, "s": 1414, "text": "For this part, I used some code from this kernel that had all the data in it." }, { "code": null, "e": 2280, "s": 1492, "text": "base_skin_dir = os.path.join('..', 'input')imageid_path_dict = {os.path.splitext(os.path.basename(x))[0]: x for x in glob(os.path.join(base_skin_dir, '*', '*.jpg'))}lesion_type_dict = { 'nv': 'Melanocytic nevi', 'mel': 'dermatofibroma', 'bkl': 'Benign keratosis-like lesions ', 'bcc': 'Basal cell carcinoma', 'akiec': 'Actinic keratoses', 'vasc': 'Vascular lesions', 'df': 'Dermatofibroma'tile_df = pd.read_csv(os.path.join(base_skin_dir, 'HAM10000_metadata.csv'))tile_df['path'] = tile_df['image_id'].map(imageid_path_dict.get)tile_df['cell_type'] = tile_df['dx'].map(lesion_type_dict.get) tile_df['cell_type_idx'] = pd.Categorical(tile_df['cell_type']).codestile_df[['cell_type_idx', 'cell_type']].sort_values('cell_type_idx').drop_duplicates()" }, { "code": null, "e": 2508, "s": 2280, "text": "Then you should get an output that looks like this. As you can see we have a nice overview of our ground truth data. The only part we need is the column ‘cell_type_idx’, because this data is what we need for the model training." }, { "code": null, "e": 2730, "s": 2508, "text": "Even though only the one column is what we really need it can still be a good idea to learn what everything means. So let's look quickly at how often these other tumors that are in our table actually occur in the dataset." }, { "code": null, "e": 2766, "s": 2730, "text": "tile_df['cell_type'].value_counts()" }, { "code": null, "e": 2840, "s": 2766, "text": "After you put in that code you should get an output that looks like this:" }, { "code": null, "e": 3215, "s": 2840, "text": "As you can see, the Melanocytic nevi occur nearly 58 times as often as the Dermatofibroma. It can happen that the Melanocytic nevi are preferred in the prediction compared to the Dermatofibroma. One solution could be to show less frequent classes more often in the training. But this isn't a huge problem that needs to be solved right now and we can do just fine without it." }, { "code": null, "e": 3254, "s": 3215, "text": "Let’s look more at the complete table:" }, { "code": null, "e": 3272, "s": 3254, "text": "tile_df.sample(3)" }, { "code": null, "e": 3592, "s": 3272, "text": "The table above can be used to get the input data using the path. The corresponding ground truth label is already given in the same line by the column ‘cell_type_idx’. Later we will create an input batch X of several loaded images and a corresponding ground-truth value y given by the corresponding ground-truth labels." }, { "code": null, "e": 3673, "s": 3592, "text": "But, before we get to that we need to do something else first. Choosing a model." }, { "code": null, "e": 3851, "s": 3673, "text": "PyTorch has a feature that has well-established models. These models can optionally already be trained on the ImageNet dataset, causing the training time to be lower in general." }, { "code": null, "e": 3929, "s": 3851, "text": "So, let's load a pre-trained ResNet50 and adjust the last layer a little bit." }, { "code": null, "e": 14981, "s": 3929, "text": "import torchvision.models as modelsmodel_conv = models.resnet50(pretrained=True) Downloading: \"https://download.pytorch.org/models/resnet50- 19c8e357.pth\" to /tmp/.torch/models/resnet50-19c8e357.pth 100% ██████████| 102502400/102502400 [00:01<00:00, 83469977.65it/s]print(model_conv) ResNet( (conv1): Conv2d(3, 64, kernel_size=(7, 7), stride=(2, 2), padding=(3, 3), bias=False) (bn1): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (relu): ReLU(inplace) (maxpool): MaxPool2d(kernel_size=3, stride=2, padding=1, dilation=1, ceil_mode=False) (layer1): Sequential( (0): Bottleneck( (conv1): Conv2d(64, 64, kernel_size=(1, 1), stride=(1, 1), bias=False) (bn1): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (conv2): Conv2d(64, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False) (bn2): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (conv3): Conv2d(64, 256, kernel_size=(1, 1), stride=(1, 1), bias=False) (bn3): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (relu): ReLU(inplace) (downsample): Sequential( (0): Conv2d(64, 256, kernel_size=(1, 1), stride=(1, 1), bias=False) (1): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) ) ) (1): Bottleneck( (conv1): Conv2d(256, 64, kernel_size=(1, 1), stride=(1, 1), bias=False) (bn1): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (conv2): Conv2d(64, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False) (bn2): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (conv3): Conv2d(64, 256, kernel_size=(1, 1), stride=(1, 1), bias=False) (bn3): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (relu): ReLU(inplace) ) (2): Bottleneck( (conv1): Conv2d(256, 64, kernel_size=(1, 1), stride=(1, 1), bias=False) (bn1): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (conv2): Conv2d(64, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False) (bn2): BatchNorm2d(64, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (conv3): Conv2d(64, 256, kernel_size=(1, 1), stride=(1, 1), bias=False) (bn3): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (relu): ReLU(inplace) ) ) (layer2): Sequential( (0): Bottleneck( (conv1): Conv2d(256, 128, kernel_size=(1, 1), stride=(1, 1), bias=False) (bn1): BatchNorm2d(128, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (conv2): Conv2d(128, 128, kernel_size=(3, 3), stride=(2, 2), padding=(1, 1), bias=False) (bn2): BatchNorm2d(128, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (conv3): Conv2d(128, 512, kernel_size=(1, 1), stride=(1, 1), bias=False) (bn3): BatchNorm2d(512, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (relu): ReLU(inplace) (downsample): Sequential( (0): Conv2d(256, 512, kernel_size=(1, 1), stride=(2, 2), bias=False) (1): BatchNorm2d(512, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) ) ) (1): Bottleneck( (conv1): Conv2d(512, 128, kernel_size=(1, 1), stride=(1, 1), bias=False) (bn1): BatchNorm2d(128, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (conv2): Conv2d(128, 128, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False) (bn2): BatchNorm2d(128, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (conv3): Conv2d(128, 512, kernel_size=(1, 1), stride=(1, 1), bias=False) (bn3): BatchNorm2d(512, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (relu): ReLU(inplace) ) (2): Bottleneck( (conv1): Conv2d(512, 128, kernel_size=(1, 1), stride=(1, 1), bias=False) (bn1): BatchNorm2d(128, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (conv2): Conv2d(128, 128, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False) (bn2): BatchNorm2d(128, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (conv3): Conv2d(128, 512, kernel_size=(1, 1), stride=(1, 1), bias=False) (bn3): BatchNorm2d(512, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (relu): ReLU(inplace) ) (3): Bottleneck( (conv1): Conv2d(512, 128, kernel_size=(1, 1), stride=(1, 1), bias=False) (bn1): BatchNorm2d(128, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (conv2): Conv2d(128, 128, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False) (bn2): BatchNorm2d(128, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (conv3): Conv2d(128, 512, kernel_size=(1, 1), stride=(1, 1), bias=False) (bn3): BatchNorm2d(512, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (relu): ReLU(inplace) ) ) (layer3): Sequential( (0): Bottleneck( (conv1): Conv2d(512, 256, kernel_size=(1, 1), stride=(1, 1), bias=False) (bn1): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (conv2): Conv2d(256, 256, kernel_size=(3, 3), stride=(2, 2), padding=(1, 1), bias=False) (bn2): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (conv3): Conv2d(256, 1024, kernel_size=(1, 1), stride=(1, 1), bias=False) (bn3): BatchNorm2d(1024, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (relu): ReLU(inplace) (downsample): Sequential( (0): Conv2d(512, 1024, kernel_size=(1, 1), stride=(2, 2), bias=False) (1): BatchNorm2d(1024, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) ) ) (1): Bottleneck( (conv1): Conv2d(1024, 256, kernel_size=(1, 1), stride=(1, 1), bias=False) (bn1): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (conv2): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False) (bn2): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (conv3): Conv2d(256, 1024, kernel_size=(1, 1), stride=(1, 1), bias=False) (bn3): BatchNorm2d(1024, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (relu): ReLU(inplace) ) (2): Bottleneck( (conv1): Conv2d(1024, 256, kernel_size=(1, 1), stride=(1, 1), bias=False) (bn1): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (conv2): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False) (bn2): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (conv3): Conv2d(256, 1024, kernel_size=(1, 1), stride=(1, 1), bias=False) (bn3): BatchNorm2d(1024, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (relu): ReLU(inplace) ) (3): Bottleneck( (conv1): Conv2d(1024, 256, kernel_size=(1, 1), stride=(1, 1), bias=False) (bn1): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (conv2): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False) (bn2): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (conv3): Conv2d(256, 1024, kernel_size=(1, 1), stride=(1, 1), bias=False) (bn3): BatchNorm2d(1024, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (relu): ReLU(inplace) ) (4): Bottleneck( (conv1): Conv2d(1024, 256, kernel_size=(1, 1), stride=(1, 1), bias=False) (bn1): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (conv2): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False) (bn2): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (conv3): Conv2d(256, 1024, kernel_size=(1, 1), stride=(1, 1), bias=False) (bn3): BatchNorm2d(1024, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (relu): ReLU(inplace) ) (5): Bottleneck( (conv1): Conv2d(1024, 256, kernel_size=(1, 1), stride=(1, 1), bias=False) (bn1): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (conv2): Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False) (bn2): BatchNorm2d(256, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (conv3): Conv2d(256, 1024, kernel_size=(1, 1), stride=(1, 1), bias=False) (bn3): BatchNorm2d(1024, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (relu): ReLU(inplace) ) ) (layer4): Sequential( (0): Bottleneck( (conv1): Conv2d(1024, 512, kernel_size=(1, 1), stride=(1, 1), bias=False) (bn1): BatchNorm2d(512, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (conv2): Conv2d(512, 512, kernel_size=(3, 3), stride=(2, 2), padding=(1, 1), bias=False) (bn2): BatchNorm2d(512, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (conv3): Conv2d(512, 2048, kernel_size=(1, 1), stride=(1, 1), bias=False) (bn3): BatchNorm2d(2048, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (relu): ReLU(inplace) (downsample): Sequential( (0): Conv2d(1024, 2048, kernel_size=(1, 1), stride=(2, 2), bias=False) (1): BatchNorm2d(2048, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) ) ) (1): Bottleneck( (conv1): Conv2d(2048, 512, kernel_size=(1, 1), stride=(1, 1), bias=False) (bn1): BatchNorm2d(512, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (conv2): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False) (bn2): BatchNorm2d(512, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (conv3): Conv2d(512, 2048, kernel_size=(1, 1), stride=(1, 1), bias=False) (bn3): BatchNorm2d(2048, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (relu): ReLU(inplace) ) (2): Bottleneck( (conv1): Conv2d(2048, 512, kernel_size=(1, 1), stride=(1, 1), bias=False) (bn1): BatchNorm2d(512, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (conv2): Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1), bias=False) (bn2): BatchNorm2d(512, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (conv3): Conv2d(512, 2048, kernel_size=(1, 1), stride=(1, 1), bias=False) (bn3): BatchNorm2d(2048, eps=1e-05, momentum=0.1, affine=True, track_running_stats=True) (relu): ReLU(inplace) ) ) (avgpool): AvgPool2d(kernel_size=7, stride=1, padding=0) (fc): Linear(in_features=2048, out_features=1000, bias=True))print(model_conv.fc) Linear(in_features=2048, out_features=1000, bias=True)" }, { "code": null, "e": 15297, "s": 14981, "text": "So what we have to adjust the last layer (FC). The last layer is a linear layer, that has 2048 input neurons and having 1000 output neurons. This is useful if you have 1000 different classes. However, we only have to deal with 7 different classes — the 7 different tumor types — so we need to change the last layer." }, { "code": null, "e": 15449, "s": 15297, "text": "num_ftrs = model_conv.fc.in_featuresmodel_conv.fc = torch.nn.Linear(num_ftrs, 7)print(model_conv.fc)Linear(in_features=2048, out_features=7, bias=True)" }, { "code": null, "e": 15572, "s": 15449, "text": "So now after it’s adjusted we need to move the model to the GPU because that’s where the model will be trained in the end." }, { "code": null, "e": 15600, "s": 15572, "text": "Training and validation set" }, { "code": null, "e": 15959, "s": 15600, "text": "from sklearn.model_selection import train_test_splittrain_df, test_df = train_test_split(tile_df, test_size=0.1)# We can split the test set again in a validation set and a true test set:validation_df, test_df = train_test_split(test_df, test_size=0.5)train_df = train_df.reset_index()validation_df = validation_df.reset_index()test_df = test_df.reset_index()" }, { "code": null, "e": 15984, "s": 15959, "text": "Create a Class ‘Dataset’" }, { "code": null, "e": 16097, "s": 15984, "text": "The dataset class will allow us to easily load and transform batches of data in the background on multiple CPUs." }, { "code": null, "e": 16793, "s": 16097, "text": "class Dataset(data.Dataset): 'Characterizes a dataset for PyTorch' def __init__(self, df, transform=None): 'Initialization' self.df = df self.transform = transform def __len__(self): 'Denotes the total number of samples' return len(self.df) def __getitem__(self, index): 'Generates one sample of data' # Load data and get label X = Image.open(self.df['path'][index]) y = torch.tensor(int(self.df['cell_type_idx'][index])) if self.transform: X = self.transform(X) return X, y# Define the parameters for the dataloaderparams = {'batch_size': 4, 'shuffle': True, 'num_workers': 6}" }, { "code": null, "e": 16924, "s": 16793, "text": "Another nice thing about using the dataset class is that we can easily perform preprocessing of the data and/or data augmentation." }, { "code": null, "e": 17371, "s": 16924, "text": "In this example, we only perform mirroring (RandomHorizontalFlip, RandomVerticalFlip), Crop the image to the image center, where the melanoma is most often located (CenterCrop), randomly crop from the center of the image (RandomCrop) and normalize the image according to what the pre-trained model needs (Normalize). We then transform the image to a tensor using, which is required to use it for learning with PyTorch, with the function ToTensor:" }, { "code": null, "e": 18038, "s": 17371, "text": "define the transformation of the images.import torchvision.transforms as trfcomposed = trf.Compose([trf.RandomHorizontalFlip(), trf.RandomVerticalFlip(), trf.CenterCrop(256), trf.RandomCrop(224), trf.ToTensor(), trf.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])])# Define the trainingsset using the table train_df and using our defined transitions (composed)training_set = Dataset(train_df, transform=composed)training_generator = data.DataLoader(training_set, **params)# Same for the validation set:validation_set = Dataset(validation_df, transform=composed)validation_generator = data.DataLoader(validation_set, **params)" }, { "code": null, "e": 18167, "s": 18038, "text": "Now we have to define the optimizer we want to use. In this case, it will be an Adam optimizer with a learning rate of 1e−61e−6." }, { "code": null, "e": 18294, "s": 18167, "text": "The loss function that we will use is CrossEntropyLoss. This is the typical one chosen for multiclass classification problems." }, { "code": null, "e": 18391, "s": 18294, "text": "optimizer = torch.optim.Adam(model.parameters(), lr=1e-6)criterion = torch.nn.CrossEntropyLoss()" }, { "code": null, "e": 18605, "s": 18391, "text": "We now have a data loader for the data in the training set, a data loader for the data in the validation set and we have the optimizer and the criterion defined. We can now start on training and testing the model." }, { "code": null, "e": 18873, "s": 18605, "text": "Training and testing the model is the main part of machine learning and in my opinion the best. This is where the real stuff happens. All through the data preparation and data collection stuff are important this is the fun part and it is also super important as well." }, { "code": null, "e": 18914, "s": 18873, "text": "To train the model just input this code:" }, { "code": null, "e": 20423, "s": 18914, "text": "max_epochs = 20trainings_error = []validation_error = []for epoch in range(max_epochs): print('epoch:', epoch) count_train = 0 trainings_error_tmp = [] model.train() for data_sample, y in training_generator: data_gpu = data_sample.to(device) y_gpu = y.to(device) output = model(data_gpu) err = criterion(output, y_gpu) err.backward() optimizer.step() trainings_error_tmp.append(err.item()) count_train += 1 if count_train >= 100: count_train = 0 mean_trainings_error = np.mean(trainings_error_tmp) trainings_error.append(mean_trainings_error) print('trainings error:', mean_trainings_error) break with torch.set_grad_enabled(False): validation_error_tmp = [] count_val = 0 model.eval() for data_sample, y in validation_generator: data_gpu = data_sample.to(device) y_gpu = y.to(device) output = model(data_gpu) err = criterion(output, y_gpu) validation_error_tmp.append(err.item()) count_val += 1 if count_val >= 10: count_val = 0 mean_val_error = np.mean(validation_error_tmp) validation_error.append(mean_val_error) print('validation error:', mean_val_error) breakplt.plot(trainings_error, label = 'training error')plt.plot(validation_error, label = 'validation error')plt.legend()plt.show()" }, { "code": null, "e": 20442, "s": 20423, "text": "Testing the model:" }, { "code": null, "e": 20500, "s": 20442, "text": "To test the actual ability of the model import this code:" }, { "code": null, "e": 21080, "s": 20500, "text": "model.eval()test_set = Dataset(validation_df, transform=composed)test_generator = data.SequentialSampler(validation_set)result_array = []gt_array = []for i in test_generator: data_sample, y = validation_set.__getitem__(i) data_gpu = data_sample.unsqueeze(0).to(device) output = model(data_gpu) result = torch.argmax(output) result_array.append(result.item()) gt_array.append(y.item())correct_results = np.array(result_array)==np.array(gt_array)sum_correct = np.sum(correct_results)accuracy = sum_correct/test_generator.__len__()print(accuracy)0.8403193612774451" }, { "code": null, "e": 21252, "s": 21080, "text": "So now you can see our accuracy is pretty high but it isn’t perfect. The model isn't going to be 100% perfect yet either but it's definitely close and will get there soon." }, { "code": null, "e": 21522, "s": 21252, "text": "Now with this people don’t have to go into the doctor every time they get some symptoms of skin cancer and test just test it themselves with the comfort of their own home. And now people won’t be dying from skin cancer just because they didn’t want to go to the doctor." } ]