title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
Memcached - CAS Command
CAS stands for Check-And-Set or Compare-And-Swap. Memcached CAS command is used to set the data if it is not updated since last fetch. If the key does not exist in Memcached, then it returns NOT_FOUND. The basic syntax of Memcached CAS command is as shown below − set key flags exptime bytes unique_cas_key [noreply] value The keywords in the syntax are as described below− key − It is the name of the key by which data is stored and retrieved from Memcached. key − It is the name of the key by which data is stored and retrieved from Memcached. flags − It is the 32-bit unsigned integer that the server stores with the data provided by the user, and returns along with the data when the item is retrieved. flags − It is the 32-bit unsigned integer that the server stores with the data provided by the user, and returns along with the data when the item is retrieved. exptime − It is the expiration time in seconds. 0 means no delay. If exptime is more than 30 days, Memcached uses it as a UNIX timestamp for expiration. exptime − It is the expiration time in seconds. 0 means no delay. If exptime is more than 30 days, Memcached uses it as a UNIX timestamp for expiration. bytes − It is the number of bytes in the data block that needs to be stored. This is the length of the data that needs to be stored in Memcached. bytes − It is the number of bytes in the data block that needs to be stored. This is the length of the data that needs to be stored in Memcached. unique_cas_key − It is the unique key get from gets command. unique_cas_key − It is the unique key get from gets command. noreply (optional) − It is a parameter that informs the server not to send any reply. noreply (optional) − It is a parameter that informs the server not to send any reply. value − It is the data that needs to be stored. Data needs to be passed on new line after executing the command with the above options. value − It is the data that needs to be stored. Data needs to be passed on new line after executing the command with the above options. The output of the command is as shown below − STORED STORED indicates success. STORED indicates success. ERROR indicates error while saving data or wrong syntax. ERROR indicates error while saving data or wrong syntax. EXISTS indicates that someone has modified the CAS data since last fetch. EXISTS indicates that someone has modified the CAS data since last fetch. NOT_FOUND indicates that the key does not exist in the Memcached server. NOT_FOUND indicates that the key does not exist in the Memcached server. To execute a CAS command in Memcached, you need to get a CAS token from the Memcached gets command. cas tp 0 900 9 ERROR cas tp 0 900 9 2 memcached set tp 0 900 9 memcached STORED gets tp VALUE tp 0 9 1 memcached END cas tp 0 900 5 2 redis EXISTS cas tp 0 900 5 1 redis STORED get tp VALUE tp 0 5 redis END To get CAS data from a Memcached server, you need to use Memcached gets method. import net.spy.memcached.MemcachedClient; public class MemcachedJava { public static void main(String[] args) { // Connecting to Memcached server on localhost MemcachedClient mcc = new MemcachedClient(new InetSocketAddress("127.0.0.1", 11211)); System.out.println("Connection to server successful"); System.out.println("set status:"+mcc.set("tutorialspoint", 900, "memcached").isDone()); // Get cas token from cache long castToken = mcc.gets("tutorialspoint").cas; System.out.println("Cas token:"+castToken); // now set new data in memcached server System.out.println("Now set new data:"+mcc.cas("tutorialspoint", castToken, 900, "redis")); System.out.println("Get from Cache:"+mcc.get("tutorialspoint")); } } On compiling and executing the program, you get to see the following output − Connection to server successful set status:true Cas token:3 Now set new data:OK Get from Cache:redis Print Add Notes Bookmark this page
[ { "code": null, "e": 2307, "s": 2105, "text": "CAS stands for Check-And-Set or Compare-And-Swap. Memcached CAS command is used to set the data if it is not updated since last fetch. If the key does not exist in Memcached, then it returns NOT_FOUND." }, { "code": null, "e": 2369, "s": 2307, "text": "The basic syntax of Memcached CAS command is as shown below −" }, { "code": null, "e": 2429, "s": 2369, "text": "set key flags exptime bytes unique_cas_key [noreply]\nvalue\n" }, { "code": null, "e": 2480, "s": 2429, "text": "The keywords in the syntax are as described below−" }, { "code": null, "e": 2566, "s": 2480, "text": "key − It is the name of the key by which data is stored and retrieved from Memcached." }, { "code": null, "e": 2652, "s": 2566, "text": "key − It is the name of the key by which data is stored and retrieved from Memcached." }, { "code": null, "e": 2813, "s": 2652, "text": "flags − It is the 32-bit unsigned integer that the server stores with the data provided by the user, and returns along with the data when the item is retrieved." }, { "code": null, "e": 2974, "s": 2813, "text": "flags − It is the 32-bit unsigned integer that the server stores with the data provided by the user, and returns along with the data when the item is retrieved." }, { "code": null, "e": 3127, "s": 2974, "text": "exptime − It is the expiration time in seconds. 0 means no delay. If exptime is more than 30 days, Memcached uses it as a UNIX timestamp for expiration." }, { "code": null, "e": 3280, "s": 3127, "text": "exptime − It is the expiration time in seconds. 0 means no delay. If exptime is more than 30 days, Memcached uses it as a UNIX timestamp for expiration." }, { "code": null, "e": 3426, "s": 3280, "text": "bytes − It is the number of bytes in the data block that needs to be stored. This is the length of the data that needs to be stored in Memcached." }, { "code": null, "e": 3572, "s": 3426, "text": "bytes − It is the number of bytes in the data block that needs to be stored. This is the length of the data that needs to be stored in Memcached." }, { "code": null, "e": 3633, "s": 3572, "text": "unique_cas_key − It is the unique key get from gets command." }, { "code": null, "e": 3694, "s": 3633, "text": "unique_cas_key − It is the unique key get from gets command." }, { "code": null, "e": 3780, "s": 3694, "text": "noreply (optional) − It is a parameter that informs the server not to send any\nreply." }, { "code": null, "e": 3866, "s": 3780, "text": "noreply (optional) − It is a parameter that informs the server not to send any\nreply." }, { "code": null, "e": 4002, "s": 3866, "text": "value − It is the data that needs to be stored. Data needs to be passed on new line after executing the command with the above options." }, { "code": null, "e": 4138, "s": 4002, "text": "value − It is the data that needs to be stored. Data needs to be passed on new line after executing the command with the above options." }, { "code": null, "e": 4184, "s": 4138, "text": "The output of the command is as shown below −" }, { "code": null, "e": 4192, "s": 4184, "text": "STORED\n" }, { "code": null, "e": 4218, "s": 4192, "text": "STORED indicates success." }, { "code": null, "e": 4244, "s": 4218, "text": "STORED indicates success." }, { "code": null, "e": 4302, "s": 4244, "text": "ERROR indicates error while saving data or wrong syntax." }, { "code": null, "e": 4360, "s": 4302, "text": "ERROR indicates error while saving data or wrong syntax." }, { "code": null, "e": 4434, "s": 4360, "text": "EXISTS indicates that someone has modified the CAS data since last fetch." }, { "code": null, "e": 4508, "s": 4434, "text": "EXISTS indicates that someone has modified the CAS data since last fetch." }, { "code": null, "e": 4581, "s": 4508, "text": "NOT_FOUND indicates that the key does not exist in the Memcached server." }, { "code": null, "e": 4654, "s": 4581, "text": "NOT_FOUND indicates that the key does not exist in the Memcached server." }, { "code": null, "e": 4754, "s": 4654, "text": "To execute a CAS command in Memcached, you need to get a CAS token from the Memcached gets command." }, { "code": null, "e": 4962, "s": 4754, "text": "cas tp 0 900 9\nERROR\ncas tp 0 900 9 2\nmemcached\nset tp 0 900 9\nmemcached\nSTORED\ngets tp\nVALUE tp 0 9 1\nmemcached\nEND\ncas tp 0 900 5 2\nredis\nEXISTS\ncas tp 0 900 5 1\nredis\nSTORED\nget tp\nVALUE tp 0 5\nredis\nEND\n" }, { "code": null, "e": 5042, "s": 4962, "text": "To get CAS data from a Memcached server, you need to use Memcached gets method." }, { "code": null, "e": 5837, "s": 5042, "text": "import net.spy.memcached.MemcachedClient;\npublic class MemcachedJava {\n public static void main(String[] args) {\n \n // Connecting to Memcached server on localhost\n MemcachedClient mcc = new MemcachedClient(new\n InetSocketAddress(\"127.0.0.1\", 11211));\n System.out.println(\"Connection to server successful\");\n System.out.println(\"set status:\"+mcc.set(\"tutorialspoint\", 900, \"memcached\").isDone());\n\n // Get cas token from cache\n long castToken = mcc.gets(\"tutorialspoint\").cas;\n System.out.println(\"Cas token:\"+castToken);\n\n // now set new data in memcached server\n System.out.println(\"Now set new data:\"+mcc.cas(\"tutorialspoint\",\n castToken, 900, \"redis\"));\n System.out.println(\"Get from Cache:\"+mcc.get(\"tutorialspoint\"));\n }\n}" }, { "code": null, "e": 5915, "s": 5837, "text": "On compiling and executing the program, you get to see the following output −" }, { "code": null, "e": 6017, "s": 5915, "text": "Connection to server successful\nset status:true\nCas token:3\nNow set new data:OK\nGet from Cache:redis\n" }, { "code": null, "e": 6024, "s": 6017, "text": " Print" }, { "code": null, "e": 6035, "s": 6024, "text": " Add Notes" } ]
C# program to generate secure random numbers
For secure random numbers, use the RNGCryptoServiceProvider Class. It implements a cryptographic Random Number Generator. Using the same class, we have found some random values using the following − using (RNGCryptoServiceProvider crypto = new RNGCryptoServiceProvider()) { byte[] val = new byte[6]; crypto.GetBytes(val); randomvalue = BitConverter.ToInt32(val, 1); } To generate random secure numbers, you can try to run the following code. Live Demo using System; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; using System.Security.Cryptography; public class Demo { public static void Main(string[] args) { for (int i = 0; i <= 5; i++) { Console.WriteLine(randomFunc()); } } private static double randomFunc() { string n = ""; int randomvalue; double n2; using (RNGCryptoServiceProvider crypto = new RNGCryptoServiceProvider()) { byte[] val = new byte[6]; crypto.GetBytes(val); randomvalue = BitConverter.ToInt32(val, 1); } n += randomvalue.ToString().Substring(1, 1)[0]; n += randomvalue.ToString().Substring(2, 1)[0]; n += randomvalue.ToString().Substring(3, 1)[0]; n += randomvalue.ToString().Substring(4, 1)[0]; n += randomvalue.ToString().Substring(5, 1)[0]; double.TryParse(n, out n2); n2 = n2 / 100000; return n2; } } 0.13559 0.0465 0.18058 0.26494 0.52231 0.78927
[ { "code": null, "e": 1184, "s": 1062, "text": "For secure random numbers, use the RNGCryptoServiceProvider Class. It implements a cryptographic Random Number Generator." }, { "code": null, "e": 1261, "s": 1184, "text": "Using the same class, we have found some random values using the following −" }, { "code": null, "e": 1439, "s": 1261, "text": "using (RNGCryptoServiceProvider crypto = new RNGCryptoServiceProvider()) {\n byte[] val = new byte[6];\n crypto.GetBytes(val);\n randomvalue = BitConverter.ToInt32(val, 1);\n}" }, { "code": null, "e": 1513, "s": 1439, "text": "To generate random secure numbers, you can try to run the following code." }, { "code": null, "e": 1524, "s": 1513, "text": " Live Demo" }, { "code": null, "e": 2482, "s": 1524, "text": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text.RegularExpressions;\nusing System.Security.Cryptography;\npublic class Demo {\n public static void Main(string[] args) {\n for (int i = 0; i <= 5; i++) {\n Console.WriteLine(randomFunc());\n }\n }\n private static double randomFunc() {\n string n = \"\";\n int randomvalue;\n double n2;\n using (RNGCryptoServiceProvider crypto = new RNGCryptoServiceProvider()) {\n byte[] val = new byte[6];\n crypto.GetBytes(val);\n randomvalue = BitConverter.ToInt32(val, 1);\n }\n n += randomvalue.ToString().Substring(1, 1)[0];\n n += randomvalue.ToString().Substring(2, 1)[0];\n n += randomvalue.ToString().Substring(3, 1)[0];\n n += randomvalue.ToString().Substring(4, 1)[0];\n n += randomvalue.ToString().Substring(5, 1)[0];\n double.TryParse(n, out n2);\n n2 = n2 / 100000;\n return n2;\n }\n}" }, { "code": null, "e": 2529, "s": 2482, "text": "0.13559\n0.0465\n0.18058\n0.26494\n0.52231\n0.78927" } ]
Bootstrap 4 | Nav-pills - GeeksforGeeks
24 Dec, 2019 Nav-pills is used for menu purpose in Bootstrap 4 to nav tag-based navigation. To Justify Nav-pills with Bootstrap 4 is possible by following approach.Approach 1:To Justify Nav-pills with Bootstrap 3, nav-justify class is available but in Bootstrap 4 nav-fill or nav-justified classes available in defaultAdd class nav-fill or nav-justified to nav tag or nav element.The difference of nav-fill and nav-justified is class nav-fill gives unequal spatial for Nav Pill item based on its name length. but nav-justified equalize the Nav Pill spatial with one another.Example 1:Below example illustrate how to Justify Nav-pills with Bootstrap 4 using class nav-fill or nav-justified.<!DOCTYPE html><html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"> </script></head> <body> <div class="container"> <center> <h1 style="color:green;padding:13px;">GeeksforGeeeks</h1> <br> <br> <p>Nav Fill Unequal spatial of Nav Pills</p> <br> <nav class="nav nav-pills nav-fill"> <a class="nav-item nav-link active" href="#">Active</a> <a class="nav-item nav-link" href="#">Much longer nav link</a> <a class="nav-item nav-link" href="#">Link</a> <a class="nav-item nav-link disabled" href="#" tabindex="-1" aria-disabled="true">Disabled</a> </nav> <br> <p>Nav Justified -Equal spatial of Nav Pills</p> <br> <nav class="nav nav-pills nav-justified"> <a class="nav-item nav-link active" href="#">Active</a> <a class="nav-item nav-link" href="#"> Much longer nav link</a> <a class="nav-item nav-link" href="#"> Link</a> <a class="nav-item nav-link disabled" href="#" tabindex="-1" aria-disabled="true"> Disabled</a> </nav> </center> </div> <script> $(document).ready(function() { $('nav a').click(function() { $('nav a').removeClass("active"); $(this).addClass("active"); }); }); </script></body> </html>Output:Approach 2:To Justify Nav-pills with Bootstrap 4 using flex that is if the nav is made with flex box.Add class flex-column and flex-sm-row to nav tag or nav element.This flex is somehow similar to nav-fill for its unequal spatial of Nav Pills.Example 2:Below example illustrate how to Justify Nav-pills with Bootstrap 4 using flex.<!DOCTYPE html><html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script></head> <body> <div class="container"> <center> <h1 style="color:green;padding:13px;">GeeksforGeeeks</h1> <br> <br> <p>Using Flex -Unequal spatial of Nav Pills</p> <br> <nav class="nav nav-pills flex-column flex-sm-row"> <a class="flex-sm-fill text-sm-center nav-link active" href="#">Active</a> <a class="flex-sm-fill text-sm-center nav-link" href="#">Longer nav link</a> <a class="flex-sm-fill text-sm-center nav-link" href="#">Link</a> <a class="flex-sm-fill text-sm-center nav-link disabled" href="#" tabindex="-1" aria-disabled="true"> Disabled </a> </nav> </center> </div> <script> $(document).ready(function() { $('nav a').click(function() { $('nav a').removeClass("active"); $(this).addClass("active"); }); }); </script></body> </html>Output:Reference: https://getbootstrap.com/docs/4.0/components/navs/My Personal Notes arrow_drop_upSave Approach 1: To Justify Nav-pills with Bootstrap 3, nav-justify class is available but in Bootstrap 4 nav-fill or nav-justified classes available in default Add class nav-fill or nav-justified to nav tag or nav element. The difference of nav-fill and nav-justified is class nav-fill gives unequal spatial for Nav Pill item based on its name length. but nav-justified equalize the Nav Pill spatial with one another. Example 1:Below example illustrate how to Justify Nav-pills with Bootstrap 4 using class nav-fill or nav-justified. <!DOCTYPE html><html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"> </script></head> <body> <div class="container"> <center> <h1 style="color:green;padding:13px;">GeeksforGeeeks</h1> <br> <br> <p>Nav Fill Unequal spatial of Nav Pills</p> <br> <nav class="nav nav-pills nav-fill"> <a class="nav-item nav-link active" href="#">Active</a> <a class="nav-item nav-link" href="#">Much longer nav link</a> <a class="nav-item nav-link" href="#">Link</a> <a class="nav-item nav-link disabled" href="#" tabindex="-1" aria-disabled="true">Disabled</a> </nav> <br> <p>Nav Justified -Equal spatial of Nav Pills</p> <br> <nav class="nav nav-pills nav-justified"> <a class="nav-item nav-link active" href="#">Active</a> <a class="nav-item nav-link" href="#"> Much longer nav link</a> <a class="nav-item nav-link" href="#"> Link</a> <a class="nav-item nav-link disabled" href="#" tabindex="-1" aria-disabled="true"> Disabled</a> </nav> </center> </div> <script> $(document).ready(function() { $('nav a').click(function() { $('nav a').removeClass("active"); $(this).addClass("active"); }); }); </script></body> </html> Output: Approach 2: To Justify Nav-pills with Bootstrap 4 using flex that is if the nav is made with flex box. Add class flex-column and flex-sm-row to nav tag or nav element. This flex is somehow similar to nav-fill for its unequal spatial of Nav Pills. Example 2:Below example illustrate how to Justify Nav-pills with Bootstrap 4 using flex. <!DOCTYPE html><html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script></head> <body> <div class="container"> <center> <h1 style="color:green;padding:13px;">GeeksforGeeeks</h1> <br> <br> <p>Using Flex -Unequal spatial of Nav Pills</p> <br> <nav class="nav nav-pills flex-column flex-sm-row"> <a class="flex-sm-fill text-sm-center nav-link active" href="#">Active</a> <a class="flex-sm-fill text-sm-center nav-link" href="#">Longer nav link</a> <a class="flex-sm-fill text-sm-center nav-link" href="#">Link</a> <a class="flex-sm-fill text-sm-center nav-link disabled" href="#" tabindex="-1" aria-disabled="true"> Disabled </a> </nav> </center> </div> <script> $(document).ready(function() { $('nav a').click(function() { $('nav a').removeClass("active"); $(this).addClass("active"); }); }); </script></body> </html> Output: Reference: https://getbootstrap.com/docs/4.0/components/navs/ Bootstrap-4 Bootstrap-Misc Picked Bootstrap Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to change navigation bar color in Bootstrap ? Form validation using jQuery How to pass data into a bootstrap modal? How to align navbar items to the right in Bootstrap 4 ? How to Show Images on Click 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 ? How to insert spaces/tabs in text using HTML/CSS? Top 10 Projects For Beginners To Practice HTML and CSS Skills
[ { "code": null, "e": 28440, "s": 28412, "text": "\n24 Dec, 2019" }, { "code": null, "e": 28519, "s": 28440, "text": "Nav-pills is used for menu purpose in Bootstrap 4 to nav tag-based navigation." }, { "code": null, "e": 33376, "s": 28519, "text": "To Justify Nav-pills with Bootstrap 4 is possible by following approach.Approach 1:To Justify Nav-pills with Bootstrap 3, nav-justify class is available but in Bootstrap 4 nav-fill or nav-justified classes available in defaultAdd class nav-fill or nav-justified to nav tag or nav element.The difference of nav-fill and nav-justified is class nav-fill gives unequal spatial for Nav Pill item based on its name length. but nav-justified equalize the Nav Pill spatial with one another.Example 1:Below example illustrate how to Justify Nav-pills with Bootstrap 4 using class nav-fill or nav-justified.<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"utf-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css\"> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js\"> </script></head> <body> <div class=\"container\"> <center> <h1 style=\"color:green;padding:13px;\">GeeksforGeeeks</h1> <br> <br> <p>Nav Fill Unequal spatial of Nav Pills</p> <br> <nav class=\"nav nav-pills nav-fill\"> <a class=\"nav-item nav-link active\" href=\"#\">Active</a> <a class=\"nav-item nav-link\" href=\"#\">Much longer nav link</a> <a class=\"nav-item nav-link\" href=\"#\">Link</a> <a class=\"nav-item nav-link disabled\" href=\"#\" tabindex=\"-1\" aria-disabled=\"true\">Disabled</a> </nav> <br> <p>Nav Justified -Equal spatial of Nav Pills</p> <br> <nav class=\"nav nav-pills nav-justified\"> <a class=\"nav-item nav-link active\" href=\"#\">Active</a> <a class=\"nav-item nav-link\" href=\"#\"> Much longer nav link</a> <a class=\"nav-item nav-link\" href=\"#\"> Link</a> <a class=\"nav-item nav-link disabled\" href=\"#\" tabindex=\"-1\" aria-disabled=\"true\"> Disabled</a> </nav> </center> </div> <script> $(document).ready(function() { $('nav a').click(function() { $('nav a').removeClass(\"active\"); $(this).addClass(\"active\"); }); }); </script></body> </html>Output:Approach 2:To Justify Nav-pills with Bootstrap 4 using flex that is if the nav is made with flex box.Add class flex-column and flex-sm-row to nav tag or nav element.This flex is somehow similar to nav-fill for its unequal spatial of Nav Pills.Example 2:Below example illustrate how to Justify Nav-pills with Bootstrap 4 using flex.<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"utf-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css\"> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js\"></script></head> <body> <div class=\"container\"> <center> <h1 style=\"color:green;padding:13px;\">GeeksforGeeeks</h1> <br> <br> <p>Using Flex -Unequal spatial of Nav Pills</p> <br> <nav class=\"nav nav-pills flex-column flex-sm-row\"> <a class=\"flex-sm-fill text-sm-center nav-link active\" href=\"#\">Active</a> <a class=\"flex-sm-fill text-sm-center nav-link\" href=\"#\">Longer nav link</a> <a class=\"flex-sm-fill text-sm-center nav-link\" href=\"#\">Link</a> <a class=\"flex-sm-fill text-sm-center nav-link disabled\" href=\"#\" tabindex=\"-1\" aria-disabled=\"true\"> Disabled </a> </nav> </center> </div> <script> $(document).ready(function() { $('nav a').click(function() { $('nav a').removeClass(\"active\"); $(this).addClass(\"active\"); }); }); </script></body> </html>Output:Reference: https://getbootstrap.com/docs/4.0/components/navs/My Personal Notes\narrow_drop_upSave" }, { "code": null, "e": 33388, "s": 33376, "text": "Approach 1:" }, { "code": null, "e": 33532, "s": 33388, "text": "To Justify Nav-pills with Bootstrap 3, nav-justify class is available but in Bootstrap 4 nav-fill or nav-justified classes available in default" }, { "code": null, "e": 33595, "s": 33532, "text": "Add class nav-fill or nav-justified to nav tag or nav element." }, { "code": null, "e": 33790, "s": 33595, "text": "The difference of nav-fill and nav-justified is class nav-fill gives unequal spatial for Nav Pill item based on its name length. but nav-justified equalize the Nav Pill spatial with one another." }, { "code": null, "e": 33906, "s": 33790, "text": "Example 1:Below example illustrate how to Justify Nav-pills with Bootstrap 4 using class nav-fill or nav-justified." }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"utf-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css\"> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js\"> </script></head> <body> <div class=\"container\"> <center> <h1 style=\"color:green;padding:13px;\">GeeksforGeeeks</h1> <br> <br> <p>Nav Fill Unequal spatial of Nav Pills</p> <br> <nav class=\"nav nav-pills nav-fill\"> <a class=\"nav-item nav-link active\" href=\"#\">Active</a> <a class=\"nav-item nav-link\" href=\"#\">Much longer nav link</a> <a class=\"nav-item nav-link\" href=\"#\">Link</a> <a class=\"nav-item nav-link disabled\" href=\"#\" tabindex=\"-1\" aria-disabled=\"true\">Disabled</a> </nav> <br> <p>Nav Justified -Equal spatial of Nav Pills</p> <br> <nav class=\"nav nav-pills nav-justified\"> <a class=\"nav-item nav-link active\" href=\"#\">Active</a> <a class=\"nav-item nav-link\" href=\"#\"> Much longer nav link</a> <a class=\"nav-item nav-link\" href=\"#\"> Link</a> <a class=\"nav-item nav-link disabled\" href=\"#\" tabindex=\"-1\" aria-disabled=\"true\"> Disabled</a> </nav> </center> </div> <script> $(document).ready(function() { $('nav a').click(function() { $('nav a').removeClass(\"active\"); $(this).addClass(\"active\"); }); }); </script></body> </html>", "e": 36047, "s": 33906, "text": null }, { "code": null, "e": 36055, "s": 36047, "text": "Output:" }, { "code": null, "e": 36067, "s": 36055, "text": "Approach 2:" }, { "code": null, "e": 36158, "s": 36067, "text": "To Justify Nav-pills with Bootstrap 4 using flex that is if the nav is made with flex box." }, { "code": null, "e": 36223, "s": 36158, "text": "Add class flex-column and flex-sm-row to nav tag or nav element." }, { "code": null, "e": 36302, "s": 36223, "text": "This flex is somehow similar to nav-fill for its unequal spatial of Nav Pills." }, { "code": null, "e": 36391, "s": 36302, "text": "Example 2:Below example illustrate how to Justify Nav-pills with Bootstrap 4 using flex." }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"utf-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"> <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css\"> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js\"></script></head> <body> <div class=\"container\"> <center> <h1 style=\"color:green;padding:13px;\">GeeksforGeeeks</h1> <br> <br> <p>Using Flex -Unequal spatial of Nav Pills</p> <br> <nav class=\"nav nav-pills flex-column flex-sm-row\"> <a class=\"flex-sm-fill text-sm-center nav-link active\" href=\"#\">Active</a> <a class=\"flex-sm-fill text-sm-center nav-link\" href=\"#\">Longer nav link</a> <a class=\"flex-sm-fill text-sm-center nav-link\" href=\"#\">Link</a> <a class=\"flex-sm-fill text-sm-center nav-link disabled\" href=\"#\" tabindex=\"-1\" aria-disabled=\"true\"> Disabled </a> </nav> </center> </div> <script> $(document).ready(function() { $('nav a').click(function() { $('nav a').removeClass(\"active\"); $(this).addClass(\"active\"); }); }); </script></body> </html>", "e": 38070, "s": 36391, "text": null }, { "code": null, "e": 38078, "s": 38070, "text": "Output:" }, { "code": null, "e": 38140, "s": 38078, "text": "Reference: https://getbootstrap.com/docs/4.0/components/navs/" }, { "code": null, "e": 38152, "s": 38140, "text": "Bootstrap-4" }, { "code": null, "e": 38167, "s": 38152, "text": "Bootstrap-Misc" }, { "code": null, "e": 38174, "s": 38167, "text": "Picked" }, { "code": null, "e": 38184, "s": 38174, "text": "Bootstrap" }, { "code": null, "e": 38201, "s": 38184, "text": "Web Technologies" }, { "code": null, "e": 38299, "s": 38201, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 38349, "s": 38299, "text": "How to change navigation bar color in Bootstrap ?" }, { "code": null, "e": 38378, "s": 38349, "text": "Form validation using jQuery" }, { "code": null, "e": 38419, "s": 38378, "text": "How to pass data into a bootstrap modal?" }, { "code": null, "e": 38475, "s": 38419, "text": "How to align navbar items to the right in Bootstrap 4 ?" }, { "code": null, "e": 38516, "s": 38475, "text": "How to Show Images on Click using HTML ?" }, { "code": null, "e": 38558, "s": 38516, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 38591, "s": 38558, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 38634, "s": 38591, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 38684, "s": 38634, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
times() - Unix, Linux System Call
Unix - Home Unix - Getting Started Unix - File Management Unix - Directories Unix - File Permission Unix - Environment Unix - Basic Utilities Unix - Pipes & Filters Unix - Processes Unix - Communication Unix - The vi Editor Unix - What is Shell? Unix - Using Variables Unix - Special Variables Unix - Using Arrays Unix - Basic Operators Unix - Decision Making Unix - Shell Loops Unix - Loop Control Unix - Shell Substitutions Unix - Quoting Mechanisms Unix - IO Redirections Unix - Shell Functions Unix - Manpage Help Unix - Regular Expressions Unix - File System Basics Unix - User Administration Unix - System Performance Unix - System Logging Unix - Signals and Traps Unix - Useful Commands Unix - Quick Guide Unix - Builtin Functions Unix - System Calls Unix - Commands List Unix Useful Resources Computer Glossary Who is Who Copyright © 2014 by tutorialspoint clock_t times(struct tms *buf); struct tms { clock_t tms_utime; /* user time */ clock_t tms_stime; /* system time */ clock_t tms_cutime; /* user time of children */ clock_t tms_cstime; /* system time of children */ }; The tms_utime field contains the CPU time spent executing instructions of the calling process. The tms_stime field contains the CPU time spent in the system while executing tasks on behalf of the calling process. The tms_cutime field contains the sum of the tms_utime and tms_cutime values for all waited-for terminated children. The tms_cstime field contains the sum of the tms_stime and tms_cstime values for all waited-for terminated children. Times for terminated children (and their descendants) is added in at the moment wait(2) or waitpid(2) returns their process ID. In particular, times of grandchildren that the children did not wait for are never seen. All times reported are in clock ticks. In Linux kernel versions before 2.6.9, if the disposition of SIGCHLD is set to SIG_IGN then the times of terminated children are automatically included in the tms_cstime and tms_cutime fields, although POSIX.1-2001 says that this should only happen if the calling process wait()s on its children. This non-conformance is rectified in Linux 2.6.9 and later. On Linux, the buf argument can be specified as NULL, with the result that times() just returns a function result. However, POSIX does not specify this behaviour, and most other Unix implementations require a non-NULL value for buf. Note that clock(3) returns values of type clock_t that are not measured in clock ticks but in CLOCKS_PER_SEC. On older systems the number of clock ticks per second is given by the variable HZ. time (1) time (1) getrusage (2) getrusage (2) wait (2) wait (2) Advertisements 129 Lectures 23 hours Eduonix Learning Solutions 5 Lectures 4.5 hours Frahaan Hussain 35 Lectures 2 hours Pradeep D 41 Lectures 2.5 hours Musab Zayadneh 46 Lectures 4 hours GUHARAJANM 6 Lectures 4 hours Uplatz Print Add Notes Bookmark this page
[ { "code": null, "e": 1466, "s": 1454, "text": "Unix - Home" }, { "code": null, "e": 1489, "s": 1466, "text": "Unix - Getting Started" }, { "code": null, "e": 1512, "s": 1489, "text": "Unix - File Management" }, { "code": null, "e": 1531, "s": 1512, "text": "Unix - Directories" }, { "code": null, "e": 1554, "s": 1531, "text": "Unix - File Permission" }, { "code": null, "e": 1573, "s": 1554, "text": "Unix - Environment" }, { "code": null, "e": 1596, "s": 1573, "text": "Unix - Basic Utilities" }, { "code": null, "e": 1619, "s": 1596, "text": "Unix - Pipes & Filters" }, { "code": null, "e": 1636, "s": 1619, "text": "Unix - Processes" }, { "code": null, "e": 1657, "s": 1636, "text": "Unix - Communication" }, { "code": null, "e": 1678, "s": 1657, "text": "Unix - The vi Editor" }, { "code": null, "e": 1700, "s": 1678, "text": "Unix - What is Shell?" }, { "code": null, "e": 1723, "s": 1700, "text": "Unix - Using Variables" }, { "code": null, "e": 1748, "s": 1723, "text": "Unix - Special Variables" }, { "code": null, "e": 1768, "s": 1748, "text": "Unix - Using Arrays" }, { "code": null, "e": 1791, "s": 1768, "text": "Unix - Basic Operators" }, { "code": null, "e": 1814, "s": 1791, "text": "Unix - Decision Making" }, { "code": null, "e": 1833, "s": 1814, "text": "Unix - Shell Loops" }, { "code": null, "e": 1853, "s": 1833, "text": "Unix - Loop Control" }, { "code": null, "e": 1880, "s": 1853, "text": "Unix - Shell Substitutions" }, { "code": null, "e": 1906, "s": 1880, "text": "Unix - Quoting Mechanisms" }, { "code": null, "e": 1929, "s": 1906, "text": "Unix - IO Redirections" }, { "code": null, "e": 1952, "s": 1929, "text": "Unix - Shell Functions" }, { "code": null, "e": 1972, "s": 1952, "text": "Unix - Manpage Help" }, { "code": null, "e": 1999, "s": 1972, "text": "Unix - Regular Expressions" }, { "code": null, "e": 2025, "s": 1999, "text": "Unix - File System Basics" }, { "code": null, "e": 2052, "s": 2025, "text": "Unix - User Administration" }, { "code": null, "e": 2078, "s": 2052, "text": "Unix - System Performance" }, { "code": null, "e": 2100, "s": 2078, "text": "Unix - System Logging" }, { "code": null, "e": 2125, "s": 2100, "text": "Unix - Signals and Traps" }, { "code": null, "e": 2148, "s": 2125, "text": "Unix - Useful Commands" }, { "code": null, "e": 2167, "s": 2148, "text": "Unix - Quick Guide" }, { "code": null, "e": 2192, "s": 2167, "text": "Unix - Builtin Functions" }, { "code": null, "e": 2212, "s": 2192, "text": "Unix - System Calls" }, { "code": null, "e": 2233, "s": 2212, "text": "Unix - Commands List" }, { "code": null, "e": 2255, "s": 2233, "text": "Unix Useful Resources" }, { "code": null, "e": 2273, "s": 2255, "text": "Computer Glossary" }, { "code": null, "e": 2284, "s": 2273, "text": "Who is Who" }, { "code": null, "e": 2319, "s": 2284, "text": "Copyright © 2014 by tutorialspoint" }, { "code": null, "e": 2353, "s": 2319, "text": "\nclock_t times(struct tms *buf); " }, { "code": null, "e": 2544, "s": 2355, "text": "struct tms {\nclock_t tms_utime; /* user time */\nclock_t tms_stime; /* system time */\nclock_t tms_cutime; /* user time of children */\nclock_t tms_cstime; /* system time of children */\n};\n" }, { "code": null, "e": 2993, "s": 2544, "text": "\nThe\ntms_utime field contains the CPU time spent executing instructions\nof the calling process.\nThe\ntms_stime field contains the CPU time spent in the system while\nexecuting tasks on behalf of the calling process.\nThe\ntms_cutime field contains the sum of the\ntms_utime and\ntms_cutime values for all waited-for terminated children.\nThe\ntms_cstime field contains the sum of the\ntms_stime and\ntms_cstime values for all waited-for terminated children.\n" }, { "code": null, "e": 3212, "s": 2993, "text": "\nTimes for terminated children (and their descendants)\nis added in at the moment\nwait(2)\nor\nwaitpid(2)\nreturns their process ID. In particular, times of grandchildren\nthat the children did not wait for are never seen.\n" }, { "code": null, "e": 3253, "s": 3212, "text": "\nAll times reported are in clock ticks.\n" }, { "code": null, "e": 3612, "s": 3253, "text": "\nIn Linux kernel versions before 2.6.9,\nif the disposition of\nSIGCHLD is set to\nSIG_IGN then the times of terminated children\nare automatically included in the\ntms_cstime and\ntms_cutime fields, although POSIX.1-2001 says that this should only happen\nif the calling process\nwait()s on its children.\nThis non-conformance is rectified in Linux 2.6.9 and later.\n" }, { "code": null, "e": 3846, "s": 3612, "text": "\nOn Linux, the\nbuf argument can be specified as NULL, with the result that\ntimes() just returns a function result.\nHowever, POSIX does not specify this behaviour, and most\nother Unix implementations require a non-NULL value for\nbuf. " }, { "code": null, "e": 3958, "s": 3846, "text": "\nNote that\nclock(3)\nreturns values of type\nclock_t that are not measured in clock ticks\nbut in\nCLOCKS_PER_SEC. " }, { "code": null, "e": 4043, "s": 3958, "text": "\nOn older systems the number of clock ticks per second is given\nby the variable HZ.\n" }, { "code": null, "e": 4052, "s": 4043, "text": "time (1)" }, { "code": null, "e": 4061, "s": 4052, "text": "time (1)" }, { "code": null, "e": 4075, "s": 4061, "text": "getrusage (2)" }, { "code": null, "e": 4089, "s": 4075, "text": "getrusage (2)" }, { "code": null, "e": 4098, "s": 4089, "text": "wait (2)" }, { "code": null, "e": 4107, "s": 4098, "text": "wait (2)" }, { "code": null, "e": 4124, "s": 4107, "text": "\nAdvertisements\n" }, { "code": null, "e": 4159, "s": 4124, "text": "\n 129 Lectures \n 23 hours \n" }, { "code": null, "e": 4187, "s": 4159, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 4221, "s": 4187, "text": "\n 5 Lectures \n 4.5 hours \n" }, { "code": null, "e": 4238, "s": 4221, "text": " Frahaan Hussain" }, { "code": null, "e": 4271, "s": 4238, "text": "\n 35 Lectures \n 2 hours \n" }, { "code": null, "e": 4282, "s": 4271, "text": " Pradeep D" }, { "code": null, "e": 4317, "s": 4282, "text": "\n 41 Lectures \n 2.5 hours \n" }, { "code": null, "e": 4333, "s": 4317, "text": " Musab Zayadneh" }, { "code": null, "e": 4366, "s": 4333, "text": "\n 46 Lectures \n 4 hours \n" }, { "code": null, "e": 4378, "s": 4366, "text": " GUHARAJANM" }, { "code": null, "e": 4410, "s": 4378, "text": "\n 6 Lectures \n 4 hours \n" }, { "code": null, "e": 4418, "s": 4410, "text": " Uplatz" }, { "code": null, "e": 4425, "s": 4418, "text": " Print" }, { "code": null, "e": 4436, "s": 4425, "text": " Add Notes" } ]
Select Columns that Satisfy a Condition in PySpark
29 Jun, 2021 In this article, we are going to select columns in the dataframe based on the condition using the where() function in Pyspark. Let’s create a sample dataframe with employee data. Python3 # importing moduleimport pyspark # importing sparksession from pyspark.sql modulefrom pyspark.sql import SparkSession # creating sparksession and giving an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate() # list of employee datadata = [[1, "sravan", "company 1"], [2, "ojaswi", "company 1"], [3, "rohith", "company 2"], [4, "sridevi", "company 1"], [1, "sravan", "company 1"], [4, "sridevi", "company 1"]] # specify column namescolumns = ['ID', 'NAME', 'Company'] # creating a dataframe from the lists of datadataframe = spark.createDataFrame(data, columns) # display dataframedataframe.show() Output: This method is used to return the dataframe based on the given condition. It can take a condition and returns the dataframe Syntax: where(dataframe.column condition) Here dataframe is the input dataframeThe column is the column name where we have to raise a condition Here dataframe is the input dataframe The column is the column name where we have to raise a condition After applying the where clause, we will select the data from the dataframe Syntax: dataframe.select('column_name').where(dataframe.column condition) Here dataframe is the input dataframeThe column is the column name where we have to raise a condition Here dataframe is the input dataframe The column is the column name where we have to raise a condition Example 1: Python program to return ID based on condition Python3 # importing moduleimport pyspark # importing sparksession from pyspark.sql modulefrom pyspark.sql import SparkSession # creating sparksession and giving an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate() # list of employee datadata = [[1, "sravan", "company 1"], [2, "ojaswi", "company 1"], [3, "rohith", "company 2"], [4, "sridevi", "company 1"], [1, "sravan", "company 1"], [4, "sridevi", "company 1"]] # specify column namescolumns = ['ID', 'NAME', 'Company'] # creating a dataframe from the lists of datadataframe = spark.createDataFrame(data, columns) # select ID where ID less than 3dataframe.select('ID').where(dataframe.ID < 3).show() Output: Example 2: Python program to select ID and name where ID =4. Python3 # importing moduleimport pyspark # importing sparksession from pyspark.sql modulefrom pyspark.sql import SparkSession # creating sparksession and giving an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate() # list of employee datadata = [[1, "sravan", "company 1"], [2, "ojaswi", "company 1"], [3, "rohith", "company 2"], [4, "sridevi", "company 1"], [1, "sravan", "company 1"], [4, "sridevi", "company 1"]] # specify column namescolumns = ['ID', 'NAME', 'Company'] # creating a dataframe from the lists of datadataframe = spark.createDataFrame(data, columns) # select ID and name where ID =4dataframe.select(['ID', 'NAME']).where(dataframe.ID == 4).show() Output: Example 3: Python program to select all column based on condition Python3 # importing moduleimport pyspark # importing sparksession from pyspark.sql modulefrom pyspark.sql import SparkSession # creating sparksession and giving an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate() # list of employee datadata = [[1, "sravan", "company 1"], [2, "ojaswi", "company 1"], [3, "rohith", "company 2"], [4, "sridevi", "company 1"], [1, "sravan", "company 1"], [4, "sridevi", "company 1"]] # specify column namescolumns = ['ID', 'NAME', 'Company'] # creating a dataframe from the lists of datadataframe = spark.createDataFrame(data, columns) # select all columns e where name = sridevidataframe.select(['ID', 'NAME', 'Company']).where( dataframe.NAME == 'sridevi').show() Output: Picked Python-Pyspark 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 Jun, 2021" }, { "code": null, "e": 156, "s": 28, "text": "In this article, we are going to select columns in the dataframe based on the condition using the where() function in Pyspark. " }, { "code": null, "e": 208, "s": 156, "text": "Let’s create a sample dataframe with employee data." }, { "code": null, "e": 216, "s": 208, "text": "Python3" }, { "code": "# importing moduleimport pyspark # importing sparksession from pyspark.sql modulefrom pyspark.sql import SparkSession # creating sparksession and giving an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate() # list of employee datadata = [[1, \"sravan\", \"company 1\"], [2, \"ojaswi\", \"company 1\"], [3, \"rohith\", \"company 2\"], [4, \"sridevi\", \"company 1\"], [1, \"sravan\", \"company 1\"], [4, \"sridevi\", \"company 1\"]] # specify column namescolumns = ['ID', 'NAME', 'Company'] # creating a dataframe from the lists of datadataframe = spark.createDataFrame(data, columns) # display dataframedataframe.show()", "e": 853, "s": 216, "text": null }, { "code": null, "e": 861, "s": 853, "text": "Output:" }, { "code": null, "e": 985, "s": 861, "text": "This method is used to return the dataframe based on the given condition. It can take a condition and returns the dataframe" }, { "code": null, "e": 993, "s": 985, "text": "Syntax:" }, { "code": null, "e": 1027, "s": 993, "text": "where(dataframe.column condition)" }, { "code": null, "e": 1130, "s": 1027, "text": "Here dataframe is the input dataframeThe column is the column name where we have to raise a condition" }, { "code": null, "e": 1168, "s": 1130, "text": "Here dataframe is the input dataframe" }, { "code": null, "e": 1234, "s": 1168, "text": "The column is the column name where we have to raise a condition" }, { "code": null, "e": 1310, "s": 1234, "text": "After applying the where clause, we will select the data from the dataframe" }, { "code": null, "e": 1318, "s": 1310, "text": "Syntax:" }, { "code": null, "e": 1384, "s": 1318, "text": "dataframe.select('column_name').where(dataframe.column condition)" }, { "code": null, "e": 1486, "s": 1384, "text": "Here dataframe is the input dataframeThe column is the column name where we have to raise a condition" }, { "code": null, "e": 1524, "s": 1486, "text": "Here dataframe is the input dataframe" }, { "code": null, "e": 1589, "s": 1524, "text": "The column is the column name where we have to raise a condition" }, { "code": null, "e": 1647, "s": 1589, "text": "Example 1: Python program to return ID based on condition" }, { "code": null, "e": 1655, "s": 1647, "text": "Python3" }, { "code": "# importing moduleimport pyspark # importing sparksession from pyspark.sql modulefrom pyspark.sql import SparkSession # creating sparksession and giving an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate() # list of employee datadata = [[1, \"sravan\", \"company 1\"], [2, \"ojaswi\", \"company 1\"], [3, \"rohith\", \"company 2\"], [4, \"sridevi\", \"company 1\"], [1, \"sravan\", \"company 1\"], [4, \"sridevi\", \"company 1\"]] # specify column namescolumns = ['ID', 'NAME', 'Company'] # creating a dataframe from the lists of datadataframe = spark.createDataFrame(data, columns) # select ID where ID less than 3dataframe.select('ID').where(dataframe.ID < 3).show()", "e": 2343, "s": 1655, "text": null }, { "code": null, "e": 2351, "s": 2343, "text": "Output:" }, { "code": null, "e": 2413, "s": 2351, "text": "Example 2: Python program to select ID and name where ID =4." }, { "code": null, "e": 2421, "s": 2413, "text": "Python3" }, { "code": "# importing moduleimport pyspark # importing sparksession from pyspark.sql modulefrom pyspark.sql import SparkSession # creating sparksession and giving an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate() # list of employee datadata = [[1, \"sravan\", \"company 1\"], [2, \"ojaswi\", \"company 1\"], [3, \"rohith\", \"company 2\"], [4, \"sridevi\", \"company 1\"], [1, \"sravan\", \"company 1\"], [4, \"sridevi\", \"company 1\"]] # specify column namescolumns = ['ID', 'NAME', 'Company'] # creating a dataframe from the lists of datadataframe = spark.createDataFrame(data, columns) # select ID and name where ID =4dataframe.select(['ID', 'NAME']).where(dataframe.ID == 4).show()", "e": 3120, "s": 2421, "text": null }, { "code": null, "e": 3128, "s": 3120, "text": "Output:" }, { "code": null, "e": 3194, "s": 3128, "text": "Example 3: Python program to select all column based on condition" }, { "code": null, "e": 3202, "s": 3194, "text": "Python3" }, { "code": "# importing moduleimport pyspark # importing sparksession from pyspark.sql modulefrom pyspark.sql import SparkSession # creating sparksession and giving an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate() # list of employee datadata = [[1, \"sravan\", \"company 1\"], [2, \"ojaswi\", \"company 1\"], [3, \"rohith\", \"company 2\"], [4, \"sridevi\", \"company 1\"], [1, \"sravan\", \"company 1\"], [4, \"sridevi\", \"company 1\"]] # specify column namescolumns = ['ID', 'NAME', 'Company'] # creating a dataframe from the lists of datadataframe = spark.createDataFrame(data, columns) # select all columns e where name = sridevidataframe.select(['ID', 'NAME', 'Company']).where( dataframe.NAME == 'sridevi').show()", "e": 3937, "s": 3202, "text": null }, { "code": null, "e": 3945, "s": 3937, "text": "Output:" }, { "code": null, "e": 3952, "s": 3945, "text": "Picked" }, { "code": null, "e": 3967, "s": 3952, "text": "Python-Pyspark" }, { "code": null, "e": 3974, "s": 3967, "text": "Python" } ]
p5.js | isPlaying() Function
18 Nov, 2021 The isPlaying() function is an inbuilt function of p5.sound library that verifies that the play() function performed successfully, if that play was successful then this function will return true else false. That means it returns a Boolean value.Syntax: isPlaying() Note: All the sound-related functions only work when the sound library is included in the head section of the index.html file.Parameters: This function does not accept any parameter.Return Values: This function return the Boolean value of play true or false, true means audio is playing and false means not.Below examples illustrates the p5.isPlaying() function in JavaScript: Example 1: Before the play() function will calling isPlaying() function. javascript var sound;var ply;function preload() { // Initialize sound sound = loadSound("pfivesound.mp3");} function setup() { //Checking playing or not var ply = sound.isPlaying(); console.log(ply); // Playing the preloaded sound sound.play();} Output: false Example 2: After the play() function will calling isPlaying() function. javascript var sound;var ply;function preload() { // Initialize sound sound = loadSound("pfivesound.mp3");} function setup() { // Playing the preloaded sound sound.play(); //Checking playing or not var ply = sound.isPlaying(); console.log(ply);} Output: true Online editor: https://editor.p5js.org/ Environment Setup: https://www.geeksforgeeks.org/p5-js-soundfile-object-installation-and-methods/Supported Browsers: The browsers supported by p5.isPlaying() function are listed below: Google Chrome Internet Explorer Firefox Safari Opera kashishsoda 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": "\n18 Nov, 2021" }, { "code": null, "e": 282, "s": 28, "text": "The isPlaying() function is an inbuilt function of p5.sound library that verifies that the play() function performed successfully, if that play was successful then this function will return true else false. That means it returns a Boolean value.Syntax: " }, { "code": null, "e": 294, "s": 282, "text": "isPlaying()" }, { "code": null, "e": 745, "s": 294, "text": "Note: All the sound-related functions only work when the sound library is included in the head section of the index.html file.Parameters: This function does not accept any parameter.Return Values: This function return the Boolean value of play true or false, true means audio is playing and false means not.Below examples illustrates the p5.isPlaying() function in JavaScript: Example 1: Before the play() function will calling isPlaying() function. " }, { "code": null, "e": 756, "s": 745, "text": "javascript" }, { "code": "var sound;var ply;function preload() { // Initialize sound sound = loadSound(\"pfivesound.mp3\");} function setup() { //Checking playing or not var ply = sound.isPlaying(); console.log(ply); // Playing the preloaded sound sound.play();}", "e": 1030, "s": 756, "text": null }, { "code": null, "e": 1039, "s": 1030, "text": "Output: " }, { "code": null, "e": 1045, "s": 1039, "text": "false" }, { "code": null, "e": 1119, "s": 1045, "text": "Example 2: After the play() function will calling isPlaying() function. " }, { "code": null, "e": 1130, "s": 1119, "text": "javascript" }, { "code": "var sound;var ply;function preload() { // Initialize sound sound = loadSound(\"pfivesound.mp3\");} function setup() { // Playing the preloaded sound sound.play(); //Checking playing or not var ply = sound.isPlaying(); console.log(ply);}", "e": 1395, "s": 1130, "text": null }, { "code": null, "e": 1404, "s": 1395, "text": "Output: " }, { "code": null, "e": 1409, "s": 1404, "text": "true" }, { "code": null, "e": 1636, "s": 1409, "text": "Online editor: https://editor.p5js.org/ Environment Setup: https://www.geeksforgeeks.org/p5-js-soundfile-object-installation-and-methods/Supported Browsers: The browsers supported by p5.isPlaying() function are listed below: " }, { "code": null, "e": 1650, "s": 1636, "text": "Google Chrome" }, { "code": null, "e": 1668, "s": 1650, "text": "Internet Explorer" }, { "code": null, "e": 1676, "s": 1668, "text": "Firefox" }, { "code": null, "e": 1683, "s": 1676, "text": "Safari" }, { "code": null, "e": 1690, "s": 1683, "text": "Opera " }, { "code": null, "e": 1702, "s": 1690, "text": "kashishsoda" }, { "code": null, "e": 1719, "s": 1702, "text": "JavaScript-p5.js" }, { "code": null, "e": 1730, "s": 1719, "text": "JavaScript" }, { "code": null, "e": 1747, "s": 1730, "text": "Web Technologies" } ]
Explainable AI for Multi-Output Regression | by Cory Randolph | Feb, 2021 | Towards Data Science | Towards Data Science
Opening the “black box” of machine learning models is not only critical in understanding the models we create, but also in communicating to others the information brought to light by the machine learning model. I have seen several projects fail because they could not be explained well to others, which is why understanding the models we build is necessary in order to increase the successful implementation of machine learning projects. Recently I was working on an ML project that required multi-output regression (predicting more than one output/label/target) and had a hard time finding solid examples or resources implementing explainability. Working though the challenges of how to explain multi-output regression models involved a lot of trial and error. Ultimately, I was able to break down my multi-output regression model, and I gained a few “lessons learned” along the way that are worth sharing. The full code walk through can be found on GitHub at SHAP Values for Multi-Output Regression Models and can be run in the browser through Google Colab. Creating the data model for multi-output regression to demonstrate explainability through SHAP. The below code creates data with 1,000 samples to train on, 10 features, and only 7 of them are meaningfully tied with the output/label we are trying to predict. (Later we will see how SHAP values help us see the informative features.) Lastly we have 5 outputs/labels making this a multi-output regression problem. X, y = make_regression(n_samples=1000, n_features=10, n_informative=7, n_targets=5, random_state=0) To create a multi-output regression model, I use a Tensorflow/Keras model since it allows the user to easily set the number of outputs/labels equal to the number of labels they are trying to predict from the data. model = Sequential()model.add(Dense(32, input_dim=10, activation=’relu’))model.add(Dense(5))model.compile(loss=’mae’, optimizer=’adam’)model.fit(X, y, verbose=0, epochs=100) After importing SHAP and choosing the data to generate explanations for, we can now plot explanations for individual outputs/labels. See SHAP Values for Multi-Output Models Notebook for full code. shap.force_plot(base_value = explainer.expected_value[current_label.value],shap_values = shap_value_single[current_label.value], features = X[list_of_labels].iloc[X_idx:X_idx+1,:]) The below plot shows how each feature/input influenced the over all prediction. (Red being higher values and blue being lower values.) Now we have a detailed explanation for an individual prediction from what was otherwise a “blackbox” model. By selecting a different label we can see how the same input features affected each output/label independently (see full code notebook for dynamic drop-downs). As with many ML projects, it is hard to tell which of the inputs/features we used really effected the predictions, but we can again use SHAP and the built-in summary plots to show a model-level summary for each individual output/label. From the data setup earlier, we know that there were 3 features that did not have any influence on the outputs, and we can now easily see that the bottom 3 features (03, 07, and 01) are those features. Break the problem down into a simpler problem by trying to explain a single output/label of a model since there are more resources available. Then work back up to the original problem (this example used a dropdown to dynamically select any of the multiple outputs/labels to explore). Creating a tutorial as a self-contained notebook that can run in the browser and select individual outputs/labels forced me to understand at a level beyond copying and pasting code to get a quick solution. If you are trying to open the black box of a multi-output machine learning model, I hope this demonstrates the value of the SHAP and helps you in explaining your model.
[ { "code": null, "e": 610, "s": 172, "text": "Opening the “black box” of machine learning models is not only critical in understanding the models we create, but also in communicating to others the information brought to light by the machine learning model. I have seen several projects fail because they could not be explained well to others, which is why understanding the models we build is necessary in order to increase the successful implementation of machine learning projects." }, { "code": null, "e": 1080, "s": 610, "text": "Recently I was working on an ML project that required multi-output regression (predicting more than one output/label/target) and had a hard time finding solid examples or resources implementing explainability. Working though the challenges of how to explain multi-output regression models involved a lot of trial and error. Ultimately, I was able to break down my multi-output regression model, and I gained a few “lessons learned” along the way that are worth sharing." }, { "code": null, "e": 1232, "s": 1080, "text": "The full code walk through can be found on GitHub at SHAP Values for Multi-Output Regression Models and can be run in the browser through Google Colab." }, { "code": null, "e": 1328, "s": 1232, "text": "Creating the data model for multi-output regression to demonstrate explainability through SHAP." }, { "code": null, "e": 1643, "s": 1328, "text": "The below code creates data with 1,000 samples to train on, 10 features, and only 7 of them are meaningfully tied with the output/label we are trying to predict. (Later we will see how SHAP values help us see the informative features.) Lastly we have 5 outputs/labels making this a multi-output regression problem." }, { "code": null, "e": 1743, "s": 1643, "text": "X, y = make_regression(n_samples=1000, n_features=10, n_informative=7, n_targets=5, random_state=0)" }, { "code": null, "e": 1957, "s": 1743, "text": "To create a multi-output regression model, I use a Tensorflow/Keras model since it allows the user to easily set the number of outputs/labels equal to the number of labels they are trying to predict from the data." }, { "code": null, "e": 2131, "s": 1957, "text": "model = Sequential()model.add(Dense(32, input_dim=10, activation=’relu’))model.add(Dense(5))model.compile(loss=’mae’, optimizer=’adam’)model.fit(X, y, verbose=0, epochs=100)" }, { "code": null, "e": 2328, "s": 2131, "text": "After importing SHAP and choosing the data to generate explanations for, we can now plot explanations for individual outputs/labels. See SHAP Values for Multi-Output Models Notebook for full code." }, { "code": null, "e": 2509, "s": 2328, "text": "shap.force_plot(base_value = explainer.expected_value[current_label.value],shap_values = shap_value_single[current_label.value], features = X[list_of_labels].iloc[X_idx:X_idx+1,:])" }, { "code": null, "e": 2912, "s": 2509, "text": "The below plot shows how each feature/input influenced the over all prediction. (Red being higher values and blue being lower values.) Now we have a detailed explanation for an individual prediction from what was otherwise a “blackbox” model. By selecting a different label we can see how the same input features affected each output/label independently (see full code notebook for dynamic drop-downs)." }, { "code": null, "e": 3148, "s": 2912, "text": "As with many ML projects, it is hard to tell which of the inputs/features we used really effected the predictions, but we can again use SHAP and the built-in summary plots to show a model-level summary for each individual output/label." }, { "code": null, "e": 3350, "s": 3148, "text": "From the data setup earlier, we know that there were 3 features that did not have any influence on the outputs, and we can now easily see that the bottom 3 features (03, 07, and 01) are those features." }, { "code": null, "e": 3634, "s": 3350, "text": "Break the problem down into a simpler problem by trying to explain a single output/label of a model since there are more resources available. Then work back up to the original problem (this example used a dropdown to dynamically select any of the multiple outputs/labels to explore)." }, { "code": null, "e": 3840, "s": 3634, "text": "Creating a tutorial as a self-contained notebook that can run in the browser and select individual outputs/labels forced me to understand at a level beyond copying and pasting code to get a quick solution." } ]
How to change the owner of a directory using Python?
You can change the owner of a file or a directory using the pwd, grp and os modules. The uid module is used to get the uid from user name, grp to get gid group name string and os to change the owner: import pwd import grp import os uid = pwd.getpwnam("nobody").pw_uid gid = grp.getgrnam("nogroup").gr_gid path = 'my_folder' os.chown(path, uid, gid)
[ { "code": null, "e": 1262, "s": 1062, "text": "You can change the owner of a file or a directory using the pwd, grp and os modules. The uid module is used to get the uid from user name, grp to get gid group name string and os to change the owner:" }, { "code": null, "e": 1411, "s": 1262, "text": "import pwd\nimport grp\nimport os\nuid = pwd.getpwnam(\"nobody\").pw_uid\ngid = grp.getgrnam(\"nogroup\").gr_gid\npath = 'my_folder'\nos.chown(path, uid, gid)" } ]
How to display the count over the bar in Matplotlib histogram?
To display the count over the bar in matplotlib histogram, we can iterate each patch and use text() method to place the values over the patches. Set the figure size and adjust the padding between and around the subplots. Make a list of numbers to make a histogram plot. Use hist() method to make histograms. Iterate the patches and calculate the mid-values of each patch and height of the patch to place a text. To display the figure, use show() method. import matplotlib.pyplot as plt plt.rcParams["figure.figsize"] = [7.50, 3.50] plt.rcParams["figure.autolayout"] = True data = [3, 5, 1, 7, 9, 5, 3, 7, 5] _, _, patches = plt.hist(data, align="mid") for pp in patches: x = (pp._x0 + pp._x1)/2 y = pp._y1 + 0.05 plt.text(x, y, pp._y1) plt.show()
[ { "code": null, "e": 1207, "s": 1062, "text": "To display the count over the bar in matplotlib histogram, we can iterate each patch and use text() method to place the values over the patches." }, { "code": null, "e": 1283, "s": 1207, "text": "Set the figure size and adjust the padding between and around the subplots." }, { "code": null, "e": 1332, "s": 1283, "text": "Make a list of numbers to make a histogram plot." }, { "code": null, "e": 1370, "s": 1332, "text": "Use hist() method to make histograms." }, { "code": null, "e": 1474, "s": 1370, "text": "Iterate the patches and calculate the mid-values of each patch and height of the patch to place a text." }, { "code": null, "e": 1516, "s": 1474, "text": "To display the figure, use show() method." }, { "code": null, "e": 1822, "s": 1516, "text": "import matplotlib.pyplot as plt\n\nplt.rcParams[\"figure.figsize\"] = [7.50, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\n\ndata = [3, 5, 1, 7, 9, 5, 3, 7, 5]\n_, _, patches = plt.hist(data, align=\"mid\")\n\nfor pp in patches:\n x = (pp._x0 + pp._x1)/2\n y = pp._y1 + 0.05\n plt.text(x, y, pp._y1)\n\nplt.show()" } ]
How to create advanced Loading Screen using CSS ? - GeeksforGeeks
23 Nov, 2021 In this article, we are going to build an advanced version of a wave-like structure for loading screens using HTML and CSS. The loading screen is useful when a certain page took a few seconds to load the content of the webpage. If a certain webpage doesn’t contain the loading screen then at the time of loading the web page, the user might think that the webpage is not responding at all. So, this way can be effective to make the user distracted or wait for a few seconds until the page is fully loaded. In this way, the users can be able to engage with the webpage for a bit longer duration. CSS loading screen Approach: Declare the div element that has the load class. Inside the div element, declare the h2 tag to show the loading percentage. In the CSS part, add the border-radius property in the load class, also make the position relative. Set the height and width property equal and give a border-radius to set rounded corners. Then, assign a rotate animation to it using the @keyframe property to create the animation/transition effects to the browser. Set the overflow property of the div element to hidden, so that only the part inside div is visible, to simulate a loading screen. Example: This example describes the CSS loading screen with a wave-like structure. HTML <!DOCTYPE html><html> <head> <title>Advanced Loading Screen</title> <style> body { background-color: black; } h1 { color: #4CAF50; text-align: center; font-size: 70px; margin: 20px 0; } .load { height: 250px; width: 250px; margin: auto; border-radius: 50%; position: relative; top: 20%; overflow: hidden; border: 4px solid #DDD; } .load::after { content: ""; position: absolute; top: 25%; left: -50%; height: 200%; width: 200%; background-color: #388E3C; box-shadow: 0 0 15px #4CAF50; border-radius: 40%; animation: rotate 10s linear forwards infinite; opacity: 0.9; } h2 { color: white; font-size: 70px; text-align: center; font-family: "Trebuchet MS"; position: relative; top: 10%; } @keyframes rotate { to { transform: rotate(360deg); } } </style></head> <body> <h1>GeeksforGeeks</h1> <div class="load"> <h2>75%</h2> </div></body> </html> Output: CSS loading screen Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. CSS-Properties CSS-Questions HTML-Questions CSS HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Design a web page using HTML and CSS Form validation using jQuery How to fetch data from localserver database and display on HTML table using PHP ? How to Create Time-Table schedule using HTML ? Search Bar using HTML, CSS and JavaScript REST API (Introduction) How to Insert Form Data into Database using PHP ? Form validation using HTML and JavaScript How to set input type date in dd-mm-yyyy format using HTML ? How to set the default value for an HTML <select> element ?
[ { "code": null, "e": 24985, "s": 24957, "text": "\n23 Nov, 2021" }, { "code": null, "e": 25580, "s": 24985, "text": "In this article, we are going to build an advanced version of a wave-like structure for loading screens using HTML and CSS. The loading screen is useful when a certain page took a few seconds to load the content of the webpage. If a certain webpage doesn’t contain the loading screen then at the time of loading the web page, the user might think that the webpage is not responding at all. So, this way can be effective to make the user distracted or wait for a few seconds until the page is fully loaded. In this way, the users can be able to engage with the webpage for a bit longer duration." }, { "code": null, "e": 25599, "s": 25580, "text": "CSS loading screen" }, { "code": null, "e": 25609, "s": 25599, "text": "Approach:" }, { "code": null, "e": 25733, "s": 25609, "text": "Declare the div element that has the load class. Inside the div element, declare the h2 tag to show the loading percentage." }, { "code": null, "e": 25834, "s": 25733, "text": "In the CSS part, add the border-radius property in the load class, also make the position relative. " }, { "code": null, "e": 26049, "s": 25834, "text": "Set the height and width property equal and give a border-radius to set rounded corners. Then, assign a rotate animation to it using the @keyframe property to create the animation/transition effects to the browser." }, { "code": null, "e": 26180, "s": 26049, "text": "Set the overflow property of the div element to hidden, so that only the part inside div is visible, to simulate a loading screen." }, { "code": null, "e": 26263, "s": 26180, "text": "Example: This example describes the CSS loading screen with a wave-like structure." }, { "code": null, "e": 26268, "s": 26263, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <title>Advanced Loading Screen</title> <style> body { background-color: black; } h1 { color: #4CAF50; text-align: center; font-size: 70px; margin: 20px 0; } .load { height: 250px; width: 250px; margin: auto; border-radius: 50%; position: relative; top: 20%; overflow: hidden; border: 4px solid #DDD; } .load::after { content: \"\"; position: absolute; top: 25%; left: -50%; height: 200%; width: 200%; background-color: #388E3C; box-shadow: 0 0 15px #4CAF50; border-radius: 40%; animation: rotate 10s linear forwards infinite; opacity: 0.9; } h2 { color: white; font-size: 70px; text-align: center; font-family: \"Trebuchet MS\"; position: relative; top: 10%; } @keyframes rotate { to { transform: rotate(360deg); } } </style></head> <body> <h1>GeeksforGeeks</h1> <div class=\"load\"> <h2>75%</h2> </div></body> </html>", "e": 27439, "s": 26268, "text": null }, { "code": null, "e": 27447, "s": 27439, "text": "Output:" }, { "code": null, "e": 27466, "s": 27447, "text": "CSS loading screen" }, { "code": null, "e": 27603, "s": 27466, "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": 27618, "s": 27603, "text": "CSS-Properties" }, { "code": null, "e": 27632, "s": 27618, "text": "CSS-Questions" }, { "code": null, "e": 27647, "s": 27632, "text": "HTML-Questions" }, { "code": null, "e": 27651, "s": 27647, "text": "CSS" }, { "code": null, "e": 27656, "s": 27651, "text": "HTML" }, { "code": null, "e": 27673, "s": 27656, "text": "Web Technologies" }, { "code": null, "e": 27678, "s": 27673, "text": "HTML" }, { "code": null, "e": 27776, "s": 27678, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27785, "s": 27776, "text": "Comments" }, { "code": null, "e": 27798, "s": 27785, "text": "Old Comments" }, { "code": null, "e": 27835, "s": 27798, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 27864, "s": 27835, "text": "Form validation using jQuery" }, { "code": null, "e": 27946, "s": 27864, "text": "How to fetch data from localserver database and display on HTML table using PHP ?" }, { "code": null, "e": 27993, "s": 27946, "text": "How to Create Time-Table schedule using HTML ?" }, { "code": null, "e": 28035, "s": 27993, "text": "Search Bar using HTML, CSS and JavaScript" }, { "code": null, "e": 28059, "s": 28035, "text": "REST API (Introduction)" }, { "code": null, "e": 28109, "s": 28059, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 28151, "s": 28109, "text": "Form validation using HTML and JavaScript" }, { "code": null, "e": 28212, "s": 28151, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" } ]
Laravel - Ajax
Ajax (Asynchronous JavaScript and XML) is a set of web development techniques utilizing many web technologies used on the client-side to create asynchronous Web applications. Import jquery library in your view file to use ajax functions of jquery which will be used to send and receive data using ajax from the server. On the server side you can use the response() function to send response to client and to send response in JSON format you can chain the response function with json() function. json(string|array $data = array(), int $status = 200, array $headers = array(), int $options) Step 1 − Create a view file called resources/views/message.php and copy the following code in that file. <html> <head> <title>Ajax Example</title> <script src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"> </script> <script> function getMessage() { $.ajax({ type:'POST', url:'/getmsg', data:'_token = <?php echo csrf_token() ?>', success:function(data) { $("#msg").html(data.msg); } }); } </script> </head> <body> <div id = 'msg'>This message will be replaced using Ajax. Click the button to replace the message.</div> <?php echo Form::button('Replace Message',['onClick'=>'getMessage()']); ?> </body> </html> Step 2 − Create a controller called AjaxController by executing the following command. php artisan make:controller AjaxController --plain Step 3 − After successful execution, you will receive the following output − Step 4 − Copy the following code in app/Http/Controllers/AjaxController.php file. app/Http/Controllers/AjaxController.php <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Http\Requests; use App\Http\Controllers\Controller; class AjaxController extends Controller { public function index() { $msg = "This is a simple message."; return response()->json(array('msg'=> $msg), 200); } } Step 5 − Add the following lines in app/Http/routes.php. app/Http/routes.php Route::get('ajax',function() { return view('message'); }); Route::post('/getmsg','AjaxController@index'); Step 6 − Visit the following URL to test the Ajax functionality. http://localhost:8000/ajax Step 7 − You will be redirected to a page where you will see a message as shown in the following image. Step 8 − The output will appear as shown in the following image after clicking the button. 13 Lectures 3 hours Sebastian Sulinski 35 Lectures 3.5 hours Antonio Papa 7 Lectures 1.5 hours Sebastian Sulinski 42 Lectures 1 hours Skillbakerystudios 165 Lectures 13 hours Paul Carlo Tordecilla 116 Lectures 13 hours Hafizullah Masoudi Print Add Notes Bookmark this page
[ { "code": null, "e": 2967, "s": 2472, "text": "Ajax (Asynchronous JavaScript and XML) is a set of web development techniques utilizing many web technologies used on the client-side to create asynchronous Web applications. Import jquery library in your view file to use ajax functions of jquery which will be used to send and receive data using ajax from the server. On the server side you can use the response() function to send response to client and to send response in JSON format you can chain the response function with json() function." }, { "code": null, "e": 3062, "s": 2967, "text": "json(string|array $data = array(), int $status = 200, array $headers = array(), int $options)\n" }, { "code": null, "e": 3167, "s": 3062, "text": "Step 1 − Create a view file called resources/views/message.php and copy the following code in that file." }, { "code": null, "e": 3928, "s": 3167, "text": "<html>\n <head>\n <title>Ajax Example</title>\n \n <script src = \"https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js\">\n </script>\n \n <script>\n function getMessage() {\n $.ajax({\n type:'POST',\n url:'/getmsg',\n data:'_token = <?php echo csrf_token() ?>',\n success:function(data) {\n $(\"#msg\").html(data.msg);\n }\n });\n }\n </script>\n </head>\n \n <body>\n <div id = 'msg'>This message will be replaced using Ajax. \n Click the button to replace the message.</div>\n <?php\n echo Form::button('Replace Message',['onClick'=>'getMessage()']);\n ?>\n </body>\n\n</html>" }, { "code": null, "e": 4015, "s": 3928, "text": "Step 2 − Create a controller called AjaxController by executing the following command." }, { "code": null, "e": 4067, "s": 4015, "text": "php artisan make:controller AjaxController --plain\n" }, { "code": null, "e": 4144, "s": 4067, "text": "Step 3 − After successful execution, you will receive the following output −" }, { "code": null, "e": 4180, "s": 4144, "text": "Step 4 − Copy the following code in" }, { "code": null, "e": 4226, "s": 4180, "text": "app/Http/Controllers/AjaxController.php file." }, { "code": null, "e": 4266, "s": 4226, "text": "app/Http/Controllers/AjaxController.php" }, { "code": null, "e": 4573, "s": 4266, "text": "<?php\n\nnamespace App\\Http\\Controllers;\n\nuse Illuminate\\Http\\Request;\nuse App\\Http\\Requests;\nuse App\\Http\\Controllers\\Controller;\n\nclass AjaxController extends Controller {\n public function index() {\n $msg = \"This is a simple message.\";\n return response()->json(array('msg'=> $msg), 200);\n }\n}" }, { "code": null, "e": 4630, "s": 4573, "text": "Step 5 − Add the following lines in app/Http/routes.php." }, { "code": null, "e": 4650, "s": 4630, "text": "app/Http/routes.php" }, { "code": null, "e": 4760, "s": 4650, "text": "Route::get('ajax',function() {\n return view('message');\n});\nRoute::post('/getmsg','AjaxController@index');\n" }, { "code": null, "e": 4825, "s": 4760, "text": "Step 6 − Visit the following URL to test the Ajax functionality." }, { "code": null, "e": 4853, "s": 4825, "text": "http://localhost:8000/ajax\n" }, { "code": null, "e": 4957, "s": 4853, "text": "Step 7 − You will be redirected to a page where you will see a message as shown in the following image." }, { "code": null, "e": 5048, "s": 4957, "text": "Step 8 − The output will appear as shown in the following image after clicking the button." }, { "code": null, "e": 5081, "s": 5048, "text": "\n 13 Lectures \n 3 hours \n" }, { "code": null, "e": 5101, "s": 5081, "text": " Sebastian Sulinski" }, { "code": null, "e": 5136, "s": 5101, "text": "\n 35 Lectures \n 3.5 hours \n" }, { "code": null, "e": 5150, "s": 5136, "text": " Antonio Papa" }, { "code": null, "e": 5184, "s": 5150, "text": "\n 7 Lectures \n 1.5 hours \n" }, { "code": null, "e": 5204, "s": 5184, "text": " Sebastian Sulinski" }, { "code": null, "e": 5237, "s": 5204, "text": "\n 42 Lectures \n 1 hours \n" }, { "code": null, "e": 5257, "s": 5237, "text": " Skillbakerystudios" }, { "code": null, "e": 5292, "s": 5257, "text": "\n 165 Lectures \n 13 hours \n" }, { "code": null, "e": 5315, "s": 5292, "text": " Paul Carlo Tordecilla" }, { "code": null, "e": 5350, "s": 5315, "text": "\n 116 Lectures \n 13 hours \n" }, { "code": null, "e": 5370, "s": 5350, "text": " Hafizullah Masoudi" }, { "code": null, "e": 5377, "s": 5370, "text": " Print" }, { "code": null, "e": 5388, "s": 5377, "text": " Add Notes" } ]
Get count of array elements from a specific field in MongoDB documents?
To count array elements from a specific field, use $size in MongoDB. Let us create a collection with documents − > db.demo723.insertOne({"Subject":["MySQL","MongoDB"]}); { "acknowledged" : true, "insertedId" : ObjectId("5eab094d43417811278f588a") } > db.demo723.insertOne({"Subject":["C"]}); { "acknowledged" : true, "insertedId" : ObjectId("5eab095243417811278f588b") } > db.demo723.insertOne({"Subject":["C++","Java","Python"]}); { "acknowledged" : true, "insertedId" : ObjectId("5eab095f43417811278f588c") } Display all documents from a collection with the help of find() method − > db.demo723.find(); This will produce the following output − { "_id" : ObjectId("5eab094d43417811278f588a"), "Subject" : [ "MySQL", "MongoDB" ] } { "_id" : ObjectId("5eab095243417811278f588b"), "Subject" : [ "C" ] } { "_id" : ObjectId("5eab095f43417811278f588c"), "Subject" : [ "C++", "Java", "Python" ] } Following is the query to count array elements in MongoDB − > db.demo723.aggregate([ ... { $project: { count: { $size: '$Subject' } } } ... ]) This will produce the following output − { "_id" : ObjectId("5eab094d43417811278f588a"), "count" : 2 } { "_id" : ObjectId("5eab095243417811278f588b"), "count" : 1 } { "_id" : ObjectId("5eab095f43417811278f588c"), "count" : 3 }
[ { "code": null, "e": 1175, "s": 1062, "text": "To count array elements from a specific field, use $size in MongoDB. Let us create a collection with documents −" }, { "code": null, "e": 1591, "s": 1175, "text": "> db.demo723.insertOne({\"Subject\":[\"MySQL\",\"MongoDB\"]});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5eab094d43417811278f588a\")\n}\n> db.demo723.insertOne({\"Subject\":[\"C\"]});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5eab095243417811278f588b\")\n}\n> db.demo723.insertOne({\"Subject\":[\"C++\",\"Java\",\"Python\"]});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5eab095f43417811278f588c\")\n}" }, { "code": null, "e": 1664, "s": 1591, "text": "Display all documents from a collection with the help of find() method −" }, { "code": null, "e": 1685, "s": 1664, "text": "> db.demo723.find();" }, { "code": null, "e": 1726, "s": 1685, "text": "This will produce the following output −" }, { "code": null, "e": 1971, "s": 1726, "text": "{ \"_id\" : ObjectId(\"5eab094d43417811278f588a\"), \"Subject\" : [ \"MySQL\", \"MongoDB\" ] }\n{ \"_id\" : ObjectId(\"5eab095243417811278f588b\"), \"Subject\" : [ \"C\" ] }\n{ \"_id\" : ObjectId(\"5eab095f43417811278f588c\"), \"Subject\" : [ \"C++\", \"Java\", \"Python\" ] }" }, { "code": null, "e": 2031, "s": 1971, "text": "Following is the query to count array elements in MongoDB −" }, { "code": null, "e": 2117, "s": 2031, "text": "> db.demo723.aggregate([\n... { $project: { count: { $size: '$Subject' } } }\n... ])" }, { "code": null, "e": 2158, "s": 2117, "text": "This will produce the following output −" }, { "code": null, "e": 2344, "s": 2158, "text": "{ \"_id\" : ObjectId(\"5eab094d43417811278f588a\"), \"count\" : 2 }\n{ \"_id\" : ObjectId(\"5eab095243417811278f588b\"), \"count\" : 1 }\n{ \"_id\" : ObjectId(\"5eab095f43417811278f588c\"), \"count\" : 3 }" } ]
How To Delete A Column In Pandas | Towards Data Science
Deleting columns from pandas DataFrames is a fairly common task. In today’s short guide we are going to explore how you can delete specific column(s) by name. More specifically, we are going to discuss how to delete columns using: del command drop() method pop() method Additionally, we will discuss how to delete columns by specified their index rather than their name. First, let’s create an example pandas DataFrame that we’ll use throughout this guide in order to demonstrate a few concepts. import pandas as pddf = pd.DataFrame({ 'colA':[1, 2, 3], 'colB': ['a', 'b', 'c'], 'colC': [True, False, False],})print(df)# colA colB colC# 0 1 a True# 1 2 b False# 2 3 c False If you want to delete a specific column the first option you have is to call del as shown below: del df['colC']print(df)# colA colB# 0 1 a# 1 2 b# 2 3 c This approach will only work only if you wish to delete a single column. If you need to delete multiple column in one go, read the following section. Additionally, it’s important to note that del df.colC won’t work! The syntax must be identical to the one shown in the example above. pandas.DataFrame.drop method is used to delete the specified labels from either rows or columns. In order to delete columns, you need to specify axis=1 as shown below: df = df.drop(['colA', 'colC'], axis=1)print(df)# colB# 0 a# 1 b# 2 c Note that if you want to delete the columns without having to re-assign the result back to df, all you need to do is specify inplace to True : df.drop(['colA', 'colC'], axis=1, inplace=True) Another option is pandas.DataFrame.pop that returns the deleted column and finally deletes it from the original DataFrame. df.pop('colB') will return column colB that we want to get deleted from the DataFrame: 0 a1 b2 c and we can verify that the column has indeed been deleted from the original frame: print(df) colA colC0 1 True1 2 False2 3 False In the sections above, we explored how to delete specific columns by their name. However, you may also need to delete a particular column by referencing its index instead. To do so, you can use pandas.DataFrame.drop method. Assuming that we want to drop columns colA and colC with indices 0 and 2 respectively, we can do so as shown below: df.drop(df.columns[[0, 2]], axis=1, inplace=True) In today’s short guide we explored how to delete specific column(s) in a pandas DataFrame in various ways either by name or by index. You may also be interested in reading about how to rename columns of pandas DataFrames. If so make sure not to miss the article below. towardsdatascience.com Moreover, the article below discusses how to perform proper row selection based on specific conditions.
[ { "code": null, "e": 403, "s": 172, "text": "Deleting columns from pandas DataFrames is a fairly common task. In today’s short guide we are going to explore how you can delete specific column(s) by name. More specifically, we are going to discuss how to delete columns using:" }, { "code": null, "e": 415, "s": 403, "text": "del command" }, { "code": null, "e": 429, "s": 415, "text": "drop() method" }, { "code": null, "e": 442, "s": 429, "text": "pop() method" }, { "code": null, "e": 543, "s": 442, "text": "Additionally, we will discuss how to delete columns by specified their index rather than their name." }, { "code": null, "e": 668, "s": 543, "text": "First, let’s create an example pandas DataFrame that we’ll use throughout this guide in order to demonstrate a few concepts." }, { "code": null, "e": 885, "s": 668, "text": "import pandas as pddf = pd.DataFrame({ 'colA':[1, 2, 3], 'colB': ['a', 'b', 'c'], 'colC': [True, False, False],})print(df)# colA colB colC# 0 1 a True# 1 2 b False# 2 3 c False" }, { "code": null, "e": 982, "s": 885, "text": "If you want to delete a specific column the first option you have is to call del as shown below:" }, { "code": null, "e": 1062, "s": 982, "text": "del df['colC']print(df)# colA colB# 0 1 a# 1 2 b# 2 3 c" }, { "code": null, "e": 1212, "s": 1062, "text": "This approach will only work only if you wish to delete a single column. If you need to delete multiple column in one go, read the following section." }, { "code": null, "e": 1346, "s": 1212, "text": "Additionally, it’s important to note that del df.colC won’t work! The syntax must be identical to the one shown in the example above." }, { "code": null, "e": 1443, "s": 1346, "text": "pandas.DataFrame.drop method is used to delete the specified labels from either rows or columns." }, { "code": null, "e": 1514, "s": 1443, "text": "In order to delete columns, you need to specify axis=1 as shown below:" }, { "code": null, "e": 1594, "s": 1514, "text": "df = df.drop(['colA', 'colC'], axis=1)print(df)# colB# 0 a# 1 b# 2 c" }, { "code": null, "e": 1737, "s": 1594, "text": "Note that if you want to delete the columns without having to re-assign the result back to df, all you need to do is specify inplace to True :" }, { "code": null, "e": 1785, "s": 1737, "text": "df.drop(['colA', 'colC'], axis=1, inplace=True)" }, { "code": null, "e": 1908, "s": 1785, "text": "Another option is pandas.DataFrame.pop that returns the deleted column and finally deletes it from the original DataFrame." }, { "code": null, "e": 1923, "s": 1908, "text": "df.pop('colB')" }, { "code": null, "e": 1995, "s": 1923, "text": "will return column colB that we want to get deleted from the DataFrame:" }, { "code": null, "e": 2014, "s": 1995, "text": "0 a1 b2 c" }, { "code": null, "e": 2097, "s": 2014, "text": "and we can verify that the column has indeed been deleted from the original frame:" }, { "code": null, "e": 2163, "s": 2097, "text": "print(df) colA colC0 1 True1 2 False2 3 False" }, { "code": null, "e": 2335, "s": 2163, "text": "In the sections above, we explored how to delete specific columns by their name. However, you may also need to delete a particular column by referencing its index instead." }, { "code": null, "e": 2503, "s": 2335, "text": "To do so, you can use pandas.DataFrame.drop method. Assuming that we want to drop columns colA and colC with indices 0 and 2 respectively, we can do so as shown below:" }, { "code": null, "e": 2553, "s": 2503, "text": "df.drop(df.columns[[0, 2]], axis=1, inplace=True)" }, { "code": null, "e": 2687, "s": 2553, "text": "In today’s short guide we explored how to delete specific column(s) in a pandas DataFrame in various ways either by name or by index." }, { "code": null, "e": 2822, "s": 2687, "text": "You may also be interested in reading about how to rename columns of pandas DataFrames. If so make sure not to miss the article below." }, { "code": null, "e": 2845, "s": 2822, "text": "towardsdatascience.com" } ]
Here’s how you can access your entire iMessage history on your Mac | by Yorgos Askalidis | Towards Data Science
A guide on how to create a data-science-friendly file with your iMessage history. If you use the Messages app on your Apple computer then you probably have connected your Apple-Id to that computer in order to send and receive iMessages across all your Apple devices (iPhone, iPad, computer). When using the Messages app, you can see all your history of messages on that device and maybe (like me) you have wondered where exactly is that data stored? Can you access it in a format that is easy to analyze? Wouldn’t it be great to be able to see how many messages you have sent per day? Or read the first message you have ever sent to your friends? Well you’re in luck! Your Apple computer stores that message history right within your grasp in a hidden folder on your hard drive! This is a somehow technical guide for extracting all the iMessage data in your computer’s hard drive and putting them in an analysis-friendly file. Note: this approach only works for Macs (laptops and desktops) and only gets your iMessage history. Green bubble messages unfortunately are not captured. If you just want to see the good stuff you can find the notebook with the minimal code to extract and prepare the data here. The iMessage history that powers your Messages app is stored in a database file in your computer’s hard drive, in a hidden folder named Library which, in turn, is in your username folder. You can usually find your username folder on the side bar of the finder. Hidden folders are folders that by default don’t appear to the user, usually holding files that a casual user doesn’t have to interact with, such as system-related files. You can make the hidden folders appear by simultaneously pressing the Command, the Shift and the dot keys: “Command+Shift+.”. If for some reason that doesn’t work, you can also open the Terminal app and simply type the following. defaults write com.apple.finder AppleShowAllFiles YES Once that works, you can go and find the Messages folder, (which contains the chat.db database) within the Library folder as shown in the image below. A very simple way to understand what a database file is is to think of it a a folder that contains a bunch of excel-like tables. Much like larger or enterprise-grade databases you can connect and access the data in the database in a variety of ways. In this tutorial, I’m using Python and the amazing pandas module to connect to the database, explore the tables and data it holds and then read that data from the appropriate tables. connection codeimport sqlite3import pandas as pd# substitute username with your usernameconn = sqlite3.connect('/Users/username/Library/Messages/chat.db')# connect to the databasecur = conn.cursor()# get the names of the tables in the databasecur.execute(" select name from sqlite_master where type = 'table' ") for name in cur.fetchall(): print(name) Above we connect to the database and explore what tables are in there. I found that there are a few tables in the database including one called message and others names chat, handle and attachment. Let’s explore the message table because that’s the one that sounds most promising to hold our iMessages. I do that by transferring the table into a pandas dataframe, a type of file that is much easier to explore and manipulate for data analyis projects. # get the 10 entries of the message table using pandasmessages = pd.read_sql_query("select * from message limit 10", conn) We hit bingo! The message table indeed seems to hold all the saved iMessages. It has a text field with the actual sent or received message, a date field (more on that below) and a handle id. After a little exploration I found that the handle_id is a code for each phone number or Apple-id that you have had a conversation with. In order to map the handle_id back to the Apple-id we can use a table in the database (appropriately) named handle and join on handle_id. # get the handles to apple-id mapping tablehandles = pd.read_sql_query("select * from handle", conn)# and join to the messages, on handle_idmessages.rename(columns={'ROWID' : 'message_id'}, inplace = True)handles.rename(columns={'id' : 'phone_number', 'ROWID': 'handle_id'}, inplace = True)merge_leve_1 = temp = pd.merge(messages[['text', 'handle_id', 'date','is_sent', 'message_id']], handles[['handle_id', 'phone_number']], on ='handle_id', how='left') Similarly, the message table also includes a chat_id that maps each message back to unique chat. This can be useful when doing analysis on chats with multiple people in them. We can get the chat_id of each message by joining the message table with the (again, appropriately named) chat_message_join table on message_id. # get the chat to message mappingchat_message_joins = pd.read_sql_query("select * from chat_message_join", conn)# and join back to the merge_level_1 tabledf_messages = pd.merge(merge_level_1, chat_message_joins[['chat_id', 'message_id']], on = 'message_id', how='left') The message table also includes a date column and this was a little tricky for me to decode since it isn’t exactly in any format that is widely used in the industry. Moreover, the way that this column is recorded is a little different in newer version of Mac OS X compared to older ones. Credit to this stackoverflow page that helped me figure this out. In Mac OS X versions before High Sierra (which is version 10.13 and released in September 2017), the date column is an epoch type but, unlike the standard of counting the seconds from 1970–01–01, it is counting the seconds from 2001–01–01. In order to convert that type into a data field we can actually comprehend we can use a command while querying the message table to create a new field (we will call it date_utc, since it is giving a UTC timezone date as a result) based on the date field. # convert 2001-01-01 epoch time into a timestamp# Mac OS X versions before High Sierradatetime(message.date + strftime("%s", "2001-01-01") ,"unixepoch","localtime")# how to use that in the SQL querymessages = pd.read_sql_query("select *, datetime(message.date + strftime("%s", "2001-01-01") ,"unixepoch","localtime") as date_uct from message", conn) In Mac OS X High Sierra and above, it’s the same thing but the date format is now much more granular: it is in nano-second level. So now we need to divide by 1,000,000,000 before we apply the same code snippet we applied above. # convert 2001-01-01 epoch time into a timestamp# Mac OS X versions after High Sierradatetime(message.date/1000000000 + strftime("%s", "2001-01-01") ,"unixepoch","localtime")# how to use that in the SQL querymessages = pd.read_sql_query("select *, datetime(message.date/1000000000 + strftime("%s", "2001-01-01") ,"unixepoch","localtime") as date_uct from message", conn) You can find the notebook here with all the code in order for you to extract your iMessages from your laptop and start analyzing! It should only take a few minutes and by the end of it you should have a basic history of your iMessage data that includes the phone number (or email), the text, a unique chat for each unique group of people you had a chat with and the timestamp (in UTC timezone) of each message sent. You can actually find more data in the database such as details if the message was delivered and read as well as attachments. I’m not touching on those attributes on this post. This post also only instructs on how to get iMessage data from your Apple computer. If you have any pointers on how you can extract your iMessage history from Apple mobile devices (iPhone & iPad) let me know in the comments. Happy reading your messages! Was this helpful? Let me know if things were not clear.
[ { "code": null, "e": 253, "s": 171, "text": "A guide on how to create a data-science-friendly file with your iMessage history." }, { "code": null, "e": 818, "s": 253, "text": "If you use the Messages app on your Apple computer then you probably have connected your Apple-Id to that computer in order to send and receive iMessages across all your Apple devices (iPhone, iPad, computer). When using the Messages app, you can see all your history of messages on that device and maybe (like me) you have wondered where exactly is that data stored? Can you access it in a format that is easy to analyze? Wouldn’t it be great to be able to see how many messages you have sent per day? Or read the first message you have ever sent to your friends?" }, { "code": null, "e": 950, "s": 818, "text": "Well you’re in luck! Your Apple computer stores that message history right within your grasp in a hidden folder on your hard drive!" }, { "code": null, "e": 1098, "s": 950, "text": "This is a somehow technical guide for extracting all the iMessage data in your computer’s hard drive and putting them in an analysis-friendly file." }, { "code": null, "e": 1252, "s": 1098, "text": "Note: this approach only works for Macs (laptops and desktops) and only gets your iMessage history. Green bubble messages unfortunately are not captured." }, { "code": null, "e": 1377, "s": 1252, "text": "If you just want to see the good stuff you can find the notebook with the minimal code to extract and prepare the data here." }, { "code": null, "e": 1638, "s": 1377, "text": "The iMessage history that powers your Messages app is stored in a database file in your computer’s hard drive, in a hidden folder named Library which, in turn, is in your username folder. You can usually find your username folder on the side bar of the finder." }, { "code": null, "e": 2039, "s": 1638, "text": "Hidden folders are folders that by default don’t appear to the user, usually holding files that a casual user doesn’t have to interact with, such as system-related files. You can make the hidden folders appear by simultaneously pressing the Command, the Shift and the dot keys: “Command+Shift+.”. If for some reason that doesn’t work, you can also open the Terminal app and simply type the following." }, { "code": null, "e": 2093, "s": 2039, "text": "defaults write com.apple.finder AppleShowAllFiles YES" }, { "code": null, "e": 2244, "s": 2093, "text": "Once that works, you can go and find the Messages folder, (which contains the chat.db database) within the Library folder as shown in the image below." }, { "code": null, "e": 2494, "s": 2244, "text": "A very simple way to understand what a database file is is to think of it a a folder that contains a bunch of excel-like tables. Much like larger or enterprise-grade databases you can connect and access the data in the database in a variety of ways." }, { "code": null, "e": 2677, "s": 2494, "text": "In this tutorial, I’m using Python and the amazing pandas module to connect to the database, explore the tables and data it holds and then read that data from the appropriate tables." }, { "code": null, "e": 3032, "s": 2677, "text": "connection codeimport sqlite3import pandas as pd# substitute username with your usernameconn = sqlite3.connect('/Users/username/Library/Messages/chat.db')# connect to the databasecur = conn.cursor()# get the names of the tables in the databasecur.execute(\" select name from sqlite_master where type = 'table' \") for name in cur.fetchall(): print(name)" }, { "code": null, "e": 3484, "s": 3032, "text": "Above we connect to the database and explore what tables are in there. I found that there are a few tables in the database including one called message and others names chat, handle and attachment. Let’s explore the message table because that’s the one that sounds most promising to hold our iMessages. I do that by transferring the table into a pandas dataframe, a type of file that is much easier to explore and manipulate for data analyis projects." }, { "code": null, "e": 3607, "s": 3484, "text": "# get the 10 entries of the message table using pandasmessages = pd.read_sql_query(\"select * from message limit 10\", conn)" }, { "code": null, "e": 4073, "s": 3607, "text": "We hit bingo! The message table indeed seems to hold all the saved iMessages. It has a text field with the actual sent or received message, a date field (more on that below) and a handle id. After a little exploration I found that the handle_id is a code for each phone number or Apple-id that you have had a conversation with. In order to map the handle_id back to the Apple-id we can use a table in the database (appropriately) named handle and join on handle_id." }, { "code": null, "e": 4529, "s": 4073, "text": "# get the handles to apple-id mapping tablehandles = pd.read_sql_query(\"select * from handle\", conn)# and join to the messages, on handle_idmessages.rename(columns={'ROWID' : 'message_id'}, inplace = True)handles.rename(columns={'id' : 'phone_number', 'ROWID': 'handle_id'}, inplace = True)merge_leve_1 = temp = pd.merge(messages[['text', 'handle_id', 'date','is_sent', 'message_id']], handles[['handle_id', 'phone_number']], on ='handle_id', how='left')" }, { "code": null, "e": 4849, "s": 4529, "text": "Similarly, the message table also includes a chat_id that maps each message back to unique chat. This can be useful when doing analysis on chats with multiple people in them. We can get the chat_id of each message by joining the message table with the (again, appropriately named) chat_message_join table on message_id." }, { "code": null, "e": 5119, "s": 4849, "text": "# get the chat to message mappingchat_message_joins = pd.read_sql_query(\"select * from chat_message_join\", conn)# and join back to the merge_level_1 tabledf_messages = pd.merge(merge_level_1, chat_message_joins[['chat_id', 'message_id']], on = 'message_id', how='left')" }, { "code": null, "e": 5407, "s": 5119, "text": "The message table also includes a date column and this was a little tricky for me to decode since it isn’t exactly in any format that is widely used in the industry. Moreover, the way that this column is recorded is a little different in newer version of Mac OS X compared to older ones." }, { "code": null, "e": 5473, "s": 5407, "text": "Credit to this stackoverflow page that helped me figure this out." }, { "code": null, "e": 5968, "s": 5473, "text": "In Mac OS X versions before High Sierra (which is version 10.13 and released in September 2017), the date column is an epoch type but, unlike the standard of counting the seconds from 1970–01–01, it is counting the seconds from 2001–01–01. In order to convert that type into a data field we can actually comprehend we can use a command while querying the message table to create a new field (we will call it date_utc, since it is giving a UTC timezone date as a result) based on the date field." }, { "code": null, "e": 6318, "s": 5968, "text": "# convert 2001-01-01 epoch time into a timestamp# Mac OS X versions before High Sierradatetime(message.date + strftime(\"%s\", \"2001-01-01\") ,\"unixepoch\",\"localtime\")# how to use that in the SQL querymessages = pd.read_sql_query(\"select *, datetime(message.date + strftime(\"%s\", \"2001-01-01\") ,\"unixepoch\",\"localtime\") as date_uct from message\", conn)" }, { "code": null, "e": 6546, "s": 6318, "text": "In Mac OS X High Sierra and above, it’s the same thing but the date format is now much more granular: it is in nano-second level. So now we need to divide by 1,000,000,000 before we apply the same code snippet we applied above." }, { "code": null, "e": 6917, "s": 6546, "text": "# convert 2001-01-01 epoch time into a timestamp# Mac OS X versions after High Sierradatetime(message.date/1000000000 + strftime(\"%s\", \"2001-01-01\") ,\"unixepoch\",\"localtime\")# how to use that in the SQL querymessages = pd.read_sql_query(\"select *, datetime(message.date/1000000000 + strftime(\"%s\", \"2001-01-01\") ,\"unixepoch\",\"localtime\") as date_uct from message\", conn)" }, { "code": null, "e": 7047, "s": 6917, "text": "You can find the notebook here with all the code in order for you to extract your iMessages from your laptop and start analyzing!" }, { "code": null, "e": 7333, "s": 7047, "text": "It should only take a few minutes and by the end of it you should have a basic history of your iMessage data that includes the phone number (or email), the text, a unique chat for each unique group of people you had a chat with and the timestamp (in UTC timezone) of each message sent." }, { "code": null, "e": 7510, "s": 7333, "text": "You can actually find more data in the database such as details if the message was delivered and read as well as attachments. I’m not touching on those attributes on this post." }, { "code": null, "e": 7735, "s": 7510, "text": "This post also only instructs on how to get iMessage data from your Apple computer. If you have any pointers on how you can extract your iMessage history from Apple mobile devices (iPhone & iPad) let me know in the comments." }, { "code": null, "e": 7764, "s": 7735, "text": "Happy reading your messages!" } ]
Elixir - Strings
Strings in Elixir are inserted between double quotes, and they are encoded in UTF-8. Unlike C and C++ where the default strings are ASCII encoded and only 256 different characters are possible, UTF-8 consists of 1,112,064 code points. This means that UTF-8 encoding consists of those many different possible characters. Since the strings use utf-8, we can also use symbols like: ö, ł, etc. To create a string variable, simply assign a string to a variable − str = "Hello world" To print this to your console, simply call the IO.puts function and pass it the variable str − str = str = "Hello world" IO.puts(str) The above program generates the following result − Hello World You can create an empty string using the string literal, "". For example, a = "" if String.length(a) === 0 do IO.puts("a is an empty string") end The above program generates the following result. a is an empty string String interpolation is a way to construct a new String value from a mix of constants, variables, literals, and expressions by including their values inside a string literal. Elixir supports string interpolation, to use a variable in a string, when writing it, wrap it with curly braces and prepend the curly braces with a '#' sign. For example, x = "Apocalypse" y = "X-men #{x}" IO.puts(y) This will take the value of x and substitute it in y. The above code will generate the following result − X-men Apocalypse We have already seen the use of String concatenation in previous chapters. The '<>' operator is used to concatenate strings in Elixir. To concatenate 2 strings, x = "Dark" y = "Knight" z = x <> " " <> y IO.puts(z) The above code generates the following result − Dark Knight To get the length of the string, we use the String.length function. Pass the string as a parameter and it will show you its size. For example, IO.puts(String.length("Hello")) When running above program, it produces following result − 5 To reverse a string, pass it to the String.reverse function. For example, IO.puts(String.reverse("Elixir")) The above program generates the following result − rixilE To compare 2 strings, we can use the == or the === operators. For example, var_1 = "Hello world" var_2 = "Hello Elixir" if var_1 === var_2 do IO.puts("#{var_1} and #{var_2} are the same") else IO.puts("#{var_1} and #{var_2} are not the same") end The above program generates the following result − Hello world and Hello elixir are not the same. We have already seen the use of the =~ string match operator. To check if a string matches a regex, we can also use the string match operator or the String.match? function. For example, IO.puts(String.match?("foo", ~r/foo/)) IO.puts(String.match?("bar", ~r/foo/)) The above program generates the following result − true false This same can also be achieved by using the =~ operator. For example, IO.puts("foo" =~ ~r/foo/) The above program generates the following result − true Elixir supports a large number of functions related to strings, some of the most used are listed in the following table. at(string, position) Returns the grapheme at the position of the given utf8 string. If position is greater than string length, then it returns nil capitalize(string) Converts the first character in the given string to uppercase and the remainder to lowercase contains?(string, contents) Checks if string contains any of the given contents downcase(string) Converts all characters in the given string to lowercase ends_with?(string, suffixes) Returns true if string ends with any of the suffixes given first(string) Returns the first grapheme from a utf8 string, nil if the string is empty last(string) Returns the last grapheme from a utf8 string, nil if the string is empty replace(subject, pattern, replacement, options \\ []) Returns a new string created by replacing occurrences of pattern in subject with replacement slice(string, start, len) Returns a substring starting at the offset start, and of length len split(string) Divides a string into substrings at each Unicode whitespace occurrence with leading and trailing whitespace ignored. Groups of whitespace are treated as a single occurrence. Divisions do not occur on non-breaking whitespace upcase(string) Converts all characters in the given string to uppercase A binary is just a sequence of bytes. Binaries are defined using << >>. For example: << 0, 1, 2, 3 >> Of course, those bytes can be organized in any way, even in a sequence that does not make them a valid string. For example, << 239, 191, 191 >> Strings are also binaries. And the string concatenation operator <> is actually a Binary concatenation operator: IO.puts(<< 0, 1 >> <> << 2, 3 >>) The above code generates the following result − << 0, 1, 2, 3 >> Note the ł character. Since this is utf-8 encoded, this character representation takes up 2 bytes. Since each number represented in a binary is meant to be a byte, when this value goes up from 255, it is truncated. To prevent this, we use size modifier to specify how many bits we want that number to take. For example − IO.puts(<< 256 >>) # truncated, it'll print << 0 >> IO.puts(<< 256 :: size(16) >>) #Takes 16 bits/2 bytes, will print << 1, 0 >> The above program will generate the following result − << 0 >> << 1, 0 >> We can also use the utf8 modifier, if a character is code point then, it will be produced in the output; else the bytes − IO.puts(<< 256 :: utf8 >>) The above program generates the following result − Ā We also have a function called is_binary that checks if a given variable is a binary. Note that only variables which are stored as multiples of 8bits are binaries. If we define a binary using the size modifier and pass it a value that is not a multiple of 8, we end up with a bitstring instead of a binary. For example, bs = << 1 :: size(1) >> IO.puts(bs) IO.puts(is_binary(bs)) IO.puts(is_bitstring(bs)) The above program generates the following result − << 1::size(1) >> false true This means that variable bs is not a binary but rather a bitstring. We can also say that a binary is a bitstring where the number of bits is divisible by 8. Pattern matching works on binaries as well as bitstrings in the same way. 35 Lectures 3 hours Pranjal Srivastava 54 Lectures 6 hours Pranjal Srivastava, Harshit Srivastava 80 Lectures 9.5 hours Pranjal Srivastava 43 Lectures 4 hours Mohammad Nauman Print Add Notes Bookmark this page
[ { "code": null, "e": 2573, "s": 2182, "text": "Strings in Elixir are inserted between double quotes, and they are encoded in UTF-8. Unlike C and C++ where the default strings are ASCII encoded and only 256 different characters are possible, UTF-8 consists of 1,112,064 code points. This means that UTF-8 encoding consists of those many different possible characters. Since the strings use utf-8, we can also use symbols like: ö, ł, etc." }, { "code": null, "e": 2641, "s": 2573, "text": "To create a string variable, simply assign a string to a variable −" }, { "code": null, "e": 2661, "s": 2641, "text": "str = \"Hello world\"" }, { "code": null, "e": 2756, "s": 2661, "text": "To print this to your console, simply call the IO.puts function and pass it the variable str −" }, { "code": null, "e": 2796, "s": 2756, "text": "str = str = \"Hello world\" \nIO.puts(str)" }, { "code": null, "e": 2847, "s": 2796, "text": "The above program generates the following result −" }, { "code": null, "e": 2860, "s": 2847, "text": "Hello World\n" }, { "code": null, "e": 2934, "s": 2860, "text": "You can create an empty string using the string literal, \"\". For example," }, { "code": null, "e": 3009, "s": 2934, "text": "a = \"\"\nif String.length(a) === 0 do\n IO.puts(\"a is an empty string\")\nend" }, { "code": null, "e": 3059, "s": 3009, "text": "The above program generates the following result." }, { "code": null, "e": 3081, "s": 3059, "text": "a is an empty string\n" }, { "code": null, "e": 3414, "s": 3081, "text": "String interpolation is a way to construct a new String value from a mix of constants, variables, literals, and expressions by including their values inside a string literal. Elixir supports string interpolation, to use a variable in a string, when writing it, wrap it with curly braces and prepend the curly braces with a '#' sign." }, { "code": null, "e": 3427, "s": 3414, "text": "For example," }, { "code": null, "e": 3473, "s": 3427, "text": "x = \"Apocalypse\" \ny = \"X-men #{x}\"\nIO.puts(y)" }, { "code": null, "e": 3579, "s": 3473, "text": "This will take the value of x and substitute it in y. The above code will generate the following result −" }, { "code": null, "e": 3597, "s": 3579, "text": "X-men Apocalypse\n" }, { "code": null, "e": 3758, "s": 3597, "text": "We have already seen the use of String concatenation in previous chapters. The '<>' operator is used to concatenate strings in Elixir. To concatenate 2 strings," }, { "code": null, "e": 3811, "s": 3758, "text": "x = \"Dark\"\ny = \"Knight\"\nz = x <> \" \" <> y\nIO.puts(z)" }, { "code": null, "e": 3859, "s": 3811, "text": "The above code generates the following result −" }, { "code": null, "e": 3872, "s": 3859, "text": "Dark Knight\n" }, { "code": null, "e": 4016, "s": 3872, "text": "To get the length of the string, we use the String.length function. Pass the string as a parameter and it will show you its size. For example, " }, { "code": null, "e": 4048, "s": 4016, "text": "IO.puts(String.length(\"Hello\"))" }, { "code": null, "e": 4107, "s": 4048, "text": "When running above program, it produces following result −" }, { "code": null, "e": 4110, "s": 4107, "text": "5\n" }, { "code": null, "e": 4184, "s": 4110, "text": "To reverse a string, pass it to the String.reverse function. For example," }, { "code": null, "e": 4218, "s": 4184, "text": "IO.puts(String.reverse(\"Elixir\"))" }, { "code": null, "e": 4269, "s": 4218, "text": "The above program generates the following result −" }, { "code": null, "e": 4277, "s": 4269, "text": "rixilE\n" }, { "code": null, "e": 4352, "s": 4277, "text": "To compare 2 strings, we can use the == or the === operators. For example," }, { "code": null, "e": 4530, "s": 4352, "text": "var_1 = \"Hello world\"\nvar_2 = \"Hello Elixir\"\nif var_1 === var_2 do\n IO.puts(\"#{var_1} and #{var_2} are the same\")\nelse\n IO.puts(\"#{var_1} and #{var_2} are not the same\")\nend" }, { "code": null, "e": 4581, "s": 4530, "text": "The above program generates the following result −" }, { "code": null, "e": 4629, "s": 4581, "text": "Hello world and Hello elixir are not the same.\n" }, { "code": null, "e": 4815, "s": 4629, "text": "We have already seen the use of the =~ string match operator. To check if a string matches a regex, we can also use the string match operator or the String.match? function. For example," }, { "code": null, "e": 4893, "s": 4815, "text": "IO.puts(String.match?(\"foo\", ~r/foo/))\nIO.puts(String.match?(\"bar\", ~r/foo/))" }, { "code": null, "e": 4944, "s": 4893, "text": "The above program generates the following result −" }, { "code": null, "e": 4957, "s": 4944, "text": "true \nfalse\n" }, { "code": null, "e": 5027, "s": 4957, "text": "This same can also be achieved by using the =~ operator. For example," }, { "code": null, "e": 5053, "s": 5027, "text": "IO.puts(\"foo\" =~ ~r/foo/)" }, { "code": null, "e": 5104, "s": 5053, "text": "The above program generates the following result −" }, { "code": null, "e": 5110, "s": 5104, "text": "true\n" }, { "code": null, "e": 5231, "s": 5110, "text": "Elixir supports a large number of functions related to strings, some of the most used are listed in the following table." }, { "code": null, "e": 5252, "s": 5231, "text": "at(string, position)" }, { "code": null, "e": 5378, "s": 5252, "text": "Returns the grapheme at the position of the given utf8 string. If position is greater than string length, then it returns nil" }, { "code": null, "e": 5397, "s": 5378, "text": "capitalize(string)" }, { "code": null, "e": 5490, "s": 5397, "text": "Converts the first character in the given string to uppercase and the remainder to lowercase" }, { "code": null, "e": 5518, "s": 5490, "text": "contains?(string, contents)" }, { "code": null, "e": 5570, "s": 5518, "text": "Checks if string contains any of the given contents" }, { "code": null, "e": 5587, "s": 5570, "text": "downcase(string)" }, { "code": null, "e": 5644, "s": 5587, "text": "Converts all characters in the given string to lowercase" }, { "code": null, "e": 5673, "s": 5644, "text": "ends_with?(string, suffixes)" }, { "code": null, "e": 5732, "s": 5673, "text": "Returns true if string ends with any of the suffixes given" }, { "code": null, "e": 5746, "s": 5732, "text": "first(string)" }, { "code": null, "e": 5820, "s": 5746, "text": "Returns the first grapheme from a utf8 string, nil if the string is empty" }, { "code": null, "e": 5834, "s": 5820, "text": "\nlast(string)" }, { "code": null, "e": 5907, "s": 5834, "text": "Returns the last grapheme from a utf8 string, nil if the string is empty" }, { "code": null, "e": 5962, "s": 5907, "text": "\nreplace(subject, pattern, replacement, options \\\\ [])" }, { "code": null, "e": 6055, "s": 5962, "text": "Returns a new string created by replacing occurrences of pattern in subject with replacement" }, { "code": null, "e": 6081, "s": 6055, "text": "slice(string, start, len)" }, { "code": null, "e": 6149, "s": 6081, "text": "Returns a substring starting at the offset start, and of length len" }, { "code": null, "e": 6163, "s": 6149, "text": "split(string)" }, { "code": null, "e": 6387, "s": 6163, "text": "Divides a string into substrings at each Unicode whitespace occurrence with leading and trailing whitespace ignored. Groups of whitespace are treated as a single occurrence. Divisions do not occur on non-breaking whitespace" }, { "code": null, "e": 6402, "s": 6387, "text": "upcase(string)" }, { "code": null, "e": 6459, "s": 6402, "text": "Converts all characters in the given string to uppercase" }, { "code": null, "e": 6545, "s": 6459, "text": "A binary is just a sequence of bytes. Binaries are defined using << >>. For example: " }, { "code": null, "e": 6563, "s": 6545, "text": "<< 0, 1, 2, 3 >>\n" }, { "code": null, "e": 6688, "s": 6563, "text": "Of course, those bytes can be organized in any way, even in a sequence that does not make them a valid string. For example, " }, { "code": null, "e": 6709, "s": 6688, "text": "<< 239, 191, 191 >>\n" }, { "code": null, "e": 6823, "s": 6709, "text": "Strings are also binaries. And the string concatenation operator <> is actually a Binary concatenation operator: " }, { "code": null, "e": 6857, "s": 6823, "text": "IO.puts(<< 0, 1 >> <> << 2, 3 >>)" }, { "code": null, "e": 6905, "s": 6857, "text": "The above code generates the following result −" }, { "code": null, "e": 6923, "s": 6905, "text": "<< 0, 1, 2, 3 >>\n" }, { "code": null, "e": 7022, "s": 6923, "text": "Note the ł character. Since this is utf-8 encoded, this character representation takes up 2 bytes." }, { "code": null, "e": 7244, "s": 7022, "text": "Since each number represented in a binary is meant to be a byte, when this value goes up from 255, it is truncated. To prevent this, we use size modifier to specify how many bits we want that number to take. For example −" }, { "code": null, "e": 7373, "s": 7244, "text": "IO.puts(<< 256 >>) # truncated, it'll print << 0 >>\nIO.puts(<< 256 :: size(16) >>) #Takes 16 bits/2 bytes, will print << 1, 0 >>" }, { "code": null, "e": 7428, "s": 7373, "text": "The above program will generate the following result −" }, { "code": null, "e": 7448, "s": 7428, "text": "<< 0 >>\n<< 1, 0 >>\n" }, { "code": null, "e": 7570, "s": 7448, "text": "We can also use the utf8 modifier, if a character is code point then, it will be produced in the output; else the bytes −" }, { "code": null, "e": 7597, "s": 7570, "text": "IO.puts(<< 256 :: utf8 >>)" }, { "code": null, "e": 7648, "s": 7597, "text": "The above program generates the following result −" }, { "code": null, "e": 7652, "s": 7648, "text": "Ā\n" }, { "code": null, "e": 7816, "s": 7652, "text": "We also have a function called is_binary that checks if a given variable is a binary. Note that only variables which are stored as multiples of 8bits are binaries." }, { "code": null, "e": 7973, "s": 7816, "text": "If we define a binary using the size modifier and pass it a value that is not a multiple of 8, we end up with a bitstring instead of a binary. For example, " }, { "code": null, "e": 8058, "s": 7973, "text": "bs = << 1 :: size(1) >>\nIO.puts(bs)\nIO.puts(is_binary(bs))\nIO.puts(is_bitstring(bs))" }, { "code": null, "e": 8109, "s": 8058, "text": "The above program generates the following result −" }, { "code": null, "e": 8138, "s": 8109, "text": "<< 1::size(1) >>\nfalse\ntrue\n" }, { "code": null, "e": 8369, "s": 8138, "text": "This means that variable bs is not a binary but rather a bitstring. We can also say that a binary is a bitstring where the number of bits is divisible by 8. Pattern matching works on binaries as well as bitstrings in the same way." }, { "code": null, "e": 8402, "s": 8369, "text": "\n 35 Lectures \n 3 hours \n" }, { "code": null, "e": 8422, "s": 8402, "text": " Pranjal Srivastava" }, { "code": null, "e": 8455, "s": 8422, "text": "\n 54 Lectures \n 6 hours \n" }, { "code": null, "e": 8495, "s": 8455, "text": " Pranjal Srivastava, Harshit Srivastava" }, { "code": null, "e": 8530, "s": 8495, "text": "\n 80 Lectures \n 9.5 hours \n" }, { "code": null, "e": 8550, "s": 8530, "text": " Pranjal Srivastava" }, { "code": null, "e": 8583, "s": 8550, "text": "\n 43 Lectures \n 4 hours \n" }, { "code": null, "e": 8600, "s": 8583, "text": " Mohammad Nauman" }, { "code": null, "e": 8607, "s": 8600, "text": " Print" }, { "code": null, "e": 8618, "s": 8607, "text": " Add Notes" } ]
Evaluate a boolean expression represented as string - GeeksforGeeks
15 Mar, 2022 Given a string consisting of only 0, 1, A, B, C where A = AND B = OR C = XOR Calculate the value of the string assuming no order of precedence and evaluation is done from left to right.Constraints – The length of string will be odd. It will always be a valid string. Example, 1AA0 will not be given as an input. Examples: Input : 1A0B1 Output : 1 1 AND 0 OR 1 = 1 Input : 1C1B1B0A0 Output : 0 Source : Microsoft online round for internship 2017 The idea is to traverse all operands by jumping a character after every iteration. For current operand str[i], check values of str[i+1] and str[i+2], accordingly decide the value of current subexpression. C++ Java Python3 C# PHP Javascript // C++ program to evaluate value of an expression.#include <bits/stdc++.h> using namespace std; int evaluateBoolExpr(string s){ int n = s.length(); // Traverse all operands by jumping // a character after every iteration. for (int i = 0; i < n; i += 2) { // If operator next to current operand // is AND. if (s[i + 1] == 'A') { if (s[i + 2] == '0'|| s[i] == '0') s[i + 2] = '0'; else s[i + 2] = '1'; } // If operator next to current operand // is OR. else if (s[i + 1] == 'B') { if (s[i + 2] == '1'|| s[i] == '1') s[i + 2] = '1'; else s[i + 2] = '0'; } // If operator next to current operand // is XOR (Assuming a valid input) else { if (s[i + 2] == s[i]) s[i + 2] = '0'; else s[i + 2] = '1'; } } return s[n - 1] -'0';} // Driver codeint main(){ string s = "1C1B1B0A0"; cout << evaluateBoolExpr(s); return 0;} // Java program to evaluate value of an expression.public class Evaluate_BoolExp { // Evaluates boolean expression // and returns the result static int evaluateBoolExpr(StringBuffer s) { int n = s.length(); // Traverse all operands by jumping // a character after every iteration. for (int i = 0; i < n; i += 2) { // If operator next to current operand // is AND. if( i + 1 < n && i + 2 < n) { if (s.charAt(i + 1) == 'A') { if (s.charAt(i + 2) == '0' || s.charAt(i) == 0) s.setCharAt(i + 2, '0'); else s.setCharAt(i + 2, '1'); } // If operator next to current operand // is OR. else if ((i + 1) < n && s.charAt(i + 1 ) == 'B') { if (s.charAt(i + 2) == '1' || s.charAt(i) == '1') s.setCharAt(i + 2, '1'); else s.setCharAt(i + 2, '0'); } // If operator next to current operand // is XOR (Assuming a valid input) else { if (s.charAt(i + 2) == s.charAt(i)) s.setCharAt(i + 2, '0'); else s.setCharAt(i + 2 ,'1'); } } } return s.charAt(n - 1) - '0'; } // Driver code public static void main(String[] args) { String s = "1C1B1B0A0"; StringBuffer sb = new StringBuffer(s); System.out.println(evaluateBoolExpr(sb)); }}// This code is contributed by Sumit Ghosh # Python3 program to evaluate value# of an expression.import math as mt def evaluateBoolExpr(s): n = len(s) # Traverse all operands by jumping # a character after every iteration. for i in range(0, n - 2, 2): # If operator next to current # operand is AND.''' if (s[i + 1] == "A"): if (s[i + 2] == "0" or s[i] == "0"): s[i + 2] = "0" else: s[i + 2] = "1" # If operator next to current # operand is OR. else if (s[i + 1] == "B"): if (s[i + 2] == "1" or s[i] == "1"): s[i + 2] = "1" else: s[i + 2] = "0" # If operator next to current operand # is XOR (Assuming a valid input) else: if (s[i + 2] == s[i]): s[i + 2] = "0" else: s[i + 2] = "1" return ord(s[n - 1]) - ord("0") # Driver codes = "1C1B1B0A0"string=[s[i] for i in range(len(s))]print(evaluateBoolExpr(string)) # This code is contributed# by mohit kumar 29 // C# program to evaluate value// of an expression.using System;using System.Text; class GFG{ // Evaluates boolean expression// and returns the resultpublic static int evaluateBoolExpr(StringBuilder s){ int n = s.Length; // Traverse all operands by jumping // a character after every iteration. for (int i = 0; i < n; i += 2) { // If operator next to current // operand is AND. if (i + 1 < n && i + 2 < n) { if (s[i + 1] == 'A') { if (s[i + 2] == '0' || s[i] == 0) { s[i + 2] = '0'; } else { s[i + 2] = '1'; } } // If operator next to current // operand is OR. else if ((i + 1) < n && s[i + 1] == 'B') { if (s[i + 2] == '1' || s[i] == '1') { s[i + 2] = '1'; } else { s[i + 2] = '0'; } } // If operator next to current operand // is XOR (Assuming a valid input) else { if (s[i + 2] == s[i]) { s[i + 2] = '0'; } else { s[i + 2] = '1'; } } } } return s[n - 1] - '0';} // Driver codepublic static void Main(string[] args){ string s = "1C1B1B0A0"; StringBuilder sb = new StringBuilder(s); Console.WriteLine(evaluateBoolExpr(sb));}} // This code is contributed by Shrikant13 <?php// PHP program to evaluate value// of an expression. function evaluateBoolExpr($s){ $n = strlen($s); // Traverse all operands by jumping // a character after every iteration. for ($i = 0; $i < $n; $i += 2) { // If operator next to current operand // is AND. if (($i + 1) < $n && $s[$i + 1] == 'A') { if ($s[$i + 2] == '0'|| $s[$i] == '0') $s[$i + 2] = '0'; else $s[$i + 2] = '1'; } // If operator next to current operand // is OR. else if (($i + 1) < $n && $s[$i + 1] == 'B') { if ($s[$i + 2] == '1'|| $s[$i] == '1') $s[$i + 2] = '1'; else $s[$i + 2] = '0'; } // If operator next to current operand // is XOR (Assuming a valid input) else { if (($i + 2) < $n && $s[$i + 2] == $s[$i]) $s[$i + 2] = '0'; else $s[$i + 2] = '1'; } } return $s[$n - 1] -'0';} // Driver code$s = "1C1B1B0A0";echo evaluateBoolExpr($s); // This code is contributed// by Akanksha Rai <script> // Javascript program to evaluate// value of an expression. // Evaluates boolean expression// and returns the resultfunction evaluateBoolExpr(s){ let n = s.length; // Traverse all operands by jumping // a character after every iteration. for(let i = 0; i < n; i += 2) { // If operator next to current // operand is AND. if (i + 1 < n && i + 2 < n) { if (s[i + 1] == 'A') { if (s[i + 2] == '0' || s[i] == 0) { s[i + 2] = '0'; } else { s[i + 2] = '1'; } } // If operator next to current // operand is OR. else if ((i + 1) < n && s[i + 1] == 'B') { if (s[i + 2] == '1' || s[i] == '1') { s[i + 2] = '1'; } else { s[i + 2] = '0'; } } // If operator next to current operand // is XOR (Assuming a valid input) else { if (s[i + 2] == s[i]) { s[i + 2] = '0'; } else { s[i + 2] = '1'; } } } } return (s[n - 1].charCodeAt() - '0'.charCodeAt());} // Driver codelet s = "1C1B1B0A0";let sb = s.split(''); document.write(evaluateBoolExpr(sb) + "</br>"); // This code is contributed by rameshtravel07 </script> Output: 0 This article is contributed by Ayushi Jain. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. jit_t shrikanth13 mohit kumar 29 Akanksha_Rai rameshtravel07 surinderdawra388 Microsoft Strings Microsoft Strings Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Python program to check if a string is palindrome or not KMP Algorithm for Pattern Searching Different methods to reverse a string in C/C++ Convert string to char array in C++ Array of Strings in C++ (5 Different Ways to Create) Longest Palindromic Substring | Set 1 Reverse words in a given string Caesar Cipher in Cryptography Length of the longest substring without repeating characters Check whether two strings are anagram of each other
[ { "code": null, "e": 24808, "s": 24780, "text": "\n15 Mar, 2022" }, { "code": null, "e": 25120, "s": 24808, "text": "Given a string consisting of only 0, 1, A, B, C where A = AND B = OR C = XOR Calculate the value of the string assuming no order of precedence and evaluation is done from left to right.Constraints – The length of string will be odd. It will always be a valid string. Example, 1AA0 will not be given as an input." }, { "code": null, "e": 25131, "s": 25120, "text": "Examples: " }, { "code": null, "e": 25203, "s": 25131, "text": "Input : 1A0B1\nOutput : 1\n1 AND 0 OR 1 = 1\n\nInput : 1C1B1B0A0\nOutput : 0" }, { "code": null, "e": 25255, "s": 25203, "text": "Source : Microsoft online round for internship 2017" }, { "code": null, "e": 25460, "s": 25255, "text": "The idea is to traverse all operands by jumping a character after every iteration. For current operand str[i], check values of str[i+1] and str[i+2], accordingly decide the value of current subexpression." }, { "code": null, "e": 25464, "s": 25460, "text": "C++" }, { "code": null, "e": 25469, "s": 25464, "text": "Java" }, { "code": null, "e": 25477, "s": 25469, "text": "Python3" }, { "code": null, "e": 25480, "s": 25477, "text": "C#" }, { "code": null, "e": 25484, "s": 25480, "text": "PHP" }, { "code": null, "e": 25495, "s": 25484, "text": "Javascript" }, { "code": "// C++ program to evaluate value of an expression.#include <bits/stdc++.h> using namespace std; int evaluateBoolExpr(string s){ int n = s.length(); // Traverse all operands by jumping // a character after every iteration. for (int i = 0; i < n; i += 2) { // If operator next to current operand // is AND. if (s[i + 1] == 'A') { if (s[i + 2] == '0'|| s[i] == '0') s[i + 2] = '0'; else s[i + 2] = '1'; } // If operator next to current operand // is OR. else if (s[i + 1] == 'B') { if (s[i + 2] == '1'|| s[i] == '1') s[i + 2] = '1'; else s[i + 2] = '0'; } // If operator next to current operand // is XOR (Assuming a valid input) else { if (s[i + 2] == s[i]) s[i + 2] = '0'; else s[i + 2] = '1'; } } return s[n - 1] -'0';} // Driver codeint main(){ string s = \"1C1B1B0A0\"; cout << evaluateBoolExpr(s); return 0;}", "e": 26576, "s": 25495, "text": null }, { "code": "// Java program to evaluate value of an expression.public class Evaluate_BoolExp { // Evaluates boolean expression // and returns the result static int evaluateBoolExpr(StringBuffer s) { int n = s.length(); // Traverse all operands by jumping // a character after every iteration. for (int i = 0; i < n; i += 2) { // If operator next to current operand // is AND. if( i + 1 < n && i + 2 < n) { if (s.charAt(i + 1) == 'A') { if (s.charAt(i + 2) == '0' || s.charAt(i) == 0) s.setCharAt(i + 2, '0'); else s.setCharAt(i + 2, '1'); } // If operator next to current operand // is OR. else if ((i + 1) < n && s.charAt(i + 1 ) == 'B') { if (s.charAt(i + 2) == '1' || s.charAt(i) == '1') s.setCharAt(i + 2, '1'); else s.setCharAt(i + 2, '0'); } // If operator next to current operand // is XOR (Assuming a valid input) else { if (s.charAt(i + 2) == s.charAt(i)) s.setCharAt(i + 2, '0'); else s.setCharAt(i + 2 ,'1'); } } } return s.charAt(n - 1) - '0'; } // Driver code public static void main(String[] args) { String s = \"1C1B1B0A0\"; StringBuffer sb = new StringBuffer(s); System.out.println(evaluateBoolExpr(sb)); }}// This code is contributed by Sumit Ghosh", "e": 28403, "s": 26576, "text": null }, { "code": "# Python3 program to evaluate value# of an expression.import math as mt def evaluateBoolExpr(s): n = len(s) # Traverse all operands by jumping # a character after every iteration. for i in range(0, n - 2, 2): # If operator next to current # operand is AND.''' if (s[i + 1] == \"A\"): if (s[i + 2] == \"0\" or s[i] == \"0\"): s[i + 2] = \"0\" else: s[i + 2] = \"1\" # If operator next to current # operand is OR. else if (s[i + 1] == \"B\"): if (s[i + 2] == \"1\" or s[i] == \"1\"): s[i + 2] = \"1\" else: s[i + 2] = \"0\" # If operator next to current operand # is XOR (Assuming a valid input) else: if (s[i + 2] == s[i]): s[i + 2] = \"0\" else: s[i + 2] = \"1\" return ord(s[n - 1]) - ord(\"0\") # Driver codes = \"1C1B1B0A0\"string=[s[i] for i in range(len(s))]print(evaluateBoolExpr(string)) # This code is contributed# by mohit kumar 29", "e": 29461, "s": 28403, "text": null }, { "code": "// C# program to evaluate value// of an expression.using System;using System.Text; class GFG{ // Evaluates boolean expression// and returns the resultpublic static int evaluateBoolExpr(StringBuilder s){ int n = s.Length; // Traverse all operands by jumping // a character after every iteration. for (int i = 0; i < n; i += 2) { // If operator next to current // operand is AND. if (i + 1 < n && i + 2 < n) { if (s[i + 1] == 'A') { if (s[i + 2] == '0' || s[i] == 0) { s[i + 2] = '0'; } else { s[i + 2] = '1'; } } // If operator next to current // operand is OR. else if ((i + 1) < n && s[i + 1] == 'B') { if (s[i + 2] == '1' || s[i] == '1') { s[i + 2] = '1'; } else { s[i + 2] = '0'; } } // If operator next to current operand // is XOR (Assuming a valid input) else { if (s[i + 2] == s[i]) { s[i + 2] = '0'; } else { s[i + 2] = '1'; } } } } return s[n - 1] - '0';} // Driver codepublic static void Main(string[] args){ string s = \"1C1B1B0A0\"; StringBuilder sb = new StringBuilder(s); Console.WriteLine(evaluateBoolExpr(sb));}} // This code is contributed by Shrikant13", "e": 31126, "s": 29461, "text": null }, { "code": "<?php// PHP program to evaluate value// of an expression. function evaluateBoolExpr($s){ $n = strlen($s); // Traverse all operands by jumping // a character after every iteration. for ($i = 0; $i < $n; $i += 2) { // If operator next to current operand // is AND. if (($i + 1) < $n && $s[$i + 1] == 'A') { if ($s[$i + 2] == '0'|| $s[$i] == '0') $s[$i + 2] = '0'; else $s[$i + 2] = '1'; } // If operator next to current operand // is OR. else if (($i + 1) < $n && $s[$i + 1] == 'B') { if ($s[$i + 2] == '1'|| $s[$i] == '1') $s[$i + 2] = '1'; else $s[$i + 2] = '0'; } // If operator next to current operand // is XOR (Assuming a valid input) else { if (($i + 2) < $n && $s[$i + 2] == $s[$i]) $s[$i + 2] = '0'; else $s[$i + 2] = '1'; } } return $s[$n - 1] -'0';} // Driver code$s = \"1C1B1B0A0\";echo evaluateBoolExpr($s); // This code is contributed// by Akanksha Rai", "e": 32278, "s": 31126, "text": null }, { "code": "<script> // Javascript program to evaluate// value of an expression. // Evaluates boolean expression// and returns the resultfunction evaluateBoolExpr(s){ let n = s.length; // Traverse all operands by jumping // a character after every iteration. for(let i = 0; i < n; i += 2) { // If operator next to current // operand is AND. if (i + 1 < n && i + 2 < n) { if (s[i + 1] == 'A') { if (s[i + 2] == '0' || s[i] == 0) { s[i + 2] = '0'; } else { s[i + 2] = '1'; } } // If operator next to current // operand is OR. else if ((i + 1) < n && s[i + 1] == 'B') { if (s[i + 2] == '1' || s[i] == '1') { s[i + 2] = '1'; } else { s[i + 2] = '0'; } } // If operator next to current operand // is XOR (Assuming a valid input) else { if (s[i + 2] == s[i]) { s[i + 2] = '0'; } else { s[i + 2] = '1'; } } } } return (s[n - 1].charCodeAt() - '0'.charCodeAt());} // Driver codelet s = \"1C1B1B0A0\";let sb = s.split(''); document.write(evaluateBoolExpr(sb) + \"</br>\"); // This code is contributed by rameshtravel07 </script>", "e": 33904, "s": 32278, "text": null }, { "code": null, "e": 33913, "s": 33904, "text": "Output: " }, { "code": null, "e": 33915, "s": 33913, "text": "0" }, { "code": null, "e": 34335, "s": 33915, "text": "This article is contributed by Ayushi Jain. 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": 34341, "s": 34335, "text": "jit_t" }, { "code": null, "e": 34353, "s": 34341, "text": "shrikanth13" }, { "code": null, "e": 34368, "s": 34353, "text": "mohit kumar 29" }, { "code": null, "e": 34381, "s": 34368, "text": "Akanksha_Rai" }, { "code": null, "e": 34396, "s": 34381, "text": "rameshtravel07" }, { "code": null, "e": 34413, "s": 34396, "text": "surinderdawra388" }, { "code": null, "e": 34423, "s": 34413, "text": "Microsoft" }, { "code": null, "e": 34431, "s": 34423, "text": "Strings" }, { "code": null, "e": 34441, "s": 34431, "text": "Microsoft" }, { "code": null, "e": 34449, "s": 34441, "text": "Strings" }, { "code": null, "e": 34547, "s": 34449, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34556, "s": 34547, "text": "Comments" }, { "code": null, "e": 34569, "s": 34556, "text": "Old Comments" }, { "code": null, "e": 34626, "s": 34569, "text": "Python program to check if a string is palindrome or not" }, { "code": null, "e": 34662, "s": 34626, "text": "KMP Algorithm for Pattern Searching" }, { "code": null, "e": 34709, "s": 34662, "text": "Different methods to reverse a string in C/C++" }, { "code": null, "e": 34745, "s": 34709, "text": "Convert string to char array in C++" }, { "code": null, "e": 34798, "s": 34745, "text": "Array of Strings in C++ (5 Different Ways to Create)" }, { "code": null, "e": 34836, "s": 34798, "text": "Longest Palindromic Substring | Set 1" }, { "code": null, "e": 34868, "s": 34836, "text": "Reverse words in a given string" }, { "code": null, "e": 34898, "s": 34868, "text": "Caesar Cipher in Cryptography" }, { "code": null, "e": 34959, "s": 34898, "text": "Length of the longest substring without repeating characters" } ]
How to add table row in jQuery?
To add table row in jQuery, use the append() method to add table tags. You can try to run the following code to learn how to add table row in jQuery: Live Demo <!DOCTYPE html> <html> <head> <title>jQuery Add Table Rows</title> <style> table{ width: 100%; margin: 25px 0; border-collapse: collapse; } table, th, td{ border: 1px solid #6C220B; } table th, table td{ padding: 8px; text-align: left; } </style> <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script> <script> $(document).ready(function(){ $(".row").click(function(){ var name = $("#name").val(); var subject = $("#subject").val(); var markup = "<tr><td><input type='checkbox' name='record'></td><td>" + name + "</td><td>" + subject + "</td></tr>"; $("table tbody").append(markup); }); }); </script> </head> <body> <form> <input type="text" id="name" placeholder="Enter Name"> <input type="text" id="subject" placeholder="Enter Subject"> <input type="button" class="row" value="Click to Add Row"> </form> <table> <thead> <tr> <th>Choose</th> <th>Name</th> <th>Subject</th> </tr> </thead> <tbody> <tr> <td><input type="checkbox" name="result"></td> <td>Amit</td> <td>Java</td> </tr> </tbody> </table> </body> </html>
[ { "code": null, "e": 1133, "s": 1062, "text": "To add table row in jQuery, use the append() method to add table tags." }, { "code": null, "e": 1212, "s": 1133, "text": "You can try to run the following code to learn how to add table row in jQuery:" }, { "code": null, "e": 1222, "s": 1212, "text": "Live Demo" }, { "code": null, "e": 2769, "s": 1222, "text": "<!DOCTYPE html>\n<html>\n <head>\n <title>jQuery Add Table Rows</title>\n <style>\n table{\n width: 100%;\n margin: 25px 0;\n border-collapse: collapse;\n }\n table, th, td{\n border: 1px solid #6C220B;\n }\n table th, table td{\n padding: 8px;\n text-align: left;\n }\n </style>\n <script src=\"https://code.jquery.com/jquery-3.2.1.min.js\"></script>\n <script>\n $(document).ready(function(){\n $(\".row\").click(function(){\n var name = $(\"#name\").val();\n var subject = $(\"#subject\").val();\n var markup = \"<tr><td><input type='checkbox' name='record'></td><td>\" + name + \"</td><td>\" + subject + \"</td></tr>\";\n $(\"table tbody\").append(markup);\n }); \n }); \n </script>\n </head>\n <body>\n <form>\n <input type=\"text\" id=\"name\" placeholder=\"Enter Name\">\n <input type=\"text\" id=\"subject\" placeholder=\"Enter Subject\">\n <input type=\"button\" class=\"row\" value=\"Click to Add Row\">\n </form>\n <table>\n <thead>\n <tr>\n <th>Choose</th>\n <th>Name</th>\n <th>Subject</th>\n </tr>\n </thead>\n <tbody>\n <tr>\n <td><input type=\"checkbox\" name=\"result\"></td>\n <td>Amit</td>\n <td>Java</td>\n </tr>\n </tbody>\n </table>\n </body>\n</html>" } ]
Dynamic Programming | Building Bridges - GeeksforGeeks
12 May, 2022 Consider a 2-D map with a horizontal river passing through its center. There are n cities on the southern bank with x-coordinates a(1) ... a(n) and n cities on the northern bank with x-coordinates b(1) ... b(n). You want to connect as many north-south pairs of cities as possible with bridges such that no two bridges cross. When connecting cities, you can only connect city a(i) on the northern bank to city b(i) on the southern bank. Maximum number of bridges that can be built to connect north-south pairs with the above mentioned constraints. The values in the upper bank can be considered as the northern x-coordinates of the cities and the values in the bottom bank can be considered as the corresponding southern x-coordinates of the cities to which the northern x-coordinate city can be connected.Examples: Input : 6 4 2 1 2 3 6 5 Output : Maximum number of bridges = 2 Explanation: Let the north-south x-coordinates be written in increasing order. 1 2 3 4 5 6 \ \ \ \ For the north-south pairs \ \ (2, 6) and (1, 5) \ \ the bridges can be built. \ \ We can consider other pairs also, \ \ but then only one bridge can be built \ \ because more than one bridge built will \ \ then cross each other. \ \ 1 2 3 4 5 6 Input : 8 1 4 3 5 2 6 7 1 2 3 4 5 6 7 8 Output : Maximum number of bridges = 5 Approach: It is a variation of LIS problem. The following are the steps to solve the problem. Sort the north-south pairs on the basis of increasing order of south x-coordinates.If two south x-coordinates are same, then sort on the basis of increasing order of north x-coordinates.Now find the Longest Increasing Subsequence of the north x-coordinates.One thing to note that in the increasing subsequence a value can be greater as well as can be equal to its previous value. Sort the north-south pairs on the basis of increasing order of south x-coordinates. If two south x-coordinates are same, then sort on the basis of increasing order of north x-coordinates. Now find the Longest Increasing Subsequence of the north x-coordinates. One thing to note that in the increasing subsequence a value can be greater as well as can be equal to its previous value. We can also sort on the basis of north x-coordinates and find the LIS on the south x-coordinates. CPP Java // C++ implementation of building bridges#include <bits/stdc++.h> using namespace std; // north-south coordinates// of each City Pairstruct CityPairs{ int north, south;}; // comparison function to sort// the given set of CityPairsbool compare(struct CityPairs a, struct CityPairs b){ if (a.south == b.south) return a.north < b.north; return a.south < b.south;} // function to find the maximum number// of bridges that can be builtint maxBridges(struct CityPairs values[], int n){ int lis[n]; for (int i=0; i<n; i++) lis[i] = 1; sort(values, values+n, compare); // logic of longest increasing subsequence // applied on the northern coordinates for (int i=1; i<n; i++) for (int j=0; j<i; j++) if (values[i].north >= values[j].north && lis[i] < 1 + lis[j]) lis[i] = 1 + lis[j]; int max = lis[0]; for (int i=1; i<n; i++) if (max < lis[i]) max = lis[i]; // required number of bridges // that can be built return max; } // Driver program to test aboveint main(){ struct CityPairs values[] = {{6, 2}, {4, 3}, {2, 6}, {1, 5}}; int n = 4; cout << "Maximum number of bridges = " << maxBridges(values, n); return 0;} // Java Program for maximizing the no. of bridges// such that none of them cross each other import java.util.*; class CityPairs // Create user-defined class{ int north, south; CityPairs(int north, int south) // Constructor { this.north = north; this.south = south; }}// Use Comparator for manual sortingclass MyCmp implements Comparator<CityPairs>{ public int compare(CityPairs cp1, CityPairs cp2) { // If 2 cities have same north coordinates // then sort them in increasing order // according to south coordinates. if (cp1.north == cp2.north) return cp1.south - cp2.south; // Sort in increasing order of // north coordinates. return cp1.north - cp2.north; }}public class BuildingBridges { // function to find the max. number of bridges // that can be built public static int maxBridges(CityPairs[] pairs, int n) { int[] LIS = new int[n]; // By default single city has LIS = 1. Arrays.fill(LIS, 1); Arrays.sort(pairs, new MyCmp()); // Sorting-> // calling // our self made comparator // Logic for Longest increasing subsequence // applied on south coordinates. for (int i = 1; i < n; i++) { for (int j = 0; j < i; j++) { if (pairs[i].south >= pairs[j].south) LIS[i] = Math.max(LIS[i], LIS[j] + 1); } } int max = LIS[0]; for (int i = 1; i < n; i++) { max = Math.max(max, LIS[i]); } // Return the max number of bridges that can be // built. return max; } // Driver Program to test above public static void main(String[] args) { int n = 4; CityPairs[] pairs = new CityPairs[n]; pairs[0] = new CityPairs(6, 2); pairs[1] = new CityPairs(4, 3); pairs[2] = new CityPairs(2, 6); pairs[3] = new CityPairs(1, 5); System.out.println("Maximum number of bridges = " + maxBridges(pairs, n)); }} Output: Maximum number of bridges = 2 Time Complexity: O(n2) Approach – 2 (Optimization in LIS ) Note – This is the variation/Application of Longest Increasing Subsequence (LIS). Step -1 Initially let the one side be north of the bridge and other side be south of the bridge. Step -2 Let we take north side and sort the element with respect to their position. Step -3 As per north side is sorted therefore it is increasing and if we apply LIS on south side then we will able to get the non-overlapping bridges. Note – Longest Increasing subsequence can be done in O(NlogN) using Patience sort. The main optimization lies in the fact that smallest element have higher chance of contributing in LIS. Input: 6 4 2 1 2 3 6 5 Step 1 –Sort the input at north position of bridge. 1 2 4 6 5 6 3 2 Step -2 Apply LIS on South bank that is 5 6 3 2 In optimization of LIS if we find an element which is smaller than current element then we Replace the halt the current flow and start with the new smaller element. If we find larger element than current element we increment the answer. 5————- >6 (Answer =2) HALT we find 3 which is smaller than 6 3 (Answer = 1) HALT we find 2 which is smaller than 3 2 (Answer=1) FINAL ANSWER = 2 C++ #include<bits/stdc++.h>using namespace std; int non_overlapping_bridges(vector<pair<int,int>> &temp,int n){ //Step - 1 Sort the north side. sort(temp.begin(),temp.end()); // Create the Dp array to store the flow of non overlapping bridges. // ans-->Store the final max number of non-overlapping bridges. vector<int> dp(n+1,INT_MAX); int ans=0; for(int i=0;i<n;i++) { int idx=lower_bound(dp.begin(),dp.end(),temp[i].second)-dp.begin(); dp[idx]=temp[i].second; ans=max(ans,idx+1); } return ans;} int main(){ int n=4; vector<pair<int,int>> temp; temp.push_back(make_pair(6,2)); temp.push_back(make_pair(4,3)); temp.push_back(make_pair(2,6)); temp.push_back(make_pair(1,5)); cout<<non_overlapping_bridges(temp,n)<<endl; return 0;} OUTPUT – 2 Time Complexity – O(NlogN) Space Complexity – O(N) Problem References: https://www.geeksforgeeks.org/dynamic-programming-set-14-variations-of-lis/Solution References: https://www.youtube.com/watch?v=w6tSmS86C4wThis article is contributed by Ayush Jauhari. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. varun9 diveshkumar4 hritikbhatnagar2182 ryanranaut abhishek0719kadiyan devy2k87 LIS Dynamic Programming Dynamic Programming Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Optimal Substructure Property in Dynamic Programming | DP-2 Optimal Binary Search Tree | DP-24 Min Cost Path | DP-6 Greedy approach vs Dynamic programming Maximum Subarray Sum using Divide and Conquer algorithm Word Break Problem | DP-32 3 Different ways to print Fibonacci series in Java Maximum sum such that no two elements are adjacent Top 50 Dynamic Programming Coding Problems for Interviews How to solve a Dynamic Programming Problem ?
[ { "code": null, "e": 25943, "s": 25915, "text": "\n12 May, 2022" }, { "code": null, "e": 26491, "s": 25943, "text": "Consider a 2-D map with a horizontal river passing through its center. There are n cities on the southern bank with x-coordinates a(1) ... a(n) and n cities on the northern bank with x-coordinates b(1) ... b(n). You want to connect as many north-south pairs of cities as possible with bridges such that no two bridges cross. When connecting cities, you can only connect city a(i) on the northern bank to city b(i) on the southern bank. Maximum number of bridges that can be built to connect north-south pairs with the above mentioned constraints. " }, { "code": null, "e": 26761, "s": 26491, "text": "The values in the upper bank can be considered as the northern x-coordinates of the cities and the values in the bottom bank can be considered as the corresponding southern x-coordinates of the cities to which the northern x-coordinate city can be connected.Examples: " }, { "code": null, "e": 27369, "s": 26761, "text": "Input : 6 4 2 1\n 2 3 6 5\nOutput : Maximum number of bridges = 2\nExplanation: Let the north-south x-coordinates\nbe written in increasing order.\n\n1 2 3 4 5 6\n \\ \\\n \\ \\ For the north-south pairs\n \\ \\ (2, 6) and (1, 5)\n \\ \\ the bridges can be built.\n \\ \\ We can consider other pairs also,\n \\ \\ but then only one bridge can be built \n \\ \\ because more than one bridge built will\n \\ \\ then cross each other.\n \\ \\\n1 2 3 4 5 6 \n\nInput : 8 1 4 3 5 2 6 7 \n 1 2 3 4 5 6 7 8\nOutput : Maximum number of bridges = 5" }, { "code": null, "e": 27466, "s": 27371, "text": "Approach: It is a variation of LIS problem. The following are the steps to solve the problem. " }, { "code": null, "e": 27846, "s": 27466, "text": "Sort the north-south pairs on the basis of increasing order of south x-coordinates.If two south x-coordinates are same, then sort on the basis of increasing order of north x-coordinates.Now find the Longest Increasing Subsequence of the north x-coordinates.One thing to note that in the increasing subsequence a value can be greater as well as can be equal to its previous value." }, { "code": null, "e": 27930, "s": 27846, "text": "Sort the north-south pairs on the basis of increasing order of south x-coordinates." }, { "code": null, "e": 28034, "s": 27930, "text": "If two south x-coordinates are same, then sort on the basis of increasing order of north x-coordinates." }, { "code": null, "e": 28106, "s": 28034, "text": "Now find the Longest Increasing Subsequence of the north x-coordinates." }, { "code": null, "e": 28229, "s": 28106, "text": "One thing to note that in the increasing subsequence a value can be greater as well as can be equal to its previous value." }, { "code": null, "e": 28328, "s": 28229, "text": "We can also sort on the basis of north x-coordinates and find the LIS on the south x-coordinates. " }, { "code": null, "e": 28332, "s": 28328, "text": "CPP" }, { "code": null, "e": 28337, "s": 28332, "text": "Java" }, { "code": "// C++ implementation of building bridges#include <bits/stdc++.h> using namespace std; // north-south coordinates// of each City Pairstruct CityPairs{ int north, south;}; // comparison function to sort// the given set of CityPairsbool compare(struct CityPairs a, struct CityPairs b){ if (a.south == b.south) return a.north < b.north; return a.south < b.south;} // function to find the maximum number// of bridges that can be builtint maxBridges(struct CityPairs values[], int n){ int lis[n]; for (int i=0; i<n; i++) lis[i] = 1; sort(values, values+n, compare); // logic of longest increasing subsequence // applied on the northern coordinates for (int i=1; i<n; i++) for (int j=0; j<i; j++) if (values[i].north >= values[j].north && lis[i] < 1 + lis[j]) lis[i] = 1 + lis[j]; int max = lis[0]; for (int i=1; i<n; i++) if (max < lis[i]) max = lis[i]; // required number of bridges // that can be built return max; } // Driver program to test aboveint main(){ struct CityPairs values[] = {{6, 2}, {4, 3}, {2, 6}, {1, 5}}; int n = 4; cout << \"Maximum number of bridges = \" << maxBridges(values, n); return 0;}", "e": 29642, "s": 28337, "text": null }, { "code": "// Java Program for maximizing the no. of bridges// such that none of them cross each other import java.util.*; class CityPairs // Create user-defined class{ int north, south; CityPairs(int north, int south) // Constructor { this.north = north; this.south = south; }}// Use Comparator for manual sortingclass MyCmp implements Comparator<CityPairs>{ public int compare(CityPairs cp1, CityPairs cp2) { // If 2 cities have same north coordinates // then sort them in increasing order // according to south coordinates. if (cp1.north == cp2.north) return cp1.south - cp2.south; // Sort in increasing order of // north coordinates. return cp1.north - cp2.north; }}public class BuildingBridges { // function to find the max. number of bridges // that can be built public static int maxBridges(CityPairs[] pairs, int n) { int[] LIS = new int[n]; // By default single city has LIS = 1. Arrays.fill(LIS, 1); Arrays.sort(pairs, new MyCmp()); // Sorting-> // calling // our self made comparator // Logic for Longest increasing subsequence // applied on south coordinates. for (int i = 1; i < n; i++) { for (int j = 0; j < i; j++) { if (pairs[i].south >= pairs[j].south) LIS[i] = Math.max(LIS[i], LIS[j] + 1); } } int max = LIS[0]; for (int i = 1; i < n; i++) { max = Math.max(max, LIS[i]); } // Return the max number of bridges that can be // built. return max; } // Driver Program to test above public static void main(String[] args) { int n = 4; CityPairs[] pairs = new CityPairs[n]; pairs[0] = new CityPairs(6, 2); pairs[1] = new CityPairs(4, 3); pairs[2] = new CityPairs(2, 6); pairs[3] = new CityPairs(1, 5); System.out.println(\"Maximum number of bridges = \" + maxBridges(pairs, n)); }}", "e": 31737, "s": 29642, "text": null }, { "code": null, "e": 31747, "s": 31737, "text": "Output: " }, { "code": null, "e": 31777, "s": 31747, "text": "Maximum number of bridges = 2" }, { "code": null, "e": 31800, "s": 31777, "text": "Time Complexity: O(n2)" }, { "code": null, "e": 31836, "s": 31800, "text": "Approach – 2 (Optimization in LIS )" }, { "code": null, "e": 31918, "s": 31836, "text": "Note – This is the variation/Application of Longest Increasing Subsequence (LIS)." }, { "code": null, "e": 32015, "s": 31918, "text": "Step -1 Initially let the one side be north of the bridge and other side be south of the bridge." }, { "code": null, "e": 32099, "s": 32015, "text": "Step -2 Let we take north side and sort the element with respect to their position." }, { "code": null, "e": 32250, "s": 32099, "text": "Step -3 As per north side is sorted therefore it is increasing and if we apply LIS on south side then we will able to get the non-overlapping bridges." }, { "code": null, "e": 32333, "s": 32250, "text": "Note – Longest Increasing subsequence can be done in O(NlogN) using Patience sort." }, { "code": null, "e": 32437, "s": 32333, "text": "The main optimization lies in the fact that smallest element have higher chance of contributing in LIS." }, { "code": null, "e": 32452, "s": 32437, "text": "Input: 6 4 2 1" }, { "code": null, "e": 32470, "s": 32452, "text": " 2 3 6 5" }, { "code": null, "e": 32522, "s": 32470, "text": "Step 1 –Sort the input at north position of bridge." }, { "code": null, "e": 32532, "s": 32522, "text": "1 2 4 6 " }, { "code": null, "e": 32540, "s": 32532, "text": "5 6 3 2" }, { "code": null, "e": 32588, "s": 32540, "text": "Step -2 Apply LIS on South bank that is 5 6 3 2" }, { "code": null, "e": 32827, "s": 32588, "text": "In optimization of LIS if we find an element which is smaller than current element then we Replace the halt the current flow and start with the new smaller element. If we find larger element than current element we increment the answer. " }, { "code": null, "e": 32890, "s": 32827, "text": "5————- >6 (Answer =2) HALT we find 3 which is smaller than 6 " }, { "code": null, "e": 32944, "s": 32890, "text": "3 (Answer = 1) HALT we find 2 which is smaller than 3" }, { "code": null, "e": 32957, "s": 32944, "text": "2 (Answer=1)" }, { "code": null, "e": 32974, "s": 32957, "text": "FINAL ANSWER = 2" }, { "code": null, "e": 32978, "s": 32974, "text": "C++" }, { "code": "#include<bits/stdc++.h>using namespace std; int non_overlapping_bridges(vector<pair<int,int>> &temp,int n){ //Step - 1 Sort the north side. sort(temp.begin(),temp.end()); // Create the Dp array to store the flow of non overlapping bridges. // ans-->Store the final max number of non-overlapping bridges. vector<int> dp(n+1,INT_MAX); int ans=0; for(int i=0;i<n;i++) { int idx=lower_bound(dp.begin(),dp.end(),temp[i].second)-dp.begin(); dp[idx]=temp[i].second; ans=max(ans,idx+1); } return ans;} int main(){ int n=4; vector<pair<int,int>> temp; temp.push_back(make_pair(6,2)); temp.push_back(make_pair(4,3)); temp.push_back(make_pair(2,6)); temp.push_back(make_pair(1,5)); cout<<non_overlapping_bridges(temp,n)<<endl; return 0;}", "e": 33785, "s": 32978, "text": null }, { "code": null, "e": 33796, "s": 33785, "text": "OUTPUT – 2" }, { "code": null, "e": 33823, "s": 33796, "text": "Time Complexity – O(NlogN)" }, { "code": null, "e": 33847, "s": 33823, "text": "Space Complexity – O(N)" }, { "code": null, "e": 34432, "s": 33847, "text": "Problem References: https://www.geeksforgeeks.org/dynamic-programming-set-14-variations-of-lis/Solution References: https://www.youtube.com/watch?v=w6tSmS86C4wThis article is contributed by Ayush Jauhari. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 34439, "s": 34432, "text": "varun9" }, { "code": null, "e": 34452, "s": 34439, "text": "diveshkumar4" }, { "code": null, "e": 34472, "s": 34452, "text": "hritikbhatnagar2182" }, { "code": null, "e": 34483, "s": 34472, "text": "ryanranaut" }, { "code": null, "e": 34503, "s": 34483, "text": "abhishek0719kadiyan" }, { "code": null, "e": 34512, "s": 34503, "text": "devy2k87" }, { "code": null, "e": 34516, "s": 34512, "text": "LIS" }, { "code": null, "e": 34536, "s": 34516, "text": "Dynamic Programming" }, { "code": null, "e": 34556, "s": 34536, "text": "Dynamic Programming" }, { "code": null, "e": 34654, "s": 34556, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34714, "s": 34654, "text": "Optimal Substructure Property in Dynamic Programming | DP-2" }, { "code": null, "e": 34749, "s": 34714, "text": "Optimal Binary Search Tree | DP-24" }, { "code": null, "e": 34770, "s": 34749, "text": "Min Cost Path | DP-6" }, { "code": null, "e": 34809, "s": 34770, "text": "Greedy approach vs Dynamic programming" }, { "code": null, "e": 34865, "s": 34809, "text": "Maximum Subarray Sum using Divide and Conquer algorithm" }, { "code": null, "e": 34892, "s": 34865, "text": "Word Break Problem | DP-32" }, { "code": null, "e": 34943, "s": 34892, "text": "3 Different ways to print Fibonacci series in Java" }, { "code": null, "e": 34994, "s": 34943, "text": "Maximum sum such that no two elements are adjacent" }, { "code": null, "e": 35052, "s": 34994, "text": "Top 50 Dynamic Programming Coding Problems for Interviews" } ]
Merge two unsorted linked lists to get a sorted list - GeeksforGeeks
27 Dec, 2021 Given two unsorted Linked List, the task is to merge them to get a sorted singly linked list.Examples: Input: List 1 = 3 -> 1 -> 5, List 2 = 6-> 2 -> 4 Output: 1 -> 2 -> 3 -> 4 -> 5 -> 6 Input: List 1 = 4 -> 7 -> 5, List 2 = 2-> 1 -> 8 -> 1 Output: 1 -> 1 -> 2 -> 4 -> 5 -> 7 -> 8 Naive Approach: The naive approach is to sort the given linked lists and then merge the two sorted linked lists together into one list in increasing order.To solve the problem mentioned above the naive method is to sort the two linked lists individually and merge the two linked lists together into one list which is in increasing order. Efficient Approach: To optimize the above method we will concatenate the two linked lists and then sort it using any sorting algorithm. Below are the steps: Concatenate the two lists by traversing the first list until we reach it’s a tail node and then point the next of the tail node to the head node of the second list. Store this concatenated list in the first list.Sort the above-merged linked list. Here, we will use a bubble sort. So, if node->next->data is less then node->data, then swap the data of the two adjacent nodes. Concatenate the two lists by traversing the first list until we reach it’s a tail node and then point the next of the tail node to the head node of the second list. Store this concatenated list in the first list. Sort the above-merged linked list. Here, we will use a bubble sort. So, if node->next->data is less then node->data, then swap the data of the two adjacent nodes. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Create structure for a nodestruct node { int data; node* next;}; // Function to print the linked listvoid setData(node* head){ node* tmp; // Store the head of the linked // list into a temporary node* // and iterate tmp = head; while (tmp != NULL) { cout << tmp->data << " -> "; tmp = tmp->next; }} // Function takes the head of the// LinkedList and the data as// argument and if no LinkedList// exists, it creates one with the// head pointing to first node.// If it exists already, it appends// given node at end of the last nodenode* getData(node* head, int num){ // Create a new node node* temp = new node; node* tail = head; // Insert data into the temporary // node and point it's next to NULL temp->data = num; temp->next = NULL; // Check if head is null, create a // linked list with temp as head // and tail of the list if (head == NULL) { head = temp; tail = temp; } // Else insert the temporary node // after the tail of the existing // node and make the temporary node // as the tail of the linked list else { while (tail != NULL) { if (tail->next == NULL) { tail->next = temp; tail = tail->next; } tail = tail->next; } } // Return the list return head;} // Function to concatenate the two listsnode* mergelists(node** head1, node** head2){ node* tail = *head1; // Iterate through the head1 to find the // last node join the next of last node // of head1 to the 1st node of head2 while (tail != NULL) { if (tail->next == NULL && head2 != NULL) { tail->next = *head2; break; } tail = tail->next; } // return the concatenated lists as a // single list - head1 return *head1;} // Sort the linked list using bubble sortvoid sortlist(node** head1){ node* curr = *head1; node* temp = *head1; // Compares two adjacent elements // and swaps if the first element // is greater than the other one. while (curr->next != NULL) { temp = curr->next; while (temp != NULL) { if (temp->data < curr->data) { int t = temp->data; temp->data = curr->data; curr->data = t; } temp = temp->next; } curr = curr->next; }} // Driver Codeint main(){ node* head1 = new node; node* head2 = new node; head1 = NULL; head2 = NULL; // Given Linked List 1 head1 = getData(head1, 4); head1 = getData(head1, 7); head1 = getData(head1, 5); // Given Linked List 2 head2 = getData(head2, 2); head2 = getData(head2, 1); head2 = getData(head2, 8); head2 = getData(head2, 1); // Merge the two lists // in a single list head1 = mergelists(&head1, &head2); // Sort the unsorted merged list sortlist(&head1); // Print the final // sorted merged list setData(head1); return 0;} // Java program for// the above approachclass GFG{ static node head1 = null;static node head2 = null; // Create structure for a nodestatic class node{ int data; node next;}; // Function to print// the linked liststatic void setData(node head){ node tmp; // Store the head of the linked // list into a temporary node // and iterate tmp = head; while (tmp != null) { System.out.print(tmp.data + " -> "); tmp = tmp.next; }} // Function takes the head of the// LinkedList and the data as// argument and if no LinkedList// exists, it creates one with the// head pointing to first node.// If it exists already, it appends// given node at end of the last nodestatic node getData(node head, int num){ // Create a new node node temp = new node(); node tail = head; // Insert data into the temporary // node and point it's next to null temp.data = num; temp.next = null; // Check if head is null, create a // linked list with temp as head // and tail of the list if (head == null) { head = temp; tail = temp; } // Else insert the temporary node // after the tail of the existing // node and make the temporary node // as the tail of the linked list else { while (tail != null) { if (tail.next == null) { tail.next = temp; tail = tail.next; } tail = tail.next; } } // Return the list return head;} // Function to concatenate// the two listsstatic node mergelists(){ node tail = head1; // Iterate through the // head1 to find the // last node join the // next of last node // of head1 to the // 1st node of head2 while (tail != null) { if (tail.next == null && head2 != null) { tail.next = head2; break; } tail = tail.next; } // return the concatenated // lists as a single list - head1 return head1;} // Sort the linked list// using bubble sortstatic void sortlist(){ node curr = head1; node temp = head1; // Compares two adjacent elements // and swaps if the first element // is greater than the other one. while (curr.next != null) { temp = curr.next; while (temp != null) { if (temp.data < curr.data) { int t = temp.data; temp.data = curr.data; curr.data = t; } temp = temp.next; } curr = curr.next; }} // Driver Codepublic static void main(String[] args){ // Given Linked List 1 head1 = getData(head1, 4); head1 = getData(head1, 7); head1 = getData(head1, 5); // Given Linked List 2 head2 = getData(head2, 2); head2 = getData(head2, 1); head2 = getData(head2, 8); head2 = getData(head2, 1); // Merge the two lists // in a single list head1 = mergelists(); // Sort the unsorted merged list sortlist(); // Print the final // sorted merged list setData(head1);}} // This code is contributed by shikhasingrajput # Python3 program for the# above approach # Create structure for a nodeclass node: def __init__(self, x): self.data = x self.next = None # Function to print the linked# listdef setData(head): # Store the head of the # linked list into a # temporary node* and # iterate tmp = head while (tmp != None): print(tmp.data, end = " -> ") tmp = tmp.next # Function takes the head of the# LinkedList and the data as# argument and if no LinkedList# exists, it creates one with the# head pointing to first node.# If it exists already, it appends# given node at end of the last nodedef getData(head, num): # Create a new node temp = node(-1) tail = head # Insert data into the temporary # node and point it's next to NULL temp.data = num temp.next = None # Check if head is null, create a # linked list with temp as head # and tail of the list if (head == None): head = temp tail = temp # Else insert the temporary node # after the tail of the existing # node and make the temporary node # as the tail of the linked list else: while (tail != None): if (tail.next == None): tail.next = temp tail = tail.next tail = tail.next # Return the list return head # Function to concatenate the# two listsdef mergelists(head1,head2): tail = head1 # Iterate through the head1 to # find the last node join the # next of last node of head1 # to the 1st node of head2 while (tail != None): if (tail.next == None and head2 != None): tail.next =head2 break tail = tail.next # return the concatenated # lists as a single list # - head1 return head1 # Sort the linked list using# bubble sortdef sortlist(head1): curr = head1 temp = head1 # Compares two adjacent elements # and swaps if the first element # is greater than the other one. while (curr.next != None): temp = curr.next while (temp != None): if (temp.data < curr.data): t = temp.data temp.data = curr.data curr.data = t temp = temp.next curr = curr.next # Driver Codeif __name__ == '__main__': head1 = node(-1) head2 = node(-1) head1 = None head2 = None # Given Linked List 1 head1 = getData(head1, 4) head1 = getData(head1, 7) head1 = getData(head1, 5) # Given Linked List 2 head2 = getData(head2, 2) head2 = getData(head2, 1) head2 = getData(head2, 8) head2 = getData(head2, 1) # Merge the two lists # in a single list head1 = mergelists(head1,head2) # Sort the unsorted merged list sortlist(head1) # Print the final # sorted merged list setData(head1) # This code is contributed by Mohit Kumar 29 // C# program for// the above approachusing System; class GFG{ static node head1 = null;static node head2 = null; // Create structure for a nodeclass node{ public int data; public node next;}; // Function to print// the linked liststatic void setData(node head){ node tmp; // Store the head of the linked // list into a temporary node // and iterate tmp = head; while (tmp != null) { Console.Write(tmp.data + " -> "); tmp = tmp.next; }} // Function takes the head of//the List and the data as// argument and if no List// exists, it creates one with the// head pointing to first node.// If it exists already, it appends// given node at end of the last nodestatic node getData(node head, int num){ // Create a new node node temp = new node(); node tail = head; // Insert data into the temporary // node and point it's next to null temp.data = num; temp.next = null; // Check if head is null, create a // linked list with temp as head // and tail of the list if (head == null) { head = temp; tail = temp; } // Else insert the temporary node // after the tail of the existing // node and make the temporary node // as the tail of the linked list else { while (tail != null) { if (tail.next == null) { tail.next = temp; tail = tail.next; } tail = tail.next; } } // Return the list return head;} // Function to concatenate// the two listsstatic node mergelists(){ node tail = head1; // Iterate through the // head1 to find the // last node join the // next of last node // of head1 to the // 1st node of head2 while (tail != null) { if (tail.next == null && head2 != null) { tail.next = head2; break; } tail = tail.next; } // return the concatenated // lists as a single list - head1 return head1;} // Sort the linked list// using bubble sortstatic void sortlist(){ node curr = head1; node temp = head1; // Compares two adjacent elements // and swaps if the first element // is greater than the other one. while (curr.next != null) { temp = curr.next; while (temp != null) { if (temp.data < curr.data) { int t = temp.data; temp.data = curr.data; curr.data = t; } temp = temp.next; } curr = curr.next; }} // Driver Codepublic static void Main(String[] args){ // Given Linked List 1 head1 = getData(head1, 4); head1 = getData(head1, 7); head1 = getData(head1, 5); // Given Linked List 2 head2 = getData(head2, 2); head2 = getData(head2, 1); head2 = getData(head2, 8); head2 = getData(head2, 1); // Merge the two lists // in a single list head1 = mergelists(); // Sort the unsorted merged list sortlist(); // Print the final // sorted merged list setData(head1);}} // This code is contributed by Amit Katiyar <script>// javascript program for// the above approach var head1 = null; var head2 = null; // Create structure for a node class node { constructor(){ this.data=0; this.next = null; } } // Function to print // the linked list function setData( head) { var tmp; // Store the head of the linked // list into a temporary node // and iterate tmp = head; while (tmp != null) { document.write(tmp.data + " -> "); tmp = tmp.next; } } // Function takes the head of the // LinkedList and the data as // argument and if no LinkedList // exists, it creates one with the // head pointing to first node. // If it exists already, it appends // given node at end of the last node function getData( head , num) { // Create a new node temp = new node(); var tail = head; // Insert data into the temporary // node and point it's next to null temp.data = num; temp.next = null; // Check if head is null, create a // linked list with temp as head // and tail of the list if (head == null) { head = temp; tail = temp; } // Else insert the temporary node // after the tail of the existing // node and make the temporary node // as the tail of the linked list else { while (tail != null) { if (tail.next == null) { tail.next = temp; tail = tail.next; } tail = tail.next; } } // Return the list return head; } // Function to concatenate // the two lists function mergelists() { tail = head1; // Iterate through the // head1 to find the // last node join the // next of last node // of head1 to the // 1st node of head2 while (tail != null) { if (tail.next == null && head2 != null) { tail.next = head2; break; } tail = tail.next; } // return the concatenated // lists as a single list - head1 return head1; } // Sort the linked list // using bubble sort function sortlist() { curr = head1; temp = head1; // Compares two adjacent elements // and swaps if the first element // is greater than the other one. while (curr.next != null) { temp = curr.next; while (temp != null) { if (temp.data < curr.data) { var t = temp.data; temp.data = curr.data; curr.data = t; } temp = temp.next; } curr = curr.next; } } // Driver Code // Given Linked List 1 head1 = getData(head1, 4); head1 = getData(head1, 7); head1 = getData(head1, 5); // Given Linked List 2 head2 = getData(head2, 2); head2 = getData(head2, 1); head2 = getData(head2, 8); head2 = getData(head2, 1); // Merge the two lists // in a single list head1 = mergelists(); // Sort the unsorted merged list sortlist(); // Print the final // sorted merged list setData(head1); // This code is contributed by umadevi9616.</script> 1 -> 1 -> 2 -> 4 -> 5 -> 7 -> 8 Time Complexity: O((M+N)^2) where M and N are the lengths of the two given linked lists. We are merging the two list and performing bubble sort on the merged list. The time complexity of bubble sort is quadratic.Auxiliary Space: O(1) shikhasingrajput amit143katiyar mohit kumar 29 umadevi9616 pankajsharmagfg abhinavjain194 simranarora5sos simmytarika5 Amazon-Question interview-preparation Algorithms Competitive Programming Data Structures Linked List Sorting Data Structures Linked List Sorting Algorithms Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments DSA Sheet by Love Babbar Quadratic Probing in Hashing SCAN (Elevator) Disk Scheduling Algorithms K means Clustering - Introduction Difference between Informed and Uninformed Search in AI Practice for cracking any coding interview Arrow operator -> in C/C++ with Examples Competitive Programming - A Complete Guide Modulo 10^9+7 (1000000007) Top 10 Algorithms and Data Structures for Competitive Programming
[ { "code": null, "e": 24690, "s": 24662, "text": "\n27 Dec, 2021" }, { "code": null, "e": 24794, "s": 24690, "text": "Given two unsorted Linked List, the task is to merge them to get a sorted singly linked list.Examples: " }, { "code": null, "e": 24878, "s": 24794, "text": "Input: List 1 = 3 -> 1 -> 5, List 2 = 6-> 2 -> 4 Output: 1 -> 2 -> 3 -> 4 -> 5 -> 6" }, { "code": null, "e": 24974, "s": 24878, "text": "Input: List 1 = 4 -> 7 -> 5, List 2 = 2-> 1 -> 8 -> 1 Output: 1 -> 1 -> 2 -> 4 -> 5 -> 7 -> 8 " }, { "code": null, "e": 25312, "s": 24974, "text": "Naive Approach: The naive approach is to sort the given linked lists and then merge the two sorted linked lists together into one list in increasing order.To solve the problem mentioned above the naive method is to sort the two linked lists individually and merge the two linked lists together into one list which is in increasing order." }, { "code": null, "e": 25470, "s": 25312, "text": "Efficient Approach: To optimize the above method we will concatenate the two linked lists and then sort it using any sorting algorithm. Below are the steps: " }, { "code": null, "e": 25845, "s": 25470, "text": "Concatenate the two lists by traversing the first list until we reach it’s a tail node and then point the next of the tail node to the head node of the second list. Store this concatenated list in the first list.Sort the above-merged linked list. Here, we will use a bubble sort. So, if node->next->data is less then node->data, then swap the data of the two adjacent nodes." }, { "code": null, "e": 26058, "s": 25845, "text": "Concatenate the two lists by traversing the first list until we reach it’s a tail node and then point the next of the tail node to the head node of the second list. Store this concatenated list in the first list." }, { "code": null, "e": 26221, "s": 26058, "text": "Sort the above-merged linked list. Here, we will use a bubble sort. So, if node->next->data is less then node->data, then swap the data of the two adjacent nodes." }, { "code": null, "e": 26272, "s": 26221, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 26276, "s": 26272, "text": "C++" }, { "code": null, "e": 26281, "s": 26276, "text": "Java" }, { "code": null, "e": 26289, "s": 26281, "text": "Python3" }, { "code": null, "e": 26292, "s": 26289, "text": "C#" }, { "code": null, "e": 26303, "s": 26292, "text": "Javascript" }, { "code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Create structure for a nodestruct node { int data; node* next;}; // Function to print the linked listvoid setData(node* head){ node* tmp; // Store the head of the linked // list into a temporary node* // and iterate tmp = head; while (tmp != NULL) { cout << tmp->data << \" -> \"; tmp = tmp->next; }} // Function takes the head of the// LinkedList and the data as// argument and if no LinkedList// exists, it creates one with the// head pointing to first node.// If it exists already, it appends// given node at end of the last nodenode* getData(node* head, int num){ // Create a new node node* temp = new node; node* tail = head; // Insert data into the temporary // node and point it's next to NULL temp->data = num; temp->next = NULL; // Check if head is null, create a // linked list with temp as head // and tail of the list if (head == NULL) { head = temp; tail = temp; } // Else insert the temporary node // after the tail of the existing // node and make the temporary node // as the tail of the linked list else { while (tail != NULL) { if (tail->next == NULL) { tail->next = temp; tail = tail->next; } tail = tail->next; } } // Return the list return head;} // Function to concatenate the two listsnode* mergelists(node** head1, node** head2){ node* tail = *head1; // Iterate through the head1 to find the // last node join the next of last node // of head1 to the 1st node of head2 while (tail != NULL) { if (tail->next == NULL && head2 != NULL) { tail->next = *head2; break; } tail = tail->next; } // return the concatenated lists as a // single list - head1 return *head1;} // Sort the linked list using bubble sortvoid sortlist(node** head1){ node* curr = *head1; node* temp = *head1; // Compares two adjacent elements // and swaps if the first element // is greater than the other one. while (curr->next != NULL) { temp = curr->next; while (temp != NULL) { if (temp->data < curr->data) { int t = temp->data; temp->data = curr->data; curr->data = t; } temp = temp->next; } curr = curr->next; }} // Driver Codeint main(){ node* head1 = new node; node* head2 = new node; head1 = NULL; head2 = NULL; // Given Linked List 1 head1 = getData(head1, 4); head1 = getData(head1, 7); head1 = getData(head1, 5); // Given Linked List 2 head2 = getData(head2, 2); head2 = getData(head2, 1); head2 = getData(head2, 8); head2 = getData(head2, 1); // Merge the two lists // in a single list head1 = mergelists(&head1, &head2); // Sort the unsorted merged list sortlist(&head1); // Print the final // sorted merged list setData(head1); return 0;}", "e": 29469, "s": 26303, "text": null }, { "code": "// Java program for// the above approachclass GFG{ static node head1 = null;static node head2 = null; // Create structure for a nodestatic class node{ int data; node next;}; // Function to print// the linked liststatic void setData(node head){ node tmp; // Store the head of the linked // list into a temporary node // and iterate tmp = head; while (tmp != null) { System.out.print(tmp.data + \" -> \"); tmp = tmp.next; }} // Function takes the head of the// LinkedList and the data as// argument and if no LinkedList// exists, it creates one with the// head pointing to first node.// If it exists already, it appends// given node at end of the last nodestatic node getData(node head, int num){ // Create a new node node temp = new node(); node tail = head; // Insert data into the temporary // node and point it's next to null temp.data = num; temp.next = null; // Check if head is null, create a // linked list with temp as head // and tail of the list if (head == null) { head = temp; tail = temp; } // Else insert the temporary node // after the tail of the existing // node and make the temporary node // as the tail of the linked list else { while (tail != null) { if (tail.next == null) { tail.next = temp; tail = tail.next; } tail = tail.next; } } // Return the list return head;} // Function to concatenate// the two listsstatic node mergelists(){ node tail = head1; // Iterate through the // head1 to find the // last node join the // next of last node // of head1 to the // 1st node of head2 while (tail != null) { if (tail.next == null && head2 != null) { tail.next = head2; break; } tail = tail.next; } // return the concatenated // lists as a single list - head1 return head1;} // Sort the linked list// using bubble sortstatic void sortlist(){ node curr = head1; node temp = head1; // Compares two adjacent elements // and swaps if the first element // is greater than the other one. while (curr.next != null) { temp = curr.next; while (temp != null) { if (temp.data < curr.data) { int t = temp.data; temp.data = curr.data; curr.data = t; } temp = temp.next; } curr = curr.next; }} // Driver Codepublic static void main(String[] args){ // Given Linked List 1 head1 = getData(head1, 4); head1 = getData(head1, 7); head1 = getData(head1, 5); // Given Linked List 2 head2 = getData(head2, 2); head2 = getData(head2, 1); head2 = getData(head2, 8); head2 = getData(head2, 1); // Merge the two lists // in a single list head1 = mergelists(); // Sort the unsorted merged list sortlist(); // Print the final // sorted merged list setData(head1);}} // This code is contributed by shikhasingrajput", "e": 32297, "s": 29469, "text": null }, { "code": "# Python3 program for the# above approach # Create structure for a nodeclass node: def __init__(self, x): self.data = x self.next = None # Function to print the linked# listdef setData(head): # Store the head of the # linked list into a # temporary node* and # iterate tmp = head while (tmp != None): print(tmp.data, end = \" -> \") tmp = tmp.next # Function takes the head of the# LinkedList and the data as# argument and if no LinkedList# exists, it creates one with the# head pointing to first node.# If it exists already, it appends# given node at end of the last nodedef getData(head, num): # Create a new node temp = node(-1) tail = head # Insert data into the temporary # node and point it's next to NULL temp.data = num temp.next = None # Check if head is null, create a # linked list with temp as head # and tail of the list if (head == None): head = temp tail = temp # Else insert the temporary node # after the tail of the existing # node and make the temporary node # as the tail of the linked list else: while (tail != None): if (tail.next == None): tail.next = temp tail = tail.next tail = tail.next # Return the list return head # Function to concatenate the# two listsdef mergelists(head1,head2): tail = head1 # Iterate through the head1 to # find the last node join the # next of last node of head1 # to the 1st node of head2 while (tail != None): if (tail.next == None and head2 != None): tail.next =head2 break tail = tail.next # return the concatenated # lists as a single list # - head1 return head1 # Sort the linked list using# bubble sortdef sortlist(head1): curr = head1 temp = head1 # Compares two adjacent elements # and swaps if the first element # is greater than the other one. while (curr.next != None): temp = curr.next while (temp != None): if (temp.data < curr.data): t = temp.data temp.data = curr.data curr.data = t temp = temp.next curr = curr.next # Driver Codeif __name__ == '__main__': head1 = node(-1) head2 = node(-1) head1 = None head2 = None # Given Linked List 1 head1 = getData(head1, 4) head1 = getData(head1, 7) head1 = getData(head1, 5) # Given Linked List 2 head2 = getData(head2, 2) head2 = getData(head2, 1) head2 = getData(head2, 8) head2 = getData(head2, 1) # Merge the two lists # in a single list head1 = mergelists(head1,head2) # Sort the unsorted merged list sortlist(head1) # Print the final # sorted merged list setData(head1) # This code is contributed by Mohit Kumar 29", "e": 35195, "s": 32297, "text": null }, { "code": "// C# program for// the above approachusing System; class GFG{ static node head1 = null;static node head2 = null; // Create structure for a nodeclass node{ public int data; public node next;}; // Function to print// the linked liststatic void setData(node head){ node tmp; // Store the head of the linked // list into a temporary node // and iterate tmp = head; while (tmp != null) { Console.Write(tmp.data + \" -> \"); tmp = tmp.next; }} // Function takes the head of//the List and the data as// argument and if no List// exists, it creates one with the// head pointing to first node.// If it exists already, it appends// given node at end of the last nodestatic node getData(node head, int num){ // Create a new node node temp = new node(); node tail = head; // Insert data into the temporary // node and point it's next to null temp.data = num; temp.next = null; // Check if head is null, create a // linked list with temp as head // and tail of the list if (head == null) { head = temp; tail = temp; } // Else insert the temporary node // after the tail of the existing // node and make the temporary node // as the tail of the linked list else { while (tail != null) { if (tail.next == null) { tail.next = temp; tail = tail.next; } tail = tail.next; } } // Return the list return head;} // Function to concatenate// the two listsstatic node mergelists(){ node tail = head1; // Iterate through the // head1 to find the // last node join the // next of last node // of head1 to the // 1st node of head2 while (tail != null) { if (tail.next == null && head2 != null) { tail.next = head2; break; } tail = tail.next; } // return the concatenated // lists as a single list - head1 return head1;} // Sort the linked list// using bubble sortstatic void sortlist(){ node curr = head1; node temp = head1; // Compares two adjacent elements // and swaps if the first element // is greater than the other one. while (curr.next != null) { temp = curr.next; while (temp != null) { if (temp.data < curr.data) { int t = temp.data; temp.data = curr.data; curr.data = t; } temp = temp.next; } curr = curr.next; }} // Driver Codepublic static void Main(String[] args){ // Given Linked List 1 head1 = getData(head1, 4); head1 = getData(head1, 7); head1 = getData(head1, 5); // Given Linked List 2 head2 = getData(head2, 2); head2 = getData(head2, 1); head2 = getData(head2, 8); head2 = getData(head2, 1); // Merge the two lists // in a single list head1 = mergelists(); // Sort the unsorted merged list sortlist(); // Print the final // sorted merged list setData(head1);}} // This code is contributed by Amit Katiyar", "e": 38394, "s": 35195, "text": null }, { "code": "<script>// javascript program for// the above approach var head1 = null; var head2 = null; // Create structure for a node class node { constructor(){ this.data=0; this.next = null; } } // Function to print // the linked list function setData( head) { var tmp; // Store the head of the linked // list into a temporary node // and iterate tmp = head; while (tmp != null) { document.write(tmp.data + \" -> \"); tmp = tmp.next; } } // Function takes the head of the // LinkedList and the data as // argument and if no LinkedList // exists, it creates one with the // head pointing to first node. // If it exists already, it appends // given node at end of the last node function getData( head , num) { // Create a new node temp = new node(); var tail = head; // Insert data into the temporary // node and point it's next to null temp.data = num; temp.next = null; // Check if head is null, create a // linked list with temp as head // and tail of the list if (head == null) { head = temp; tail = temp; } // Else insert the temporary node // after the tail of the existing // node and make the temporary node // as the tail of the linked list else { while (tail != null) { if (tail.next == null) { tail.next = temp; tail = tail.next; } tail = tail.next; } } // Return the list return head; } // Function to concatenate // the two lists function mergelists() { tail = head1; // Iterate through the // head1 to find the // last node join the // next of last node // of head1 to the // 1st node of head2 while (tail != null) { if (tail.next == null && head2 != null) { tail.next = head2; break; } tail = tail.next; } // return the concatenated // lists as a single list - head1 return head1; } // Sort the linked list // using bubble sort function sortlist() { curr = head1; temp = head1; // Compares two adjacent elements // and swaps if the first element // is greater than the other one. while (curr.next != null) { temp = curr.next; while (temp != null) { if (temp.data < curr.data) { var t = temp.data; temp.data = curr.data; curr.data = t; } temp = temp.next; } curr = curr.next; } } // Driver Code // Given Linked List 1 head1 = getData(head1, 4); head1 = getData(head1, 7); head1 = getData(head1, 5); // Given Linked List 2 head2 = getData(head2, 2); head2 = getData(head2, 1); head2 = getData(head2, 8); head2 = getData(head2, 1); // Merge the two lists // in a single list head1 = mergelists(); // Sort the unsorted merged list sortlist(); // Print the final // sorted merged list setData(head1); // This code is contributed by umadevi9616.</script>", "e": 41881, "s": 38394, "text": null }, { "code": null, "e": 41913, "s": 41881, "text": "1 -> 1 -> 2 -> 4 -> 5 -> 7 -> 8" }, { "code": null, "e": 42149, "s": 41915, "text": "Time Complexity: O((M+N)^2) where M and N are the lengths of the two given linked lists. We are merging the two list and performing bubble sort on the merged list. The time complexity of bubble sort is quadratic.Auxiliary Space: O(1)" }, { "code": null, "e": 42166, "s": 42149, "text": "shikhasingrajput" }, { "code": null, "e": 42181, "s": 42166, "text": "amit143katiyar" }, { "code": null, "e": 42196, "s": 42181, "text": "mohit kumar 29" }, { "code": null, "e": 42208, "s": 42196, "text": "umadevi9616" }, { "code": null, "e": 42224, "s": 42208, "text": "pankajsharmagfg" }, { "code": null, "e": 42239, "s": 42224, "text": "abhinavjain194" }, { "code": null, "e": 42255, "s": 42239, "text": "simranarora5sos" }, { "code": null, "e": 42268, "s": 42255, "text": "simmytarika5" }, { "code": null, "e": 42284, "s": 42268, "text": "Amazon-Question" }, { "code": null, "e": 42306, "s": 42284, "text": "interview-preparation" }, { "code": null, "e": 42317, "s": 42306, "text": "Algorithms" }, { "code": null, "e": 42341, "s": 42317, "text": "Competitive Programming" }, { "code": null, "e": 42357, "s": 42341, "text": "Data Structures" }, { "code": null, "e": 42369, "s": 42357, "text": "Linked List" }, { "code": null, "e": 42377, "s": 42369, "text": "Sorting" }, { "code": null, "e": 42393, "s": 42377, "text": "Data Structures" }, { "code": null, "e": 42405, "s": 42393, "text": "Linked List" }, { "code": null, "e": 42413, "s": 42405, "text": "Sorting" }, { "code": null, "e": 42424, "s": 42413, "text": "Algorithms" }, { "code": null, "e": 42522, "s": 42424, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 42531, "s": 42522, "text": "Comments" }, { "code": null, "e": 42544, "s": 42531, "text": "Old Comments" }, { "code": null, "e": 42569, "s": 42544, "text": "DSA Sheet by Love Babbar" }, { "code": null, "e": 42598, "s": 42569, "text": "Quadratic Probing in Hashing" }, { "code": null, "e": 42641, "s": 42598, "text": "SCAN (Elevator) Disk Scheduling Algorithms" }, { "code": null, "e": 42675, "s": 42641, "text": "K means Clustering - Introduction" }, { "code": null, "e": 42731, "s": 42675, "text": "Difference between Informed and Uninformed Search in AI" }, { "code": null, "e": 42774, "s": 42731, "text": "Practice for cracking any coding interview" }, { "code": null, "e": 42815, "s": 42774, "text": "Arrow operator -> in C/C++ with Examples" }, { "code": null, "e": 42858, "s": 42815, "text": "Competitive Programming - A Complete Guide" }, { "code": null, "e": 42885, "s": 42858, "text": "Modulo 10^9+7 (1000000007)" } ]
XML DOM - Set Node
In this chapter, we will study about how to change the values of nodes in an XML DOM object. Node value can be changed as follows − var value = node.nodeValue; If node is an Attribute then the value variable will be the value of the attribute; if node is a Text node it will be the text content; if node is an Element it will be null. Following sections will demonstrate the node value setting for each node type (attribute, text node and element). The node.xml used in all the following examples is as below − <Company> <Employee category = "Technical"> <FirstName>Tanmay</FirstName> <LastName>Patil</LastName> <ContactNo>1234567890</ContactNo> <Email>[email protected]</Email> </Employee> <Employee category = "Non-Technical"> <FirstName>Taniya</FirstName> <LastName>Mishra</LastName> <ContactNo>1234667898</ContactNo> <Email>[email protected]</Email> </Employee> <Employee category = "Management"> <FirstName>Tanisha</FirstName> <LastName>Sharma</LastName> <ContactNo>1234562350</ContactNo> <Email>[email protected]</Email> </Employee> </Company> When we, say the change value of Node element we mean to edit the text content of an element (which is also called the text node). Following example demonstrates how to change the text node of an element. The following example (set_text_node_example.htm) parses an XML document (node.xml) into an XML DOM object and change the value of an element's text node. In this case, Email of each Employee to [email protected] and print the values. <!DOCTYPE html> <html> <head> <script> function loadXMLDoc(filename) { if (window.XMLHttpRequest) { xhttp = new XMLHttpRequest(); } else // code for IE5 and IE6 { xhttp = new ActiveXObject("Microsoft.XMLHTTP"); } xhttp.open("GET",filename,false); xhttp.send(); return xhttp.responseXML; } </script> </head> <body> <script> xmlDoc = loadXMLDoc("/dom/node.xml"); x = xmlDoc.getElementsByTagName("Email"); for(i = 0;i<x.length;i++) { x[i].childNodes[0].nodeValue = "[email protected]"; document.write(i+'); document.write(x[i].childNodes[0].nodeValue); document.write('<br>'); } </script> </body> </html> Save this file as set_text_node_example.htm on the server path (this file and node.xml should be on the same path in your server). You will receive the following output − 0) [email protected] 1) [email protected] 2) [email protected] The following example demonstrates how to change the attribute node of an element. The following example (set_attribute_example.htm) parses an XML document (node.xml) into an XML DOM object and changes the value of an element's attribute node. In this case, the Category of each Employee to admin-0, admin-1, admin-2 respectively and print the values. <!DOCTYPE html> <html> <head> <script> function loadXMLDoc(filename) { if (window.XMLHttpRequest) { xhttp = new XMLHttpRequest(); } else // code for IE5 and IE6 { xhttp = new ActiveXObject("Microsoft.XMLHTTP"); } xhttp.open("GET",filename,false); xhttp.send(); return xhttp.responseXML; } </script> </head> <body> <script> xmlDoc = loadXMLDoc("/dom/node.xml"); x = xmlDoc.getElementsByTagName("Employee"); for(i = 0 ;i<x.length;i++){ newcategory = x[i].getAttributeNode('category'); newcategory.nodeValue = "admin-"+i; document.write(i+'); document.write(x[i].getAttributeNode('category').nodeValue); document.write('<br>'); } </script> </body> </html> Save this file as set_node_attribute_example.htm on the server path (this file and node.xml should be on the same path in your server). The result would be as below − 0) admin-0 1) admin-1 2) admin-2 41 Lectures 5 hours Abhishek And Pukhraj 33 Lectures 3.5 hours Abhishek And Pukhraj 15 Lectures 1 hours Zach Miller 15 Lectures 4 hours Prof. Paul Cline, Ed.D 13 Lectures 4 hours Prof. Paul Cline, Ed.D 17 Lectures 2 hours Laurence Svekis Print Add Notes Bookmark this page
[ { "code": null, "e": 2420, "s": 2288, "text": "In this chapter, we will study about how to change the values of nodes in an XML DOM object. Node value can be changed as follows −" }, { "code": null, "e": 2449, "s": 2420, "text": "var value = node.nodeValue;\n" }, { "code": null, "e": 2624, "s": 2449, "text": "If node is an Attribute then the value variable will be the value of the attribute; if node is a Text node it will be the text content; if node is an Element it will be null." }, { "code": null, "e": 2738, "s": 2624, "text": "Following sections will demonstrate the node value setting for each node type (attribute, text node and element)." }, { "code": null, "e": 2800, "s": 2738, "text": "The node.xml used in all the following examples is as below −" }, { "code": null, "e": 3446, "s": 2800, "text": "<Company>\n <Employee category = \"Technical\">\n <FirstName>Tanmay</FirstName>\n <LastName>Patil</LastName>\n <ContactNo>1234567890</ContactNo>\n <Email>[email protected]</Email>\n </Employee>\n \n <Employee category = \"Non-Technical\">\n <FirstName>Taniya</FirstName>\n <LastName>Mishra</LastName>\n <ContactNo>1234667898</ContactNo>\n <Email>[email protected]</Email>\n </Employee>\n \n <Employee category = \"Management\">\n <FirstName>Tanisha</FirstName>\n <LastName>Sharma</LastName>\n <ContactNo>1234562350</ContactNo>\n <Email>[email protected]</Email>\n </Employee>\n</Company>" }, { "code": null, "e": 3651, "s": 3446, "text": "When we, say the change value of Node element we mean to edit the text content of an element (which is also called the text node). Following example demonstrates how to change the text node of an element." }, { "code": null, "e": 3884, "s": 3651, "text": "The following example (set_text_node_example.htm) parses an XML document (node.xml) into an XML DOM object and change the value of an element's text node. In this case, Email of each Employee to [email protected] and print the values." }, { "code": null, "e": 4731, "s": 3884, "text": "<!DOCTYPE html>\n<html>\n <head>\n <script>\n function loadXMLDoc(filename) {\n if (window.XMLHttpRequest) {\n xhttp = new XMLHttpRequest();\n } else // code for IE5 and IE6 {\n xhttp = new ActiveXObject(\"Microsoft.XMLHTTP\");\n }\n xhttp.open(\"GET\",filename,false);\n xhttp.send();\n return xhttp.responseXML;\n }\n </script>\n </head>\n <body>\n <script>\n xmlDoc = loadXMLDoc(\"/dom/node.xml\");\n\n x = xmlDoc.getElementsByTagName(\"Email\");\n for(i = 0;i<x.length;i++) {\t\n\t\n x[i].childNodes[0].nodeValue = \"[email protected]\";\n document.write(i+');\n document.write(x[i].childNodes[0].nodeValue);\n document.write('<br>');\n }\n\t\n </script>\n </body>\n</html>" }, { "code": null, "e": 4902, "s": 4731, "text": "Save this file as set_text_node_example.htm on the server path (this file and node.xml should be on the same path in your server). You will receive the following output −" }, { "code": null, "e": 4960, "s": 4902, "text": "0) [email protected]\n1) [email protected]\n2) [email protected]\n" }, { "code": null, "e": 5043, "s": 4960, "text": "The following example demonstrates how to change the attribute node of an element." }, { "code": null, "e": 5312, "s": 5043, "text": "The following example (set_attribute_example.htm) parses an XML document (node.xml) into an XML DOM object and changes the value of an element's attribute node. In this case, the Category of each Employee to admin-0, admin-1, admin-2 respectively and print the values." }, { "code": null, "e": 6225, "s": 5312, "text": "<!DOCTYPE html>\n<html>\n <head>\n <script>\n function loadXMLDoc(filename) {\n if (window.XMLHttpRequest) {\n xhttp = new XMLHttpRequest();\n } else // code for IE5 and IE6 {\n xhttp = new ActiveXObject(\"Microsoft.XMLHTTP\");\n }\n xhttp.open(\"GET\",filename,false);\n xhttp.send();\n return xhttp.responseXML;\n }\n </script>\n </head>\n <body>\n <script>\n xmlDoc = loadXMLDoc(\"/dom/node.xml\");\n\n x = xmlDoc.getElementsByTagName(\"Employee\");\n for(i = 0 ;i<x.length;i++){\t\n\t\n newcategory = x[i].getAttributeNode('category');\n newcategory.nodeValue = \"admin-\"+i;\n document.write(i+');\n document.write(x[i].getAttributeNode('category').nodeValue);\n document.write('<br>');\n }\n\t\n </script>\n </body>\n</html>" }, { "code": null, "e": 6392, "s": 6225, "text": "Save this file as set_node_attribute_example.htm on the server path (this file and node.xml should be on the same path in your server). The result would be as below −" }, { "code": null, "e": 6426, "s": 6392, "text": "0) admin-0\n1) admin-1\n2) admin-2\n" }, { "code": null, "e": 6459, "s": 6426, "text": "\n 41 Lectures \n 5 hours \n" }, { "code": null, "e": 6481, "s": 6459, "text": " Abhishek And Pukhraj" }, { "code": null, "e": 6516, "s": 6481, "text": "\n 33 Lectures \n 3.5 hours \n" }, { "code": null, "e": 6538, "s": 6516, "text": " Abhishek And Pukhraj" }, { "code": null, "e": 6571, "s": 6538, "text": "\n 15 Lectures \n 1 hours \n" }, { "code": null, "e": 6584, "s": 6571, "text": " Zach Miller" }, { "code": null, "e": 6617, "s": 6584, "text": "\n 15 Lectures \n 4 hours \n" }, { "code": null, "e": 6641, "s": 6617, "text": " Prof. Paul Cline, Ed.D" }, { "code": null, "e": 6674, "s": 6641, "text": "\n 13 Lectures \n 4 hours \n" }, { "code": null, "e": 6698, "s": 6674, "text": " Prof. Paul Cline, Ed.D" }, { "code": null, "e": 6731, "s": 6698, "text": "\n 17 Lectures \n 2 hours \n" }, { "code": null, "e": 6748, "s": 6731, "text": " Laurence Svekis" }, { "code": null, "e": 6755, "s": 6748, "text": " Print" }, { "code": null, "e": 6766, "s": 6755, "text": " Add Notes" } ]
Numpy | Array Creation - GeeksforGeeks
15 Nov, 2018 Array creation using List : Arrays are used to store multiple values in one single variable.Python does not have built-in support for Arrays, but Python lists can be used instead.Example : arr = [1, 2, 3, 4, 5] arr1 = ["geeks", "for", "geeks"] Output: 1 2 3 4 5 Array creation using array functions :array(data type, value list) function is used to create an array with data type and value list specified in its arguments.Example : Output: The new created array is : 1 2 3 1 5 Array creation using numpy methods :NumPy offers several functions to create arrays with initial placeholder content. These minimize the necessity of growing arrays, an expensive operation. For example: np.zeros,np.empty etc. numpy.empty(shape, dtype = float, order = ‘C’) : Return a new array of given shape and type, with random values. Output : Matrix b : [ 0 1079574528] Matrix a : [[0 0] [0 0]] Matrix a : [[ 0. 0. 0.] [ 0. 0. 0.] [ 0. 0. 0.]] numpy.zeros(shape, dtype = None, order = ‘C’) : Return a new array of given shape and type, with zeros. Output : Matrix b : [0 0] Matrix a : [[0 0] [0 0]] Matrix c : [[ 0. 0. 0.] [ 0. 0. 0.] [ 0. 0. 0.]] Reshaping array: We can use reshape method to reshape an array. Consider an array with shape (a1, a2, a3, ..., aN). We can reshape and convert it into another array with shape (b1, b2, b3, ..., bM).The only required condition is: a1 x a2 x a3 ... x aN = b1 x b2 x b3 ... x bM . (i.e original size of array remains unchanged.) numpy.reshape(array, shape, order = ‘C’) : Shapes an array without changing data of array. Output : Original array : [0 1 2 3 4 5 6 7] array reshaped with 2 rows and 4 columns : [[0 1 2 3] [4 5 6 7]] array reshaped with 2 rows and 4 columns : [[0 1] [2 3] [4 5] [6 7]] Original array reshaped to 3D : [[[0 1] [2 3]] [[4 5] [6 7]]] To create sequences of numbers, NumPy provides a function analogous to range that returns arrays instead of lists.arange returns evenly spaced values within a given interval. step size is specified.linspace returns evenly spaced values within a given interval. num no. of elements are returned. arange([start,] stop[, step,][, dtype]) : Returns an array with evenly spaced elements as per the interval. The interval mentioned is half opened i.e. [Start, Stop) Output : A [[0 1] [2 3]] A [4 5 6 7 8 9] A [ 4 7 10 13 16 19] numpy.linspace(start, stop, num = 50, endpoint = True, retstep = False, dtype = None) : Returns number spaces evenly w.r.t interval. Similiar to arange but instead of step it uses sample number. Output : B (array([ 2. , 2.25, 2.5 , 2.75, 3. ]), 0.25) A [ 0. 0.22039774 0.42995636 0.6183698 0.77637192 0.8961922 0.9719379 0.99988386 0.9786557 0.90929743] Flatten array: We can use flatten method to get a copy of array collapsed into one dimension. It accepts order argument. Default value is ‘C’ (for row-major order). Use ‘F’ for column major order. numpy.ndarray.flatten(order = ‘C’) : Return a copy of the array collapsed into one dimension. Output : [1, 2, 3, 4] [1, 3, 2, 4] Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Difference between sh and bash Python - Add values to Dictionary of List How to Install Scala IDE For Eclipse? How to Test React Components using Jest ? Spring @Controller Annotation with Example What is External JavaScript ? Create a dictionary with list comprehension in Python Converting an image to a Torch Tensor in Python How to Calculate Cosine Similarity in Python? 10 Best C and C++ Books For Beginners & Advanced Programmers
[ { "code": null, "e": 41448, "s": 41420, "text": "\n15 Nov, 2018" }, { "code": null, "e": 41637, "s": 41448, "text": "Array creation using List : Arrays are used to store multiple values in one single variable.Python does not have built-in support for Arrays, but Python lists can be used instead.Example :" }, { "code": null, "e": 41693, "s": 41637, "text": "arr = [1, 2, 3, 4, 5]\narr1 = [\"geeks\", \"for\", \"geeks\"]\n" }, { "code": null, "e": 41701, "s": 41693, "text": "Output:" }, { "code": null, "e": 41712, "s": 41701, "text": "1\n2\n3\n4\n5\n" }, { "code": null, "e": 41883, "s": 41712, "text": " Array creation using array functions :array(data type, value list) function is used to create an array with data type and value list specified in its arguments.Example :" }, { "code": null, "e": 41891, "s": 41883, "text": "Output:" }, { "code": null, "e": 41929, "s": 41891, "text": "The new created array is : 1 2 3 1 5\n" }, { "code": null, "e": 42156, "s": 41929, "text": " Array creation using numpy methods :NumPy offers several functions to create arrays with initial placeholder content. These minimize the necessity of growing arrays, an expensive operation. For example: np.zeros,np.empty etc." }, { "code": null, "e": 42269, "s": 42156, "text": "numpy.empty(shape, dtype = float, order = ‘C’) : Return a new array of given shape and type, with random values." }, { "code": null, "e": 42278, "s": 42269, "text": "Output :" }, { "code": null, "e": 42404, "s": 42278, "text": "Matrix b : \n [ 0 1079574528]\n\nMatrix a : \n [[0 0]\n [0 0]]\n\nMatrix a : \n [[ 0. 0. 0.]\n [ 0. 0. 0.]\n [ 0. 0. 0.]]" }, { "code": null, "e": 42508, "s": 42404, "text": "numpy.zeros(shape, dtype = None, order = ‘C’) : Return a new array of given shape and type, with zeros." }, { "code": null, "e": 42517, "s": 42508, "text": "Output :" }, { "code": null, "e": 42626, "s": 42517, "text": "Matrix b : \n [0 0]\n\nMatrix a : \n [[0 0]\n [0 0]]\n\nMatrix c : \n [[ 0. 0. 0.]\n [ 0. 0. 0.]\n [ 0. 0. 0.]]\n" }, { "code": null, "e": 42953, "s": 42626, "text": " Reshaping array: We can use reshape method to reshape an array. Consider an array with shape (a1, a2, a3, ..., aN). We can reshape and convert it into another array with shape (b1, b2, b3, ..., bM).The only required condition is: a1 x a2 x a3 ... x aN = b1 x b2 x b3 ... x bM . (i.e original size of array remains unchanged.)" }, { "code": null, "e": 43044, "s": 42953, "text": "numpy.reshape(array, shape, order = ‘C’) : Shapes an array without changing data of array." }, { "code": null, "e": 43053, "s": 43044, "text": "Output :" }, { "code": null, "e": 43306, "s": 43053, "text": "Original array : \n [0 1 2 3 4 5 6 7]\n\narray reshaped with 2 rows and 4 columns : \n [[0 1 2 3]\n [4 5 6 7]]\n\narray reshaped with 2 rows and 4 columns : \n [[0 1]\n [2 3]\n [4 5]\n [6 7]]\n\nOriginal array reshaped to 3D : \n [[[0 1]\n [2 3]]\n\n [[4 5]\n [6 7]]]\n" }, { "code": null, "e": 43601, "s": 43306, "text": "To create sequences of numbers, NumPy provides a function analogous to range that returns arrays instead of lists.arange returns evenly spaced values within a given interval. step size is specified.linspace returns evenly spaced values within a given interval. num no. of elements are returned." }, { "code": null, "e": 43766, "s": 43601, "text": "arange([start,] stop[, step,][, dtype]) : Returns an array with evenly spaced elements as per the interval. The interval mentioned is half opened i.e. [Start, Stop)" }, { "code": null, "e": 43775, "s": 43766, "text": "Output :" }, { "code": null, "e": 43837, "s": 43775, "text": "A\n [[0 1]\n [2 3]]\n\nA\n [4 5 6 7 8 9]\n\nA\n [ 4 7 10 13 16 19]\n\n" }, { "code": null, "e": 44032, "s": 43837, "text": "numpy.linspace(start, stop, num = 50, endpoint = True, retstep = False, dtype = None) : Returns number spaces evenly w.r.t interval. Similiar to arange but instead of step it uses sample number." }, { "code": null, "e": 44041, "s": 44032, "text": "Output :" }, { "code": null, "e": 44221, "s": 44041, "text": "B\n (array([ 2. , 2.25, 2.5 , 2.75, 3. ]), 0.25)\n\nA\n [ 0. 0.22039774 0.42995636 0.6183698 0.77637192 0.8961922\n 0.9719379 0.99988386 0.9786557 0.90929743]" }, { "code": null, "e": 44419, "s": 44221, "text": " Flatten array: We can use flatten method to get a copy of array collapsed into one dimension. It accepts order argument. Default value is ‘C’ (for row-major order). Use ‘F’ for column major order." }, { "code": null, "e": 44513, "s": 44419, "text": "numpy.ndarray.flatten(order = ‘C’) : Return a copy of the array collapsed into one dimension." }, { "code": null, "e": 44522, "s": 44513, "text": "Output :" }, { "code": null, "e": 44549, "s": 44522, "text": "[1, 2, 3, 4]\n[1, 3, 2, 4]\n" }, { "code": null, "e": 44649, "s": 44551, "text": "Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here." }, { "code": null, "e": 44658, "s": 44649, "text": "Comments" }, { "code": null, "e": 44671, "s": 44658, "text": "Old Comments" }, { "code": null, "e": 44702, "s": 44671, "text": "Difference between sh and bash" }, { "code": null, "e": 44744, "s": 44702, "text": "Python - Add values to Dictionary of List" }, { "code": null, "e": 44782, "s": 44744, "text": "How to Install Scala IDE For Eclipse?" }, { "code": null, "e": 44824, "s": 44782, "text": "How to Test React Components using Jest ?" }, { "code": null, "e": 44867, "s": 44824, "text": "Spring @Controller Annotation with Example" }, { "code": null, "e": 44897, "s": 44867, "text": "What is External JavaScript ?" }, { "code": null, "e": 44951, "s": 44897, "text": "Create a dictionary with list comprehension in Python" }, { "code": null, "e": 44999, "s": 44951, "text": "Converting an image to a Torch Tensor in Python" }, { "code": null, "e": 45045, "s": 44999, "text": "How to Calculate Cosine Similarity in Python?" } ]
How to change the Azure tag value using PowerShell?
To change the azure value using PowerShell we need to use the Update-AZTag command with the merge property. For example, we have the Azure VM TestMachine2k16 and we have its tags as shown below. PS C:\> $vm = Get-AzVM -VMName TestMachine2k16 PS C:\> $vm | Select -ExpandProperty Tags Key Value --- ----- Owner Chirag For Ansible Patching_Day Sunday Application SecretTag We need to change the Patching_Day from Sunday to Wednesday. We will use the below command. $tag = @{Patching_Day='Wednesday'} Update-AzTag -Tag $tag -ResourceId $vm.Id -Operation Merge -Verbose Name Value ============ ========= Patching_Day Wednesday For Ansible Application SecretTag Owner Chirag There is also property Replace available in Update-AZTag but please be cautious while using the Replace parameter because once you apply it, the current tag will be changed but other tags will be erased. Update-AzTag -Tag $tag -ResourceId $vm.Id -Operation Replace -Verbose Properties : Name Value ============ ========= Patching_Day Wednesday
[ { "code": null, "e": 1170, "s": 1062, "text": "To change the azure value using PowerShell we need to use the Update-AZTag command with the merge property." }, { "code": null, "e": 1257, "s": 1170, "text": "For example, we have the Azure VM TestMachine2k16 and we have its tags as shown below." }, { "code": null, "e": 1346, "s": 1257, "text": "PS C:\\> $vm = Get-AzVM -VMName TestMachine2k16\nPS C:\\> $vm | Select -ExpandProperty Tags" }, { "code": null, "e": 1458, "s": 1346, "text": "Key Value\n--- -----\nOwner Chirag\nFor Ansible\nPatching_Day Sunday\nApplication SecretTag" }, { "code": null, "e": 1550, "s": 1458, "text": "We need to change the Patching_Day from Sunday to Wednesday. We will use the below command." }, { "code": null, "e": 1653, "s": 1550, "text": "$tag = @{Patching_Day='Wednesday'}\nUpdate-AzTag -Tag $tag -ResourceId $vm.Id -Operation Merge -Verbose" }, { "code": null, "e": 1794, "s": 1653, "text": "Name Value\n============ =========\nPatching_Day Wednesday\nFor Ansible\nApplication SecretTag\nOwner Chirag" }, { "code": null, "e": 1998, "s": 1794, "text": "There is also property Replace available in Update-AZTag but please be cautious while using the Replace parameter because once you apply it, the current tag will be changed but other tags will be erased." }, { "code": null, "e": 2068, "s": 1998, "text": "Update-AzTag -Tag $tag -ResourceId $vm.Id -Operation Replace -Verbose" }, { "code": null, "e": 2149, "s": 2068, "text": "Properties :\nName Value\n============ =========\nPatching_Day Wednesday" } ]
C++ Program for Gnome Sort?
Here we will see how the gnome sort works. This is another sorting algorithm. In this approach if the list is already sorted it will take O(n) time. So best case time complexity is O(n). But average case and worst case complexity is O(n^2). Now let us see the algorithm to get the idea about this sorting technique. begin index := 0 while index < n, do if index is 0, then index := index + 1 end if if arr[index] >= arr[index -1], then index := index + 1 else exchange arr[index] and arr[index - 1] index := index - 1 end if done end Live Demo #include<iostream> using namespace std; void gnomeSort(int arr[], int n){ int index = 0; while(index < n){ if(index == 0) index++; if(arr[index] >= arr[index - 1]){ //if the element is greater than previous one index++; } else { swap(arr[index], arr[index - 1]); index--; } } } main() { int data[] = {54, 74, 98, 154, 98, 32, 20, 13, 35, 40}; int n = sizeof(data)/sizeof(data[0]); cout << "Sorted Sequence "; gnomeSort(data, n); for(int i = 0; i <n;i++){ cout << data[i] << " "; } } Sorted Sequence 13 20 32 35 40 54 74 98 98 154
[ { "code": null, "e": 1378, "s": 1062, "text": "Here we will see how the gnome sort works. This is another sorting algorithm. In this approach if the list is already sorted it will take O(n) time. So best case time complexity is O(n). But average case and worst case complexity is O(n^2). Now let us see the algorithm to get the idea about this sorting technique." }, { "code": null, "e": 1671, "s": 1378, "text": "begin\n index := 0\n while index < n, do\n if index is 0, then\n index := index + 1\n end if\n if arr[index] >= arr[index -1], then\n index := index + 1\n else\n exchange arr[index] and arr[index - 1]\n index := index - 1\n end if\n done\nend" }, { "code": null, "e": 1682, "s": 1671, "text": " Live Demo" }, { "code": null, "e": 2249, "s": 1682, "text": "#include<iostream>\nusing namespace std;\nvoid gnomeSort(int arr[], int n){\n int index = 0;\n while(index < n){\n if(index == 0) index++;\n if(arr[index] >= arr[index - 1]){ //if the element is greater than previous one\n index++;\n } else {\n swap(arr[index], arr[index - 1]);\n index--;\n }\n }\n}\nmain() {\n int data[] = {54, 74, 98, 154, 98, 32, 20, 13, 35, 40};\n int n = sizeof(data)/sizeof(data[0]);\n cout << \"Sorted Sequence \";\n gnomeSort(data, n);\n for(int i = 0; i <n;i++){\n cout << data[i] << \" \";\n }\n}" }, { "code": null, "e": 2296, "s": 2249, "text": "Sorted Sequence 13 20 32 35 40 54 74 98 98 154" } ]
How can we convert a map to the JSON object in Java?
The JSON is a lightweight, text-based and language-independent data exchange format. The JSON can represent two structured types like objects and arrays. An object is an unordered collection of key/value pairs and an array is an ordered sequence of values. We can convert a Map to JSON object using the toJSONString() method(static) of org.json.simple.JSONValue. It has two important static methods: writeJSONString() method to encode an object into JSON text and write it out, escape() method to escape the special characters and escape quotes, \, /, \r, \n, \b, \f, \t. import java.util.*; import org.json.simple.JSONValue; public class ConvertMapJSONTest { public static void main(String[] args) { Map<String, Object> map = new HashMap<String, Object>(); map.put("1", "India"); map.put("2", "Australia"); map.put("3", "England"); map.put("4", "South Africa"); String jsonStr = JSONValue.toJSONString(map); // converts Map to JSON System.out.println(jsonStr); } } {"1":"India","2":"Australia","3":"England","4":"South Africa"}
[ { "code": null, "e": 1320, "s": 1062, "text": "The JSON is a lightweight, text-based and language-independent data exchange format. The JSON can represent two structured types like objects and arrays. An object is an unordered collection of key/value pairs and an array is an ordered sequence of values. " }, { "code": null, "e": 1635, "s": 1320, "text": "We can convert a Map to JSON object using the toJSONString() method(static) of org.json.simple.JSONValue. It has two important static methods: writeJSONString() method to encode an object into JSON text and write it out, escape() method to escape the special characters and escape quotes, \\, /, \\r, \\n, \\b, \\f, \\t." }, { "code": null, "e": 2077, "s": 1635, "text": "import java.util.*;\nimport org.json.simple.JSONValue;\npublic class ConvertMapJSONTest {\n public static void main(String[] args) {\n Map<String, Object> map = new HashMap<String, Object>();\n map.put(\"1\", \"India\");\n map.put(\"2\", \"Australia\");\n map.put(\"3\", \"England\");\n map.put(\"4\", \"South Africa\");\n String jsonStr = JSONValue.toJSONString(map); // converts Map to JSON\n System.out.println(jsonStr);\n }\n}" }, { "code": null, "e": 2140, "s": 2077, "text": "{\"1\":\"India\",\"2\":\"Australia\",\"3\":\"England\",\"4\":\"South Africa\"}" } ]
Image Processing with Python — Alternative Histogram Equalization Methods | by Tonichi Edeza | Towards Data Science
In a previous article, we discussed how to manually equalize each channel’s histogram. However, direct manipulation of the RGB channels is only one method to enhance and image. In this article we shall go over these methods and see their effects. Let’s get started! As always, let us first import the required Python Libraries. import numpy as npimport matplotlib.pyplot as pltfrom skimage.io import imshow, imreadfrom skimage.color import rgb2hsv, rgb2gray, rgb2yuvfrom skimage import color, exposure, transformfrom skimage.exposure import histogram, cumulative_distribution, equalize_histfrom skimage import img_as_ubyte, img_as_uint Great! Now let us load the image we wish to work with. dark_image = imread('flea_market.png')plt.figure(num=None, figsize=(8, 6), dpi=80)imshow(dark_image); The image clearly has lighting issues. Not only is it quite dark in some spots, it is blindingly bright in others. Let us first see what happens if we do a simple greyscale histogram adjustment. dark_image_grey = img_as_ubyte(rgb2gray(dark_image))freq, bins = cumulative_distribution(dark_image_grey, nbins =256)target_bins = np.arange(255)target_freq = np.linspace(0, 1, len(target_bins))interpolation = np.interp(freq, target_freq, target_bins)dark_image_eq = img_as_ubyte(interpolation[dark_image_grey].astype(int))freq_adj, bins_adj = cumulative_distribution(dark_image_eq) fig, axes = plt.subplots(1, 2, figsize=(15,7));axes[0].imshow(dark_image_grey, cmap = 'gray');axes[0].set_title(f'Original Greyscale', fontsize = 18)axes[1].imshow(dark_image_eq, cmap = 'gray');axes[1].set_title(f'Adjusted Greyscale', fontsize = 18) axes[0].axis('off');axes[1].axis('off'); We can see that the image has improved significantly. However the bright spots are still quite evident. Let us see if we can remedy this. Below is a code for transforming the image into a Histogram Equalized Image by individually adjusting each color channel. def rgb_adjuster_lin(image): target_bins = np.arange(255) target_freq = np.linspace(0, 1, len(target_bins)) freq_bins = [cumulative_distribution(image[:,:,i]) for i in \ range(3)] names = ['Reds', 'Greens', 'Blues'] line_color = ['red','green','blue'] adjusted_figures = [] f_size = 20 #Pad frequencies with min frequency adj_freqs = [] for i in range(len(freq_bins)): if len(freq_bins[i][0]) < 256: frequencies = list(freq_bins[i][0]) min_pad = [min(frequencies)] * (256 - len(frequencies)) frequencies = min_pad + frequencies else: frequencies = freq_bins[i][0] adj_freqs.append(np.array(frequencies)) #Plot RGB Images fig, ax = plt.subplots(1,3, figsize=[15,5]) for n, ax in enumerate(ax.flatten()): interpolation = np.interp(adj_freqs[n], target_freq, target_bins) adjusted_image = img_as_ubyte(interpolation[image[:,:,n]].astype(int)) ax.set_title(f'{names[n]}', fontsize = f_size) ax.imshow(adjusted_image, cmap = names[n]) adjusted_figures.append([adjusted_image]) fig.tight_layout() #Plot Adjusted CDFs fig, ax = plt.subplots(1,3, figsize=[15,3]) for n, ax in enumerate(ax.flatten()): interpolation = np.interp(adj_freqs[n], target_freq, target_bins) adjusted_image = img_as_ubyte(interpolation[image[:,:,n]] .astype(int)) freq_adj, bins_adj = cumulative_distribution(adjusted_image) ax.set_title(f'{names[n]}', fontsize = f_size) ax.step(bins_adj, freq_adj, c=line_color[n], label='Actual CDF') ax.plot(target_bins, target_freq, c='gray', label='Target CDF', linestyle = '--') fig.tight_layout() adjusted_image = np.dstack((adjusted_figures[0][0], adjusted_figures[1][0], adjusted_figures[2][0])) #Plot Original Image against Adjusted Image fig, ax = plt.subplots(1,2, figsize=[17,7]) ax[0].imshow(image); ax[0].set_title(f'Original Image', fontsize = f_size) ax[1].imshow(adjusted_image); ax[1].set_title(f'Adjusted Image', fontsize = f_size) fig.tight_layout() return adjusted_image Excellent! We see that the image has improved greatly. However the glaring brightness of the bulbs are still very evident. To this end let us explore alternative ways to adjust the histogram of images. Adjustment via the HSV Color Space One alternative method we can explore is by first converting the RGB image into an HSV image. From there we can equalize the histogram for the V (Value) channel. The below code does just that (Note that I sliced the image so that it would only feed it the RGB channel, omitting the transparency channel). For the purposes of the article, we shall bypass our manually constructed code and opt for the equalize_hist function in Skimage Library. hsv_image = color.rgb2hsv(dark_image[:,:,:-1])hsv_image[:, :, 2] = equalize_hist(hsv_image[:, :, 2])hsv_adjusted = color.hsv2rgb(hsv_image) fig, ax = plt.subplots(1,2, figsize=[15,10]) ax[0].imshow(dark_image);ax[0].set_title(f'Original Image', fontsize = 18) ax[1].imshow(hsv_adjusted);ax[1].set_title(f'HSV Adjusted Image', fontsize = 18) fig.tight_layout() It is clear that adjusting the image based solely on the V channel produces excellent results. Not only have the colors retained their vibrancy, the overall image also seems sharper. Also, the overall warm tone of the image is maintained. In some cases this may be preferable. The glare from the bulbs are also not as blinding as those in the RGB adjusted images. The below code shows a side by side comparison of the RGB and HSV adjustment on another picture. For brevity and to ensure comparability, we will use the equalize_histogram function in Skimage to do the RGB adjustment. rice_terraces = imread('rice_terraces.png')plt.figure(num=None, figsize=(8, 6), dpi=80)imshow(rice_terraces); def rgb_vs_hsv(image): f_size = 22 #Equalize Histogram rgb_adjusted = image.copy() rgb_adjusted = equalize_hist(rgb_adjusted) #HSV Adjustment new_image = color.rgb2hsv(image[:,:,:-1]) new_image[:, :, 2] = equalize_hist(new_image [:, :, 2]) hsv_adjusted = color.hsv2rgb(new_image) images = [image, rgb_adjusted, hsv_adjusted] names = ['Original', 'RGB Adjusted', 'HSV Adjusted'] fig, ax = plt.subplots(1,3, figsize=[19,14]) for n, ax in enumerate(ax.flatten()): ax.imshow(images[n]) ax.set_title(f'{names[n]}', fontsize = f_size) ax.set_axis_off() fig.tight_layout() rgb_vs_hsv(rice_terraces) As we can see, there is a stark difference between adjusting the image directly via the color channels as compared to adjusting it via the V channel. The latter produces an image far crisper yet maintains its color overcast. Adjustment via the YUV Color Space Lastly, we should go over adjusting the image via the YUV color space. This is not too different from the previous method of adjusting the image by the HSV color space, in fact the codes are strikingly similar. We shall apply the method to the below image. red_tree = imread('red_tree.png')plt.figure(num=None, figsize=(8, 6), dpi=80)imshow(red_tree); #HSV Adjustment Manualhsv_image = color.rgb2hsv(red_tree[:,:,:-1])hsv_image[:, :, 2] = equalize_hist(hsv_image[:, :, 2])hsv_adjusted = color.hsv2rgb(hsv_image)#YUV Adjustment Manualyuv = color.rgb2yuv(red_tree[:,:,:-1])yuv[:, :, 0] = equalize_hist(yuv[:, :, 0])yuv_adjusted = color.yuv2rgb(yuv)fig, ax = plt.subplots(1,3, figsize=[15,10]) ax[0].imshow(red_tree);ax[0].set_title(f'Original Image', fontsize = 18)ax[1].imshow(hsv_adjusted);ax[1].set_title(f'HSV Adjusted', fontsize = 18)ax[2].imshow(yuv_adjusted);ax[2].set_title(f'YUV Adjusted', fontsize = 18) fig.tight_layout() We see that the YUV adjusted image stands out due to its overall brighter color. Unlike the deeper and crisper colors from the HSV adjusted image, the YUV offers overall increased lighting. This would make it ideal in situations where the goal would be to brighten the image’s color. Indeed, the YUV image almost looks like it was shot on a bright sunny day. In Conclusion We have only scratched the surface of alternative histogram adjustment techniques. I hope this has given you additional insight on the topic and opened your mind to trying out other methods for this staple process. In succeeding articles we shall discuss the myriad of alternative techniques we can use for this process as well as the many other color spaces available for us to use. Remember, humans can see way more than RGB!
[ { "code": null, "e": 419, "s": 172, "text": "In a previous article, we discussed how to manually equalize each channel’s histogram. However, direct manipulation of the RGB channels is only one method to enhance and image. In this article we shall go over these methods and see their effects." }, { "code": null, "e": 438, "s": 419, "text": "Let’s get started!" }, { "code": null, "e": 500, "s": 438, "text": "As always, let us first import the required Python Libraries." }, { "code": null, "e": 808, "s": 500, "text": "import numpy as npimport matplotlib.pyplot as pltfrom skimage.io import imshow, imreadfrom skimage.color import rgb2hsv, rgb2gray, rgb2yuvfrom skimage import color, exposure, transformfrom skimage.exposure import histogram, cumulative_distribution, equalize_histfrom skimage import img_as_ubyte, img_as_uint" }, { "code": null, "e": 863, "s": 808, "text": "Great! Now let us load the image we wish to work with." }, { "code": null, "e": 965, "s": 863, "text": "dark_image = imread('flea_market.png')plt.figure(num=None, figsize=(8, 6), dpi=80)imshow(dark_image);" }, { "code": null, "e": 1160, "s": 965, "text": "The image clearly has lighting issues. Not only is it quite dark in some spots, it is blindingly bright in others. Let us first see what happens if we do a simple greyscale histogram adjustment." }, { "code": null, "e": 1844, "s": 1160, "text": "dark_image_grey = img_as_ubyte(rgb2gray(dark_image))freq, bins = cumulative_distribution(dark_image_grey, nbins =256)target_bins = np.arange(255)target_freq = np.linspace(0, 1, len(target_bins))interpolation = np.interp(freq, target_freq, target_bins)dark_image_eq = img_as_ubyte(interpolation[dark_image_grey].astype(int))freq_adj, bins_adj = cumulative_distribution(dark_image_eq) fig, axes = plt.subplots(1, 2, figsize=(15,7));axes[0].imshow(dark_image_grey, cmap = 'gray');axes[0].set_title(f'Original Greyscale', fontsize = 18)axes[1].imshow(dark_image_eq, cmap = 'gray');axes[1].set_title(f'Adjusted Greyscale', fontsize = 18) axes[0].axis('off');axes[1].axis('off');" }, { "code": null, "e": 2104, "s": 1844, "text": "We can see that the image has improved significantly. However the bright spots are still quite evident. Let us see if we can remedy this. Below is a code for transforming the image into a Histogram Equalized Image by individually adjusting each color channel." }, { "code": null, "e": 4508, "s": 2104, "text": "def rgb_adjuster_lin(image): target_bins = np.arange(255) target_freq = np.linspace(0, 1, len(target_bins)) freq_bins = [cumulative_distribution(image[:,:,i]) for i in \\ range(3)] names = ['Reds', 'Greens', 'Blues'] line_color = ['red','green','blue'] adjusted_figures = [] f_size = 20 #Pad frequencies with min frequency adj_freqs = [] for i in range(len(freq_bins)): if len(freq_bins[i][0]) < 256: frequencies = list(freq_bins[i][0]) min_pad = [min(frequencies)] * (256 - len(frequencies)) frequencies = min_pad + frequencies else: frequencies = freq_bins[i][0] adj_freqs.append(np.array(frequencies)) #Plot RGB Images fig, ax = plt.subplots(1,3, figsize=[15,5]) for n, ax in enumerate(ax.flatten()): interpolation = np.interp(adj_freqs[n], target_freq, target_bins) adjusted_image = img_as_ubyte(interpolation[image[:,:,n]].astype(int)) ax.set_title(f'{names[n]}', fontsize = f_size) ax.imshow(adjusted_image, cmap = names[n]) adjusted_figures.append([adjusted_image]) fig.tight_layout() #Plot Adjusted CDFs fig, ax = plt.subplots(1,3, figsize=[15,3]) for n, ax in enumerate(ax.flatten()): interpolation = np.interp(adj_freqs[n], target_freq, target_bins) adjusted_image = img_as_ubyte(interpolation[image[:,:,n]] .astype(int)) freq_adj, bins_adj = cumulative_distribution(adjusted_image) ax.set_title(f'{names[n]}', fontsize = f_size) ax.step(bins_adj, freq_adj, c=line_color[n], label='Actual CDF') ax.plot(target_bins, target_freq, c='gray', label='Target CDF', linestyle = '--') fig.tight_layout() adjusted_image = np.dstack((adjusted_figures[0][0], adjusted_figures[1][0], adjusted_figures[2][0])) #Plot Original Image against Adjusted Image fig, ax = plt.subplots(1,2, figsize=[17,7]) ax[0].imshow(image); ax[0].set_title(f'Original Image', fontsize = f_size) ax[1].imshow(adjusted_image); ax[1].set_title(f'Adjusted Image', fontsize = f_size) fig.tight_layout() return adjusted_image" }, { "code": null, "e": 4710, "s": 4508, "text": "Excellent! We see that the image has improved greatly. However the glaring brightness of the bulbs are still very evident. To this end let us explore alternative ways to adjust the histogram of images." }, { "code": null, "e": 4745, "s": 4710, "text": "Adjustment via the HSV Color Space" }, { "code": null, "e": 5188, "s": 4745, "text": "One alternative method we can explore is by first converting the RGB image into an HSV image. From there we can equalize the histogram for the V (Value) channel. The below code does just that (Note that I sliced the image so that it would only feed it the RGB channel, omitting the transparency channel). For the purposes of the article, we shall bypass our manually constructed code and opt for the equalize_hist function in Skimage Library." }, { "code": null, "e": 5564, "s": 5188, "text": "hsv_image = color.rgb2hsv(dark_image[:,:,:-1])hsv_image[:, :, 2] = equalize_hist(hsv_image[:, :, 2])hsv_adjusted = color.hsv2rgb(hsv_image) fig, ax = plt.subplots(1,2, figsize=[15,10]) ax[0].imshow(dark_image);ax[0].set_title(f'Original Image', fontsize = 18) ax[1].imshow(hsv_adjusted);ax[1].set_title(f'HSV Adjusted Image', fontsize = 18) fig.tight_layout()" }, { "code": null, "e": 5747, "s": 5564, "text": "It is clear that adjusting the image based solely on the V channel produces excellent results. Not only have the colors retained their vibrancy, the overall image also seems sharper." }, { "code": null, "e": 6147, "s": 5747, "text": "Also, the overall warm tone of the image is maintained. In some cases this may be preferable. The glare from the bulbs are also not as blinding as those in the RGB adjusted images. The below code shows a side by side comparison of the RGB and HSV adjustment on another picture. For brevity and to ensure comparability, we will use the equalize_histogram function in Skimage to do the RGB adjustment." }, { "code": null, "e": 6257, "s": 6147, "text": "rice_terraces = imread('rice_terraces.png')plt.figure(num=None, figsize=(8, 6), dpi=80)imshow(rice_terraces);" }, { "code": null, "e": 6930, "s": 6257, "text": "def rgb_vs_hsv(image): f_size = 22 #Equalize Histogram rgb_adjusted = image.copy() rgb_adjusted = equalize_hist(rgb_adjusted) #HSV Adjustment new_image = color.rgb2hsv(image[:,:,:-1]) new_image[:, :, 2] = equalize_hist(new_image [:, :, 2]) hsv_adjusted = color.hsv2rgb(new_image) images = [image, rgb_adjusted, hsv_adjusted] names = ['Original', 'RGB Adjusted', 'HSV Adjusted'] fig, ax = plt.subplots(1,3, figsize=[19,14]) for n, ax in enumerate(ax.flatten()): ax.imshow(images[n]) ax.set_title(f'{names[n]}', fontsize = f_size) ax.set_axis_off() fig.tight_layout() rgb_vs_hsv(rice_terraces)" }, { "code": null, "e": 7155, "s": 6930, "text": "As we can see, there is a stark difference between adjusting the image directly via the color channels as compared to adjusting it via the V channel. The latter produces an image far crisper yet maintains its color overcast." }, { "code": null, "e": 7190, "s": 7155, "text": "Adjustment via the YUV Color Space" }, { "code": null, "e": 7447, "s": 7190, "text": "Lastly, we should go over adjusting the image via the YUV color space. This is not too different from the previous method of adjusting the image by the HSV color space, in fact the codes are strikingly similar. We shall apply the method to the below image." }, { "code": null, "e": 7542, "s": 7447, "text": "red_tree = imread('red_tree.png')plt.figure(num=None, figsize=(8, 6), dpi=80)imshow(red_tree);" }, { "code": null, "e": 8127, "s": 7542, "text": "#HSV Adjustment Manualhsv_image = color.rgb2hsv(red_tree[:,:,:-1])hsv_image[:, :, 2] = equalize_hist(hsv_image[:, :, 2])hsv_adjusted = color.hsv2rgb(hsv_image)#YUV Adjustment Manualyuv = color.rgb2yuv(red_tree[:,:,:-1])yuv[:, :, 0] = equalize_hist(yuv[:, :, 0])yuv_adjusted = color.yuv2rgb(yuv)fig, ax = plt.subplots(1,3, figsize=[15,10]) ax[0].imshow(red_tree);ax[0].set_title(f'Original Image', fontsize = 18)ax[1].imshow(hsv_adjusted);ax[1].set_title(f'HSV Adjusted', fontsize = 18)ax[2].imshow(yuv_adjusted);ax[2].set_title(f'YUV Adjusted', fontsize = 18) fig.tight_layout()" }, { "code": null, "e": 8486, "s": 8127, "text": "We see that the YUV adjusted image stands out due to its overall brighter color. Unlike the deeper and crisper colors from the HSV adjusted image, the YUV offers overall increased lighting. This would make it ideal in situations where the goal would be to brighten the image’s color. Indeed, the YUV image almost looks like it was shot on a bright sunny day." }, { "code": null, "e": 8500, "s": 8486, "text": "In Conclusion" }, { "code": null, "e": 8884, "s": 8500, "text": "We have only scratched the surface of alternative histogram adjustment techniques. I hope this has given you additional insight on the topic and opened your mind to trying out other methods for this staple process. In succeeding articles we shall discuss the myriad of alternative techniques we can use for this process as well as the many other color spaces available for us to use." } ]
Print Single and Multiple variable in Python?
In this section, we are going to check printing single and multiple variable output in two different python version. >>> #Python 2.7 >>> #Print single variable >>> print 27 27 >>> print "Rahul" Rahul >>> #Print single variable, single brackets >>> print(27) 27 >>> print("Rahul") Rahul >>> #Python 3.6 >>> #Print single variable without brackets >>> print 27 SyntaxError: Missing parentheses in call to 'print' >>> print "Rahul" SyntaxError: Missing parentheses in call to 'print' Above syntax in 3.6, is due to: In python 3.x, print is not a statement but a function (print()). So print is changed to print(). >>> print (27) 27 >>> print("Rahul") Rahul Python 2.x (for e.g: python 2.7) >>> #Python 2.7 >>> #Print multiple variables >>> print 27, 54, 81 27 54 81 >>> #Print multiple variables inside brackets >>> print (27, 54, 81) (27, 54, 81) >>> #With () brackets, above is treating it as a tuple, and hence generating the >>> #tuple of 3 variables >>> print ("Rahul", "Raj", "Rajesh") ('Rahul', 'Raj', 'Rajesh') >>> So from above output, we can see in python 2.x, passing multiple variables inside the brackets (), will treat it as tuple of multiple items #Python 3.6 #Print multiple variables >>> print(27, 54, 81) 27 54 81 >>> print ("Rahul", "Raj", "Rajesh") Rahul Raj Rajesh Let’s take another example of multiple statements in python 2.x and python 3.x
[ { "code": null, "e": 1179, "s": 1062, "text": "In this section, we are going to check printing single and multiple variable output in two different python version." }, { "code": null, "e": 1348, "s": 1179, "text": ">>> #Python 2.7\n>>> #Print single variable\n>>> print 27\n27\n>>> print \"Rahul\"\nRahul\n>>> #Print single variable, single brackets\n>>> print(27)\n27\n>>> print(\"Rahul\")\nRahul" }, { "code": null, "e": 1543, "s": 1348, "text": ">>> #Python 3.6\n>>> #Print single variable without brackets\n>>> print 27\nSyntaxError: Missing parentheses in call to 'print'\n>>> print \"Rahul\"\nSyntaxError: Missing parentheses in call to 'print'" }, { "code": null, "e": 1673, "s": 1543, "text": "Above syntax in 3.6, is due to: In python 3.x, print is not a statement but a function (print()). So print is changed to print()." }, { "code": null, "e": 1716, "s": 1673, "text": ">>> print (27)\n27\n>>> print(\"Rahul\")\nRahul" }, { "code": null, "e": 1749, "s": 1716, "text": "Python 2.x (for e.g: python 2.7)" }, { "code": null, "e": 2082, "s": 1749, "text": ">>> #Python 2.7\n>>> #Print multiple variables\n>>> print 27, 54, 81\n27 54 81\n>>> #Print multiple variables inside brackets\n>>> print (27, 54, 81)\n(27, 54, 81)\n>>> #With () brackets, above is treating it as a tuple, and hence generating the\n>>> #tuple of 3 variables\n>>> print (\"Rahul\", \"Raj\", \"Rajesh\")\n('Rahul', 'Raj', 'Rajesh')\n>>>" }, { "code": null, "e": 2222, "s": 2082, "text": "So from above output, we can see in python 2.x, passing multiple variables inside the brackets (), will treat it as tuple of multiple items" }, { "code": null, "e": 2345, "s": 2222, "text": "#Python 3.6\n#Print multiple variables\n>>> print(27, 54, 81)\n27 54 81\n>>> print (\"Rahul\", \"Raj\", \"Rajesh\")\nRahul Raj Rajesh" }, { "code": null, "e": 2424, "s": 2345, "text": "Let’s take another example of multiple statements in python 2.x and python 3.x" } ]
How to create a Hyperlink using JavaFX?
A Hyperlink is a UI component that responds to clicks and rollovers. You can create a hyperlink by instantiating the javafx.scene.control.Hiperlink class. The following Example demonstrates the creation of a Hyperlink. import javafx.application.Application; import javafx.geometry.Insets; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.control.Hyperlink; import javafx.scene.layout.VBox; import javafx.scene.paint.Color; import javafx.stage.Stage; public class HiperlinkExample extends Application { public void start(Stage stage) { //Creating a hyper link Hyperlink link = new Hyperlink("https://www.tutorialspoint.com"); //Creating a vbox to hold the pagination VBox vbox = new VBox(); vbox.setSpacing(5); vbox.setPadding(new Insets(50, 50, 50, 60)); vbox.getChildren().addAll(link); //Setting the stage Group root = new Group(vbox); Scene scene = new Scene(root, 595, 200, Color.BEIGE); stage.setTitle("Hyperlink"); stage.setScene(scene); stage.show(); } public static void main(String args[]){ launch(args); } }
[ { "code": null, "e": 1217, "s": 1062, "text": "A Hyperlink is a UI component that responds to clicks and rollovers. You can create a hyperlink by instantiating the javafx.scene.control.Hiperlink class." }, { "code": null, "e": 1281, "s": 1217, "text": "The following Example demonstrates the creation of a Hyperlink." }, { "code": null, "e": 2201, "s": 1281, "text": "import javafx.application.Application;\nimport javafx.geometry.Insets;\nimport javafx.scene.Group;\nimport javafx.scene.Scene;\nimport javafx.scene.control.Hyperlink;\nimport javafx.scene.layout.VBox;\nimport javafx.scene.paint.Color;\nimport javafx.stage.Stage;\npublic class HiperlinkExample extends Application {\n public void start(Stage stage) {\n //Creating a hyper link\n Hyperlink link = new Hyperlink(\"https://www.tutorialspoint.com\");\n //Creating a vbox to hold the pagination\n VBox vbox = new VBox();\n vbox.setSpacing(5);\n vbox.setPadding(new Insets(50, 50, 50, 60));\n vbox.getChildren().addAll(link);\n //Setting the stage\n Group root = new Group(vbox);\n Scene scene = new Scene(root, 595, 200, Color.BEIGE);\n stage.setTitle(\"Hyperlink\");\n stage.setScene(scene);\n stage.show();\n }\n public static void main(String args[]){\n launch(args);\n }\n}" } ]
Data Wrangling Basics — Why is Regex In Python Preceded By The Letter r? | by Ujjwal Dalmia | Towards Data Science
When writing regular expressions (regex) in Python language, we always start with the letter r. In this tutorial, we will understand the reason behind using it by answering the following questions: What are the escape sequences?How Python interpreter interprets escape sequences with or without the letter r?How regular expressions work in the Python language?The importance of using the letter r in regular expressions What are the escape sequences? How Python interpreter interprets escape sequences with or without the letter r? How regular expressions work in the Python language? The importance of using the letter r in regular expressions An escape sequence is a character set that does not represent itself when used in a text definition. It gets translated to some other character or character set that is otherwise difficult to present in a programming language. For example, in Python language, the character set \n represents a new line, and \t represents a tab. Both the character sets, \n, and \t are escape sequences. The list of standard escape sequences understood by the Python interpreter and their associated meanings are as follows: To understand its impact on escape sequences, let us have a look at the following example: #### Sample Text Definitiontext_1 = "My name is Ujjwal Dalmia.\nI love learning and teaching the Python language"print(text_1)#### Sample OutputMy name is Ujjwal Dalmia.I love learning and teaching the Python language#### Sample Text Definitiontext_2 = "My name is Ujjwal Dalmia.\sI love learning and teaching the Python language"print(text_2)#### Sample OutputMy name is Ujjwal Dalmia.\sI love learning and teaching the Python language In text_1 above, the example uses \n character set whereas text_2 uses \s. From the escape sequences table shared in section 1, we can see that \n is part of the standard escape sequence-set in Python language, whereas \s is not. Therefore, when we print both the variables, escape sequence \n is interpreted as a new line character by the Python interpreter, whereas \s is left as it is. Note that the definition of both text_1 and text_2 does not include the letter r. Let us take a step further and include the letter r in the text definition. #### Sample Text Definition (with letter "r")text_1 = r"My name is Ujjwal Dalmia.\nI love learning and teaching the Python language"print(text_1)#### Sample OutputMy name is Ujjwal Dalmia.\nI love learning and teaching the Python language#### Sample Text Definition (with letter "r")text_2 = r"My name is Ujjwal Dalmia.\sI love learning and teaching the Python language"print(text_2)#### Sample OutputMy name is Ujjwal Dalmia.\sI love learning and teaching the Python language The inclusion of the letter r had no impact on text_2 because \s is not part of the standard escape sequence set in Python language. Surprisingly, for text_1, the Python interpreter did not convert \n into the new line character. It is because the presence of the letter r has transformed the text into a raw-string. In simple terms, the letter r has instructed the Python interpreter to leave the escape sequence as it is. To understand how regular expressions work in Python language, we will use the sub() function (re Python package) that substitutes the part of old text with the new text based on the regular expression driven pattern matching. Let us understand this with an example: #### Importing the re packageimport re#### Using the sub functionre.sub("\ts","s", "\tsing")#### Sample Output'sing' In this example, we are trying to replace the letter s preceded by a tab with the standalone letter s. One can see from the output that the text \tsing converts to sing. Let us refer to the below flow chart to understand how the sub() function produced the desired result. In the flow chart, we refer to \ts as regex, letter s as new text, and \tsing as old text. In the previous example, we have used the character set \t, which is part of the standard escape list in Python language. Therefore, in the first step, the Python interpreter replaced the escape sequence with the tab in both regex text and the old text. Since the regex pattern matched with the input text in the last step, the substitution took place. In the next example, we will use a different character set, \s, that is not a part of the standard escape list in Python language. #### Importing the re packageimport re#### Using the sub function(this time with a non-standard escape sequence)re.sub("\ss","s", "\ssing")#### Sample Output"\ssing" In this example, we are trying to replace any instance of the letter s preceded by \s with the standalone letter s. It is evident that there was no change in the input text, and the output remained the same as the old text. Again, in the flow chart, we refer to \ss as regex, s as the new text, and \ssing as the old. Let us understand the reason behind this behavior from the below flowchart: In step 1, since \s is not a standard escape sequence, the Python interpreter neither modified the regular expression nor the old text and left them as it is. In step 2, since \s is a metacharacter representing space, it gets converted from \ss to space s. Because in the old text, space s did not exist, there was no positive match, and hence the old-text remained the same. The two learnings we can draw from this section are: The evaluation of old text and new text for escape sequences is done only by the Python interpreter. For the regular expression by the Python and the regex interpreter. Therefore, for both old and new text, the outcome of step 1 is their final version, and for regex, it is step 2. In a scenario where the texts and regex pattern contain only the standard escape sequence, which is part of Python language, we get our desired results. Whereas, when there are additional metacharacters, the results might not be as per expectation. From the 2nd example of the previous section, we saw that the regex failed to deliver the expected result. To find the right solution, let us work our way backward. To substitute \ss from the old text with the letter s, we expect the regex pattern at step 3 to match the text we want to replace. To achieve this, we need the regex pattern to be \\ss by the end of step two. When the regex interpreter encounters this pattern, it will convert the metacharacters double backslashes to single, and the output of step 2 will be \ss. Finally, to ensure that regex at step 2 is \\ss, we pass \\\\ss at step 1. It is because double backslashes are a standard escape sequence of Python language and, as per the table in section 1, the Python interpreter will convert double backslashes to single. To get \\ss as the output of step 1, we supply \\\\ss as our first regular expression. The Python interpreter will convert the \\\\ss text pattern to \\ss. Therefore, the solution code to the problem mentioned above is as follows: #### Importing the re packageimport re#### Using the sub function with the modified regexre.sub("\\\\ss","s", "\ssing")#### Sample output'sing' We now have the solution to our problem, but the question which remains is, where did we use the letter r? The regex expression arrived at in the previous discussion is a candidate solution. In simple regex requirements, one can work with the above approach, but consider a scenario where the regular expression dictates the use of multiple meta characters and standard escape sequences. It would require us: To first differentiate between standard and non-standard escape sequences Then, appropriately place the right number of backslashes every time we encounter an escape sequence or metacharacters. In such cumbersome scenarios, taking the below approach helps: The only change we have made here is to replace four backslashes with two preceded by the letter r. It will ensure that in step 1, the Python interpreter considers the regular expression as the raw-string and leaves it as it is. Converting regex to a raw string will ensure the following: We are free from the worry of remembering the list of Python standard escape sequences. We do not have to worry about the right number of backslashes for the presence of standard escape sequences or any metacharacters. Given above, our final and most appropriate solution will be as follows: #### Importing the re packageimport re#### Using the sub function with the modified regexre.sub(r"\\ss","s", "\ssing")#### Sample Output'sing' Watch out for this letter r whenever writing your next regular expression. I hope that this tutorial gave you a good insight into the working of the regular expression. HAPPY LEARNING ! ! ! !
[ { "code": null, "e": 370, "s": 172, "text": "When writing regular expressions (regex) in Python language, we always start with the letter r. In this tutorial, we will understand the reason behind using it by answering the following questions:" }, { "code": null, "e": 592, "s": 370, "text": "What are the escape sequences?How Python interpreter interprets escape sequences with or without the letter r?How regular expressions work in the Python language?The importance of using the letter r in regular expressions" }, { "code": null, "e": 623, "s": 592, "text": "What are the escape sequences?" }, { "code": null, "e": 704, "s": 623, "text": "How Python interpreter interprets escape sequences with or without the letter r?" }, { "code": null, "e": 757, "s": 704, "text": "How regular expressions work in the Python language?" }, { "code": null, "e": 817, "s": 757, "text": "The importance of using the letter r in regular expressions" }, { "code": null, "e": 1204, "s": 817, "text": "An escape sequence is a character set that does not represent itself when used in a text definition. It gets translated to some other character or character set that is otherwise difficult to present in a programming language. For example, in Python language, the character set \\n represents a new line, and \\t represents a tab. Both the character sets, \\n, and \\t are escape sequences." }, { "code": null, "e": 1325, "s": 1204, "text": "The list of standard escape sequences understood by the Python interpreter and their associated meanings are as follows:" }, { "code": null, "e": 1416, "s": 1325, "text": "To understand its impact on escape sequences, let us have a look at the following example:" }, { "code": null, "e": 1853, "s": 1416, "text": "#### Sample Text Definitiontext_1 = \"My name is Ujjwal Dalmia.\\nI love learning and teaching the Python language\"print(text_1)#### Sample OutputMy name is Ujjwal Dalmia.I love learning and teaching the Python language#### Sample Text Definitiontext_2 = \"My name is Ujjwal Dalmia.\\sI love learning and teaching the Python language\"print(text_2)#### Sample OutputMy name is Ujjwal Dalmia.\\sI love learning and teaching the Python language" }, { "code": null, "e": 2324, "s": 1853, "text": "In text_1 above, the example uses \\n character set whereas text_2 uses \\s. From the escape sequences table shared in section 1, we can see that \\n is part of the standard escape sequence-set in Python language, whereas \\s is not. Therefore, when we print both the variables, escape sequence \\n is interpreted as a new line character by the Python interpreter, whereas \\s is left as it is. Note that the definition of both text_1 and text_2 does not include the letter r." }, { "code": null, "e": 2400, "s": 2324, "text": "Let us take a step further and include the letter r in the text definition." }, { "code": null, "e": 2877, "s": 2400, "text": "#### Sample Text Definition (with letter \"r\")text_1 = r\"My name is Ujjwal Dalmia.\\nI love learning and teaching the Python language\"print(text_1)#### Sample OutputMy name is Ujjwal Dalmia.\\nI love learning and teaching the Python language#### Sample Text Definition (with letter \"r\")text_2 = r\"My name is Ujjwal Dalmia.\\sI love learning and teaching the Python language\"print(text_2)#### Sample OutputMy name is Ujjwal Dalmia.\\sI love learning and teaching the Python language" }, { "code": null, "e": 3301, "s": 2877, "text": "The inclusion of the letter r had no impact on text_2 because \\s is not part of the standard escape sequence set in Python language. Surprisingly, for text_1, the Python interpreter did not convert \\n into the new line character. It is because the presence of the letter r has transformed the text into a raw-string. In simple terms, the letter r has instructed the Python interpreter to leave the escape sequence as it is." }, { "code": null, "e": 3568, "s": 3301, "text": "To understand how regular expressions work in Python language, we will use the sub() function (re Python package) that substitutes the part of old text with the new text based on the regular expression driven pattern matching. Let us understand this with an example:" }, { "code": null, "e": 3685, "s": 3568, "text": "#### Importing the re packageimport re#### Using the sub functionre.sub(\"\\ts\",\"s\", \"\\tsing\")#### Sample Output'sing'" }, { "code": null, "e": 4049, "s": 3685, "text": "In this example, we are trying to replace the letter s preceded by a tab with the standalone letter s. One can see from the output that the text \\tsing converts to sing. Let us refer to the below flow chart to understand how the sub() function produced the desired result. In the flow chart, we refer to \\ts as regex, letter s as new text, and \\tsing as old text." }, { "code": null, "e": 4402, "s": 4049, "text": "In the previous example, we have used the character set \\t, which is part of the standard escape list in Python language. Therefore, in the first step, the Python interpreter replaced the escape sequence with the tab in both regex text and the old text. Since the regex pattern matched with the input text in the last step, the substitution took place." }, { "code": null, "e": 4533, "s": 4402, "text": "In the next example, we will use a different character set, \\s, that is not a part of the standard escape list in Python language." }, { "code": null, "e": 4699, "s": 4533, "text": "#### Importing the re packageimport re#### Using the sub function(this time with a non-standard escape sequence)re.sub(\"\\ss\",\"s\", \"\\ssing\")#### Sample Output\"\\ssing\"" }, { "code": null, "e": 5093, "s": 4699, "text": "In this example, we are trying to replace any instance of the letter s preceded by \\s with the standalone letter s. It is evident that there was no change in the input text, and the output remained the same as the old text. Again, in the flow chart, we refer to \\ss as regex, s as the new text, and \\ssing as the old. Let us understand the reason behind this behavior from the below flowchart:" }, { "code": null, "e": 5469, "s": 5093, "text": "In step 1, since \\s is not a standard escape sequence, the Python interpreter neither modified the regular expression nor the old text and left them as it is. In step 2, since \\s is a metacharacter representing space, it gets converted from \\ss to space s. Because in the old text, space s did not exist, there was no positive match, and hence the old-text remained the same." }, { "code": null, "e": 5522, "s": 5469, "text": "The two learnings we can draw from this section are:" }, { "code": null, "e": 5804, "s": 5522, "text": "The evaluation of old text and new text for escape sequences is done only by the Python interpreter. For the regular expression by the Python and the regex interpreter. Therefore, for both old and new text, the outcome of step 1 is their final version, and for regex, it is step 2." }, { "code": null, "e": 6053, "s": 5804, "text": "In a scenario where the texts and regex pattern contain only the standard escape sequence, which is part of Python language, we get our desired results. Whereas, when there are additional metacharacters, the results might not be as per expectation." }, { "code": null, "e": 6218, "s": 6053, "text": "From the 2nd example of the previous section, we saw that the regex failed to deliver the expected result. To find the right solution, let us work our way backward." }, { "code": null, "e": 6349, "s": 6218, "text": "To substitute \\ss from the old text with the letter s, we expect the regex pattern at step 3 to match the text we want to replace." }, { "code": null, "e": 6582, "s": 6349, "text": "To achieve this, we need the regex pattern to be \\\\ss by the end of step two. When the regex interpreter encounters this pattern, it will convert the metacharacters double backslashes to single, and the output of step 2 will be \\ss." }, { "code": null, "e": 6998, "s": 6582, "text": "Finally, to ensure that regex at step 2 is \\\\ss, we pass \\\\\\\\ss at step 1. It is because double backslashes are a standard escape sequence of Python language and, as per the table in section 1, the Python interpreter will convert double backslashes to single. To get \\\\ss as the output of step 1, we supply \\\\\\\\ss as our first regular expression. The Python interpreter will convert the \\\\\\\\ss text pattern to \\\\ss." }, { "code": null, "e": 7073, "s": 6998, "text": "Therefore, the solution code to the problem mentioned above is as follows:" }, { "code": null, "e": 7217, "s": 7073, "text": "#### Importing the re packageimport re#### Using the sub function with the modified regexre.sub(\"\\\\\\\\ss\",\"s\", \"\\ssing\")#### Sample output'sing'" }, { "code": null, "e": 7626, "s": 7217, "text": "We now have the solution to our problem, but the question which remains is, where did we use the letter r? The regex expression arrived at in the previous discussion is a candidate solution. In simple regex requirements, one can work with the above approach, but consider a scenario where the regular expression dictates the use of multiple meta characters and standard escape sequences. It would require us:" }, { "code": null, "e": 7700, "s": 7626, "text": "To first differentiate between standard and non-standard escape sequences" }, { "code": null, "e": 7820, "s": 7700, "text": "Then, appropriately place the right number of backslashes every time we encounter an escape sequence or metacharacters." }, { "code": null, "e": 7883, "s": 7820, "text": "In such cumbersome scenarios, taking the below approach helps:" }, { "code": null, "e": 8172, "s": 7883, "text": "The only change we have made here is to replace four backslashes with two preceded by the letter r. It will ensure that in step 1, the Python interpreter considers the regular expression as the raw-string and leaves it as it is. Converting regex to a raw string will ensure the following:" }, { "code": null, "e": 8260, "s": 8172, "text": "We are free from the worry of remembering the list of Python standard escape sequences." }, { "code": null, "e": 8391, "s": 8260, "text": "We do not have to worry about the right number of backslashes for the presence of standard escape sequences or any metacharacters." }, { "code": null, "e": 8464, "s": 8391, "text": "Given above, our final and most appropriate solution will be as follows:" }, { "code": null, "e": 8607, "s": 8464, "text": "#### Importing the re packageimport re#### Using the sub function with the modified regexre.sub(r\"\\\\ss\",\"s\", \"\\ssing\")#### Sample Output'sing'" }, { "code": null, "e": 8776, "s": 8607, "text": "Watch out for this letter r whenever writing your next regular expression. I hope that this tutorial gave you a good insight into the working of the regular expression." } ]
Suffix Array
From a given string, we can get all possible suffixes. After sorting the suffixes in lexicographical order, we can get the suffix array. Suffix arrays can also be formed using suffix trees. By using the DFS traversal of suffix trees, we can get suffix arrays. Suffix arrays are helpful to find suffixes in linear time. We can also find substrings using suffix array by using binary search type procedure. The time complexity is O(m log n) Input: Main String: “BANANA”, Pattern: “NAN” Output: Pattern found at position: 2 fillSuffixArray (text, suffArray) Input: The main string Output: The array of suffixes Begin n := text Length define suffix array as allSuffix of size n for i := 0 to n-1, do allSuffix[i].index := i allSuffix[i].suff := substring of text from (i to end) done sort the allSuffix array store indexes of all suffix array in suffArray. End suffixArraySearch (text, pattern, suffArray) Input: The main string, the pattern and the suffix array Output − the location where patterns are found Begin patLen := size of pattern strLen := size of text left := 0 right := strLen -1 while left <= right, do mid := left + (right - left)/2 tempStr := substring of text from suffArray[mid] to end result := compare tempStr and pattern upto pattern length. if result = 0, then print the location if res < 0, then right := mid – 1 else left := mid +1 done End #include<iostream> #include<algorithm> #include<cstring> using namespace std; struct suffix { int index; string suff; }; int strCompare(string st1, string st2, int n) { int i = 0; while(n--) { if(st1[i] != st2[i]) return st1[i] - st2[i]; i++; } return 0; } bool comp(suffix suff1, suffix suff2) { //compare two strings for sorting if(suff1.suff<suff2.suff) return true; return false; } void fillSuffixArray(string mainString, int suffArr[]) { int n = mainString.size(); suffix allSuffix[n]; //array to hold all suffixes for(int i = 0; i<n; i++) { allSuffix[i].index = i; allSuffix[i].suff = mainString.substr(i); //from ith position to end } sort(allSuffix, allSuffix+n, comp); for(int i = 0; i<n; i++) suffArr[i] = allSuffix[i].index; //indexes of all sorted suffix } void suffixArraySearch(string mainString, string pattern, int suffArr[], int array[], int *index) { int patLen = pattern.size(); int strLen = mainString.size(); int left = 0, right = strLen - 1; //left and right for binary search while(left <= right) { int mid = left + (right - left)/2; string tempStr = mainString.substr(suffArr[mid]); int result = strCompare(pattern,tempStr, patLen); if(result == 0) { //the pattern is found (*index)++; array[(*index)] = suffArr[mid]; } if(result < 0) right = mid -1; else left = mid +1; } } int main() { string mainString = "BANANA"; string pattern = "NAN"; int locArray[mainString.size()]; int index = -1; int suffArr[mainString.size()]; fillSuffixArray(mainString, suffArr); suffixArraySearch(mainString, pattern, suffArr, locArray, &index); for(int i = 0; i <= index; i++) { cout << "Pattern found at position: " << locArray[i]<<endl; } } Pattern found at position: 2
[ { "code": null, "e": 1467, "s": 1062, "text": "From a given string, we can get all possible suffixes. After sorting the suffixes in lexicographical order, we can get the suffix array. Suffix arrays can also be formed using suffix trees. By using the DFS traversal of suffix trees, we can get suffix arrays. Suffix arrays are helpful to find suffixes in linear time. We can also find substrings using suffix array by using binary search type procedure." }, { "code": null, "e": 1501, "s": 1467, "text": "The time complexity is O(m log n)" }, { "code": null, "e": 1583, "s": 1501, "text": "Input:\nMain String: “BANANA”, Pattern: “NAN”\nOutput:\nPattern found at position: 2" }, { "code": null, "e": 1617, "s": 1583, "text": "fillSuffixArray (text, suffArray)" }, { "code": null, "e": 1640, "s": 1617, "text": "Input: The main string" }, { "code": null, "e": 1670, "s": 1640, "text": "Output: The array of suffixes" }, { "code": null, "e": 1951, "s": 1670, "text": "Begin\n n := text Length\n define suffix array as allSuffix of size n\n\n for i := 0 to n-1, do\n allSuffix[i].index := i\n allSuffix[i].suff := substring of text from (i to end)\n done\n\n sort the allSuffix array\n store indexes of all suffix array in suffArray.\nEnd" }, { "code": null, "e": 1996, "s": 1951, "text": "suffixArraySearch (text, pattern, suffArray)" }, { "code": null, "e": 2053, "s": 1996, "text": "Input: The main string, the pattern and the suffix array" }, { "code": null, "e": 2100, "s": 2053, "text": "Output − the location where patterns are found" }, { "code": null, "e": 2539, "s": 2100, "text": "Begin\n patLen := size of pattern\n strLen := size of text\n left := 0\n right := strLen -1\n\n while left <= right, do\n mid := left + (right - left)/2\n tempStr := substring of text from suffArray[mid] to end\n result := compare tempStr and pattern upto pattern length.\n\n if result = 0, then\n print the location\n if res < 0, then\n right := mid – 1\n else\n left := mid +1\n done\nEnd" }, { "code": null, "e": 4439, "s": 2539, "text": "#include<iostream>\n#include<algorithm>\n#include<cstring>\nusing namespace std;\n\nstruct suffix {\n int index;\n string suff;\n};\n\nint strCompare(string st1, string st2, int n) {\n int i = 0;\n while(n--) {\n if(st1[i] != st2[i])\n return st1[i] - st2[i];\n i++;\n }\n return 0;\n}\n\nbool comp(suffix suff1, suffix suff2) { //compare two strings for sorting\n if(suff1.suff<suff2.suff)\n return true;\n return false;\n}\n\nvoid fillSuffixArray(string mainString, int suffArr[]) {\n int n = mainString.size();\n suffix allSuffix[n]; //array to hold all suffixes\n\n for(int i = 0; i<n; i++) {\n allSuffix[i].index = i;\n allSuffix[i].suff = mainString.substr(i); //from ith position to end\n }\n\n sort(allSuffix, allSuffix+n, comp);\n for(int i = 0; i<n; i++)\n suffArr[i] = allSuffix[i].index; //indexes of all sorted suffix\n}\n\nvoid suffixArraySearch(string mainString, string pattern, int suffArr[], int array[], int *index) {\n int patLen = pattern.size();\n int strLen = mainString.size();\n int left = 0, right = strLen - 1; //left and right for binary search\n\n while(left <= right) {\n int mid = left + (right - left)/2;\n string tempStr = mainString.substr(suffArr[mid]);\n int result = strCompare(pattern,tempStr, patLen);\n \n if(result == 0) { //the pattern is found\n (*index)++;\n array[(*index)] = suffArr[mid];\n }\n\n if(result < 0)\n right = mid -1;\n else\n left = mid +1;\n }\n}\n\nint main() {\n string mainString = \"BANANA\";\n string pattern = \"NAN\";\n int locArray[mainString.size()];\n int index = -1;\n\n int suffArr[mainString.size()];\n fillSuffixArray(mainString, suffArr);\n \n suffixArraySearch(mainString, pattern, suffArr, locArray, &index);\n for(int i = 0; i <= index; i++) {\n cout << \"Pattern found at position: \" << locArray[i]<<endl;\n }\n}" }, { "code": null, "e": 4468, "s": 4439, "text": "Pattern found at position: 2" } ]
Corona Virus | TCS Codevita 2020 - GeeksforGeeks
24 Jan, 2022 Problem Description: A city is represented as a two-dimensional rectangular matrix. The outer wall of the given matrix denotes the boundaries of the city. Citizens are dispersed in the city at different locations. They are either depicted by {a, c}. Coronavirus has already infected the city. The Coronavirus enters the city from coordinate (0, 0) and traverses along a diagonal path until it encounters a human. If it encounters a human, designated as a, its trajectory rotates anti-clockwise (right to left) by 90 degrees. Similarly, if it encounters a human, designated as c, its trajectory rotates clockwise (left to right) by 90 degrees. After infecting the person, the virus continues to move along its diagonal path. During its traversal, if it hits the boundary of the city for the first time, it rotates 90 degrees to reenter the city. However, if it hits any of the boundary walls, the second time, the virus gets destroyed. You have to calculate the trajectory taken by the virus, print the city map where infected citizens can be found and finally report the number of safe and infected citizens. Input: An input matrix of 9 rows and 20 columns consisting of characters “*”, “a”, “c” and “.” where “*” denotes an element on the boundaries of the city “a” denotes citizen after encountering whom the virus trajectory changes by 90 degrees (anti-clockwise direction) “c” denotes citizen after encountering whom the virus trajectory changes by 90 degrees (clockwise direction) “.” (dot) denotes an empty location within the city Output: A random number of lines each denoting the coordinates of the trajectory of the virus. From the next line an output matrix of 9 rows and 20 columns consisting of characters “*”, “a”, “c”, “.” and “-” where “*” denotes an element on the boundaries of the city “a” denotes citizen after encountering whom the virus trajectory changes by 90 degrees (anti-clockwise direction) “c” denotes citizen after encountering whom the virus trajectory changes by 90 degrees (clockwise direction) “.” (dot) denotes an empty location within the city “-“ denotes the location of the infected citizen And the next two lines print the number of safe and infected citizens in the city. Constraints: 0 <= x <= 20 0 <= y <= 8 The virus cannot hit the three corners (20, 8) (20, 0) (0, 8) Examples: Input:*********************....c.............**...c..............**c.................**.............a....**c.c...............**.a................**...........c......*********************Output:0 01 12 21 32 43 54 65 56 47 38 29 110 011 112 213 314 413 512 611 710 8*********************....c.............**...-..............**c.................**.............-....**-.c...............**.-................**...........c......*********************safe=4infected=4Explanation: The virus trajectory starts from (0, 0) and crosses (1, 1) (2, 2). At (2, 2) we have a citizen of type a causing the virus trajectory to be rotated by 90 degrees anti-clockwise. It moves until the next citizen in its path is encountered at (1, 3) of type c causing the virus trajectory to be rotated by 90 degree clockwise. It continues on its path till it reaches the next human in its path at (4, 6) of type c Virus trajectory is again rotated by 90 degrees clockwise until it hits the boundary at (10, 0). Since this is the first time that the virus hits the boundary, it rotates by 90 degrees anticlockwise to reenter the city. The trajectory then continues towards (11, 1) (12, 2) (13, 3) and finally a citizen at (14, 4) of type a rotating the trajectory to 90 degree anticlockwise. From there it continues its trajectory and hits the boundary at (10, 8).Since this is the second time the virus hits the boundary, the virus is destroyed.So, along its trajectory starting from (0, 0) it has infected 4 citizens at location (2, 2) (1, 3) (4, 6) (14, 4). The other 4 citizens who did not come in the virus trajectory are deemed to be safe. Input:*********************..................**..c...............**....c.............**.........a........**..................**.......a......c...**..................*********************Output:0 01 12 23 34 45 56 47 38 29 310 49 58 67 76 85 74 63 52 41 30 2*********************..................**..c...............**....-.............**.........-........**..................**.......-......c...**..................*********************safe=2infected=3Explanation: The virus trajectory starts from (0, 0) and crosses (1, 1) (2, 2) (5, 5). At (5, 5) we have a citizen of type c causing the virus trajectory to be rotated by 90 degrees clockwise. It moves until the next citizen in its path is encountered at (8, 2) of type a causing the virus trajectory to be rotated by 90 degree anti-clockwise. It continues on its path till it reaches the next human in its path at (10, 4) of type a Virus trajectory is again rotated by 90 degrees clockwise until it hits the boundary at (6, 8). Since this is the first time that the virus hits the boundary, it rotates by 90 degrees anticlockwise to reenter the city. The trajectory then continues towards (9, 5) (8, 6) (7, 7) (6, 8) and renters the city by rotating the trajectory by 90 degrees anti-clockwise to follow the trajectory (5, 7) (4, 6) (3, 5) (2, 4) (1, 3) (0, 2).At (0, 2) it again hits the boundary and since this is the second time the virus hits the boundary, the virus is destroyed. So along its trajectory starting from (0, 0) it has infected 3 citizens at location (5, 5) (10, 4) (8, 2). The other 2 citizens who did not come in the virus trajectory are deemed to be safe. Approach: The idea to solve this problem is to first invert the graph represented by the input and traverse the graph according to the given conditions. Follow the below steps to solve the problem: First, invert the input array in an inverted array. So the last row becomes the first and the second last the second and so on. This is done to view the graph in a two-dimension coordinate system with positive x and y. Traverse the graph and keep the track of the number of times the virus has hit the boundary in a variable named bound and run a while loop until the value of this variable is less than or equal to 1. Initialize a variable, direct, to hold the direction of motion as:If direct is 1, the direction is north-east.If direct is 2, the direction is north-west.If direct is 3, the direction is south-east.If direct is 4, the direction is south-west. If direct is 1, the direction is north-east. If direct is 2, the direction is north-west. If direct is 3, the direction is south-east. If direct is 4, the direction is south-west. The virus will have 4 directions of motion. The virus will start from the vertex (0, 0) with the direction of motion as 1(moving towards the north-east). The direction of the variable is changed when it encounters a wall. Also, when ‘a’ is encountered, change the value of direct to the resulting anti-clockwise direction and when ‘c’ is encountered, change the value of direct to 90 degrees clockwise from the current direction. For the ‘.’ (dot) character in the matrix, keep incrementing or decrementing the current position variables by 1 to move diagonally in the direct variable’s depicted direction. Below is the implementation of the above approach: C++ // C++ program for the above approach #include <bits/stdc++.h>using namespace std;#define row 9#define col 20 // Function to print trajectory of the virus// and safe and infected citizensvoid coronaVirus(char arr[row][col]){ // To store Inverted Array char inverted[9][20]; // Temporary array to store // original array char temp[9][20]; // To store number of infected citizens int count = 0; // To store total number of citizens ('a', 'c') int total = 0; // To invert the array for (int i = 0; i <= 8; i++) { for (int j = 0; j < 20; j++) { // Invert the array row wise inverted[i][j] = arr[8 - i][j]; } } // Count the number of citizens for (int i = 0; i <= 8; i++) { for (int j = 0; j < 20; j++) { // Count total number of citizens. if (inverted[i][j] == 'a' || inverted[i][j] == 'c') { total++; } // Copy inverted array in temp temp[i][j] = inverted[i][j]; } } // To store number of times, // virus encountered a boundary int bound = 0; // Variable for row-wise traversal int i = 1; // Variable for column-wise traversal int j = 1; // Variable to store direction int direct = 1; // The virus starts from (0, 0) always cout << "0 0" << endl; // To break infinite looping int flag = 0; // Finding trajectory and safe // and infected citizens while (bound <= 1 && flag < 1000) { flag++; cout << i << " " << j << endl; // Virus has striked the boundary twice. // Therefore, end loop if (inverted[j][i] == '*' && bound == 1) { break; } // Virus striked the corners, end loop if (inverted[j][i] == '*') { if (i == 0 && j == 8 || i == 20 && j == 8 || i == 20 && j == 0) { break; } } // First time for the virus // to hit the boundary if (inverted[j][i] == '*' && bound == 0) { // Increment bound variable bound++; // Strikes the left wall if (i == 0 && j != 8 && j != 0) { // Turns 90 degree clockwise if (direct == 2) { direct = 1; i++; j++; } // Else turns 90 degree anticlockwise else if (direct == 4) { direct = 3; j--; i++; } } // Strikes the right wall else if (i == 20 && j != 0 && j != 8) { // Turns 90 degree anticlockwise if (direct == 1) { direct = 2; i--; j++; } // Else turns 90 degree clockwise else if (direct == 3) { direct = 4; i--; j--; } } // Strikes the upper wall else if (j == 8 && i != 0 && i != 20) { // Turns 90 degree anticlockwise if (direct == 2) { direct = 4; i--; j--; } // Else turns 90 degree clockwise else if (direct == 1) { direct = 3; j--; i++; } } // Strikes the lower wall else if (j == 0 && i != 0 && i != 20) { // Turns 90 degree clockwise if (direct == 4) { direct = 2; i--; j++; } // Else turns 90 degree anticlockwise else if (direct == 3) { direct = 1; i++; j++; } } continue; } // Make 'c' visited by replacing it by'-' if (inverted[j][i] == 'c') { temp[j][i] = '-'; // Turns all directions 90 // degree clockwise if (direct == 1) { direct = 3; j--; i++; } else if (direct == 2) { direct = 1; i++; j++; } else if (direct == 3) { direct = 4; i--; j--; } else if (direct == 4) { direct = 2; i--; j++; } // Increment count of infected citizens count++; continue; } // Make 'a' visited by replacing it by'-' if (inverted[j][i] == 'a') { temp[j][i] = '-'; // Turns all directions by 90 degree // anticlockwise if (direct == 1) { direct = 2; i--; j++; } else if (direct == 2) { direct = 4; i--; j--; } else if (direct == 3) { direct = 1; i++; j++; } else if (direct == 4) { direct = 3; j--; i++; } // Increment count of // infected citizens count++; continue; } // Increment the counter diagonally // in the given direction. if (inverted[j][i] == '.') { if (direct == 1) { i++; j++; } else if (direct == 2) { i--; j++; } else if (direct == 3) { j--; i++; } else if (direct == 4) { i--; j--; } continue; } } // Print the mirror of the array // i.e. last row must be printed first. for (int i = 0; i <= 8; i++) { for (int j = 0; j < 20; j++) { cout << temp[8 - i][j]; } cout << endl; } // Print safe and infected citizens cout << "safe=" << (total - count) << endl; cout << "infected=" << (count) << endl;} // Driver Codeint main(){ // Given 2D array char arr[row][col] = { { '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*' }, { '*', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '*' }, { '*', '.', '.', 'c', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '*' }, { '*', '.', '.', '.', '.', 'c', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '*' }, { '*', '.', '.', '.', '.', '.', '.', '.', '.', '.', 'a', '.', '.', '.', '.', '.', '.', '.', '.', '*' }, { '*', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '*' }, { '*', '.', '.', '.', '.', '.', '.', '.', 'a', '.', '.', '.', '.', '.', '.', 'c', '.', '.', '.', '*' }, { '*', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '*' }, { '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*' } }; // Function Call coronaVirus(arr); return 0;} 0 0 1 1 2 2 3 3 4 4 5 5 6 4 7 3 8 2 9 3 10 4 9 5 8 6 7 7 6 8 5 7 4 6 3 5 2 4 1 3 0 2 ******************** *..................* *..c...............* *....-.............* *.........-........* *..................* *.......-......c...* *..................* ******************** safe=2 infected=3 Time Complexity: O(R*C) where R is the number of rows and C is the number of columnsAuxiliary Space: O(R*C) akshaysingh98088 rkbhola5 TCS Graph TCS Graph Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Best First Search (Informed Search) Longest Path in a Directed Acyclic Graph Graph Coloring | Set 2 (Greedy Algorithm) Find if there is a path between two vertices in a directed graph Vertex Cover Problem | Set 1 (Introduction and Approximate Algorithm) Snake and Ladder Problem Check if a given graph is tree or not Tree, Back, Edge and Cross Edges in DFS of Graph Iterative Deepening Search(IDS) or Iterative Deepening Depth First Search(IDDFS) Real-time application of Data Structures
[ { "code": null, "e": 24675, "s": 24647, "text": "\n24 Jan, 2022" }, { "code": null, "e": 24696, "s": 24675, "text": "Problem Description:" }, { "code": null, "e": 24968, "s": 24696, "text": "A city is represented as a two-dimensional rectangular matrix. The outer wall of the given matrix denotes the boundaries of the city. Citizens are dispersed in the city at different locations. They are either depicted by {a, c}. Coronavirus has already infected the city." }, { "code": null, "e": 25399, "s": 24968, "text": "The Coronavirus enters the city from coordinate (0, 0) and traverses along a diagonal path until it encounters a human. If it encounters a human, designated as a, its trajectory rotates anti-clockwise (right to left) by 90 degrees. Similarly, if it encounters a human, designated as c, its trajectory rotates clockwise (left to right) by 90 degrees. After infecting the person, the virus continues to move along its diagonal path." }, { "code": null, "e": 25610, "s": 25399, "text": "During its traversal, if it hits the boundary of the city for the first time, it rotates 90 degrees to reenter the city. However, if it hits any of the boundary walls, the second time, the virus gets destroyed." }, { "code": null, "e": 25784, "s": 25610, "text": "You have to calculate the trajectory taken by the virus, print the city map where infected citizens can be found and finally report the number of safe and infected citizens." }, { "code": null, "e": 25791, "s": 25784, "text": "Input:" }, { "code": null, "e": 25885, "s": 25791, "text": "An input matrix of 9 rows and 20 columns consisting of characters “*”, “a”, “c” and “.” where" }, { "code": null, "e": 25938, "s": 25885, "text": "“*” denotes an element on the boundaries of the city" }, { "code": null, "e": 26052, "s": 25938, "text": "“a” denotes citizen after encountering whom the virus trajectory changes by 90 degrees (anti-clockwise direction)" }, { "code": null, "e": 26161, "s": 26052, "text": "“c” denotes citizen after encountering whom the virus trajectory changes by 90 degrees (clockwise direction)" }, { "code": null, "e": 26214, "s": 26161, "text": "“.” (dot) denotes an empty location within the city " }, { "code": null, "e": 26222, "s": 26214, "text": "Output:" }, { "code": null, "e": 26309, "s": 26222, "text": "A random number of lines each denoting the coordinates of the trajectory of the virus." }, { "code": null, "e": 26428, "s": 26309, "text": "From the next line an output matrix of 9 rows and 20 columns consisting of characters “*”, “a”, “c”, “.” and “-” where" }, { "code": null, "e": 26481, "s": 26428, "text": "“*” denotes an element on the boundaries of the city" }, { "code": null, "e": 26595, "s": 26481, "text": "“a” denotes citizen after encountering whom the virus trajectory changes by 90 degrees (anti-clockwise direction)" }, { "code": null, "e": 26704, "s": 26595, "text": "“c” denotes citizen after encountering whom the virus trajectory changes by 90 degrees (clockwise direction)" }, { "code": null, "e": 26756, "s": 26704, "text": "“.” (dot) denotes an empty location within the city" }, { "code": null, "e": 26805, "s": 26756, "text": "“-“ denotes the location of the infected citizen" }, { "code": null, "e": 26888, "s": 26805, "text": "And the next two lines print the number of safe and infected citizens in the city." }, { "code": null, "e": 26901, "s": 26888, "text": "Constraints:" }, { "code": null, "e": 26914, "s": 26901, "text": "0 <= x <= 20" }, { "code": null, "e": 26926, "s": 26914, "text": "0 <= y <= 8" }, { "code": null, "e": 26988, "s": 26926, "text": "The virus cannot hit the three corners (20, 8) (20, 0) (0, 8)" }, { "code": null, "e": 26998, "s": 26988, "text": "Examples:" }, { "code": null, "e": 28615, "s": 26998, "text": "Input:*********************....c.............**...c..............**c.................**.............a....**c.c...............**.a................**...........c......*********************Output:0 01 12 21 32 43 54 65 56 47 38 29 110 011 112 213 314 413 512 611 710 8*********************....c.............**...-..............**c.................**.............-....**-.c...............**.-................**...........c......*********************safe=4infected=4Explanation: The virus trajectory starts from (0, 0) and crosses (1, 1) (2, 2). At (2, 2) we have a citizen of type a causing the virus trajectory to be rotated by 90 degrees anti-clockwise. It moves until the next citizen in its path is encountered at (1, 3) of type c causing the virus trajectory to be rotated by 90 degree clockwise. It continues on its path till it reaches the next human in its path at (4, 6) of type c Virus trajectory is again rotated by 90 degrees clockwise until it hits the boundary at (10, 0). Since this is the first time that the virus hits the boundary, it rotates by 90 degrees anticlockwise to reenter the city. The trajectory then continues towards (11, 1) (12, 2) (13, 3) and finally a citizen at (14, 4) of type a rotating the trajectory to 90 degree anticlockwise. From there it continues its trajectory and hits the boundary at (10, 8).Since this is the second time the virus hits the boundary, the virus is destroyed.So, along its trajectory starting from (0, 0) it has infected 4 citizens at location (2, 2) (1, 3) (4, 6) (14, 4). The other 4 citizens who did not come in the virus trajectory are deemed to be safe." }, { "code": null, "e": 30246, "s": 28615, "text": "Input:*********************..................**..c...............**....c.............**.........a........**..................**.......a......c...**..................*********************Output:0 01 12 23 34 45 56 47 38 29 310 49 58 67 76 85 74 63 52 41 30 2*********************..................**..c...............**....-.............**.........-........**..................**.......-......c...**..................*********************safe=2infected=3Explanation: The virus trajectory starts from (0, 0) and crosses (1, 1) (2, 2) (5, 5). At (5, 5) we have a citizen of type c causing the virus trajectory to be rotated by 90 degrees clockwise. It moves until the next citizen in its path is encountered at (8, 2) of type a causing the virus trajectory to be rotated by 90 degree anti-clockwise. It continues on its path till it reaches the next human in its path at (10, 4) of type a Virus trajectory is again rotated by 90 degrees clockwise until it hits the boundary at (6, 8). Since this is the first time that the virus hits the boundary, it rotates by 90 degrees anticlockwise to reenter the city. The trajectory then continues towards (9, 5) (8, 6) (7, 7) (6, 8) and renters the city by rotating the trajectory by 90 degrees anti-clockwise to follow the trajectory (5, 7) (4, 6) (3, 5) (2, 4) (1, 3) (0, 2).At (0, 2) it again hits the boundary and since this is the second time the virus hits the boundary, the virus is destroyed. So along its trajectory starting from (0, 0) it has infected 3 citizens at location (5, 5) (10, 4) (8, 2). The other 2 citizens who did not come in the virus trajectory are deemed to be safe." }, { "code": null, "e": 30444, "s": 30246, "text": "Approach: The idea to solve this problem is to first invert the graph represented by the input and traverse the graph according to the given conditions. Follow the below steps to solve the problem:" }, { "code": null, "e": 30663, "s": 30444, "text": "First, invert the input array in an inverted array. So the last row becomes the first and the second last the second and so on. This is done to view the graph in a two-dimension coordinate system with positive x and y." }, { "code": null, "e": 30863, "s": 30663, "text": "Traverse the graph and keep the track of the number of times the virus has hit the boundary in a variable named bound and run a while loop until the value of this variable is less than or equal to 1." }, { "code": null, "e": 31106, "s": 30863, "text": "Initialize a variable, direct, to hold the direction of motion as:If direct is 1, the direction is north-east.If direct is 2, the direction is north-west.If direct is 3, the direction is south-east.If direct is 4, the direction is south-west." }, { "code": null, "e": 31151, "s": 31106, "text": "If direct is 1, the direction is north-east." }, { "code": null, "e": 31196, "s": 31151, "text": "If direct is 2, the direction is north-west." }, { "code": null, "e": 31241, "s": 31196, "text": "If direct is 3, the direction is south-east." }, { "code": null, "e": 31286, "s": 31241, "text": "If direct is 4, the direction is south-west." }, { "code": null, "e": 31508, "s": 31286, "text": "The virus will have 4 directions of motion. The virus will start from the vertex (0, 0) with the direction of motion as 1(moving towards the north-east). The direction of the variable is changed when it encounters a wall." }, { "code": null, "e": 31716, "s": 31508, "text": "Also, when ‘a’ is encountered, change the value of direct to the resulting anti-clockwise direction and when ‘c’ is encountered, change the value of direct to 90 degrees clockwise from the current direction." }, { "code": null, "e": 31893, "s": 31716, "text": "For the ‘.’ (dot) character in the matrix, keep incrementing or decrementing the current position variables by 1 to move diagonally in the direct variable’s depicted direction." }, { "code": null, "e": 31944, "s": 31893, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 31948, "s": 31944, "text": "C++" }, { "code": "// C++ program for the above approach #include <bits/stdc++.h>using namespace std;#define row 9#define col 20 // Function to print trajectory of the virus// and safe and infected citizensvoid coronaVirus(char arr[row][col]){ // To store Inverted Array char inverted[9][20]; // Temporary array to store // original array char temp[9][20]; // To store number of infected citizens int count = 0; // To store total number of citizens ('a', 'c') int total = 0; // To invert the array for (int i = 0; i <= 8; i++) { for (int j = 0; j < 20; j++) { // Invert the array row wise inverted[i][j] = arr[8 - i][j]; } } // Count the number of citizens for (int i = 0; i <= 8; i++) { for (int j = 0; j < 20; j++) { // Count total number of citizens. if (inverted[i][j] == 'a' || inverted[i][j] == 'c') { total++; } // Copy inverted array in temp temp[i][j] = inverted[i][j]; } } // To store number of times, // virus encountered a boundary int bound = 0; // Variable for row-wise traversal int i = 1; // Variable for column-wise traversal int j = 1; // Variable to store direction int direct = 1; // The virus starts from (0, 0) always cout << \"0 0\" << endl; // To break infinite looping int flag = 0; // Finding trajectory and safe // and infected citizens while (bound <= 1 && flag < 1000) { flag++; cout << i << \" \" << j << endl; // Virus has striked the boundary twice. // Therefore, end loop if (inverted[j][i] == '*' && bound == 1) { break; } // Virus striked the corners, end loop if (inverted[j][i] == '*') { if (i == 0 && j == 8 || i == 20 && j == 8 || i == 20 && j == 0) { break; } } // First time for the virus // to hit the boundary if (inverted[j][i] == '*' && bound == 0) { // Increment bound variable bound++; // Strikes the left wall if (i == 0 && j != 8 && j != 0) { // Turns 90 degree clockwise if (direct == 2) { direct = 1; i++; j++; } // Else turns 90 degree anticlockwise else if (direct == 4) { direct = 3; j--; i++; } } // Strikes the right wall else if (i == 20 && j != 0 && j != 8) { // Turns 90 degree anticlockwise if (direct == 1) { direct = 2; i--; j++; } // Else turns 90 degree clockwise else if (direct == 3) { direct = 4; i--; j--; } } // Strikes the upper wall else if (j == 8 && i != 0 && i != 20) { // Turns 90 degree anticlockwise if (direct == 2) { direct = 4; i--; j--; } // Else turns 90 degree clockwise else if (direct == 1) { direct = 3; j--; i++; } } // Strikes the lower wall else if (j == 0 && i != 0 && i != 20) { // Turns 90 degree clockwise if (direct == 4) { direct = 2; i--; j++; } // Else turns 90 degree anticlockwise else if (direct == 3) { direct = 1; i++; j++; } } continue; } // Make 'c' visited by replacing it by'-' if (inverted[j][i] == 'c') { temp[j][i] = '-'; // Turns all directions 90 // degree clockwise if (direct == 1) { direct = 3; j--; i++; } else if (direct == 2) { direct = 1; i++; j++; } else if (direct == 3) { direct = 4; i--; j--; } else if (direct == 4) { direct = 2; i--; j++; } // Increment count of infected citizens count++; continue; } // Make 'a' visited by replacing it by'-' if (inverted[j][i] == 'a') { temp[j][i] = '-'; // Turns all directions by 90 degree // anticlockwise if (direct == 1) { direct = 2; i--; j++; } else if (direct == 2) { direct = 4; i--; j--; } else if (direct == 3) { direct = 1; i++; j++; } else if (direct == 4) { direct = 3; j--; i++; } // Increment count of // infected citizens count++; continue; } // Increment the counter diagonally // in the given direction. if (inverted[j][i] == '.') { if (direct == 1) { i++; j++; } else if (direct == 2) { i--; j++; } else if (direct == 3) { j--; i++; } else if (direct == 4) { i--; j--; } continue; } } // Print the mirror of the array // i.e. last row must be printed first. for (int i = 0; i <= 8; i++) { for (int j = 0; j < 20; j++) { cout << temp[8 - i][j]; } cout << endl; } // Print safe and infected citizens cout << \"safe=\" << (total - count) << endl; cout << \"infected=\" << (count) << endl;} // Driver Codeint main(){ // Given 2D array char arr[row][col] = { { '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*' }, { '*', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '*' }, { '*', '.', '.', 'c', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '*' }, { '*', '.', '.', '.', '.', 'c', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '*' }, { '*', '.', '.', '.', '.', '.', '.', '.', '.', '.', 'a', '.', '.', '.', '.', '.', '.', '.', '.', '*' }, { '*', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '*' }, { '*', '.', '.', '.', '.', '.', '.', '.', 'a', '.', '.', '.', '.', '.', '.', 'c', '.', '.', '.', '*' }, { '*', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '.', '*' }, { '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*', '*' } }; // Function Call coronaVirus(arr); return 0;}", "e": 39712, "s": 31948, "text": null }, { "code": null, "e": 40004, "s": 39712, "text": "0 0\n1 1\n2 2\n3 3\n4 4\n5 5\n6 4\n7 3\n8 2\n9 3\n10 4\n9 5\n8 6\n7 7\n6 8\n5 7\n4 6\n3 5\n2 4\n1 3\n0 2\n********************\n*..................*\n*..c...............*\n*....-.............*\n*.........-........*\n*..................*\n*.......-......c...*\n*..................*\n********************\nsafe=2\ninfected=3" }, { "code": null, "e": 40114, "s": 40006, "text": "Time Complexity: O(R*C) where R is the number of rows and C is the number of columnsAuxiliary Space: O(R*C)" }, { "code": null, "e": 40133, "s": 40116, "text": "akshaysingh98088" }, { "code": null, "e": 40142, "s": 40133, "text": "rkbhola5" }, { "code": null, "e": 40146, "s": 40142, "text": "TCS" }, { "code": null, "e": 40152, "s": 40146, "text": "Graph" }, { "code": null, "e": 40156, "s": 40152, "text": "TCS" }, { "code": null, "e": 40162, "s": 40156, "text": "Graph" }, { "code": null, "e": 40260, "s": 40162, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 40269, "s": 40260, "text": "Comments" }, { "code": null, "e": 40282, "s": 40269, "text": "Old Comments" }, { "code": null, "e": 40318, "s": 40282, "text": "Best First Search (Informed Search)" }, { "code": null, "e": 40359, "s": 40318, "text": "Longest Path in a Directed Acyclic Graph" }, { "code": null, "e": 40401, "s": 40359, "text": "Graph Coloring | Set 2 (Greedy Algorithm)" }, { "code": null, "e": 40466, "s": 40401, "text": "Find if there is a path between two vertices in a directed graph" }, { "code": null, "e": 40536, "s": 40466, "text": "Vertex Cover Problem | Set 1 (Introduction and Approximate Algorithm)" }, { "code": null, "e": 40561, "s": 40536, "text": "Snake and Ladder Problem" }, { "code": null, "e": 40599, "s": 40561, "text": "Check if a given graph is tree or not" }, { "code": null, "e": 40648, "s": 40599, "text": "Tree, Back, Edge and Cross Edges in DFS of Graph" }, { "code": null, "e": 40729, "s": 40648, "text": "Iterative Deepening Search(IDS) or Iterative Deepening Depth First Search(IDDFS)" } ]
Handling missing keys in Python dictionaries
In Python there is one container called the Dictionary. In the dictionaries, we can map keys to its value. Using dictionary the values can be accessed in constant time. But when the given keys are not present, it may occur some errors. In this section we will see how to handle these kind of errors. If we are trying to access missing keys, it may return errors like this. Live Demo country_dict = {'India' : 'IN', 'Australia' : 'AU', 'Brazil' : 'BR'} print(country_dict['Australia']) print(country_dict['Canada']) # This will return error AU --------------------------------------------------------------------------- KeyErrorTraceback (most recent call last) <ipython-input-2-a91092e7ee85> in <module>() 2 3 print(country_dict['Australia']) ----> 4 print(country_dict['Canada'])# This will return error KeyError: 'Canada' We can use the get method to check for keys. This method takes two parameters. The first one is the key, and the second one is the default value. When the key is found, it will return the value associated with the key, but when the key is not present, it will return the default value, which is passed as second argument. Live Demo country_dict = {'India' : 'IN', 'Australia' : 'AU', 'Brazil' : 'BR'} print(country_dict.get('Australia', 'Not Found')) print(country_dict.get('Canada', 'Not Found')) AU Not Found This setdefault() method is similar to the get() method. It also takes two argument like get(). The first one is the key and the second one is default value. The only difference of this method is, when there is a missing key, it will add new keys with default value. Live Demo country_dict = {'India' : 'IN', 'Australia' : 'AU', 'Brazil' : 'BR'} country_dict.setdefault('Canada', 'Not Present') #Set a default value for Canada print(country_dict['Australia']) print(country_dict['Canada']) AU Not Present The defaultdict is a container. It is located at the collections module in Python. The defaultdict takes the default factory as its argument. Initially the default factory is set to 0 (integer). When a key is not present, it returns the value of default factory. We do not need to specify the methods again and again, so it provides faster method for the dictionary objects. Live Demo import collections as col #set the default factory with the string 'key not present' country_dict = col.defaultdict(lambda: 'Key Not Present') country_dict['India'] = 'IN' country_dict['Australia'] = 'AU' country_dict['Brazil'] = 'BR' print(country_dict['Australia']) print(country_dict['Canada']) AU Key Not Present
[ { "code": null, "e": 1298, "s": 1062, "text": "In Python there is one container called the Dictionary. In the dictionaries, we can map keys to its value. Using dictionary the values can be accessed in constant time. But when the given keys are not present, it may occur some errors." }, { "code": null, "e": 1435, "s": 1298, "text": "In this section we will see how to handle these kind of errors. If we are trying to access missing keys, it may return errors like this." }, { "code": null, "e": 1446, "s": 1435, "text": " Live Demo" }, { "code": null, "e": 1603, "s": 1446, "text": "country_dict = {'India' : 'IN', 'Australia' : 'AU', 'Brazil' : 'BR'}\nprint(country_dict['Australia'])\nprint(country_dict['Canada']) # This will return error" }, { "code": null, "e": 1902, "s": 1603, "text": "AU\n---------------------------------------------------------------------------\nKeyErrorTraceback (most recent call last)\n<ipython-input-2-a91092e7ee85> in <module>()\n 2 \n 3 print(country_dict['Australia'])\n----> 4 print(country_dict['Canada'])# This will return error\n\nKeyError: 'Canada'\n" }, { "code": null, "e": 2225, "s": 1902, "text": "We can use the get method to check for keys. This method takes two parameters. The first one is the key, and the second one is the default value. When the key is found, it will return the value associated with the key, but when the key is not present, it will return the default value, which is passed as second argument." }, { "code": null, "e": 2236, "s": 2225, "text": " Live Demo" }, { "code": null, "e": 2402, "s": 2236, "text": "country_dict = {'India' : 'IN', 'Australia' : 'AU', 'Brazil' : 'BR'}\nprint(country_dict.get('Australia', 'Not Found'))\nprint(country_dict.get('Canada', 'Not Found'))" }, { "code": null, "e": 2416, "s": 2402, "text": "AU\nNot Found\n" }, { "code": null, "e": 2683, "s": 2416, "text": "This setdefault() method is similar to the get() method. It also takes two argument like get(). The first one is the key and the second one is default value. The only difference of this method is, when there is a missing key, it will add new keys with default value." }, { "code": null, "e": 2694, "s": 2683, "text": " Live Demo" }, { "code": null, "e": 2907, "s": 2694, "text": "country_dict = {'India' : 'IN', 'Australia' : 'AU', 'Brazil' : 'BR'}\ncountry_dict.setdefault('Canada', 'Not Present') #Set a default value for Canada\nprint(country_dict['Australia'])\nprint(country_dict['Canada'])" }, { "code": null, "e": 2923, "s": 2907, "text": "AU\nNot Present\n" }, { "code": null, "e": 3186, "s": 2923, "text": "The defaultdict is a container. It is located at the collections module in Python. The defaultdict takes the default factory as its argument. Initially the default factory is set to 0 (integer). When a key is not present, it returns the value of default factory." }, { "code": null, "e": 3298, "s": 3186, "text": "We do not need to specify the methods again and again, so it provides faster method for the dictionary objects." }, { "code": null, "e": 3309, "s": 3298, "text": " Live Demo" }, { "code": null, "e": 3607, "s": 3309, "text": "import collections as col\n#set the default factory with the string 'key not present'\ncountry_dict = col.defaultdict(lambda: 'Key Not Present')\ncountry_dict['India'] = 'IN'\ncountry_dict['Australia'] = 'AU'\ncountry_dict['Brazil'] = 'BR'\nprint(country_dict['Australia'])\nprint(country_dict['Canada'])" }, { "code": null, "e": 3627, "s": 3607, "text": "AU\nKey Not Present\n" } ]
Convert string to lowercase or uppercase in Arduino
In order to convert a string to lower/upper case, the in-built .toLowerCase() and .toUpperCase() functions can be used. Note: These functions change the original string itself, and don't return a new string with the changes. The implementation is shown below − void setup() { Serial.begin(9600); Serial.println(); String s1 = "Hello World"; Serial.println(s1); s1.toLowerCase(); Serial.println(s1); s1.toUpperCase(); Serial.println(s1); } void loop() { // put your main code here, to run repeatedly: } The corresponding Serial Monitor output is − As you can see, the changes have been made in s1 itself. The return of .toUpperCase() and .toLowerCase() is void.
[ { "code": null, "e": 1182, "s": 1062, "text": "In order to convert a string to lower/upper case, the in-built .toLowerCase() and .toUpperCase() functions can be used." }, { "code": null, "e": 1287, "s": 1182, "text": "Note: These functions change the original string itself, and don't return a new string with the changes." }, { "code": null, "e": 1323, "s": 1287, "text": "The implementation is shown below −" }, { "code": null, "e": 1591, "s": 1323, "text": "void setup() {\n Serial.begin(9600);\n Serial.println();\n String s1 = \"Hello World\";\n Serial.println(s1);\n s1.toLowerCase();\n Serial.println(s1);\n s1.toUpperCase();\n Serial.println(s1);\n}\nvoid loop() {\n // put your main code here, to run repeatedly:\n}" }, { "code": null, "e": 1636, "s": 1591, "text": "The corresponding Serial Monitor output is −" }, { "code": null, "e": 1750, "s": 1636, "text": "As you can see, the changes have been made in s1 itself. The return of .toUpperCase() and .toLowerCase() is void." } ]
Vertical Width of a Binary Tree | Practice | GeeksforGeeks
Given a Binary Tree of N nodes. Find the vertical width of the tree. Example 1: Input: 1 / \ 2 3 / \ / \ 4 5 6 7 \ \ 8 9 Output: 6 Explanation: The width of a binary tree is the number of vertical paths in that tree. The above tree contains 6 vertical lines. Example 2: Input: 1 / \ 2 3 Output: 3 Your Task: You don't have to read input or print anything. Your task is to complete the function verticalWidth() which takes root as the only parameter, and returns the vertical width of the binary tree. Expected Time Complexity: O(N). Expected Auxiliary Space: O(Height of the Tree). Constraints: 1 <= Number of nodes <= 105 0 prasad119042891 week ago Simple approach in Java public static int[] helper(Node root){ int[] res = new int[2]; if(root == null){ return res; } int[] leftres = helper(root.left); int[] rightres = helper(root.right); res[0] = Math.max(leftres[0]+1,rightres[0]-1); res[0] = Math.max(res[0],0); res[1] = Math.max(leftres[1]-1,rightres[1]+1); res[1] = Math.max(res[1],0); return res; } //Function to find the vertical width of a Binary Tree. public static int verticalWidth(Node root){ // code here. if(root == null){ return 0; } int[] res = helper(root); return res[0]+res[1]-1;} 0 amankumar2783 weeks ago Very EASY JAVA SOLUTION: Without use of HashMap: NOTE: I removed STATIC from both function: class Tree{ int max=0; int min=0; public void resl(Node root,int index){ if(index>max) max=index; if(index<min) min=index; if(root.left!=null) resl(root.left,index-1); if(root.right!=null) resl(root.right,index+1); } //Function to find the vertical width of a Binary Tree. public int verticalWidth(Node root){ // code here. if(root==null){ return 0; } resl(root,0); return max-min+1;}} 0 rohanyt744 weeks ago void inorder(Node*root,int h, unordered_set<int>&st){ if(!root)return; else{ inorder(root->left,h-1,st); st.insert(h); inorder(root->right,h+1,st); }}int verticalWidth(Node* root){ // Code here unordered_set<int>st; inorder(root,0,st); return st.size();} +2 tbomble62921 month ago unordered_set<int>st; void inorder(Node *root, int hd) { if(root != NULL) { inorder(root->left, hd-1); st.insert(hd); inorder(root->right, hd+1); } } int verticalWidth(Node* root) { st.clear(); inorder(root, 0); return st.size(); } 0 amanavengeraman1 month ago public static int verticalWidth(Node root){ if(root == null){ return 0; } HashMap<Integer, Integer> hm = new HashMap<>(); lvl(root, 0, hm); return hm.size();}static void lvl(Node root, int dis, HashMap<Integer, Integer> hm){ if(root == null){ return; } if(!hm.containsKey(dis)){ hm.put(dis,root.data); } lvl(root.left, dis-1, hm); lvl(root.right, dis+1, hm); return;} 0 forcer2 months ago map<int,int>m; if(!root) return 0; queue<pair<Node*,int>>q; q.push({root,0}); while(!q.empty()) { Node *t=q.front().first; int val=q.front().second; q.pop(); m[val]++; if(t->left) q.push({t->left,val-1}); if(t->right) q.push({t->right,val+1}); } return m.size(); +5 gurjotsingh21003Premium2 months ago EASY C++ solution void width(Node* root,int& lmost,int& rmost,int level) { if(root==NULL)return; width(root->left,lmost,rmost,level-1); lmost=min(lmost,level); width(root->right,lmost,rmost,level+1); rmost=max(rmost,level); } int verticalWidth(Node* root) { // Code here if(root==NULL)return 0; int lmost=INT_MAX; int rmost=INT_MIN; int level=0; width(root,lmost,rmost,level); return (rmost-lmost+1); } +2 harshitraj7122 months ago Nasa walon se jyaada toh tree ke sawaal khatarnaak hain 0 shubhamkavia1998 This comment was deleted. 0 ankitgupta502 months ago // BFS Approach class Tree{ public static class Pair{ Node root; int level; Pair(Node root, int level){ this.root = root; this.level = level; } } //Function to find the vertical width of a Binary Tree. public static int verticalWidth(Node root){ if(root==null) return 0; Queue<Pair> q = new LinkedList<>(); q.add(new Pair(root,1)); int min = Integer.MAX_VALUE; int max = Integer.MIN_VALUE; while(!q.isEmpty()){ Pair temp = q.remove(); min = Math.min(min,temp.level); max = Math.max(max,temp.level); if(temp.root.left!=null){ q.add(new Pair(temp.root.left,temp.level-1)); } if(temp.root.right!=null){ q.add(new Pair(temp.root.right,temp.level+1)); } } return max-min+1;}} We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial? Login to access your submissions. Problem Contest Reset the IDE using the second button on the top right corner. Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints. You can access the hints to get an idea about what is expected of you as well as the final solution code. You can view the solutions submitted by other users from the submission tab.
[ { "code": null, "e": 307, "s": 226, "text": "Given a Binary Tree of N nodes. Find the vertical width of the tree.\n\nExample 1:" }, { "code": null, "e": 566, "s": 307, "text": "Input:\n 1\n / \\\n 2 3\n / \\ / \\\n 4 5 6 7\n \\ \\\n 8 9\nOutput: 6\nExplanation: The width of a binary tree is\nthe number of vertical paths in that tree.\n\n\n\nThe above tree contains 6 vertical lines." }, { "code": null, "e": 579, "s": 568, "text": "Example 2:" }, { "code": null, "e": 624, "s": 579, "text": "Input:\n 1\n / \\\n 2 3\nOutput: 3\n" }, { "code": null, "e": 637, "s": 626, "text": "Your Task:" }, { "code": null, "e": 830, "s": 637, "text": "You don't have to read input or print anything. Your task is to complete the function verticalWidth() which takes root as the only parameter, and returns the vertical width of the binary tree." }, { "code": null, "e": 913, "s": 832, "text": "Expected Time Complexity: O(N).\nExpected Auxiliary Space: O(Height of the Tree)." }, { "code": null, "e": 956, "s": 915, "text": "Constraints:\n1 <= Number of nodes <= 105" }, { "code": null, "e": 958, "s": 956, "text": "0" }, { "code": null, "e": 983, "s": 958, "text": "prasad119042891 week ago" }, { "code": null, "e": 1007, "s": 983, "text": "Simple approach in Java" }, { "code": null, "e": 1635, "s": 1009, "text": "public static int[] helper(Node root){ int[] res = new int[2]; if(root == null){ return res; } int[] leftres = helper(root.left); int[] rightres = helper(root.right); res[0] = Math.max(leftres[0]+1,rightres[0]-1); res[0] = Math.max(res[0],0); res[1] = Math.max(leftres[1]-1,rightres[1]+1); res[1] = Math.max(res[1],0); return res; } //Function to find the vertical width of a Binary Tree. public static int verticalWidth(Node root){ // code here. if(root == null){ return 0; } int[] res = helper(root); return res[0]+res[1]-1;}" }, { "code": null, "e": 1637, "s": 1635, "text": "0" }, { "code": null, "e": 1661, "s": 1637, "text": "amankumar2783 weeks ago" }, { "code": null, "e": 1686, "s": 1661, "text": "Very EASY JAVA SOLUTION:" }, { "code": null, "e": 1710, "s": 1686, "text": "Without use of HashMap:" }, { "code": null, "e": 1753, "s": 1710, "text": "NOTE: I removed STATIC from both function:" }, { "code": null, "e": 2237, "s": 1755, "text": "class Tree{ int max=0; int min=0; public void resl(Node root,int index){ if(index>max) max=index; if(index<min) min=index; if(root.left!=null) resl(root.left,index-1); if(root.right!=null) resl(root.right,index+1); } //Function to find the vertical width of a Binary Tree. public int verticalWidth(Node root){ // code here. if(root==null){ return 0; } resl(root,0); return max-min+1;}}" }, { "code": null, "e": 2239, "s": 2237, "text": "0" }, { "code": null, "e": 2260, "s": 2239, "text": "rohanyt744 weeks ago" }, { "code": null, "e": 2564, "s": 2260, "text": "void inorder(Node*root,int h, unordered_set<int>&st){ if(!root)return; else{ inorder(root->left,h-1,st); st.insert(h); inorder(root->right,h+1,st); }}int verticalWidth(Node* root){ // Code here unordered_set<int>st; inorder(root,0,st); return st.size();} " }, { "code": null, "e": 2567, "s": 2564, "text": "+2" }, { "code": null, "e": 2590, "s": 2567, "text": "tbomble62921 month ago" }, { "code": null, "e": 2770, "s": 2590, "text": "unordered_set<int>st;\nvoid inorder(Node *root, int hd)\n{\n if(root != NULL)\n {\n inorder(root->left, hd-1);\n st.insert(hd);\n inorder(root->right, hd+1);\n }\n}" }, { "code": null, "e": 2862, "s": 2770, "text": "\nint verticalWidth(Node* root)\n{\n st.clear();\n inorder(root, 0);\n return st.size();\n}" }, { "code": null, "e": 2864, "s": 2862, "text": "0" }, { "code": null, "e": 2891, "s": 2864, "text": "amanavengeraman1 month ago" }, { "code": null, "e": 3324, "s": 2891, "text": "public static int verticalWidth(Node root){ if(root == null){ return 0; } HashMap<Integer, Integer> hm = new HashMap<>(); lvl(root, 0, hm); return hm.size();}static void lvl(Node root, int dis, HashMap<Integer, Integer> hm){ if(root == null){ return; } if(!hm.containsKey(dis)){ hm.put(dis,root.data); } lvl(root.left, dis-1, hm); lvl(root.right, dis+1, hm); return;}" }, { "code": null, "e": 3326, "s": 3324, "text": "0" }, { "code": null, "e": 3345, "s": 3326, "text": "forcer2 months ago" }, { "code": null, "e": 3685, "s": 3345, "text": " map<int,int>m;\n if(!root) return 0;\n queue<pair<Node*,int>>q;\n q.push({root,0});\n while(!q.empty())\n {\n Node *t=q.front().first;\n int val=q.front().second;\n q.pop();\n m[val]++;\n if(t->left) q.push({t->left,val-1});\n if(t->right) q.push({t->right,val+1});\n }\n return m.size();" }, { "code": null, "e": 3688, "s": 3685, "text": "+5" }, { "code": null, "e": 3724, "s": 3688, "text": "gurjotsingh21003Premium2 months ago" }, { "code": null, "e": 3742, "s": 3724, "text": "EASY C++ solution" }, { "code": null, "e": 4167, "s": 3742, "text": "void width(Node* root,int& lmost,int& rmost,int level)\n{\n if(root==NULL)return;\n \n width(root->left,lmost,rmost,level-1);\n lmost=min(lmost,level);\n width(root->right,lmost,rmost,level+1);\n rmost=max(rmost,level);\n}\nint verticalWidth(Node* root)\n{\n // Code here\n if(root==NULL)return 0;\n int lmost=INT_MAX;\n int rmost=INT_MIN;\n int level=0;\n width(root,lmost,rmost,level);\n return (rmost-lmost+1);\n}" }, { "code": null, "e": 4170, "s": 4167, "text": "+2" }, { "code": null, "e": 4196, "s": 4170, "text": "harshitraj7122 months ago" }, { "code": null, "e": 4252, "s": 4196, "text": "Nasa walon se jyaada toh tree ke sawaal khatarnaak hain" }, { "code": null, "e": 4254, "s": 4252, "text": "0" }, { "code": null, "e": 4271, "s": 4254, "text": "shubhamkavia1998" }, { "code": null, "e": 4297, "s": 4271, "text": "This comment was deleted." }, { "code": null, "e": 4299, "s": 4297, "text": "0" }, { "code": null, "e": 4324, "s": 4299, "text": "ankitgupta502 months ago" }, { "code": null, "e": 4340, "s": 4324, "text": "// BFS Approach" }, { "code": null, "e": 5152, "s": 4340, "text": "class Tree{ public static class Pair{ Node root; int level; Pair(Node root, int level){ this.root = root; this.level = level; } } //Function to find the vertical width of a Binary Tree. public static int verticalWidth(Node root){ if(root==null) return 0; Queue<Pair> q = new LinkedList<>(); q.add(new Pair(root,1)); int min = Integer.MAX_VALUE; int max = Integer.MIN_VALUE; while(!q.isEmpty()){ Pair temp = q.remove(); min = Math.min(min,temp.level); max = Math.max(max,temp.level); if(temp.root.left!=null){ q.add(new Pair(temp.root.left,temp.level-1)); } if(temp.root.right!=null){ q.add(new Pair(temp.root.right,temp.level+1)); } } return max-min+1;}}" }, { "code": null, "e": 5298, "s": 5152, "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": 5334, "s": 5298, "text": " Login to access your submissions. " }, { "code": null, "e": 5344, "s": 5334, "text": "\nProblem\n" }, { "code": null, "e": 5354, "s": 5344, "text": "\nContest\n" }, { "code": null, "e": 5417, "s": 5354, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 5565, "s": 5417, "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": 5773, "s": 5565, "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": 5879, "s": 5773, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
C# | Math.Ceiling() Method - GeeksforGeeks
16 Sep, 2021 In C#, Math.Ceiling() is a Math class method. This method is used to find the smallest integer , which is greater than or equal to the passed argument. The Ceiling method operates both functionalities in decimal and double. This method can be overload by passing different arguments to it. Math.Ceiling(Decimal) Method Math.Ceiling(Double) Method This method is used to returns the smallest integral value which is greater than or equal to the specified decimal number in the argument list.Syntax: public static decimal Ceiling(decimal d) Parameter: Decimal d: It is the decimal number of type System.Decimal. Return Type: This function return the smallest integral value which will be greater than or equal to d. The type of this method is System.Decimal and return a decimal instead of an integral type.Examples: Input : 888.765M; Output : 889 Input : -20002.999M Output : -20002 Program : To demonstrate the Math.Ceiling(Decimal) method. CSHARP // C# program to illustrate the// Math.Ceiling(Decimal) functionusing System; class SudoPlacement { // Main method static void Main() { // Input decimal value. decimal decim_n1 = 2.10M; decimal decim_n2 = -99.90M; decimal decim_n3 = 33.001M; // Calculate Ceiling values by // Using Math.Ceiling() function decimal ceil_t1 = Math.Ceiling(decim_n1); decimal ceil_t2 = Math.Ceiling(decim_n2); decimal ceil_t3 = Math.Ceiling(decim_n3); // Print First values and Ceiling Console.WriteLine("Input Value = " + decim_n1); Console.WriteLine("Ceiling value = " + ceil_t1); // Print Second values and Ceiling Console.WriteLine("Input Value = " + decim_n2); Console.WriteLine("Ceiling value = " + ceil_t2); // Print third values and Ceiling Console.WriteLine("Input Value = " + decim_n3); Console.WriteLine("Ceiling value = " + ceil_t3); }} Input Value = 2.10 Ceiling value = 3 Input Value = -99.90 Ceiling value = -99 Input Value = 33.001 Ceiling value = 34 This method is used to returns the smallest integral value which is greater than or equal to the specified double-precision floating-point number in the argument list.Syntax: public static double Ceiling(double d) Parameter: Double d: It is the double number of type System.Double. Return Type: This method returns the smallest integral value that is greater than or equal to d. If d is equal to NaN, NegativeInfinity, or PositiveInfinity, that value is returned. The type of this method is System.Double.Examples: Input : 10.1 Output : 11 Input : -2222.2220 Output : -2222 Program : To demonstrate the Math.Ceiling(Double) method. CSHARP // C# program to illustrate the// Math.Ceiling(Double) functionusing System; class SudoPlacement { // Main method static void Main() { // Input different Double value. double n1 = 101.10; double n2 = -1.1; double n3 = 9222.1000; // Calculate Ceiling values by // Using Math.Ceiling() function double t1 = Math.Ceiling(n1); double t2 = Math.Ceiling(n2); double t3 = Math.Ceiling(n3); // Print First values and Ceiling Console.WriteLine("Input Value = " + n1); Console.WriteLine("Ceiling value = " + t1); // Print Second values and Ceiling Console.WriteLine("Input Value = " + n2); Console.WriteLine("Ceiling value = " + t2); // Print third values and Ceiling Console.WriteLine("Input Value = " + n3); Console.WriteLine("Ceiling value = " + t3); }} Input Value = 101.1 Ceiling value = 102 Input Value = -1.1 Ceiling value = -1 Input Value = 9222.1 Ceiling value = 9223 References: https://msdn.microsoft.com/en-us/library/1cz5da1c(v=vs.110).aspx https://msdn.microsoft.com/en-us/library/zx4t0t48(v=vs.110).aspx nnr223442 CSharp-Math CSharp-method C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments C# Dictionary with examples C# | Method Overriding C# | Class and Object Difference between Ref and Out keywords in C# Introduction to .NET Framework C# | Constructors C# | String.IndexOf( ) Method | Set - 1 Extension Method in C# C# | Abstract Classes C# | Delegates
[ { "code": null, "e": 24532, "s": 24504, "text": "\n16 Sep, 2021" }, { "code": null, "e": 24823, "s": 24532, "text": "In C#, Math.Ceiling() is a Math class method. This method is used to find the smallest integer , which is greater than or equal to the passed argument. The Ceiling method operates both functionalities in decimal and double. This method can be overload by passing different arguments to it. " }, { "code": null, "e": 24852, "s": 24823, "text": "Math.Ceiling(Decimal) Method" }, { "code": null, "e": 24880, "s": 24852, "text": "Math.Ceiling(Double) Method" }, { "code": null, "e": 25035, "s": 24882, "text": "This method is used to returns the smallest integral value which is greater than or equal to the specified decimal number in the argument list.Syntax: " }, { "code": null, "e": 25076, "s": 25035, "text": "public static decimal Ceiling(decimal d)" }, { "code": null, "e": 25089, "s": 25076, "text": "Parameter: " }, { "code": null, "e": 25149, "s": 25089, "text": "Decimal d: It is the decimal number of type System.Decimal." }, { "code": null, "e": 25356, "s": 25149, "text": "Return Type: This function return the smallest integral value which will be greater than or equal to d. The type of this method is System.Decimal and return a decimal instead of an integral type.Examples: " }, { "code": null, "e": 25426, "s": 25356, "text": "Input : 888.765M;\nOutput : 889\n\nInput : -20002.999M\nOutput : -20002" }, { "code": null, "e": 25486, "s": 25426, "text": "Program : To demonstrate the Math.Ceiling(Decimal) method. " }, { "code": null, "e": 25493, "s": 25486, "text": "CSHARP" }, { "code": "// C# program to illustrate the// Math.Ceiling(Decimal) functionusing System; class SudoPlacement { // Main method static void Main() { // Input decimal value. decimal decim_n1 = 2.10M; decimal decim_n2 = -99.90M; decimal decim_n3 = 33.001M; // Calculate Ceiling values by // Using Math.Ceiling() function decimal ceil_t1 = Math.Ceiling(decim_n1); decimal ceil_t2 = Math.Ceiling(decim_n2); decimal ceil_t3 = Math.Ceiling(decim_n3); // Print First values and Ceiling Console.WriteLine(\"Input Value = \" + decim_n1); Console.WriteLine(\"Ceiling value = \" + ceil_t1); // Print Second values and Ceiling Console.WriteLine(\"Input Value = \" + decim_n2); Console.WriteLine(\"Ceiling value = \" + ceil_t2); // Print third values and Ceiling Console.WriteLine(\"Input Value = \" + decim_n3); Console.WriteLine(\"Ceiling value = \" + ceil_t3); }}", "e": 26469, "s": 25493, "text": null }, { "code": null, "e": 26590, "s": 26469, "text": "Input Value = 2.10\nCeiling value = 3\nInput Value = -99.90\nCeiling value = -99\nInput Value = 33.001\nCeiling value = 34" }, { "code": null, "e": 26769, "s": 26592, "text": "This method is used to returns the smallest integral value which is greater than or equal to the specified double-precision floating-point number in the argument list.Syntax: " }, { "code": null, "e": 26808, "s": 26769, "text": "public static double Ceiling(double d)" }, { "code": null, "e": 26821, "s": 26808, "text": "Parameter: " }, { "code": null, "e": 26878, "s": 26821, "text": "Double d: It is the double number of type System.Double." }, { "code": null, "e": 27113, "s": 26878, "text": "Return Type: This method returns the smallest integral value that is greater than or equal to d. If d is equal to NaN, NegativeInfinity, or PositiveInfinity, that value is returned. The type of this method is System.Double.Examples: " }, { "code": null, "e": 27177, "s": 27113, "text": "Input : 10.1 \nOutput : 11\n\nInput : -2222.2220\nOutput : -2222" }, { "code": null, "e": 27236, "s": 27177, "text": "Program : To demonstrate the Math.Ceiling(Double) method. " }, { "code": null, "e": 27243, "s": 27236, "text": "CSHARP" }, { "code": "// C# program to illustrate the// Math.Ceiling(Double) functionusing System; class SudoPlacement { // Main method static void Main() { // Input different Double value. double n1 = 101.10; double n2 = -1.1; double n3 = 9222.1000; // Calculate Ceiling values by // Using Math.Ceiling() function double t1 = Math.Ceiling(n1); double t2 = Math.Ceiling(n2); double t3 = Math.Ceiling(n3); // Print First values and Ceiling Console.WriteLine(\"Input Value = \" + n1); Console.WriteLine(\"Ceiling value = \" + t1); // Print Second values and Ceiling Console.WriteLine(\"Input Value = \" + n2); Console.WriteLine(\"Ceiling value = \" + t2); // Print third values and Ceiling Console.WriteLine(\"Input Value = \" + n3); Console.WriteLine(\"Ceiling value = \" + t3); }}", "e": 28137, "s": 27243, "text": null }, { "code": null, "e": 28260, "s": 28137, "text": "Input Value = 101.1\nCeiling value = 102\nInput Value = -1.1\nCeiling value = -1\nInput Value = 9222.1\nCeiling value = 9223" }, { "code": null, "e": 28276, "s": 28262, "text": "References: " }, { "code": null, "e": 28341, "s": 28276, "text": "https://msdn.microsoft.com/en-us/library/1cz5da1c(v=vs.110).aspx" }, { "code": null, "e": 28406, "s": 28341, "text": "https://msdn.microsoft.com/en-us/library/zx4t0t48(v=vs.110).aspx" }, { "code": null, "e": 28418, "s": 28408, "text": "nnr223442" }, { "code": null, "e": 28430, "s": 28418, "text": "CSharp-Math" }, { "code": null, "e": 28444, "s": 28430, "text": "CSharp-method" }, { "code": null, "e": 28447, "s": 28444, "text": "C#" }, { "code": null, "e": 28545, "s": 28447, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28554, "s": 28545, "text": "Comments" }, { "code": null, "e": 28567, "s": 28554, "text": "Old Comments" }, { "code": null, "e": 28595, "s": 28567, "text": "C# Dictionary with examples" }, { "code": null, "e": 28618, "s": 28595, "text": "C# | Method Overriding" }, { "code": null, "e": 28640, "s": 28618, "text": "C# | Class and Object" }, { "code": null, "e": 28686, "s": 28640, "text": "Difference between Ref and Out keywords in C#" }, { "code": null, "e": 28717, "s": 28686, "text": "Introduction to .NET Framework" }, { "code": null, "e": 28735, "s": 28717, "text": "C# | Constructors" }, { "code": null, "e": 28775, "s": 28735, "text": "C# | String.IndexOf( ) Method | Set - 1" }, { "code": null, "e": 28798, "s": 28775, "text": "Extension Method in C#" }, { "code": null, "e": 28820, "s": 28798, "text": "C# | Abstract Classes" } ]
Must we implement all the methods in a class that implements an interface in Java?
Yes, it is mandatory to implement all the methods in a class that implements an interface until and unless that class is declared as an abstract class. There are only two choices − Implement every method defined by the interface. Declare the class as an abstract class, as a result, forces you to subclass the class (and implement the missing methods) before you can create any objects. The only case the class do not need to implement all methods in the interface is when any class in its inheritance tree has already provided concrete (i.e. non-abstract) method implementations then the subclass is under no obligation to re-implement those methods. The subclass may not implement the interface at all and just method signature is matched. interface MyInterface { void m() throws NullPointerException; } class SuperClass { // SuperClass class doesn't implements MyInterface interface public void m() { System.out.println("Inside SuperClass m()"); } } class SubClass extends SuperClass implements MyInterface { } public class Program { public static void main(String args[]) { SubClass s = new SubClass(); s.m(); } } Inside SuperClass m() The above code shows a concrete class SubClass that declares that it implements an interface MyInterface, but doesn't implement the m() method of the interface. The code is legal because it's parent class SuperClass implements a method called m() with the same name as the method in the interface.
[ { "code": null, "e": 1214, "s": 1062, "text": "Yes, it is mandatory to implement all the methods in a class that implements an interface until and unless that class is declared as an abstract class." }, { "code": null, "e": 1243, "s": 1214, "text": "There are only two choices −" }, { "code": null, "e": 1292, "s": 1243, "text": "Implement every method defined by the interface." }, { "code": null, "e": 1449, "s": 1292, "text": "Declare the class as an abstract class, as a result, forces you to subclass the class (and implement the missing methods) before you can create any objects." }, { "code": null, "e": 1804, "s": 1449, "text": "The only case the class do not need to implement all methods in the interface is when any class in its inheritance tree has already provided concrete (i.e. non-abstract) method implementations then the subclass is under no obligation to re-implement those methods. The subclass may not implement the interface at all and just method signature is matched." }, { "code": null, "e": 2216, "s": 1804, "text": "interface MyInterface {\n void m() throws NullPointerException;\n}\nclass SuperClass {\n // SuperClass class doesn't implements MyInterface interface\n public void m() {\n System.out.println(\"Inside SuperClass m()\");\n }\n}\nclass SubClass extends SuperClass implements MyInterface {\n}\npublic class Program {\n public static void main(String args[]) {\n SubClass s = new SubClass();\n s.m();\n }\n}" }, { "code": null, "e": 2238, "s": 2216, "text": "Inside SuperClass m()" }, { "code": null, "e": 2536, "s": 2238, "text": "The above code shows a concrete class SubClass that declares that it implements an interface MyInterface, but doesn't implement the m() method of the interface. The code is legal because it's parent class SuperClass implements a method called m() with the same name as the method in the interface." } ]
How to define a Regular Expression in JavaScript?
A regular expression is an object that describes a pattern of characters. The JavaScript RegExp class represents regular expressions, and both String and RegExp define methods that use regular expressions to perform powerful pattern-matching and search-and-replace functions on the text. A regular expression could be defined with the RegExp () constructor, as follows − var pattern = new RegExp(pattern, attributes); or var pattern = /pattern/attributes; The following are the parameters − pattern − A string that specifies the pattern of the regular expression or another regular expression. attributes − An optional string containing any of the "g", "i", and "m" attributes that specify global, case-insensitive, and multiline matches, respectively.
[ { "code": null, "e": 1136, "s": 1062, "text": "A regular expression is an object that describes a pattern of characters." }, { "code": null, "e": 1433, "s": 1136, "text": "The JavaScript RegExp class represents regular expressions, and both String and RegExp define methods that use regular expressions to perform powerful pattern-matching and search-and-replace functions on the text. A regular expression could be defined with the RegExp () constructor, as follows −" }, { "code": null, "e": 1520, "s": 1433, "text": "var pattern = new RegExp(pattern, attributes);\n\nor\n\nvar pattern = /pattern/attributes;" }, { "code": null, "e": 1555, "s": 1520, "text": "The following are the parameters −" }, { "code": null, "e": 1658, "s": 1555, "text": "pattern − A string that specifies the pattern of the regular expression or another regular expression." }, { "code": null, "e": 1817, "s": 1658, "text": "attributes − An optional string containing any of the \"g\", \"i\", and \"m\" attributes that specify global, case-insensitive, and multiline matches, respectively." } ]
How to write a JDBC application which connects to multiple databases simultaneously?
To connect with a database, you need to Register the Driver: Select the required database, register the Driver class of the particular database using the registerDriver() method of the DriverManager class or, the forName() method of the class named Class. Register the Driver: Select the required database, register the Driver class of the particular database using the registerDriver() method of the DriverManager class or, the forName() method of the class named Class. DriverManager.registerDriver(new com.mysql.jdbc.Driver()); Get connection: Create a connection object by passing the URL of the database, username and password (of a user in the database) in string format, as parameters to the getConnection() method of the DriverManager class. Get connection: Create a connection object by passing the URL of the database, username and password (of a user in the database) in string format, as parameters to the getConnection() method of the DriverManager class. Connection mysqlCon = DriverManager.getConnection(mysqlUrl, "root", "password"); To connect to multiple databases in a single JDBC program you need to connect to the two (or more) databases simultaneously using the above steps. Here, in this example, we are trying to connect to Oracle and MySQL Databases where following are the URLs and sample user credentials of both databases. import java.sql.Connection; import java.sql.DriverManager; public class MultipleConnections { public static void main(String[] args) throws Exception { //Registering the Driver DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver()); //Getting the connection String oracleUrl = "jdbc:oracle:thin:@localhost:1521/xe"; Connection oracleCon = DriverManager.getConnection(oracleUrl, "system", "password"); System.out.println("oracleConn=" + oracleCon); //Registering the Driver DriverManager.registerDriver(new com.mysql.jdbc.Driver()); //Getting the connection String mysqlUrl = "jdbc:mysql://localhost/"; Connection mysqlCon = DriverManager.getConnection(mysqlUrl, "root", "password"); System.out.println("mysqlConn=" + mysqlCon); } } oracleConn = oracle.jdbc.driver.T4CConnection@6477463f mysqlConn = com.mysql.jdbc.JDBC4Connection@3059cbc
[ { "code": null, "e": 1102, "s": 1062, "text": "To connect with a database, you need to" }, { "code": null, "e": 1318, "s": 1102, "text": "Register the Driver: Select the required database, register the Driver class of the particular database using the registerDriver() method of the DriverManager class or, the forName() method of the class named Class." }, { "code": null, "e": 1534, "s": 1318, "text": "Register the Driver: Select the required database, register the Driver class of the particular database using the registerDriver() method of the DriverManager class or, the forName() method of the class named Class." }, { "code": null, "e": 1593, "s": 1534, "text": "DriverManager.registerDriver(new com.mysql.jdbc.Driver());" }, { "code": null, "e": 1812, "s": 1593, "text": "Get connection: Create a connection object by passing the URL of the database, username and password (of a user in the database) in string format, as parameters to the getConnection() method of the DriverManager class." }, { "code": null, "e": 2031, "s": 1812, "text": "Get connection: Create a connection object by passing the URL of the database, username and password (of a user in the database) in string format, as parameters to the getConnection() method of the DriverManager class." }, { "code": null, "e": 2112, "s": 2031, "text": "Connection mysqlCon = DriverManager.getConnection(mysqlUrl, \"root\", \"password\");" }, { "code": null, "e": 2259, "s": 2112, "text": "To connect to multiple databases in a single JDBC program you need to connect to the two (or more) databases simultaneously using the above steps." }, { "code": null, "e": 2413, "s": 2259, "text": "Here, in this example, we are trying to connect to Oracle and MySQL Databases where following are the URLs and sample user credentials of both databases." }, { "code": null, "e": 3236, "s": 2413, "text": "import java.sql.Connection;\nimport java.sql.DriverManager;\npublic class MultipleConnections {\n public static void main(String[] args) throws Exception {\n //Registering the Driver\n DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());\n //Getting the connection\n String oracleUrl = \"jdbc:oracle:thin:@localhost:1521/xe\";\n Connection oracleCon = DriverManager.getConnection(oracleUrl, \"system\", \"password\");\n System.out.println(\"oracleConn=\" + oracleCon);\n //Registering the Driver\n DriverManager.registerDriver(new com.mysql.jdbc.Driver());\n //Getting the connection\n String mysqlUrl = \"jdbc:mysql://localhost/\";\n Connection mysqlCon = DriverManager.getConnection(mysqlUrl, \"root\", \"password\");\n System.out.println(\"mysqlConn=\" + mysqlCon);\n }\n}" }, { "code": null, "e": 3342, "s": 3236, "text": "oracleConn = oracle.jdbc.driver.T4CConnection@6477463f\nmysqlConn = com.mysql.jdbc.JDBC4Connection@3059cbc" } ]
How to hide/show an image on button click using jQuery ? - GeeksforGeeks
01 Aug, 2021 In this article, we will see how we can hide or show any particular image in jQuery when a button gets clicked. This is quite easy to do with some lines of jQuery code. Before we jump to the topic, let’s know which methods of jQuery will be used for this. So there is a method called show() and another one is hide(), these two methods of jQuery can make our work a lot easier. For this tutorial, we will use the CDN link of jQuery in order to use it. We have to paste the following code into our HTML page inside the head tag. This script can be found on the official website of jQuery. jQuery CDN link: <script src=”https://code.jquery.com/jquery-3.6.0.min.js” integrity=”sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=” crossorigin=”anonymous”></script> Now let’s see what will be the jQuery code for the functionality that we are going to implement in our page. HTML <script> $(document).ready(function () { $("#image").hide(); $("#hide").attr('disabled', true); $("#hide").click(function () { $("#image").hide(); $("#hide").attr('disabled', true); $("#show").attr('disabled', false); }); $("#show").click(function () { $("#image").show(); $("#hide").attr('disabled', false); $("#show").attr('disabled', true); }); });</script> The code written above will be responsible for hiding or showing the image on our webpage. We have used a click() method which will be called when the button of id(hide) will be clicked and another click() method will be called when another button of id(show) will be click. In both the click() methods there are two other methods are being used that are hide and show which are linked with the image tag of id(image). So that this image can be altered on the button click. We have added some more functionality to the buttons so that when the image will be visible, at that time show button will be grayed out and when the image will not be visible at that time hide button will be grayed out, this will give some more clarity to the user. Now for the clear view let’s have a look at our HTML page with complete code. Example: HTML <!DOCTYPE html><html lang="en"> <head> <!-- CDN link of jQuery --> <script src= "https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"> </script></head> <body> <!-- Both buttons that will hide or show the image --> <button id="show">Show image</button> <button id="hide">Hide image</button> <!-- Image that will follow the commands accordingly --> <img id="image" src="gfglogo.png" alt="Photo"> <!-- Code for hiding or showing image on button click --> <script> $(document).ready(function () { $("#image").hide(); $("#hide").attr('disabled', true); $("#hide").click(function () { $("#image").hide(); $("#hide").attr('disabled', true); $("#show").attr('disabled', false); }); $("#show").click(function () { $("#image").show(); $("#hide").attr('disabled', false); $("#show").attr('disabled', true); }); }); </script></body> </html> Now to check the above code, we have to open that HTML file in our browser and see the functionality of the buttons working that we have implemented. Output: jQuery-Methods jQuery-Questions Picked JQuery Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to prevent Body from scrolling when a modal is opened using jQuery ? jQuery | ajax() Method Difference Between JavaScript and jQuery How to get the value in an input text box using jQuery ? QR Code Generator using HTML, CSS and jQuery Top 10 Front End Developer Skills That You Need in 2022 Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 25388, "s": 25360, "text": "\n01 Aug, 2021" }, { "code": null, "e": 25766, "s": 25388, "text": "In this article, we will see how we can hide or show any particular image in jQuery when a button gets clicked. This is quite easy to do with some lines of jQuery code. Before we jump to the topic, let’s know which methods of jQuery will be used for this. So there is a method called show() and another one is hide(), these two methods of jQuery can make our work a lot easier." }, { "code": null, "e": 25976, "s": 25766, "text": "For this tutorial, we will use the CDN link of jQuery in order to use it. We have to paste the following code into our HTML page inside the head tag. This script can be found on the official website of jQuery." }, { "code": null, "e": 25993, "s": 25976, "text": "jQuery CDN link:" }, { "code": null, "e": 26149, "s": 25993, "text": "<script src=”https://code.jquery.com/jquery-3.6.0.min.js” integrity=”sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=” crossorigin=”anonymous”></script>" }, { "code": null, "e": 26258, "s": 26149, "text": "Now let’s see what will be the jQuery code for the functionality that we are going to implement in our page." }, { "code": null, "e": 26263, "s": 26258, "text": "HTML" }, { "code": "<script> $(document).ready(function () { $(\"#image\").hide(); $(\"#hide\").attr('disabled', true); $(\"#hide\").click(function () { $(\"#image\").hide(); $(\"#hide\").attr('disabled', true); $(\"#show\").attr('disabled', false); }); $(\"#show\").click(function () { $(\"#image\").show(); $(\"#hide\").attr('disabled', false); $(\"#show\").attr('disabled', true); }); });</script>", "e": 26740, "s": 26263, "text": null }, { "code": null, "e": 27481, "s": 26740, "text": "The code written above will be responsible for hiding or showing the image on our webpage. We have used a click() method which will be called when the button of id(hide) will be clicked and another click() method will be called when another button of id(show) will be click. In both the click() methods there are two other methods are being used that are hide and show which are linked with the image tag of id(image). So that this image can be altered on the button click. We have added some more functionality to the buttons so that when the image will be visible, at that time show button will be grayed out and when the image will not be visible at that time hide button will be grayed out, this will give some more clarity to the user." }, { "code": null, "e": 27559, "s": 27481, "text": "Now for the clear view let’s have a look at our HTML page with complete code." }, { "code": null, "e": 27568, "s": 27559, "text": "Example:" }, { "code": null, "e": 27573, "s": 27568, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <!-- CDN link of jQuery --> <script src= \"https://code.jquery.com/jquery-3.6.0.min.js\" integrity=\"sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=\" crossorigin=\"anonymous\"> </script></head> <body> <!-- Both buttons that will hide or show the image --> <button id=\"show\">Show image</button> <button id=\"hide\">Hide image</button> <!-- Image that will follow the commands accordingly --> <img id=\"image\" src=\"gfglogo.png\" alt=\"Photo\"> <!-- Code for hiding or showing image on button click --> <script> $(document).ready(function () { $(\"#image\").hide(); $(\"#hide\").attr('disabled', true); $(\"#hide\").click(function () { $(\"#image\").hide(); $(\"#hide\").attr('disabled', true); $(\"#show\").attr('disabled', false); }); $(\"#show\").click(function () { $(\"#image\").show(); $(\"#hide\").attr('disabled', false); $(\"#show\").attr('disabled', true); }); }); </script></body> </html>", "e": 28746, "s": 27573, "text": null }, { "code": null, "e": 28896, "s": 28746, "text": "Now to check the above code, we have to open that HTML file in our browser and see the functionality of the buttons working that we have implemented." }, { "code": null, "e": 28904, "s": 28896, "text": "Output:" }, { "code": null, "e": 28919, "s": 28904, "text": "jQuery-Methods" }, { "code": null, "e": 28936, "s": 28919, "text": "jQuery-Questions" }, { "code": null, "e": 28943, "s": 28936, "text": "Picked" }, { "code": null, "e": 28950, "s": 28943, "text": "JQuery" }, { "code": null, "e": 28967, "s": 28950, "text": "Web Technologies" }, { "code": null, "e": 29065, "s": 28967, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29074, "s": 29065, "text": "Comments" }, { "code": null, "e": 29087, "s": 29074, "text": "Old Comments" }, { "code": null, "e": 29160, "s": 29087, "text": "How to prevent Body from scrolling when a modal is opened using jQuery ?" }, { "code": null, "e": 29183, "s": 29160, "text": "jQuery | ajax() Method" }, { "code": null, "e": 29224, "s": 29183, "text": "Difference Between JavaScript and jQuery" }, { "code": null, "e": 29281, "s": 29224, "text": "How to get the value in an input text box using jQuery ?" }, { "code": null, "e": 29326, "s": 29281, "text": "QR Code Generator using HTML, CSS and jQuery" }, { "code": null, "e": 29382, "s": 29326, "text": "Top 10 Front End Developer Skills That You Need in 2022" }, { "code": null, "e": 29415, "s": 29382, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 29477, "s": 29415, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 29520, "s": 29477, "text": "How to fetch data from an API in ReactJS ?" } ]
How to create notes taking site using HTML, Bootstrap and JavaScript ? - GeeksforGeeks
12 Mar, 2021 We are going to make a website that will take our notes and saves them for our future use using HTML, CSS and JavaScript . Prerequisite: Basic understanding of HTML, Bootstrap, and JavaScript. Approach: HTML: We will create the basic framework of the website using HTML. Bootstrap: makes our work easier as compared to CSS. So we have used Bootstrap to beautify our framework. JavaScript: The basic logic of saving the notes and deleting them is inside the index.js file. Example: Here we first design the structure of our project then we will code for the functionality. index.html <!DOCTYPE html><html lang="en"> <head> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"> </script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"> </script></head> <body> <nav class="navbar navbar-expand-lg navbar-light bg-success"> <a class="navbar-brand" href="#"> <p style="font-size: 30px;"> THE NOTES TAKER </p> </a> </nav> <div class="container my-3"> <h1>Take your Notes here</h1> <div class="card"> <div class="card-body"> <h5 class="card-title"> Add a Note </h5> <div class="form-group"> <textarea class="form-control" id="addTxt" rows="3"> </textarea> </div> <button class="btn btn-primary" id="addBtn" style= "background-color:green"> Add Note </button> </div> </div> <hr> <h1>Your Notes</h1> <hr> <div id="notes" class= "row container-fluid"> </div> </div> <script src="gfg.js"></script></body> </html> index.js showNotes(); // If user adds a note, add it to the localStoragelet addBtn = document.getElementById("addBtn");addBtn.addEventListener("click", function(e) { let addTxt = document.getElementById("addTxt"); let notes = localStorage.getItem("notes"); if (notes == null) notesObj = []; else notesObj = JSON.parse(notes); notesObj.push(addTxt.value); localStorage.setItem("notes", JSON.stringify(notesObj)); addTxt.value = ""; showNotes();}); // Function to show elements from localStoragefunction showNotes() { let notes = localStorage.getItem("notes"); if (notes == null) notesObj = []; else notesObj = JSON.parse(notes); let html = ""; notesObj.forEach(function(element, index) { html += `<div class="noteCard my-2 mx-2 card" style="width: 18rem;"> <div class="card-body"> <h5 class="card-title"> Note ${index + 1} </h5> <p class="card-text"> ${element} </p> <button id="${index}" onclick= "deleteNote(this.id)" class="btn btn-primary"> Delete Note </button> </div> </div>`; }); let notesElm = document.getElementById("notes"); if (notesObj.length != 0) notesElm.innerHTML = html; else notesElm.innerHTML = `Nothing to show! Use "Add a Note" section above to add notes.`;} // Function to delete a notefunction deleteNote(index) { let notes = localStorage.getItem("notes"); if (notes == null) notesObj = []; else notesObj = JSON.parse(notes); notesObj.splice(index, 1); localStorage.setItem("notes", JSON.stringify(notesObj)); showNotes();} Output: Bootstrap-Questions HTML-Questions JavaScript-Questions Bootstrap HTML JavaScript Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to set Bootstrap Timepicker using datetimepicker library ? How to Show Images on Click using HTML ? How to Use Bootstrap with React? Tailwind CSS vs Bootstrap How to keep gap between columns using Bootstrap? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS? 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 ?
[ { "code": null, "e": 25564, "s": 25536, "text": "\n12 Mar, 2021" }, { "code": null, "e": 25687, "s": 25564, "text": "We are going to make a website that will take our notes and saves them for our future use using HTML, CSS and JavaScript ." }, { "code": null, "e": 25701, "s": 25687, "text": "Prerequisite:" }, { "code": null, "e": 25757, "s": 25701, "text": "Basic understanding of HTML, Bootstrap, and JavaScript." }, { "code": null, "e": 25767, "s": 25757, "text": "Approach:" }, { "code": null, "e": 25835, "s": 25767, "text": "HTML: We will create the basic framework of the website using HTML." }, { "code": null, "e": 25941, "s": 25835, "text": "Bootstrap: makes our work easier as compared to CSS. So we have used Bootstrap to beautify our framework." }, { "code": null, "e": 26036, "s": 25941, "text": "JavaScript: The basic logic of saving the notes and deleting them is inside the index.js file." }, { "code": null, "e": 26136, "s": 26036, "text": "Example: Here we first design the structure of our project then we will code for the functionality." }, { "code": null, "e": 26147, "s": 26136, "text": "index.html" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css\" integrity=\"sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T\" crossorigin=\"anonymous\"> <script src=\"https://code.jquery.com/jquery-3.3.1.slim.min.js\" integrity=\"sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo\" crossorigin=\"anonymous\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js\" integrity=\"sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1\" crossorigin=\"anonymous\"> </script> <script src=\"https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js\" integrity=\"sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM\" crossorigin=\"anonymous\"> </script></head> <body> <nav class=\"navbar navbar-expand-lg navbar-light bg-success\"> <a class=\"navbar-brand\" href=\"#\"> <p style=\"font-size: 30px;\"> THE NOTES TAKER </p> </a> </nav> <div class=\"container my-3\"> <h1>Take your Notes here</h1> <div class=\"card\"> <div class=\"card-body\"> <h5 class=\"card-title\"> Add a Note </h5> <div class=\"form-group\"> <textarea class=\"form-control\" id=\"addTxt\" rows=\"3\"> </textarea> </div> <button class=\"btn btn-primary\" id=\"addBtn\" style= \"background-color:green\"> Add Note </button> </div> </div> <hr> <h1>Your Notes</h1> <hr> <div id=\"notes\" class= \"row container-fluid\"> </div> </div> <script src=\"gfg.js\"></script></body> </html>", "e": 28171, "s": 26147, "text": null }, { "code": null, "e": 28180, "s": 28171, "text": "index.js" }, { "code": "showNotes(); // If user adds a note, add it to the localStoragelet addBtn = document.getElementById(\"addBtn\");addBtn.addEventListener(\"click\", function(e) { let addTxt = document.getElementById(\"addTxt\"); let notes = localStorage.getItem(\"notes\"); if (notes == null) notesObj = []; else notesObj = JSON.parse(notes); notesObj.push(addTxt.value); localStorage.setItem(\"notes\", JSON.stringify(notesObj)); addTxt.value = \"\"; showNotes();}); // Function to show elements from localStoragefunction showNotes() { let notes = localStorage.getItem(\"notes\"); if (notes == null) notesObj = []; else notesObj = JSON.parse(notes); let html = \"\"; notesObj.forEach(function(element, index) { html += `<div class=\"noteCard my-2 mx-2 card\" style=\"width: 18rem;\"> <div class=\"card-body\"> <h5 class=\"card-title\"> Note ${index + 1} </h5> <p class=\"card-text\"> ${element} </p> <button id=\"${index}\" onclick= \"deleteNote(this.id)\" class=\"btn btn-primary\"> Delete Note </button> </div> </div>`; }); let notesElm = document.getElementById(\"notes\"); if (notesObj.length != 0) notesElm.innerHTML = html; else notesElm.innerHTML = `Nothing to show! Use \"Add a Note\" section above to add notes.`;} // Function to delete a notefunction deleteNote(index) { let notes = localStorage.getItem(\"notes\"); if (notes == null) notesObj = []; else notesObj = JSON.parse(notes); notesObj.splice(index, 1); localStorage.setItem(\"notes\", JSON.stringify(notesObj)); showNotes();}", "e": 30004, "s": 28180, "text": null }, { "code": null, "e": 30012, "s": 30004, "text": "Output:" }, { "code": null, "e": 30032, "s": 30012, "text": "Bootstrap-Questions" }, { "code": null, "e": 30047, "s": 30032, "text": "HTML-Questions" }, { "code": null, "e": 30068, "s": 30047, "text": "JavaScript-Questions" }, { "code": null, "e": 30078, "s": 30068, "text": "Bootstrap" }, { "code": null, "e": 30083, "s": 30078, "text": "HTML" }, { "code": null, "e": 30094, "s": 30083, "text": "JavaScript" }, { "code": null, "e": 30111, "s": 30094, "text": "Web Technologies" }, { "code": null, "e": 30116, "s": 30111, "text": "HTML" }, { "code": null, "e": 30214, "s": 30116, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30223, "s": 30214, "text": "Comments" }, { "code": null, "e": 30236, "s": 30223, "text": "Old Comments" }, { "code": null, "e": 30299, "s": 30236, "text": "How to set Bootstrap Timepicker using datetimepicker library ?" }, { "code": null, "e": 30340, "s": 30299, "text": "How to Show Images on Click using HTML ?" }, { "code": null, "e": 30373, "s": 30340, "text": "How to Use Bootstrap with React?" }, { "code": null, "e": 30399, "s": 30373, "text": "Tailwind CSS vs Bootstrap" }, { "code": null, "e": 30448, "s": 30399, "text": "How to keep gap between columns using Bootstrap?" }, { "code": null, "e": 30510, "s": 30448, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 30560, "s": 30510, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 30620, "s": 30560, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 30668, "s": 30620, "text": "How to update Node.js and NPM to next version ?" } ]
C# | Replace() Method - GeeksforGeeks
10 May, 2019 In C#, Replace() method is a string method. This method is used to replace all the specified Unicode characters or specified string from the current string object and returns a new modified string. This method can be overloaded by passing arguments to it. Syntax: public string Replace(char Oldchar, char Newchar) or public string Replace(string Oldvalue, string Newvalue) Explanation:The First Method takes two parameters Oldchar and Newchar, where Oldchar is the Unicode character to be replaced and Newchar is the character to replace all occurrences of OldChar.The second method also takes two parameters Oldvalue and Newvalue where Oldvalue is the string to be replaced and Newvalue is a string to replace all occurrences of Oldvalue. The return type value of both the methods is System.String. Exceptions: ArgumentNullException: If OldValue or Oldchar both are null. ArgumentException If OldValue or Oldchar is the empty string (“”). Below are the programs to demonstrate the above methods : Example 1: Program to demonstrate the public string Replace(char Oldchar, char Newchar) method. All occurrences of a specified character are replaced with another specified character. If oldChar is not found in the current string object then string remains unchanged.Input : str = "GeeksForGeeks" str.Replace('s', 'G'); Output: GeekGForGeekG Input : str = "GeeksForGeeks" str.Replace('e', ' '); Output: G ksForG ks // C# program to illustrate the Replace()// Method with character parameterusing System; class Geeks { // Main Method public static void Main() { // string String str = "Geeks For Geeks"; Console.WriteLine("OldString : " + str); // replace the character 's' with 'G' Console.WriteLine("NewString: " + str.Replace('s', 'G')); // oldString will remain unchanged // its return the modified string Console.WriteLine("\nOldString: " + str); // replace the character 'e' with space ' ' Console.WriteLine("NewString: " + str.Replace('e', ' ')); }}Output:OldString : Geeks For Geeks NewString: GeekG For GeekG OldString: Geeks For Geeks NewString: G ks For G ks Input : str = "GeeksForGeeks" str.Replace('s', 'G'); Output: GeekGForGeekG Input : str = "GeeksForGeeks" str.Replace('e', ' '); Output: G ksForG ks // C# program to illustrate the Replace()// Method with character parameterusing System; class Geeks { // Main Method public static void Main() { // string String str = "Geeks For Geeks"; Console.WriteLine("OldString : " + str); // replace the character 's' with 'G' Console.WriteLine("NewString: " + str.Replace('s', 'G')); // oldString will remain unchanged // its return the modified string Console.WriteLine("\nOldString: " + str); // replace the character 'e' with space ' ' Console.WriteLine("NewString: " + str.Replace('e', ' ')); }} OldString : Geeks For Geeks NewString: GeekG For GeekG OldString: Geeks For Geeks NewString: G ks For G ks Example 2: Program to demonstrate the public string Replace(string Oldvalue, string Newvalue) method. All occurrences of a specified string in the current string instance are replaced with another specified string. If Oldvalue is not found in the current string then string remains unchanged.Input: str = "Geeks For Geeks" str.Replace("Geeks", "---"); Output: --- For --- Input: str = "Geeks For Geeks" str.Replace("For", "GFG"); Output: Geeks GFG Geeks // C# program to illustrate the Replace// Method with string parameterusing System; class Geeks { // Main Method public static void Main() { // define string String str = "Geeks For Geeks"; Console.WriteLine("OldString : " + str); // replace the string 'Geeks' with '---' // in string 'Geeks comes two time so replace two times Console.WriteLine("NewString: " + str.Replace("Geeks", "---")); // oldString will remain unchanged // its return the modified string Console.WriteLine("\nOldString: " + str); // replace the string 'For' with 'GFG' Console.WriteLine("NewString: " + str.Replace("For", "GFG")); }}Output:OldString : Geeks For Geeks NewString: --- For --- OldString: Geeks For Geeks NewString: Geeks GFG Geeks Input: str = "Geeks For Geeks" str.Replace("Geeks", "---"); Output: --- For --- Input: str = "Geeks For Geeks" str.Replace("For", "GFG"); Output: Geeks GFG Geeks // C# program to illustrate the Replace// Method with string parameterusing System; class Geeks { // Main Method public static void Main() { // define string String str = "Geeks For Geeks"; Console.WriteLine("OldString : " + str); // replace the string 'Geeks' with '---' // in string 'Geeks comes two time so replace two times Console.WriteLine("NewString: " + str.Replace("Geeks", "---")); // oldString will remain unchanged // its return the modified string Console.WriteLine("\nOldString: " + str); // replace the string 'For' with 'GFG' Console.WriteLine("NewString: " + str.Replace("For", "GFG")); }} OldString : Geeks For Geeks NewString: --- For --- OldString: Geeks For Geeks NewString: Geeks GFG Geeks To perform multiple replacements operations on the string(Replacement’s Chain) : The above Replace() method returns the modified string, so now we can chain together successive calls to the Replace method to perform multiple replacements on the string. Method calls are executed from left to right.In below example, for the given string “XXXXX” first X will be replaced with Y and then Y will be replaced with Z and finally, Z will be replaced with A. Example : // C# program to demonstrate the // multiple replacements callsusing System; public class Geeks{ // Main Method public static void Main() { String str = "XXXXX"; Console.WriteLine("Old String: " + str); // chain together str = str.Replace('X', 'Y').Replace('Y', 'Z').Replace('Z', 'A'); Console.WriteLine("New string: " + str); }} Old String: XXXXX New string: AAAAA Important Points to Remember : Replace() method does not modify the value of the current instance. Instead, it returns a new string in which all occurrences of Oldvalue are replaced by Newvalue, similarly oldchar are replaced by Newchar. It performs a case-sensitive search to find OldValue or Oldchar. If Newvalue is null, all occurrences of Oldvalue are removed. References: https://msdn.microsoft.com/en-us/library/czx8s9ts(v=vs.110).aspx https://msdn.microsoft.com/en-us/library/fk49wtc1(v=vs.110).aspx Akanksha_Rai CSharp-method CSharp-string C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Program to calculate Electricity Bill C# | Method Overriding Introduction to .NET Framework C# Dictionary with examples C# | Class and Object C# | Delegates Common Language Runtime (CLR) in C# C# | Constructors Different ways to sort an array in descending order in C# C# | Data Types
[ { "code": null, "e": 24356, "s": 24328, "text": "\n10 May, 2019" }, { "code": null, "e": 24612, "s": 24356, "text": "In C#, Replace() method is a string method. This method is used to replace all the specified Unicode characters or specified string from the current string object and returns a new modified string. This method can be overloaded by passing arguments to it." }, { "code": null, "e": 24620, "s": 24612, "text": "Syntax:" }, { "code": null, "e": 24730, "s": 24620, "text": "public string Replace(char Oldchar, char Newchar)\nor\npublic string Replace(string Oldvalue, string Newvalue)\n" }, { "code": null, "e": 25157, "s": 24730, "text": "Explanation:The First Method takes two parameters Oldchar and Newchar, where Oldchar is the Unicode character to be replaced and Newchar is the character to replace all occurrences of OldChar.The second method also takes two parameters Oldvalue and Newvalue where Oldvalue is the string to be replaced and Newvalue is a string to replace all occurrences of Oldvalue. The return type value of both the methods is System.String." }, { "code": null, "e": 25169, "s": 25157, "text": "Exceptions:" }, { "code": null, "e": 25230, "s": 25169, "text": "ArgumentNullException: If OldValue or Oldchar both are null." }, { "code": null, "e": 25297, "s": 25230, "text": "ArgumentException If OldValue or Oldchar is the empty string (“”)." }, { "code": null, "e": 25355, "s": 25297, "text": "Below are the programs to demonstrate the above methods :" }, { "code": null, "e": 26544, "s": 25355, "text": "Example 1: Program to demonstrate the public string Replace(char Oldchar, char Newchar) method. All occurrences of a specified character are replaced with another specified character. If oldChar is not found in the current string object then string remains unchanged.Input : str = \"GeeksForGeeks\"\n str.Replace('s', 'G');\nOutput: GeekGForGeekG\n\nInput : str = \"GeeksForGeeks\"\n str.Replace('e', ' ');\nOutput: G ksForG ks\n// C# program to illustrate the Replace()// Method with character parameterusing System; class Geeks { // Main Method public static void Main() { // string String str = \"Geeks For Geeks\"; Console.WriteLine(\"OldString : \" + str); // replace the character 's' with 'G' Console.WriteLine(\"NewString: \" + str.Replace('s', 'G')); // oldString will remain unchanged // its return the modified string Console.WriteLine(\"\\nOldString: \" + str); // replace the character 'e' with space ' ' Console.WriteLine(\"NewString: \" + str.Replace('e', ' ')); }}Output:OldString : Geeks For Geeks\nNewString: GeekG For GeekG\n\nOldString: Geeks For Geeks\nNewString: G ks For G ks\n" }, { "code": null, "e": 26714, "s": 26544, "text": "Input : str = \"GeeksForGeeks\"\n str.Replace('s', 'G');\nOutput: GeekGForGeekG\n\nInput : str = \"GeeksForGeeks\"\n str.Replace('e', ' ');\nOutput: G ksForG ks\n" }, { "code": "// C# program to illustrate the Replace()// Method with character parameterusing System; class Geeks { // Main Method public static void Main() { // string String str = \"Geeks For Geeks\"; Console.WriteLine(\"OldString : \" + str); // replace the character 's' with 'G' Console.WriteLine(\"NewString: \" + str.Replace('s', 'G')); // oldString will remain unchanged // its return the modified string Console.WriteLine(\"\\nOldString: \" + str); // replace the character 'e' with space ' ' Console.WriteLine(\"NewString: \" + str.Replace('e', ' ')); }}", "e": 27350, "s": 26714, "text": null }, { "code": null, "e": 27461, "s": 27350, "text": "OldString : Geeks For Geeks\nNewString: GeekG For GeekG\n\nOldString: Geeks For Geeks\nNewString: G ks For G ks\n" }, { "code": null, "e": 28758, "s": 27461, "text": "Example 2: Program to demonstrate the public string Replace(string Oldvalue, string Newvalue) method. All occurrences of a specified string in the current string instance are replaced with another specified string. If Oldvalue is not found in the current string then string remains unchanged.Input: str = \"Geeks For Geeks\"\n str.Replace(\"Geeks\", \"---\");\nOutput: --- For ---\n\nInput: str = \"Geeks For Geeks\"\n str.Replace(\"For\", \"GFG\");\nOutput: Geeks GFG Geeks\n// C# program to illustrate the Replace// Method with string parameterusing System; class Geeks { // Main Method public static void Main() { // define string String str = \"Geeks For Geeks\"; Console.WriteLine(\"OldString : \" + str); // replace the string 'Geeks' with '---' // in string 'Geeks comes two time so replace two times Console.WriteLine(\"NewString: \" + str.Replace(\"Geeks\", \"---\")); // oldString will remain unchanged // its return the modified string Console.WriteLine(\"\\nOldString: \" + str); // replace the string 'For' with 'GFG' Console.WriteLine(\"NewString: \" + str.Replace(\"For\", \"GFG\")); }}Output:OldString : Geeks For Geeks\nNewString: --- For ---\n\nOldString: Geeks For Geeks\nNewString: Geeks GFG Geeks\n" }, { "code": null, "e": 28942, "s": 28758, "text": "Input: str = \"Geeks For Geeks\"\n str.Replace(\"Geeks\", \"---\");\nOutput: --- For ---\n\nInput: str = \"Geeks For Geeks\"\n str.Replace(\"For\", \"GFG\");\nOutput: Geeks GFG Geeks\n" }, { "code": "// C# program to illustrate the Replace// Method with string parameterusing System; class Geeks { // Main Method public static void Main() { // define string String str = \"Geeks For Geeks\"; Console.WriteLine(\"OldString : \" + str); // replace the string 'Geeks' with '---' // in string 'Geeks comes two time so replace two times Console.WriteLine(\"NewString: \" + str.Replace(\"Geeks\", \"---\")); // oldString will remain unchanged // its return the modified string Console.WriteLine(\"\\nOldString: \" + str); // replace the string 'For' with 'GFG' Console.WriteLine(\"NewString: \" + str.Replace(\"For\", \"GFG\")); }}", "e": 29651, "s": 28942, "text": null }, { "code": null, "e": 29758, "s": 29651, "text": "OldString : Geeks For Geeks\nNewString: --- For ---\n\nOldString: Geeks For Geeks\nNewString: Geeks GFG Geeks\n" }, { "code": null, "e": 29839, "s": 29758, "text": "To perform multiple replacements operations on the string(Replacement’s Chain) :" }, { "code": null, "e": 30210, "s": 29839, "text": "The above Replace() method returns the modified string, so now we can chain together successive calls to the Replace method to perform multiple replacements on the string. Method calls are executed from left to right.In below example, for the given string “XXXXX” first X will be replaced with Y and then Y will be replaced with Z and finally, Z will be replaced with A." }, { "code": null, "e": 30220, "s": 30210, "text": "Example :" }, { "code": "// C# program to demonstrate the // multiple replacements callsusing System; public class Geeks{ // Main Method public static void Main() { String str = \"XXXXX\"; Console.WriteLine(\"Old String: \" + str); // chain together str = str.Replace('X', 'Y').Replace('Y', 'Z').Replace('Z', 'A'); Console.WriteLine(\"New string: \" + str); }}", "e": 30602, "s": 30220, "text": null }, { "code": null, "e": 30639, "s": 30602, "text": "Old String: XXXXX\nNew string: AAAAA\n" }, { "code": null, "e": 30670, "s": 30639, "text": "Important Points to Remember :" }, { "code": null, "e": 30877, "s": 30670, "text": "Replace() method does not modify the value of the current instance. Instead, it returns a new string in which all occurrences of Oldvalue are replaced by Newvalue, similarly oldchar are replaced by Newchar." }, { "code": null, "e": 31004, "s": 30877, "text": "It performs a case-sensitive search to find OldValue or Oldchar. If Newvalue is null, all occurrences of Oldvalue are removed." }, { "code": null, "e": 31016, "s": 31004, "text": "References:" }, { "code": null, "e": 31081, "s": 31016, "text": "https://msdn.microsoft.com/en-us/library/czx8s9ts(v=vs.110).aspx" }, { "code": null, "e": 31146, "s": 31081, "text": "https://msdn.microsoft.com/en-us/library/fk49wtc1(v=vs.110).aspx" }, { "code": null, "e": 31159, "s": 31146, "text": "Akanksha_Rai" }, { "code": null, "e": 31173, "s": 31159, "text": "CSharp-method" }, { "code": null, "e": 31187, "s": 31173, "text": "CSharp-string" }, { "code": null, "e": 31190, "s": 31187, "text": "C#" }, { "code": null, "e": 31288, "s": 31190, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31297, "s": 31288, "text": "Comments" }, { "code": null, "e": 31310, "s": 31297, "text": "Old Comments" }, { "code": null, "e": 31348, "s": 31310, "text": "Program to calculate Electricity Bill" }, { "code": null, "e": 31371, "s": 31348, "text": "C# | Method Overriding" }, { "code": null, "e": 31402, "s": 31371, "text": "Introduction to .NET Framework" }, { "code": null, "e": 31430, "s": 31402, "text": "C# Dictionary with examples" }, { "code": null, "e": 31452, "s": 31430, "text": "C# | Class and Object" }, { "code": null, "e": 31467, "s": 31452, "text": "C# | Delegates" }, { "code": null, "e": 31503, "s": 31467, "text": "Common Language Runtime (CLR) in C#" }, { "code": null, "e": 31521, "s": 31503, "text": "C# | Constructors" }, { "code": null, "e": 31579, "s": 31521, "text": "Different ways to sort an array in descending order in C#" } ]
Confusing Number II in C++
Suppose we have a digit, now if we rotate that digit by 180 degrees to form new digits. When 0, 1, 6, 8, 9 are rotated 180 degrees, they become 0, 1, 9, 8, 6 respectively. But when 2, 3, 4, 5 and 7 are rotated 180 degrees, they become invalid. A confusing number is a number that when rotated 180 degrees becomes a new number. So, if we have a positive integer N, we have to find the number of confusing numbers between 1 and N inclusive. So, if the input is like 20, then the output will be 6 To solve this, we will follow these steps − Define one map mapping Define one map mapping Define an array valid Define an array valid Define a function solve(), this will take num, rotate, digit, N, Define a function solve(), this will take num, rotate, digit, N, if rotate is not equal to num, then −(increase ret by 1) if rotate is not equal to num, then − (increase ret by 1) (increase ret by 1) for initialize i := 0, when i < size of valid, update (increase i by 1), do −dig := valid[i]if num * 10 + dig > N, thenCome out from the loopsolve(num * 10 + dig, Define one map, digit * 10, N) for initialize i := 0, when i < size of valid, update (increase i by 1), do − dig := valid[i] dig := valid[i] if num * 10 + dig > N, thenCome out from the loop if num * 10 + dig > N, then Come out from the loop Come out from the loop solve(num * 10 + dig, Define one map, digit * 10, N) solve(num * 10 + dig, Define one map, digit * 10, N) From the main method do the following − From the main method do the following − ret := 0 ret := 0 valid := { 0, 1, 6, 8, 9 } valid := { 0, 1, 6, 8, 9 } mapping[0] := 0 mapping[0] := 0 mapping[1] := 1 mapping[1] := 1 mapping[6] := 9 mapping[6] := 9 mapping[9] := 6 mapping[9] := 6 mapping[8] := 8 mapping[8] := 8 solve(1, 1, 10, N) solve(1, 1, 10, N) solve(6, 9, 10, N) solve(6, 9, 10, N) solve(9, 6, 10, N) solve(9, 6, 10, N) solve(8, 8, 10, N) solve(8, 8, 10, N) return ret return ret Let us see the following implementation to get better understanding − Live Demo #include <bits/stdc++.h> using namespace std; typedef long long int lli; class Solution { public: int ret; map <int, int> mapping; vector <int> valid; void solve(lli num, lli rotate, lli digit, lli N){ if (rotate != num) { ret++; } for (int i = 0; i < valid.size(); i++) { int dig = valid[i]; if (num * 10 + dig > N) { break; } solve(num * 10 + dig, mapping[dig] * digit + rotate, digit * 10, N); } } int confusingNumberII(int N) { ret = 0; valid = { 0, 1, 6, 8, 9 }; mapping[0] = 0; mapping[1] = 1; mapping[6] = 9; mapping[9] = 6; mapping[8] = 8; solve(1, 1, 10, N); solve(6, 9, 10, N); solve(9, 6, 10, N); solve(8, 8, 10, N); return ret; } }; main(){ Solution ob; cout << (ob.confusingNumberII(20)); } 20 6
[ { "code": null, "e": 1306, "s": 1062, "text": "Suppose we have a digit, now if we rotate that digit by 180 degrees to form new digits. When 0, 1, 6, 8, 9 are rotated 180 degrees, they become 0, 1, 9, 8, 6 respectively. But when 2, 3, 4, 5 and 7 are rotated 180 degrees, they become invalid." }, { "code": null, "e": 1501, "s": 1306, "text": "A confusing number is a number that when rotated 180 degrees becomes a new number. So, if we have a positive integer N, we have to find the number of confusing numbers between 1 and N inclusive." }, { "code": null, "e": 1556, "s": 1501, "text": "So, if the input is like 20, then the output will be 6" }, { "code": null, "e": 1600, "s": 1556, "text": "To solve this, we will follow these steps −" }, { "code": null, "e": 1623, "s": 1600, "text": "Define one map mapping" }, { "code": null, "e": 1646, "s": 1623, "text": "Define one map mapping" }, { "code": null, "e": 1668, "s": 1646, "text": "Define an array valid" }, { "code": null, "e": 1690, "s": 1668, "text": "Define an array valid" }, { "code": null, "e": 1755, "s": 1690, "text": "Define a function solve(), this will take num, rotate, digit, N," }, { "code": null, "e": 1820, "s": 1755, "text": "Define a function solve(), this will take num, rotate, digit, N," }, { "code": null, "e": 1877, "s": 1820, "text": "if rotate is not equal to num, then −(increase ret by 1)" }, { "code": null, "e": 1915, "s": 1877, "text": "if rotate is not equal to num, then −" }, { "code": null, "e": 1935, "s": 1915, "text": "(increase ret by 1)" }, { "code": null, "e": 1955, "s": 1935, "text": "(increase ret by 1)" }, { "code": null, "e": 2149, "s": 1955, "text": "for initialize i := 0, when i < size of valid, update (increase i by 1), do −dig := valid[i]if num * 10 + dig > N, thenCome out from the loopsolve(num * 10 + dig, Define one map, digit * 10, N)" }, { "code": null, "e": 2227, "s": 2149, "text": "for initialize i := 0, when i < size of valid, update (increase i by 1), do −" }, { "code": null, "e": 2243, "s": 2227, "text": "dig := valid[i]" }, { "code": null, "e": 2259, "s": 2243, "text": "dig := valid[i]" }, { "code": null, "e": 2309, "s": 2259, "text": "if num * 10 + dig > N, thenCome out from the loop" }, { "code": null, "e": 2337, "s": 2309, "text": "if num * 10 + dig > N, then" }, { "code": null, "e": 2360, "s": 2337, "text": "Come out from the loop" }, { "code": null, "e": 2383, "s": 2360, "text": "Come out from the loop" }, { "code": null, "e": 2436, "s": 2383, "text": "solve(num * 10 + dig, Define one map, digit * 10, N)" }, { "code": null, "e": 2489, "s": 2436, "text": "solve(num * 10 + dig, Define one map, digit * 10, N)" }, { "code": null, "e": 2529, "s": 2489, "text": "From the main method do the following −" }, { "code": null, "e": 2569, "s": 2529, "text": "From the main method do the following −" }, { "code": null, "e": 2578, "s": 2569, "text": "ret := 0" }, { "code": null, "e": 2587, "s": 2578, "text": "ret := 0" }, { "code": null, "e": 2614, "s": 2587, "text": "valid := { 0, 1, 6, 8, 9 }" }, { "code": null, "e": 2641, "s": 2614, "text": "valid := { 0, 1, 6, 8, 9 }" }, { "code": null, "e": 2657, "s": 2641, "text": "mapping[0] := 0" }, { "code": null, "e": 2673, "s": 2657, "text": "mapping[0] := 0" }, { "code": null, "e": 2689, "s": 2673, "text": "mapping[1] := 1" }, { "code": null, "e": 2705, "s": 2689, "text": "mapping[1] := 1" }, { "code": null, "e": 2721, "s": 2705, "text": "mapping[6] := 9" }, { "code": null, "e": 2737, "s": 2721, "text": "mapping[6] := 9" }, { "code": null, "e": 2753, "s": 2737, "text": "mapping[9] := 6" }, { "code": null, "e": 2769, "s": 2753, "text": "mapping[9] := 6" }, { "code": null, "e": 2785, "s": 2769, "text": "mapping[8] := 8" }, { "code": null, "e": 2801, "s": 2785, "text": "mapping[8] := 8" }, { "code": null, "e": 2820, "s": 2801, "text": "solve(1, 1, 10, N)" }, { "code": null, "e": 2839, "s": 2820, "text": "solve(1, 1, 10, N)" }, { "code": null, "e": 2858, "s": 2839, "text": "solve(6, 9, 10, N)" }, { "code": null, "e": 2877, "s": 2858, "text": "solve(6, 9, 10, N)" }, { "code": null, "e": 2896, "s": 2877, "text": "solve(9, 6, 10, N)" }, { "code": null, "e": 2915, "s": 2896, "text": "solve(9, 6, 10, N)" }, { "code": null, "e": 2934, "s": 2915, "text": "solve(8, 8, 10, N)" }, { "code": null, "e": 2953, "s": 2934, "text": "solve(8, 8, 10, N)" }, { "code": null, "e": 2964, "s": 2953, "text": "return ret" }, { "code": null, "e": 2975, "s": 2964, "text": "return ret" }, { "code": null, "e": 3045, "s": 2975, "text": "Let us see the following implementation to get better understanding −" }, { "code": null, "e": 3056, "s": 3045, "text": " Live Demo" }, { "code": null, "e": 3943, "s": 3056, "text": "#include <bits/stdc++.h>\nusing namespace std;\ntypedef long long int lli;\nclass Solution {\n public:\n int ret;\n map <int, int> mapping;\n vector <int> valid;\n void solve(lli num, lli rotate, lli digit, lli N){\n if (rotate != num) {\n ret++;\n }\n for (int i = 0; i < valid.size(); i++) {\n int dig = valid[i];\n if (num * 10 + dig > N) {\n break;\n }\n solve(num * 10 + dig, mapping[dig] * digit + rotate, digit * 10, N);\n }\n }\n int confusingNumberII(int N) {\n ret = 0;\n valid = { 0, 1, 6, 8, 9 };\n mapping[0] = 0;\n mapping[1] = 1;\n mapping[6] = 9;\n mapping[9] = 6;\n mapping[8] = 8;\n solve(1, 1, 10, N);\n solve(6, 9, 10, N);\n solve(9, 6, 10, N);\n solve(8, 8, 10, N);\n return ret;\n }\n};\nmain(){\n Solution ob;\n cout << (ob.confusingNumberII(20));\n}" }, { "code": null, "e": 3946, "s": 3943, "text": "20" }, { "code": null, "e": 3948, "s": 3946, "text": "6" } ]
How to display a Listbox with columns using Tkinter?
To deal with lots of data in any application, Tkinter provides a Treeview widget. It has various features such as displaying data in the form of tables consisting of Rows and Columns. Treeview widget enables the user to add tables, insert data into it, and manipulate the data from the table. The Treeview widget can be constructed by defining the Treeview(parent, column, **options) constructor. # Import the required libraries from tkinter import * from tkinter import ttk # Create an instance of tkinter frame win = Tk() # Set the size of the tkinter window win.geometry("700x350") s = ttk.Style() s.theme_use('clam') # Add a Treeview widget tree = ttk.Treeview(win, column=("c1", "c2", "c3"), show='headings', height=5) tree.column("# 1", anchor=CENTER) tree.heading("# 1", text="ID") tree.column("# 2", anchor=CENTER) tree.heading("# 2", text="FName") tree.column("# 3", anchor=CENTER) tree.heading("# 3", text="LName") # Insert the data in Treeview widget tree.insert('', 'end', text="1", values=('1', 'Joe', 'Nash')) tree.insert('', 'end', text="2", values=('2', 'Emily', 'Mackmohan')) tree.insert('', 'end', text="3", values=('3', 'Estilla', 'Roffe')) tree.insert('', 'end', text="4", values=('4', 'Percy', 'Andrews')) tree.insert('', 'end', text="5", values=('5', 'Stephan', 'Heyward')) tree.pack() win.mainloop() When we execute the above code, it will display a List of items with some columns.
[ { "code": null, "e": 1246, "s": 1062, "text": "To deal with lots of data in any application, Tkinter provides a Treeview widget. It has various features such as displaying data in the form of tables consisting of Rows and Columns." }, { "code": null, "e": 1459, "s": 1246, "text": "Treeview widget enables the user to add tables, insert data into it, and manipulate the data from the table. The Treeview widget can be constructed by defining the Treeview(parent, column, **options) constructor." }, { "code": null, "e": 2393, "s": 1459, "text": "# Import the required libraries\nfrom tkinter import *\nfrom tkinter import ttk\n\n# Create an instance of tkinter frame\nwin = Tk()\n\n# Set the size of the tkinter window\nwin.geometry(\"700x350\")\n\ns = ttk.Style()\ns.theme_use('clam')\n\n# Add a Treeview widget\ntree = ttk.Treeview(win, column=(\"c1\", \"c2\", \"c3\"), show='headings', height=5)\n\ntree.column(\"# 1\", anchor=CENTER)\ntree.heading(\"# 1\", text=\"ID\")\ntree.column(\"# 2\", anchor=CENTER)\ntree.heading(\"# 2\", text=\"FName\")\ntree.column(\"# 3\", anchor=CENTER)\ntree.heading(\"# 3\", text=\"LName\")\n\n# Insert the data in Treeview widget\ntree.insert('', 'end', text=\"1\", values=('1', 'Joe', 'Nash'))\ntree.insert('', 'end', text=\"2\", values=('2', 'Emily', 'Mackmohan'))\ntree.insert('', 'end', text=\"3\", values=('3', 'Estilla', 'Roffe'))\ntree.insert('', 'end', text=\"4\", values=('4', 'Percy', 'Andrews'))\ntree.insert('', 'end', text=\"5\", values=('5', 'Stephan', 'Heyward'))\n\ntree.pack()\n\nwin.mainloop()" }, { "code": null, "e": 2476, "s": 2393, "text": "When we execute the above code, it will display a List of items with some columns." } ]
Get specific row from PySpark dataframe - GeeksforGeeks
18 Jul, 2021 In this article, we will discuss how to get the specific row from the PySpark dataframe. Creating Dataframe for demonstration: Python3 # importing moduleimport pyspark # importing sparksession# from pyspark.sql modulefrom pyspark.sql import SparkSession # creating sparksession# and giving an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate() # list of employee data with 5 row valuesdata = [["1", "sravan", "company 1"], ["2", "ojaswi", "company 2"], ["3", "bobby", "company 3"], ["4", "rohith", "company 2"], ["5", "gnanesh", "company 1"]] # specify column namescolumns = ['Employee ID', 'Employee NAME', 'Company Name'] # creating a dataframe from the lists of datadataframe = spark.createDataFrame(data, columns) # display dataframedataframe.show() Output: This is used to get the all row’s data from the dataframe in list format. Syntax: dataframe.collect()[index_position] Where, dataframe is the pyspark dataframe index_position is the index row in dataframe Example: Python code to access rows Python3 # get first rowprint(dataframe.collect()[0]) # get second rowprint(dataframe.collect()[1]) # get last rowprint(dataframe.collect()[-1]) # get third rowprint(dataframe.collect()[2]) Output: Row(Employee ID=’1′, Employee NAME=’sravan’, Company Name=’company 1′) Row(Employee ID=’2′, Employee NAME=’ojaswi’, Company Name=’company 2′) Row(Employee ID=’5′, Employee NAME=’gnanesh’, Company Name=’company 1′) Row(Employee ID=’3′, Employee NAME=’bobby’, Company Name=’company 3′) This function is used to get the top n rows from the pyspark dataframe. Syntax: dataframe.show(no_of_rows) where, no_of_rows is the row number to get the data Example: Python code to get the data using show() function Python3 # display dataframe only top 2 rowsprint(dataframe.show(2)) # display dataframe only top 1 rowprint(dataframe.show(1)) # display dataframe print(dataframe.show()) Output: This function is used to return only the first row in the dataframe. Syntax: dataframe.first() Example: Python code to select the first row in the dataframe. Python3 # display first row of the dataframeprint(dataframe.first()) Output: Row(Employee ID=’1′, Employee NAME=’sravan’, Company Name=’company 1′) This method is used to display top n rows in the dataframe. Syntax: dataframe.head(n) where, n is the number of rows to be displayed Example: Python code to display the number of rows to be displayed. Python3 # display only 1 rowprint(dataframe.head(1)) # display only top 3 rowsprint(dataframe.head(3)) # display only top 2 rowsprint(dataframe.head(2)) Output: [Row(Employee ID=’1′, Employee NAME=’sravan’, Company Name=’company 1′)] [Row(Employee ID=’1′, Employee NAME=’sravan’, Company Name=’company 1′), Row(Employee ID=’2′, Employee NAME=’ojaswi’, Company Name=’company 2′), Row(Employee ID=’3′, Employee NAME=’bobby’, Company Name=’company 3′)] [Row(Employee ID=’1′, Employee NAME=’sravan’, Company Name=’company 1′), Row(Employee ID=’2′, Employee NAME=’ojaswi’, Company Name=’company 2′)] Used to return last n rows in the dataframe Syntax: dataframe.tail(n) where n is the no of rows to be returned from last in the dataframe. Example: Python code to get last n rows Python3 # display only 1 row from lastprint(dataframe.tail(1)) # display only top 3 rows from lastprint(dataframe.tail(3)) # display only top 2 rows from lastprint(dataframe.tail(2)) Output: [Row(Employee ID=’5′, Employee NAME=’gnanesh’, Company Name=’company 1′)] [Row(Employee ID=’3′, Employee NAME=’bobby’, Company Name=’company 3′), Row(Employee ID=’4′, Employee NAME=’rohith’, Company Name=’company 2′), Row(Employee ID=’5′, Employee NAME=’gnanesh’, Company Name=’company 1′)] [Row(Employee ID=’4′, Employee NAME=’rohith’, Company Name=’company 2′), Row(Employee ID=’5′, Employee NAME=’gnanesh’, Company Name=’company 1′)] This method is used to select a particular row from the dataframe, It can be used with collect() function. Syntax: dataframe.select([columns]).collect()[index] where, dataframe is the pyspark dataframe Columns is the list of columns to be displayed in each row Index is the index number of row to be displayed. Example: Python code to select the particular row. Python3 # select first rowprint(dataframe.select(['Employee ID', 'Employee NAME', 'Company Name']).collect()[0]) # select third rowprint(dataframe.select(['Employee ID', 'Employee NAME', 'Company Name']).collect()[2]) # select forth rowprint(dataframe.select(['Employee ID', 'Employee NAME', 'Company Name']).collect()[3]) Output: Row(Employee ID=’1′, Employee NAME=’sravan’, Company Name=’company 1′) Row(Employee ID=’3′, Employee NAME=’bobby’, Company Name=’company 3′) Row(Employee ID=’4′, Employee NAME=’rohith’, Company Name=’company 2′) This method is also used to select top n rows Syntax: dataframe.take(n) where n is the number of rows to be selected Python3 # select top 2 rowsprint(dataframe.take(2)) # select top 4 rowsprint(dataframe.take(4)) # select top 1 rowprint(dataframe.take(1)) Output: [Row(Employee ID=’1′, Employee NAME=’sravan’, Company Name=’company 1′), Row(Employee ID=’2′, Employee NAME=’ojaswi’, Company Name=’company 2′)] [Row(Employee ID=’1′, Employee NAME=’sravan’, Company Name=’company 1′), Row(Employee ID=’2′, Employee NAME=’ojaswi’, Company Name=’company 2′), Row(Employee ID=’3′, Employee NAME=’bobby’, Company Name=’company 3′), Row(Employee ID=’4′, Employee NAME=’rohith’, Company Name=’company 2′)] [Row(Employee ID=’1′, Employee NAME=’sravan’, Company Name=’company 1′)] Picked Python-Pyspark Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Python Dictionary Read a file line by line in Python Enumerate() in Python How to Install PIP on Windows ? Iterate over a list in Python Different ways to create Pandas Dataframe Python program to convert a list to string Python String | replace() Reading and Writing to text files in Python sum() function in Python
[ { "code": null, "e": 24317, "s": 24289, "text": "\n18 Jul, 2021" }, { "code": null, "e": 24406, "s": 24317, "text": "In this article, we will discuss how to get the specific row from the PySpark dataframe." }, { "code": null, "e": 24444, "s": 24406, "text": "Creating Dataframe for demonstration:" }, { "code": null, "e": 24452, "s": 24444, "text": "Python3" }, { "code": "# importing moduleimport pyspark # importing sparksession# from pyspark.sql modulefrom pyspark.sql import SparkSession # creating sparksession# and giving an app namespark = SparkSession.builder.appName('sparkdf').getOrCreate() # list of employee data with 5 row valuesdata = [[\"1\", \"sravan\", \"company 1\"], [\"2\", \"ojaswi\", \"company 2\"], [\"3\", \"bobby\", \"company 3\"], [\"4\", \"rohith\", \"company 2\"], [\"5\", \"gnanesh\", \"company 1\"]] # specify column namescolumns = ['Employee ID', 'Employee NAME', 'Company Name'] # creating a dataframe from the lists of datadataframe = spark.createDataFrame(data, columns) # display dataframedataframe.show()", "e": 25135, "s": 24452, "text": null }, { "code": null, "e": 25143, "s": 25135, "text": "Output:" }, { "code": null, "e": 25217, "s": 25143, "text": "This is used to get the all row’s data from the dataframe in list format." }, { "code": null, "e": 25261, "s": 25217, "text": "Syntax: dataframe.collect()[index_position]" }, { "code": null, "e": 25268, "s": 25261, "text": "Where," }, { "code": null, "e": 25303, "s": 25268, "text": "dataframe is the pyspark dataframe" }, { "code": null, "e": 25348, "s": 25303, "text": "index_position is the index row in dataframe" }, { "code": null, "e": 25384, "s": 25348, "text": "Example: Python code to access rows" }, { "code": null, "e": 25392, "s": 25384, "text": "Python3" }, { "code": "# get first rowprint(dataframe.collect()[0]) # get second rowprint(dataframe.collect()[1]) # get last rowprint(dataframe.collect()[-1]) # get third rowprint(dataframe.collect()[2])", "e": 25576, "s": 25392, "text": null }, { "code": null, "e": 25584, "s": 25576, "text": "Output:" }, { "code": null, "e": 25655, "s": 25584, "text": "Row(Employee ID=’1′, Employee NAME=’sravan’, Company Name=’company 1′)" }, { "code": null, "e": 25726, "s": 25655, "text": "Row(Employee ID=’2′, Employee NAME=’ojaswi’, Company Name=’company 2′)" }, { "code": null, "e": 25798, "s": 25726, "text": "Row(Employee ID=’5′, Employee NAME=’gnanesh’, Company Name=’company 1′)" }, { "code": null, "e": 25868, "s": 25798, "text": "Row(Employee ID=’3′, Employee NAME=’bobby’, Company Name=’company 3′)" }, { "code": null, "e": 25940, "s": 25868, "text": "This function is used to get the top n rows from the pyspark dataframe." }, { "code": null, "e": 25975, "s": 25940, "text": "Syntax: dataframe.show(no_of_rows)" }, { "code": null, "e": 26027, "s": 25975, "text": "where, no_of_rows is the row number to get the data" }, { "code": null, "e": 26086, "s": 26027, "text": "Example: Python code to get the data using show() function" }, { "code": null, "e": 26094, "s": 26086, "text": "Python3" }, { "code": "# display dataframe only top 2 rowsprint(dataframe.show(2)) # display dataframe only top 1 rowprint(dataframe.show(1)) # display dataframe print(dataframe.show())", "e": 26259, "s": 26094, "text": null }, { "code": null, "e": 26267, "s": 26259, "text": "Output:" }, { "code": null, "e": 26336, "s": 26267, "text": "This function is used to return only the first row in the dataframe." }, { "code": null, "e": 26362, "s": 26336, "text": "Syntax: dataframe.first()" }, { "code": null, "e": 26425, "s": 26362, "text": "Example: Python code to select the first row in the dataframe." }, { "code": null, "e": 26433, "s": 26425, "text": "Python3" }, { "code": "# display first row of the dataframeprint(dataframe.first())", "e": 26494, "s": 26433, "text": null }, { "code": null, "e": 26502, "s": 26494, "text": "Output:" }, { "code": null, "e": 26573, "s": 26502, "text": "Row(Employee ID=’1′, Employee NAME=’sravan’, Company Name=’company 1′)" }, { "code": null, "e": 26633, "s": 26573, "text": "This method is used to display top n rows in the dataframe." }, { "code": null, "e": 26659, "s": 26633, "text": "Syntax: dataframe.head(n)" }, { "code": null, "e": 26706, "s": 26659, "text": "where, n is the number of rows to be displayed" }, { "code": null, "e": 26774, "s": 26706, "text": "Example: Python code to display the number of rows to be displayed." }, { "code": null, "e": 26782, "s": 26774, "text": "Python3" }, { "code": "# display only 1 rowprint(dataframe.head(1)) # display only top 3 rowsprint(dataframe.head(3)) # display only top 2 rowsprint(dataframe.head(2))", "e": 26930, "s": 26782, "text": null }, { "code": null, "e": 26938, "s": 26930, "text": "Output:" }, { "code": null, "e": 27011, "s": 26938, "text": "[Row(Employee ID=’1′, Employee NAME=’sravan’, Company Name=’company 1′)]" }, { "code": null, "e": 27085, "s": 27011, "text": "[Row(Employee ID=’1′, Employee NAME=’sravan’, Company Name=’company 1′), " }, { "code": null, "e": 27158, "s": 27085, "text": "Row(Employee ID=’2′, Employee NAME=’ojaswi’, Company Name=’company 2′), " }, { "code": null, "e": 27229, "s": 27158, "text": "Row(Employee ID=’3′, Employee NAME=’bobby’, Company Name=’company 3′)]" }, { "code": null, "e": 27303, "s": 27229, "text": "[Row(Employee ID=’1′, Employee NAME=’sravan’, Company Name=’company 1′), " }, { "code": null, "e": 27375, "s": 27303, "text": "Row(Employee ID=’2′, Employee NAME=’ojaswi’, Company Name=’company 2′)]" }, { "code": null, "e": 27419, "s": 27375, "text": "Used to return last n rows in the dataframe" }, { "code": null, "e": 27445, "s": 27419, "text": "Syntax: dataframe.tail(n)" }, { "code": null, "e": 27514, "s": 27445, "text": "where n is the no of rows to be returned from last in the dataframe." }, { "code": null, "e": 27554, "s": 27514, "text": "Example: Python code to get last n rows" }, { "code": null, "e": 27562, "s": 27554, "text": "Python3" }, { "code": "# display only 1 row from lastprint(dataframe.tail(1)) # display only top 3 rows from lastprint(dataframe.tail(3)) # display only top 2 rows from lastprint(dataframe.tail(2))", "e": 27740, "s": 27562, "text": null }, { "code": null, "e": 27748, "s": 27740, "text": "Output:" }, { "code": null, "e": 27822, "s": 27748, "text": "[Row(Employee ID=’5′, Employee NAME=’gnanesh’, Company Name=’company 1′)]" }, { "code": null, "e": 27894, "s": 27822, "text": "[Row(Employee ID=’3′, Employee NAME=’bobby’, Company Name=’company 3′)," }, { "code": null, "e": 27967, "s": 27894, "text": " Row(Employee ID=’4′, Employee NAME=’rohith’, Company Name=’company 2′)," }, { "code": null, "e": 28042, "s": 27967, "text": " Row(Employee ID=’5′, Employee NAME=’gnanesh’, Company Name=’company 1′)]" }, { "code": null, "e": 28115, "s": 28042, "text": "[Row(Employee ID=’4′, Employee NAME=’rohith’, Company Name=’company 2′)," }, { "code": null, "e": 28189, "s": 28115, "text": " Row(Employee ID=’5′, Employee NAME=’gnanesh’, Company Name=’company 1′)]" }, { "code": null, "e": 28296, "s": 28189, "text": "This method is used to select a particular row from the dataframe, It can be used with collect() function." }, { "code": null, "e": 28349, "s": 28296, "text": "Syntax: dataframe.select([columns]).collect()[index]" }, { "code": null, "e": 28357, "s": 28349, "text": "where, " }, { "code": null, "e": 28392, "s": 28357, "text": "dataframe is the pyspark dataframe" }, { "code": null, "e": 28451, "s": 28392, "text": "Columns is the list of columns to be displayed in each row" }, { "code": null, "e": 28501, "s": 28451, "text": "Index is the index number of row to be displayed." }, { "code": null, "e": 28552, "s": 28501, "text": "Example: Python code to select the particular row." }, { "code": null, "e": 28560, "s": 28552, "text": "Python3" }, { "code": "# select first rowprint(dataframe.select(['Employee ID', 'Employee NAME', 'Company Name']).collect()[0]) # select third rowprint(dataframe.select(['Employee ID', 'Employee NAME', 'Company Name']).collect()[2]) # select forth rowprint(dataframe.select(['Employee ID', 'Employee NAME', 'Company Name']).collect()[3])", "e": 29015, "s": 28560, "text": null }, { "code": null, "e": 29023, "s": 29015, "text": "Output:" }, { "code": null, "e": 29094, "s": 29023, "text": "Row(Employee ID=’1′, Employee NAME=’sravan’, Company Name=’company 1′)" }, { "code": null, "e": 29164, "s": 29094, "text": "Row(Employee ID=’3′, Employee NAME=’bobby’, Company Name=’company 3′)" }, { "code": null, "e": 29235, "s": 29164, "text": "Row(Employee ID=’4′, Employee NAME=’rohith’, Company Name=’company 2′)" }, { "code": null, "e": 29281, "s": 29235, "text": "This method is also used to select top n rows" }, { "code": null, "e": 29307, "s": 29281, "text": "Syntax: dataframe.take(n)" }, { "code": null, "e": 29352, "s": 29307, "text": "where n is the number of rows to be selected" }, { "code": null, "e": 29360, "s": 29352, "text": "Python3" }, { "code": "# select top 2 rowsprint(dataframe.take(2)) # select top 4 rowsprint(dataframe.take(4)) # select top 1 rowprint(dataframe.take(1))", "e": 29493, "s": 29360, "text": null }, { "code": null, "e": 29501, "s": 29493, "text": "Output:" }, { "code": null, "e": 29575, "s": 29501, "text": "[Row(Employee ID=’1′, Employee NAME=’sravan’, Company Name=’company 1′), " }, { "code": null, "e": 29647, "s": 29575, "text": "Row(Employee ID=’2′, Employee NAME=’ojaswi’, Company Name=’company 2′)]" }, { "code": null, "e": 29720, "s": 29647, "text": "[Row(Employee ID=’1′, Employee NAME=’sravan’, Company Name=’company 1′)," }, { "code": null, "e": 29792, "s": 29720, "text": "Row(Employee ID=’2′, Employee NAME=’ojaswi’, Company Name=’company 2′)," }, { "code": null, "e": 29864, "s": 29792, "text": " Row(Employee ID=’3′, Employee NAME=’bobby’, Company Name=’company 3′)," }, { "code": null, "e": 29938, "s": 29864, "text": " Row(Employee ID=’4′, Employee NAME=’rohith’, Company Name=’company 2′)]" }, { "code": null, "e": 30011, "s": 29938, "text": "[Row(Employee ID=’1′, Employee NAME=’sravan’, Company Name=’company 1′)]" }, { "code": null, "e": 30018, "s": 30011, "text": "Picked" }, { "code": null, "e": 30033, "s": 30018, "text": "Python-Pyspark" }, { "code": null, "e": 30040, "s": 30033, "text": "Python" }, { "code": null, "e": 30138, "s": 30040, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30147, "s": 30138, "text": "Comments" }, { "code": null, "e": 30160, "s": 30147, "text": "Old Comments" }, { "code": null, "e": 30178, "s": 30160, "text": "Python Dictionary" }, { "code": null, "e": 30213, "s": 30178, "text": "Read a file line by line in Python" }, { "code": null, "e": 30235, "s": 30213, "text": "Enumerate() in Python" }, { "code": null, "e": 30267, "s": 30235, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 30297, "s": 30267, "text": "Iterate over a list in Python" }, { "code": null, "e": 30339, "s": 30297, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 30382, "s": 30339, "text": "Python program to convert a list to string" }, { "code": null, "e": 30408, "s": 30382, "text": "Python String | replace()" }, { "code": null, "e": 30452, "s": 30408, "text": "Reading and Writing to text files in Python" } ]
COBOL - Environment Setup
We have set up the COBOL Programming environment online, so that you can compile and execute all the available examples online. It gives you confidence in what you are reading and enables you to verify the programs with different options. Feel free to modify any example and execute it online. IDENTIFICATION DIVISION. PROGRAM-ID. HELLO. PROCEDURE DIVISION. DISPLAY 'Hello World'. STOP RUN. For most of the examples given in this tutorial, you will find a Try it option in our website code sections at the top right corner that will take you to the online compiler. So just make use of it and enjoy your learning. There are many Free Mainframe Emulators available for Windows which can be used to write and learn simple COBOL programs. One such emulator is Hercules, which can be easily installed on Windows by following a few simple steps as given below − Download and install the Hercules emulator, which is available from the Hercules' home site: www.hercules-390.eu Download and install the Hercules emulator, which is available from the Hercules' home site: www.hercules-390.eu Once you have installed the package on Windows machine, it will create a folder like C:/hercules/mvs/cobol. Once you have installed the package on Windows machine, it will create a folder like C:/hercules/mvs/cobol. Run the Command Prompt (CMD) and reach the directory C:/hercules/mvs/cobol on CMD. Run the Command Prompt (CMD) and reach the directory C:/hercules/mvs/cobol on CMD. The complete guide on various commands to write and execute a JCL and COBOL programs can be found at: www.jaymoseley.com/hercules/installmvs/instmvs2.htm The complete guide on various commands to write and execute a JCL and COBOL programs can be found at: www.jaymoseley.com/hercules/installmvs/instmvs2.htm Hercules is an open-source software implementation of the mainframe System/370 and ESA/390 architectures, in addition to the latest 64-bit z/Architecture. Hercules runs under Linux, Windows, Solaris, FreeBSD, and Mac OS X. A user can connect to a mainframe server in a number of ways such as thin client, dummy terminal, Virtual Client System (VCS), or Virtual Desktop System (VDS). Every valid user is given a login id to enter into the Z/OS interface (TSO/E or ISPF). In order to execute a COBOL program in batch mode using JCL, the program needs to be compiled, and a load module is created with all the sub-programs. The JCL uses the load module and not the actual program at the time of execution. The load libraries are concatenated and given to the JCL at the time of execution using JCLLIB or STEPLIB. There are many mainframe compiler utilities available to compile a COBOL program. Some corporate companies use Change Management tools like Endevor, which compiles and stores every version of the program. This is useful in tracking the changes made to the program. //COMPILE JOB ,CLASS=6,MSGCLASS=X,NOTIFY=&SYSUID //* //STEP1 EXEC IGYCRCTL,PARM=RMODE,DYNAM,SSRANGE //SYSIN DD DSN=MYDATA.URMI.SOURCES(MYCOBB),DISP=SHR //SYSLIB DD DSN=MYDATA.URMI.COPYBOOK(MYCOPY),DISP=SHR //SYSLMOD DD DSN=MYDATA.URMI.LOAD(MYCOBB),DISP=SHR //SYSPRINT DD SYSOUT=* //* IGYCRCTL is an IBM COBOL compiler utility. The compiler options are passed using the PARM parameter. In the above example, RMODE instructs the compiler to use relative addressing mode in the program. The COBOL program is passed using the SYSIN parameter. Copybook is the library used by the program in SYSLIB. Given below is a JCL example where the program MYPROG is executed using the input file MYDATA.URMI.INPUT and produces two output files written to the spool. //COBBSTEP JOB CLASS=6,NOTIFY=&SYSUID // //STEP10 EXEC PGM=MYPROG,PARM=ACCT5000 //STEPLIB DD DSN=MYDATA.URMI.LOADLIB,DISP=SHR //INPUT1 DD DSN=MYDATA.URMI.INPUT,DISP=SHR //OUT1 DD SYSOUT=* //OUT2 DD SYSOUT=* //SYSIN DD * //CUST1 1000 //CUST2 1001 /* The load module of MYPROG is located in MYDATA.URMI.LOADLIB. This is important to note that the above JCL can be used for a non-DB2 COBOL module only. For running a COBOL-DB2 program, a specialized IBM utility is used in the JCL and the program; DB2 region and required parameters are passed as input to the utility. The steps followed in running a COBOL-DB2 program are as follows − When a COBOL-DB2 program is compiled, a DBRM (Database Request Module) is created along with the load module. The DBRM contains the SQL statements of the COBOL programs with its syntax checked to be correct. When a COBOL-DB2 program is compiled, a DBRM (Database Request Module) is created along with the load module. The DBRM contains the SQL statements of the COBOL programs with its syntax checked to be correct. The DBRM is bound to the DB2 region (environment) in which the COBOL will run. This can be done using the IKJEFT01 utility in a JCL. The DBRM is bound to the DB2 region (environment) in which the COBOL will run. This can be done using the IKJEFT01 utility in a JCL. After the bind step, the COBOL-DB2 program is run using IKJEFT01 (again) with the load library and the DBRM library as the input to the JCL. After the bind step, the COBOL-DB2 program is run using IKJEFT01 (again) with the load library and the DBRM library as the input to the JCL. //STEP001 EXEC PGM=IKJEFT01 //* //STEPLIB DD DSN=MYDATA.URMI.DBRMLIB,DISP=SHR //* //input files //output files //SYSPRINT DD SYSOUT=* //SYSABOUT DD SYSOUT=* //SYSDBOUT DD SYSOUT=* //SYSUDUMP DD SYSOUT=* //DISPLAY DD SYSOUT=* //SYSOUT DD SYSOUT=* //SYSTSPRT DD SYSOUT=* //SYSTSIN DD * DSN SYSTEM(SSID) RUN PROGRAM(MYCOBB) PLAN(PLANNAME) PARM(parameters to cobol program) - LIB('MYDATA.URMI.LOADLIB') END /* In the above example, MYCOBB is the COBOL-DB2 program run using IKJEFT01. Please note that the program name, DB2 Sub-System Id (SSID), and DB2 Plan name are passed within the SYSTSIN DD statement. The DBRM library is specified in the STEPLIB. 12 Lectures 2.5 hours Nishant Malik 33 Lectures 3.5 hours Craig Kenneth Kaercher Print Add Notes Bookmark this page
[ { "code": null, "e": 2316, "s": 2022, "text": "We have set up the COBOL Programming environment online, so that you can compile and execute all the available examples online. It gives you confidence in what you are reading and enables you to verify the programs with different options. Feel free to modify any example and execute it online." }, { "code": null, "e": 2417, "s": 2316, "text": "IDENTIFICATION DIVISION.\nPROGRAM-ID. HELLO.\n\nPROCEDURE DIVISION.\n DISPLAY 'Hello World'.\nSTOP RUN." }, { "code": null, "e": 2640, "s": 2417, "text": "For most of the examples given in this tutorial, you will find a Try it option in our website code sections at the top right corner that will take you to the online compiler. So just make use of it and enjoy your learning." }, { "code": null, "e": 2762, "s": 2640, "text": "There are many Free Mainframe Emulators available for Windows which can be used to write and learn simple COBOL programs." }, { "code": null, "e": 2883, "s": 2762, "text": "One such emulator is Hercules, which can be easily installed on Windows by following a few simple steps as given below −" }, { "code": null, "e": 2996, "s": 2883, "text": "Download and install the Hercules emulator, which is available from the Hercules' home site: www.hercules-390.eu" }, { "code": null, "e": 3109, "s": 2996, "text": "Download and install the Hercules emulator, which is available from the Hercules' home site: www.hercules-390.eu" }, { "code": null, "e": 3217, "s": 3109, "text": "Once you have installed the package on Windows machine, it will create a folder like C:/hercules/mvs/cobol." }, { "code": null, "e": 3325, "s": 3217, "text": "Once you have installed the package on Windows machine, it will create a folder like C:/hercules/mvs/cobol." }, { "code": null, "e": 3408, "s": 3325, "text": "Run the Command Prompt (CMD) and reach the directory C:/hercules/mvs/cobol on CMD." }, { "code": null, "e": 3491, "s": 3408, "text": "Run the Command Prompt (CMD) and reach the directory C:/hercules/mvs/cobol on CMD." }, { "code": null, "e": 3645, "s": 3491, "text": "The complete guide on various commands to write and execute a JCL and COBOL programs can be found at:\nwww.jaymoseley.com/hercules/installmvs/instmvs2.htm" }, { "code": null, "e": 3747, "s": 3645, "text": "The complete guide on various commands to write and execute a JCL and COBOL programs can be found at:" }, { "code": null, "e": 3799, "s": 3747, "text": "www.jaymoseley.com/hercules/installmvs/instmvs2.htm" }, { "code": null, "e": 4022, "s": 3799, "text": "Hercules is an open-source software implementation of the mainframe System/370 and ESA/390 architectures, in addition to the latest 64-bit z/Architecture. Hercules runs under Linux, Windows, Solaris, FreeBSD, and Mac OS X." }, { "code": null, "e": 4269, "s": 4022, "text": "A user can connect to a mainframe server in a number of ways such as thin client, dummy terminal, Virtual Client System (VCS), or Virtual Desktop System (VDS). Every valid user is given a login id to enter into the Z/OS interface (TSO/E or ISPF)." }, { "code": null, "e": 4609, "s": 4269, "text": "In order to execute a COBOL program in batch mode using JCL, the program needs to be compiled, and a load module is created with all the sub-programs. The JCL uses the load module and not the actual program at the time of execution. The load libraries are concatenated and given to the JCL at the time of execution using JCLLIB or STEPLIB." }, { "code": null, "e": 4874, "s": 4609, "text": "There are many mainframe compiler utilities available to compile a COBOL program. Some corporate companies use Change Management tools like Endevor, which compiles and stores every version of the program. This is useful in tracking the changes made to the program." }, { "code": null, "e": 5199, "s": 4874, "text": "//COMPILE JOB ,CLASS=6,MSGCLASS=X,NOTIFY=&SYSUID \n//* \n//STEP1 EXEC IGYCRCTL,PARM=RMODE,DYNAM,SSRANGE\n//SYSIN DD DSN=MYDATA.URMI.SOURCES(MYCOBB),DISP=SHR\n//SYSLIB DD DSN=MYDATA.URMI.COPYBOOK(MYCOPY),DISP=SHR\n//SYSLMOD DD DSN=MYDATA.URMI.LOAD(MYCOBB),DISP=SHR\n//SYSPRINT DD SYSOUT=*\n//*" }, { "code": null, "e": 5509, "s": 5199, "text": "IGYCRCTL is an IBM COBOL compiler utility. The compiler options are passed using the PARM parameter. In the above example, RMODE instructs the compiler to use relative addressing mode in the program. The COBOL program is passed using the SYSIN parameter. Copybook is the library used by the program in SYSLIB." }, { "code": null, "e": 5666, "s": 5509, "text": "Given below is a JCL example where the program MYPROG is executed using the input file MYDATA.URMI.INPUT and produces two output files written to the spool." }, { "code": null, "e": 5946, "s": 5666, "text": "//COBBSTEP JOB CLASS=6,NOTIFY=&SYSUID\n//\n//STEP10 EXEC PGM=MYPROG,PARM=ACCT5000\n//STEPLIB DD DSN=MYDATA.URMI.LOADLIB,DISP=SHR\n//INPUT1 DD DSN=MYDATA.URMI.INPUT,DISP=SHR\n//OUT1 DD SYSOUT=*\n//OUT2 DD SYSOUT=*\n//SYSIN DD *\n//CUST1 1000\n//CUST2 1001\n/*" }, { "code": null, "e": 6097, "s": 5946, "text": "The load module of MYPROG is located in MYDATA.URMI.LOADLIB. This is important to note that the above JCL can be used for a non-DB2 COBOL module only." }, { "code": null, "e": 6263, "s": 6097, "text": "For running a COBOL-DB2 program, a specialized IBM utility is used in the JCL and the program; DB2 region and required parameters are passed as input to the utility." }, { "code": null, "e": 6330, "s": 6263, "text": "The steps followed in running a COBOL-DB2 program are as follows −" }, { "code": null, "e": 6538, "s": 6330, "text": "When a COBOL-DB2 program is compiled, a DBRM (Database Request Module) is created along with the load module. The DBRM contains the SQL statements of the COBOL programs with its syntax checked to be correct." }, { "code": null, "e": 6746, "s": 6538, "text": "When a COBOL-DB2 program is compiled, a DBRM (Database Request Module) is created along with the load module. The DBRM contains the SQL statements of the COBOL programs with its syntax checked to be correct." }, { "code": null, "e": 6879, "s": 6746, "text": "The DBRM is bound to the DB2 region (environment) in which the COBOL will run. This can be done using the IKJEFT01 utility in a JCL." }, { "code": null, "e": 7012, "s": 6879, "text": "The DBRM is bound to the DB2 region (environment) in which the COBOL will run. This can be done using the IKJEFT01 utility in a JCL." }, { "code": null, "e": 7153, "s": 7012, "text": "After the bind step, the COBOL-DB2 program is run using IKJEFT01 (again) with the load library and the DBRM library as the input to the JCL." }, { "code": null, "e": 7294, "s": 7153, "text": "After the bind step, the COBOL-DB2 program is run using IKJEFT01 (again) with the load library and the DBRM library as the input to the JCL." }, { "code": null, "e": 7718, "s": 7294, "text": "//STEP001 EXEC PGM=IKJEFT01\n//*\n//STEPLIB DD DSN=MYDATA.URMI.DBRMLIB,DISP=SHR\n//*\n//input files\n//output files\n//SYSPRINT DD SYSOUT=*\n//SYSABOUT DD SYSOUT=*\n//SYSDBOUT DD SYSOUT=*\n//SYSUDUMP DD SYSOUT=*\n//DISPLAY DD SYSOUT=*\n//SYSOUT DD SYSOUT=*\n//SYSTSPRT DD SYSOUT=*\n//SYSTSIN DD *\n DSN SYSTEM(SSID)\n RUN PROGRAM(MYCOBB) PLAN(PLANNAME) PARM(parameters to cobol program) -\n LIB('MYDATA.URMI.LOADLIB')\n END\n/*" }, { "code": null, "e": 7961, "s": 7718, "text": "In the above example, MYCOBB is the COBOL-DB2 program run using IKJEFT01. Please note that the program name, DB2 Sub-System Id (SSID), and DB2 Plan name are passed within the SYSTSIN DD statement. The DBRM library is specified in the STEPLIB." }, { "code": null, "e": 7996, "s": 7961, "text": "\n 12 Lectures \n 2.5 hours \n" }, { "code": null, "e": 8011, "s": 7996, "text": " Nishant Malik" }, { "code": null, "e": 8046, "s": 8011, "text": "\n 33 Lectures \n 3.5 hours \n" }, { "code": null, "e": 8070, "s": 8046, "text": " Craig Kenneth Kaercher" }, { "code": null, "e": 8077, "s": 8070, "text": " Print" }, { "code": null, "e": 8088, "s": 8077, "text": " Add Notes" } ]
Python | Peak Signal-to-Noise Ratio (PSNR)
06 Feb, 2020 Peak signal-to-noise ratio (PSNR) is the ratio between the maximum possible power of an image and the power of corrupting noise that affects the quality of its representation. To estimate the PSNR of an image, it is necessary to compare that image to an ideal clean image with the maximum possible power. PSNR is defined as follows: Here, L is the number of maximum possible intensity levels (minimum intensity level suppose to be 0) in an image. MSE is the mean squared error & it is defined as: Where, O represents the matrix data of original image. D represents the matrix data of degraded image. m represents the numbers of rows of pixels and i represents the index of that row of the image. n represents the number of columns of pixels and j represents the index of that column of the image.RMSE is the root mean squared error. Here, we have an original image and it’s compressed version, let’s see the PSNR value for these images, Original Image :Compressed Image : Below is the Python implementation – from math import log10, sqrtimport cv2import numpy as np def PSNR(original, compressed): mse = np.mean((original - compressed) ** 2) if(mse == 0): # MSE is zero means no noise is present in the signal . # Therefore PSNR have no importance. return 100 max_pixel = 255.0 psnr = 20 * log10(max_pixel / sqrt(mse)) return psnr def main(): original = cv2.imread("original_image.png") compressed = cv2.imread("compressed_image.png", 1) value = PSNR(original, compressed) print(f"PSNR value is {value} dB") if __name__ == "__main__": main() Output: PSNR value is 43.862955653517126 dB PSNR is most commonly used to estimate the efficiency of compressors, filters, etc. The larger the value of PSNR, the more efficient is a corresponding compression or filter method. Image-Processing Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Python OOPs Concepts Introduction To PYTHON
[ { "code": null, "e": 52, "s": 24, "text": "\n06 Feb, 2020" }, { "code": null, "e": 357, "s": 52, "text": "Peak signal-to-noise ratio (PSNR) is the ratio between the maximum possible power of an image and the power of corrupting noise that affects the quality of its representation. To estimate the PSNR of an image, it is necessary to compare that image to an ideal clean image with the maximum possible power." }, { "code": null, "e": 386, "s": 357, "text": "PSNR is defined as follows: " }, { "code": null, "e": 506, "s": 391, "text": " Here, L is the number of maximum possible intensity levels (minimum intensity level suppose to be 0) in an image." }, { "code": null, "e": 557, "s": 506, "text": "MSE is the mean squared error & it is defined as: " }, { "code": null, "e": 901, "s": 565, "text": "Where, O represents the matrix data of original image. D represents the matrix data of degraded image. m represents the numbers of rows of pixels and i represents the index of that row of the image. n represents the number of columns of pixels and j represents the index of that column of the image.RMSE is the root mean squared error." }, { "code": null, "e": 1005, "s": 901, "text": "Here, we have an original image and it’s compressed version, let’s see the PSNR value for these images," }, { "code": null, "e": 1040, "s": 1005, "text": "Original Image :Compressed Image :" }, { "code": null, "e": 1077, "s": 1040, "text": "Below is the Python implementation –" }, { "code": "from math import log10, sqrtimport cv2import numpy as np def PSNR(original, compressed): mse = np.mean((original - compressed) ** 2) if(mse == 0): # MSE is zero means no noise is present in the signal . # Therefore PSNR have no importance. return 100 max_pixel = 255.0 psnr = 20 * log10(max_pixel / sqrt(mse)) return psnr def main(): original = cv2.imread(\"original_image.png\") compressed = cv2.imread(\"compressed_image.png\", 1) value = PSNR(original, compressed) print(f\"PSNR value is {value} dB\") if __name__ == \"__main__\": main()", "e": 1677, "s": 1077, "text": null }, { "code": null, "e": 1685, "s": 1677, "text": "Output:" }, { "code": null, "e": 1722, "s": 1685, "text": "PSNR value is 43.862955653517126 dB " }, { "code": null, "e": 1904, "s": 1722, "text": "PSNR is most commonly used to estimate the efficiency of compressors, filters, etc. The larger the value of PSNR, the more efficient is a corresponding compression or filter method." }, { "code": null, "e": 1921, "s": 1904, "text": "Image-Processing" }, { "code": null, "e": 1928, "s": 1921, "text": "Python" }, { "code": null, "e": 2026, "s": 1928, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2044, "s": 2026, "text": "Python Dictionary" }, { "code": null, "e": 2086, "s": 2044, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 2108, "s": 2086, "text": "Enumerate() in Python" }, { "code": null, "e": 2143, "s": 2108, "text": "Read a file line by line in Python" }, { "code": null, "e": 2169, "s": 2143, "text": "Python String | replace()" }, { "code": null, "e": 2201, "s": 2169, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2230, "s": 2201, "text": "*args and **kwargs in Python" }, { "code": null, "e": 2257, "s": 2230, "text": "Python Classes and Objects" }, { "code": null, "e": 2278, "s": 2257, "text": "Python OOPs Concepts" } ]
Libuv in Node.js
03 Sep, 2021 Node.js relies on various dependencies under the hood for providing various features. V8 libuv llhttp c-ares OpenSSL Libuv is one of them, let’s discuss libuv in detail. libuv: libuv is a C library originally written for Node.js to abstract non-blocking I/O operations. Event-driven asynchronous I/O model is integrated. It allows the CPU and other resources to be used simultaneously while still performing I/O operations, thereby resulting in efficient use of resources and network. It facilitates an event-driven approach wherein I/O and other activities are performed using callback-based notifications. Example: If a program is querying the database, the CPU sits idle until the query is processed and the program stays at a halt, thereby causing wastage of system resources. To prevent this, libuv is used in Node.js which facilitates a non-blocking I/O. It also has mechanisms to handle services like File System, DNS, network, child processes, pipes, signal handling, polling, and streaming.To perform blocking operations that can’t be done asynchronously at OS level, libuv also includes a thread pool to distribute CPU loads. What is a thread pool? Libuv assigns tasks to a pool of worker threads. However, all callbacks that occur on task completion are executed on the main thread. Note: After Node 10.5 worker threads can also be used to execute JavaScript in parallel. Libuv uses 4 threads by default, but can be changed using the UV_THREADPOOL_SIZE process.env.UV_THREADPOOL_SIZE = 5 Features of libuv: Full-featured event loop backed by epoll (Linux), kqueue (OSX), IOCP (Windows), event ports (SunOS). Asynchronous TCP (net module) and UDP (dgram module) Asynchronous DNS resolution (used partly for the dns module) Asynchronous file, file system operations & events (fs module) ANSI escape code controlled TTY Thread pool and Signal handling Child processes High-resolution clock Threading and synchronization primitives. Inter-Process Communication using sockets and Unix domain sockets (Windows) Event or I/O loop: Event or I/O loop uses a single threaded asynchronous I/O approach, hence it is tied to a single thread. In order to run multiple event loops, each of these event loops must be run on a different thread. It is not thread-safe by default with some exceptions. Libuv maintains an Event queue and event demultiplexer. The loop listens for incoming I/O and emits event for each request. The requests are then assigned to specific handler (OS dependent). After successful execution, registered callback is enqueued in event queue which are continuously executed one by one. Note: The current time required during entire process is cached by libuv at beginning of each iteration of loop to minimize frequent system calls. Example: If a network request is made, a callback is registered for that request, and the task is assigned to the handler. Until it is performed other operations carry on. On successful execution/termination, the registered callback is en-queued in the event queue which is then executed by the main thread after the execution of previous callbacks already present in the queue. It uses platform-specific mechanisms as mentioned earlier to achieve the best compatibility and performance epoll (Linux), kqueue (OSX), IOCP (Windows), event ports (SunOS). File I/O: File I/O is implemented in libuv using a global thread pool on which all loops can queue work. It allows disk to be used in an abstracted asynchronous fashion. It breaks down complex operations into simpler operations to facilitate async-like behavior. Example: If the program instructs to write a buffer to a specific file, in normal situations, the I/O will be blocked until the operation is successful/terminated. However, libuv abstracts this into an async manner by putting an event notification which would notify about operations success/failure after it is finished, until then the other I/O operations can be performed hassle-free. Note: Thread-safety is not assured by libuv (with few exceptions) Unlike event loop, File I/O uses platform-independent mechanisms. There are 3 kinds of async disk APIs that are handled by File I/O: linux AIO (supported in kernel)posix AIO (supported by linux, BSD, Mac OS X, solaris, AIX, etc)Windows’ overlapped I/O linux AIO (supported in kernel) posix AIO (supported by linux, BSD, Mac OS X, solaris, AIX, etc) Windows’ overlapped I/O Benefits: Disk operations are performed asynchronously. High level operations can be broken down to simpler disk operations which facilitate rectifying the information. Disk thread can use vector operations like readv & writev allowing more buffers to be passed. Reference: http://docs.libuv.org/en/v1.x/design.html didonatofr nandagunasekaran NodeJS-Questions Picked Technical Scripter 2020 Node.js Technical Scripter Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Installation of Node.js on Windows JWT Authentication with Node.js Difference between dependencies, devDependencies and peerDependencies Mongoose Populate() Method Mongoose find() Function Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ? Differences between Functional Components and Class Components in React
[ { "code": null, "e": 28, "s": 0, "text": "\n03 Sep, 2021" }, { "code": null, "e": 114, "s": 28, "text": "Node.js relies on various dependencies under the hood for providing various features." }, { "code": null, "e": 117, "s": 114, "text": "V8" }, { "code": null, "e": 123, "s": 117, "text": "libuv" }, { "code": null, "e": 130, "s": 123, "text": "llhttp" }, { "code": null, "e": 137, "s": 130, "text": "c-ares" }, { "code": null, "e": 145, "s": 137, "text": "OpenSSL" }, { "code": null, "e": 198, "s": 145, "text": "Libuv is one of them, let’s discuss libuv in detail." }, { "code": null, "e": 299, "s": 198, "text": "libuv: libuv is a C library originally written for Node.js to abstract non-blocking I/O operations. " }, { "code": null, "e": 350, "s": 299, "text": "Event-driven asynchronous I/O model is integrated." }, { "code": null, "e": 514, "s": 350, "text": "It allows the CPU and other resources to be used simultaneously while still performing I/O operations, thereby resulting in efficient use of resources and network." }, { "code": null, "e": 637, "s": 514, "text": "It facilitates an event-driven approach wherein I/O and other activities are performed using callback-based notifications." }, { "code": null, "e": 890, "s": 637, "text": "Example: If a program is querying the database, the CPU sits idle until the query is processed and the program stays at a halt, thereby causing wastage of system resources. To prevent this, libuv is used in Node.js which facilitates a non-blocking I/O." }, { "code": null, "e": 1166, "s": 890, "text": "It also has mechanisms to handle services like File System, DNS, network, child processes, pipes, signal handling, polling, and streaming.To perform blocking operations that can’t be done asynchronously at OS level, libuv also includes a thread pool to distribute CPU loads. " }, { "code": null, "e": 1191, "s": 1166, "text": "What is a thread pool? " }, { "code": null, "e": 1497, "s": 1191, "text": "Libuv assigns tasks to a pool of worker threads. However, all callbacks that occur on task completion are executed on the main thread. Note: After Node 10.5 worker threads can also be used to execute JavaScript in parallel. Libuv uses 4 threads by default, but can be changed using the UV_THREADPOOL_SIZE " }, { "code": null, "e": 1532, "s": 1497, "text": "process.env.UV_THREADPOOL_SIZE = 5" }, { "code": null, "e": 1552, "s": 1532, "text": "Features of libuv: " }, { "code": null, "e": 1653, "s": 1552, "text": "Full-featured event loop backed by epoll (Linux), kqueue (OSX), IOCP (Windows), event ports (SunOS)." }, { "code": null, "e": 1706, "s": 1653, "text": "Asynchronous TCP (net module) and UDP (dgram module)" }, { "code": null, "e": 1767, "s": 1706, "text": "Asynchronous DNS resolution (used partly for the dns module)" }, { "code": null, "e": 1830, "s": 1767, "text": "Asynchronous file, file system operations & events (fs module)" }, { "code": null, "e": 1862, "s": 1830, "text": "ANSI escape code controlled TTY" }, { "code": null, "e": 1894, "s": 1862, "text": "Thread pool and Signal handling" }, { "code": null, "e": 1910, "s": 1894, "text": "Child processes" }, { "code": null, "e": 1932, "s": 1910, "text": "High-resolution clock" }, { "code": null, "e": 1974, "s": 1932, "text": "Threading and synchronization primitives." }, { "code": null, "e": 2051, "s": 1974, "text": "Inter-Process Communication using sockets and Unix domain sockets (Windows) " }, { "code": null, "e": 2332, "s": 2053, "text": "Event or I/O loop: Event or I/O loop uses a single threaded asynchronous I/O approach, hence it is tied to a single thread. In order to run multiple event loops, each of these event loops must be run on a different thread. It is not thread-safe by default with some exceptions. " }, { "code": null, "e": 2789, "s": 2332, "text": "Libuv maintains an Event queue and event demultiplexer. The loop listens for incoming I/O and emits event for each request. The requests are then assigned to specific handler (OS dependent). After successful execution, registered callback is enqueued in event queue which are continuously executed one by one. Note: The current time required during entire process is cached by libuv at beginning of each iteration of loop to minimize frequent system calls." }, { "code": null, "e": 3168, "s": 2789, "text": "Example: If a network request is made, a callback is registered for that request, and the task is assigned to the handler. Until it is performed other operations carry on. On successful execution/termination, the registered callback is en-queued in the event queue which is then executed by the main thread after the execution of previous callbacks already present in the queue." }, { "code": null, "e": 3342, "s": 3168, "text": "It uses platform-specific mechanisms as mentioned earlier to achieve the best compatibility and performance epoll (Linux), kqueue (OSX), IOCP (Windows), event ports (SunOS)." }, { "code": null, "e": 3606, "s": 3342, "text": "File I/O: File I/O is implemented in libuv using a global thread pool on which all loops can queue work. It allows disk to be used in an abstracted asynchronous fashion. It breaks down complex operations into simpler operations to facilitate async-like behavior. " }, { "code": null, "e": 4060, "s": 3606, "text": "Example: If the program instructs to write a buffer to a specific file, in normal situations, the I/O will be blocked until the operation is successful/terminated. However, libuv abstracts this into an async manner by putting an event notification which would notify about operations success/failure after it is finished, until then the other I/O operations can be performed hassle-free. Note: Thread-safety is not assured by libuv (with few exceptions)" }, { "code": null, "e": 4193, "s": 4060, "text": "Unlike event loop, File I/O uses platform-independent mechanisms. There are 3 kinds of async disk APIs that are handled by File I/O:" }, { "code": null, "e": 4312, "s": 4193, "text": "linux AIO (supported in kernel)posix AIO (supported by linux, BSD, Mac OS X, solaris, AIX, etc)Windows’ overlapped I/O" }, { "code": null, "e": 4344, "s": 4312, "text": "linux AIO (supported in kernel)" }, { "code": null, "e": 4409, "s": 4344, "text": "posix AIO (supported by linux, BSD, Mac OS X, solaris, AIX, etc)" }, { "code": null, "e": 4433, "s": 4409, "text": "Windows’ overlapped I/O" }, { "code": null, "e": 4444, "s": 4433, "text": "Benefits: " }, { "code": null, "e": 4490, "s": 4444, "text": "Disk operations are performed asynchronously." }, { "code": null, "e": 4603, "s": 4490, "text": "High level operations can be broken down to simpler disk operations which facilitate rectifying the information." }, { "code": null, "e": 4697, "s": 4603, "text": "Disk thread can use vector operations like readv & writev allowing more buffers to be passed." }, { "code": null, "e": 4750, "s": 4697, "text": "Reference: http://docs.libuv.org/en/v1.x/design.html" }, { "code": null, "e": 4761, "s": 4750, "text": "didonatofr" }, { "code": null, "e": 4778, "s": 4761, "text": "nandagunasekaran" }, { "code": null, "e": 4795, "s": 4778, "text": "NodeJS-Questions" }, { "code": null, "e": 4802, "s": 4795, "text": "Picked" }, { "code": null, "e": 4826, "s": 4802, "text": "Technical Scripter 2020" }, { "code": null, "e": 4834, "s": 4826, "text": "Node.js" }, { "code": null, "e": 4853, "s": 4834, "text": "Technical Scripter" }, { "code": null, "e": 4870, "s": 4853, "text": "Web Technologies" }, { "code": null, "e": 4968, "s": 4870, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5003, "s": 4968, "text": "Installation of Node.js on Windows" }, { "code": null, "e": 5035, "s": 5003, "text": "JWT Authentication with Node.js" }, { "code": null, "e": 5105, "s": 5035, "text": "Difference between dependencies, devDependencies and peerDependencies" }, { "code": null, "e": 5132, "s": 5105, "text": "Mongoose Populate() Method" }, { "code": null, "e": 5157, "s": 5132, "text": "Mongoose find() Function" }, { "code": null, "e": 5219, "s": 5157, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 5280, "s": 5219, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 5330, "s": 5280, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 5373, "s": 5330, "text": "How to fetch data from an API in ReactJS ?" } ]
Python program to find Last date of Month
11 Jun, 2021 Given a datetime object, the task is to write a Python Program to compute the last date of datetime object Month. Examples: Input : test_date = datetime.datetime(2018, 6, 4) Output : 30 Explanation : April has 30 days, each year Input : test_date = datetime.datetime(2020, 2, 4) Output : 29 Explanation : February had 29 days in 2020, leap year. In this, extract the next month, and subtract the day of next month object extracted from the next month, resulting in 1 day before beginning of next month, i.e last date of current month. Python3 # Python3 code to demonstrate working of# Get Last date of Month# Using replace() + timedelta()import datetime # initializing datetest_date = datetime.datetime(2018, 6, 4) # printing original dateprint("The original date is : " + str(test_date)) # getting next month# using replace to get to last day + offset# to reach next monthnxt_mnth = test_date.replace(day=28) + datetime.timedelta(days=4) # subtracting the days from next month date to# get last date of current Monthres = nxt_mnth - datetime.timedelta(days=nxt_mnth.day) # printing resultprint("Last date of month : " + str(res.day)) Output: The original date is : 2018-06-04 00:00:00 Last date of month : 30 This uses an inbuilt function to solve this problem. In this, given year and month, the range can be computed using monthrange() and its second element can get the result required. Python3 # Python3 code to demonstrate working of# Get Last date of Month# Using calendar()from datetime import datetimeimport calendar # initializing datetest_date = datetime(2018, 6, 4) # printing original dateprint("The original date is : " + str(test_date)) # monthrange() gets the date range# required of monthres = calendar.monthrange(test_date.year, test_date.month)[1] # printing resultprint("Last date of month : " + str(res)) Output: The original date is : 2018-06-04 00:00:00 Last date of month : 30 sooda367 Python datetime-program Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n11 Jun, 2021" }, { "code": null, "e": 167, "s": 53, "text": "Given a datetime object, the task is to write a Python Program to compute the last date of datetime object Month." }, { "code": null, "e": 177, "s": 167, "text": "Examples:" }, { "code": null, "e": 227, "s": 177, "text": "Input : test_date = datetime.datetime(2018, 6, 4)" }, { "code": null, "e": 239, "s": 227, "text": "Output : 30" }, { "code": null, "e": 282, "s": 239, "text": "Explanation : April has 30 days, each year" }, { "code": null, "e": 332, "s": 282, "text": "Input : test_date = datetime.datetime(2020, 2, 4)" }, { "code": null, "e": 344, "s": 332, "text": "Output : 29" }, { "code": null, "e": 399, "s": 344, "text": "Explanation : February had 29 days in 2020, leap year." }, { "code": null, "e": 588, "s": 399, "text": "In this, extract the next month, and subtract the day of next month object extracted from the next month, resulting in 1 day before beginning of next month, i.e last date of current month." }, { "code": null, "e": 596, "s": 588, "text": "Python3" }, { "code": "# Python3 code to demonstrate working of# Get Last date of Month# Using replace() + timedelta()import datetime # initializing datetest_date = datetime.datetime(2018, 6, 4) # printing original dateprint(\"The original date is : \" + str(test_date)) # getting next month# using replace to get to last day + offset# to reach next monthnxt_mnth = test_date.replace(day=28) + datetime.timedelta(days=4) # subtracting the days from next month date to# get last date of current Monthres = nxt_mnth - datetime.timedelta(days=nxt_mnth.day) # printing resultprint(\"Last date of month : \" + str(res.day))", "e": 1201, "s": 596, "text": null }, { "code": null, "e": 1209, "s": 1201, "text": "Output:" }, { "code": null, "e": 1276, "s": 1209, "text": "The original date is : 2018-06-04 00:00:00\nLast date of month : 30" }, { "code": null, "e": 1457, "s": 1276, "text": "This uses an inbuilt function to solve this problem. In this, given year and month, the range can be computed using monthrange() and its second element can get the result required." }, { "code": null, "e": 1465, "s": 1457, "text": "Python3" }, { "code": "# Python3 code to demonstrate working of# Get Last date of Month# Using calendar()from datetime import datetimeimport calendar # initializing datetest_date = datetime(2018, 6, 4) # printing original dateprint(\"The original date is : \" + str(test_date)) # monthrange() gets the date range# required of monthres = calendar.monthrange(test_date.year, test_date.month)[1] # printing resultprint(\"Last date of month : \" + str(res))", "e": 1905, "s": 1465, "text": null }, { "code": null, "e": 1913, "s": 1905, "text": "Output:" }, { "code": null, "e": 1980, "s": 1913, "text": "The original date is : 2018-06-04 00:00:00\nLast date of month : 30" }, { "code": null, "e": 1989, "s": 1980, "text": "sooda367" }, { "code": null, "e": 2013, "s": 1989, "text": "Python datetime-program" }, { "code": null, "e": 2020, "s": 2013, "text": "Python" }, { "code": null, "e": 2036, "s": 2020, "text": "Python Programs" } ]
Python | Search Key from Value
11 Jun, 2021 The problem of finding a value from a given key is quite common. But we may have a problem in which we wish to get the back key from the input key we feed. Let’s discuss certain ways in which this problem can be solved. Method #1 : Using Naive Method In this method, we just run a loop for each of the values and return the corresponding key or keys whose value match. This is the brute force way to perform this particular task. Python3 # Python3 code to demonstrate working of# Search Key from Value# Using naive method # initializing dictionarytest_dict = {'Gfg' : 1, 'for' : 2, 'CS' : 3} # printing original dictionaryprint("The original dictionary is : " + str(test_dict)) # initializing valueval = 3 # Using naive method# Search key from Valuefor key in test_dict: if test_dict[key] == val: res = key # printing resultprint("The key corresponding to value : " + str(res)) The original dictionary is : {'Gfg': 1, 'for': 2, 'CS': 3} The key corresponding to value : CS Method #2 : Using items() + list comprehension This problem can be easily solved using the items(), which is used to extract both keys and values at once, hence making the search easy and can be executed using list comprehension making it a one liner. Python3 # Python3 code to demonstrate working of# Search Key from Value# Using items() + list comprehension # initializing dictionarytest_dict = {'Gfg' : 1, 'for' : 2, 'CS' : 3} # printing original dictionaryprint("The original dictionary is : " + str(test_dict)) # initializing valueval = 3 # Using items() + list comprehension# Search key from Valueres = [key for key, value in test_dict.items() if value == val] # printing resultprint("The key corresponding to value : " + str(res)) The original dictionary is : {'Gfg': 1, 'for': 2, 'CS': 3} The key corresponding to value : ['CS'] varshagumber28 Python dictionary-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON How to drop one or multiple columns in Pandas Dataframe Defaultdict in Python Python | Get dictionary keys as a list Python | Convert a list to dictionary Python | Convert string dictionary to dictionary Python Program for Fibonacci numbers
[ { "code": null, "e": 28, "s": 0, "text": "\n11 Jun, 2021" }, { "code": null, "e": 459, "s": 28, "text": "The problem of finding a value from a given key is quite common. But we may have a problem in which we wish to get the back key from the input key we feed. Let’s discuss certain ways in which this problem can be solved. Method #1 : Using Naive Method In this method, we just run a loop for each of the values and return the corresponding key or keys whose value match. This is the brute force way to perform this particular task. " }, { "code": null, "e": 467, "s": 459, "text": "Python3" }, { "code": "# Python3 code to demonstrate working of# Search Key from Value# Using naive method # initializing dictionarytest_dict = {'Gfg' : 1, 'for' : 2, 'CS' : 3} # printing original dictionaryprint(\"The original dictionary is : \" + str(test_dict)) # initializing valueval = 3 # Using naive method# Search key from Valuefor key in test_dict: if test_dict[key] == val: res = key # printing resultprint(\"The key corresponding to value : \" + str(res))", "e": 917, "s": 467, "text": null }, { "code": null, "e": 1013, "s": 917, "text": "The original dictionary is : {'Gfg': 1, 'for': 2, 'CS': 3}\nThe key corresponding to value : CS\n" }, { "code": null, "e": 1267, "s": 1013, "text": " Method #2 : Using items() + list comprehension This problem can be easily solved using the items(), which is used to extract both keys and values at once, hence making the search easy and can be executed using list comprehension making it a one liner. " }, { "code": null, "e": 1275, "s": 1267, "text": "Python3" }, { "code": "# Python3 code to demonstrate working of# Search Key from Value# Using items() + list comprehension # initializing dictionarytest_dict = {'Gfg' : 1, 'for' : 2, 'CS' : 3} # printing original dictionaryprint(\"The original dictionary is : \" + str(test_dict)) # initializing valueval = 3 # Using items() + list comprehension# Search key from Valueres = [key for key, value in test_dict.items() if value == val] # printing resultprint(\"The key corresponding to value : \" + str(res))", "e": 1753, "s": 1275, "text": null }, { "code": null, "e": 1853, "s": 1753, "text": "The original dictionary is : {'Gfg': 1, 'for': 2, 'CS': 3}\nThe key corresponding to value : ['CS']\n" }, { "code": null, "e": 1868, "s": 1853, "text": "varshagumber28" }, { "code": null, "e": 1895, "s": 1868, "text": "Python dictionary-programs" }, { "code": null, "e": 1902, "s": 1895, "text": "Python" }, { "code": null, "e": 1918, "s": 1902, "text": "Python Programs" }, { "code": null, "e": 2016, "s": 1918, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2048, "s": 2016, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2075, "s": 2048, "text": "Python Classes and Objects" }, { "code": null, "e": 2096, "s": 2075, "text": "Python OOPs Concepts" }, { "code": null, "e": 2119, "s": 2096, "text": "Introduction To PYTHON" }, { "code": null, "e": 2175, "s": 2119, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 2197, "s": 2175, "text": "Defaultdict in Python" }, { "code": null, "e": 2236, "s": 2197, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 2274, "s": 2236, "text": "Python | Convert a list to dictionary" }, { "code": null, "e": 2323, "s": 2274, "text": "Python | Convert string dictionary to dictionary" } ]
How to Create Your Own Custom View in Android with Kotlin?
05 May, 2021 In this article, we’re going to talk about how we can create our own custom view in Android step by step. We all know that in the beginning android platform provides us some basic views for example – TextView, ImageView, EditText, Button, ImageButton, RadioButton, etc. But, sometimes we need a whole new type of view where our prebuilt layouts and widgets fail to meet our needs. So, let’s get dive into it. First, the concept of Custom View in Android is nothing but having our own customized view model other than the prebuilt ones. And how do we achieve that? By simply bringing together different types of prebuilt views and then use the combined one as a single view. We all know that in the beginning android platform provides us some basic views for example – TextView, ImageView, EditText, Button, ImageButton, RadioButton, etc. But, sometimes we need a more interactive and complex type of view where our prebuilt layouts and widgets fail to meet our needs. There the custom views come into the picture. Now the custom views in Android are fully customized by the developers in order to achieve the goal. Although custom views aren’t needed everywhere. But, at a higher development level where complexity is more, we need them. Whenever we’re going to create a custom view for our apps, we need some items under consideration. Introduce yourself to the lifecycle of a view in Android. Now, 3 basic methods are to be taken under importance. onMeasure()onLayout()onDraw() onMeasure() onLayout() onDraw() These 3 methods will be overridden in the corresponding Java/Kotlin class. As suggested by the method name it is used for measurement purposes. Basically, we can control the width and height of our custom view. If not overridden: The size of the view will be either ‘match_parent’ or ‘wrap_content’. If overridden: On overriding this method we have more control of size over the custom view. Do not call the method ‘super.onMeasure()’. Instead, we’ll be calling the method ‘setMeasuredDimension(width, height)’. Overriding onMeasure(): When this method is called we get ‘widthMeasureSpec’ & ‘heightMeasureSpec’ as parameters. A size mode is a constraint that is set by the parent for its child’s views. Available 3 types of modes are listed below. UNSPECIFIED: No constraints are given, so it can be of whatever size it wants. EXACTLY: Exact size is determined for the child views. AT_MOST: Child can be as large as it wants up to the specified size. Example: Kotlin override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { // requested width and mode val reqWidth = MeasureSpec.getSize(widthMeasureSpec) val reqWidthMode = MeasureSpec.getMode(widthMeasureSpec) // requested height and mode val reqHeight = MeasureSpec.getSize(heightMeasureSpec) val reqHeightMode = MeasureSpec.getMode(heightMeasureSpec) // your choice val desiredWidth: Int = // TODO("Define your desired width") val desiredHeight: Int = // TODO("Define your desired height") val width = when (requestedWidthMode) { MeasureSpec.EXACTLY -> reqWidth MeasureSpec.UNSPECIFIED -> desiredWidth else -> Math.min(reqWidth, desiredWidth) // AT_MOST condition } val height = when (requestedHeightMode) { MeasureSpec.EXACTLY -> reqHeight MeasureSpec.UNSPECIFIED -> desiredHeight else -> Math.min(reqHeight, desiredHeight) // AT_MOST condition } // set the width and the height of the view setMeasuredDimension(width, height)} This method is used by the parent view to notify our custom view about its position. One should use it to calculate their drawing width and height. Point to remember whatever happens in onMeasure() affects the positions, got from the parent. This is recommended one should always calculate the drawing size here before proceeding to draw the view. All the drawing happens within this part. It’s not hard at all as you get an instance of Canvas object and you are free to draw whatever you want. Overriding onDraw() : First for simplicity get the width and height of the canvas object with ‘getWidth()’ & ‘getHeight()’ methods. Example: Kotlin protected fun onDraw(canvas:Canvas) { // Grab canvas dimensions. val canvasWidth = canvas.getWidth() val canvasHeight = canvas.getHeight() // Calculate horizontal center. val centerX = canvasWidth * 0.5f // Draw the background. backgroundRect.set(0f, 0f, canvasWidth, canvasHeight) canvas.drawRoundRect(backgroundRect, cornerRadius, cornerRadius, backgroundPaint) // Draw baseline. val baselineY = Math.round(canvasHeight * 0.6f).toFloat() canvas.drawLine(0, baselineY, canvasWidth, baselineY, linePaint) // Draw text. // Measure the width of text to display. val textWidth = numberPaint.measureText(displayedCount) // Figure out an x-coordinate that will center the text in the canvas. val textX = Math.round(centerX - textWidth * 0.5f).toFloat() // Draw. canvas.drawText(displayedCount, textX, baselineY, numberPaint)} Android-View Kotlin Android Picked Android Kotlin Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Add Views Dynamically and Store Data in Arraylist in Android? Android SDK and it's Components Flutter - Custom Bottom Navigation Bar How to Communicate Between Fragments in Android? Retrofit with Kotlin Coroutine in Android How to Add Views Dynamically and Store Data in Arraylist in Android? Android UI Layouts Kotlin Array How to Communicate Between Fragments in Android? Retrofit with Kotlin Coroutine in Android
[ { "code": null, "e": 28, "s": 0, "text": "\n05 May, 2021" }, { "code": null, "e": 437, "s": 28, "text": "In this article, we’re going to talk about how we can create our own custom view in Android step by step. We all know that in the beginning android platform provides us some basic views for example – TextView, ImageView, EditText, Button, ImageButton, RadioButton, etc. But, sometimes we need a whole new type of view where our prebuilt layouts and widgets fail to meet our needs. So, let’s get dive into it." }, { "code": null, "e": 702, "s": 437, "text": "First, the concept of Custom View in Android is nothing but having our own customized view model other than the prebuilt ones. And how do we achieve that? By simply bringing together different types of prebuilt views and then use the combined one as a single view." }, { "code": null, "e": 1266, "s": 702, "text": "We all know that in the beginning android platform provides us some basic views for example – TextView, ImageView, EditText, Button, ImageButton, RadioButton, etc. But, sometimes we need a more interactive and complex type of view where our prebuilt layouts and widgets fail to meet our needs. There the custom views come into the picture. Now the custom views in Android are fully customized by the developers in order to achieve the goal. Although custom views aren’t needed everywhere. But, at a higher development level where complexity is more, we need them." }, { "code": null, "e": 1423, "s": 1266, "text": "Whenever we’re going to create a custom view for our apps, we need some items under consideration. Introduce yourself to the lifecycle of a view in Android." }, { "code": null, "e": 1478, "s": 1423, "text": "Now, 3 basic methods are to be taken under importance." }, { "code": null, "e": 1508, "s": 1478, "text": "onMeasure()onLayout()onDraw()" }, { "code": null, "e": 1520, "s": 1508, "text": "onMeasure()" }, { "code": null, "e": 1531, "s": 1520, "text": "onLayout()" }, { "code": null, "e": 1540, "s": 1531, "text": "onDraw()" }, { "code": null, "e": 1616, "s": 1540, "text": "These 3 methods will be overridden in the corresponding Java/Kotlin class. " }, { "code": null, "e": 1752, "s": 1616, "text": "As suggested by the method name it is used for measurement purposes. Basically, we can control the width and height of our custom view." }, { "code": null, "e": 1841, "s": 1752, "text": "If not overridden: The size of the view will be either ‘match_parent’ or ‘wrap_content’." }, { "code": null, "e": 2053, "s": 1841, "text": "If overridden: On overriding this method we have more control of size over the custom view. Do not call the method ‘super.onMeasure()’. Instead, we’ll be calling the method ‘setMeasuredDimension(width, height)’." }, { "code": null, "e": 2077, "s": 2053, "text": "Overriding onMeasure():" }, { "code": null, "e": 2289, "s": 2077, "text": "When this method is called we get ‘widthMeasureSpec’ & ‘heightMeasureSpec’ as parameters. A size mode is a constraint that is set by the parent for its child’s views. Available 3 types of modes are listed below." }, { "code": null, "e": 2368, "s": 2289, "text": "UNSPECIFIED: No constraints are given, so it can be of whatever size it wants." }, { "code": null, "e": 2423, "s": 2368, "text": "EXACTLY: Exact size is determined for the child views." }, { "code": null, "e": 2492, "s": 2423, "text": "AT_MOST: Child can be as large as it wants up to the specified size." }, { "code": null, "e": 2501, "s": 2492, "text": "Example:" }, { "code": null, "e": 2508, "s": 2501, "text": "Kotlin" }, { "code": "override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { // requested width and mode val reqWidth = MeasureSpec.getSize(widthMeasureSpec) val reqWidthMode = MeasureSpec.getMode(widthMeasureSpec) // requested height and mode val reqHeight = MeasureSpec.getSize(heightMeasureSpec) val reqHeightMode = MeasureSpec.getMode(heightMeasureSpec) // your choice val desiredWidth: Int = // TODO(\"Define your desired width\") val desiredHeight: Int = // TODO(\"Define your desired height\") val width = when (requestedWidthMode) { MeasureSpec.EXACTLY -> reqWidth MeasureSpec.UNSPECIFIED -> desiredWidth else -> Math.min(reqWidth, desiredWidth) // AT_MOST condition } val height = when (requestedHeightMode) { MeasureSpec.EXACTLY -> reqHeight MeasureSpec.UNSPECIFIED -> desiredHeight else -> Math.min(reqHeight, desiredHeight) // AT_MOST condition } // set the width and the height of the view setMeasuredDimension(width, height)}", "e": 3625, "s": 2508, "text": null }, { "code": null, "e": 3974, "s": 3625, "text": "This method is used by the parent view to notify our custom view about its position. One should use it to calculate their drawing width and height. Point to remember whatever happens in onMeasure() affects the positions, got from the parent. This is recommended one should always calculate the drawing size here before proceeding to draw the view. " }, { "code": null, "e": 4121, "s": 3974, "text": "All the drawing happens within this part. It’s not hard at all as you get an instance of Canvas object and you are free to draw whatever you want." }, { "code": null, "e": 4143, "s": 4121, "text": "Overriding onDraw() :" }, { "code": null, "e": 4255, "s": 4143, "text": "First for simplicity get the width and height of the canvas object with ‘getWidth()’ & ‘getHeight()’ methods. " }, { "code": null, "e": 4264, "s": 4255, "text": "Example:" }, { "code": null, "e": 4271, "s": 4264, "text": "Kotlin" }, { "code": "protected fun onDraw(canvas:Canvas) { // Grab canvas dimensions. val canvasWidth = canvas.getWidth() val canvasHeight = canvas.getHeight() // Calculate horizontal center. val centerX = canvasWidth * 0.5f // Draw the background. backgroundRect.set(0f, 0f, canvasWidth, canvasHeight) canvas.drawRoundRect(backgroundRect, cornerRadius, cornerRadius, backgroundPaint) // Draw baseline. val baselineY = Math.round(canvasHeight * 0.6f).toFloat() canvas.drawLine(0, baselineY, canvasWidth, baselineY, linePaint) // Draw text. // Measure the width of text to display. val textWidth = numberPaint.measureText(displayedCount) // Figure out an x-coordinate that will center the text in the canvas. val textX = Math.round(centerX - textWidth * 0.5f).toFloat() // Draw. canvas.drawText(displayedCount, textX, baselineY, numberPaint)}", "e": 5112, "s": 4271, "text": null }, { "code": null, "e": 5125, "s": 5112, "text": "Android-View" }, { "code": null, "e": 5140, "s": 5125, "text": "Kotlin Android" }, { "code": null, "e": 5147, "s": 5140, "text": "Picked" }, { "code": null, "e": 5155, "s": 5147, "text": "Android" }, { "code": null, "e": 5162, "s": 5155, "text": "Kotlin" }, { "code": null, "e": 5170, "s": 5162, "text": "Android" }, { "code": null, "e": 5268, "s": 5170, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5337, "s": 5268, "text": "How to Add Views Dynamically and Store Data in Arraylist in Android?" }, { "code": null, "e": 5369, "s": 5337, "text": "Android SDK and it's Components" }, { "code": null, "e": 5408, "s": 5369, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 5457, "s": 5408, "text": "How to Communicate Between Fragments in Android?" }, { "code": null, "e": 5499, "s": 5457, "text": "Retrofit with Kotlin Coroutine in Android" }, { "code": null, "e": 5568, "s": 5499, "text": "How to Add Views Dynamically and Store Data in Arraylist in Android?" }, { "code": null, "e": 5587, "s": 5568, "text": "Android UI Layouts" }, { "code": null, "e": 5600, "s": 5587, "text": "Kotlin Array" }, { "code": null, "e": 5649, "s": 5600, "text": "How to Communicate Between Fragments in Android?" } ]
Java Program for Identity Matrix
13 Jan, 2022 Introduction to Identity Matrix : The dictionary definition of an Identity Matrix is a square matrix in which all the elements of the principal or main diagonal are 1’s and all other elements are zeros. In the below image, every matrix is an Identity Matrix. In linear algebra, this is sometimes called as a Unit Matrix, of a square matrix (size = n x n) with ones on the main diagonal and zeros elsewhere. The identity matrix is denoted by “ I “. Sometimes U or E is also used to denote an Identity Matrix. A property of the identity matrix is that it leaves a matrix unchanged if it is multiplied by an Identity Matrix. Examples: Input : 2 Output : 1 0 0 1 Input : 4 Output : 1 0 0 0 0 1 0 0 0 0 1 0 0 0 0 1 The explanation is simple. We need to make all the elements of principal or main diagonal as 1 and everything else as 0. Program to print Identity Matrix : The logic is simple. You need to the print 1 in those positions where row is equal to column of a matrix and make all other positions as 0. Java // Java program to print Identity Matrixclass GFG { static int identity(int num) { int row, col; for (row = 0; row < num; row++) { for (col = 0; col < num; col++) { // Checking if row is equal to column if (row == col) System.out.print( 1+" "); else System.out.print( 0+" "); } System.out.println(); } return 0; } // Driver Code public static void main(String args[]) { int size = 5; identity(size); }} /*This code is contributed by Nikita tiwari.*/ Output: 1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 1 Program to check if a given square matrix is Identity Matrix : Java // Java program to check if a given // matrix is identityclass GFG { int MAX = 100; static boolean isIdentity(int mat[][], int N) { for (int row = 0; row < N; row++) { for (int col = 0; col < N; col++) { if (row == col && mat[row][col] != 1) return false; else if (row != col && mat[row][col] != 0) return false; } } return true; } // Driver Code public static void main(String args[]) { int N = 4; int mat[][] = {{1, 0, 0, 0}, {0, 1, 0, 0}, {0, 0, 1, 0}, {0, 0, 0, 1}}; if (isIdentity(mat, N)) System.out.println("Yes "); else System.out.println("No "); }} /*This code is contributed by Nikita Tiwari.*/ Output: Yes Java Java Programs Mathematical Matrix School Programming Mathematical Matrix Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Introduction to Java Constructors in Java Exceptions in Java Generics in Java Java Programming Examples Convert Double to Integer in Java Implementing a Linked List in Java using Class Factory method design pattern in Java Java Program to Remove Duplicate Elements From the Array
[ { "code": null, "e": 28, "s": 0, "text": "\n13 Jan, 2022" }, { "code": null, "e": 62, "s": 28, "text": "Introduction to Identity Matrix :" }, { "code": null, "e": 290, "s": 62, "text": " The dictionary definition of an Identity Matrix is a square matrix in which all the elements of the principal or main diagonal are 1’s and all other elements are zeros. In the below image, every matrix is an Identity Matrix. " }, { "code": null, "e": 653, "s": 290, "text": "In linear algebra, this is sometimes called as a Unit Matrix, of a square matrix (size = n x n) with ones on the main diagonal and zeros elsewhere. The identity matrix is denoted by “ I “. Sometimes U or E is also used to denote an Identity Matrix. A property of the identity matrix is that it leaves a matrix unchanged if it is multiplied by an Identity Matrix." }, { "code": null, "e": 665, "s": 653, "text": "Examples: " }, { "code": null, "e": 904, "s": 665, "text": "Input : 2\nOutput : 1 0\n 0 1\n\nInput : 4\nOutput : 1 0 0 0\n 0 1 0 0\n 0 0 1 0\n 0 0 0 1\nThe explanation is simple. We need to make all\nthe elements of principal or main diagonal as \n1 and everything else as 0." }, { "code": null, "e": 1080, "s": 904, "text": "Program to print Identity Matrix : The logic is simple. You need to the print 1 in those positions where row is equal to column of a matrix and make all other positions as 0. " }, { "code": null, "e": 1085, "s": 1080, "text": "Java" }, { "code": "// Java program to print Identity Matrixclass GFG { static int identity(int num) { int row, col; for (row = 0; row < num; row++) { for (col = 0; col < num; col++) { // Checking if row is equal to column if (row == col) System.out.print( 1+\" \"); else System.out.print( 0+\" \"); } System.out.println(); } return 0; } // Driver Code public static void main(String args[]) { int size = 5; identity(size); }} /*This code is contributed by Nikita tiwari.*/", "e": 1759, "s": 1085, "text": null }, { "code": null, "e": 1768, "s": 1759, "text": "Output: " }, { "code": null, "e": 1848, "s": 1768, "text": "1 0 0 0 0 \n0 1 0 0 0 \n0 0 1 0 0 \n0 0 0 1 0 \n0 0 0 0 1 " }, { "code": null, "e": 1913, "s": 1848, "text": " Program to check if a given square matrix is Identity Matrix : " }, { "code": null, "e": 1918, "s": 1913, "text": "Java" }, { "code": "// Java program to check if a given // matrix is identityclass GFG { int MAX = 100; static boolean isIdentity(int mat[][], int N) { for (int row = 0; row < N; row++) { for (int col = 0; col < N; col++) { if (row == col && mat[row][col] != 1) return false; else if (row != col && mat[row][col] != 0) return false; } } return true; } // Driver Code public static void main(String args[]) { int N = 4; int mat[][] = {{1, 0, 0, 0}, {0, 1, 0, 0}, {0, 0, 1, 0}, {0, 0, 0, 1}}; if (isIdentity(mat, N)) System.out.println(\"Yes \"); else System.out.println(\"No \"); }} /*This code is contributed by Nikita Tiwari.*/", "e": 2822, "s": 1918, "text": null }, { "code": null, "e": 2830, "s": 2822, "text": "Output:" }, { "code": null, "e": 2834, "s": 2830, "text": "Yes" }, { "code": null, "e": 2841, "s": 2836, "text": "Java" }, { "code": null, "e": 2855, "s": 2841, "text": "Java Programs" }, { "code": null, "e": 2868, "s": 2855, "text": "Mathematical" }, { "code": null, "e": 2875, "s": 2868, "text": "Matrix" }, { "code": null, "e": 2894, "s": 2875, "text": "School Programming" }, { "code": null, "e": 2907, "s": 2894, "text": "Mathematical" }, { "code": null, "e": 2914, "s": 2907, "text": "Matrix" }, { "code": null, "e": 2919, "s": 2914, "text": "Java" }, { "code": null, "e": 3017, "s": 2919, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3032, "s": 3017, "text": "Stream In Java" }, { "code": null, "e": 3053, "s": 3032, "text": "Introduction to Java" }, { "code": null, "e": 3074, "s": 3053, "text": "Constructors in Java" }, { "code": null, "e": 3093, "s": 3074, "text": "Exceptions in Java" }, { "code": null, "e": 3110, "s": 3093, "text": "Generics in Java" }, { "code": null, "e": 3136, "s": 3110, "text": "Java Programming Examples" }, { "code": null, "e": 3170, "s": 3136, "text": "Convert Double to Integer in Java" }, { "code": null, "e": 3217, "s": 3170, "text": "Implementing a Linked List in Java using Class" }, { "code": null, "e": 3255, "s": 3217, "text": "Factory method design pattern in Java" } ]
Smart Pointers in C++ and How to Use Them
01 Dec, 2021 In this article, we will be discussing smart pointers in C++. What are Smart Pointers, why, and how to use them properly? Pointers are used for accessing the resources which are external to the program – like heap memory. So, for accessing the heap memory (if anything is created inside heap memory), pointers are used. When accessing any external resource we just use a copy of the resource. If we make any change to it, we just change it in the copied version. But, if we use a pointer to the resource, we’ll be able to change the original resource. Take a look at the code below. C++ #include <iostream>using namespace std; class Rectangle {private: int length; int breadth;}; void fun(){ // By taking a pointer p and // dynamically creating object // of class rectangle Rectangle* p = new Rectangle();} int main(){ // Infinite Loop while (1) { fun(); }} In function fun, it creates a pointer that is pointing to the Rectangle object. The object Rectangle contains two integers, length and breadth. When the function fun ends, p will be destroyed as it is a local variable. But, the memory it consumed won’t be deallocated because we forgot to use delete p; at the end of the function. That means the memory won’t be free to be used by other resources. But, we don’t need the variable anymore, but we need the memory. In function main, fun is called in an infinite loop. That means it’ll keep creating p. It’ll allocate more and more memory but won’t free them as we didn’t deallocate it. The memory that’s wasted can’t be used again. Which is a memory leak. The entire heap memory may become useless for this reason. C++11 comes up with a solution to this problem, Smart Pointer. As we’ve known unconsciously not deallocating a pointer causes a memory leak that may lead to crash of the program. Languages Java, C# has Garbage Collection Mechanisms to smartly deallocate unused memory to be used again. The programmer doesn’t have to worry about any memory leak. C++11 comes up with its own mechanism that’s Smart Pointer. When the object is destroyed it frees the memory as well. So, we don’t need to delete it as Smart Pointer does will handle it. A Smart Pointer is a wrapper class over a pointer with an operator like * and -> overloaded. The objects of the smart pointer class look like normal pointers. But, unlike Normal Pointers it can deallocate and free destroyed object memory. The idea is to take a class with a pointer, destructor and overloaded operators like * and ->. Since the destructor is automatically called when an object goes out of scope, the dynamically allocated memory would automatically be deleted (or reference count can be decremented). Consider the following simple SmartPtr class. C++ #include <iostream>using namespace std; class SmartPtr { int* ptr; // Actual pointerpublic: // Constructor: Refer https:// www.geeksforgeeks.org/g-fact-93/ // for use of explicit keyword explicit SmartPtr(int* p = NULL) { ptr = p; } // Destructor ~SmartPtr() { delete (ptr); } // Overloading dereferencing operator int& operator*() { return *ptr; }}; int main(){ SmartPtr ptr(new int()); *ptr = 20; cout << *ptr; // We don't need to call delete ptr: when the object // ptr goes out of scope, the destructor for it is automatically // called and destructor does delete ptr. return 0;} 20 This only works for int. So, we’ll have to create Smart Pointer for every object? No, there’s a solution, Template. In the code below as you can see T can be of any type. Read more about Template here. C++ #include <iostream>using namespace std; // A generic smart pointer classtemplate <class T>class SmartPtr { T* ptr; // Actual pointerpublic: // Constructor explicit SmartPtr(T* p = NULL) { ptr = p; } // Destructor ~SmartPtr() { delete (ptr); } // Overloading dereferencing operator T& operator*() { return *ptr; } // Overloading arrow operator so that // members of T can be accessed // like a pointer (useful if T represents // a class or struct or union type) T* operator->() { return ptr; }}; int main(){ SmartPtr<int> ptr(new int()); *ptr = 20; cout << *ptr; return 0;} 20 Note: Smart pointers are also useful in the management of resources, such as file handles or network sockets. unique_ptr stores one pointer only. We can assign a different object by removing the current object from the pointer. Notice the code below. First, the unique_pointer is pointing to P1. But, then we remove P1 and assign P2 so the pointer now points to P2. C++14 #include <iostream>using namespace std;#include <memory> class Rectangle { int length; int breadth; public: Rectangle(int l, int b){ length = l; breadth = b; } int area(){ return length * breadth; }}; int main(){ unique_ptr<Rectangle> P1(new Rectangle(10, 5)); cout << P1->area() << endl; // This'll print 50 // unique_ptr<Rectangle> P2(P1); unique_ptr<Rectangle> P2; P2 = move(P1); // This'll print 50 cout << P2->area() << endl; // cout<<P1->area()<<endl; return 0;} 50 50 By using shared_ptr more than one pointer can point to this one object at a time and it’ll maintain a Reference Counter using use_count() method. C++14 #include <iostream>using namespace std;#include <memory> class Rectangle { int length; int breadth; public: Rectangle(int l, int b) { length = l; breadth = b; } int area() { return length * breadth; }}; int main(){ shared_ptr<Rectangle> P1(new Rectangle(10, 5)); // This'll print 50 cout << P1->area() << endl; shared_ptr<Rectangle> P2; P2 = P1; // This'll print 50 cout << P2->area() << endl; // This'll now not give an error, cout << P1->area() << endl; // This'll also print 50 now // This'll print 2 as Reference Counter is 2 cout << P1.use_count() << endl; return 0;} 50 50 50 2 It’s much more similar to shared_ptr except it’ll not maintain a Reference Counter. In this case, a pointer will not have a stronghold on the object. The reason is if suppose pointers are holding the object and requesting for other objects then they may form a Deadlock. C++ libraries provide implementations of smart pointers in the form of auto_ptr, unique_ptr, shared_ptr and weak_ptr References: http://en.wikipedia.org/wiki/Smart_pointer This article is improved by AmiyaRanjanRout. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. It had been improved again by AAShakil50. BabisSarantoglou AmiyaRanjanRout shrutipriyain bogdanpescarus94 aashakil50 surindertarika1234 cpp-pointer C Language C++ CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. std::sort() in C++ STL Bitwise Operators in C/C++ Substring in C++ Dynamic Memory Allocation in C using malloc(), calloc(), free() and realloc() Function Pointer in C Vector in C++ STL Initialize a vector in C++ (7 different ways) std::sort() in C++ STL Bitwise Operators in C/C++ unordered_map in C++ STL
[ { "code": null, "e": 54, "s": 26, "text": "\n01 Dec, 2021" }, { "code": null, "e": 176, "s": 54, "text": "In this article, we will be discussing smart pointers in C++. What are Smart Pointers, why, and how to use them properly?" }, { "code": null, "e": 606, "s": 176, "text": "Pointers are used for accessing the resources which are external to the program – like heap memory. So, for accessing the heap memory (if anything is created inside heap memory), pointers are used. When accessing any external resource we just use a copy of the resource. If we make any change to it, we just change it in the copied version. But, if we use a pointer to the resource, we’ll be able to change the original resource." }, { "code": null, "e": 637, "s": 606, "text": "Take a look at the code below." }, { "code": null, "e": 641, "s": 637, "text": "C++" }, { "code": "#include <iostream>using namespace std; class Rectangle {private: int length; int breadth;}; void fun(){ // By taking a pointer p and // dynamically creating object // of class rectangle Rectangle* p = new Rectangle();} int main(){ // Infinite Loop while (1) { fun(); }}", "e": 946, "s": 641, "text": null }, { "code": null, "e": 1409, "s": 946, "text": "In function fun, it creates a pointer that is pointing to the Rectangle object. The object Rectangle contains two integers, length and breadth. When the function fun ends, p will be destroyed as it is a local variable. But, the memory it consumed won’t be deallocated because we forgot to use delete p; at the end of the function. That means the memory won’t be free to be used by other resources. But, we don’t need the variable anymore, but we need the memory." }, { "code": null, "e": 1772, "s": 1409, "text": "In function main, fun is called in an infinite loop. That means it’ll keep creating p. It’ll allocate more and more memory but won’t free them as we didn’t deallocate it. The memory that’s wasted can’t be used again. Which is a memory leak. The entire heap memory may become useless for this reason. C++11 comes up with a solution to this problem, Smart Pointer." }, { "code": null, "e": 2242, "s": 1772, "text": "As we’ve known unconsciously not deallocating a pointer causes a memory leak that may lead to crash of the program. Languages Java, C# has Garbage Collection Mechanisms to smartly deallocate unused memory to be used again. The programmer doesn’t have to worry about any memory leak. C++11 comes up with its own mechanism that’s Smart Pointer. When the object is destroyed it frees the memory as well. So, we don’t need to delete it as Smart Pointer does will handle it." }, { "code": null, "e": 2481, "s": 2242, "text": "A Smart Pointer is a wrapper class over a pointer with an operator like * and -> overloaded. The objects of the smart pointer class look like normal pointers. But, unlike Normal Pointers it can deallocate and free destroyed object memory." }, { "code": null, "e": 2806, "s": 2481, "text": "The idea is to take a class with a pointer, destructor and overloaded operators like * and ->. Since the destructor is automatically called when an object goes out of scope, the dynamically allocated memory would automatically be deleted (or reference count can be decremented). Consider the following simple SmartPtr class." }, { "code": null, "e": 2810, "s": 2806, "text": "C++" }, { "code": "#include <iostream>using namespace std; class SmartPtr { int* ptr; // Actual pointerpublic: // Constructor: Refer https:// www.geeksforgeeks.org/g-fact-93/ // for use of explicit keyword explicit SmartPtr(int* p = NULL) { ptr = p; } // Destructor ~SmartPtr() { delete (ptr); } // Overloading dereferencing operator int& operator*() { return *ptr; }}; int main(){ SmartPtr ptr(new int()); *ptr = 20; cout << *ptr; // We don't need to call delete ptr: when the object // ptr goes out of scope, the destructor for it is automatically // called and destructor does delete ptr. return 0;}", "e": 3443, "s": 2810, "text": null }, { "code": null, "e": 3446, "s": 3443, "text": "20" }, { "code": null, "e": 3650, "s": 3448, "text": "This only works for int. So, we’ll have to create Smart Pointer for every object? No, there’s a solution, Template. In the code below as you can see T can be of any type. Read more about Template here." }, { "code": null, "e": 3654, "s": 3650, "text": "C++" }, { "code": "#include <iostream>using namespace std; // A generic smart pointer classtemplate <class T>class SmartPtr { T* ptr; // Actual pointerpublic: // Constructor explicit SmartPtr(T* p = NULL) { ptr = p; } // Destructor ~SmartPtr() { delete (ptr); } // Overloading dereferencing operator T& operator*() { return *ptr; } // Overloading arrow operator so that // members of T can be accessed // like a pointer (useful if T represents // a class or struct or union type) T* operator->() { return ptr; }}; int main(){ SmartPtr<int> ptr(new int()); *ptr = 20; cout << *ptr; return 0;}", "e": 4278, "s": 3654, "text": null }, { "code": null, "e": 4281, "s": 4278, "text": "20" }, { "code": null, "e": 4393, "s": 4283, "text": "Note: Smart pointers are also useful in the management of resources, such as file handles or network sockets." }, { "code": null, "e": 4649, "s": 4393, "text": "unique_ptr stores one pointer only. We can assign a different object by removing the current object from the pointer. Notice the code below. First, the unique_pointer is pointing to P1. But, then we remove P1 and assign P2 so the pointer now points to P2." }, { "code": null, "e": 4655, "s": 4649, "text": "C++14" }, { "code": "#include <iostream>using namespace std;#include <memory> class Rectangle { int length; int breadth; public: Rectangle(int l, int b){ length = l; breadth = b; } int area(){ return length * breadth; }}; int main(){ unique_ptr<Rectangle> P1(new Rectangle(10, 5)); cout << P1->area() << endl; // This'll print 50 // unique_ptr<Rectangle> P2(P1); unique_ptr<Rectangle> P2; P2 = move(P1); // This'll print 50 cout << P2->area() << endl; // cout<<P1->area()<<endl; return 0;}", "e": 5195, "s": 4655, "text": null }, { "code": null, "e": 5201, "s": 5195, "text": "50\n50" }, { "code": null, "e": 5350, "s": 5203, "text": "By using shared_ptr more than one pointer can point to this one object at a time and it’ll maintain a Reference Counter using use_count() method. " }, { "code": null, "e": 5356, "s": 5350, "text": "C++14" }, { "code": "#include <iostream>using namespace std;#include <memory> class Rectangle { int length; int breadth; public: Rectangle(int l, int b) { length = l; breadth = b; } int area() { return length * breadth; }}; int main(){ shared_ptr<Rectangle> P1(new Rectangle(10, 5)); // This'll print 50 cout << P1->area() << endl; shared_ptr<Rectangle> P2; P2 = P1; // This'll print 50 cout << P2->area() << endl; // This'll now not give an error, cout << P1->area() << endl; // This'll also print 50 now // This'll print 2 as Reference Counter is 2 cout << P1.use_count() << endl; return 0;}", "e": 6019, "s": 5356, "text": null }, { "code": null, "e": 6030, "s": 6019, "text": "50\n50\n50\n2" }, { "code": null, "e": 6304, "s": 6032, "text": "It’s much more similar to shared_ptr except it’ll not maintain a Reference Counter. In this case, a pointer will not have a stronghold on the object. The reason is if suppose pointers are holding the object and requesting for other objects then they may form a Deadlock. " }, { "code": null, "e": 6421, "s": 6304, "text": "C++ libraries provide implementations of smart pointers in the form of auto_ptr, unique_ptr, shared_ptr and weak_ptr" }, { "code": null, "e": 6476, "s": 6421, "text": "References: http://en.wikipedia.org/wiki/Smart_pointer" }, { "code": null, "e": 6688, "s": 6476, "text": "This article is improved by AmiyaRanjanRout. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. It had been improved again by AAShakil50." }, { "code": null, "e": 6705, "s": 6688, "text": "BabisSarantoglou" }, { "code": null, "e": 6721, "s": 6705, "text": "AmiyaRanjanRout" }, { "code": null, "e": 6735, "s": 6721, "text": "shrutipriyain" }, { "code": null, "e": 6752, "s": 6735, "text": "bogdanpescarus94" }, { "code": null, "e": 6763, "s": 6752, "text": "aashakil50" }, { "code": null, "e": 6782, "s": 6763, "text": "surindertarika1234" }, { "code": null, "e": 6794, "s": 6782, "text": "cpp-pointer" }, { "code": null, "e": 6805, "s": 6794, "text": "C Language" }, { "code": null, "e": 6809, "s": 6805, "text": "C++" }, { "code": null, "e": 6813, "s": 6809, "text": "CPP" }, { "code": null, "e": 6911, "s": 6813, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6934, "s": 6911, "text": "std::sort() in C++ STL" }, { "code": null, "e": 6961, "s": 6934, "text": "Bitwise Operators in C/C++" }, { "code": null, "e": 6978, "s": 6961, "text": "Substring in C++" }, { "code": null, "e": 7056, "s": 6978, "text": "Dynamic Memory Allocation in C using malloc(), calloc(), free() and realloc()" }, { "code": null, "e": 7078, "s": 7056, "text": "Function Pointer in C" }, { "code": null, "e": 7096, "s": 7078, "text": "Vector in C++ STL" }, { "code": null, "e": 7142, "s": 7096, "text": "Initialize a vector in C++ (7 different ways)" }, { "code": null, "e": 7165, "s": 7142, "text": "std::sort() in C++ STL" }, { "code": null, "e": 7192, "s": 7165, "text": "Bitwise Operators in C/C++" } ]
How to drop a level from a multi-level column index in Pandas Dataframe ?
21 Apr, 2021 In this article, we will learn about how to drop a level from a multi-level column index. But before that, we need to know what is a multi-level index. A multi-level index dataframe is a type of dataframe that contains multiple level or hierarchical indexing.In this article, we will be creating a dataframe of our own choice with multiple column indexing, and then we are going to drop off a level of our hierarchical indexing. Let’s understand this using step-by-step implementation with the help of an example. Step 1: Import all the libraries required. Python3 # importing all important librariesimport pandas as pd Step 2: Create a multi-level column index Pandas Dataframe and show it. We are creating a multi-index column using MultiIndex.from_tuples() which helps us to create multiple indexes one below another, and it is created column-wise. After that, using pd.Dataframe() we are creating data and converting it into the tabular format with the column names as the multi-level indexes. Also, we are changing the index name of the table using df.index. Python3 # Creating a multilevel index index = pd.MultiIndex.from_tuples([("Group 1", "Group 1"), ("Group 1", "Group 2"), ("Group 3","Group 3")]) # Creating a pandas dataframe with # multilevel-column indexingdf = pd.DataFrame([["Ross","Joey","Chandler"], ["Rachel","","Monica"]], columns=index) # Labelling the dataframe index.index = df. indexindex. name = "F.R.I.E.N.D.S" # Showing the above multi-index column# dataframeprint(df) Output: Step 3: Drop the level(s) of the dataframe Now a multi-level column index dataframe is created using python. Now let us implement the above concept now. We need to drop a level. We can do that using df.columns.droplevel(level=0). This helps us to drop an index level from the top that is of index 0. Python3 # Dropping a level downdf.columns = df.columns.droplevel(0) Step 4: Show the required result Python3 print(df) Output: Hence, we have been able to drop a level of index column successfully. Let’s see some more examples based on the above approach. Example 1: In the next example, we will be dropping a level from a specific index in the multi-level column index. This can be done using the same syntax we have used earlier[df.columns.droplevel(level=0)] where if we specify the level number, then the following index gets deleted according to zero-based indexing. So let us move to the implementation of the concept. Python3 # importing all important librariesimport pandas as pd # Creating a multilevel index index = pd.MultiIndex.from_tuples([("Company A", "Company B","Company C"), ("Company A", "Company A","Company B"), ("Company A","Company B","Company C")]) # Creating a pandas dataframe with # multilevel-column indexingdf = pd.DataFrame([["Atreyi","Digangana","Sohom"], ["Sujit","Bjon","Rajshekhar"], ["Debosmita","Shatabdi",""]], columns=index) # Labelling the dataframe index.index = df. indexindex. name = "ECE Placement" # Showing the above multi-index column# dataframeprint(df) Output: Now, if we want to drop level with index 2, then let’s see what happens! Python3 # Dropping a level number 2df.columns = df.columns.droplevel(2)print(df) Output: Hence, we can observe that in the multi-level column index, we have successfully removed the level with index number 2. Example 2: In this example, we will be implementing more concepts of the multi-level index. We will be deleting multiple levels at the same time. Python3 # importing all important librariesimport pandas as pd # Creating a multilevel indexindex = pd.MultiIndex.from_tuples([("Company A", "Company B", "Company C"), ("Company A", "Company A", "Company B"), ("Company A", "Company B", "Company C")]) # Creating a pandas dataframe with# multilevel-column indexingdf = pd.DataFrame([["Atreyi", "Digangana", "Sohom"], ["Sujit", "Bjon", "Rajshekhar"], ["Debosmita", "Shatabdi", ""]], columns=index) # Labelling the dataframe index.index = df. indexindex. name = "ECE Placement" # Showing the above multi-index column# dataframeprint(df) Output: As we can see, every list of arrays contains the indexes column-wise. So, three arrays mean three columns and the number of values in the array refers to the number of rows. Let us delete multiple indexes from the dataframe now. We can do that using df.columns.droplevel(level=0) by calling it multiple times. But here is a catch! Python3 # Dropping a level downdf.columns = df.columns.droplevel(0) # Dropping another level downdf.columns = df.columns.droplevel(0) # Showing the dataframeprint(df) As we can see, there are two droplevel statements with the level as 0. This is because, after the removal of a single level, the remaining ones get rearranged. So the level that was at index 1 will now come to index 0, Hence multiple droplevels are written in that case. Output: Hence, level 0 and level 1 get removed, and we are left with only level 2 which is now shown as level 0. Example 3: In the last example, let us remove multiple levels from various positions in the dataframe. Python3 # importing all important librariesimport pandas as pd # Creating a pandas dataframedf = pd.DataFrame([["Coding", "System Design"], ["DBMS", "Aptitude"], ["Logical Reasoning", "Development"]]) # Creating multilevel index from tuplesdf.columns = pd.MultiIndex.from_tuples([('Group 1', 'Group 2', 'Group 3', 'Group 4'), ('Group 3', 'Group 4', 'Group 5', 'Group 6')], names=['level 1', 'level 2', 'level 3', 'level 4'])# Showing the dataframeprint(df) Output: Now let us remove level 1 and 3 respectively: Python3 # Dropping a level down(Level 1)df.columns = df.columns.droplevel(0) # Dropping a level down after# re-arrangement(Level 2)df.columns = df.columns.droplevel(1) # Showing the dataframeprint(df) As we can see, we have dropped a level down from index 0 in the first case. After re-arrangement level 2 will now come to the 0 indexes of the multi-level index dataframe. Now in order to remove level 3 now, we have to specify the level as 1 according to the 0-based indexing after re-arrangement. Now levels 2 and 4 will be shown in the resultant output. Output: Picked Python pandas-indexing Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON How to drop one or multiple columns in Pandas Dataframe Python | os.path.join() method Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python | Get unique values from a list Create a directory in Python
[ { "code": null, "e": 28, "s": 0, "text": "\n21 Apr, 2021" }, { "code": null, "e": 457, "s": 28, "text": "In this article, we will learn about how to drop a level from a multi-level column index. But before that, we need to know what is a multi-level index. A multi-level index dataframe is a type of dataframe that contains multiple level or hierarchical indexing.In this article, we will be creating a dataframe of our own choice with multiple column indexing, and then we are going to drop off a level of our hierarchical indexing." }, { "code": null, "e": 542, "s": 457, "text": "Let’s understand this using step-by-step implementation with the help of an example." }, { "code": null, "e": 585, "s": 542, "text": "Step 1: Import all the libraries required." }, { "code": null, "e": 593, "s": 585, "text": "Python3" }, { "code": "# importing all important librariesimport pandas as pd", "e": 648, "s": 593, "text": null }, { "code": null, "e": 720, "s": 648, "text": "Step 2: Create a multi-level column index Pandas Dataframe and show it." }, { "code": null, "e": 1096, "s": 720, "text": "We are creating a multi-index column using MultiIndex.from_tuples() which helps us to create multiple indexes one below another, and it is created column-wise. After that, using pd.Dataframe() we are creating data and converting it into the tabular format with the column names as the multi-level indexes. Also, we are changing the index name of the table using df.index. " }, { "code": null, "e": 1104, "s": 1096, "text": "Python3" }, { "code": "# Creating a multilevel index index = pd.MultiIndex.from_tuples([(\"Group 1\", \"Group 1\"), (\"Group 1\", \"Group 2\"), (\"Group 3\",\"Group 3\")]) # Creating a pandas dataframe with # multilevel-column indexingdf = pd.DataFrame([[\"Ross\",\"Joey\",\"Chandler\"], [\"Rachel\",\"\",\"Monica\"]], columns=index) # Labelling the dataframe index.index = df. indexindex. name = \"F.R.I.E.N.D.S\" # Showing the above multi-index column# dataframeprint(df)", "e": 1637, "s": 1104, "text": null }, { "code": null, "e": 1645, "s": 1637, "text": "Output:" }, { "code": null, "e": 1688, "s": 1645, "text": "Step 3: Drop the level(s) of the dataframe" }, { "code": null, "e": 1945, "s": 1688, "text": "Now a multi-level column index dataframe is created using python. Now let us implement the above concept now. We need to drop a level. We can do that using df.columns.droplevel(level=0). This helps us to drop an index level from the top that is of index 0." }, { "code": null, "e": 1953, "s": 1945, "text": "Python3" }, { "code": "# Dropping a level downdf.columns = df.columns.droplevel(0)", "e": 2013, "s": 1953, "text": null }, { "code": null, "e": 2046, "s": 2013, "text": "Step 4: Show the required result" }, { "code": null, "e": 2054, "s": 2046, "text": "Python3" }, { "code": "print(df)", "e": 2064, "s": 2054, "text": null }, { "code": null, "e": 2072, "s": 2064, "text": "Output:" }, { "code": null, "e": 2143, "s": 2072, "text": "Hence, we have been able to drop a level of index column successfully." }, { "code": null, "e": 2201, "s": 2143, "text": "Let’s see some more examples based on the above approach." }, { "code": null, "e": 2212, "s": 2201, "text": "Example 1:" }, { "code": null, "e": 2570, "s": 2212, "text": "In the next example, we will be dropping a level from a specific index in the multi-level column index. This can be done using the same syntax we have used earlier[df.columns.droplevel(level=0)] where if we specify the level number, then the following index gets deleted according to zero-based indexing. So let us move to the implementation of the concept." }, { "code": null, "e": 2578, "s": 2570, "text": "Python3" }, { "code": "# importing all important librariesimport pandas as pd # Creating a multilevel index index = pd.MultiIndex.from_tuples([(\"Company A\", \"Company B\",\"Company C\"), (\"Company A\", \"Company A\",\"Company B\"), (\"Company A\",\"Company B\",\"Company C\")]) # Creating a pandas dataframe with # multilevel-column indexingdf = pd.DataFrame([[\"Atreyi\",\"Digangana\",\"Sohom\"], [\"Sujit\",\"Bjon\",\"Rajshekhar\"], [\"Debosmita\",\"Shatabdi\",\"\"]], columns=index) # Labelling the dataframe index.index = df. indexindex. name = \"ECE Placement\" # Showing the above multi-index column# dataframeprint(df)", "e": 3273, "s": 2578, "text": null }, { "code": null, "e": 3281, "s": 3273, "text": "Output:" }, { "code": null, "e": 3354, "s": 3281, "text": "Now, if we want to drop level with index 2, then let’s see what happens!" }, { "code": null, "e": 3362, "s": 3354, "text": "Python3" }, { "code": "# Dropping a level number 2df.columns = df.columns.droplevel(2)print(df)", "e": 3435, "s": 3362, "text": null }, { "code": null, "e": 3443, "s": 3435, "text": "Output:" }, { "code": null, "e": 3564, "s": 3443, "text": "Hence, we can observe that in the multi-level column index, we have successfully removed the level with index number 2. " }, { "code": null, "e": 3575, "s": 3564, "text": "Example 2:" }, { "code": null, "e": 3710, "s": 3575, "text": "In this example, we will be implementing more concepts of the multi-level index. We will be deleting multiple levels at the same time." }, { "code": null, "e": 3718, "s": 3710, "text": "Python3" }, { "code": "# importing all important librariesimport pandas as pd # Creating a multilevel indexindex = pd.MultiIndex.from_tuples([(\"Company A\", \"Company B\", \"Company C\"), (\"Company A\", \"Company A\", \"Company B\"), (\"Company A\", \"Company B\", \"Company C\")]) # Creating a pandas dataframe with# multilevel-column indexingdf = pd.DataFrame([[\"Atreyi\", \"Digangana\", \"Sohom\"], [\"Sujit\", \"Bjon\", \"Rajshekhar\"], [\"Debosmita\", \"Shatabdi\", \"\"]], columns=index) # Labelling the dataframe index.index = df. indexindex. name = \"ECE Placement\" # Showing the above multi-index column# dataframeprint(df)", "e": 4419, "s": 3718, "text": null }, { "code": null, "e": 4427, "s": 4419, "text": "Output:" }, { "code": null, "e": 4759, "s": 4427, "text": "As we can see, every list of arrays contains the indexes column-wise. So, three arrays mean three columns and the number of values in the array refers to the number of rows. Let us delete multiple indexes from the dataframe now. We can do that using df.columns.droplevel(level=0) by calling it multiple times. But here is a catch! " }, { "code": null, "e": 4767, "s": 4759, "text": "Python3" }, { "code": "# Dropping a level downdf.columns = df.columns.droplevel(0) # Dropping another level downdf.columns = df.columns.droplevel(0) # Showing the dataframeprint(df)", "e": 4928, "s": 4767, "text": null }, { "code": null, "e": 5199, "s": 4928, "text": "As we can see, there are two droplevel statements with the level as 0. This is because, after the removal of a single level, the remaining ones get rearranged. So the level that was at index 1 will now come to index 0, Hence multiple droplevels are written in that case." }, { "code": null, "e": 5207, "s": 5199, "text": "Output:" }, { "code": null, "e": 5312, "s": 5207, "text": "Hence, level 0 and level 1 get removed, and we are left with only level 2 which is now shown as level 0." }, { "code": null, "e": 5323, "s": 5312, "text": "Example 3:" }, { "code": null, "e": 5416, "s": 5323, "text": "In the last example, let us remove multiple levels from various positions in the dataframe. " }, { "code": null, "e": 5424, "s": 5416, "text": "Python3" }, { "code": "# importing all important librariesimport pandas as pd # Creating a pandas dataframedf = pd.DataFrame([[\"Coding\", \"System Design\"], [\"DBMS\", \"Aptitude\"], [\"Logical Reasoning\", \"Development\"]]) # Creating multilevel index from tuplesdf.columns = pd.MultiIndex.from_tuples([('Group 1', 'Group 2', 'Group 3', 'Group 4'), ('Group 3', 'Group 4', 'Group 5', 'Group 6')], names=['level 1', 'level 2', 'level 3', 'level 4'])# Showing the dataframeprint(df)", "e": 5988, "s": 5424, "text": null }, { "code": null, "e": 5996, "s": 5988, "text": "Output:" }, { "code": null, "e": 6042, "s": 5996, "text": "Now let us remove level 1 and 3 respectively:" }, { "code": null, "e": 6050, "s": 6042, "text": "Python3" }, { "code": "# Dropping a level down(Level 1)df.columns = df.columns.droplevel(0) # Dropping a level down after# re-arrangement(Level 2)df.columns = df.columns.droplevel(1) # Showing the dataframeprint(df)", "e": 6245, "s": 6050, "text": null }, { "code": null, "e": 6601, "s": 6245, "text": "As we can see, we have dropped a level down from index 0 in the first case. After re-arrangement level 2 will now come to the 0 indexes of the multi-level index dataframe. Now in order to remove level 3 now, we have to specify the level as 1 according to the 0-based indexing after re-arrangement. Now levels 2 and 4 will be shown in the resultant output." }, { "code": null, "e": 6609, "s": 6601, "text": "Output:" }, { "code": null, "e": 6616, "s": 6609, "text": "Picked" }, { "code": null, "e": 6639, "s": 6616, "text": "Python pandas-indexing" }, { "code": null, "e": 6653, "s": 6639, "text": "Python-pandas" }, { "code": null, "e": 6660, "s": 6653, "text": "Python" }, { "code": null, "e": 6758, "s": 6660, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6790, "s": 6758, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 6817, "s": 6790, "text": "Python Classes and Objects" }, { "code": null, "e": 6838, "s": 6817, "text": "Python OOPs Concepts" }, { "code": null, "e": 6861, "s": 6838, "text": "Introduction To PYTHON" }, { "code": null, "e": 6917, "s": 6861, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 6948, "s": 6917, "text": "Python | os.path.join() method" }, { "code": null, "e": 6990, "s": 6948, "text": "Check if element exists in list in Python" }, { "code": null, "e": 7032, "s": 6990, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 7071, "s": 7032, "text": "Python | Get unique values from a list" } ]
Bootstrap 4 | Introduction
28 Apr, 2022 Bootstrap is a free and open-source tool collection for creating responsive websites and web applications. It is the most popular HTML, CSS, and JavaScript framework for developing responsive, mobile-first websites. It solves many problems which we had once, one of which is the cross-browser compatibility issue. Nowadays, the websites are perfect for all the browsers (IE, Firefox, and Chrome) and for all sizes of screens (Desktop, Tablets, Phablets, and Phones). All thanks to Bootstrap developers -Mark Otto and Jacob Thornton of Twitter, though it was later declared to be an open-source project. Why Bootstrap? Faster and Easier Web Development. It creates Platform-independent web pages. It creates Responsive Web-pages. It is designed to be responsive to mobile devices too. It is Free! Available on www.getbootstrap.com How to use Bootstrap 4 on a webpage: There are two ways to include Bootstrap on the website. Include Bootstrap from the CDN link. Download Bootstrap from getbootstrap.com and use it. BootStrap 4 from CDN: This method of installing Bootstrap is easy. It is highly recommended to follow this method. Go to www.getbootstrap.com and click Getting Started. Scroll down and copy the Bootstrap CDN for CSS, JS, Popper.js, and jQuery links. Bootstrap CSS Library: <link rel=”stylesheet” href=”https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css” integrity=”sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T” crossorigin=”anonymous”> jQuery Library: <script src=”https://code.jquery.com/jquery-3.3.1.slim.min.js” integrity=”sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo” crossorigin=”anonymous”> </script> JS Library: <script src=”https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js” integrity=”sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1′′ crossorigin=”anonymous”> </script> The Latest compiled JavaScript Library: <script src=”https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js” integrity=”sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM” crossorigin=”anonymous”> </script> Copy the links and paste them into the head section of the HTML code. Example: HTML <!DOCTYPE html><html lang="en"><head> <title>Bootstrap Example</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- Bootstrap CSS library --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"> <!-- jQuery library --> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script> <!-- JS library --> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script> <!-- Latest compiled JavaScript library --> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script></head><body> <div class="container"> <h1>GeeksforGeeks</h1> <p>A computer science portal for geeks</p> </div></body></html> Output: Download Bootstrap: This method of installing bootstrap is also easy, but it can work offline ( doesn’t require an internet connection ) but it might not work for some browsers. Go to www.getbootstrap.com and click Getting Started. Click on the Download Bootstrap button. A.zip file would get downloaded. Extract it and go into the distribution folder. It contains two folders named CSS and JS. <link rel=”stylesheet” type=”text/css” href=”css/bootstrap.min.css”> <script src=”js/bootstrap.min.js”> </script> <script src=”https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js”> </script> Add the file link to the HTML document and then open the web page using web browsers. Example: HTML <!DOCTYPE html><html lang="en"><head> <title>Bootstrap Example</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" type="text/css" href="css/bootstrap.min.css"> <script src="js/bootstrap.min.js"></script></head><body> <div class="container"> <h1>GeeksforGeeks</h1> <p>A computer science portal for geeks</p> </div></body></html> Output: ghoshsuman0129 tanwarsinghvaibhav rkbhola5 sahilintern Bootstrap-4 Bootstrap Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to change navigation bar color in Bootstrap ? Form validation using jQuery How to pass data into a bootstrap modal? How to align navbar items to the right in Bootstrap 4 ? How to Show Images on Click using HTML ? 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": "\n28 Apr, 2022" }, { "code": null, "e": 655, "s": 52, "text": "Bootstrap is a free and open-source tool collection for creating responsive websites and web applications. It is the most popular HTML, CSS, and JavaScript framework for developing responsive, mobile-first websites. It solves many problems which we had once, one of which is the cross-browser compatibility issue. Nowadays, the websites are perfect for all the browsers (IE, Firefox, and Chrome) and for all sizes of screens (Desktop, Tablets, Phablets, and Phones). All thanks to Bootstrap developers -Mark Otto and Jacob Thornton of Twitter, though it was later declared to be an open-source project." }, { "code": null, "e": 671, "s": 655, "text": "Why Bootstrap? " }, { "code": null, "e": 706, "s": 671, "text": "Faster and Easier Web Development." }, { "code": null, "e": 749, "s": 706, "text": "It creates Platform-independent web pages." }, { "code": null, "e": 782, "s": 749, "text": "It creates Responsive Web-pages." }, { "code": null, "e": 837, "s": 782, "text": "It is designed to be responsive to mobile devices too." }, { "code": null, "e": 883, "s": 837, "text": "It is Free! Available on www.getbootstrap.com" }, { "code": null, "e": 977, "s": 883, "text": "How to use Bootstrap 4 on a webpage: There are two ways to include Bootstrap on the website. " }, { "code": null, "e": 1014, "s": 977, "text": "Include Bootstrap from the CDN link." }, { "code": null, "e": 1067, "s": 1014, "text": "Download Bootstrap from getbootstrap.com and use it." }, { "code": null, "e": 1183, "s": 1067, "text": "BootStrap 4 from CDN: This method of installing Bootstrap is easy. It is highly recommended to follow this method. " }, { "code": null, "e": 1318, "s": 1183, "text": "Go to www.getbootstrap.com and click Getting Started. Scroll down and copy the Bootstrap CDN for CSS, JS, Popper.js, and jQuery links." }, { "code": null, "e": 1341, "s": 1318, "text": "Bootstrap CSS Library:" }, { "code": null, "e": 1365, "s": 1341, "text": "<link rel=”stylesheet” " }, { "code": null, "e": 1446, "s": 1365, "text": "href=”https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css” " }, { "code": null, "e": 1530, "s": 1446, "text": "integrity=”sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T”" }, { "code": null, "e": 1555, "s": 1530, "text": "crossorigin=”anonymous”>" }, { "code": null, "e": 1571, "s": 1555, "text": "jQuery Library:" }, { "code": null, "e": 1635, "s": 1571, "text": "<script src=”https://code.jquery.com/jquery-3.3.1.slim.min.js” " }, { "code": null, "e": 1720, "s": 1635, "text": "integrity=”sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo” " }, { "code": null, "e": 1745, "s": 1720, "text": "crossorigin=”anonymous”>" }, { "code": null, "e": 1755, "s": 1745, "text": "</script>" }, { "code": null, "e": 1767, "s": 1755, "text": "JS Library:" }, { "code": null, "e": 1856, "s": 1767, "text": "<script src=”https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js” " }, { "code": null, "e": 1942, "s": 1856, "text": "integrity=”sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1′′ " }, { "code": null, "e": 1967, "s": 1942, "text": "crossorigin=”anonymous”>" }, { "code": null, "e": 1977, "s": 1967, "text": "</script>" }, { "code": null, "e": 2017, "s": 1977, "text": "The Latest compiled JavaScript Library:" }, { "code": null, "e": 2103, "s": 2017, "text": "<script src=”https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js” " }, { "code": null, "e": 2188, "s": 2103, "text": "integrity=”sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM” " }, { "code": null, "e": 2213, "s": 2188, "text": "crossorigin=”anonymous”>" }, { "code": null, "e": 2223, "s": 2213, "text": "</script>" }, { "code": null, "e": 2293, "s": 2223, "text": "Copy the links and paste them into the head section of the HTML code." }, { "code": null, "e": 2303, "s": 2293, "text": "Example: " }, { "code": null, "e": 2308, "s": 2303, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"><head> <title>Bootstrap Example</title> <meta charset=\"utf-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"> <!-- Bootstrap CSS library --> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css\" integrity=\"sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T\" crossorigin=\"anonymous\"> <!-- jQuery library --> <script src=\"https://code.jquery.com/jquery-3.3.1.slim.min.js\" integrity=\"sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo\" crossorigin=\"anonymous\"></script> <!-- JS library --> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js\" integrity=\"sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1\" crossorigin=\"anonymous\"></script> <!-- Latest compiled JavaScript library --> <script src=\"https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js\" integrity=\"sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM\" crossorigin=\"anonymous\"></script></head><body> <div class=\"container\"> <h1>GeeksforGeeks</h1> <p>A computer science portal for geeks</p> </div></body></html>", "e": 3634, "s": 2308, "text": null }, { "code": null, "e": 3643, "s": 3634, "text": "Output: " }, { "code": null, "e": 3822, "s": 3643, "text": "Download Bootstrap: This method of installing bootstrap is also easy, but it can work offline ( doesn’t require an internet connection ) but it might not work for some browsers. " }, { "code": null, "e": 3916, "s": 3822, "text": "Go to www.getbootstrap.com and click Getting Started. Click on the Download Bootstrap button." }, { "code": null, "e": 4039, "s": 3916, "text": "A.zip file would get downloaded. Extract it and go into the distribution folder. It contains two folders named CSS and JS." }, { "code": null, "e": 4108, "s": 4039, "text": "<link rel=”stylesheet” type=”text/css” href=”css/bootstrap.min.css”>" }, { "code": null, "e": 4153, "s": 4108, "text": "<script src=”js/bootstrap.min.js”> </script>" }, { "code": null, "e": 4233, "s": 4153, "text": "<script src=”https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js”>" }, { "code": null, "e": 4243, "s": 4233, "text": "</script>" }, { "code": null, "e": 4329, "s": 4243, "text": "Add the file link to the HTML document and then open the web page using web browsers." }, { "code": null, "e": 4340, "s": 4329, "text": "Example: " }, { "code": null, "e": 4345, "s": 4340, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"><head> <title>Bootstrap Example</title> <meta charset=\"utf-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"> <link rel=\"stylesheet\" type=\"text/css\" href=\"css/bootstrap.min.css\"> <script src=\"js/bootstrap.min.js\"></script></head><body> <div class=\"container\"> <h1>GeeksforGeeks</h1> <p>A computer science portal for geeks</p> </div></body></html>", "e": 4796, "s": 4345, "text": null }, { "code": null, "e": 4805, "s": 4796, "text": "Output: " }, { "code": null, "e": 4820, "s": 4805, "text": "ghoshsuman0129" }, { "code": null, "e": 4839, "s": 4820, "text": "tanwarsinghvaibhav" }, { "code": null, "e": 4848, "s": 4839, "text": "rkbhola5" }, { "code": null, "e": 4860, "s": 4848, "text": "sahilintern" }, { "code": null, "e": 4872, "s": 4860, "text": "Bootstrap-4" }, { "code": null, "e": 4882, "s": 4872, "text": "Bootstrap" }, { "code": null, "e": 4899, "s": 4882, "text": "Web Technologies" }, { "code": null, "e": 4997, "s": 4899, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5047, "s": 4997, "text": "How to change navigation bar color in Bootstrap ?" }, { "code": null, "e": 5076, "s": 5047, "text": "Form validation using jQuery" }, { "code": null, "e": 5117, "s": 5076, "text": "How to pass data into a bootstrap modal?" }, { "code": null, "e": 5173, "s": 5117, "text": "How to align navbar items to the right in Bootstrap 4 ?" }, { "code": null, "e": 5214, "s": 5173, "text": "How to Show Images on Click using HTML ?" }, { "code": null, "e": 5247, "s": 5214, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 5309, "s": 5247, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 5370, "s": 5309, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 5420, "s": 5370, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Java Program to Rotate Matrix Elements
21 Feb, 2022 Matrix is simply a two-dimensional array. So the goal is to deal with fixed indices at which elements are present and to perform operations on indexes such that elements on the addressed should be swapped in such a manner it should lookout as the matrix is rotated. Here we will be discussing two methods in dealing with indices Using naive approach Using optimal approach Using naive approach Using optimal approach Method 1: Using naive approach For a given matrix, the task is to rotate its elements in a clockwise direction. Illustrations: For 4*4 matrix Input: 7 8 9 10 11 12 2 3 4 Output: 10 7 8 2 11 9 3 4 12 For 4*4 matrix Input: 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 Output: 8 4 5 6 12 13 9 7 16 14 10 11 17 18 19 15 Approach: Here, we will use loops in order to print the elements in spiral form. Where, we will rotate all the rings of the elements one by one, starting from the outermost one. And for rotating a ring, we need to do the following: Move the elements of the top row,Move the elements of the last column,Move the elements of the bottom row, andMove the elements of the first column. Move the elements of the top row, Move the elements of the last column, Move the elements of the bottom row, and Move the elements of the first column. Moreover, repeat the above steps if there is an inner ring as well. Example: Java // Java Program to Rotate Matrix Elements // Importing classes from java.lang package import java.lang.*;// Importing classes from java.util package import java.util.*; // main Class class GFG { static int r = 4; static int c = 4; // Method // To rotate a matrix of // dimension r x c. And initially, // p = r and q = c static void rotate_matrix(int p, int q, int matrix[][]) { int rw = 0, cl = 0; int previous, current; // rw is the Starting row index // p is the ending row index // cl is the starting column index // q is the ending column index and // x is the iterator while (rw < p && cl < q) { if (rw + 1 == p || cl + 1 == q) break; // After storing the first element of the // next row, this element will substitute // the first element of the current row previous = matrix[rw + 1][cl]; // Moving the elements of the first row // from rest of the rows for (int x = cl; x < q; x++) { current = matrix[rw][x]; matrix[rw][x] = previous; previous = current; } rw++; // Moving the elements of the last column // from rest of the columns for (int x = rw; x < p; x++) { current = matrix[x][q - 1]; matrix[x][q - 1] = previous; previous = current; } q--; // Moving the elements of the last row // from rest of the rows if (rw < p) { for (int x = q - 1; x >= cl; x--) { current = matrix[p - 1][x]; matrix[p - 1][x] = previous; previous = current; } } p--; // Moving elements of the first column // from rest of the rows if (cl < q) { for (int x = p - 1; x >= rw; x--) { current = matrix[x][cl]; matrix[x][cl] = previous; previous = current; } } cl++; } // Prints the rotated matrix for (int x = 0; x < r; x++) { for (int y = 0; y < c; y++) System.out.print(matrix[x][y] + " "); System.out.print("\n"); } } // Method 2 // Main driver method public static void main(String[] args) { // Custom input array int b[][] = { { 5, 6, 7, 8 }, { 1, 2, 3, 4 }, { 0, 15, 6, 5 }, { 3, 1, 2, 12 } }; // Calling function(Method1) to rotate matrix rotate_matrix(r, c, b); }} 1 5 6 7 0 15 2 8 3 6 3 4 1 2 12 5 Method 2: Using optimal approach For a given matrix of size M×N, we need to rotate the matrix elements by k times to the right side. Where k is a number. Approach: An optimal approach is to observe each row of the stated matrix as an array and then execute an array rotation. It is performed by replicating the elements of the matrix from the given number k to the end of an array to the starting of the array utilizing a temporary array. And then the rest of the elements from the start to (k-1) to the end of an array. Illustration: Input : M = 3, N = 3, k = 2 1 2 3 4 5 6 7 8 9 Output : 2 3 1 5 6 4 8 9 7 Input : M = 2, N = 2, k = 2 11 12 13 14 Output : 11 12 13 14 Example: Java // Java Program to Rotate Matrix to Right Side by K Times // Main Classpublic class GFG { // Dimension of the matrix // Initializing to custom values static final int P = 3; static final int Q = 3; // Method 1 // To rotate the stated matrix by K times static void rotate_Matrix(int mat[][], int K) { // Using temporary array of dimension P int tempo[] = new int[P]; // Rotating matrix by k times across the size of // matrix K = K % P; for (int j = 0; j < Q; j++) { // Copying first P-K elements // to the temporary array for (int l = 0; l < P - K; l++) tempo[l] = mat[j][l]; // Copying the elements of the matrix // from K to the end to the starting for (int x = P - K; x < P; x++) mat[j][x - P + K] = mat[j][x]; // Copying the elements of the matrix // from the temporary array to end for (int x = K; x < P; x++) mat[j][x] = tempo[x - K]; } } // Method 2 // To show the resultant matrix static void show_Matrix(int mat[][]) { for (int j = 0; j < Q; j++) { for (int x = 0; x < P; x++) System.out.print(mat[j][x] + " "); System.out.println(); } } // Method 3 // Main driver method public static void main(String[] args) { // Custom input array int mat[][] = { { 1, 2, 5 }, { 3, 4, 6 }, { 8, 10, 9 } }; // Custom value of K int K = 2; // Calling the above created method for // rotating matrix by k times rotate_Matrix(mat, K); // Calling the above method for // displaying rotated matrix show_Matrix(mat); }} 2 5 1 4 6 3 10 9 8 simranarora5sos Java Java Programs Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n21 Feb, 2022" }, { "code": null, "e": 357, "s": 28, "text": "Matrix is simply a two-dimensional array. So the goal is to deal with fixed indices at which elements are present and to perform operations on indexes such that elements on the addressed should be swapped in such a manner it should lookout as the matrix is rotated. Here we will be discussing two methods in dealing with indices" }, { "code": null, "e": 402, "s": 357, "text": "Using naive approach Using optimal approach " }, { "code": null, "e": 424, "s": 402, "text": "Using naive approach " }, { "code": null, "e": 448, "s": 424, "text": "Using optimal approach " }, { "code": null, "e": 480, "s": 448, "text": "Method 1: Using naive approach " }, { "code": null, "e": 561, "s": 480, "text": "For a given matrix, the task is to rotate its elements in a clockwise direction." }, { "code": null, "e": 576, "s": 561, "text": "Illustrations:" }, { "code": null, "e": 682, "s": 576, "text": "For 4*4 matrix\n\nInput:\n7 8 9\n10 11 12\n2 3 4\n\nOutput:\n10 7 8\n2 11 9\n3 4 12" }, { "code": null, "e": 859, "s": 682, "text": "For 4*4 matrix\n\nInput:\n4 5 6 7 \n8 9 10 11\n12 13 14 15\n16 17 18 19\n\nOutput:\n8 4 5 6\n12 13 9 7\n16 14 10 11\n17 18 19 15" }, { "code": null, "e": 869, "s": 859, "text": "Approach:" }, { "code": null, "e": 1091, "s": 869, "text": "Here, we will use loops in order to print the elements in spiral form. Where, we will rotate all the rings of the elements one by one, starting from the outermost one. And for rotating a ring, we need to do the following:" }, { "code": null, "e": 1240, "s": 1091, "text": "Move the elements of the top row,Move the elements of the last column,Move the elements of the bottom row, andMove the elements of the first column." }, { "code": null, "e": 1274, "s": 1240, "text": "Move the elements of the top row," }, { "code": null, "e": 1312, "s": 1274, "text": "Move the elements of the last column," }, { "code": null, "e": 1353, "s": 1312, "text": "Move the elements of the bottom row, and" }, { "code": null, "e": 1392, "s": 1353, "text": "Move the elements of the first column." }, { "code": null, "e": 1460, "s": 1392, "text": "Moreover, repeat the above steps if there is an inner ring as well." }, { "code": null, "e": 1469, "s": 1460, "text": "Example:" }, { "code": null, "e": 1474, "s": 1469, "text": "Java" }, { "code": "// Java Program to Rotate Matrix Elements // Importing classes from java.lang package import java.lang.*;// Importing classes from java.util package import java.util.*; // main Class class GFG { static int r = 4; static int c = 4; // Method // To rotate a matrix of // dimension r x c. And initially, // p = r and q = c static void rotate_matrix(int p, int q, int matrix[][]) { int rw = 0, cl = 0; int previous, current; // rw is the Starting row index // p is the ending row index // cl is the starting column index // q is the ending column index and // x is the iterator while (rw < p && cl < q) { if (rw + 1 == p || cl + 1 == q) break; // After storing the first element of the // next row, this element will substitute // the first element of the current row previous = matrix[rw + 1][cl]; // Moving the elements of the first row // from rest of the rows for (int x = cl; x < q; x++) { current = matrix[rw][x]; matrix[rw][x] = previous; previous = current; } rw++; // Moving the elements of the last column // from rest of the columns for (int x = rw; x < p; x++) { current = matrix[x][q - 1]; matrix[x][q - 1] = previous; previous = current; } q--; // Moving the elements of the last row // from rest of the rows if (rw < p) { for (int x = q - 1; x >= cl; x--) { current = matrix[p - 1][x]; matrix[p - 1][x] = previous; previous = current; } } p--; // Moving elements of the first column // from rest of the rows if (cl < q) { for (int x = p - 1; x >= rw; x--) { current = matrix[x][cl]; matrix[x][cl] = previous; previous = current; } } cl++; } // Prints the rotated matrix for (int x = 0; x < r; x++) { for (int y = 0; y < c; y++) System.out.print(matrix[x][y] + \" \"); System.out.print(\"\\n\"); } } // Method 2 // Main driver method public static void main(String[] args) { // Custom input array int b[][] = { { 5, 6, 7, 8 }, { 1, 2, 3, 4 }, { 0, 15, 6, 5 }, { 3, 1, 2, 12 } }; // Calling function(Method1) to rotate matrix rotate_matrix(r, c, b); }}", "e": 4271, "s": 1474, "text": null }, { "code": null, "e": 4309, "s": 4271, "text": "1 5 6 7 \n0 15 2 8 \n3 6 3 4 \n1 2 12 5 " }, { "code": null, "e": 4343, "s": 4309, "text": "Method 2: Using optimal approach " }, { "code": null, "e": 4464, "s": 4343, "text": "For a given matrix of size M×N, we need to rotate the matrix elements by k times to the right side. Where k is a number." }, { "code": null, "e": 4474, "s": 4464, "text": "Approach:" }, { "code": null, "e": 4831, "s": 4474, "text": "An optimal approach is to observe each row of the stated matrix as an array and then execute an array rotation. It is performed by replicating the elements of the matrix from the given number k to the end of an array to the starting of the array utilizing a temporary array. And then the rest of the elements from the start to (k-1) to the end of an array." }, { "code": null, "e": 4845, "s": 4831, "text": "Illustration:" }, { "code": null, "e": 5062, "s": 4845, "text": "Input : M = 3, N = 3, k = 2\n 1 2 3\n 4 5 6\n 7 8 9 \n\nOutput : 2 3 1\n 5 6 4\n 8 9 7 \n\n\nInput : M = 2, N = 2, k = 2\n 11 12\n 13 14\n \nOutput : 11 12\n 13 14" }, { "code": null, "e": 5071, "s": 5062, "text": "Example:" }, { "code": null, "e": 5076, "s": 5071, "text": "Java" }, { "code": "// Java Program to Rotate Matrix to Right Side by K Times // Main Classpublic class GFG { // Dimension of the matrix // Initializing to custom values static final int P = 3; static final int Q = 3; // Method 1 // To rotate the stated matrix by K times static void rotate_Matrix(int mat[][], int K) { // Using temporary array of dimension P int tempo[] = new int[P]; // Rotating matrix by k times across the size of // matrix K = K % P; for (int j = 0; j < Q; j++) { // Copying first P-K elements // to the temporary array for (int l = 0; l < P - K; l++) tempo[l] = mat[j][l]; // Copying the elements of the matrix // from K to the end to the starting for (int x = P - K; x < P; x++) mat[j][x - P + K] = mat[j][x]; // Copying the elements of the matrix // from the temporary array to end for (int x = K; x < P; x++) mat[j][x] = tempo[x - K]; } } // Method 2 // To show the resultant matrix static void show_Matrix(int mat[][]) { for (int j = 0; j < Q; j++) { for (int x = 0; x < P; x++) System.out.print(mat[j][x] + \" \"); System.out.println(); } } // Method 3 // Main driver method public static void main(String[] args) { // Custom input array int mat[][] = { { 1, 2, 5 }, { 3, 4, 6 }, { 8, 10, 9 } }; // Custom value of K int K = 2; // Calling the above created method for // rotating matrix by k times rotate_Matrix(mat, K); // Calling the above method for // displaying rotated matrix show_Matrix(mat); }}", "e": 6894, "s": 5076, "text": null }, { "code": null, "e": 6916, "s": 6894, "text": "2 5 1 \n4 6 3 \n10 9 8 " }, { "code": null, "e": 6932, "s": 6916, "text": "simranarora5sos" }, { "code": null, "e": 6937, "s": 6932, "text": "Java" }, { "code": null, "e": 6951, "s": 6937, "text": "Java Programs" }, { "code": null, "e": 6956, "s": 6951, "text": "Java" } ]
Subtract two numbers without using arithmetic operators
01 Nov, 2021 Write a function subtract(x, y) that returns x-y where x and y are integers. The function should not use any of the arithmetic operators (+, ++, –, -, .. etc). The idea is to use bitwise operators. Addition of two numbers has been discussed using Bitwise operators. Like addition, the idea is to use subtractor logic. The truth table for the half subtractor is given below. X Y Diff Borrow 0 0 0 0 0 1 1 1 1 0 1 0 1 1 0 0 From the above table one can draw the Karnaugh map for “difference” and “borrow”.So, Logic equations are: Diff = y ⊕ x Borrow = x' . y Source: Wikipedia page for subtractor Following is implementation based on above equations. C++ C Java Python3 C# PHP Javascript // C++ program to Subtract two numbers// without using arithmetic operators#include <iostream>using namespace std; int subtract(int x, int y){ // Iterate till there // is no carry while (y != 0) { // borrow contains common // set bits of y and unset // bits of x int borrow = (~x) & y; // Subtraction of bits of x // and y where at least one // of the bits is not set x = x ^ y; // Borrow is shifted by one // so that subtracting it from // x gives the required sum y = borrow << 1; } return x;} // Driver Codeint main(){ int x = 29, y = 13; cout << "x - y is " << subtract(x, y); return 0;} // This code is contributed by shivanisinghss2110 // C program to Subtract two numbers// without using arithmetic operators#include<stdio.h> int subtract(int x, int y){ // Iterate till there // is no carry while (y != 0) { // borrow contains common // set bits of y and unset // bits of x int borrow = (~x) & y; // Subtraction of bits of x // and y where at least one // of the bits is not set x = x ^ y; // Borrow is shifted by one // so that subtracting it from // x gives the required sum y = borrow << 1; } return x;} // Driver Codeint main(){ int x = 29, y = 13; printf("x - y is %d", subtract(x, y)); return 0;} // Java Program to subtract two Number// without using arithmetic operatorimport java.io.*; class GFG{ static int subtract(int x, int y) { // Iterate till there // is no carry while (y != 0) { // borrow contains common // set bits of y and unset // bits of x int borrow = (~x) & y; // Subtraction of bits of x // and y where at least one // of the bits is not set x = x ^ y; // Borrow is shifted by one // so that subtracting it from // x gives the required sum y = borrow << 1; } return x;} // Driver Code public static void main (String[] args) { int x = 29, y = 13; System.out.println("x - y is " + subtract(x, y)); }} // This code is contributed by vt_m def subtract(x, y): # Iterate till there # is no carry while (y != 0): # borrow contains common # set bits of y and unset # bits of x borrow = (~x) & y # Subtraction of bits of x # and y where at least one # of the bits is not set x = x ^ y # Borrow is shifted by one # so that subtracting it from # x gives the required sum y = borrow << 1 return x # Driver Codex = 29y = 13print("x - y is",subtract(x, y)) # This code is contributed by# Smitha Dinesh Semwal // C# Program to subtract two Number// without using arithmetic operatorusing System; class GFG { static int subtract(int x, int y) { // Iterate till there // is no carry while (y != 0) { // borrow contains common // set bits of y and unset // bits of x int borrow = (~x) & y; // Subtraction of bits of x // and y where at least one // of the bits is not set x = x ^ y; // Borrow is shifted by one // so that subtracting it from // x gives the required sum y = borrow << 1; } return x; } // Driver Code public static void Main () { int x = 29, y = 13; Console.WriteLine("x - y is " + subtract(x, y)); }} // This code is contributed by anuj_67. <?php// PHP Program to subtract two Number// without using arithmetic operator function subtract($x, $y){ // Iterate till there is no carry while ($y != 0) { // borrow contains common set // bits of y and unset // bits of x $borrow = (~$x) & $y; // Subtraction of bits of x // and y where at least // one of the bits is not set $x = $x ^ $y; // Borrow is shifted by one so // that subtracting it from // x gives the required sum $y = $borrow << 1; } return $x;} // Driver Code $x = 29; $y = 13; echo "x - y is ", subtract($x,$y); // This code is contributed by Ajit?> <script> // JavaScript program to Subtract two numbers// without using arithmetic operators function subtract(x, y){ // Iterate till there // is no carry while (y != 0) { // borrow contains common // set bits of y and unset // bits of x let borrow = (~x) & y; // Subtraction of bits of x // and y where at least one // of the bits is not set x = x ^ y; // Borrow is shifted by one // so that subtracting it from // x gives the required sum y = borrow << 1; } return x;} // Driver Code let x = 29, y = 13;document.write("x - y is " + subtract(x, y)); // This code is contributed by Surbhi Tyagi. </script> Output : x - y is 16 Time Complexity: O(log y) Auxiliary Space: O(1) Following is recursive implementation for the same approach. C++ C Java Python3 C# PHP Javascript #include <iostream>using namespace std; int subtract(int x, int y){ if (y == 0) return x; return subtract(x ^ y, (~x & y) << 1);} // Driver programint main(){ int x = 29, y = 13; cout << "x - y is "<< subtract(x, y); return 0;} // this code is contributed by shivanisinghss2110 #include<stdio.h> int subtract(int x, int y){ if (y == 0) return x; return subtract(x ^ y, (~x & y) << 1);} // Driver programint main(){ int x = 29, y = 13; printf("x - y is %d", subtract(x, y)); return 0;} // Java Program to subtract two Number// without using arithmetic operator// Recursive implementation.class GFG { static int subtract(int x, int y) { if (y == 0) return x; return subtract(x ^ y, (~x & y) << 1); } // Driver program public static void main(String[] args) { int x = 29, y = 13; System.out.printf("x - y is %d", subtract(x, y)); }} // This code is contributed by // Smitha Dinesh Semwal. # Python Program to# subtract two Number# without using arithmetic operator# Recursive implementation. def subtract(x, y): if (y == 0): return x return subtract(x ^ y, (~x & y) << 1) # Driver programx = 29y = 13print("x - y is", subtract(x, y)) # This code is contributed by# Smitha Dinesh Semwal // C# Program to subtract two Number// without using arithmetic operator// Recursive implementation.using System; class GFG { static int subtract(int x, int y) { if (y == 0) return x; return subtract(x ^ y, (~x & y) << 1); } // Driver program public static void Main() { int x = 29, y = 13; Console.WriteLine("x - y is "+ subtract(x, y)); }} // This code is contributed by anuj_67. <?php function subtract($x, $y){ if ($y == 0) return $x; return subtract($x ^ $y, (~$x & $y) << 1);} // Driver Code$x = 29; $y = 13;echo "x - y is ", subtract($x, $y); # This code is contributed by ajit?> <script>// javascript Program to subtract two Number// without using arithmetic operator// Recursive implementation. function subtract(x , y){ if (y == 0) return x; return subtract(x ^ y, (~x & y) << 1);} // Driver programvar x = 29, y = 13;document.write("x - y is "+ subtract(x, y)); // This code is contributed by Princi Singh</script> Output : x - y is 16 Time Complexity: O(log y) Auxiliary Space: O(log y) This article is contributed Dheeraj. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above jit_t vt_m surbhityagi15 princi singh simmytarika5 adnanirshad158 shivanisinghss2110 arorakashish0911 subham348 Bit Magic Bit Magic Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n01 Nov, 2021" }, { "code": null, "e": 371, "s": 52, "text": "Write a function subtract(x, y) that returns x-y where x and y are integers. The function should not use any of the arithmetic operators (+, ++, –, -, .. etc). The idea is to use bitwise operators. Addition of two numbers has been discussed using Bitwise operators. Like addition, the idea is to use subtractor logic. " }, { "code": null, "e": 428, "s": 371, "text": "The truth table for the half subtractor is given below. " }, { "code": null, "e": 536, "s": 428, "text": "X Y Diff Borrow\n0 0 0 0\n0 1 1 1\n1 0 1 0\n1 1 0 0" }, { "code": null, "e": 643, "s": 536, "text": "From the above table one can draw the Karnaugh map for “difference” and “borrow”.So, Logic equations are: " }, { "code": null, "e": 683, "s": 643, "text": " Diff = y ⊕ x\n Borrow = x' . y " }, { "code": null, "e": 721, "s": 683, "text": "Source: Wikipedia page for subtractor" }, { "code": null, "e": 777, "s": 721, "text": "Following is implementation based on above equations. " }, { "code": null, "e": 781, "s": 777, "text": "C++" }, { "code": null, "e": 783, "s": 781, "text": "C" }, { "code": null, "e": 788, "s": 783, "text": "Java" }, { "code": null, "e": 796, "s": 788, "text": "Python3" }, { "code": null, "e": 799, "s": 796, "text": "C#" }, { "code": null, "e": 803, "s": 799, "text": "PHP" }, { "code": null, "e": 814, "s": 803, "text": "Javascript" }, { "code": "// C++ program to Subtract two numbers// without using arithmetic operators#include <iostream>using namespace std; int subtract(int x, int y){ // Iterate till there // is no carry while (y != 0) { // borrow contains common // set bits of y and unset // bits of x int borrow = (~x) & y; // Subtraction of bits of x // and y where at least one // of the bits is not set x = x ^ y; // Borrow is shifted by one // so that subtracting it from // x gives the required sum y = borrow << 1; } return x;} // Driver Codeint main(){ int x = 29, y = 13; cout << \"x - y is \" << subtract(x, y); return 0;} // This code is contributed by shivanisinghss2110", "e": 1569, "s": 814, "text": null }, { "code": "// C program to Subtract two numbers// without using arithmetic operators#include<stdio.h> int subtract(int x, int y){ // Iterate till there // is no carry while (y != 0) { // borrow contains common // set bits of y and unset // bits of x int borrow = (~x) & y; // Subtraction of bits of x // and y where at least one // of the bits is not set x = x ^ y; // Borrow is shifted by one // so that subtracting it from // x gives the required sum y = borrow << 1; } return x;} // Driver Codeint main(){ int x = 29, y = 13; printf(\"x - y is %d\", subtract(x, y)); return 0;}", "e": 2250, "s": 1569, "text": null }, { "code": "// Java Program to subtract two Number// without using arithmetic operatorimport java.io.*; class GFG{ static int subtract(int x, int y) { // Iterate till there // is no carry while (y != 0) { // borrow contains common // set bits of y and unset // bits of x int borrow = (~x) & y; // Subtraction of bits of x // and y where at least one // of the bits is not set x = x ^ y; // Borrow is shifted by one // so that subtracting it from // x gives the required sum y = borrow << 1; } return x;} // Driver Code public static void main (String[] args) { int x = 29, y = 13; System.out.println(\"x - y is \" + subtract(x, y)); }} // This code is contributed by vt_m", "e": 3095, "s": 2250, "text": null }, { "code": "def subtract(x, y): # Iterate till there # is no carry while (y != 0): # borrow contains common # set bits of y and unset # bits of x borrow = (~x) & y # Subtraction of bits of x # and y where at least one # of the bits is not set x = x ^ y # Borrow is shifted by one # so that subtracting it from # x gives the required sum y = borrow << 1 return x # Driver Codex = 29y = 13print(\"x - y is\",subtract(x, y)) # This code is contributed by# Smitha Dinesh Semwal", "e": 3673, "s": 3095, "text": null }, { "code": "// C# Program to subtract two Number// without using arithmetic operatorusing System; class GFG { static int subtract(int x, int y) { // Iterate till there // is no carry while (y != 0) { // borrow contains common // set bits of y and unset // bits of x int borrow = (~x) & y; // Subtraction of bits of x // and y where at least one // of the bits is not set x = x ^ y; // Borrow is shifted by one // so that subtracting it from // x gives the required sum y = borrow << 1; } return x; } // Driver Code public static void Main () { int x = 29, y = 13; Console.WriteLine(\"x - y is \" + subtract(x, y)); }} // This code is contributed by anuj_67.", "e": 4609, "s": 3673, "text": null }, { "code": "<?php// PHP Program to subtract two Number// without using arithmetic operator function subtract($x, $y){ // Iterate till there is no carry while ($y != 0) { // borrow contains common set // bits of y and unset // bits of x $borrow = (~$x) & $y; // Subtraction of bits of x // and y where at least // one of the bits is not set $x = $x ^ $y; // Borrow is shifted by one so // that subtracting it from // x gives the required sum $y = $borrow << 1; } return $x;} // Driver Code $x = 29; $y = 13; echo \"x - y is \", subtract($x,$y); // This code is contributed by Ajit?>", "e": 5332, "s": 4609, "text": null }, { "code": "<script> // JavaScript program to Subtract two numbers// without using arithmetic operators function subtract(x, y){ // Iterate till there // is no carry while (y != 0) { // borrow contains common // set bits of y and unset // bits of x let borrow = (~x) & y; // Subtraction of bits of x // and y where at least one // of the bits is not set x = x ^ y; // Borrow is shifted by one // so that subtracting it from // x gives the required sum y = borrow << 1; } return x;} // Driver Code let x = 29, y = 13;document.write(\"x - y is \" + subtract(x, y)); // This code is contributed by Surbhi Tyagi. </script>", "e": 6043, "s": 5332, "text": null }, { "code": null, "e": 6053, "s": 6043, "text": "Output : " }, { "code": null, "e": 6065, "s": 6053, "text": "x - y is 16" }, { "code": null, "e": 6091, "s": 6065, "text": "Time Complexity: O(log y)" }, { "code": null, "e": 6113, "s": 6091, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 6175, "s": 6113, "text": "Following is recursive implementation for the same approach. " }, { "code": null, "e": 6179, "s": 6175, "text": "C++" }, { "code": null, "e": 6181, "s": 6179, "text": "C" }, { "code": null, "e": 6186, "s": 6181, "text": "Java" }, { "code": null, "e": 6194, "s": 6186, "text": "Python3" }, { "code": null, "e": 6197, "s": 6194, "text": "C#" }, { "code": null, "e": 6201, "s": 6197, "text": "PHP" }, { "code": null, "e": 6212, "s": 6201, "text": "Javascript" }, { "code": "#include <iostream>using namespace std; int subtract(int x, int y){ if (y == 0) return x; return subtract(x ^ y, (~x & y) << 1);} // Driver programint main(){ int x = 29, y = 13; cout << \"x - y is \"<< subtract(x, y); return 0;} // this code is contributed by shivanisinghss2110", "e": 6512, "s": 6212, "text": null }, { "code": "#include<stdio.h> int subtract(int x, int y){ if (y == 0) return x; return subtract(x ^ y, (~x & y) << 1);} // Driver programint main(){ int x = 29, y = 13; printf(\"x - y is %d\", subtract(x, y)); return 0;}", "e": 6741, "s": 6512, "text": null }, { "code": "// Java Program to subtract two Number// without using arithmetic operator// Recursive implementation.class GFG { static int subtract(int x, int y) { if (y == 0) return x; return subtract(x ^ y, (~x & y) << 1); } // Driver program public static void main(String[] args) { int x = 29, y = 13; System.out.printf(\"x - y is %d\", subtract(x, y)); }} // This code is contributed by // Smitha Dinesh Semwal.", "e": 7234, "s": 6741, "text": null }, { "code": "# Python Program to# subtract two Number# without using arithmetic operator# Recursive implementation. def subtract(x, y): if (y == 0): return x return subtract(x ^ y, (~x & y) << 1) # Driver programx = 29y = 13print(\"x - y is\", subtract(x, y)) # This code is contributed by# Smitha Dinesh Semwal", "e": 7546, "s": 7234, "text": null }, { "code": "// C# Program to subtract two Number// without using arithmetic operator// Recursive implementation.using System; class GFG { static int subtract(int x, int y) { if (y == 0) return x; return subtract(x ^ y, (~x & y) << 1); } // Driver program public static void Main() { int x = 29, y = 13; Console.WriteLine(\"x - y is \"+ subtract(x, y)); }} // This code is contributed by anuj_67.", "e": 8018, "s": 7546, "text": null }, { "code": "<?php function subtract($x, $y){ if ($y == 0) return $x; return subtract($x ^ $y, (~$x & $y) << 1);} // Driver Code$x = 29; $y = 13;echo \"x - y is \", subtract($x, $y); # This code is contributed by ajit?>", "e": 8254, "s": 8018, "text": null }, { "code": "<script>// javascript Program to subtract two Number// without using arithmetic operator// Recursive implementation. function subtract(x , y){ if (y == 0) return x; return subtract(x ^ y, (~x & y) << 1);} // Driver programvar x = 29, y = 13;document.write(\"x - y is \"+ subtract(x, y)); // This code is contributed by Princi Singh</script>", "e": 8629, "s": 8254, "text": null }, { "code": null, "e": 8639, "s": 8629, "text": "Output : " }, { "code": null, "e": 8651, "s": 8639, "text": "x - y is 16" }, { "code": null, "e": 8677, "s": 8651, "text": "Time Complexity: O(log y)" }, { "code": null, "e": 8703, "s": 8677, "text": "Auxiliary Space: O(log y)" }, { "code": null, "e": 8865, "s": 8703, "text": "This article is contributed Dheeraj. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above " }, { "code": null, "e": 8871, "s": 8865, "text": "jit_t" }, { "code": null, "e": 8876, "s": 8871, "text": "vt_m" }, { "code": null, "e": 8890, "s": 8876, "text": "surbhityagi15" }, { "code": null, "e": 8903, "s": 8890, "text": "princi singh" }, { "code": null, "e": 8916, "s": 8903, "text": "simmytarika5" }, { "code": null, "e": 8931, "s": 8916, "text": "adnanirshad158" }, { "code": null, "e": 8950, "s": 8931, "text": "shivanisinghss2110" }, { "code": null, "e": 8967, "s": 8950, "text": "arorakashish0911" }, { "code": null, "e": 8977, "s": 8967, "text": "subham348" }, { "code": null, "e": 8987, "s": 8977, "text": "Bit Magic" }, { "code": null, "e": 8997, "s": 8987, "text": "Bit Magic" } ]
Sort the array of strings according to alphabetical order defined by another string
28 Feb, 2022 Given a string str and an array of strings strArr[], the task is to sort the array according to the alphabetical order defined by str. Note: str and every string in strArr[] consists of only lower case alphabets.Examples: Input: str = “fguecbdavwyxzhijklmnopqrst”, strArr[] = {“geeksforgeeks”, “is”, “the”, “best”, “place”, “for”, “learning”} Output: for geeksforgeeks best is learning place theInput: str = “avdfghiwyxzjkecbmnopqrstul”, strArr[] = {“rainbow”, “consists”, “of”, “colours”} Output: consists colours of rainbow Approach: Traverse every character of str and store the value in a map with character as the key and its index in the array as the value. Now, this map will act as the new alphabetical order of the characters. Start comparing the string in the strArr[] and instead of comparing the ASCII values of the characters, compare the values mapped to those particular characters in the map i.e. if character c1 appears before character c2 in str then c1 < c2.Below is the implementation of the above approach: C++ Java Python3 Javascript // C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Map to store the characters with their order// in the new alphabetical orderunordered_map<char, int> h; // Function that returns true if x < y// according to the new alphabetical orderbool compare(string x, string y){ for (int i = 0; i < min(x.size(), y.size()); i++) { if (h[x[i]] == h[y[i]]) continue; return h[x[i]] < h[y[i]]; } return x.size() < y.size();} // Driver codeint main(){ string str = "fguecbdavwyxzhijklmnopqrst"; vector<string> v{ "geeksforgeeks", "is", "the", "best", "place", "for", "learning" }; // Store the order for each character // in the new alphabetical sequence h.clear(); for (int i = 0; i < str.size(); i++) h[str[i]] = i; sort(v.begin(), v.end(), compare); // Print the strings after sorting for (auto x : v) cout << x << " "; return 0;} // Java implementation of the approachimport java.util.Arrays;import java.util.Comparator; public class GFG{private static void sort(String[] strArr, String str){ Comparator<String> myComp = new Comparator<String>() { @Override public int compare(String a, String b) { for(int i = 0; i < Math.min(a.length(), b.length()); i++) { if (str.indexOf(a.charAt(i)) == str.indexOf(b.charAt(i))) { continue; } else if(str.indexOf(a.charAt(i)) > str.indexOf(b.charAt(i))) { return 1; } else { return -1; } } return 0; } }; Arrays.sort(strArr, myComp);} // Driver Codepublic static void main(String[] args){ String str = "fguecbdavwyxzhijklmnopqrst"; String[] strArr = {"geeksforgeeks", "is", "the", "best", "place", "for", "learning"}; sort(strArr, str); for(int i = 0; i < strArr.length; i++) { System.out.print(strArr[i] + " "); }}} # Python3 implementation of the approach # Function to sort and print the array# according to the new alphabetical orderdef sortStringArray(s, a, n): # Sort the array according to the new alphabetical order a = sorted(a, key = lambda word: [s.index(c) for c in word]) for i in a: print(i, end =' ') # Driver codes = "fguecbdavwyxzhijklmnopqrst"a = ["geeksforgeeks", "is", "the", "best", "place", "for", "learning"]n = len(a)sortStringArray(s, a, n) <script> // JavaScript implementation of the approach // Map to store the characters with their order// in the new alphabetical orderlet h = new Map(); // Function that returns true if x < y// according to the new alphabetical orderfunction compare(x, y){ for (let i = 0; i < Math.min(x.length, y.length); i++) { if (h.get(x[i]) == h.get(y[i])) continue; return h.get(x[i]) - h.get(y[i]); } return x.length - y.length;} // Driver codelet str = "fguecbdavwyxzhijklmnopqrst";let v = [ "geeksforgeeks", "is", "the","best", "place", "for", "learning" ]; // Store the order for each character// in the new alphabetical sequenceh.clear();for (let i = 0; i < str.length; i++) h.set(str[i],i); v.sort(compare); // Print the strings after sortingfor (let x of v) document.write(x + " "); // This code is contributed by shinjanpatra</script> for geeksforgeeks best is learning place the Time Complexity: O(N * log(N)), where N is the size of the string str Auxiliary Space: O(N) dungeondragon22 subhammahato348 simranarora5sos shinjanpatra Advanced Data Structure Algorithms Competitive Programming Data Structures Hash Sorting Data Structures Hash Sorting Algorithms Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Agents in Artificial Intelligence Decision Tree Introduction with example Segment Tree | Set 1 (Sum of given range) Binary Indexed Tree or Fenwick Tree AVL Tree | Set 2 (Deletion) DSA Sheet by Love Babbar SDE SHEET - A Complete Guide for SDE Preparation Top 50 Array Coding Problems for Interviews Difference between BFS and DFS
[ { "code": null, "e": 52, "s": 24, "text": "\n28 Feb, 2022" }, { "code": null, "e": 275, "s": 52, "text": "Given a string str and an array of strings strArr[], the task is to sort the array according to the alphabetical order defined by str. Note: str and every string in strArr[] consists of only lower case alphabets.Examples: " }, { "code": null, "e": 580, "s": 275, "text": "Input: str = “fguecbdavwyxzhijklmnopqrst”, strArr[] = {“geeksforgeeks”, “is”, “the”, “best”, “place”, “for”, “learning”} Output: for geeksforgeeks best is learning place theInput: str = “avdfghiwyxzjkecbmnopqrstul”, strArr[] = {“rainbow”, “consists”, “of”, “colours”} Output: consists colours of rainbow " }, { "code": null, "e": 1082, "s": 580, "text": "Approach: Traverse every character of str and store the value in a map with character as the key and its index in the array as the value. Now, this map will act as the new alphabetical order of the characters. Start comparing the string in the strArr[] and instead of comparing the ASCII values of the characters, compare the values mapped to those particular characters in the map i.e. if character c1 appears before character c2 in str then c1 < c2.Below is the implementation of the above approach:" }, { "code": null, "e": 1086, "s": 1082, "text": "C++" }, { "code": null, "e": 1091, "s": 1086, "text": "Java" }, { "code": null, "e": 1099, "s": 1091, "text": "Python3" }, { "code": null, "e": 1110, "s": 1099, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Map to store the characters with their order// in the new alphabetical orderunordered_map<char, int> h; // Function that returns true if x < y// according to the new alphabetical orderbool compare(string x, string y){ for (int i = 0; i < min(x.size(), y.size()); i++) { if (h[x[i]] == h[y[i]]) continue; return h[x[i]] < h[y[i]]; } return x.size() < y.size();} // Driver codeint main(){ string str = \"fguecbdavwyxzhijklmnopqrst\"; vector<string> v{ \"geeksforgeeks\", \"is\", \"the\", \"best\", \"place\", \"for\", \"learning\" }; // Store the order for each character // in the new alphabetical sequence h.clear(); for (int i = 0; i < str.size(); i++) h[str[i]] = i; sort(v.begin(), v.end(), compare); // Print the strings after sorting for (auto x : v) cout << x << \" \"; return 0;}", "e": 2074, "s": 1110, "text": null }, { "code": "// Java implementation of the approachimport java.util.Arrays;import java.util.Comparator; public class GFG{private static void sort(String[] strArr, String str){ Comparator<String> myComp = new Comparator<String>() { @Override public int compare(String a, String b) { for(int i = 0; i < Math.min(a.length(), b.length()); i++) { if (str.indexOf(a.charAt(i)) == str.indexOf(b.charAt(i))) { continue; } else if(str.indexOf(a.charAt(i)) > str.indexOf(b.charAt(i))) { return 1; } else { return -1; } } return 0; } }; Arrays.sort(strArr, myComp);} // Driver Codepublic static void main(String[] args){ String str = \"fguecbdavwyxzhijklmnopqrst\"; String[] strArr = {\"geeksforgeeks\", \"is\", \"the\", \"best\", \"place\", \"for\", \"learning\"}; sort(strArr, str); for(int i = 0; i < strArr.length; i++) { System.out.print(strArr[i] + \" \"); }}}", "e": 3321, "s": 2074, "text": null }, { "code": "# Python3 implementation of the approach # Function to sort and print the array# according to the new alphabetical orderdef sortStringArray(s, a, n): # Sort the array according to the new alphabetical order a = sorted(a, key = lambda word: [s.index(c) for c in word]) for i in a: print(i, end =' ') # Driver codes = \"fguecbdavwyxzhijklmnopqrst\"a = [\"geeksforgeeks\", \"is\", \"the\", \"best\", \"place\", \"for\", \"learning\"]n = len(a)sortStringArray(s, a, n)", "e": 3791, "s": 3321, "text": null }, { "code": "<script> // JavaScript implementation of the approach // Map to store the characters with their order// in the new alphabetical orderlet h = new Map(); // Function that returns true if x < y// according to the new alphabetical orderfunction compare(x, y){ for (let i = 0; i < Math.min(x.length, y.length); i++) { if (h.get(x[i]) == h.get(y[i])) continue; return h.get(x[i]) - h.get(y[i]); } return x.length - y.length;} // Driver codelet str = \"fguecbdavwyxzhijklmnopqrst\";let v = [ \"geeksforgeeks\", \"is\", \"the\",\"best\", \"place\", \"for\", \"learning\" ]; // Store the order for each character// in the new alphabetical sequenceh.clear();for (let i = 0; i < str.length; i++) h.set(str[i],i); v.sort(compare); // Print the strings after sortingfor (let x of v) document.write(x + \" \"); // This code is contributed by shinjanpatra</script>", "e": 4663, "s": 3791, "text": null }, { "code": null, "e": 4708, "s": 4663, "text": "for geeksforgeeks best is learning place the" }, { "code": null, "e": 4780, "s": 4710, "text": "Time Complexity: O(N * log(N)), where N is the size of the string str" }, { "code": null, "e": 4802, "s": 4780, "text": "Auxiliary Space: O(N)" }, { "code": null, "e": 4818, "s": 4802, "text": "dungeondragon22" }, { "code": null, "e": 4834, "s": 4818, "text": "subhammahato348" }, { "code": null, "e": 4850, "s": 4834, "text": "simranarora5sos" }, { "code": null, "e": 4863, "s": 4850, "text": "shinjanpatra" }, { "code": null, "e": 4887, "s": 4863, "text": "Advanced Data Structure" }, { "code": null, "e": 4898, "s": 4887, "text": "Algorithms" }, { "code": null, "e": 4922, "s": 4898, "text": "Competitive Programming" }, { "code": null, "e": 4938, "s": 4922, "text": "Data Structures" }, { "code": null, "e": 4943, "s": 4938, "text": "Hash" }, { "code": null, "e": 4951, "s": 4943, "text": "Sorting" }, { "code": null, "e": 4967, "s": 4951, "text": "Data Structures" }, { "code": null, "e": 4972, "s": 4967, "text": "Hash" }, { "code": null, "e": 4980, "s": 4972, "text": "Sorting" }, { "code": null, "e": 4991, "s": 4980, "text": "Algorithms" }, { "code": null, "e": 5089, "s": 4991, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5123, "s": 5089, "text": "Agents in Artificial Intelligence" }, { "code": null, "e": 5163, "s": 5123, "text": "Decision Tree Introduction with example" }, { "code": null, "e": 5205, "s": 5163, "text": "Segment Tree | Set 1 (Sum of given range)" }, { "code": null, "e": 5241, "s": 5205, "text": "Binary Indexed Tree or Fenwick Tree" }, { "code": null, "e": 5269, "s": 5241, "text": "AVL Tree | Set 2 (Deletion)" }, { "code": null, "e": 5294, "s": 5269, "text": "DSA Sheet by Love Babbar" }, { "code": null, "e": 5343, "s": 5294, "text": "SDE SHEET - A Complete Guide for SDE Preparation" }, { "code": null, "e": 5387, "s": 5343, "text": "Top 50 Array Coding Problems for Interviews" } ]
PHP | count() Function
23 May, 2022 This inbuilt function of PHP is used to count the current elements in the array. The function might return 0 for the variable that has been set to an empty array. Also for the variable which is not set the function returns 0. Syntax: count($array, mode) Parameters: The function generally takes one parameter that is the array for which the elements is needed to be counted. But in addition, the function can take a parameter mode which tells the function to count element in which normal or recursive mode. $array (mandatory) : Refers to the array, whose elements are needed to be counted.mode (optional) : This is used to set the mode of the function. The parameter can take two possible values, either 0 or 1. 1 generally indicates to count the values of the array recursively. This helps in counting the multidimensional array. The default value is 0 or False. $array (mandatory) : Refers to the array, whose elements are needed to be counted. mode (optional) : This is used to set the mode of the function. The parameter can take two possible values, either 0 or 1. 1 generally indicates to count the values of the array recursively. This helps in counting the multidimensional array. The default value is 0 or False. Return Values: The function returns the number of elements in an array. Below programs will help in understanding the working of count() function. Program 1: Counting normally, that is passing mode as 0 or not passing the parameter mode. PHP <?php // PHP program to illustrate working of count()$array = array("Aakash", "Ravi", "Prashant", "49", "50"); print_r(count($array)); ?> Output: 5 Program 2: Counting recursively or passing mode as 1. PHP <?php // PHP program to illustrate working of count()$array = array('names' => array('Aakash', 'Ravi', 'Prashant'), 'rollno' => array('5', '10', '15')); // recursive count - mode as 1echo("Recursive count: ".count($array,1)."\n"); // normal count - mode as 0echo("Normal count: ".count($array,0)."\n"); ?> Output: Recursive count: 8 Normal count: 2 Reference: http://php.net/manual/en/function.count.php simmytarika5 PHP-array PHP-function PHP Web Technologies PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to fetch data from localserver database and display on HTML table using PHP ? Difference between HTTP GET and POST Methods Different ways for passing data to view in Laravel PHP | file_exists( ) Function PHP | Ternary Operator Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ?
[ { "code": null, "e": 28, "s": 0, "text": "\n23 May, 2022" }, { "code": null, "e": 255, "s": 28, "text": "This inbuilt function of PHP is used to count the current elements in the array. The function might return 0 for the variable that has been set to an empty array. Also for the variable which is not set the function returns 0. " }, { "code": null, "e": 263, "s": 255, "text": "Syntax:" }, { "code": null, "e": 283, "s": 263, "text": "count($array, mode)" }, { "code": null, "e": 537, "s": 283, "text": "Parameters: The function generally takes one parameter that is the array for which the elements is needed to be counted. But in addition, the function can take a parameter mode which tells the function to count element in which normal or recursive mode." }, { "code": null, "e": 894, "s": 537, "text": "$array (mandatory) : Refers to the array, whose elements are needed to be counted.mode (optional) : This is used to set the mode of the function. The parameter can take two possible values, either 0 or 1. 1 generally indicates to count the values of the array recursively. This helps in counting the multidimensional array. The default value is 0 or False." }, { "code": null, "e": 977, "s": 894, "text": "$array (mandatory) : Refers to the array, whose elements are needed to be counted." }, { "code": null, "e": 1252, "s": 977, "text": "mode (optional) : This is used to set the mode of the function. The parameter can take two possible values, either 0 or 1. 1 generally indicates to count the values of the array recursively. This helps in counting the multidimensional array. The default value is 0 or False." }, { "code": null, "e": 1400, "s": 1252, "text": "Return Values: The function returns the number of elements in an array. Below programs will help in understanding the working of count() function. " }, { "code": null, "e": 1492, "s": 1400, "text": "Program 1: Counting normally, that is passing mode as 0 or not passing the parameter mode. " }, { "code": null, "e": 1496, "s": 1492, "text": "PHP" }, { "code": "<?php // PHP program to illustrate working of count()$array = array(\"Aakash\", \"Ravi\", \"Prashant\", \"49\", \"50\"); print_r(count($array)); ?>", "e": 1634, "s": 1496, "text": null }, { "code": null, "e": 1642, "s": 1634, "text": "Output:" }, { "code": null, "e": 1644, "s": 1642, "text": "5" }, { "code": null, "e": 1699, "s": 1644, "text": "Program 2: Counting recursively or passing mode as 1. " }, { "code": null, "e": 1703, "s": 1699, "text": "PHP" }, { "code": "<?php // PHP program to illustrate working of count()$array = array('names' => array('Aakash', 'Ravi', 'Prashant'), 'rollno' => array('5', '10', '15')); // recursive count - mode as 1echo(\"Recursive count: \".count($array,1).\"\\n\"); // normal count - mode as 0echo(\"Normal count: \".count($array,0).\"\\n\"); ?>", "e": 2023, "s": 1703, "text": null }, { "code": null, "e": 2031, "s": 2023, "text": "Output:" }, { "code": null, "e": 2066, "s": 2031, "text": "Recursive count: 8\nNormal count: 2" }, { "code": null, "e": 2121, "s": 2066, "text": "Reference: http://php.net/manual/en/function.count.php" }, { "code": null, "e": 2134, "s": 2121, "text": "simmytarika5" }, { "code": null, "e": 2144, "s": 2134, "text": "PHP-array" }, { "code": null, "e": 2157, "s": 2144, "text": "PHP-function" }, { "code": null, "e": 2161, "s": 2157, "text": "PHP" }, { "code": null, "e": 2178, "s": 2161, "text": "Web Technologies" }, { "code": null, "e": 2182, "s": 2178, "text": "PHP" }, { "code": null, "e": 2280, "s": 2182, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2362, "s": 2280, "text": "How to fetch data from localserver database and display on HTML table using PHP ?" }, { "code": null, "e": 2407, "s": 2362, "text": "Difference between HTTP GET and POST Methods" }, { "code": null, "e": 2458, "s": 2407, "text": "Different ways for passing data to view in Laravel" }, { "code": null, "e": 2488, "s": 2458, "text": "PHP | file_exists( ) Function" }, { "code": null, "e": 2511, "s": 2488, "text": "PHP | Ternary Operator" }, { "code": null, "e": 2544, "s": 2511, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 2606, "s": 2544, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 2667, "s": 2606, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2717, "s": 2667, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Minimize Cost to reduce the Array to a single element by given operations
19 Jan, 2022 Given an array a[] consisting of N integers and an integer K, the task is to find the minimum cost to reduce the given array to a single element by choosing any pair of consecutive array elements and replace them by (a[i] + a[i+1]) for a cost K * (a[i] + a[i+1]). Examples: Input: a[] = {1, 2, 3}, K = 2 Output: 18 Explanation: Replacing {1, 2} by 3 modifies the array to {3, 3}. Cost 2 * 3 = 6 Replacing {3, 3} by 6 modifies the array to {6}. Cost 2 * 6 = 12 Therefore, the total cost is 18Input: a[] = {4, 5, 6, 7}, K = 3 Output: 132 Naive Approach: The simplest solution is to split the array into two halves, for every index and compute the cost of the two halves recursively and finally add their respective costs.Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ Program to implement// the above approach#include <bits/stdc++.h>using namespace std;#define inf 10000009 // Function to combine the sum of the two halvesint Combine(int a[], int i, int j){ int sum = 0; // Calculate the sum from i to j for (int l = i; l <= j; l++) sum += a[l]; return sum;} // Function to minimize the cost to// reduce the array to a single elementint minCost(int a[], int i, int j, int k){ if (i >= j) { // Base case // If n = 1 or n = 0 return 0; } // Initialize cost to maximum value int best_cost = inf; // Iterate through all possible indices // and find the best index // to combine the subproblems for (int pos = i; pos < j; pos++) { // Compute left subproblem int left = minCost(a, i, pos, k); // Compute right subproblem int right = minCost(a, pos + 1, j, k); // Calculate the best cost best_cost = min(best_cost, left + right + k * Combine(a, i, j)); } // Return the answer return best_cost;} // Driver codeint main(){ int n = 4; int a[] = { 4, 5, 6, 7 }; int k = 3; cout << minCost(a, 0, n - 1, k) << endl; return 0;} // This code is contributed by PrinciRaj1992 // Java Program to implement// the above approachimport java.io.*; class GFG { static int inf = 10000009; // Function to minimize the cost to // reduce the array to a single element public static int minCost(int a[], int i, int j, int k) { if (i >= j) { // Base case // If n = 1 or n = 0 return 0; } // Initialize cost to maximum value int best_cost = inf; // Iterate through all possible indices // and find the best index // to combine the subproblems for (int pos = i; pos < j; pos++) { // Compute left subproblem int left = minCost(a, i, pos, k); // Compute right subproblem int right = minCost(a, pos + 1, j, k); // Calculate the best cost best_cost = Math.min( best_cost, left + right + k * Combine(a, i, j)); } // Return the answer return best_cost; } // Function to combine the sum of the two halves public static int Combine(int a[], int i, int j) { int sum = 0; // Calculate the sum from i to j for (int l = i; l <= j; l++) sum += a[l]; return sum; } // Driver code public static void main(String[] args) { int n = 4; int a[] = { 4, 5, 6, 7 }; int k = 3; System.out.println(minCost(a, 0, n - 1, k)); }} # Python3 Program to implement# the above approachinf = 10000009; # Function to minimize the cost to# reduce the array to a single elementdef minCost(a, i, j, k): if (i >= j): # Base case # If n = 1 or n = 0 return 0; # Initialize cost to maximum value best_cost = inf; # Iterate through all possible indices # and find the best index # to combine the subproblems for pos in range(i, j): # Compute left subproblem left = minCost(a, i, pos, k); # Compute right subproblem right = minCost(a, pos + 1, j, k); # Calculate the best cost best_cost = min(best_cost, left + right + k * Combine(a, i, j)); # Return the answer return best_cost; # Function to combine# the sum of the two halvesdef Combine(a, i, j): sum = 0; # Calculate the sum from i to j for l in range(i, j + 1): sum += a[l]; return sum; # Driver codeif __name__ == '__main__': n = 4; a = [4, 5, 6, 7]; k = 3; print(minCost(a, 0, n - 1, k)); # This code is contributed by Amit Katiyar // C# Program to implement// the above approachusing System;class GFG{ static int inf = 10000009; // Function to minimize the cost to // reduce the array to a single element public static int minCost(int []a, int i, int j, int k) { if (i >= j) { // Base case // If n = 1 or n = 0 return 0; } // Initialize cost to maximum value int best_cost = inf; // Iterate through all possible indices // and find the best index // to combine the subproblems for (int pos = i; pos < j; pos++) { // Compute left subproblem int left = minCost(a, i, pos, k); // Compute right subproblem int right = minCost(a, pos + 1, j, k); // Calculate the best cost best_cost = Math.Min(best_cost, left + right + k * Combine(a, i, j)); } // Return the answer return best_cost; } // Function to combine the sum of the two halves public static int Combine(int []a, int i, int j) { int sum = 0; // Calculate the sum from i to j for (int l = i; l <= j; l++) sum += a[l]; return sum; } // Driver code public static void Main(String[] args) { int n = 4; int []a = { 4, 5, 6, 7 }; int k = 3; Console.WriteLine(minCost(a, 0, n - 1, k)); }} // This code is contributed by Rohit_ranjan <script> // JavaScript Program to implement// the above approachvar inf = 10000009; // Function to combine the sum of the two halvesfunction Combine(a, i, j){ var sum = 0; // Calculate the sum from i to j for (var l = i; l <= j; l++) sum += a[l]; return sum;} // Function to minimize the cost to// reduce the array to a single elementfunction minCost(a, i, j, k){ if (i >= j) { // Base case // If n = 1 or n = 0 return 0; } // Initialize cost to maximum value var best_cost = inf; // Iterate through all possible indices // and find the best index // to combine the subproblems for (var pos = i; pos < j; pos++) { // Compute left subproblem var left = minCost(a, i, pos, k); // Compute right subproblem var right = minCost(a, pos + 1, j, k); // Calculate the best cost best_cost = Math.min(best_cost, left + right + k * Combine(a, i, j)); } // Return the answer return best_cost;} // Driver code var n = 4;var a = [4, 5, 6, 7];var k = 3;document.write( minCost(a, 0, n - 1, k)); </script> 132 Time Complexity: O(2N) Auxiliary Space: O(1) Efficient Approach: To optimize the above approach, the idea is to use the concept of Dynamic Programming. Follow the steps below to solve the problem: Initialize a matrix dp[][] and such that dp[i][j] stores the sum from index i to j. Calculate sum(i, j) using Prefix Sum technique. Compute the sum of the two subproblems and update the cost with the minimum value. Store in dp[][] and return. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program for the above approach#include <bits/stdc++.h>using namespace std; int inf = 10000000; // Function to generate the cost using// Prefix Sum Array techniquevector<int> preprocess(vector<int> a, int n){ vector<int> p(n); p[0] = a[0]; for(int i = 1; i < n; i++) { p[i] = p[i - 1] + a[i]; } return p;} // Function to combine the sum of the// two subproblemsint Combine(vector<int> p, int i, int j){ if (i == 0) return p[j]; else return p[j] - p[i - 1];} // Function to minimize the cost to// add the array elements to a single elementint minCost(vector<int> a, int i, int j, int k, vector<int> prefix, vector<vector<int>> dp){ if (i >= j) return 0; // Check if the value is // already stored in the array if (dp[i][j] != -1) return dp[i][j]; int best_cost = inf; for(int pos = i; pos < j; pos++) { // Compute left subproblem int left = minCost(a, i, pos, k, prefix, dp); // Compute left subproblem int right = minCost(a, pos + 1, j, k, prefix, dp); // Calculate minimum cost best_cost = min(best_cost, left + right + (k * Combine(prefix, i, j))); } // Store the answer to // avoid recalculation return dp[i][j] = best_cost;} // Driver code int main(){ int n = 4; vector<int> a = { 4, 5, 6, 7 }; int k = 3; // Initialise dp array vector<vector<int>> dp; dp.resize(n + 1, vector<int>(n + 1)); for(int i = 0; i < n + 1; i++) { for(int j = 0; j < n + 1; j++) { dp[i][j] = -1; } } // Preprocessing the array vector<int> prefix = preprocess(a, n); cout << minCost(a, 0, n - 1, k, prefix, dp) << endl; return 0;} // This code is contributed by divyeshrabadiya07 // Java Program for the above approachimport java.util.*;public class Main { static int inf = 10000000; // Function to minimize the cost to // add the array elements to a single element public static int minCost(int a[], int i, int j, int k, int[] prefix, int[][] dp) { if (i >= j) return 0; // Check if the value is // already stored in the array if (dp[i][j] != -1) return dp[i][j]; int best_cost = inf; for (int pos = i; pos < j; pos++) { // Compute left subproblem int left = minCost(a, i, pos, k, prefix, dp); // Compute left subproblem int right = minCost(a, pos + 1, j, k, prefix, dp); // Calculate minimum cost best_cost = Math.min( best_cost, left + right + (k * Combine(prefix, i, j))); } // Store the answer to // avoid recalculation return dp[i][j] = best_cost; } // Function to generate the cost using // Prefix Sum Array technique public static int[] preprocess(int[] a, int n) { int p[] = new int[n]; p[0] = a[0]; for (int i = 1; i < n; i++) p[i] = p[i - 1] + a[i]; return p; } // Function to combine the sum of the two subproblems public static int Combine(int[] p, int i, int j) { if (i == 0) return p[j]; else return p[j] - p[i - 1]; } // Driver Code public static void main(String args[]) { int n = 4; int a[] = { 4, 5, 6, 7 }; int k = 3; // Initialise dp array int dp[][] = new int[n + 1][n + 1]; for (int i[] : dp) Arrays.fill(i, -1); // Preprocessing the array int prefix[] = preprocess(a, n); System.out.println( minCost(a, 0, n - 1, k, prefix, dp)); }} # Python3 program for the above approachinf = 10000000 # Function to minimize the cost to# add the array elements to a single elementdef minCost(a, i, j, k, prefix, dp): if (i >= j): return 0 # Check if the value is # already stored in the array if (dp[i][j] != -1): return dp[i][j] best_cost = inf for pos in range(i, j): # Compute left subproblem left = minCost(a, i, pos, k, prefix, dp) # Compute left subproblem right = minCost(a, pos + 1, j, k, prefix, dp) # Calculate minimum cost best_cost = min(best_cost, left + right + (k * Combine(prefix, i, j))) # Store the answer to # avoid recalculation dp[i][j] = best_cost return dp[i][j] # Function to generate the cost using# Prefix Sum Array techniquedef preprocess(a, n): p = [0] * n p[0] = a[0] for i in range(1, n): p[i] = p[i - 1] + a[i] return p # Function to combine the sum# of the two subproblemsdef Combine(p, i, j): if (i == 0): return p[j] else: return p[j] - p[i - 1] # Driver Codeif __name__ == "__main__": n = 4 a = [ 4, 5, 6, 7 ] k = 3 # Initialise dp array dp = [[-1 for x in range (n + 1)] for y in range (n + 1)] # Preprocessing the array prefix = preprocess(a, n) print(minCost(a, 0, n - 1, k, prefix, dp)) # This code is contributed by chitranayal // C# Program for the above approachusing System;class GFG{ static int inf = 10000000; // Function to minimize the cost to // add the array elements to a single element public static int minCost(int []a, int i, int j, int k, int[] prefix, int[,] dp) { if (i >= j) return 0; // Check if the value is // already stored in the array if (dp[i, j] != -1) return dp[i, j]; int best_cost = inf; for (int pos = i; pos < j; pos++) { // Compute left subproblem int left = minCost(a, i, pos, k, prefix, dp); // Compute left subproblem int right = minCost(a, pos + 1, j, k, prefix, dp); // Calculate minimum cost best_cost = Math.Min(best_cost, left + right + (k * Combine(prefix, i, j))); } // Store the answer to // avoid recalculation return dp[i, j] = best_cost; } // Function to generate the cost using // Prefix Sum Array technique public static int[] preprocess(int[] a, int n) { int []p = new int[n]; p[0] = a[0]; for (int i = 1; i < n; i++) p[i] = p[i - 1] + a[i]; return p; } // Function to combine the sum of the two subproblems public static int Combine(int[] p, int i, int j) { if (i == 0) return p[j]; else return p[j] - p[i - 1]; } // Driver Code public static void Main(String []args) { int n = 4; int []a = { 4, 5, 6, 7 }; int k = 3; // Initialise dp array int [,]dp = new int[n + 1, n + 1]; for(int i = 0; i < n + 1; i++) { for (int j = 0; j < n + 1; j++) { dp[i, j] = -1; } } // Preprocessing the array int []prefix = preprocess(a, n); Console.WriteLine(minCost(a, 0, n - 1, k, prefix, dp)); }} // This code is contributed by sapnasingh4991 <script> // JavaScript program for the above approach var inf = 10000000; // Function to generate the cost using// Prefix Sum Array techniquefunction preprocess(a, n){ var p = Array(n); p[0] = a[0]; for(var i = 1; i < n; i++) { p[i] = p[i - 1] + a[i]; } return p;} // Function to combine the sum of the// two subproblemsfunction Combine(p, i, j){ if (i == 0) return p[j]; else return p[j] - p[i - 1];} // Function to minimize the cost to// add the array elements to a single elementfunction minCost(a, i, j, k, prefix, dp){ if (i >= j) return 0; // Check if the value is // already stored in the array if (dp[i][j] != -1) return dp[i][j]; var best_cost = inf; for(var pos = i; pos < j; pos++) { // Compute left subproblem var left = minCost(a, i, pos, k, prefix, dp); // Compute left subproblem var right = minCost(a, pos + 1, j, k, prefix, dp); // Calculate minimum cost best_cost = Math.min(best_cost, left + right + (k * Combine(prefix, i, j))); } // Store the answer to // avoid recalculation return dp[i][j] = best_cost;} // Driver code var n = 4;var a = [4, 5, 6, 7];var k = 3;// Initialise dp arrayvar dp = Array.from(Array(n+1), ()=>Array(n+1).fill(-1)); // Preprocessing the arrayvar prefix = preprocess(a, n); document.write( minCost(a, 0, n - 1, k, prefix, dp)) </script> 132 Time Complexity: O(N2) Auxiliary Space: O(N2) Rohit_ranjan princiraj1992 sapnasingh4991 amit143katiyar ukasp divyeshrabadiya07 rutvik_56 rrrtnx khushboogoyal499 gabaa406 sumitgumber28 prefix-sum Arrays Dynamic Programming Recursion prefix-sum Arrays Dynamic Programming Recursion 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 0-1 Knapsack Problem | DP-10 Longest Common Subsequence | DP-4 Subset Sum Problem | DP-25 Longest Palindromic Substring | Set 1 Longest Increasing Subsequence | DP-3
[ { "code": null, "e": 54, "s": 26, "text": "\n19 Jan, 2022" }, { "code": null, "e": 318, "s": 54, "text": "Given an array a[] consisting of N integers and an integer K, the task is to find the minimum cost to reduce the given array to a single element by choosing any pair of consecutive array elements and replace them by (a[i] + a[i+1]) for a cost K * (a[i] + a[i+1])." }, { "code": null, "e": 328, "s": 318, "text": "Examples:" }, { "code": null, "e": 590, "s": 328, "text": "Input: a[] = {1, 2, 3}, K = 2 Output: 18 Explanation: Replacing {1, 2} by 3 modifies the array to {3, 3}. Cost 2 * 3 = 6 Replacing {3, 3} by 6 modifies the array to {6}. Cost 2 * 6 = 12 Therefore, the total cost is 18Input: a[] = {4, 5, 6, 7}, K = 3 Output: 132" }, { "code": null, "e": 825, "s": 590, "text": "Naive Approach: The simplest solution is to split the array into two halves, for every index and compute the cost of the two halves recursively and finally add their respective costs.Below is the implementation of the above approach: " }, { "code": null, "e": 829, "s": 825, "text": "C++" }, { "code": null, "e": 834, "s": 829, "text": "Java" }, { "code": null, "e": 842, "s": 834, "text": "Python3" }, { "code": null, "e": 845, "s": 842, "text": "C#" }, { "code": null, "e": 856, "s": 845, "text": "Javascript" }, { "code": "// C++ Program to implement// the above approach#include <bits/stdc++.h>using namespace std;#define inf 10000009 // Function to combine the sum of the two halvesint Combine(int a[], int i, int j){ int sum = 0; // Calculate the sum from i to j for (int l = i; l <= j; l++) sum += a[l]; return sum;} // Function to minimize the cost to// reduce the array to a single elementint minCost(int a[], int i, int j, int k){ if (i >= j) { // Base case // If n = 1 or n = 0 return 0; } // Initialize cost to maximum value int best_cost = inf; // Iterate through all possible indices // and find the best index // to combine the subproblems for (int pos = i; pos < j; pos++) { // Compute left subproblem int left = minCost(a, i, pos, k); // Compute right subproblem int right = minCost(a, pos + 1, j, k); // Calculate the best cost best_cost = min(best_cost, left + right + k * Combine(a, i, j)); } // Return the answer return best_cost;} // Driver codeint main(){ int n = 4; int a[] = { 4, 5, 6, 7 }; int k = 3; cout << minCost(a, 0, n - 1, k) << endl; return 0;} // This code is contributed by PrinciRaj1992", "e": 2134, "s": 856, "text": null }, { "code": "// Java Program to implement// the above approachimport java.io.*; class GFG { static int inf = 10000009; // Function to minimize the cost to // reduce the array to a single element public static int minCost(int a[], int i, int j, int k) { if (i >= j) { // Base case // If n = 1 or n = 0 return 0; } // Initialize cost to maximum value int best_cost = inf; // Iterate through all possible indices // and find the best index // to combine the subproblems for (int pos = i; pos < j; pos++) { // Compute left subproblem int left = minCost(a, i, pos, k); // Compute right subproblem int right = minCost(a, pos + 1, j, k); // Calculate the best cost best_cost = Math.min( best_cost, left + right + k * Combine(a, i, j)); } // Return the answer return best_cost; } // Function to combine the sum of the two halves public static int Combine(int a[], int i, int j) { int sum = 0; // Calculate the sum from i to j for (int l = i; l <= j; l++) sum += a[l]; return sum; } // Driver code public static void main(String[] args) { int n = 4; int a[] = { 4, 5, 6, 7 }; int k = 3; System.out.println(minCost(a, 0, n - 1, k)); }}", "e": 3606, "s": 2134, "text": null }, { "code": "# Python3 Program to implement# the above approachinf = 10000009; # Function to minimize the cost to# reduce the array to a single elementdef minCost(a, i, j, k): if (i >= j): # Base case # If n = 1 or n = 0 return 0; # Initialize cost to maximum value best_cost = inf; # Iterate through all possible indices # and find the best index # to combine the subproblems for pos in range(i, j): # Compute left subproblem left = minCost(a, i, pos, k); # Compute right subproblem right = minCost(a, pos + 1, j, k); # Calculate the best cost best_cost = min(best_cost, left + right + k * Combine(a, i, j)); # Return the answer return best_cost; # Function to combine# the sum of the two halvesdef Combine(a, i, j): sum = 0; # Calculate the sum from i to j for l in range(i, j + 1): sum += a[l]; return sum; # Driver codeif __name__ == '__main__': n = 4; a = [4, 5, 6, 7]; k = 3; print(minCost(a, 0, n - 1, k)); # This code is contributed by Amit Katiyar", "e": 4739, "s": 3606, "text": null }, { "code": "// C# Program to implement// the above approachusing System;class GFG{ static int inf = 10000009; // Function to minimize the cost to // reduce the array to a single element public static int minCost(int []a, int i, int j, int k) { if (i >= j) { // Base case // If n = 1 or n = 0 return 0; } // Initialize cost to maximum value int best_cost = inf; // Iterate through all possible indices // and find the best index // to combine the subproblems for (int pos = i; pos < j; pos++) { // Compute left subproblem int left = minCost(a, i, pos, k); // Compute right subproblem int right = minCost(a, pos + 1, j, k); // Calculate the best cost best_cost = Math.Min(best_cost, left + right + k * Combine(a, i, j)); } // Return the answer return best_cost; } // Function to combine the sum of the two halves public static int Combine(int []a, int i, int j) { int sum = 0; // Calculate the sum from i to j for (int l = i; l <= j; l++) sum += a[l]; return sum; } // Driver code public static void Main(String[] args) { int n = 4; int []a = { 4, 5, 6, 7 }; int k = 3; Console.WriteLine(minCost(a, 0, n - 1, k)); }} // This code is contributed by Rohit_ranjan", "e": 6107, "s": 4739, "text": null }, { "code": "<script> // JavaScript Program to implement// the above approachvar inf = 10000009; // Function to combine the sum of the two halvesfunction Combine(a, i, j){ var sum = 0; // Calculate the sum from i to j for (var l = i; l <= j; l++) sum += a[l]; return sum;} // Function to minimize the cost to// reduce the array to a single elementfunction minCost(a, i, j, k){ if (i >= j) { // Base case // If n = 1 or n = 0 return 0; } // Initialize cost to maximum value var best_cost = inf; // Iterate through all possible indices // and find the best index // to combine the subproblems for (var pos = i; pos < j; pos++) { // Compute left subproblem var left = minCost(a, i, pos, k); // Compute right subproblem var right = minCost(a, pos + 1, j, k); // Calculate the best cost best_cost = Math.min(best_cost, left + right + k * Combine(a, i, j)); } // Return the answer return best_cost;} // Driver code var n = 4;var a = [4, 5, 6, 7];var k = 3;document.write( minCost(a, 0, n - 1, k)); </script>", "e": 7261, "s": 6107, "text": null }, { "code": null, "e": 7265, "s": 7261, "text": "132" }, { "code": null, "e": 7313, "s": 7267, "text": "Time Complexity: O(2N) Auxiliary Space: O(1) " }, { "code": null, "e": 7465, "s": 7313, "text": "Efficient Approach: To optimize the above approach, the idea is to use the concept of Dynamic Programming. Follow the steps below to solve the problem:" }, { "code": null, "e": 7549, "s": 7465, "text": "Initialize a matrix dp[][] and such that dp[i][j] stores the sum from index i to j." }, { "code": null, "e": 7597, "s": 7549, "text": "Calculate sum(i, j) using Prefix Sum technique." }, { "code": null, "e": 7680, "s": 7597, "text": "Compute the sum of the two subproblems and update the cost with the minimum value." }, { "code": null, "e": 7708, "s": 7680, "text": "Store in dp[][] and return." }, { "code": null, "e": 7759, "s": 7708, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 7763, "s": 7759, "text": "C++" }, { "code": null, "e": 7768, "s": 7763, "text": "Java" }, { "code": null, "e": 7776, "s": 7768, "text": "Python3" }, { "code": null, "e": 7779, "s": 7776, "text": "C#" }, { "code": null, "e": 7790, "s": 7779, "text": "Javascript" }, { "code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; int inf = 10000000; // Function to generate the cost using// Prefix Sum Array techniquevector<int> preprocess(vector<int> a, int n){ vector<int> p(n); p[0] = a[0]; for(int i = 1; i < n; i++) { p[i] = p[i - 1] + a[i]; } return p;} // Function to combine the sum of the// two subproblemsint Combine(vector<int> p, int i, int j){ if (i == 0) return p[j]; else return p[j] - p[i - 1];} // Function to minimize the cost to// add the array elements to a single elementint minCost(vector<int> a, int i, int j, int k, vector<int> prefix, vector<vector<int>> dp){ if (i >= j) return 0; // Check if the value is // already stored in the array if (dp[i][j] != -1) return dp[i][j]; int best_cost = inf; for(int pos = i; pos < j; pos++) { // Compute left subproblem int left = minCost(a, i, pos, k, prefix, dp); // Compute left subproblem int right = minCost(a, pos + 1, j, k, prefix, dp); // Calculate minimum cost best_cost = min(best_cost, left + right + (k * Combine(prefix, i, j))); } // Store the answer to // avoid recalculation return dp[i][j] = best_cost;} // Driver code int main(){ int n = 4; vector<int> a = { 4, 5, 6, 7 }; int k = 3; // Initialise dp array vector<vector<int>> dp; dp.resize(n + 1, vector<int>(n + 1)); for(int i = 0; i < n + 1; i++) { for(int j = 0; j < n + 1; j++) { dp[i][j] = -1; } } // Preprocessing the array vector<int> prefix = preprocess(a, n); cout << minCost(a, 0, n - 1, k, prefix, dp) << endl; return 0;} // This code is contributed by divyeshrabadiya07", "e": 9689, "s": 7790, "text": null }, { "code": "// Java Program for the above approachimport java.util.*;public class Main { static int inf = 10000000; // Function to minimize the cost to // add the array elements to a single element public static int minCost(int a[], int i, int j, int k, int[] prefix, int[][] dp) { if (i >= j) return 0; // Check if the value is // already stored in the array if (dp[i][j] != -1) return dp[i][j]; int best_cost = inf; for (int pos = i; pos < j; pos++) { // Compute left subproblem int left = minCost(a, i, pos, k, prefix, dp); // Compute left subproblem int right = minCost(a, pos + 1, j, k, prefix, dp); // Calculate minimum cost best_cost = Math.min( best_cost, left + right + (k * Combine(prefix, i, j))); } // Store the answer to // avoid recalculation return dp[i][j] = best_cost; } // Function to generate the cost using // Prefix Sum Array technique public static int[] preprocess(int[] a, int n) { int p[] = new int[n]; p[0] = a[0]; for (int i = 1; i < n; i++) p[i] = p[i - 1] + a[i]; return p; } // Function to combine the sum of the two subproblems public static int Combine(int[] p, int i, int j) { if (i == 0) return p[j]; else return p[j] - p[i - 1]; } // Driver Code public static void main(String args[]) { int n = 4; int a[] = { 4, 5, 6, 7 }; int k = 3; // Initialise dp array int dp[][] = new int[n + 1][n + 1]; for (int i[] : dp) Arrays.fill(i, -1); // Preprocessing the array int prefix[] = preprocess(a, n); System.out.println( minCost(a, 0, n - 1, k, prefix, dp)); }}", "e": 11631, "s": 9689, "text": null }, { "code": "# Python3 program for the above approachinf = 10000000 # Function to minimize the cost to# add the array elements to a single elementdef minCost(a, i, j, k, prefix, dp): if (i >= j): return 0 # Check if the value is # already stored in the array if (dp[i][j] != -1): return dp[i][j] best_cost = inf for pos in range(i, j): # Compute left subproblem left = minCost(a, i, pos, k, prefix, dp) # Compute left subproblem right = minCost(a, pos + 1, j, k, prefix, dp) # Calculate minimum cost best_cost = min(best_cost, left + right + (k * Combine(prefix, i, j))) # Store the answer to # avoid recalculation dp[i][j] = best_cost return dp[i][j] # Function to generate the cost using# Prefix Sum Array techniquedef preprocess(a, n): p = [0] * n p[0] = a[0] for i in range(1, n): p[i] = p[i - 1] + a[i] return p # Function to combine the sum# of the two subproblemsdef Combine(p, i, j): if (i == 0): return p[j] else: return p[j] - p[i - 1] # Driver Codeif __name__ == \"__main__\": n = 4 a = [ 4, 5, 6, 7 ] k = 3 # Initialise dp array dp = [[-1 for x in range (n + 1)] for y in range (n + 1)] # Preprocessing the array prefix = preprocess(a, n) print(minCost(a, 0, n - 1, k, prefix, dp)) # This code is contributed by chitranayal", "e": 13155, "s": 11631, "text": null }, { "code": "// C# Program for the above approachusing System;class GFG{ static int inf = 10000000; // Function to minimize the cost to // add the array elements to a single element public static int minCost(int []a, int i, int j, int k, int[] prefix, int[,] dp) { if (i >= j) return 0; // Check if the value is // already stored in the array if (dp[i, j] != -1) return dp[i, j]; int best_cost = inf; for (int pos = i; pos < j; pos++) { // Compute left subproblem int left = minCost(a, i, pos, k, prefix, dp); // Compute left subproblem int right = minCost(a, pos + 1, j, k, prefix, dp); // Calculate minimum cost best_cost = Math.Min(best_cost, left + right + (k * Combine(prefix, i, j))); } // Store the answer to // avoid recalculation return dp[i, j] = best_cost; } // Function to generate the cost using // Prefix Sum Array technique public static int[] preprocess(int[] a, int n) { int []p = new int[n]; p[0] = a[0]; for (int i = 1; i < n; i++) p[i] = p[i - 1] + a[i]; return p; } // Function to combine the sum of the two subproblems public static int Combine(int[] p, int i, int j) { if (i == 0) return p[j]; else return p[j] - p[i - 1]; } // Driver Code public static void Main(String []args) { int n = 4; int []a = { 4, 5, 6, 7 }; int k = 3; // Initialise dp array int [,]dp = new int[n + 1, n + 1]; for(int i = 0; i < n + 1; i++) { for (int j = 0; j < n + 1; j++) { dp[i, j] = -1; } } // Preprocessing the array int []prefix = preprocess(a, n); Console.WriteLine(minCost(a, 0, n - 1, k, prefix, dp)); }} // This code is contributed by sapnasingh4991", "e": 15004, "s": 13155, "text": null }, { "code": "<script> // JavaScript program for the above approach var inf = 10000000; // Function to generate the cost using// Prefix Sum Array techniquefunction preprocess(a, n){ var p = Array(n); p[0] = a[0]; for(var i = 1; i < n; i++) { p[i] = p[i - 1] + a[i]; } return p;} // Function to combine the sum of the// two subproblemsfunction Combine(p, i, j){ if (i == 0) return p[j]; else return p[j] - p[i - 1];} // Function to minimize the cost to// add the array elements to a single elementfunction minCost(a, i, j, k, prefix, dp){ if (i >= j) return 0; // Check if the value is // already stored in the array if (dp[i][j] != -1) return dp[i][j]; var best_cost = inf; for(var pos = i; pos < j; pos++) { // Compute left subproblem var left = minCost(a, i, pos, k, prefix, dp); // Compute left subproblem var right = minCost(a, pos + 1, j, k, prefix, dp); // Calculate minimum cost best_cost = Math.min(best_cost, left + right + (k * Combine(prefix, i, j))); } // Store the answer to // avoid recalculation return dp[i][j] = best_cost;} // Driver code var n = 4;var a = [4, 5, 6, 7];var k = 3;// Initialise dp arrayvar dp = Array.from(Array(n+1), ()=>Array(n+1).fill(-1)); // Preprocessing the arrayvar prefix = preprocess(a, n); document.write( minCost(a, 0, n - 1, k, prefix, dp)) </script>", "e": 16521, "s": 15004, "text": null }, { "code": null, "e": 16525, "s": 16521, "text": "132" }, { "code": null, "e": 16573, "s": 16527, "text": "Time Complexity: O(N2) Auxiliary Space: O(N2)" }, { "code": null, "e": 16586, "s": 16573, "text": "Rohit_ranjan" }, { "code": null, "e": 16600, "s": 16586, "text": "princiraj1992" }, { "code": null, "e": 16615, "s": 16600, "text": "sapnasingh4991" }, { "code": null, "e": 16630, "s": 16615, "text": "amit143katiyar" }, { "code": null, "e": 16636, "s": 16630, "text": "ukasp" }, { "code": null, "e": 16654, "s": 16636, "text": "divyeshrabadiya07" }, { "code": null, "e": 16664, "s": 16654, "text": "rutvik_56" }, { "code": null, "e": 16671, "s": 16664, "text": "rrrtnx" }, { "code": null, "e": 16688, "s": 16671, "text": "khushboogoyal499" }, { "code": null, "e": 16697, "s": 16688, "text": "gabaa406" }, { "code": null, "e": 16711, "s": 16697, "text": "sumitgumber28" }, { "code": null, "e": 16722, "s": 16711, "text": "prefix-sum" }, { "code": null, "e": 16729, "s": 16722, "text": "Arrays" }, { "code": null, "e": 16749, "s": 16729, "text": "Dynamic Programming" }, { "code": null, "e": 16759, "s": 16749, "text": "Recursion" }, { "code": null, "e": 16770, "s": 16759, "text": "prefix-sum" }, { "code": null, "e": 16777, "s": 16770, "text": "Arrays" }, { "code": null, "e": 16797, "s": 16777, "text": "Dynamic Programming" }, { "code": null, "e": 16807, "s": 16797, "text": "Recursion" }, { "code": null, "e": 16905, "s": 16807, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 16973, "s": 16905, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 17017, "s": 16973, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 17049, "s": 17017, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 17097, "s": 17049, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 17111, "s": 17097, "text": "Linear Search" }, { "code": null, "e": 17140, "s": 17111, "text": "0-1 Knapsack Problem | DP-10" }, { "code": null, "e": 17174, "s": 17140, "text": "Longest Common Subsequence | DP-4" }, { "code": null, "e": 17201, "s": 17174, "text": "Subset Sum Problem | DP-25" }, { "code": null, "e": 17239, "s": 17201, "text": "Longest Palindromic Substring | Set 1" } ]
Minimize the maximum distance between adjacent points after adding K points anywhere in between
26 May, 2022 Given an array arr[] of N integers representing the position of N points along a straight line and an integer K, the task is to find the minimum value of the maximum distance between adjacent points after adding K points anywhere in between, not necessarily on an integer position. Examples: Input: arr[] = {2, 4, 8, 10}, K = 1Output: 2Explanation: A point at position 6 can be added. So the new array of points become {2, 4, 6, 8, 10} and the maximum distance between two adjacent points is 2 which is minimum possible. Input: arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, K = 9Output: 0.5 Approach: The given problem can be solved by using Binary Search. The idea is to perform a binary search on the value D in the range [0, 108] where D represents the value of the maximum distance between the adjacent points after adding K points. Follow the steps below to solve the given problem: Initialize variables, low = 1 and high = 108, where low represents the lower bound and high represents the upper bound of the binary search. Create a function isPossible(), which returns the boolean value of whether it is possible to add K points in the array such that the maximum distance between adjacent points is D. It is based on the observation that for two adjacent points (i, j), the number of points required to be placed in their middle such that the maximum distance between them is D = (j -i)/D. Therefore, traverse the range using the binary search algorithm discussed here, and if for the mid-value D in the range [X, Y], if isPossible(D) is false, then iterate in the upper half of the range i.e, [D, Y]. Otherwise, iterate on the lower half i.e, [X, D]. Iterate a loop until (high – low) > 10-6. The value stored in low is the required answer. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program for the above approach#include <iostream>using namespace std; // Function to check if it is possible// to add K points such that the maximum// distance between adjacent points is Dbool isPossible(double D, int arr[], int N, int K){ // Stores the count of point used int used = 0; // Iterate over all given points for (int i = 0; i < N - 1; ++i) { // Add number of points required // to be placed between ith // and (i+1)th point used += (int)((arr[i + 1] - arr[i]) / D); } // Return answer return used <= K;} // Function to find the minimum value of// maximum distance between adjacent points// after adding K points any where betweendouble minMaxDist(int stations[], int N, int K){ // Stores the lower bound and upper // bound of the given range double low = 0, high = 1e8; // Perform binary search while (high - low > 1e-6) { // Find the middle value double mid = (low + high) / 2.0; if (isPossible(mid, stations, N, K)) { // Update the current range // to lower half high = mid; } // Update the current range // to upper half else { low = mid; } } return low;} // Driver Codeint main(){ int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; int K = 9; int N = sizeof(arr) / sizeof(arr[0]); cout << minMaxDist(arr, N, K); return 0;} // Java program for the above approachimport java.math.BigDecimal; class GFG { // Function to check if it is possible // to add K points such that the maximum // distance between adjacent points is D public static boolean isPossible(double D, int arr[], int N, int K) { // Stores the count of point used int used = 0; // Iterate over all given points for (int i = 0; i < N - 1; ++i) { // Add number of points required // to be placed between ith // and (i+1)th point used += (int) ((arr[i + 1] - arr[i]) / D); } // Return answer return used <= K; } // Function to find the minimum value of // maximum distance between adjacent points // after adding K points any where between public static double minMaxDist(int stations[], int N, int K) { // Stores the lower bound and upper // bound of the given range double low = 0, high = 1e8; // Perform binary search while (high - low > 1e-6) { // Find the middle value double mid = (low + high) / 2.0; if (isPossible(mid, stations, N, K)) { // Update the current range // to lower half high = mid; } // Update the current range // to upper half else { low = mid; } } // System.out.printf("Value: %.2f", low); return low; } // Driver Code public static void main(String args[]) { int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; int K = 9; int N = arr.length; System.out.printf("%.1f", minMaxDist(arr, N, K)); }} // This code is contributed by _saurabh_jaiswal. # Python3 program for the above approach # Function to check if it is possible# to add K points such that the maximum# distance between adjacent points is Ddef isPossible(D, arr, N, K) : # Stores the count of point used used = 0; # Iterate over all given points for i in range(N - 1) : # Add number of points required # to be placed between ith # and (i+1)th point used += int((arr[i + 1] - arr[i]) / D); # Return answer return used <= K; # Function to find the minimum value of# maximum distance between adjacent points# after adding K points any where betweendef minMaxDist(stations, N, K) : # Stores the lower bound and upper # bound of the given range low = 0; high = 1e8; # Perform binary search while (high - low > 1e-6) : # Find the middle value mid = (low + high) / 2.0; if (isPossible(mid, stations, N, K)) : # Update the current range # to lower half high = mid; # Update the current range # to upper half else : low = mid; return round(low, 2); # Driver Codeif __name__ == "__main__" : arr = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]; K = 9; N = len(arr); print(minMaxDist(arr, N, K)); # This code is contributed by AnkThon // C# program for the above approachusing System; public class GFG { // Function to check if it is possible // to add K points such that the maximum // distance between adjacent points is D public static bool isPossible(double D, int []arr, int N, int K) { // Stores the count of point used int used = 0; // Iterate over all given points for (int i = 0; i < N - 1; ++i) { // Add number of points required // to be placed between ith // and (i+1)th point used += (int) ((arr[i + 1] - arr[i]) / D); } // Return answer return used <= K; } // Function to find the minimum value of // maximum distance between adjacent points // after adding K points any where between public static double minMaxDist(int []stations, int N, int K) { // Stores the lower bound and upper // bound of the given range double low = 0, high = 1e8; // Perform binary search while (high - low > 1e-6) { // Find the middle value double mid = (low + high) / 2.0; if (isPossible(mid, stations, N, K)) { // Update the current range // to lower half high = mid; } // Update the current range // to upper half else { low = mid; } } // Console.Write("Value: %.2f", low); return low; } // Driver Code public static void Main(String []args) { int []arr = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; int K = 9; int N = arr.Length; Console.Write("{0:F1}", minMaxDist(arr, N, K)); }} // This code is contributed by 29AjayKumar <script> // JavaScript Program to implement // the above approach // Function to check if it is possible // to add K points such that the maximum // distance between adjacent points is D function isPossible(D, arr, N, K) { // Stores the count of point used let used = 0; // Iterate over all given points for (let i = 0; i < N - 1; ++i) { // Add number of points required // to be placed between ith // and (i+1)th point used += Math.floor((arr[i + 1] - arr[i]) / D); } // Return answer return used <= K; } // Function to find the minimum value of // maximum distance between adjacent points // after adding K points any where between function minMaxDist(stations, N, K) { // Stores the lower bound and upper // bound of the given range let low = 0, high = 1e8; // Perform binary search while (high - low > 1e-6) { // Find the middle value let mid = (low + high) / 2; if (isPossible(mid, stations, N, K)) { // Update the current range // to lower half high = mid; } // Update the current range // to upper half else { low = mid; } } return low.toFixed(1); } // Driver Code let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; let K = 9; let N = arr.length; document.write(minMaxDist(arr, N, K)); // This code is contributed by Potta Lokesh </script> 0.5 Time Complexity: O(N*log M), where the value of M is 1014.Auxiliary Space: O(1) Alternate Approach: The problem boils down to minimizing the maximum distance K times. Every time, to get the maximum distance we can use max heap. Step -1 : Iterate through the array elements and store the adjacent array element’s distances in a max heap. Step-2 : For K times, poll the max element from the heap and add to the heap max/2, max/2 i.e., we’re each time reducing the maximum distance to two equal halves. Step-3 : Return the max element after iterating for K times. Below is the implementation of the above approach: C++ Java Python3 #include<bits/stdc++.h>using namespace std; int main(){ int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; int K = 9; int N = sizeof(arr)/sizeof(arr[0]); // Max heap initialisation priority_queue<float>pq; // Add adjacent distances to max heap for (int i = 1; i < N; i++) { pq.push((float)arr[i] - (float)arr[i - 1]); } // For K times, half the maximum distance for (int i = 0; i < K; i++) { float temp = pq.top(); pq.pop(); pq.push(temp / 2); pq.push(temp / 2); } cout<<pq.top()<<endl; return 0;} // This code is contributed by shinjanpatra. import java.util.Collections;import java.util.PriorityQueue; class GFG { public static void main(String[] args) { int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; int K = 9; int N = arr.length; // Max heap initialisation PriorityQueue<Float> pq = new PriorityQueue<>( N + K, Collections.reverseOrder()); // Add adjacent distances to max heap for (int i = 1; i < N; i++) { pq.add((float)arr[i] - (float)arr[i - 1]); } // For K times, half the maximum distance for (int i = 0; i < K; i++) { float temp = pq.poll(); pq.add(temp / 2); pq.add(temp / 2); } System.out.println(pq.peek()); }}// This code is contributed by _govardhani # Python3 program for the above approach # importing "bisect" for bisection operationsimport bisect arr = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]K = 9N = len(arr) # Max heap initialisationpq = [] # Add adjacent distances to max heapfor i in range(1, N): bisect.insort(pq,float(arr[i])-float(arr[i-1])) # For K times, half the maximum distancefor i in range(K): temp=pq[0] pq.pop(0) pq.append(temp/2) pq.append(temp/2) print(pq[0]) # This code is contributed by Pushpesh Raj Time Complexity: O(NlogN)Auxiliary Space: O(N+K) lokeshpotta20 ankthon _saurabh_jaiswal 29AjayKumar govardhani rkbhola5 shinjanpatra pushpeshrajdx01 Binary Search Google Arrays Mathematical Searching Google Arrays Searching Mathematical Binary Search Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Introduction to Data Structures Window Sliding Technique Search, insert and delete in an unsorted array What is Data Structure: Types, Classifications and Applications Chocolate Distribution Problem Program for Fibonacci numbers Set in C++ Standard Template Library (STL) Write a program to print all permutations of a given string C++ Data Types Coin Change | DP-7
[ { "code": null, "e": 28, "s": 0, "text": "\n26 May, 2022" }, { "code": null, "e": 310, "s": 28, "text": "Given an array arr[] of N integers representing the position of N points along a straight line and an integer K, the task is to find the minimum value of the maximum distance between adjacent points after adding K points anywhere in between, not necessarily on an integer position." }, { "code": null, "e": 320, "s": 310, "text": "Examples:" }, { "code": null, "e": 549, "s": 320, "text": "Input: arr[] = {2, 4, 8, 10}, K = 1Output: 2Explanation: A point at position 6 can be added. So the new array of points become {2, 4, 6, 8, 10} and the maximum distance between two adjacent points is 2 which is minimum possible." }, { "code": null, "e": 614, "s": 549, "text": "Input: arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, K = 9Output: 0.5" }, { "code": null, "e": 911, "s": 614, "text": "Approach: The given problem can be solved by using Binary Search. The idea is to perform a binary search on the value D in the range [0, 108] where D represents the value of the maximum distance between the adjacent points after adding K points. Follow the steps below to solve the given problem:" }, { "code": null, "e": 1052, "s": 911, "text": "Initialize variables, low = 1 and high = 108, where low represents the lower bound and high represents the upper bound of the binary search." }, { "code": null, "e": 1420, "s": 1052, "text": "Create a function isPossible(), which returns the boolean value of whether it is possible to add K points in the array such that the maximum distance between adjacent points is D. It is based on the observation that for two adjacent points (i, j), the number of points required to be placed in their middle such that the maximum distance between them is D = (j -i)/D." }, { "code": null, "e": 1682, "s": 1420, "text": "Therefore, traverse the range using the binary search algorithm discussed here, and if for the mid-value D in the range [X, Y], if isPossible(D) is false, then iterate in the upper half of the range i.e, [D, Y]. Otherwise, iterate on the lower half i.e, [X, D]." }, { "code": null, "e": 1724, "s": 1682, "text": "Iterate a loop until (high – low) > 10-6." }, { "code": null, "e": 1772, "s": 1724, "text": "The value stored in low is the required answer." }, { "code": null, "e": 1823, "s": 1772, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 1827, "s": 1823, "text": "C++" }, { "code": null, "e": 1832, "s": 1827, "text": "Java" }, { "code": null, "e": 1840, "s": 1832, "text": "Python3" }, { "code": null, "e": 1843, "s": 1840, "text": "C#" }, { "code": null, "e": 1854, "s": 1843, "text": "Javascript" }, { "code": "// C++ program for the above approach#include <iostream>using namespace std; // Function to check if it is possible// to add K points such that the maximum// distance between adjacent points is Dbool isPossible(double D, int arr[], int N, int K){ // Stores the count of point used int used = 0; // Iterate over all given points for (int i = 0; i < N - 1; ++i) { // Add number of points required // to be placed between ith // and (i+1)th point used += (int)((arr[i + 1] - arr[i]) / D); } // Return answer return used <= K;} // Function to find the minimum value of// maximum distance between adjacent points// after adding K points any where betweendouble minMaxDist(int stations[], int N, int K){ // Stores the lower bound and upper // bound of the given range double low = 0, high = 1e8; // Perform binary search while (high - low > 1e-6) { // Find the middle value double mid = (low + high) / 2.0; if (isPossible(mid, stations, N, K)) { // Update the current range // to lower half high = mid; } // Update the current range // to upper half else { low = mid; } } return low;} // Driver Codeint main(){ int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; int K = 9; int N = sizeof(arr) / sizeof(arr[0]); cout << minMaxDist(arr, N, K); return 0;}", "e": 3351, "s": 1854, "text": null }, { "code": "// Java program for the above approachimport java.math.BigDecimal; class GFG { // Function to check if it is possible // to add K points such that the maximum // distance between adjacent points is D public static boolean isPossible(double D, int arr[], int N, int K) { // Stores the count of point used int used = 0; // Iterate over all given points for (int i = 0; i < N - 1; ++i) { // Add number of points required // to be placed between ith // and (i+1)th point used += (int) ((arr[i + 1] - arr[i]) / D); } // Return answer return used <= K; } // Function to find the minimum value of // maximum distance between adjacent points // after adding K points any where between public static double minMaxDist(int stations[], int N, int K) { // Stores the lower bound and upper // bound of the given range double low = 0, high = 1e8; // Perform binary search while (high - low > 1e-6) { // Find the middle value double mid = (low + high) / 2.0; if (isPossible(mid, stations, N, K)) { // Update the current range // to lower half high = mid; } // Update the current range // to upper half else { low = mid; } } // System.out.printf(\"Value: %.2f\", low); return low; } // Driver Code public static void main(String args[]) { int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; int K = 9; int N = arr.length; System.out.printf(\"%.1f\", minMaxDist(arr, N, K)); }} // This code is contributed by _saurabh_jaiswal.", "e": 5187, "s": 3351, "text": null }, { "code": "# Python3 program for the above approach # Function to check if it is possible# to add K points such that the maximum# distance between adjacent points is Ddef isPossible(D, arr, N, K) : # Stores the count of point used used = 0; # Iterate over all given points for i in range(N - 1) : # Add number of points required # to be placed between ith # and (i+1)th point used += int((arr[i + 1] - arr[i]) / D); # Return answer return used <= K; # Function to find the minimum value of# maximum distance between adjacent points# after adding K points any where betweendef minMaxDist(stations, N, K) : # Stores the lower bound and upper # bound of the given range low = 0; high = 1e8; # Perform binary search while (high - low > 1e-6) : # Find the middle value mid = (low + high) / 2.0; if (isPossible(mid, stations, N, K)) : # Update the current range # to lower half high = mid; # Update the current range # to upper half else : low = mid; return round(low, 2); # Driver Codeif __name__ == \"__main__\" : arr = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]; K = 9; N = len(arr); print(minMaxDist(arr, N, K)); # This code is contributed by AnkThon", "e": 6514, "s": 5187, "text": null }, { "code": "// C# program for the above approachusing System; public class GFG { // Function to check if it is possible // to add K points such that the maximum // distance between adjacent points is D public static bool isPossible(double D, int []arr, int N, int K) { // Stores the count of point used int used = 0; // Iterate over all given points for (int i = 0; i < N - 1; ++i) { // Add number of points required // to be placed between ith // and (i+1)th point used += (int) ((arr[i + 1] - arr[i]) / D); } // Return answer return used <= K; } // Function to find the minimum value of // maximum distance between adjacent points // after adding K points any where between public static double minMaxDist(int []stations, int N, int K) { // Stores the lower bound and upper // bound of the given range double low = 0, high = 1e8; // Perform binary search while (high - low > 1e-6) { // Find the middle value double mid = (low + high) / 2.0; if (isPossible(mid, stations, N, K)) { // Update the current range // to lower half high = mid; } // Update the current range // to upper half else { low = mid; } } // Console.Write(\"Value: %.2f\", low); return low; } // Driver Code public static void Main(String []args) { int []arr = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; int K = 9; int N = arr.Length; Console.Write(\"{0:F1}\", minMaxDist(arr, N, K)); }} // This code is contributed by 29AjayKumar", "e": 8334, "s": 6514, "text": null }, { "code": "<script> // JavaScript Program to implement // the above approach // Function to check if it is possible // to add K points such that the maximum // distance between adjacent points is D function isPossible(D, arr, N, K) { // Stores the count of point used let used = 0; // Iterate over all given points for (let i = 0; i < N - 1; ++i) { // Add number of points required // to be placed between ith // and (i+1)th point used += Math.floor((arr[i + 1] - arr[i]) / D); } // Return answer return used <= K; } // Function to find the minimum value of // maximum distance between adjacent points // after adding K points any where between function minMaxDist(stations, N, K) { // Stores the lower bound and upper // bound of the given range let low = 0, high = 1e8; // Perform binary search while (high - low > 1e-6) { // Find the middle value let mid = (low + high) / 2; if (isPossible(mid, stations, N, K)) { // Update the current range // to lower half high = mid; } // Update the current range // to upper half else { low = mid; } } return low.toFixed(1); } // Driver Code let arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; let K = 9; let N = arr.length; document.write(minMaxDist(arr, N, K)); // This code is contributed by Potta Lokesh </script>", "e": 10148, "s": 8334, "text": null }, { "code": null, "e": 10152, "s": 10148, "text": "0.5" }, { "code": null, "e": 10234, "s": 10154, "text": "Time Complexity: O(N*log M), where the value of M is 1014.Auxiliary Space: O(1)" }, { "code": null, "e": 10382, "s": 10234, "text": "Alternate Approach: The problem boils down to minimizing the maximum distance K times. Every time, to get the maximum distance we can use max heap." }, { "code": null, "e": 10491, "s": 10382, "text": "Step -1 : Iterate through the array elements and store the adjacent array element’s distances in a max heap." }, { "code": null, "e": 10654, "s": 10491, "text": "Step-2 : For K times, poll the max element from the heap and add to the heap max/2, max/2 i.e., we’re each time reducing the maximum distance to two equal halves." }, { "code": null, "e": 10715, "s": 10654, "text": "Step-3 : Return the max element after iterating for K times." }, { "code": null, "e": 10766, "s": 10715, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 10770, "s": 10766, "text": "C++" }, { "code": null, "e": 10775, "s": 10770, "text": "Java" }, { "code": null, "e": 10783, "s": 10775, "text": "Python3" }, { "code": "#include<bits/stdc++.h>using namespace std; int main(){ int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; int K = 9; int N = sizeof(arr)/sizeof(arr[0]); // Max heap initialisation priority_queue<float>pq; // Add adjacent distances to max heap for (int i = 1; i < N; i++) { pq.push((float)arr[i] - (float)arr[i - 1]); } // For K times, half the maximum distance for (int i = 0; i < K; i++) { float temp = pq.top(); pq.pop(); pq.push(temp / 2); pq.push(temp / 2); } cout<<pq.top()<<endl; return 0;} // This code is contributed by shinjanpatra.", "e": 11403, "s": 10783, "text": null }, { "code": "import java.util.Collections;import java.util.PriorityQueue; class GFG { public static void main(String[] args) { int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; int K = 9; int N = arr.length; // Max heap initialisation PriorityQueue<Float> pq = new PriorityQueue<>( N + K, Collections.reverseOrder()); // Add adjacent distances to max heap for (int i = 1; i < N; i++) { pq.add((float)arr[i] - (float)arr[i - 1]); } // For K times, half the maximum distance for (int i = 0; i < K; i++) { float temp = pq.poll(); pq.add(temp / 2); pq.add(temp / 2); } System.out.println(pq.peek()); }}// This code is contributed by _govardhani", "e": 12179, "s": 11403, "text": null }, { "code": "# Python3 program for the above approach # importing \"bisect\" for bisection operationsimport bisect arr = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]K = 9N = len(arr) # Max heap initialisationpq = [] # Add adjacent distances to max heapfor i in range(1, N): bisect.insort(pq,float(arr[i])-float(arr[i-1])) # For K times, half the maximum distancefor i in range(K): temp=pq[0] pq.pop(0) pq.append(temp/2) pq.append(temp/2) print(pq[0]) # This code is contributed by Pushpesh Raj", "e": 12662, "s": 12179, "text": null }, { "code": null, "e": 12711, "s": 12662, "text": "Time Complexity: O(NlogN)Auxiliary Space: O(N+K)" }, { "code": null, "e": 12725, "s": 12711, "text": "lokeshpotta20" }, { "code": null, "e": 12733, "s": 12725, "text": "ankthon" }, { "code": null, "e": 12750, "s": 12733, "text": "_saurabh_jaiswal" }, { "code": null, "e": 12762, "s": 12750, "text": "29AjayKumar" }, { "code": null, "e": 12773, "s": 12762, "text": "govardhani" }, { "code": null, "e": 12782, "s": 12773, "text": "rkbhola5" }, { "code": null, "e": 12795, "s": 12782, "text": "shinjanpatra" }, { "code": null, "e": 12811, "s": 12795, "text": "pushpeshrajdx01" }, { "code": null, "e": 12825, "s": 12811, "text": "Binary Search" }, { "code": null, "e": 12832, "s": 12825, "text": "Google" }, { "code": null, "e": 12839, "s": 12832, "text": "Arrays" }, { "code": null, "e": 12852, "s": 12839, "text": "Mathematical" }, { "code": null, "e": 12862, "s": 12852, "text": "Searching" }, { "code": null, "e": 12869, "s": 12862, "text": "Google" }, { "code": null, "e": 12876, "s": 12869, "text": "Arrays" }, { "code": null, "e": 12886, "s": 12876, "text": "Searching" }, { "code": null, "e": 12899, "s": 12886, "text": "Mathematical" }, { "code": null, "e": 12913, "s": 12899, "text": "Binary Search" }, { "code": null, "e": 13011, "s": 12913, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 13043, "s": 13011, "text": "Introduction to Data Structures" }, { "code": null, "e": 13068, "s": 13043, "text": "Window Sliding Technique" }, { "code": null, "e": 13115, "s": 13068, "text": "Search, insert and delete in an unsorted array" }, { "code": null, "e": 13179, "s": 13115, "text": "What is Data Structure: Types, Classifications and Applications" }, { "code": null, "e": 13210, "s": 13179, "text": "Chocolate Distribution Problem" }, { "code": null, "e": 13240, "s": 13210, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 13283, "s": 13240, "text": "Set in C++ Standard Template Library (STL)" }, { "code": null, "e": 13343, "s": 13283, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 13358, "s": 13343, "text": "C++ Data Types" } ]
Calculate standard deviation of a dictionary in Python
31 Aug, 2021 Python dictionary is a versatile data structure that allows a lot of operations to be done without any hassle. Calculating the standard deviation is shown below. Example #1: Using numpy.std() First, we create a dictionary. Then we store all the values in a list by iterating over it. After this using the NumPy we calculate the standard deviation of the list. Python3 # importing numpyimport numpy as np # creating our test dictionarydicti = {'a': 20, 'b': 32, 'c': 12, 'd': 93, 'e': 84} # declaring an empty listlistr = [] # appending all the values in the listfor value in dicti.values(): listr.append(value) # calculating standard deviation using np.stdstd = np.std(listr) # printing resultsprint(std) Output: 33.63569532505609 Example #2: Using list comprehension First, we create a list of values from the dictionary using a loop. Then we calculate mean, variance and then the standard deviation. Python3 # creating our test dictionarydicti = {'a': 20, 'b': 32, 'c': 12, 'd': 93, 'e': 84} # declaring an empty listlistr = [] # appending all the values in the listfor value in dicti.values(): listr.append(value) # Standard deviation of list# Using sum() + list comprehensionmean = sum(listr) / len(listr)variance = sum([((x - mean) ** 2) for x in listr]) / len(listr)res = variance ** 0.5print(res) Output: 33.63569532505609 Example #3: Using pstdev() Pythons inbuilt statistics library provides a function to compute the standard deviation of a given list. Python3 # importing the moduleimport statistics # creating the test dictionarydicti = {'a': 20, 'b': 32, 'c': 12, 'd': 93, 'e': 84} # declaring an empty listlistr = [] # appending all the values in the listfor value in dicti.values(): listr.append(value) # Standard deviation of list# Using pstdev()res = statistics.pstdev(listr)print(res) Output: 33.63569532505609 kalrap615 Python dictionary-programs Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Python | os.path.join() method 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": "\n31 Aug, 2021" }, { "code": null, "e": 190, "s": 28, "text": "Python dictionary is a versatile data structure that allows a lot of operations to be done without any hassle. Calculating the standard deviation is shown below." }, { "code": null, "e": 220, "s": 190, "text": "Example #1: Using numpy.std()" }, { "code": null, "e": 388, "s": 220, "text": "First, we create a dictionary. Then we store all the values in a list by iterating over it. After this using the NumPy we calculate the standard deviation of the list." }, { "code": null, "e": 396, "s": 388, "text": "Python3" }, { "code": "# importing numpyimport numpy as np # creating our test dictionarydicti = {'a': 20, 'b': 32, 'c': 12, 'd': 93, 'e': 84} # declaring an empty listlistr = [] # appending all the values in the listfor value in dicti.values(): listr.append(value) # calculating standard deviation using np.stdstd = np.std(listr) # printing resultsprint(std)", "e": 760, "s": 396, "text": null }, { "code": null, "e": 769, "s": 760, "text": "Output: " }, { "code": null, "e": 789, "s": 769, "text": "33.63569532505609 " }, { "code": null, "e": 826, "s": 789, "text": "Example #2: Using list comprehension" }, { "code": null, "e": 960, "s": 826, "text": "First, we create a list of values from the dictionary using a loop. Then we calculate mean, variance and then the standard deviation." }, { "code": null, "e": 968, "s": 960, "text": "Python3" }, { "code": "# creating our test dictionarydicti = {'a': 20, 'b': 32, 'c': 12, 'd': 93, 'e': 84} # declaring an empty listlistr = [] # appending all the values in the listfor value in dicti.values(): listr.append(value) # Standard deviation of list# Using sum() + list comprehensionmean = sum(listr) / len(listr)variance = sum([((x - mean) ** 2) for x in listr]) / len(listr)res = variance ** 0.5print(res)", "e": 1365, "s": 968, "text": null }, { "code": null, "e": 1374, "s": 1365, "text": "Output: " }, { "code": null, "e": 1394, "s": 1374, "text": "33.63569532505609 " }, { "code": null, "e": 1421, "s": 1394, "text": "Example #3: Using pstdev()" }, { "code": null, "e": 1527, "s": 1421, "text": "Pythons inbuilt statistics library provides a function to compute the standard deviation of a given list." }, { "code": null, "e": 1535, "s": 1527, "text": "Python3" }, { "code": "# importing the moduleimport statistics # creating the test dictionarydicti = {'a': 20, 'b': 32, 'c': 12, 'd': 93, 'e': 84} # declaring an empty listlistr = [] # appending all the values in the listfor value in dicti.values(): listr.append(value) # Standard deviation of list# Using pstdev()res = statistics.pstdev(listr)print(res)", "e": 1870, "s": 1535, "text": null }, { "code": null, "e": 1879, "s": 1870, "text": "Output: " }, { "code": null, "e": 1897, "s": 1879, "text": "33.63569532505609" }, { "code": null, "e": 1907, "s": 1897, "text": "kalrap615" }, { "code": null, "e": 1934, "s": 1907, "text": "Python dictionary-programs" }, { "code": null, "e": 1941, "s": 1934, "text": "Python" }, { "code": null, "e": 2039, "s": 1941, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2071, "s": 2039, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2098, "s": 2071, "text": "Python Classes and Objects" }, { "code": null, "e": 2119, "s": 2098, "text": "Python OOPs Concepts" }, { "code": null, "e": 2150, "s": 2119, "text": "Python | os.path.join() method" }, { "code": null, "e": 2206, "s": 2150, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 2229, "s": 2206, "text": "Introduction To PYTHON" }, { "code": null, "e": 2271, "s": 2229, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 2313, "s": 2271, "text": "Check if element exists in list in Python" }, { "code": null, "e": 2352, "s": 2313, "text": "Python | datetime.timedelta() function" } ]
JavaScript | History object
09 Jul, 2018 The window.history object contains the browsers history. First of all, window part can be removed from window.history just using history object alone works fine. The JS history object contains an array of URLs visited by the user. By using history object, you can load previous, forward or any particular page using various methods.Property of JavaScript history object : length: It returns the length of the history URLs visited by user in that session. Methods of JavaScript history object : forward(): It loads the next page. Provides a same effect as clicking back in the browser. back(): It loads the previous page. Provides a same effect as clicking forward in the browser. go(): It loads the given page number in browser. history.go(distance) function provides a same effect as pressing the back or forward button in your browser and specifying the page exactly which you want to load. JavaScript code to show the working of history.back() function:Code #1: <html><head><title>GeeksforGeeks back() example</title></head><body><b>Press the back button</b><input type="button" value="Back" onclick="previousPage()"><script>function previousPage() { window.history.back();}</script></body></html> Output: Press the back button Back Click here to see the effect of the codeNote : This example will not work if the previous page does not exist in the history list.If you click the above link then new page opens and when you press back button on that page it will redirects to that page which you opened previously. JavaScript code to show the working of history.forward() function:Code #2 : <html><head><title>GeeksforGeeks forward() example</title></head><body><b>Press the forward button</b><input type="button" value="Forward" onclick="NextPage()"><script>function NextPage() { window.history.forward()}</script></body></html> Press the forward button Forward Note : This example will not work if the next page does not exist in the history list. This code can be used when you want to use the forward button in your webpage. It works exactly same as forwarding button of your browser. If the next page doesn’t exist it will not work. JavaScript code to show the working of history.go() function:go(4) has the same effect as pressing your forward button four times.A negative value will move you backwards through your history in a browser.go(-4) has the same effect as pressing your back button four times.Code #3: <html><head><title>GeeksforGeeks go() example</title></head><body><input type="button" value="go" onclick="NextPage()"><script>function NextPage() { window.history.go(4);}</script></body></html> Note : This example will not work if the next four pages do not exist in the history list. javascript-object JavaScript 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 Roadmap to Learn JavaScript For Beginners Difference Between PUT and PATCH Request JavaScript | Promises How to filter object array based on attributes? Lodash _.debounce() Method JavaScript String includes() Method JavaScript | fetch() Method How to map, reduce and filter a Set element using JavaScript ?
[ { "code": null, "e": 52, "s": 24, "text": "\n09 Jul, 2018" }, { "code": null, "e": 424, "s": 52, "text": "The window.history object contains the browsers history. First of all, window part can be removed from window.history just using history object alone works fine. The JS history object contains an array of URLs visited by the user. By using history object, you can load previous, forward or any particular page using various methods.Property of JavaScript history object :" }, { "code": null, "e": 507, "s": 424, "text": "length: It returns the length of the history URLs visited by user in that session." }, { "code": null, "e": 546, "s": 507, "text": "Methods of JavaScript history object :" }, { "code": null, "e": 637, "s": 546, "text": "forward(): It loads the next page. Provides a same effect as clicking back in the browser." }, { "code": null, "e": 732, "s": 637, "text": "back(): It loads the previous page. Provides a same effect as clicking forward in the browser." }, { "code": null, "e": 945, "s": 732, "text": "go(): It loads the given page number in browser. history.go(distance) function provides a same effect as pressing the back or forward button in your browser and specifying the page exactly which you want to load." }, { "code": null, "e": 1017, "s": 945, "text": "JavaScript code to show the working of history.back() function:Code #1:" }, { "code": "<html><head><title>GeeksforGeeks back() example</title></head><body><b>Press the back button</b><input type=\"button\" value=\"Back\" onclick=\"previousPage()\"><script>function previousPage() { window.history.back();}</script></body></html> ", "e": 1257, "s": 1017, "text": null }, { "code": null, "e": 1265, "s": 1257, "text": "Output:" }, { "code": null, "e": 1293, "s": 1265, "text": "Press the back button Back\n" }, { "code": null, "e": 1575, "s": 1293, "text": "Click here to see the effect of the codeNote : This example will not work if the previous page does not exist in the history list.If you click the above link then new page opens and when you press back button on that page it will redirects to that page which you opened previously." }, { "code": null, "e": 1651, "s": 1575, "text": "JavaScript code to show the working of history.forward() function:Code #2 :" }, { "code": "<html><head><title>GeeksforGeeks forward() example</title></head><body><b>Press the forward button</b><input type=\"button\" value=\"Forward\" onclick=\"NextPage()\"><script>function NextPage() { window.history.forward()}</script></body></html>", "e": 1893, "s": 1651, "text": null }, { "code": null, "e": 1927, "s": 1893, "text": "Press the forward button Forward\n" }, { "code": null, "e": 2202, "s": 1927, "text": "Note : This example will not work if the next page does not exist in the history list. This code can be used when you want to use the forward button in your webpage. It works exactly same as forwarding button of your browser. If the next page doesn’t exist it will not work." }, { "code": null, "e": 2483, "s": 2202, "text": "JavaScript code to show the working of history.go() function:go(4) has the same effect as pressing your forward button four times.A negative value will move you backwards through your history in a browser.go(-4) has the same effect as pressing your back button four times.Code #3:" }, { "code": "<html><head><title>GeeksforGeeks go() example</title></head><body><input type=\"button\" value=\"go\" onclick=\"NextPage()\"><script>function NextPage() { window.history.go(4);}</script></body></html> ", "e": 2682, "s": 2483, "text": null }, { "code": null, "e": 2773, "s": 2682, "text": "Note : This example will not work if the next four pages do not exist in the history list." }, { "code": null, "e": 2791, "s": 2773, "text": "javascript-object" }, { "code": null, "e": 2802, "s": 2791, "text": "JavaScript" }, { "code": null, "e": 2900, "s": 2802, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2961, "s": 2900, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 3001, "s": 2961, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 3043, "s": 3001, "text": "Roadmap to Learn JavaScript For Beginners" }, { "code": null, "e": 3084, "s": 3043, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 3106, "s": 3084, "text": "JavaScript | Promises" }, { "code": null, "e": 3154, "s": 3106, "text": "How to filter object array based on attributes?" }, { "code": null, "e": 3181, "s": 3154, "text": "Lodash _.debounce() Method" }, { "code": null, "e": 3217, "s": 3181, "text": "JavaScript String includes() Method" }, { "code": null, "e": 3245, "s": 3217, "text": "JavaScript | fetch() Method" } ]
Sort array after converting elements to their squares
08 Jul, 2022 Given an array of both positive and negative integers ‘arr[]’ which are sorted. The task is to sort the square of the numbers of the Array. Examples: Input : arr[] = {-6, -3, -1, 2, 4, 5} Output : 1, 4, 9, 16, 25, 36 Input : arr[] = {-5, -4, -2, 0, 1} Output : 0, 1, 4, 16, 25 Simple solution is to first convert each array element into its square and then apply any “O(nlogn)” sorting algorithm to sort the array elements. Below is the implementation of the above idea C++ Java Python3 C# Javascript // C++ program to Sort square of the numbers// of the array#include <bits/stdc++.h>using namespace std; // Function to sort an square arrayvoid sortSquares(int arr[], int n){ // First convert each array elements // into its square for (int i = 0; i < n; i++) arr[i] = arr[i] * arr[i]; // Sort an array using "sort STL function " sort(arr, arr + n);} // Driver program to test above functionint main(){ int arr[] = { -6, -3, -1, 2, 4, 5 }; int n = sizeof(arr) / sizeof(arr[0]); cout << "Before sort " << endl; for (int i = 0; i < n; i++) cout << arr[i] << " "; sortSquares(arr, n); cout << "\nAfter Sort " << endl; for (int i = 0; i < n; i++) cout << arr[i] << " "; return 0;} // Java program to Sort square of the numbers// of the arrayimport java.util.*;import java.io.*; class GFG { // Function to sort an square array public static void sortSquares(int arr[]) { int n = arr.length; // First convert each array elements // into its square for (int i = 0; i < n; i++) arr[i] = arr[i] * arr[i]; // Sort an array using "inbuild sort function" // in Arrays class. Arrays.sort(arr); } // Driver program to test above function public static void main(String[] args) { int arr[] = { -6, -3, -1, 2, 4, 5 }; int n = arr.length; System.out.println("Before sort "); for (int i = 0; i < n; i++) System.out.print(arr[i] + " "); sortSquares(arr); System.out.println(""); System.out.println("After Sort "); for (int i = 0; i < n; i++) System.out.print(arr[i] + " "); }} # Python program to Sort square# of the numbers of the array # Function to sort an square arraydef sortSquare(arr, n): # First convert each array # elements into its square for i in range(n): arr[i]= arr[i] * arr[i] arr.sort() # Driver codearr = [-6, -3, -1, 2, 4, 5]n = len(arr) print("Before sort")for i in range(n): print(arr[i], end = " ") print("\n") sortSquare(arr, n) print("After sort")for i in range(n): print(arr[i], end = " ") # This code is contributed by# Shrikant13 // C# program to Sort square// of the numbers of the arrayusing System; class GFG { // Function to sort // an square array public static void sortSquares(int[] arr) { int n = arr.Length; // First convert each array // elements into its square for (int i = 0; i < n; i++) arr[i] = arr[i] * arr[i]; // Sort an array using // "inbuild sort function" // in Arrays class. Array.Sort(arr); } // Driver Code public static void Main() { int[] arr = { -6, -3, -1, 2, 4, 5 }; int n = arr.Length; Console.WriteLine("Before sort "); for (int i = 0; i < n; i++) Console.Write(arr[i] + " "); sortSquares(arr); Console.WriteLine(""); Console.WriteLine("After Sort "); for (int i = 0; i < n; i++) Console.Write(arr[i] + " "); }} // This code is contributed by anuj_67. <script> // JavaScript program for the above approach // Function to sort an square array function sortSquares(arr) { let n = arr.length; // First convert each array elements // into its square for (let i = 0; i < n; i++) arr[i] = arr[i] * arr[i]; // Sort an array using "inbuild sort function" // in Arrays class. arr.sort(); } // Driver Code let arr = [ -6, -3, -1, 2, 4, 5 ]; let n = arr.length; document.write("Before sort " + "<br/>"); for (let i = 0; i < n; i++) document.write(arr[i] + " "); sortSquares(arr); document.write("" + "<br/>"); document.write("After Sort " + "<br/>"); for (let i = 0; i < n; i++) document.write(arr[i] + " "); // This code is contributed by chinmoy1997pal.</script> Before sort -6 -3 -1 2 4 5 After Sort 1 4 9 16 25 36 Time complexity: O(n log n) Efficient solution is based on the fact that the given array is already sorted. We do the following two steps. Divide the array into two-part “Negative and positive “.Use merge function to merge two sorted arrays into a single sorted array. Divide the array into two-part “Negative and positive “. Use merge function to merge two sorted arrays into a single sorted array. Below is the implementation of the above idea. C++ Java Python3 C# Javascript // C++ program to Sort square of the numbers of the array#include <bits/stdc++.h>using namespace std; // function to sort array after doing squares of elementsvoid sortSquares(int arr[], int n){ // first divide array into negative and positive part int K = 0; for (K = 0; K < n; K++) if (arr[K] >= 0) break; // Now do the same process that we learnt // in merge sort to merge two sorted array // here both two half are sorted and we traverse // first half in reverse manner because // first half contains negative elements int i = K - 1; // Initial index of first half int j = K; // Initial index of second half int ind = 0; // Initial index of temp array // store sorted array int temp[n]; while (i >= 0 && j < n) { if (arr[i] * arr[i] < arr[j] * arr[j]) { temp[ind] = arr[i] * arr[i]; i--; } else { temp[ind] = arr[j] * arr[j]; j++; } ind++; } /* Copy the remaining elements of first half */ while (i >= 0) { temp[ind] = arr[i] * arr[i]; i--; ind++; } /* Copy the remaining elements of second half */ while (j < n) { temp[ind] = arr[j] * arr[j]; j++; ind++; } // copy 'temp' array into original array for (int i = 0; i < n; i++) arr[i] = temp[i];} // Driver program to test above functionint main(){ int arr[] = { -6, -3, -1, 2, 4, 5 }; int n = sizeof(arr) / sizeof(arr[0]); cout << "Before sort " << endl; for (int i = 0; i < n; i++) cout << arr[i] << " "; sortSquares(arr, n); cout << "\nAfter Sort " << endl; for (int i = 0; i < n; i++) cout << arr[i] << " "; return 0;} // Java program to Sort square of the numbers// of the arrayimport java.util.*;import java.io.*; class GFG { // Function to sort an square array public static void sortSquares(int arr[]) { int n = arr.length; // first divide the array into negative and positive part int k; for (k = 0; k < n; k++) { if (arr[k] >= 0) break; } // Now do the same process that we learnt // in merge sort to merge two sorted arrays // here both two halves are sorted and we traverse // first half in reverse manner because // first half contains negative elements int i = k - 1; // Initial index of first half int j = k; // Initial index of second half int ind = 0; // Initial index of temp array int[] temp = new int[n]; while (i >= 0 && j < n) { if (arr[i] * arr[i] < arr[j] * arr[j]) { temp[ind] = arr[i] * arr[i]; i--; } else { temp[ind] = arr[j] * arr[j]; j++; } ind++; } while (i >= 0) { temp[ind++] = arr[i] * arr[i]; i--; } while (j < n) { temp[ind++] = arr[j] * arr[j]; j++; } // copy 'temp' array into original array for (int x = 0; x < n; x++) arr[x] = temp[x]; } // Driver program to test above function public static void main(String[] args) { int arr[] = { -6, -3, -1, 2, 4, 5 }; int n = arr.length; System.out.println("Before sort "); for (int i = 0; i < n; i++) System.out.print(arr[i] + " "); sortSquares(arr); System.out.println(""); System.out.println("After Sort "); for (int i = 0; i < n; i++) System.out.print(arr[i] + " "); }} # Python3 program to Sort square of the numbers of the array # function to sort array after doing squares of elementsdef sortSquares(arr, n): # first divide array into negative and positive part K = 0 for K in range(n): if (arr[K] >= 0 ): break # Now do the same process that we learnt # in merge sort to merge to two sorted array # here both two halves are sorted and we traverse # first half in reverse manner because # first half contains negative elements i = K - 1 # Initial index of first half j = K # Initial index of second half ind = 0 # Initial index of temp array # store sorted array temp = [0]*n while (i >= 0 and j < n): if (arr[i] * arr[i] < arr[j] * arr[j]): temp[ind] = arr[i] * arr[i] i -= 1 else: temp[ind] = arr[j] * arr[j] j += 1 ind += 1 ''' Copy the remaining elements of first half ''' while (i >= 0): temp[ind] = arr[i] * arr[i] i -= 1 ind += 1 ''' Copy the remaining elements of second half ''' while (j < n): temp[ind] = arr[j] * arr[j] j += 1 ind += 1 # copy 'temp' array into original array for i in range(n): arr[i] = temp[i] # Driver codearr = [-6, -3, -1, 2, 4, 5 ]n = len(arr) print("Before sort ")for i in range(n): print(arr[i], end =" " ) sortSquares(arr, n)print("\nAfter Sort ")for i in range(n): print(arr[i], end =" " ) # This code is contributed by shubhamsingh10 // C# program to Sort square of the numbers// of the arrayusing System; class GFG { // Function to sort an square array public static void sortSquares(int[] arr) { int n = arr.Length; // first divide array into negative and positive part int k; for (k = 0; k < n; k++) { if (arr[k] >= 0) break; } // Now do the same process that we learnt // in merge sort to merge to two sorted array // here both two halves are sorted and we traverse // first half in reverse manner because // first half contains negative elements int i = k - 1; // Initial index of first half int j = k; // Initial index of second half int ind = 0; // Initial index of temp array int[] temp = new int[n]; while (i >= 0 && j < n) { if (arr[i] * arr[i] < arr[j] * arr[j]) { temp[ind] = arr[i] * arr[i]; i--; } else { temp[ind] = arr[j] * arr[j]; j++; } ind++; } while (i >= 0) { temp[ind++] = arr[i] * arr[i]; i--; } while (j < n) { temp[ind++] = arr[j] * arr[j]; j++; } // copy 'temp' array into original array for (int x = 0; x < n; x++) arr[x] = temp[x]; } // Driver code public static void Main(String[] args) { int[] arr = { -6, -3, -1, 2, 4, 5 }; int n = arr.Length; Console.WriteLine("Before sort "); for (int i = 0; i < n; i++) Console.Write(arr[i] + " "); sortSquares(arr); Console.WriteLine(""); Console.WriteLine("After Sort "); for (int i = 0; i < n; i++) Console.Write(arr[i] + " "); }} // This code is contributed by 29AjayKumar <script> // Javascript program to Sort// square of the numbers// of the array // Function to sort an square array function sortSquares(arr) { let n = arr.length; // first dived array into part // negative and positive let k; for (k = 0; k < n; k++) { if (arr[k] >= 0) break; } // Now do the same process that we learn // in merge sort to merge to two sorted array // here both two half are sorted and we traverse // first half in reverse meaner because // first half contain negative element let i = k - 1; // Initial index of first half let j = k; // Initial index of second half let ind = 0; // Initial index of temp array let temp = new Array(n); while (i >= 0 && j < n) { if (arr[i] * arr[i] < arr[j] * arr[j]) { temp[ind] = arr[i] * arr[i]; i--; } else { temp[ind] = arr[j] * arr[j]; j++; } ind++; } while (i >= 0) { temp[ind++] = arr[i] * arr[i]; i--; } while (j < n) { temp[ind++] = arr[j] * arr[j]; j++; } // copy 'temp' array into original array for (let x = 0; x < n; x++) arr[x] = temp[x]; } // Driver program to test above function let arr=[ -6, -3, -1, 2, 4, 5 ]; let n = arr.length; document.write("Before sort <br>"); for (let i = 0; i < n; i++) document.write(arr[i] + " "); sortSquares(arr); document.write("<br>"); document.write("After Sort <br>"); for (let i = 0; i < n; i++) document.write(arr[i] + " "); // This code is contributed by rag2127 </script> Before sort -6 -3 -1 2 4 5 After Sort 1 4 9 16 25 36 Time complexity: O(n) space complexity: O(n) Method 3:Another efficient solution is based on the two-pointer method as the array is already sorted we can compare the first and last element to check which is bigger and proceed with the result. Algorithm: Initialize left=0 and right=n-1 if abs(left) >= abs(right) then store square(arr[left])at the end of result array and increment left pointer else store square(arr[right]) in the result array and decrement right pointer decrement index of result array Implementation: C++ Java Python3 C# Javascript // CPP code for the above approach#include <bits/stdc++.h>using namespace std; // Function to sort an square arrayvoid sortSquares(vector<int>& arr, int n){ int left = 0, right = n - 1; int result[n]; // Iterate from n - 1 to 0 for (int index = n - 1; index >= 0; index--) { // Check if abs(arr[left]) is greater // than arr[right] if (abs(arr[left]) > arr[right]) { result[index] = arr[left] * arr[left]; left++; } else { result[index] = arr[right] * arr[right]; right--; } } for (int i = 0; i < n; i++) arr[i] = result[i];} // Driver Codeint main(){ vector<int> arr; arr.push_back(-6); arr.push_back(-3); arr.push_back(-1); arr.push_back(2); arr.push_back(4); arr.push_back(5); int n = 6; cout << "Before sort " << endl; for (int i = 0; i < n; i++) cout << arr[i] << " "; sortSquares(arr, n); cout << endl; cout << "After Sort " << endl; for (int i = 0; i < n; i++) cout << arr[i] << " "; return 0;} // this code is contributed by Manu Pathria // Java program to Sort square of// the numbers of the arrayimport java.util.*;import java.io.*; class GFG{ // Function to sort an square arraypublic static void sortSquares(int arr[]){ int n = arr.length, left = 0, right = n - 1; int result[] = new int[n]; for(int index = n - 1; index >= 0; index--) { if (Math.abs(arr[left]) > arr[right]) { result[index] = arr[left] * arr[left]; left++; } else { result[index] = arr[right] * arr[right]; right--; } } for(int i = 0; i < n; i++) arr[i] = result[i];} // Driver codepublic static void main(String[] args){ int arr[] = { -6, -3, -1, 2, 4, 5 }; int n = arr.length; System.out.println("Before sort "); for(int i = 0; i < n; i++) System.out.print(arr[i] + " "); sortSquares(arr); System.out.println(""); System.out.println("After Sort "); for(int i = 0; i < n; i++) System.out.print(arr[i] + " ");}} // This code is contributed by jinalparmar2382 # Python3 program to Sort square of the numbers of the array # function to sort array after doing squares of elementsdef sortSquares(arr, n): left, right = 0, n - 1 index = n - 1 result = [0 for x in arr] while index >= 0: if abs(arr[left]) >= abs(arr[right]): result[index] = arr[left] * arr[left] left += 1 else: result[index] = arr[right] * arr[right] right -= 1 index -= 1 for i in range(n): arr[i] = result[i] # Driver codearr = [-6, -3, -1, 2, 4, 5 ]n = len(arr) print("Before sort ")for i in range(n): print(arr[i], end =" " ) sortSquares(arr, n)print("\nAfter Sort ")for i in range(n): print(arr[i], end =" " ) // C# program to Sort square of// the numbers of the arrayusing System;class GFG{ // Function to sort an square arraypublic static void sortSquares(int [] arr){ int n = arr.Length, left = 0, right = n - 1; int []result = new int[n]; for(int index = n - 1; index >= 0; index--) { if (Math.Abs(arr[left]) > arr[right]) { result[index] = arr[left] * arr[left]; left++; } else { result[index] = arr[right] * arr[right]; right--; } } for(int i = 0; i < n; i++) arr[i] = result[i];} // Driver codepublic static void Main(string[] args){ int []arr = {-6, -3, -1, 2, 4, 5}; int n = arr.Length; Console.WriteLine("Before sort "); for(int i = 0; i < n; i++) Console.Write(arr[i] + " "); sortSquares(arr); Console.WriteLine(""); Console.WriteLine("After Sort "); for(int i = 0; i < n; i++) Console.Write(arr[i] + " ");}} // This code is contributed by Chitranayal <script> // This function squares each value in an array // and arranges the result in ascending order, using two pointers. // The first pointer points to the first element of the array, and the second // points to the last. On each iteration, each pointer is compared to the other // and the pointer which has the lowest value is shifted closer to the other. function sortSquares(arr) { let n = nums.length, left = 0, right = n -1, result = new Array(n) ; for (let i = n - 1; i >= 0; i--) { // Here, Math.abs() is used to convert any negative numbers to their // integer equivalent... i.e. -4 becomes 4. if (Math.abs(nums[left]) > Math.abs(nums[right])) { result[i] = nums[left] ** 2; left++; } else { result[i] = nums[right] **2; right--; } } return result; } let arr = [-6, -3, -1, 2, 4, 5]; let n = arr.length; document.write("Before sort " + "</br>"); for(let i = 0; i < n; i++) document.write(arr[i] + " "); sortSquares(arr); document.write("</br>"); document.write("After Sort " + "</br>"); for(let i = 0; i < n; i++) document.write(arr[i] + " "); // This code was contributed by rameshtravel07, then was edited by: Lewis Farnworth</script> Before sort -6 -3 -1 2 4 5 After Sort 1 4 9 16 25 36 Time complexity: O(n) Auxiliary Space: O(n) This article is contributed by Nishant singh. 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. shrikanth13 vt_m 29AjayKumar SHUBHAMSINGH10 skrish87 parmarjinal ukasp manupathria chinmoy1997pal rag2127 rameshtravel07 uppooraprajwal lewfar99 hardikkoriintern Arrays Sorting Arrays Sorting Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Introduction to Data Structures Search, insert and delete in an unsorted array Window Sliding Technique Chocolate Distribution Problem Find duplicates in O(n) time and O(1) extra space | Set 1 Merge Sort Bubble Sort Algorithm QuickSort Insertion Sort Selection Sort Algorithm
[ { "code": null, "e": 54, "s": 26, "text": "\n08 Jul, 2022" }, { "code": null, "e": 195, "s": 54, "text": "Given an array of both positive and negative integers ‘arr[]’ which are sorted. The task is to sort the square of the numbers of the Array. " }, { "code": null, "e": 206, "s": 195, "text": "Examples: " }, { "code": null, "e": 338, "s": 206, "text": "Input : arr[] = {-6, -3, -1, 2, 4, 5}\nOutput : 1, 4, 9, 16, 25, 36 \n\nInput : arr[] = {-5, -4, -2, 0, 1}\nOutput : 0, 1, 4, 16, 25" }, { "code": null, "e": 485, "s": 338, "text": "Simple solution is to first convert each array element into its square and then apply any “O(nlogn)” sorting algorithm to sort the array elements." }, { "code": null, "e": 533, "s": 485, "text": "Below is the implementation of the above idea " }, { "code": null, "e": 537, "s": 533, "text": "C++" }, { "code": null, "e": 542, "s": 537, "text": "Java" }, { "code": null, "e": 550, "s": 542, "text": "Python3" }, { "code": null, "e": 553, "s": 550, "text": "C#" }, { "code": null, "e": 564, "s": 553, "text": "Javascript" }, { "code": "// C++ program to Sort square of the numbers// of the array#include <bits/stdc++.h>using namespace std; // Function to sort an square arrayvoid sortSquares(int arr[], int n){ // First convert each array elements // into its square for (int i = 0; i < n; i++) arr[i] = arr[i] * arr[i]; // Sort an array using \"sort STL function \" sort(arr, arr + n);} // Driver program to test above functionint main(){ int arr[] = { -6, -3, -1, 2, 4, 5 }; int n = sizeof(arr) / sizeof(arr[0]); cout << \"Before sort \" << endl; for (int i = 0; i < n; i++) cout << arr[i] << \" \"; sortSquares(arr, n); cout << \"\\nAfter Sort \" << endl; for (int i = 0; i < n; i++) cout << arr[i] << \" \"; return 0;}", "e": 1304, "s": 564, "text": null }, { "code": "// Java program to Sort square of the numbers// of the arrayimport java.util.*;import java.io.*; class GFG { // Function to sort an square array public static void sortSquares(int arr[]) { int n = arr.length; // First convert each array elements // into its square for (int i = 0; i < n; i++) arr[i] = arr[i] * arr[i]; // Sort an array using \"inbuild sort function\" // in Arrays class. Arrays.sort(arr); } // Driver program to test above function public static void main(String[] args) { int arr[] = { -6, -3, -1, 2, 4, 5 }; int n = arr.length; System.out.println(\"Before sort \"); for (int i = 0; i < n; i++) System.out.print(arr[i] + \" \"); sortSquares(arr); System.out.println(\"\"); System.out.println(\"After Sort \"); for (int i = 0; i < n; i++) System.out.print(arr[i] + \" \"); }}", "e": 2252, "s": 1304, "text": null }, { "code": "# Python program to Sort square# of the numbers of the array # Function to sort an square arraydef sortSquare(arr, n): # First convert each array # elements into its square for i in range(n): arr[i]= arr[i] * arr[i] arr.sort() # Driver codearr = [-6, -3, -1, 2, 4, 5]n = len(arr) print(\"Before sort\")for i in range(n): print(arr[i], end = \" \") print(\"\\n\") sortSquare(arr, n) print(\"After sort\")for i in range(n): print(arr[i], end = \" \") # This code is contributed by# Shrikant13", "e": 2758, "s": 2252, "text": null }, { "code": "// C# program to Sort square// of the numbers of the arrayusing System; class GFG { // Function to sort // an square array public static void sortSquares(int[] arr) { int n = arr.Length; // First convert each array // elements into its square for (int i = 0; i < n; i++) arr[i] = arr[i] * arr[i]; // Sort an array using // \"inbuild sort function\" // in Arrays class. Array.Sort(arr); } // Driver Code public static void Main() { int[] arr = { -6, -3, -1, 2, 4, 5 }; int n = arr.Length; Console.WriteLine(\"Before sort \"); for (int i = 0; i < n; i++) Console.Write(arr[i] + \" \"); sortSquares(arr); Console.WriteLine(\"\"); Console.WriteLine(\"After Sort \"); for (int i = 0; i < n; i++) Console.Write(arr[i] + \" \"); }} // This code is contributed by anuj_67.", "e": 3711, "s": 2758, "text": null }, { "code": "<script> // JavaScript program for the above approach // Function to sort an square array function sortSquares(arr) { let n = arr.length; // First convert each array elements // into its square for (let i = 0; i < n; i++) arr[i] = arr[i] * arr[i]; // Sort an array using \"inbuild sort function\" // in Arrays class. arr.sort(); } // Driver Code let arr = [ -6, -3, -1, 2, 4, 5 ]; let n = arr.length; document.write(\"Before sort \" + \"<br/>\"); for (let i = 0; i < n; i++) document.write(arr[i] + \" \"); sortSquares(arr); document.write(\"\" + \"<br/>\"); document.write(\"After Sort \" + \"<br/>\"); for (let i = 0; i < n; i++) document.write(arr[i] + \" \"); // This code is contributed by chinmoy1997pal.</script>", "e": 4528, "s": 3711, "text": null }, { "code": null, "e": 4585, "s": 4528, "text": "Before sort \n-6 -3 -1 2 4 5 \nAfter Sort \n1 4 9 16 25 36 " }, { "code": null, "e": 4613, "s": 4585, "text": "Time complexity: O(n log n)" }, { "code": null, "e": 4725, "s": 4613, "text": "Efficient solution is based on the fact that the given array is already sorted. We do the following two steps. " }, { "code": null, "e": 4855, "s": 4725, "text": "Divide the array into two-part “Negative and positive “.Use merge function to merge two sorted arrays into a single sorted array." }, { "code": null, "e": 4912, "s": 4855, "text": "Divide the array into two-part “Negative and positive “." }, { "code": null, "e": 4986, "s": 4912, "text": "Use merge function to merge two sorted arrays into a single sorted array." }, { "code": null, "e": 5033, "s": 4986, "text": "Below is the implementation of the above idea." }, { "code": null, "e": 5037, "s": 5033, "text": "C++" }, { "code": null, "e": 5042, "s": 5037, "text": "Java" }, { "code": null, "e": 5050, "s": 5042, "text": "Python3" }, { "code": null, "e": 5053, "s": 5050, "text": "C#" }, { "code": null, "e": 5064, "s": 5053, "text": "Javascript" }, { "code": "// C++ program to Sort square of the numbers of the array#include <bits/stdc++.h>using namespace std; // function to sort array after doing squares of elementsvoid sortSquares(int arr[], int n){ // first divide array into negative and positive part int K = 0; for (K = 0; K < n; K++) if (arr[K] >= 0) break; // Now do the same process that we learnt // in merge sort to merge two sorted array // here both two half are sorted and we traverse // first half in reverse manner because // first half contains negative elements int i = K - 1; // Initial index of first half int j = K; // Initial index of second half int ind = 0; // Initial index of temp array // store sorted array int temp[n]; while (i >= 0 && j < n) { if (arr[i] * arr[i] < arr[j] * arr[j]) { temp[ind] = arr[i] * arr[i]; i--; } else { temp[ind] = arr[j] * arr[j]; j++; } ind++; } /* Copy the remaining elements of first half */ while (i >= 0) { temp[ind] = arr[i] * arr[i]; i--; ind++; } /* Copy the remaining elements of second half */ while (j < n) { temp[ind] = arr[j] * arr[j]; j++; ind++; } // copy 'temp' array into original array for (int i = 0; i < n; i++) arr[i] = temp[i];} // Driver program to test above functionint main(){ int arr[] = { -6, -3, -1, 2, 4, 5 }; int n = sizeof(arr) / sizeof(arr[0]); cout << \"Before sort \" << endl; for (int i = 0; i < n; i++) cout << arr[i] << \" \"; sortSquares(arr, n); cout << \"\\nAfter Sort \" << endl; for (int i = 0; i < n; i++) cout << arr[i] << \" \"; return 0;}", "e": 6803, "s": 5064, "text": null }, { "code": "// Java program to Sort square of the numbers// of the arrayimport java.util.*;import java.io.*; class GFG { // Function to sort an square array public static void sortSquares(int arr[]) { int n = arr.length; // first divide the array into negative and positive part int k; for (k = 0; k < n; k++) { if (arr[k] >= 0) break; } // Now do the same process that we learnt // in merge sort to merge two sorted arrays // here both two halves are sorted and we traverse // first half in reverse manner because // first half contains negative elements int i = k - 1; // Initial index of first half int j = k; // Initial index of second half int ind = 0; // Initial index of temp array int[] temp = new int[n]; while (i >= 0 && j < n) { if (arr[i] * arr[i] < arr[j] * arr[j]) { temp[ind] = arr[i] * arr[i]; i--; } else { temp[ind] = arr[j] * arr[j]; j++; } ind++; } while (i >= 0) { temp[ind++] = arr[i] * arr[i]; i--; } while (j < n) { temp[ind++] = arr[j] * arr[j]; j++; } // copy 'temp' array into original array for (int x = 0; x < n; x++) arr[x] = temp[x]; } // Driver program to test above function public static void main(String[] args) { int arr[] = { -6, -3, -1, 2, 4, 5 }; int n = arr.length; System.out.println(\"Before sort \"); for (int i = 0; i < n; i++) System.out.print(arr[i] + \" \"); sortSquares(arr); System.out.println(\"\"); System.out.println(\"After Sort \"); for (int i = 0; i < n; i++) System.out.print(arr[i] + \" \"); }}", "e": 8693, "s": 6803, "text": null }, { "code": "# Python3 program to Sort square of the numbers of the array # function to sort array after doing squares of elementsdef sortSquares(arr, n): # first divide array into negative and positive part K = 0 for K in range(n): if (arr[K] >= 0 ): break # Now do the same process that we learnt # in merge sort to merge to two sorted array # here both two halves are sorted and we traverse # first half in reverse manner because # first half contains negative elements i = K - 1 # Initial index of first half j = K # Initial index of second half ind = 0 # Initial index of temp array # store sorted array temp = [0]*n while (i >= 0 and j < n): if (arr[i] * arr[i] < arr[j] * arr[j]): temp[ind] = arr[i] * arr[i] i -= 1 else: temp[ind] = arr[j] * arr[j] j += 1 ind += 1 ''' Copy the remaining elements of first half ''' while (i >= 0): temp[ind] = arr[i] * arr[i] i -= 1 ind += 1 ''' Copy the remaining elements of second half ''' while (j < n): temp[ind] = arr[j] * arr[j] j += 1 ind += 1 # copy 'temp' array into original array for i in range(n): arr[i] = temp[i] # Driver codearr = [-6, -3, -1, 2, 4, 5 ]n = len(arr) print(\"Before sort \")for i in range(n): print(arr[i], end =\" \" ) sortSquares(arr, n)print(\"\\nAfter Sort \")for i in range(n): print(arr[i], end =\" \" ) # This code is contributed by shubhamsingh10", "e": 10292, "s": 8693, "text": null }, { "code": "// C# program to Sort square of the numbers// of the arrayusing System; class GFG { // Function to sort an square array public static void sortSquares(int[] arr) { int n = arr.Length; // first divide array into negative and positive part int k; for (k = 0; k < n; k++) { if (arr[k] >= 0) break; } // Now do the same process that we learnt // in merge sort to merge to two sorted array // here both two halves are sorted and we traverse // first half in reverse manner because // first half contains negative elements int i = k - 1; // Initial index of first half int j = k; // Initial index of second half int ind = 0; // Initial index of temp array int[] temp = new int[n]; while (i >= 0 && j < n) { if (arr[i] * arr[i] < arr[j] * arr[j]) { temp[ind] = arr[i] * arr[i]; i--; } else { temp[ind] = arr[j] * arr[j]; j++; } ind++; } while (i >= 0) { temp[ind++] = arr[i] * arr[i]; i--; } while (j < n) { temp[ind++] = arr[j] * arr[j]; j++; } // copy 'temp' array into original array for (int x = 0; x < n; x++) arr[x] = temp[x]; } // Driver code public static void Main(String[] args) { int[] arr = { -6, -3, -1, 2, 4, 5 }; int n = arr.Length; Console.WriteLine(\"Before sort \"); for (int i = 0; i < n; i++) Console.Write(arr[i] + \" \"); sortSquares(arr); Console.WriteLine(\"\"); Console.WriteLine(\"After Sort \"); for (int i = 0; i < n; i++) Console.Write(arr[i] + \" \"); }} // This code is contributed by 29AjayKumar", "e": 12164, "s": 10292, "text": null }, { "code": "<script> // Javascript program to Sort// square of the numbers// of the array // Function to sort an square array function sortSquares(arr) { let n = arr.length; // first dived array into part // negative and positive let k; for (k = 0; k < n; k++) { if (arr[k] >= 0) break; } // Now do the same process that we learn // in merge sort to merge to two sorted array // here both two half are sorted and we traverse // first half in reverse meaner because // first half contain negative element let i = k - 1; // Initial index of first half let j = k; // Initial index of second half let ind = 0; // Initial index of temp array let temp = new Array(n); while (i >= 0 && j < n) { if (arr[i] * arr[i] < arr[j] * arr[j]) { temp[ind] = arr[i] * arr[i]; i--; } else { temp[ind] = arr[j] * arr[j]; j++; } ind++; } while (i >= 0) { temp[ind++] = arr[i] * arr[i]; i--; } while (j < n) { temp[ind++] = arr[j] * arr[j]; j++; } // copy 'temp' array into original array for (let x = 0; x < n; x++) arr[x] = temp[x]; } // Driver program to test above function let arr=[ -6, -3, -1, 2, 4, 5 ]; let n = arr.length; document.write(\"Before sort <br>\"); for (let i = 0; i < n; i++) document.write(arr[i] + \" \"); sortSquares(arr); document.write(\"<br>\"); document.write(\"After Sort <br>\"); for (let i = 0; i < n; i++) document.write(arr[i] + \" \"); // This code is contributed by rag2127 </script>", "e": 13997, "s": 12164, "text": null }, { "code": null, "e": 14054, "s": 13997, "text": "Before sort \n-6 -3 -1 2 4 5 \nAfter Sort \n1 4 9 16 25 36 " }, { "code": null, "e": 14100, "s": 14054, "text": "Time complexity: O(n) space complexity: O(n) " }, { "code": null, "e": 14299, "s": 14100, "text": "Method 3:Another efficient solution is based on the two-pointer method as the array is already sorted we can compare the first and last element to check which is bigger and proceed with the result. " }, { "code": null, "e": 14310, "s": 14299, "text": "Algorithm:" }, { "code": null, "e": 14342, "s": 14310, "text": "Initialize left=0 and right=n-1" }, { "code": null, "e": 14451, "s": 14342, "text": "if abs(left) >= abs(right) then store square(arr[left])at the end of result array and increment left pointer" }, { "code": null, "e": 14529, "s": 14451, "text": "else store square(arr[right]) in the result array and decrement right pointer" }, { "code": null, "e": 14561, "s": 14529, "text": "decrement index of result array" }, { "code": null, "e": 14577, "s": 14561, "text": "Implementation:" }, { "code": null, "e": 14581, "s": 14577, "text": "C++" }, { "code": null, "e": 14586, "s": 14581, "text": "Java" }, { "code": null, "e": 14594, "s": 14586, "text": "Python3" }, { "code": null, "e": 14597, "s": 14594, "text": "C#" }, { "code": null, "e": 14608, "s": 14597, "text": "Javascript" }, { "code": "// CPP code for the above approach#include <bits/stdc++.h>using namespace std; // Function to sort an square arrayvoid sortSquares(vector<int>& arr, int n){ int left = 0, right = n - 1; int result[n]; // Iterate from n - 1 to 0 for (int index = n - 1; index >= 0; index--) { // Check if abs(arr[left]) is greater // than arr[right] if (abs(arr[left]) > arr[right]) { result[index] = arr[left] * arr[left]; left++; } else { result[index] = arr[right] * arr[right]; right--; } } for (int i = 0; i < n; i++) arr[i] = result[i];} // Driver Codeint main(){ vector<int> arr; arr.push_back(-6); arr.push_back(-3); arr.push_back(-1); arr.push_back(2); arr.push_back(4); arr.push_back(5); int n = 6; cout << \"Before sort \" << endl; for (int i = 0; i < n; i++) cout << arr[i] << \" \"; sortSquares(arr, n); cout << endl; cout << \"After Sort \" << endl; for (int i = 0; i < n; i++) cout << arr[i] << \" \"; return 0;} // this code is contributed by Manu Pathria", "e": 15735, "s": 14608, "text": null }, { "code": "// Java program to Sort square of// the numbers of the arrayimport java.util.*;import java.io.*; class GFG{ // Function to sort an square arraypublic static void sortSquares(int arr[]){ int n = arr.length, left = 0, right = n - 1; int result[] = new int[n]; for(int index = n - 1; index >= 0; index--) { if (Math.abs(arr[left]) > arr[right]) { result[index] = arr[left] * arr[left]; left++; } else { result[index] = arr[right] * arr[right]; right--; } } for(int i = 0; i < n; i++) arr[i] = result[i];} // Driver codepublic static void main(String[] args){ int arr[] = { -6, -3, -1, 2, 4, 5 }; int n = arr.length; System.out.println(\"Before sort \"); for(int i = 0; i < n; i++) System.out.print(arr[i] + \" \"); sortSquares(arr); System.out.println(\"\"); System.out.println(\"After Sort \"); for(int i = 0; i < n; i++) System.out.print(arr[i] + \" \");}} // This code is contributed by jinalparmar2382", "e": 16800, "s": 15735, "text": null }, { "code": "# Python3 program to Sort square of the numbers of the array # function to sort array after doing squares of elementsdef sortSquares(arr, n): left, right = 0, n - 1 index = n - 1 result = [0 for x in arr] while index >= 0: if abs(arr[left]) >= abs(arr[right]): result[index] = arr[left] * arr[left] left += 1 else: result[index] = arr[right] * arr[right] right -= 1 index -= 1 for i in range(n): arr[i] = result[i] # Driver codearr = [-6, -3, -1, 2, 4, 5 ]n = len(arr) print(\"Before sort \")for i in range(n): print(arr[i], end =\" \" ) sortSquares(arr, n)print(\"\\nAfter Sort \")for i in range(n): print(arr[i], end =\" \" )", "e": 17523, "s": 16800, "text": null }, { "code": "// C# program to Sort square of// the numbers of the arrayusing System;class GFG{ // Function to sort an square arraypublic static void sortSquares(int [] arr){ int n = arr.Length, left = 0, right = n - 1; int []result = new int[n]; for(int index = n - 1; index >= 0; index--) { if (Math.Abs(arr[left]) > arr[right]) { result[index] = arr[left] * arr[left]; left++; } else { result[index] = arr[right] * arr[right]; right--; } } for(int i = 0; i < n; i++) arr[i] = result[i];} // Driver codepublic static void Main(string[] args){ int []arr = {-6, -3, -1, 2, 4, 5}; int n = arr.Length; Console.WriteLine(\"Before sort \"); for(int i = 0; i < n; i++) Console.Write(arr[i] + \" \"); sortSquares(arr); Console.WriteLine(\"\"); Console.WriteLine(\"After Sort \"); for(int i = 0; i < n; i++) Console.Write(arr[i] + \" \");}} // This code is contributed by Chitranayal", "e": 18508, "s": 17523, "text": null }, { "code": "<script> // This function squares each value in an array // and arranges the result in ascending order, using two pointers. // The first pointer points to the first element of the array, and the second // points to the last. On each iteration, each pointer is compared to the other // and the pointer which has the lowest value is shifted closer to the other. function sortSquares(arr) { let n = nums.length, left = 0, right = n -1, result = new Array(n) ; for (let i = n - 1; i >= 0; i--) { // Here, Math.abs() is used to convert any negative numbers to their // integer equivalent... i.e. -4 becomes 4. if (Math.abs(nums[left]) > Math.abs(nums[right])) { result[i] = nums[left] ** 2; left++; } else { result[i] = nums[right] **2; right--; } } return result; } let arr = [-6, -3, -1, 2, 4, 5]; let n = arr.length; document.write(\"Before sort \" + \"</br>\"); for(let i = 0; i < n; i++) document.write(arr[i] + \" \"); sortSquares(arr); document.write(\"</br>\"); document.write(\"After Sort \" + \"</br>\"); for(let i = 0; i < n; i++) document.write(arr[i] + \" \"); // This code was contributed by rameshtravel07, then was edited by: Lewis Farnworth</script>", "e": 19919, "s": 18508, "text": null }, { "code": null, "e": 19976, "s": 19919, "text": "Before sort \n-6 -3 -1 2 4 5 \nAfter Sort \n1 4 9 16 25 36 " }, { "code": null, "e": 20021, "s": 19976, "text": "Time complexity: O(n) Auxiliary Space: O(n) " }, { "code": null, "e": 20318, "s": 20021, "text": "This article is contributed by Nishant singh. 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": 20330, "s": 20318, "text": "shrikanth13" }, { "code": null, "e": 20335, "s": 20330, "text": "vt_m" }, { "code": null, "e": 20347, "s": 20335, "text": "29AjayKumar" }, { "code": null, "e": 20362, "s": 20347, "text": "SHUBHAMSINGH10" }, { "code": null, "e": 20371, "s": 20362, "text": "skrish87" }, { "code": null, "e": 20383, "s": 20371, "text": "parmarjinal" }, { "code": null, "e": 20389, "s": 20383, "text": "ukasp" }, { "code": null, "e": 20401, "s": 20389, "text": "manupathria" }, { "code": null, "e": 20416, "s": 20401, "text": "chinmoy1997pal" }, { "code": null, "e": 20424, "s": 20416, "text": "rag2127" }, { "code": null, "e": 20439, "s": 20424, "text": "rameshtravel07" }, { "code": null, "e": 20454, "s": 20439, "text": "uppooraprajwal" }, { "code": null, "e": 20463, "s": 20454, "text": "lewfar99" }, { "code": null, "e": 20480, "s": 20463, "text": "hardikkoriintern" }, { "code": null, "e": 20487, "s": 20480, "text": "Arrays" }, { "code": null, "e": 20495, "s": 20487, "text": "Sorting" }, { "code": null, "e": 20502, "s": 20495, "text": "Arrays" }, { "code": null, "e": 20510, "s": 20502, "text": "Sorting" }, { "code": null, "e": 20608, "s": 20510, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 20640, "s": 20608, "text": "Introduction to Data Structures" }, { "code": null, "e": 20687, "s": 20640, "text": "Search, insert and delete in an unsorted array" }, { "code": null, "e": 20712, "s": 20687, "text": "Window Sliding Technique" }, { "code": null, "e": 20743, "s": 20712, "text": "Chocolate Distribution Problem" }, { "code": null, "e": 20801, "s": 20743, "text": "Find duplicates in O(n) time and O(1) extra space | Set 1" }, { "code": null, "e": 20812, "s": 20801, "text": "Merge Sort" }, { "code": null, "e": 20834, "s": 20812, "text": "Bubble Sort Algorithm" }, { "code": null, "e": 20844, "s": 20834, "text": "QuickSort" }, { "code": null, "e": 20859, "s": 20844, "text": "Insertion Sort" } ]
Python Program to Print Lines Containing Given String in File
31 Aug, 2021 In this article, we are going to see how to fetch and display lines containing a given string from a given text file. Assume that you have a text file named geeks.txt saved on the location where you are going to create your python file. Here is the content of the geeks.txt file: Approach: Load the text file into the python program to find the given string in the file. Ask the user to enter the string that you want to search in the file. Read the text file line by line using readlines() function and search for the string. After finding the string, print that entire line and continue the search. If the string is not found in the entire file, display the proper verdict. Below is the implementation: Python3 # Python Program to Print Lines# Containing Given String in File # input file name with extensionfile_name = input("Enter The File's Name: ") # using try catch except to# handle file not found error. # entering try blocktry: # opening and reading the file file_read = open(file_name, "r") # asking the user to enter the string to be # searched text = input("Enter the String: ") # reading file content line by line. lines = file_read.readlines() new_list = [] idx = 0 # looping through each line in the file for line in lines: # if line have the input string, get the index # of that line and put the # line into newly created list if text in line: new_list.insert(idx, line) idx += 1 # closing file after reading file_read.close() # if length of new list is 0 that means # the input string doesn't # found in the text file if len(new_list)==0: print("\n\"" +text+ "\" is not found in \"" +file_name+ "\"!") else: # displaying the lines # containing given string lineLen = len(new_list) print("\n**** Lines containing \"" +text+ "\" ****\n") for i in range(lineLen): print(end=new_list[i]) print() # entering except block# if input file doesn't exist except : print("\nThe file doesn't exist!") Output: Lines containing string Picked Python file-handling-programs Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON Python | os.path.join() method How to drop one or multiple columns in Pandas Dataframe How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | Get unique values from a list Python | datetime.timedelta() function
[ { "code": null, "e": 28, "s": 0, "text": "\n31 Aug, 2021" }, { "code": null, "e": 265, "s": 28, "text": "In this article, we are going to see how to fetch and display lines containing a given string from a given text file. Assume that you have a text file named geeks.txt saved on the location where you are going to create your python file." }, { "code": null, "e": 308, "s": 265, "text": "Here is the content of the geeks.txt file:" }, { "code": null, "e": 318, "s": 308, "text": "Approach:" }, { "code": null, "e": 399, "s": 318, "text": "Load the text file into the python program to find the given string in the file." }, { "code": null, "e": 469, "s": 399, "text": "Ask the user to enter the string that you want to search in the file." }, { "code": null, "e": 555, "s": 469, "text": "Read the text file line by line using readlines() function and search for the string." }, { "code": null, "e": 629, "s": 555, "text": "After finding the string, print that entire line and continue the search." }, { "code": null, "e": 704, "s": 629, "text": "If the string is not found in the entire file, display the proper verdict." }, { "code": null, "e": 733, "s": 704, "text": "Below is the implementation:" }, { "code": null, "e": 741, "s": 733, "text": "Python3" }, { "code": "# Python Program to Print Lines# Containing Given String in File # input file name with extensionfile_name = input(\"Enter The File's Name: \") # using try catch except to# handle file not found error. # entering try blocktry: # opening and reading the file file_read = open(file_name, \"r\") # asking the user to enter the string to be # searched text = input(\"Enter the String: \") # reading file content line by line. lines = file_read.readlines() new_list = [] idx = 0 # looping through each line in the file for line in lines: # if line have the input string, get the index # of that line and put the # line into newly created list if text in line: new_list.insert(idx, line) idx += 1 # closing file after reading file_read.close() # if length of new list is 0 that means # the input string doesn't # found in the text file if len(new_list)==0: print(\"\\n\\\"\" +text+ \"\\\" is not found in \\\"\" +file_name+ \"\\\"!\") else: # displaying the lines # containing given string lineLen = len(new_list) print(\"\\n**** Lines containing \\\"\" +text+ \"\\\" ****\\n\") for i in range(lineLen): print(end=new_list[i]) print() # entering except block# if input file doesn't exist except : print(\"\\nThe file doesn't exist!\")", "e": 2137, "s": 741, "text": null }, { "code": null, "e": 2145, "s": 2137, "text": "Output:" }, { "code": null, "e": 2169, "s": 2145, "text": "Lines containing string" }, { "code": null, "e": 2176, "s": 2169, "text": "Picked" }, { "code": null, "e": 2206, "s": 2176, "text": "Python file-handling-programs" }, { "code": null, "e": 2213, "s": 2206, "text": "Python" }, { "code": null, "e": 2311, "s": 2213, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2343, "s": 2311, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2370, "s": 2343, "text": "Python Classes and Objects" }, { "code": null, "e": 2391, "s": 2370, "text": "Python OOPs Concepts" }, { "code": null, "e": 2414, "s": 2391, "text": "Introduction To PYTHON" }, { "code": null, "e": 2445, "s": 2414, "text": "Python | os.path.join() method" }, { "code": null, "e": 2501, "s": 2445, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 2543, "s": 2501, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 2585, "s": 2543, "text": "Check if element exists in list in Python" }, { "code": null, "e": 2624, "s": 2585, "text": "Python | Get unique values from a list" } ]
Find the missing value from the given equation a + b = c
20 May, 2021 Given an equation of the form: a + b = c Out of which any one of the terms , or is missing. The task is to find the missing term. Examples: Input: 2 + 6 = ? Output: 8 Input: ? + 3 =6 Output: 3 Approach: Missing numbers can be found simply using the equation . First, we will find two known numbers from the given equation(read as a string in the program) and convert them into integers, and put into the equation. In this way, we can find the third missing number. We can implement it by storing the equation into the string. Below is the step by step algorithm: Split the string into smaller strings from the position of spaces and store in an array. So that the array will contain: arr[0] = "a" arr[1] = "+" arr[2] = "b" arr[3] = "=" arr[4] = "c" The missing character can occur at position 0 or 2 or 4 in the vector. Find the position of missing character. Convert known characters to integers. Find missing character using the equation. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program to find the missing number// in the equation a + b = c#include <bits/stdc++.h>using namespace std; // Function to find the missing number// in the equation a + b = cint findMissing(string str){ // Array of string to store individual strings // after splitting the strings from spaces string arrStr[5]; // Using stringstream to read a string object // and split stringstream ss(str); int i = 0; while (ss.good() && i < 5) { ss >> arrStr[i]; ++i; } int pos = -1; // Find position of missing character if(arrStr[0] == "?") pos = 0; else if(arrStr[2] == "?") pos = 2; else pos = 4; if(pos == 0) { string b,c; b = arrStr[2]; c = arrStr[4]; // Using stoi() to convert strings to int int a = stoi(c) - stoi(b); return a; } else if(pos==2) { string a,c; a = arrStr[0]; c = arrStr[4]; // Using stoi() to convert strings to int int b = stoi(c) - stoi(a); return b; } else if(pos == 4) { string b,a; a = arrStr[0]; b = arrStr[2]; // Using stoi() to convert strings to int int c = stoi(a) + stoi(b); return c; }} // Driver codeint main(){ // Equation with missing value string str = "? + 3 = 7"; cout<<findMissing(str); return 0; } // Java program to find the missing number// in the equation a + b = cimport java.util.*; class GFG{ // Function to find the missing number// in the equation a + b = cstatic int findMissing(String str){ // Array of String to store individual // strings after splitting the strings // from spaces String arrStr[] = str.split(" "); int pos = -1; // Find position of missing character if (arrStr[0].equals("?")) pos = 0; else if (arrStr[2].equals("?")) pos = 2; else pos = 4; if (pos == 0) { String b, c; b = arrStr[2]; c = arrStr[4]; // Using Integer.parseInt() to // convert strings to int int a = Integer.parseInt(c) - Integer.parseInt(b); return a; } else if (pos == 2) { String a, c; a = arrStr[0]; c = arrStr[4]; // Using Integer.parseInt() to // convert strings to int int b = Integer.parseInt(c) - Integer.parseInt(a); return b; } else if (pos == 4) { String b, a; a = arrStr[0]; b = arrStr[2]; // Using Integer.parseInt() to // convert strings to int int c = Integer.parseInt(a) + Integer.parseInt(b); return c; } return 0;} // Driver codepublic static void main(String []args){ // Equation with missing value String str = "? + 3 = 7"; System.out.print(findMissing(str));}} // This code is contributed by pratham76 # Python3 program to find the missing number# in the equation a + b = c # Function to find the missing number# in the equation a + b = cdef findMissing(s): # Array of string to store individual strings # after splitting the strings from spaces arrStr = s.split() # Using stringstream to read a string object # and split pos = -1; # Find position of missing character if(arrStr[0] == "?"): pos = 0; elif(arrStr[2] == "?"): pos = 2; else: pos = 4; if(pos == 0): b = arrStr[2]; c = arrStr[4]; # Using int() to convert strings to int a = int(c) - int(b); return a; elif(pos == 2): a = arrStr[0]; c = arrStr[4]; # Using int() to convert strings to int b = int(c) - int(a); return b; elif(pos == 4): a = arrStr[0]; b = arrStr[2]; # Using int() to convert strings to int c = int(a) + int(b); return c; # Driver codeif __name__=='__main__': # Equation with missing value s = "? + 3 = 7"; print(findMissing(s)) # This code is contributed by rutvik_56 // C# program to find the missing number// in the equation a + b = cusing System;class GFG{ // Function to find the missing number // in the equation a + b = c static int findMissing(string str) { // Array of String to store individual // strings after splitting the strings // from spaces string[] arrStr = str.Split(" "); int pos = -1; // Find position of missing character if (arrStr[0].Equals("?")) pos = 0; else if (arrStr[2].Equals("?")) pos = 2; else pos = 4; if (pos == 0) { string b, c; b = arrStr[2]; c = arrStr[4]; // Using Integer.parseInt() to // convert strings to int int a = int.Parse(c) - int.Parse(b); return a; } else if (pos == 2) { string a, c; a = arrStr[0]; c = arrStr[4]; // Using Integer.parseInt() to // convert strings to int int b = int.Parse(c) - int.Parse(a); return b; } else if (pos == 4) { string b, a; a = arrStr[0]; b = arrStr[2]; // Using Integer.parseInt() to // convert strings to int int c = int.Parse(a) + int.Parse(b); return c; } return 0; } // Driver code public static void Main(string[] args) { // Equation with missing value string str = "? + 3 = 7"; Console.WriteLine(findMissing(str)); }} // This code is contributed by chitranayal. <script> // JavaScript program to find the missing number// in the equation a + b = c // Function to find the missing number// in the equation a + b = c function findMissing(str) { // Array of String to store individual // strings after splitting the strings // from spaces let arrStr = str.split(" "); let pos = -1; // Find position of missing character if (arrStr[0]==("?")) pos = 0; else if (arrStr[2]==("?")) pos = 2; else pos = 4; if (pos == 0) { let b, c; b = arrStr[2]; c = arrStr[4]; // Using Integer.parseInt() to // convert strings to int let a = parseInt(c) - parseInt(b); return a; } else if (pos == 2) { let a, c; a = arrStr[0]; c = arrStr[4]; // Using Integer.parseInt() to // convert strings to int let b = parseInt(c) - parseInt(a); return b; } else if (pos == 4) { let b, a; a = arrStr[0]; b = arrStr[2]; // Using Integer.parseInt() to // convert strings to int let c = parseInt(a) + parseInt(b); return c; } return 0; } // Driver code // Equation with missing value let str = "? + 3 = 7"; document.write(findMissing(str)); // This code is contributed by rag2127 </script> 4 rutvik_56 pratham76 ukasp rag2127 cpp-stringstream Competitive Programming Mathematical Strings Strings Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Modulo 10^9+7 (1000000007) Prefix Sum Array - Implementation and Applications in Competitive Programming Bits manipulation (Important tactics) What is Competitive Programming and How to Prepare for It? Count of strings whose prefix match with the given string to a given length k Program for Fibonacci numbers Set in C++ Standard Template Library (STL) Write a program to print all permutations of a given string C++ Data Types Merge two sorted arrays
[ { "code": null, "e": 54, "s": 26, "text": "\n20 May, 2021" }, { "code": null, "e": 86, "s": 54, "text": "Given an equation of the form: " }, { "code": null, "e": 98, "s": 86, "text": "a + b = c " }, { "code": null, "e": 187, "s": 98, "text": "Out of which any one of the terms , or is missing. The task is to find the missing term." }, { "code": null, "e": 199, "s": 187, "text": "Examples: " }, { "code": null, "e": 253, "s": 199, "text": "Input: 2 + 6 = ?\nOutput: 8\n\nInput: ? + 3 =6\nOutput: 3" }, { "code": null, "e": 586, "s": 253, "text": "Approach: Missing numbers can be found simply using the equation . First, we will find two known numbers from the given equation(read as a string in the program) and convert them into integers, and put into the equation. In this way, we can find the third missing number. We can implement it by storing the equation into the string." }, { "code": null, "e": 624, "s": 586, "text": "Below is the step by step algorithm: " }, { "code": null, "e": 745, "s": 624, "text": "Split the string into smaller strings from the position of spaces and store in an array. So that the array will contain:" }, { "code": null, "e": 810, "s": 745, "text": "arr[0] = \"a\"\narr[1] = \"+\"\narr[2] = \"b\"\narr[3] = \"=\"\narr[4] = \"c\"" }, { "code": null, "e": 921, "s": 810, "text": "The missing character can occur at position 0 or 2 or 4 in the vector. Find the position of missing character." }, { "code": null, "e": 959, "s": 921, "text": "Convert known characters to integers." }, { "code": null, "e": 1002, "s": 959, "text": "Find missing character using the equation." }, { "code": null, "e": 1055, "s": 1002, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 1059, "s": 1055, "text": "C++" }, { "code": null, "e": 1064, "s": 1059, "text": "Java" }, { "code": null, "e": 1072, "s": 1064, "text": "Python3" }, { "code": null, "e": 1075, "s": 1072, "text": "C#" }, { "code": null, "e": 1086, "s": 1075, "text": "Javascript" }, { "code": "// C++ program to find the missing number// in the equation a + b = c#include <bits/stdc++.h>using namespace std; // Function to find the missing number// in the equation a + b = cint findMissing(string str){ // Array of string to store individual strings // after splitting the strings from spaces string arrStr[5]; // Using stringstream to read a string object // and split stringstream ss(str); int i = 0; while (ss.good() && i < 5) { ss >> arrStr[i]; ++i; } int pos = -1; // Find position of missing character if(arrStr[0] == \"?\") pos = 0; else if(arrStr[2] == \"?\") pos = 2; else pos = 4; if(pos == 0) { string b,c; b = arrStr[2]; c = arrStr[4]; // Using stoi() to convert strings to int int a = stoi(c) - stoi(b); return a; } else if(pos==2) { string a,c; a = arrStr[0]; c = arrStr[4]; // Using stoi() to convert strings to int int b = stoi(c) - stoi(a); return b; } else if(pos == 4) { string b,a; a = arrStr[0]; b = arrStr[2]; // Using stoi() to convert strings to int int c = stoi(a) + stoi(b); return c; }} // Driver codeint main(){ // Equation with missing value string str = \"? + 3 = 7\"; cout<<findMissing(str); return 0; }", "e": 2555, "s": 1086, "text": null }, { "code": "// Java program to find the missing number// in the equation a + b = cimport java.util.*; class GFG{ // Function to find the missing number// in the equation a + b = cstatic int findMissing(String str){ // Array of String to store individual // strings after splitting the strings // from spaces String arrStr[] = str.split(\" \"); int pos = -1; // Find position of missing character if (arrStr[0].equals(\"?\")) pos = 0; else if (arrStr[2].equals(\"?\")) pos = 2; else pos = 4; if (pos == 0) { String b, c; b = arrStr[2]; c = arrStr[4]; // Using Integer.parseInt() to // convert strings to int int a = Integer.parseInt(c) - Integer.parseInt(b); return a; } else if (pos == 2) { String a, c; a = arrStr[0]; c = arrStr[4]; // Using Integer.parseInt() to // convert strings to int int b = Integer.parseInt(c) - Integer.parseInt(a); return b; } else if (pos == 4) { String b, a; a = arrStr[0]; b = arrStr[2]; // Using Integer.parseInt() to // convert strings to int int c = Integer.parseInt(a) + Integer.parseInt(b); return c; } return 0;} // Driver codepublic static void main(String []args){ // Equation with missing value String str = \"? + 3 = 7\"; System.out.print(findMissing(str));}} // This code is contributed by pratham76", "e": 4158, "s": 2555, "text": null }, { "code": "# Python3 program to find the missing number# in the equation a + b = c # Function to find the missing number# in the equation a + b = cdef findMissing(s): # Array of string to store individual strings # after splitting the strings from spaces arrStr = s.split() # Using stringstream to read a string object # and split pos = -1; # Find position of missing character if(arrStr[0] == \"?\"): pos = 0; elif(arrStr[2] == \"?\"): pos = 2; else: pos = 4; if(pos == 0): b = arrStr[2]; c = arrStr[4]; # Using int() to convert strings to int a = int(c) - int(b); return a; elif(pos == 2): a = arrStr[0]; c = arrStr[4]; # Using int() to convert strings to int b = int(c) - int(a); return b; elif(pos == 4): a = arrStr[0]; b = arrStr[2]; # Using int() to convert strings to int c = int(a) + int(b); return c; # Driver codeif __name__=='__main__': # Equation with missing value s = \"? + 3 = 7\"; print(findMissing(s)) # This code is contributed by rutvik_56", "e": 5413, "s": 4158, "text": null }, { "code": "// C# program to find the missing number// in the equation a + b = cusing System;class GFG{ // Function to find the missing number // in the equation a + b = c static int findMissing(string str) { // Array of String to store individual // strings after splitting the strings // from spaces string[] arrStr = str.Split(\" \"); int pos = -1; // Find position of missing character if (arrStr[0].Equals(\"?\")) pos = 0; else if (arrStr[2].Equals(\"?\")) pos = 2; else pos = 4; if (pos == 0) { string b, c; b = arrStr[2]; c = arrStr[4]; // Using Integer.parseInt() to // convert strings to int int a = int.Parse(c) - int.Parse(b); return a; } else if (pos == 2) { string a, c; a = arrStr[0]; c = arrStr[4]; // Using Integer.parseInt() to // convert strings to int int b = int.Parse(c) - int.Parse(a); return b; } else if (pos == 4) { string b, a; a = arrStr[0]; b = arrStr[2]; // Using Integer.parseInt() to // convert strings to int int c = int.Parse(a) + int.Parse(b); return c; } return 0; } // Driver code public static void Main(string[] args) { // Equation with missing value string str = \"? + 3 = 7\"; Console.WriteLine(findMissing(str)); }} // This code is contributed by chitranayal.", "e": 7048, "s": 5413, "text": null }, { "code": "<script> // JavaScript program to find the missing number// in the equation a + b = c // Function to find the missing number// in the equation a + b = c function findMissing(str) { // Array of String to store individual // strings after splitting the strings // from spaces let arrStr = str.split(\" \"); let pos = -1; // Find position of missing character if (arrStr[0]==(\"?\")) pos = 0; else if (arrStr[2]==(\"?\")) pos = 2; else pos = 4; if (pos == 0) { let b, c; b = arrStr[2]; c = arrStr[4]; // Using Integer.parseInt() to // convert strings to int let a = parseInt(c) - parseInt(b); return a; } else if (pos == 2) { let a, c; a = arrStr[0]; c = arrStr[4]; // Using Integer.parseInt() to // convert strings to int let b = parseInt(c) - parseInt(a); return b; } else if (pos == 4) { let b, a; a = arrStr[0]; b = arrStr[2]; // Using Integer.parseInt() to // convert strings to int let c = parseInt(a) + parseInt(b); return c; } return 0; } // Driver code // Equation with missing value let str = \"? + 3 = 7\"; document.write(findMissing(str)); // This code is contributed by rag2127 </script>", "e": 8548, "s": 7048, "text": null }, { "code": null, "e": 8550, "s": 8548, "text": "4" }, { "code": null, "e": 8564, "s": 8554, "text": "rutvik_56" }, { "code": null, "e": 8574, "s": 8564, "text": "pratham76" }, { "code": null, "e": 8580, "s": 8574, "text": "ukasp" }, { "code": null, "e": 8588, "s": 8580, "text": "rag2127" }, { "code": null, "e": 8605, "s": 8588, "text": "cpp-stringstream" }, { "code": null, "e": 8629, "s": 8605, "text": "Competitive Programming" }, { "code": null, "e": 8642, "s": 8629, "text": "Mathematical" }, { "code": null, "e": 8650, "s": 8642, "text": "Strings" }, { "code": null, "e": 8658, "s": 8650, "text": "Strings" }, { "code": null, "e": 8671, "s": 8658, "text": "Mathematical" }, { "code": null, "e": 8769, "s": 8671, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 8796, "s": 8769, "text": "Modulo 10^9+7 (1000000007)" }, { "code": null, "e": 8874, "s": 8796, "text": "Prefix Sum Array - Implementation and Applications in Competitive Programming" }, { "code": null, "e": 8912, "s": 8874, "text": "Bits manipulation (Important tactics)" }, { "code": null, "e": 8971, "s": 8912, "text": "What is Competitive Programming and How to Prepare for It?" }, { "code": null, "e": 9049, "s": 8971, "text": "Count of strings whose prefix match with the given string to a given length k" }, { "code": null, "e": 9079, "s": 9049, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 9122, "s": 9079, "text": "Set in C++ Standard Template Library (STL)" }, { "code": null, "e": 9182, "s": 9122, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 9197, "s": 9182, "text": "C++ Data Types" } ]
Expand the string according to the given conditions
18 Aug, 2021 Given string str of the type “3(ab)4(cd)”, the task is to expand it to “abababcdcdcdcd” where integers are from the range [1, 9].This problem was asked in ThoughtWorks interview held in October 2018. Examples: Input: str = “3(ab)4(cd)” Output: abababcdcdcdcdInput: str = “2(kl)3(ap)” Output: klklapapap Approach: We traverse through the string and wait for a numeric value, num to turn up at position i. As soon as it arrives, we check i + 1 for a ‘(‘. If it’s present, then the program enters into a loop to extract whatever is within ‘(‘ and ‘)’ and concatenate it to an empty string, temp. Later, another loop prints the generated string num number of times. Repeat these steps until the string finishes. Below is the implementation of the approach: C++ Java Python3 C# Javascript // C++ implementation of the approach#include<bits/stdc++.h>using namespace std; // Function to expand and print the given stringvoid expandString(string strin){ string temp = ""; int j; for (int i = 0; i < strin.length(); i++) { if (strin[i] >= 0) { // Subtract '0' to convert char to int int num = strin[i] - '0'; if (strin[i + 1] == '(') { // Characters within brackets for (j = i + 1; strin[j] != ')'; j++) { if ((strin[j] >= 'a' && strin[j] <= 'z') || (strin[j] >= 'A' && strin[j] <= 'Z')) { temp += strin[j]; } } // Expanding for (int k = 1; k <= num; k++) { cout << (temp); } // Reset the variables num = 0; temp = ""; if (j < strin.length()) { i = j; } } } }} // Driver codeint main(){ string strin = "3(ab)4(cd)"; expandString(strin);} // This code is contributed by Surendra_Gangwar // Java implementation of the approachpublic class GFG { // Function to expand and print the given string static void expandString(String strin) { String temp = ""; int j; for (int i = 0; i < strin.length(); i++) { if (strin.charAt(i) >= 0) { // Subtract '0' to convert char to int int num = strin.charAt(i) - '0'; if (strin.charAt(i + 1) == '(') { // Characters within brackets for (j = i + 1; strin.charAt(j) != ')'; j++) { if ((strin.charAt(j) >= 'a' && strin.charAt(j) <= 'z') || (strin.charAt(j) >= 'A' && strin.charAt(j) <= 'Z')) { temp += strin.charAt(j); } } // Expanding for (int k = 1; k <= num; k++) { System.out.print(temp); } // Reset the variables num = 0; temp = ""; if (j < strin.length()) { i = j; } } } } } // Driver code public static void main(String args[]) { String strin = "3(ab)4(cd)"; expandString(strin); }} # Python3 implementation of the approach # Function to expand and print the given stringdef expandString(strin): temp = "" j = 0 i = 0 while(i < len(strin)): if (strin[i] >= "0"): # Subtract '0' to convert char to int num = ord(strin[i])-ord("0") if (strin[i + 1] == '('): # Characters within brackets j = i + 1 while(strin[j] != ')'): if ((strin[j] >= 'a' and strin[j] <= 'z') or \ (strin[j] >= 'A' and strin[j] <= 'Z')): temp += strin[j] j += 1 # Expanding for k in range(1, num + 1): print(temp,end="") # Reset the variables num = 0 temp = "" if (j < len(strin)): i = j i += 1 # Driver codestrin = "3(ab)4(cd)"expandString(strin) # This code is contributed by shubhamsingh10 // C# implementation of// the above approachusing System;class GFG{ // Function to expand and// print the given stringstatic void expandString(string strin){ string temp = ""; int j; for (int i = 0; i < strin.Length; i++) { if (strin[i] >= 0) { // Subtract '0' to // convert char to int int num = strin[i] - '0'; if (strin[i + 1] == '(') { // Characters within brackets for (j = i + 1; strin[j] != ')'; j++) { if ((strin[j] >= 'a' && strin[j] <= 'z') || (strin[j] >= 'A' && strin[j] <= 'Z')) { temp += strin[j]; } } // Expanding for (int k = 1; k <= num; k++) { Console.Write(temp); } // Reset the variables num = 0; temp = ""; if (j < strin.Length) { i = j; } } } }} // Driver codepublic static void Main(String [] args){ string strin = "3(ab)4(cd)"; expandString(strin);}} // This code is contributed by Chitranayal <script>// Javascript implementation of the approach // Function to expand and print the given string function expandString(strin) { let temp = ""; let j; for (let i = 0; i < strin.length; i++) { if (strin[i].charCodeAt(0) >= 0) { // Subtract '0' to convert char to int let num = strin[i].charCodeAt(0) - '0'.charCodeAt(0); if (strin[i+1] == '(') { // Characters within brackets for (j = i + 1; strin[j] != ')'; j++) { if ((strin[j] >= 'a' && strin[j] <= 'z') || (strin[j] >= 'A' && strin[j] <= 'Z')) { temp += strin[j]; } } // Expanding for (let k = 1; k <= num; k++) { document.write(temp); } // Reset the variables num = 0; temp = ""; if (j < strin.length) { i = j; } } } } } // Driver code let strin = "3(ab)4(cd)"; expandString(strin); // This code is contributed by rag2127</script> abababcdcdcdcd Time Complexity: O(N*N)Auxiliary Space: O(1) SURENDRA_GANGWAR SHUBHAMSINGH10 Code_Mech ukasp rag2127 pankajsharmagfg Thoughtworks Algorithms Strings Thoughtworks Strings Algorithms Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n18 Aug, 2021" }, { "code": null, "e": 254, "s": 54, "text": "Given string str of the type “3(ab)4(cd)”, the task is to expand it to “abababcdcdcdcd” where integers are from the range [1, 9].This problem was asked in ThoughtWorks interview held in October 2018." }, { "code": null, "e": 265, "s": 254, "text": "Examples: " }, { "code": null, "e": 359, "s": 265, "text": "Input: str = “3(ab)4(cd)” Output: abababcdcdcdcdInput: str = “2(kl)3(ap)” Output: klklapapap " }, { "code": null, "e": 764, "s": 359, "text": "Approach: We traverse through the string and wait for a numeric value, num to turn up at position i. As soon as it arrives, we check i + 1 for a ‘(‘. If it’s present, then the program enters into a loop to extract whatever is within ‘(‘ and ‘)’ and concatenate it to an empty string, temp. Later, another loop prints the generated string num number of times. Repeat these steps until the string finishes." }, { "code": null, "e": 810, "s": 764, "text": "Below is the implementation of the approach: " }, { "code": null, "e": 814, "s": 810, "text": "C++" }, { "code": null, "e": 819, "s": 814, "text": "Java" }, { "code": null, "e": 827, "s": 819, "text": "Python3" }, { "code": null, "e": 830, "s": 827, "text": "C#" }, { "code": null, "e": 841, "s": 830, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include<bits/stdc++.h>using namespace std; // Function to expand and print the given stringvoid expandString(string strin){ string temp = \"\"; int j; for (int i = 0; i < strin.length(); i++) { if (strin[i] >= 0) { // Subtract '0' to convert char to int int num = strin[i] - '0'; if (strin[i + 1] == '(') { // Characters within brackets for (j = i + 1; strin[j] != ')'; j++) { if ((strin[j] >= 'a' && strin[j] <= 'z') || (strin[j] >= 'A' && strin[j] <= 'Z')) { temp += strin[j]; } } // Expanding for (int k = 1; k <= num; k++) { cout << (temp); } // Reset the variables num = 0; temp = \"\"; if (j < strin.length()) { i = j; } } } }} // Driver codeint main(){ string strin = \"3(ab)4(cd)\"; expandString(strin);} // This code is contributed by Surendra_Gangwar", "e": 2088, "s": 841, "text": null }, { "code": "// Java implementation of the approachpublic class GFG { // Function to expand and print the given string static void expandString(String strin) { String temp = \"\"; int j; for (int i = 0; i < strin.length(); i++) { if (strin.charAt(i) >= 0) { // Subtract '0' to convert char to int int num = strin.charAt(i) - '0'; if (strin.charAt(i + 1) == '(') { // Characters within brackets for (j = i + 1; strin.charAt(j) != ')'; j++) { if ((strin.charAt(j) >= 'a' && strin.charAt(j) <= 'z') || (strin.charAt(j) >= 'A' && strin.charAt(j) <= 'Z')) { temp += strin.charAt(j); } } // Expanding for (int k = 1; k <= num; k++) { System.out.print(temp); } // Reset the variables num = 0; temp = \"\"; if (j < strin.length()) { i = j; } } } } } // Driver code public static void main(String args[]) { String strin = \"3(ab)4(cd)\"; expandString(strin); }}", "e": 3492, "s": 2088, "text": null }, { "code": "# Python3 implementation of the approach # Function to expand and print the given stringdef expandString(strin): temp = \"\" j = 0 i = 0 while(i < len(strin)): if (strin[i] >= \"0\"): # Subtract '0' to convert char to int num = ord(strin[i])-ord(\"0\") if (strin[i + 1] == '('): # Characters within brackets j = i + 1 while(strin[j] != ')'): if ((strin[j] >= 'a' and strin[j] <= 'z') or \\ (strin[j] >= 'A' and strin[j] <= 'Z')): temp += strin[j] j += 1 # Expanding for k in range(1, num + 1): print(temp,end=\"\") # Reset the variables num = 0 temp = \"\" if (j < len(strin)): i = j i += 1 # Driver codestrin = \"3(ab)4(cd)\"expandString(strin) # This code is contributed by shubhamsingh10", "e": 4563, "s": 3492, "text": null }, { "code": "// C# implementation of// the above approachusing System;class GFG{ // Function to expand and// print the given stringstatic void expandString(string strin){ string temp = \"\"; int j; for (int i = 0; i < strin.Length; i++) { if (strin[i] >= 0) { // Subtract '0' to // convert char to int int num = strin[i] - '0'; if (strin[i + 1] == '(') { // Characters within brackets for (j = i + 1; strin[j] != ')'; j++) { if ((strin[j] >= 'a' && strin[j] <= 'z') || (strin[j] >= 'A' && strin[j] <= 'Z')) { temp += strin[j]; } } // Expanding for (int k = 1; k <= num; k++) { Console.Write(temp); } // Reset the variables num = 0; temp = \"\"; if (j < strin.Length) { i = j; } } } }} // Driver codepublic static void Main(String [] args){ string strin = \"3(ab)4(cd)\"; expandString(strin);}} // This code is contributed by Chitranayal", "e": 5648, "s": 4563, "text": null }, { "code": "<script>// Javascript implementation of the approach // Function to expand and print the given string function expandString(strin) { let temp = \"\"; let j; for (let i = 0; i < strin.length; i++) { if (strin[i].charCodeAt(0) >= 0) { // Subtract '0' to convert char to int let num = strin[i].charCodeAt(0) - '0'.charCodeAt(0); if (strin[i+1] == '(') { // Characters within brackets for (j = i + 1; strin[j] != ')'; j++) { if ((strin[j] >= 'a' && strin[j] <= 'z') || (strin[j] >= 'A' && strin[j] <= 'Z')) { temp += strin[j]; } } // Expanding for (let k = 1; k <= num; k++) { document.write(temp); } // Reset the variables num = 0; temp = \"\"; if (j < strin.length) { i = j; } } } } } // Driver code let strin = \"3(ab)4(cd)\"; expandString(strin); // This code is contributed by rag2127</script>", "e": 7005, "s": 5648, "text": null }, { "code": null, "e": 7020, "s": 7005, "text": "abababcdcdcdcd" }, { "code": null, "e": 7067, "s": 7022, "text": "Time Complexity: O(N*N)Auxiliary Space: O(1)" }, { "code": null, "e": 7084, "s": 7067, "text": "SURENDRA_GANGWAR" }, { "code": null, "e": 7099, "s": 7084, "text": "SHUBHAMSINGH10" }, { "code": null, "e": 7109, "s": 7099, "text": "Code_Mech" }, { "code": null, "e": 7115, "s": 7109, "text": "ukasp" }, { "code": null, "e": 7123, "s": 7115, "text": "rag2127" }, { "code": null, "e": 7139, "s": 7123, "text": "pankajsharmagfg" }, { "code": null, "e": 7152, "s": 7139, "text": "Thoughtworks" }, { "code": null, "e": 7163, "s": 7152, "text": "Algorithms" }, { "code": null, "e": 7171, "s": 7163, "text": "Strings" }, { "code": null, "e": 7184, "s": 7171, "text": "Thoughtworks" }, { "code": null, "e": 7192, "s": 7184, "text": "Strings" }, { "code": null, "e": 7203, "s": 7192, "text": "Algorithms" } ]
Find the dimensions of Right angled triangle
21 Jun, 2022 Given H (Hypotenuse) and A (area) of a right angled triangle, find the dimensions of right angled triangle such that the hypotenuse is of length H and its area is A. If no such triangle exists, print “Not Possible”. Examples: Input : H = 10, A = 24 Output : P = 6.00, B = 8.00 Input : H = 13, A = 36 Output : Not Possible Approach: Before moving to exact solution, let’s do some of mathematical calculations related to properties of Right-angled triangle. Suppose H = Hypotenuse, P = Perpendicular, B = Base and A = Area of right angled triangle. We have some sort of equations as : P^2 + B^2 = H^2 P * B = 2 * A (P+B)^2 = P^2 + B^2 + 2*P*B = H^2 + 4*A (P+B) = sqrt(H^2 + 4*A) ----1 (P-B)^2 = P^2 + B^2 - 2*P*B = H^2 - 4*A mod(P-B) = sqrt(H^2 - 4*A) ----2 from equation (2) we can conclude that if H^2 < 4*A then no solution is possible. Further from (1)+(2) and (1)-(2) we have : P = (sqrt(H^2 + 4*A) + sqrt(H^2 - 4*A) ) / 2 B = (sqrt(H^2 + 4*A) - sqrt(H^2 - 4*A) ) / 2 Below is the implementation of above approach: C++ Java Python3 C# PHP Javascript // CPP program to find dimensions of// Right angled triangle#include <bits/stdc++.h>using namespace std; // function to calculate dimensionvoid findDimen(int H, int A){ // P^2+B^2 = H^2 // P*B = 2*A // (P+B)^2 = P^2+B^2+2*P*B = H^2+4*A // (P-B)^2 = P^2+B^2-2*P*B = H^2-4*A // P+B = sqrt(H^2+4*A) // |P-B| = sqrt(H^2-4*A) if (H * H < 4 * A) { cout << "Not Possible\n"; return; } // sqrt value of H^2 + 4A and H^2- 4A double apb = sqrt(H * H + 4 * A); double asb = sqrt(H * H - 4 * A); // Set precision cout.precision(2); cout << "P = " << fixed << (apb - asb) / 2.0 << "\n"; cout << "B = " << (apb + asb) / 2.0;} // driver functionint main(){ int H = 5; int A = 6; findDimen(H, A); return 0;} // Java program to find dimensions of// Right angled triangleclass GFG { // function to calculate dimension static void findDimen(int H, int A) { // P^2+B^2 = H^2 // P*B = 2*A // (P+B)^2 = P^2+B^2+2*P*B = H^2+4*A // (P-B)^2 = P^2+B^2-2*P*B = H^2-4*A // P+B = sqrt(H^2+4*A) // |P-B| = sqrt(H^2-4*A) if (H * H < 4 * A) { System.out.println("Not Possible"); return; } // sqrt value of H^2 + 4A and H^2- 4A double apb = Math.sqrt(H * H + 4 * A); double asb = Math.sqrt(H * H - 4 * A); System.out.println("P = " + Math.round(((apb - asb) / 2.0) * 100.0) / 100.0); System.out.print("B = " + Math.round(((apb + asb) / 2.0) * 100.0) / 100.0); } // Driver function public static void main(String[] args) { int H = 5; int A = 6; findDimen(H, A); }} // This code is contributed by Anant Agarwal. # Python code to find dimensions# of Right angled triangle # importing the math package# to use sqrt functionfrom math import sqrt # function to find the dimensionsdef findDimen( H, A): # P ^ 2 + B ^ 2 = H ^ 2 # P * B = 2 * A # (P + B)^2 = P ^ 2 + B ^ 2 + 2 * P*B = H ^ 2 + 4 * A # (P-B)^2 = P ^ 2 + B ^ 2-2 * P*B = H ^ 2-4 * A # P + B = sqrt(H ^ 2 + 4 * A) # |P-B| = sqrt(H ^ 2-4 * A) if H * H < 4 * A: print("Not Possible") return # sqrt value of H ^ 2 + 4A and H ^ 2- 4A apb = sqrt(H * H + 4 * A) asb = sqrt(H * H - 4 * A) # printing the dimensions print("P = ", "%.2f" %((apb - asb) / 2.0)) print("B = ", "%.2f" %((apb + asb) / 2.0)) # driver codeH = 5 # assigning value to HA = 6 # assigning value to AfindDimen(H, A) # calling function # This code is contributed by "Abhishek Sharma 44" // C# program to find dimensions of// Right angled triangleusing System; class GFG { // function to calculate dimension static void findDimen(int H, int A) { // P^2+B^2 = H^2 // P*B = 2*A // (P+B)^2 = P^2+B^2+2*P*B = H^2+4*A // (P-B)^2 = P^2+B^2-2*P*B = H^2-4*A // P+B = sqrt(H^2+4*A) // |P-B| = sqrt(H^2-4*A) if (H * H < 4 * A) { Console.WriteLine("Not Possible"); return; } // sqrt value of H^2 + 4A and H^2- 4A double apb = Math.Sqrt(H * H + 4 * A); double asb = Math.Sqrt(H * H - 4 * A); Console.WriteLine("P = " + Math.Round( ((apb - asb) / 2.0) * 100.0) / 100.0); Console.WriteLine("B = " + Math.Round( ((apb + asb) / 2.0) * 100.0) / 100.0); } // Driver function public static void Main() { int H = 5; int A = 6; findDimen(H, A); }} // This code is contributed by vt_m. <?php// PHP program to find dimensions// of Right angled triangle // function to calculate dimensionfunction findDimen($H, $A){ // P^2+B^2 = H^2 // P*B = 2*A // (P+B)^2 = P^2+B^2+2*P*B = H^2+4*A // (P-B)^2 = P^2+B^2-2*P*B = H^2-4*A // P+B = sqrt(H^2+4*A) // |P-B| = sqrt(H^2-4*A) if ($H * $H < 4 * $A) { echo "Not Possible\n"; return; } // sqrt value of H^2 + 4A and // H^2- 4A $apb = sqrt($H * $H + 4 * $A); $asb = sqrt($H * $H - 4 * $A); echo "P = " , $fixed , ($apb - $asb) / 2.0 , "\n"; echo "B = " , ($apb + $asb) / 2.0;} // Driver Code $H = 5; $A = 6; findDimen($H, $A); // This code is contributed by vt_m.?> <script>// java script program to find dimensions// of Right angled triangle // function to calculate dimensionfunction findDimen(H, A){ // P^2+B^2 = H^2 // P*B = 2*A // (P+B)^2 = P^2+B^2+2*P*B = H^2+4*A // (P-B)^2 = P^2+B^2-2*P*B = H^2-4*A // P+B = sqrt(H^2+4*A) // |P-B| = sqrt(H^2-4*A) if (H * H < 4 * A) { document.write( "Not Possible"); return; } // sqrt value of H^2 + 4A and // H^2- 4A let apb = Math.sqrt(H * H + 4 * A); let asb = Math.sqrt(H * H - 4 * A); document.write( "P = " +((apb - asb) / 2.0).toFixed(2), "<br>"); document.write( "B = " +((apb + asb) / 2.0).toFixed(2));} // Driver Code let H = 5; let A = 6; findDimen(H, A);// This code is contributed by Gottumukkala Bobby</script> Output: P = 3.00 B = 4.00 Time complexity : O(1) Auxiliary Space : O(1) vt_m gottumukkalabobby simranarora5sos ajaymakvana triangle Geometric Mathematical Mathematical Geometric Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n21 Jun, 2022" }, { "code": null, "e": 268, "s": 52, "text": "Given H (Hypotenuse) and A (area) of a right angled triangle, find the dimensions of right angled triangle such that the hypotenuse is of length H and its area is A. If no such triangle exists, print “Not Possible”." }, { "code": null, "e": 279, "s": 268, "text": "Examples: " }, { "code": null, "e": 376, "s": 279, "text": "Input : H = 10, A = 24\nOutput : P = 6.00, B = 8.00\n\nInput : H = 13, A = 36\nOutput : Not Possible" }, { "code": null, "e": 601, "s": 376, "text": "Approach: Before moving to exact solution, let’s do some of mathematical calculations related to properties of Right-angled triangle. Suppose H = Hypotenuse, P = Perpendicular, B = Base and A = Area of right angled triangle." }, { "code": null, "e": 639, "s": 601, "text": "We have some sort of equations as : " }, { "code": null, "e": 1031, "s": 639, "text": "P^2 + B^2 = H^2\nP * B = 2 * A\n(P+B)^2 = P^2 + B^2 + 2*P*B = H^2 + 4*A\n(P+B) = sqrt(H^2 + 4*A) ----1\n(P-B)^2 = P^2 + B^2 - 2*P*B = H^2 - 4*A\nmod(P-B) = sqrt(H^2 - 4*A) ----2\nfrom equation (2) we can conclude that if \nH^2 < 4*A then no solution is possible.\n\nFurther from (1)+(2) and (1)-(2) we have :\nP = (sqrt(H^2 + 4*A) + sqrt(H^2 - 4*A) ) / 2\nB = (sqrt(H^2 + 4*A) - sqrt(H^2 - 4*A) ) / 2" }, { "code": null, "e": 1080, "s": 1031, "text": "Below is the implementation of above approach: " }, { "code": null, "e": 1084, "s": 1080, "text": "C++" }, { "code": null, "e": 1089, "s": 1084, "text": "Java" }, { "code": null, "e": 1097, "s": 1089, "text": "Python3" }, { "code": null, "e": 1100, "s": 1097, "text": "C#" }, { "code": null, "e": 1104, "s": 1100, "text": "PHP" }, { "code": null, "e": 1115, "s": 1104, "text": "Javascript" }, { "code": "// CPP program to find dimensions of// Right angled triangle#include <bits/stdc++.h>using namespace std; // function to calculate dimensionvoid findDimen(int H, int A){ // P^2+B^2 = H^2 // P*B = 2*A // (P+B)^2 = P^2+B^2+2*P*B = H^2+4*A // (P-B)^2 = P^2+B^2-2*P*B = H^2-4*A // P+B = sqrt(H^2+4*A) // |P-B| = sqrt(H^2-4*A) if (H * H < 4 * A) { cout << \"Not Possible\\n\"; return; } // sqrt value of H^2 + 4A and H^2- 4A double apb = sqrt(H * H + 4 * A); double asb = sqrt(H * H - 4 * A); // Set precision cout.precision(2); cout << \"P = \" << fixed << (apb - asb) / 2.0 << \"\\n\"; cout << \"B = \" << (apb + asb) / 2.0;} // driver functionint main(){ int H = 5; int A = 6; findDimen(H, A); return 0;}", "e": 1890, "s": 1115, "text": null }, { "code": "// Java program to find dimensions of// Right angled triangleclass GFG { // function to calculate dimension static void findDimen(int H, int A) { // P^2+B^2 = H^2 // P*B = 2*A // (P+B)^2 = P^2+B^2+2*P*B = H^2+4*A // (P-B)^2 = P^2+B^2-2*P*B = H^2-4*A // P+B = sqrt(H^2+4*A) // |P-B| = sqrt(H^2-4*A) if (H * H < 4 * A) { System.out.println(\"Not Possible\"); return; } // sqrt value of H^2 + 4A and H^2- 4A double apb = Math.sqrt(H * H + 4 * A); double asb = Math.sqrt(H * H - 4 * A); System.out.println(\"P = \" + Math.round(((apb - asb) / 2.0) * 100.0) / 100.0); System.out.print(\"B = \" + Math.round(((apb + asb) / 2.0) * 100.0) / 100.0); } // Driver function public static void main(String[] args) { int H = 5; int A = 6; findDimen(H, A); }} // This code is contributed by Anant Agarwal.", "e": 2839, "s": 1890, "text": null }, { "code": "# Python code to find dimensions# of Right angled triangle # importing the math package# to use sqrt functionfrom math import sqrt # function to find the dimensionsdef findDimen( H, A): # P ^ 2 + B ^ 2 = H ^ 2 # P * B = 2 * A # (P + B)^2 = P ^ 2 + B ^ 2 + 2 * P*B = H ^ 2 + 4 * A # (P-B)^2 = P ^ 2 + B ^ 2-2 * P*B = H ^ 2-4 * A # P + B = sqrt(H ^ 2 + 4 * A) # |P-B| = sqrt(H ^ 2-4 * A) if H * H < 4 * A: print(\"Not Possible\") return # sqrt value of H ^ 2 + 4A and H ^ 2- 4A apb = sqrt(H * H + 4 * A) asb = sqrt(H * H - 4 * A) # printing the dimensions print(\"P = \", \"%.2f\" %((apb - asb) / 2.0)) print(\"B = \", \"%.2f\" %((apb + asb) / 2.0)) # driver codeH = 5 # assigning value to HA = 6 # assigning value to AfindDimen(H, A) # calling function # This code is contributed by \"Abhishek Sharma 44\"", "e": 3701, "s": 2839, "text": null }, { "code": "// C# program to find dimensions of// Right angled triangleusing System; class GFG { // function to calculate dimension static void findDimen(int H, int A) { // P^2+B^2 = H^2 // P*B = 2*A // (P+B)^2 = P^2+B^2+2*P*B = H^2+4*A // (P-B)^2 = P^2+B^2-2*P*B = H^2-4*A // P+B = sqrt(H^2+4*A) // |P-B| = sqrt(H^2-4*A) if (H * H < 4 * A) { Console.WriteLine(\"Not Possible\"); return; } // sqrt value of H^2 + 4A and H^2- 4A double apb = Math.Sqrt(H * H + 4 * A); double asb = Math.Sqrt(H * H - 4 * A); Console.WriteLine(\"P = \" + Math.Round( ((apb - asb) / 2.0) * 100.0) / 100.0); Console.WriteLine(\"B = \" + Math.Round( ((apb + asb) / 2.0) * 100.0) / 100.0); } // Driver function public static void Main() { int H = 5; int A = 6; findDimen(H, A); }} // This code is contributed by vt_m.", "e": 4670, "s": 3701, "text": null }, { "code": "<?php// PHP program to find dimensions// of Right angled triangle // function to calculate dimensionfunction findDimen($H, $A){ // P^2+B^2 = H^2 // P*B = 2*A // (P+B)^2 = P^2+B^2+2*P*B = H^2+4*A // (P-B)^2 = P^2+B^2-2*P*B = H^2-4*A // P+B = sqrt(H^2+4*A) // |P-B| = sqrt(H^2-4*A) if ($H * $H < 4 * $A) { echo \"Not Possible\\n\"; return; } // sqrt value of H^2 + 4A and // H^2- 4A $apb = sqrt($H * $H + 4 * $A); $asb = sqrt($H * $H - 4 * $A); echo \"P = \" , $fixed , ($apb - $asb) / 2.0 , \"\\n\"; echo \"B = \" , ($apb + $asb) / 2.0;} // Driver Code $H = 5; $A = 6; findDimen($H, $A); // This code is contributed by vt_m.?>", "e": 5376, "s": 4670, "text": null }, { "code": "<script>// java script program to find dimensions// of Right angled triangle // function to calculate dimensionfunction findDimen(H, A){ // P^2+B^2 = H^2 // P*B = 2*A // (P+B)^2 = P^2+B^2+2*P*B = H^2+4*A // (P-B)^2 = P^2+B^2-2*P*B = H^2-4*A // P+B = sqrt(H^2+4*A) // |P-B| = sqrt(H^2-4*A) if (H * H < 4 * A) { document.write( \"Not Possible\"); return; } // sqrt value of H^2 + 4A and // H^2- 4A let apb = Math.sqrt(H * H + 4 * A); let asb = Math.sqrt(H * H - 4 * A); document.write( \"P = \" +((apb - asb) / 2.0).toFixed(2), \"<br>\"); document.write( \"B = \" +((apb + asb) / 2.0).toFixed(2));} // Driver Code let H = 5; let A = 6; findDimen(H, A);// This code is contributed by Gottumukkala Bobby</script>", "e": 6157, "s": 5376, "text": null }, { "code": null, "e": 6166, "s": 6157, "text": "Output: " }, { "code": null, "e": 6184, "s": 6166, "text": "P = 3.00\nB = 4.00" }, { "code": null, "e": 6230, "s": 6184, "text": "Time complexity : O(1) Auxiliary Space : O(1)" }, { "code": null, "e": 6235, "s": 6230, "text": "vt_m" }, { "code": null, "e": 6253, "s": 6235, "text": "gottumukkalabobby" }, { "code": null, "e": 6269, "s": 6253, "text": "simranarora5sos" }, { "code": null, "e": 6281, "s": 6269, "text": "ajaymakvana" }, { "code": null, "e": 6290, "s": 6281, "text": "triangle" }, { "code": null, "e": 6300, "s": 6290, "text": "Geometric" }, { "code": null, "e": 6313, "s": 6300, "text": "Mathematical" }, { "code": null, "e": 6326, "s": 6313, "text": "Mathematical" }, { "code": null, "e": 6336, "s": 6326, "text": "Geometric" } ]
URLField – Django Models
12 Feb, 2020 URLField is a CharField, for a URL. It is generally used for storing webpage links or particularly called as URLs. It is validated by URLValidator. To store larger text TextField is used. The default form widget for this field is TextInput. Syntax field_name = models.URLField(max_length=200, **options) URLField has one extra optional argument: URLField.max_length The maximum length (in characters) of the field. The max_length is enforced at the database level and in Django’s validation using MaxLengthValidator. If not specified, a default of 200 is used. Illustration of URLField using an Example. Consider a project named geeksforgeeks having an app named geeks. Refer to the following articles to check how to create a project and an app in Django. How to Create a Basic Project using MVT in Django? How to Create an App in Django ? Enter the following code into models.py file of geeks app. from django.db import modelsfrom django.db.models import Model# Create your models here. class GeeksModel(Model): geeks_field = models.URLField(max_length = 200) Add the geeks app to INSTALLED_APPS # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'geeks',] Now when we run makemigrations command from the terminal, Python manage.py makemigrations A new folder named migrations would be created in geeks directory with a file named 0001_initial.py # Generated by Django 2.2.5 on 2019-09-25 06:00 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name ='GeeksModel', fields =[ ('id', models.AutoField( auto_created = True, primary_key = True, serialize = False, verbose_name ='ID' )), ('geeks_field', models.URLField( max_length = 200, )), ], ), ] Now run, Python manage.py migrate Thus, an geeks_field URLField is created when you run migrations on the project. It is a field to store URLs validated by URLValidator. URLField is used for storing URLs in the database. One can store any kind of URL, either internal or external link. URLField should be given an argument max_length for specifying the maximum length of string it is required to store. In the production server, after the Django application is deployed, space is very limited. So it is always optimal to use max_length according to the requirement of the field. Let us create an instance of the URLField we created and check if it is working. # importing the model# from geeks appfrom geeks.models import GeeksModel # creating a instance of # GeeksModelgeek_object = GeeksModel.objects.create(geeks_field ="https://www.geeksforgeeks.org / charfield-django-models/")geek_object.save() Now let’s check it in admin server. We have created an instance of GeeksModel. Field Options are the arguments given to each field for applying some constraint or imparting a particular characteristic to a particular Field. For example, adding an argument null = True to URLField will enable it to store empty values for that table in relational database.Here are the field options and attributes that an URLField can use. NaveenArora Django-models Python Django Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n12 Feb, 2020" }, { "code": null, "e": 269, "s": 28, "text": "URLField is a CharField, for a URL. It is generally used for storing webpage links or particularly called as URLs. It is validated by URLValidator. To store larger text TextField is used. The default form widget for this field is TextInput." }, { "code": null, "e": 276, "s": 269, "text": "Syntax" }, { "code": null, "e": 332, "s": 276, "text": "field_name = models.URLField(max_length=200, **options)" }, { "code": null, "e": 374, "s": 332, "text": "URLField has one extra optional argument:" }, { "code": null, "e": 394, "s": 374, "text": "URLField.max_length" }, { "code": null, "e": 589, "s": 394, "text": "The maximum length (in characters) of the field. The max_length is enforced at the database level and in Django’s validation using MaxLengthValidator. If not specified, a default of 200 is used." }, { "code": null, "e": 698, "s": 589, "text": "Illustration of URLField using an Example. Consider a project named geeksforgeeks having an app named geeks." }, { "code": null, "e": 785, "s": 698, "text": "Refer to the following articles to check how to create a project and an app in Django." }, { "code": null, "e": 836, "s": 785, "text": "How to Create a Basic Project using MVT in Django?" }, { "code": null, "e": 869, "s": 836, "text": "How to Create an App in Django ?" }, { "code": null, "e": 928, "s": 869, "text": "Enter the following code into models.py file of geeks app." }, { "code": "from django.db import modelsfrom django.db.models import Model# Create your models here. class GeeksModel(Model): geeks_field = models.URLField(max_length = 200)", "e": 1094, "s": 928, "text": null }, { "code": null, "e": 1130, "s": 1094, "text": "Add the geeks app to INSTALLED_APPS" }, { "code": "# Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'geeks',]", "e": 1368, "s": 1130, "text": null }, { "code": null, "e": 1426, "s": 1368, "text": "Now when we run makemigrations command from the terminal," }, { "code": null, "e": 1458, "s": 1426, "text": "Python manage.py makemigrations" }, { "code": null, "e": 1558, "s": 1458, "text": "A new folder named migrations would be created in geeks directory with a file named 0001_initial.py" }, { "code": "# Generated by Django 2.2.5 on 2019-09-25 06:00 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name ='GeeksModel', fields =[ ('id', models.AutoField( auto_created = True, primary_key = True, serialize = False, verbose_name ='ID' )), ('geeks_field', models.URLField( max_length = 200, )), ], ), ]", "e": 2212, "s": 1558, "text": null }, { "code": null, "e": 2221, "s": 2212, "text": "Now run," }, { "code": null, "e": 2246, "s": 2221, "text": "Python manage.py migrate" }, { "code": null, "e": 2382, "s": 2246, "text": "Thus, an geeks_field URLField is created when you run migrations on the project. It is a field to store URLs validated by URLValidator." }, { "code": null, "e": 2872, "s": 2382, "text": "URLField is used for storing URLs in the database. One can store any kind of URL, either internal or external link. URLField should be given an argument max_length for specifying the maximum length of string it is required to store. In the production server, after the Django application is deployed, space is very limited. So it is always optimal to use max_length according to the requirement of the field. Let us create an instance of the URLField we created and check if it is working." }, { "code": "# importing the model# from geeks appfrom geeks.models import GeeksModel # creating a instance of # GeeksModelgeek_object = GeeksModel.objects.create(geeks_field =\"https://www.geeksforgeeks.org / charfield-django-models/\")geek_object.save()", "e": 3114, "s": 2872, "text": null }, { "code": null, "e": 3193, "s": 3114, "text": "Now let’s check it in admin server. We have created an instance of GeeksModel." }, { "code": null, "e": 3537, "s": 3193, "text": "Field Options are the arguments given to each field for applying some constraint or imparting a particular characteristic to a particular Field. For example, adding an argument null = True to URLField will enable it to store empty values for that table in relational database.Here are the field options and attributes that an URLField can use." }, { "code": null, "e": 3549, "s": 3537, "text": "NaveenArora" }, { "code": null, "e": 3563, "s": 3549, "text": "Django-models" }, { "code": null, "e": 3577, "s": 3563, "text": "Python Django" }, { "code": null, "e": 3584, "s": 3577, "text": "Python" } ]
High performance Computing
25 Jun, 2020 It is the use of parallel processing for running advanced application programs efficiently, relatives, and quickly. The term applies especially is a system that function above a teraflop (1012) (floating opm per second). The term High-performance computing is occasionally used as a synonym for supercomputing. Although technically a supercomputer is a system that performs at or near currently highest operational rate for computers. Some supercomputers work at more than a petaflop (1012) floating points opm per second. The most common HPC system all scientific engineers & academic institutions. Some Government agencies particularly military are also relying on APC for complex applications. High-performance Computers :Processors, memory, disks, and OS are elements of high-performance computers of interest to small & medium size businesses today are really clusters of computers. Each individual computer in a commonly configured small cluster has between one and four processors and today ‘s processors typically are from 2 to 4 crores, HPC people often referred to individual computers in a cluster as nodes. A cluster of interest to a small business could have as few as 4 nodes on 16 crores. Common cluster size in many businesses is between 16 & 64 crores or from 64 to 256 crores. The main reason to use this is that in its individual node can work together to solve a problem larger than any one computer can easily solve. These nodes are so connected that they can communicate with each other in order to produce some meaningful work. There are two popular HPC’s software i. e, Linux, and windows. Most of installations are in Linux because of its supercomputer but one can use it with his / her requirements. Importance of High performance Computing : It is used for scientific discoveries, game-changing innovations, and to improve quality of life.It is a foundation for scientific & industrial advancements.It is used in technologies like IoT, AI, 3D imaging evolves & amount of data that is used by organization is increasing exponentially to increase ability of a computer, we use High-performance computer.HPC is used to solve complex modeling problems in a spectrum of disciplines. It includes AI, Nuclear Physics, Climate Modelling, etc.HPC is applied to business uses as well as data warehouses & transaction processing. It is used for scientific discoveries, game-changing innovations, and to improve quality of life. It is a foundation for scientific & industrial advancements. It is used in technologies like IoT, AI, 3D imaging evolves & amount of data that is used by organization is increasing exponentially to increase ability of a computer, we use High-performance computer. HPC is used to solve complex modeling problems in a spectrum of disciplines. It includes AI, Nuclear Physics, Climate Modelling, etc. HPC is applied to business uses as well as data warehouses & transaction processing. Need of High performance Computing : It will complete a time-consuming operation in less time.It will complete an operation under a light deadline and perform a high numbers of operations per second.It is fast computing, we can compute in parallel over lot of computation elements CPU, GPU, etc. It set up very fast network to connect between elements. It will complete a time-consuming operation in less time. It will complete an operation under a light deadline and perform a high numbers of operations per second. It is fast computing, we can compute in parallel over lot of computation elements CPU, GPU, etc. It set up very fast network to connect between elements. Need of ever increasing Performance : Climate modelingDrug discoveryData AnalysisProtein foldingEnergy research Climate modeling Drug discovery Data Analysis Protein folding Energy research Main Components : User → Computers cluster → Data storage In HPC architecture computer servers must be networked together in a cluster.Programs & algorithms are run simultaneously on server in cluster.Cluster is networked to data storage to capture output. Together this achieve a complete set of meaningful work. Computer Organization & Architecture Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Direct Access Media (DMA) Controller in Computer Architecture Architecture of 8085 microprocessor Pin diagram of 8086 microprocessor Control Characters I2C Communication Protocol Pin diagram of 8085 microprocessor Difference between SRAM and DRAM Computer Architecture | Flynn's taxonomy Computer Organization | Different Instruction Cycles Difference between RISC and CISC processor | Set 2
[ { "code": null, "e": 28, "s": 0, "text": "\n25 Jun, 2020" }, { "code": null, "e": 249, "s": 28, "text": "It is the use of parallel processing for running advanced application programs efficiently, relatives, and quickly. The term applies especially is a system that function above a teraflop (1012) (floating opm per second)." }, { "code": null, "e": 725, "s": 249, "text": "The term High-performance computing is occasionally used as a synonym for supercomputing. Although technically a supercomputer is a system that performs at or near currently highest operational rate for computers. Some supercomputers work at more than a petaflop (1012) floating points opm per second. The most common HPC system all scientific engineers & academic institutions. Some Government agencies particularly military are also relying on APC for complex applications." }, { "code": null, "e": 1579, "s": 725, "text": "High-performance Computers :Processors, memory, disks, and OS are elements of high-performance computers of interest to small & medium size businesses today are really clusters of computers. Each individual computer in a commonly configured small cluster has between one and four processors and today ‘s processors typically are from 2 to 4 crores, HPC people often referred to individual computers in a cluster as nodes. A cluster of interest to a small business could have as few as 4 nodes on 16 crores. Common cluster size in many businesses is between 16 & 64 crores or from 64 to 256 crores. The main reason to use this is that in its individual node can work together to solve a problem larger than any one computer can easily solve. These nodes are so connected that they can communicate with each other in order to produce some meaningful work." }, { "code": null, "e": 1754, "s": 1579, "text": "There are two popular HPC’s software i. e, Linux, and windows. Most of installations are in Linux because of its supercomputer but one can use it with his / her requirements." }, { "code": null, "e": 1797, "s": 1754, "text": "Importance of High performance Computing :" }, { "code": null, "e": 2374, "s": 1797, "text": "It is used for scientific discoveries, game-changing innovations, and to improve quality of life.It is a foundation for scientific & industrial advancements.It is used in technologies like IoT, AI, 3D imaging evolves & amount of data that is used by organization is increasing exponentially to increase ability of a computer, we use High-performance computer.HPC is used to solve complex modeling problems in a spectrum of disciplines. It includes AI, Nuclear Physics, Climate Modelling, etc.HPC is applied to business uses as well as data warehouses & transaction processing." }, { "code": null, "e": 2472, "s": 2374, "text": "It is used for scientific discoveries, game-changing innovations, and to improve quality of life." }, { "code": null, "e": 2533, "s": 2472, "text": "It is a foundation for scientific & industrial advancements." }, { "code": null, "e": 2736, "s": 2533, "text": "It is used in technologies like IoT, AI, 3D imaging evolves & amount of data that is used by organization is increasing exponentially to increase ability of a computer, we use High-performance computer." }, { "code": null, "e": 2870, "s": 2736, "text": "HPC is used to solve complex modeling problems in a spectrum of disciplines. It includes AI, Nuclear Physics, Climate Modelling, etc." }, { "code": null, "e": 2955, "s": 2870, "text": "HPC is applied to business uses as well as data warehouses & transaction processing." }, { "code": null, "e": 2992, "s": 2955, "text": "Need of High performance Computing :" }, { "code": null, "e": 3308, "s": 2992, "text": "It will complete a time-consuming operation in less time.It will complete an operation under a light deadline and perform a high numbers of operations per second.It is fast computing, we can compute in parallel over lot of computation elements CPU, GPU, etc. It set up very fast network to connect between elements." }, { "code": null, "e": 3366, "s": 3308, "text": "It will complete a time-consuming operation in less time." }, { "code": null, "e": 3472, "s": 3366, "text": "It will complete an operation under a light deadline and perform a high numbers of operations per second." }, { "code": null, "e": 3626, "s": 3472, "text": "It is fast computing, we can compute in parallel over lot of computation elements CPU, GPU, etc. It set up very fast network to connect between elements." }, { "code": null, "e": 3664, "s": 3626, "text": "Need of ever increasing Performance :" }, { "code": null, "e": 3738, "s": 3664, "text": "Climate modelingDrug discoveryData AnalysisProtein foldingEnergy research" }, { "code": null, "e": 3755, "s": 3738, "text": "Climate modeling" }, { "code": null, "e": 3770, "s": 3755, "text": "Drug discovery" }, { "code": null, "e": 3784, "s": 3770, "text": "Data Analysis" }, { "code": null, "e": 3800, "s": 3784, "text": "Protein folding" }, { "code": null, "e": 3816, "s": 3800, "text": "Energy research" }, { "code": null, "e": 3834, "s": 3816, "text": "Main Components :" }, { "code": null, "e": 3875, "s": 3834, "text": "User → Computers cluster → Data storage " }, { "code": null, "e": 4131, "s": 3875, "text": "In HPC architecture computer servers must be networked together in a cluster.Programs & algorithms are run simultaneously on server in cluster.Cluster is networked to data storage to capture output. Together this achieve a complete set of meaningful work." }, { "code": null, "e": 4168, "s": 4131, "text": "Computer Organization & Architecture" }, { "code": null, "e": 4266, "s": 4168, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4328, "s": 4266, "text": "Direct Access Media (DMA) Controller in Computer Architecture" }, { "code": null, "e": 4364, "s": 4328, "text": "Architecture of 8085 microprocessor" }, { "code": null, "e": 4399, "s": 4364, "text": "Pin diagram of 8086 microprocessor" }, { "code": null, "e": 4418, "s": 4399, "text": "Control Characters" }, { "code": null, "e": 4445, "s": 4418, "text": "I2C Communication Protocol" }, { "code": null, "e": 4480, "s": 4445, "text": "Pin diagram of 8085 microprocessor" }, { "code": null, "e": 4513, "s": 4480, "text": "Difference between SRAM and DRAM" }, { "code": null, "e": 4554, "s": 4513, "text": "Computer Architecture | Flynn's taxonomy" }, { "code": null, "e": 4607, "s": 4554, "text": "Computer Organization | Different Instruction Cycles" } ]
Python | Extract numbers from string
27 Mar, 2019 Many times, while working with strings we come across this issue in which we need to get all the numeric occurrences. This type of problem generally occurs in competitive programming and also in web development. Let’s discuss certain ways in which this problem can be solved. Method #1 : Using List comprehension + isdigit() + split()This problem can be solved by using split function to convert string to list and then the list comprehension which can help us iterating through the list and isdigit function helps to get the digit out of a string. # Python3 code to demonstrate# getting numbers from string # using List comprehension + isdigit() +split() # initializing string test_string = "There are 2 apples for 4 persons" # printing original string print("The original string : " + test_string) # using List comprehension + isdigit() +split()# getting numbers from string res = [int(i) for i in test_string.split() if i.isdigit()] # print resultprint("The numbers list is : " + str(res)) The original string : There are 2 apples for 4 persons The numbers list is : [2, 4] Method #2 : Using re.findall()This particular problem can also be solved using python regex, we can use the findall function to check for the numeric occurrences using matching regex string. # Python3 code to demonstrate# getting numbers from string # using re.findall()import re # initializing string test_string = "There are 2 apples for 4 persons" # printing original string print("The original string : " + test_string) # using re.findall()# getting numbers from string temp = re.findall(r'\d+', test_string)res = list(map(int, temp)) # print resultprint("The numbers list is : " + str(res)) The original string : There are 2 apples for 4 persons The numbers list is : [2, 4] Python string-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Iterate over a list in Python How to iterate through Excel rows in Python? Enumerate() in Python Rotate axis tick labels in Seaborn and Matplotlib Python Dictionary Defaultdict in Python Python program to convert a list to string Python program to add two numbers Python | Get dictionary keys as a list Python Program for Fibonacci numbers
[ { "code": null, "e": 52, "s": 24, "text": "\n27 Mar, 2019" }, { "code": null, "e": 328, "s": 52, "text": "Many times, while working with strings we come across this issue in which we need to get all the numeric occurrences. This type of problem generally occurs in competitive programming and also in web development. Let’s discuss certain ways in which this problem can be solved." }, { "code": null, "e": 601, "s": 328, "text": "Method #1 : Using List comprehension + isdigit() + split()This problem can be solved by using split function to convert string to list and then the list comprehension which can help us iterating through the list and isdigit function helps to get the digit out of a string." }, { "code": "# Python3 code to demonstrate# getting numbers from string # using List comprehension + isdigit() +split() # initializing string test_string = \"There are 2 apples for 4 persons\" # printing original string print(\"The original string : \" + test_string) # using List comprehension + isdigit() +split()# getting numbers from string res = [int(i) for i in test_string.split() if i.isdigit()] # print resultprint(\"The numbers list is : \" + str(res))", "e": 1049, "s": 601, "text": null }, { "code": null, "e": 1134, "s": 1049, "text": "The original string : There are 2 apples for 4 persons\nThe numbers list is : [2, 4]\n" }, { "code": null, "e": 1327, "s": 1136, "text": "Method #2 : Using re.findall()This particular problem can also be solved using python regex, we can use the findall function to check for the numeric occurrences using matching regex string." }, { "code": "# Python3 code to demonstrate# getting numbers from string # using re.findall()import re # initializing string test_string = \"There are 2 apples for 4 persons\" # printing original string print(\"The original string : \" + test_string) # using re.findall()# getting numbers from string temp = re.findall(r'\\d+', test_string)res = list(map(int, temp)) # print resultprint(\"The numbers list is : \" + str(res))", "e": 1736, "s": 1327, "text": null }, { "code": null, "e": 1821, "s": 1736, "text": "The original string : There are 2 apples for 4 persons\nThe numbers list is : [2, 4]\n" }, { "code": null, "e": 1844, "s": 1821, "text": "Python string-programs" }, { "code": null, "e": 1851, "s": 1844, "text": "Python" }, { "code": null, "e": 1867, "s": 1851, "text": "Python Programs" }, { "code": null, "e": 1965, "s": 1867, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1995, "s": 1965, "text": "Iterate over a list in Python" }, { "code": null, "e": 2040, "s": 1995, "text": "How to iterate through Excel rows in Python?" }, { "code": null, "e": 2062, "s": 2040, "text": "Enumerate() in Python" }, { "code": null, "e": 2112, "s": 2062, "text": "Rotate axis tick labels in Seaborn and Matplotlib" }, { "code": null, "e": 2130, "s": 2112, "text": "Python Dictionary" }, { "code": null, "e": 2152, "s": 2130, "text": "Defaultdict in Python" }, { "code": null, "e": 2195, "s": 2152, "text": "Python program to convert a list to string" }, { "code": null, "e": 2229, "s": 2195, "text": "Python program to add two numbers" }, { "code": null, "e": 2268, "s": 2229, "text": "Python | Get dictionary keys as a list" } ]
readelf command in Linux with Examples
12 May, 2022 When we compile source code, an object file is generated of the program and with the help of linker, this object files gets converted to a binary file which, only the machine can understand. This kind of file follows some structures one of which is ELF(Executable and Linkable Format). And to get the information of these ELF files readelf command is used. 1. To display help of readelf command. $readelf This displays the help section of the command containing all its parameters and their uses. 2. To check whether a file is ELF file. $file elf_file If it prints ELF in the output then the file is an ELF file. Note: In our case, file name is elf_file. 3. To generate a elf file using gcc compiler. $gcc filename.c -o elf_file The above command will generate an executable elffile. Note: In our case, the name of file is filename.c and the name of elf file is elf_file. 4. To display file headers of a elf file. $readelf -h elf_file This will display the top-level headers of the elf file. Note: In our case, the name of elf file is elf_file. 5. To display information about the different sections of the process’ address space. $readelf -S elf_file This will display the different sections of the process’ address space. Note: In our case, the name of elf file is elf_file. 6. To display symbols table. $readelf -s elf_file This will display the symbols table of the file. Note: In our case, the name of elf file is elf_file. 7. To display core notes. $readelf -n elf_files This will display the core notes related to the file. Note: In our case, the name of elf file is elf_file. 8. To display relocation section. $readelf -r elf_file This will display the relocks(if present). Note: In our case, the name of elf file is elf_file. 9. To display the dynamic section. $readelf -d elf_file This will display the dynamic section of the file. Note: In our case, the name of elf file is elf_file. 10. To get the version of the readelf command. $readelf -v This will display the version information of the readelf command. ankita_saini linux-command Linux-file-commands Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Docker - COPY Instruction scp command in Linux with Examples chown command in Linux with Examples SED command in Linux | Set 2 nohup Command in Linux with Examples chmod command in Linux with examples mv command in Linux with examples Array Basics in Shell Scripting | Set 1 Introduction to Linux Operating System Basic Operators in Shell Scripting
[ { "code": null, "e": 28, "s": 0, "text": "\n12 May, 2022" }, { "code": null, "e": 385, "s": 28, "text": "When we compile source code, an object file is generated of the program and with the help of linker, this object files gets converted to a binary file which, only the machine can understand. This kind of file follows some structures one of which is ELF(Executable and Linkable Format). And to get the information of these ELF files readelf command is used." }, { "code": null, "e": 424, "s": 385, "text": "1. To display help of readelf command." }, { "code": null, "e": 433, "s": 424, "text": "$readelf" }, { "code": null, "e": 566, "s": 433, "text": " This displays the help section of the command containing all its parameters and their uses. 2. To check whether a file is ELF file." }, { "code": null, "e": 581, "s": 566, "text": "$file elf_file" }, { "code": null, "e": 731, "s": 581, "text": " If it prints ELF in the output then the file is an ELF file. Note: In our case, file name is elf_file. 3. To generate a elf file using gcc compiler." }, { "code": null, "e": 759, "s": 731, "text": "$gcc filename.c -o elf_file" }, { "code": null, "e": 945, "s": 759, "text": " The above command will generate an executable elffile. Note: In our case, the name of file is filename.c and the name of elf file is elf_file. 4. To display file headers of a elf file." }, { "code": null, "e": 966, "s": 945, "text": "$readelf -h elf_file" }, { "code": null, "e": 1163, "s": 966, "text": " This will display the top-level headers of the elf file. Note: In our case, the name of elf file is elf_file. 5. To display information about the different sections of the process’ address space." }, { "code": null, "e": 1184, "s": 1163, "text": "$readelf -S elf_file" }, { "code": null, "e": 1340, "s": 1184, "text": " This will display the different sections of the process’ address space. Note: In our case, the name of elf file is elf_file. 6. To display symbols table." }, { "code": null, "e": 1361, "s": 1340, "text": "$readelf -s elf_file" }, { "code": null, "e": 1491, "s": 1361, "text": " This will display the symbols table of the file. Note: In our case, the name of elf file is elf_file. 7. To display core notes." }, { "code": null, "e": 1513, "s": 1491, "text": "$readelf -n elf_files" }, { "code": null, "e": 1655, "s": 1513, "text": " This will display the core notes related to the file. Note: In our case, the name of elf file is elf_file. 8. To display relocation section." }, { "code": null, "e": 1676, "s": 1655, "text": "$readelf -r elf_file" }, { "code": null, "e": 1808, "s": 1676, "text": " This will display the relocks(if present). Note: In our case, the name of elf file is elf_file. 9. To display the dynamic section." }, { "code": null, "e": 1829, "s": 1808, "text": "$readelf -d elf_file" }, { "code": null, "e": 1981, "s": 1829, "text": " This will display the dynamic section of the file. Note: In our case, the name of elf file is elf_file. 10. To get the version of the readelf command." }, { "code": null, "e": 1993, "s": 1981, "text": "$readelf -v" }, { "code": null, "e": 2060, "s": 1993, "text": " This will display the version information of the readelf command." }, { "code": null, "e": 2073, "s": 2060, "text": "ankita_saini" }, { "code": null, "e": 2087, "s": 2073, "text": "linux-command" }, { "code": null, "e": 2107, "s": 2087, "text": "Linux-file-commands" }, { "code": null, "e": 2118, "s": 2107, "text": "Linux-Unix" }, { "code": null, "e": 2216, "s": 2118, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2242, "s": 2216, "text": "Docker - COPY Instruction" }, { "code": null, "e": 2277, "s": 2242, "text": "scp command in Linux with Examples" }, { "code": null, "e": 2314, "s": 2277, "text": "chown command in Linux with Examples" }, { "code": null, "e": 2343, "s": 2314, "text": "SED command in Linux | Set 2" }, { "code": null, "e": 2380, "s": 2343, "text": "nohup Command in Linux with Examples" }, { "code": null, "e": 2417, "s": 2380, "text": "chmod command in Linux with examples" }, { "code": null, "e": 2451, "s": 2417, "text": "mv command in Linux with examples" }, { "code": null, "e": 2491, "s": 2451, "text": "Array Basics in Shell Scripting | Set 1" }, { "code": null, "e": 2530, "s": 2491, "text": "Introduction to Linux Operating System" } ]
Food Ordering System in C
15 Jun, 2022 Prerequisite: Modular Approach in Programming Problem Statement: Write C program to implement Food ordering with the following functionalities: Login & Signup Search by Food Search by hotels Cart & Order Confirmation Approach and Functionality: This is the main function for signup, From here we are calling the account_check() function to validate the inputs. Following are the functionalities: Input the username, age, email, password, confirm the password, and mobile number. Validate the inputsUsername must contain alphabets.Age must be greater than and not equal to 0.Email must contain @, a comma and length should be greater than 5.Passwords must contain length between 8 to 12 with at least one uppercase, lowercase, number and special character. Both password and confirm password should be the same.Mobile number should contain numbers and exactly 10 digits. Username must contain alphabets. Age must be greater than and not equal to 0. Email must contain @, a comma and length should be greater than 5. Passwords must contain length between 8 to 12 with at least one uppercase, lowercase, number and special character. Both password and confirm password should be the same. Mobile number should contain numbers and exactly 10 digits. After the successful validation of all input fields, it checks whether the same account already exists or not through account_check() functionality. This function implements the login features of our project. While login, the Email, and Password are validated and checked whether it is already signed up. After the successful login, there is an option to choose either Search_by_food() or Search_by_hotels() functionalities. In this functionality, the food order is placed after selecting any Hotel. Once the hotel is selected the list of food is displayed with their respective costs. Once the food is selected, you need to go to option Select Cart for the successful ordering of the foods. Before ordering by the hotel, initialize some default hotels which we are given locally through structures in C for our demonstration. Once the hotels and their respective foods are initialized dynamically, it will display the list of hotels. Once the hotel is selected in the above step, select the food and enter the number of items to order. Once the selection of all the foods is done it will display the total amount of food selected. Move to Select Cart for the successful ordering of the foods. This functionality perform the following: Display the total cost of your orders. Confirm your order and enjoy your food. Initialization Boilerplate Signup Validate Login Hotel Initialization Search by Hotels Search by Food Cart Complete Code // C program to initialize the Food// Ordering System// Initialization#include <stdio.h> // Structure to store the user details// i.e., Signup detailsstruct details { char uname[100]; int age; char password[100]; char email[100]; char mobile[10];}; // Structure to store the hotels// and their food detailsstruct hotels { char hotel[100]; char first_food[20]; char second_food[20]; char third_food[20]; char fourth_food[25]; int first, second, third, fourth;}; // Initialize the hotels and detailsstruct hotels m[5];struct details s[100]; // Function to get the input for// a new accountvoid signup(); // Function to check whether account// is already existed or notvoid account_check(); // Function to validate all input fieldsint validate();void login();void cart();void search_by_hotels();void search_by_food();void food_order(int food); // Function to initialize the hotels and// food structure dynamicallyvoid hotel_initialize();void hotels(int hotel_choice); int flag = 1, i, j = 0, count = 0, caps = 0;int small = 0, special = 0, numbers = 0;int success = 0, x, choice;char temp_name[100], temp_password1[100];char temp_password2[100], temp_email[100];char temp_mobile[100]; int temp_age, total = 0, food_choice, n;int hotel_choice, search_choice, confirm;int ch, food, hotel_id; // C program to implement Boilerplate// Code for the Food Ordering Systemint main(){ while (1) { printf("\n\nWelcome to Food "); printf("Ordering System" "\n\n1)SIGNUP\n"); printf("2)LOGIN\n3)EXIT\n\n"); printf("Enter your choice\t"); scanf("%d", &choice); // Switch Cases switch (choice) { // For Signup Function case 1: { signup(); break; } // For Login Function case 2: { login(); break; } case 3: { exit(1); } default: { printf("\nPlease Enter the " printf("valid choice\n"); break; } } }} // Function to create a new user for// the Food ordering systemvoid signup(){ printf("Enter Your name\t"); scanf("%s", temp_name); printf("Enter Your Age\t"); scanf("%d", &temp_age); printf("Enter Your Email\t"); scanf("%s", temp_email); printf("Enter Password\t"); scanf("%s", temp_password1); printf("Confirm Password\t"); scanf("%s", temp_password2); printf("Enter Your Mobile Number\t"); scanf("%s", temp_mobile); // Function Call to validate // the user creation x = validate(); if (x == 1) account_check();} // Function to validate the user for// the signup processint validate(){ // Validate the name for (i = 0; temp_name[i] != '\0'; i++) { if (!((temp_name[i] >= 'a' && temp_name[i] <= 'z') || (temp_name[i] >= 'A' && temp_name[i] <= 'Z'))) { printf("\nPlease Enter the" printf("valid Name\n"); flag = 0; break; } } if (flag == 1) { count = 0; // Validate the Email ID for (i = 0; temp_email[i] != '\0'; i++) { if (temp_email[i] == '@' || temp_email[i] == '.') count++; } if (count >= 2 && strlen(temp_email) >= 5) { // Validating the password // check if it matches with // correct password or not if (!strcmp(temp_password1, temp_password2)) { if (strlen(temp_password1) >= 8 && strlen(temp_password1) <= 12) { caps = 0; small = 0; numbers = 0; special = 0; for (i = 0; temp_password1[i] != '\0'; i++) { if (temp_password1[i] >= 'A' && temp_password1[i] <= 'Z') caps++; else if (temp_password1[i] >= 'a' && temp_password1[i] <= 'z') small++; else if (temp_password1[i] >= '0' && temp_password1[i] <= '9') numbers++; else if (temp_password1[i] == '@' || temp_password1[i] == '&' || temp_password1[i] == '#' || temp_password1[i] == '*') special++; } if (caps >= 1 && small >= 1 && numbers >= 1 && special >= 1) { // Validating the Input age if (temp_age != 0 && temp_age > 0) { // Validating the Input mobile // number if (strlen(temp_mobile) == 10) { for (i = 0; i < 10; i++) { if (temp_mobile[i] >= '0' && temp_mobile[i] <= '9') { success = 1; } else { printf("\n\nPlease"); printf("Enter Valid "); printf("Mobile " "Number\n\n"); return 0; break; } } // Success is assigned with // value 1, Once every // inputs are correct. if (success == 1) return 1; } else { printf("\n\nPlease Enter the"); printf("10 digit mobile"); printf("number\n\n"); return 0; } } else { printf("\n\nPlease Enter "); printf("the valid age\n\n"); return 0; } } else { printf("\n\nPlease Enter the"); printf("strong password, Your "); printf("password must contain "); printf("atleast one uppercase, "); printf("Lowercase, Number and "); printf("special character\n\n"); return 0; } } else { printf("\nYour Password is very"); printf("short\nLength must "); printf("between 8 to 12\n\n"); return 0; } } else { printf("\nPassword " "Mismatch\n\n"); return 0; } } else { printf("\nPlease Enter Valid E-Mail\n\n"); return 0; } }} // Function to Login the usersvoid login(){ printf("\n\nLOGIN\n\n"); printf("\nEnter Your Email\t"); scanf("%s", temp_email); printf("Enter Your Password\t"); scanf("%s", temp_password1); for (i = 0; i < 100; i++) { // Check whether the input email // is already existed or not if (!strcmp(s[i].email, temp_email)) { // Check whether the password // is matched with email or not if (!strcmp(s[i].password, temp_password1)) { printf("\n\nWelcome %s, "); printf("Your are successfully "); printf("logged in\n\nWe Provide "); printf("two ways of search\n1) "); printf("Search By Hotels\n2) "); printf("Search by Food\n3) "); printf("Exit\n\nPlease Enter"); printf("your choice\t", s[i].uname); scanf("%d", &search_choice); // Get the input whether // the user are going to search // /Order by hotels or search/ // order by food switch (search_choice) { case 1: { search_by_hotels(); break; } case 2: { search_by_food(); break; } case 3: { exit(1); } default: { printf("Please Enter "); printf("the valid choice\n\n"); break; } } break; } else { printf("\n\nInvalid Password! "); printf("Please Enter the "); printf("correct password\n\n"); main(); break; } } else { printf("\n\nAccount doesn't "); printf("exist, Please signup!!\n\n"); main(); break; } }} // Function that initializes the// Hotelsvoid hotel_initialize(){ // Initialize the structure with // Aarya_bhavan hotel and some // foods name with their cost strcpy(m[1].hotel, "Aarya_Bhavan"); strcpy(m[1].first_food, "Sandwich"); strcpy(m[1].second_food, "Pizza"); strcpy(m[1].third_food, "Fried_Rice"); m[1].first = 70; m[1].second = 100; m[1].third = 95; // Initialize the structure with // Banu_Hotel and some foods name // and their respective costs strcpy(m[2].hotel, "Banu_Hotel"); strcpy(m[2].first_food, "Parotta"); strcpy(m[2].second_food, "Noodles"); strcpy(m[2].third_food, "Chicken_Rice"); m[2].first = 15; m[2].second = 75; m[2].third = 80; // Initialize the structure with // SR_Bhavan hotel and some foods // name and their respective costs strcpy(m[3].hotel, "SR_Bhavan"); strcpy(m[3].first_food, "Chicken_Biriyani"); strcpy(m[3].second_food, "Prawn"); strcpy(m[3].third_food, "Faloda"); m[3].first = 90; m[3].second = 120; m[3].third = 35;} // Function that implements the// functionality search by hotelsvoid search_by_hotels(){ hotel_initialize(); printf("\n\nPlease Choose the"); printf("hotels\n\n1) %s\n2) %s\n3) %s", m[1].hotel, m[2].hotel, m[3].hotel); printf("\n4) Exit\n\nPlease "); printf("select the hotel\t"); scanf("%d", &hotel_choice); if (hotel_choice > 4) { printf("Please Enter the"); printf("valid choice\n\n"); search_by_hotels(); } else if (hotel_choice == 4) exit(1); else hotels(hotel_choice);} void hotels(int hotel_choice){ total = 0; while (1) { // Displays the list of foods // available in selected hotel printf("\n\nList of foods available"); printf("in %s\n\n1) %s\tRs: %d\n2)", m[hotel_choice].hotel, m[hotel_choice].first_food, m[hotel_choice].first); printf("%s\tRs: %d\n3) %s\tRs: %d\n4)", m[hotel_choice].second_food, m[hotel_choice].second, m[hotel_choice].third_food, m[hotel_choice].third); printf("Cart\n5) Exit\n\nPlease Enter"); printf("Your Choice\t"); scanf("%d", &food_choice); // Get the input for no. of foods // to calculate the total amount if (food_choice == 1) { printf("Please Enter the "); printf("Count of %s\t", m[hotel_choice].first_food); scanf("%d", &n); total = total + (n * m[hotel_choice].first); } else if (food_choice == 2) { printf("Please Enter Count"); printf("of %s\t", m[hotel_choice].second_food); scanf("%d", &n); total = total + (n * m[hotel_choice].second); } else if (food_choice == 3) { printf("Please Enter the Count"); printf("of %s\t", m[hotel_choice].third_food); scanf("%d", &n); total = total + (n * m[hotel_choice].third); } // Once the user, completed their // order, they can go to cart // by giving choice as 4. else if (food_choice == 4) { cart(); } else if (food_choice == 5) { search_by_hotels(); } else { printf("Please Enter the"); printf("valid Choice\n\n"); } }} // Function to implement the// search by foodvoid search_by_food(){ total = 0; // Initialize all the hotels // and their foods hotel_initialize(); while (1) { printf("\n\nPlease choose the "); printf("food\n\n1) %s\t%d\n2) %s\t%d", m[1].first_food, m[1].first, m[1].second_food, m[1].second); printf("\n3) %s\t%d\n4) %s\t%d\n", m[1].third_food, m[1].third, m[2].first_food, m[2].first); printf("5) %s\t%d\n6) %s\t%d\n", m[2].second_food, m[2].second, m[2].third_food, m[2].third); printf("7) %s\t%d\n8) %s\t%d\n", m[3].first_food, m[3].first, m[3].second_food, m[3].second); printf("9) %s\t%d\n10) Cart\n", m[3].third_food, m[3].third); printf("11) Exit"); printf("\nPlease Enter Your Choice\t"); scanf("%d", &food); if (food > 10) { printf("Please Enter the "); printf("valid choice\n\n"); search_by_food(); } // Moves to the cart // functionality else if (food == 10) cart(); else if (food == 11) exit(1); // Call food_order functionality // to get the no of foods and // to calculate the total // amount of the order. else food_order(food); }} // Function to implement the cartvoid cart(){ printf("\n\n\n\n--------------Cart"); printf("----------------"); printf("\nYour Total Order"); printf("Amount is %d\n", total); printf("\n\nDo You wish to"); printf("order (y=1/n=0):"); scanf("%d", &ch); if (ch == 1) { printf("\n\nThank You for your"); printf("order!! Your Food is on "); printf("the way. Welcome again!!\n\n"); exit(1); } else if (ch == 0) { printf("Do You want to exit -1"); printf("or Go back -0"); scanf("%d", &confirm); if (confirm == 1) { printf("\n\nOops! Your order is"); printf("cancelled!! Exiting.."); printf("Thank You visit again!\n"); exit(1); } else { printf("\n\nThank You\n\n"); login(); } } else { printf("\n\nPlease Enter the "); printf("correct choice\n\n"); cart(); }} // C program to implement the Food// Ordering System#include <stdio.h>#include <string.h> // Structure to store the// user details (Signup details)struct details { char uname[100]; int age; char password[100]; char email[100]; char mobile[10];}; // Structure to store the// hotels and their food detailsstruct hotels { char hotel[100]; char first_food[20]; char second_food[20]; char third_food[20]; char fourth_food[25]; int first, second, third, fourth;}; struct hotels m[5];struct details s[100]; // Function to get the// input for new account.void signup(); // Function to check whether// the account is already// existed or notvoid account_check(); // Function to validate// all the input fields.int validate();void login();void cart();void search_by_hotels();void search_by_food();void food_order(int food); // Function to initialize the// hotels and food// structure dynamicallyvoid hotel_initialize();void hotels(int hotel_choice);int flag = 1, i, j = 0, count = 0, caps = 0;int small = 0, special = 0, numbers = 0;int success = 0, x, choice;char temp_name[100], temp_password1[100];char temp_password2[100], temp_email[100];char temp_mobile[100];int temp_age, total = 0, food_choice, n;int hotel_choice, search_choice, confirm;int ch, food, hotel_id; // Boilerplate Code for the// Food Ordering Systemint main(){ while (1) { printf("" "\n\nWelcome to Food "); printf("Ordering System\n\n1)SIGNUP\n"); printf("2)LOGIN\n3)EXIT\n\n"); printf("Enter your choice\t"); scanf("%d", &choice); switch (choice) { case 1: { signup(); break; } case 2: { login(); break; } case 3: { // exit(1); return 0; } default: { printf("\nPlease Enter the "); printf("valid choice\n"); break; } } }} // Function to create a new// user for the Food ordering// systemvoid signup(){ printf("Enter Your name\t"); scanf("%s", temp_name); printf("Enter Your Age\t"); scanf("%d", &temp_age); printf("Enter Your Email\t"); scanf("%s", temp_email); printf("Enter Password\t"); scanf("%s", temp_password1); printf("Confirm Password\t"); scanf("%s", temp_password2); printf("Enter Your Mobile Number\t"); scanf("%s", temp_mobile); // Function Call to validate // the user creation x = validate(); if (x == 1) account_check();} // Function to validate the user// for signup processint validate(){ // Validate the name for (i = 0; temp_name[i] != '\0'; i++) { if (!((temp_name[i] >= 'a' && temp_name[i] <= 'z') || (temp_name[i] >= 'A' && temp_name[i] <= 'Z'))) { printf("\nPlease Enter the"); printf("valid Name\n"); flag = 0; break; } } if (flag == 1) { count = 0; // Validate the Email ID for (i = 0; temp_email[i] != '\0'; i++) { if (temp_email[i] == '@' || temp_email[i] == '.') count++; } if (count >= 2 && strlen(temp_email) >= 5) { // Validating the Password and // Check whether it matches // with Conform Password if (!strcmp(temp_password1, temp_password2)) { if (strlen(temp_password1) >= 8 && strlen(temp_password1) <= 12) { caps = 0; small = 0; numbers = 0; special = 0; for (i = 0; temp_password1[i] != '\0'; i++) { if (temp_password1[i] >= 'A' && temp_password1[i] <= 'Z') caps++; else if (temp_password1[i] >= 'a' && temp_password1[i] <= 'z') small++; else if (temp_password1[i] >= '0' && temp_password1[i] <= '9') numbers++; else if (temp_password1[i] == '@' || temp_password1[i] == '&' || temp_password1[i] == '#' || temp_password1[i] == '*') special++; } if (caps >= 1 && small >= 1 && numbers >= 1 && special >= 1) { // Validating the Input age if (temp_age != 0 && temp_age > 0) { // Validating the Input mobile // number if (strlen(temp_mobile) == 10) { for (i = 0; i < 10; i++) { if (temp_mobile[i] >= '0' && temp_mobile[i] <= '9') { success = 1; } else { printf("\n\nPlease"); printf("Enter Valid "); printf("Mobile " "Number\n\n"); return 0; break; } } // Success is assigned with // value 1, Once every // inputs are correct. if (success == 1) return 1; } else { printf("\n\nPlease Enter the"); printf("10 digit mobile"); printf("number\n\n"); return 0; } } else { printf("\n\nPlease Enter "); printf("the valid age\n\n"); return 0; } } else { printf("\n\nPlease Enter the"); printf("strong password, Your "); printf("password must contain "); printf("atleast one uppercase, "); printf("Lowercase, Number and "); printf("special character\n\n"); return 0; } } else { printf("\nYour Password is very"); printf("short\nLength must "); printf("between 8 to 12\n\n"); return 0; } } else { printf("\nPassword Mismatch\n\n"); return 0; } } else { printf("\nPlease Enter" " Valid E-Mail\n\n"); return 0; } }} // Function to check if the account// already exists or notvoid account_check(){ for (i = 0; i < 100; i++) { // Check whether the email // and password are already // matched with existed account if (!(strcmp(temp_email, s[i].email) && strcmp(temp_password1, s[i].password))) { printf("\n\nAccount Already"); printf("Existed. Please Login !!\n\n"); main(); break; } } // if account does not already // existed, it creates a new // one with new inputs if (i == 100) { strcpy(s[j].uname, temp_name); s[j].age = temp_age; strcpy(s[j].password, temp_password1); strcpy(s[j].email, temp_email); strcpy(s[j].mobile, temp_mobile); j++; printf("\n\n\nAccount Successfully"); printf("Created!!\n\n"); }} // Function to Login the usersvoid login(){ printf("\n\nLOGIN\n\n"); printf("\nEnter Your Email\t"); scanf("%s", temp_email); printf("Enter Your Password\t"); scanf("%s", temp_password1); for (i = 0; i < 100; i++) { // Check whether the input // email is already existed or not if (!strcmp(s[i].email, temp_email)) { // Check whether the password // is matched with the email or not if (!strcmp(s[i].password, temp_password1)) { printf("\n\nWelcome %s, ", s[i].uname); printf("Your are successfully "); printf("logged in\n\nWe Provide "); printf("two ways of search\n1) "); printf("Search By Hotels\n2) "); printf("Search by Food\n3) "); printf("Exit\n\nPlease Enter"); printf("your choice\t"); scanf("%d", &search_choice); // Getting the input whether // the user are going to search // /Order by hotels or search/ // order by food. switch (search_choice) { case 1: { search_by_hotels(); break; } case 2: { search_by_food(); break; } case 3: { // exit(1); return; } default: { printf("Please Enter "); printf("the valid choice\n\n"); break; } } break; } else { printf("\n\nInvalid Password! "); printf("Please Enter the "); printf("correct password\n\n"); main(); break; } } else { printf("\n\nAccount doesn't "); printf("exist, Please signup!!\n\n"); main(); break; } }} // Function to implement the Hotel// initializervoid hotel_initialize(){ // Initializing the structure // with Aarya_bhavan hotel and // some foods name and // their respective costs. strcpy(m[1].hotel, "Aarya_Bhavan"); strcpy(m[1].first_food, "Sandwich"); strcpy(m[1].second_food, "Pizza"); strcpy(m[1].third_food, "Fried_Rice"); m[1].first = 70; m[1].second = 100; m[1].third = 95; // Initializing the structure with // Banu_Hotel and some foods name // and their respective costs. strcpy(m[2].hotel, "Banu_Hotel"); strcpy(m[2].first_food, "Parotta"); strcpy(m[2].second_food, "Noodles"); strcpy(m[2].third_food, "Chicken_Rice"); m[2].first = 15; m[2].second = 75; m[2].third = 80; // Initializing the structure with // SR_Bhavan hotel and some foods // name and their respective costs. strcpy(m[3].hotel, "SR_Bhavan"); strcpy(m[3].first_food, "Chicken_Biriyani"); strcpy(m[3].second_food, "Prawn"); strcpy(m[3].third_food, "Faloda"); m[3].first = 90; m[3].second = 120; m[3].third = 35;} // Function to implement the search// by hotelsvoid search_by_hotels(){ hotel_initialize(); printf("" "\n\nPlease Choose the"); printf("hotels\n\n1) %s\n2) %s\n3) %s", m[1].hotel, m[2].hotel, m[3].hotel); printf("\n4) Exit\n\nPlease "); printf("select the hotel\t"); scanf("%d", &hotel_choice); if (hotel_choice > 4) { printf("Please Enter the"); printf("valid choice\n\n"); search_by_hotels(); } else if (hotel_choice == 4) // exit(1); return; else hotels(hotel_choice);} // Function to implement the hotelvoid hotels(int hotel_choice){ total = 0; while (1) { // Displays the list of // foods available in // selected hotel printf("\n\nList of foods available"); printf("in %s\n\n1) %s\tRs: %d\n2)", m[hotel_choice].hotel, m[hotel_choice].first_food, m[hotel_choice].first); printf("%s\tRs: %d\n3) %s\tRs: %d\n4)", m[hotel_choice].second_food, m[hotel_choice].second, m[hotel_choice].third_food, m[hotel_choice].third); printf("Cart\n5) Exit\n\nPlease Enter"); printf("Your Choice\t"); scanf("%d", &food_choice); // Get the input for no // of foods to calculate // the total amount if (food_choice == 1) { printf("Please Enter the "); printf("Count of %s\t", m[hotel_choice].first_food); scanf("%d", &n); total = total + (n * m[hotel_choice].first); } else if (food_choice == 2) { printf("Please Enter the Count"); printf("of %s\t", m[hotel_choice].second_food); scanf("%d", &n); total = total + (n * m[hotel_choice].second); } else if (food_choice == 3) { printf("Please Enter the Count"); printf("of %s\t", m[hotel_choice].third_food); scanf("%d", &n); total = total + (n * m[hotel_choice].third); } // Once the user, completed their // order, they can go to cart // by giving choice as 4. else if (food_choice == 4) { cart(); } else if (food_choice == 5) { search_by_hotels(); } else { printf("Please Enter the"); printf("valid Choice\n\n"); } }} void search_by_food(){ total = 0; // Initialize all the // hotels and their foods hotel_initialize(); while (1) { printf("\n\nPlease choose the "); printf("food\n\n1) %s\t%d\n2) %s\t%d", m[1].first_food, m[1].first, m[1].second_food, m[1].second); printf("\n3) %s\t%d\n4) %s\t%d\n", m[1].third_food, m[1].third, m[2].first_food, m[2].first); printf("5) %s\t%d\n6) %s\t%d\n", m[2].second_food, m[2].second, m[2].third_food, m[2].third); printf("7) %s\t%d\n8) %s\t%d\n", m[3].first_food, m[3].first, m[3].second_food, m[3].second); printf("9) %s\t%d\n10) Cart\n", m[3].third_food, m[3].third); printf("11) Exit"); printf("\nPlease Enter Your Choice\t"); scanf("%d", &food); if (food > 10) { printf("Please Enter the "); printf("valid choice\n\n"); search_by_food(); } // Moves to the cart // functionality else if (food == 10) cart(); else if (food == 11) // exit(1); return; // Call food_order functionality // to get the no of foods and // to calculate the total // amount of the order. else food_order(food); }} // Function to implement the food// order functionalityvoid food_order(int food){ if (food >= 1 && food <= 3) hotel_id = 1; else if (food >= 4 && food <= 6) hotel_id = 2; else hotel_id = 3; if ((food % 3) == 1) { printf("Please Enter the"); printf(" Count of %s\t", m[hotel_id].first_food); scanf("%d", &n); total = total + (n * m[hotel_id].first); } else if ((food % 3) == 2) { printf("Please Enter the "); printf("Count of %s\t", m[hotel_id].second_food); scanf("%d", &n); total = total + (n * m[hotel_id].second); } else if ((food % 3) == 0) { printf("Please Enter the "); printf("Count of %s\t", m[hotel_id].third_food); scanf("%d", &n); total = total + (n * m[hotel_id].third); }} // Function to implement the cartvoid cart(){ printf("\n\n\n\n--------------Cart"); printf("----------------"); printf("\nYour Total Order"); printf("Amount is %d\n", total); printf("\n\nDo You wish to"); printf("order (y=1/n=0):"); scanf("%d", &ch); if (ch == 1) { printf("\n\nThank You for your"); printf("order!! Your Food is on "); printf("the way. Welcome again!!\n\n"); // exit(1); return; } else if (ch == 0) { printf("Do You want to exit -1"); printf("or Go back -0"); scanf("%d", &confirm); if (confirm == 1) { printf("\n\nOops! Your order is"); printf("cancelled!! Exiting.."); printf("Thank You visit again!\n"); // exit(1); return; } else { printf("\n\nThank You\n\n"); login(); } } else { printf("\n\nPlease Enter the "); printf("correct choice\n\n"); cart(); }} Output: Boilerplate Code: Signup: Login: Validate: Account Check: Search By Hotels: Search By Food: Cart: sumitgumber28 simmytarika5 C-programming C Language C Programs Project School Programming Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n15 Jun, 2022" }, { "code": null, "e": 196, "s": 52, "text": "Prerequisite: Modular Approach in Programming Problem Statement: Write C program to implement Food ordering with the following functionalities:" }, { "code": null, "e": 211, "s": 196, "text": "Login & Signup" }, { "code": null, "e": 226, "s": 211, "text": "Search by Food" }, { "code": null, "e": 243, "s": 226, "text": "Search by hotels" }, { "code": null, "e": 269, "s": 243, "text": "Cart & Order Confirmation" }, { "code": null, "e": 297, "s": 269, "text": "Approach and Functionality:" }, { "code": null, "e": 448, "s": 297, "text": "This is the main function for signup, From here we are calling the account_check() function to validate the inputs. Following are the functionalities:" }, { "code": null, "e": 531, "s": 448, "text": "Input the username, age, email, password, confirm the password, and mobile number." }, { "code": null, "e": 922, "s": 531, "text": "Validate the inputsUsername must contain alphabets.Age must be greater than and not equal to 0.Email must contain @, a comma and length should be greater than 5.Passwords must contain length between 8 to 12 with at least one uppercase, lowercase, number and special character. Both password and confirm password should be the same.Mobile number should contain numbers and exactly 10 digits." }, { "code": null, "e": 955, "s": 922, "text": "Username must contain alphabets." }, { "code": null, "e": 1000, "s": 955, "text": "Age must be greater than and not equal to 0." }, { "code": null, "e": 1067, "s": 1000, "text": "Email must contain @, a comma and length should be greater than 5." }, { "code": null, "e": 1238, "s": 1067, "text": "Passwords must contain length between 8 to 12 with at least one uppercase, lowercase, number and special character. Both password and confirm password should be the same." }, { "code": null, "e": 1298, "s": 1238, "text": "Mobile number should contain numbers and exactly 10 digits." }, { "code": null, "e": 1447, "s": 1298, "text": "After the successful validation of all input fields, it checks whether the same account already exists or not through account_check() functionality." }, { "code": null, "e": 1723, "s": 1447, "text": "This function implements the login features of our project. While login, the Email, and Password are validated and checked whether it is already signed up. After the successful login, there is an option to choose either Search_by_food() or Search_by_hotels() functionalities." }, { "code": null, "e": 1990, "s": 1723, "text": "In this functionality, the food order is placed after selecting any Hotel. Once the hotel is selected the list of food is displayed with their respective costs. Once the food is selected, you need to go to option Select Cart for the successful ordering of the foods." }, { "code": null, "e": 2233, "s": 1990, "text": "Before ordering by the hotel, initialize some default hotels which we are given locally through structures in C for our demonstration. Once the hotels and their respective foods are initialized dynamically, it will display the list of hotels." }, { "code": null, "e": 2492, "s": 2233, "text": "Once the hotel is selected in the above step, select the food and enter the number of items to order. Once the selection of all the foods is done it will display the total amount of food selected. Move to Select Cart for the successful ordering of the foods." }, { "code": null, "e": 2534, "s": 2492, "text": "This functionality perform the following:" }, { "code": null, "e": 2573, "s": 2534, "text": "Display the total cost of your orders." }, { "code": null, "e": 2613, "s": 2573, "text": "Confirm your order and enjoy your food." }, { "code": null, "e": 2628, "s": 2613, "text": "Initialization" }, { "code": null, "e": 2640, "s": 2628, "text": "Boilerplate" }, { "code": null, "e": 2647, "s": 2640, "text": "Signup" }, { "code": null, "e": 2656, "s": 2647, "text": "Validate" }, { "code": null, "e": 2662, "s": 2656, "text": "Login" }, { "code": null, "e": 2683, "s": 2662, "text": "Hotel Initialization" }, { "code": null, "e": 2700, "s": 2683, "text": "Search by Hotels" }, { "code": null, "e": 2715, "s": 2700, "text": "Search by Food" }, { "code": null, "e": 2720, "s": 2715, "text": "Cart" }, { "code": null, "e": 2734, "s": 2720, "text": "Complete Code" }, { "code": "// C program to initialize the Food// Ordering System// Initialization#include <stdio.h> // Structure to store the user details// i.e., Signup detailsstruct details { char uname[100]; int age; char password[100]; char email[100]; char mobile[10];}; // Structure to store the hotels// and their food detailsstruct hotels { char hotel[100]; char first_food[20]; char second_food[20]; char third_food[20]; char fourth_food[25]; int first, second, third, fourth;}; // Initialize the hotels and detailsstruct hotels m[5];struct details s[100]; // Function to get the input for// a new accountvoid signup(); // Function to check whether account// is already existed or notvoid account_check(); // Function to validate all input fieldsint validate();void login();void cart();void search_by_hotels();void search_by_food();void food_order(int food); // Function to initialize the hotels and// food structure dynamicallyvoid hotel_initialize();void hotels(int hotel_choice); int flag = 1, i, j = 0, count = 0, caps = 0;int small = 0, special = 0, numbers = 0;int success = 0, x, choice;char temp_name[100], temp_password1[100];char temp_password2[100], temp_email[100];char temp_mobile[100]; int temp_age, total = 0, food_choice, n;int hotel_choice, search_choice, confirm;int ch, food, hotel_id;", "e": 4054, "s": 2734, "text": null }, { "code": "// C program to implement Boilerplate// Code for the Food Ordering Systemint main(){ while (1) { printf(\"\\n\\nWelcome to Food \"); printf(\"Ordering System\" \"\\n\\n1)SIGNUP\\n\"); printf(\"2)LOGIN\\n3)EXIT\\n\\n\"); printf(\"Enter your choice\\t\"); scanf(\"%d\", &choice); // Switch Cases switch (choice) { // For Signup Function case 1: { signup(); break; } // For Login Function case 2: { login(); break; } case 3: { exit(1); } default: { printf(\"\\nPlease Enter the \" printf(\"valid choice\\n\"); break; } } }}", "e": 4798, "s": 4054, "text": null }, { "code": "// Function to create a new user for// the Food ordering systemvoid signup(){ printf(\"Enter Your name\\t\"); scanf(\"%s\", temp_name); printf(\"Enter Your Age\\t\"); scanf(\"%d\", &temp_age); printf(\"Enter Your Email\\t\"); scanf(\"%s\", temp_email); printf(\"Enter Password\\t\"); scanf(\"%s\", temp_password1); printf(\"Confirm Password\\t\"); scanf(\"%s\", temp_password2); printf(\"Enter Your Mobile Number\\t\"); scanf(\"%s\", temp_mobile); // Function Call to validate // the user creation x = validate(); if (x == 1) account_check();}", "e": 5373, "s": 4798, "text": null }, { "code": "// Function to validate the user for// the signup processint validate(){ // Validate the name for (i = 0; temp_name[i] != '\\0'; i++) { if (!((temp_name[i] >= 'a' && temp_name[i] <= 'z') || (temp_name[i] >= 'A' && temp_name[i] <= 'Z'))) { printf(\"\\nPlease Enter the\" printf(\"valid Name\\n\"); flag = 0; break; } } if (flag == 1) { count = 0; // Validate the Email ID for (i = 0; temp_email[i] != '\\0'; i++) { if (temp_email[i] == '@' || temp_email[i] == '.') count++; } if (count >= 2 && strlen(temp_email) >= 5) { // Validating the password // check if it matches with // correct password or not if (!strcmp(temp_password1, temp_password2)) { if (strlen(temp_password1) >= 8 && strlen(temp_password1) <= 12) { caps = 0; small = 0; numbers = 0; special = 0; for (i = 0; temp_password1[i] != '\\0'; i++) { if (temp_password1[i] >= 'A' && temp_password1[i] <= 'Z') caps++; else if (temp_password1[i] >= 'a' && temp_password1[i] <= 'z') small++; else if (temp_password1[i] >= '0' && temp_password1[i] <= '9') numbers++; else if (temp_password1[i] == '@' || temp_password1[i] == '&' || temp_password1[i] == '#' || temp_password1[i] == '*') special++; } if (caps >= 1 && small >= 1 && numbers >= 1 && special >= 1) { // Validating the Input age if (temp_age != 0 && temp_age > 0) { // Validating the Input mobile // number if (strlen(temp_mobile) == 10) { for (i = 0; i < 10; i++) { if (temp_mobile[i] >= '0' && temp_mobile[i] <= '9') { success = 1; } else { printf(\"\\n\\nPlease\"); printf(\"Enter Valid \"); printf(\"Mobile \" \"Number\\n\\n\"); return 0; break; } } // Success is assigned with // value 1, Once every // inputs are correct. if (success == 1) return 1; } else { printf(\"\\n\\nPlease Enter the\"); printf(\"10 digit mobile\"); printf(\"number\\n\\n\"); return 0; } } else { printf(\"\\n\\nPlease Enter \"); printf(\"the valid age\\n\\n\"); return 0; } } else { printf(\"\\n\\nPlease Enter the\"); printf(\"strong password, Your \"); printf(\"password must contain \"); printf(\"atleast one uppercase, \"); printf(\"Lowercase, Number and \"); printf(\"special character\\n\\n\"); return 0; } } else { printf(\"\\nYour Password is very\"); printf(\"short\\nLength must \"); printf(\"between 8 to 12\\n\\n\"); return 0; } } else { printf(\"\\nPassword \" \"Mismatch\\n\\n\"); return 0; } } else { printf(\"\\nPlease Enter Valid E-Mail\\n\\n\"); return 0; } }}", "e": 10427, "s": 5373, "text": null }, { "code": "// Function to Login the usersvoid login(){ printf(\"\\n\\nLOGIN\\n\\n\"); printf(\"\\nEnter Your Email\\t\"); scanf(\"%s\", temp_email); printf(\"Enter Your Password\\t\"); scanf(\"%s\", temp_password1); for (i = 0; i < 100; i++) { // Check whether the input email // is already existed or not if (!strcmp(s[i].email, temp_email)) { // Check whether the password // is matched with email or not if (!strcmp(s[i].password, temp_password1)) { printf(\"\\n\\nWelcome %s, \"); printf(\"Your are successfully \"); printf(\"logged in\\n\\nWe Provide \"); printf(\"two ways of search\\n1) \"); printf(\"Search By Hotels\\n2) \"); printf(\"Search by Food\\n3) \"); printf(\"Exit\\n\\nPlease Enter\"); printf(\"your choice\\t\", s[i].uname); scanf(\"%d\", &search_choice); // Get the input whether // the user are going to search // /Order by hotels or search/ // order by food switch (search_choice) { case 1: { search_by_hotels(); break; } case 2: { search_by_food(); break; } case 3: { exit(1); } default: { printf(\"Please Enter \"); printf(\"the valid choice\\n\\n\"); break; } } break; } else { printf(\"\\n\\nInvalid Password! \"); printf(\"Please Enter the \"); printf(\"correct password\\n\\n\"); main(); break; } } else { printf(\"\\n\\nAccount doesn't \"); printf(\"exist, Please signup!!\\n\\n\"); main(); break; } }}", "e": 12443, "s": 10427, "text": null }, { "code": "// Function that initializes the// Hotelsvoid hotel_initialize(){ // Initialize the structure with // Aarya_bhavan hotel and some // foods name with their cost strcpy(m[1].hotel, \"Aarya_Bhavan\"); strcpy(m[1].first_food, \"Sandwich\"); strcpy(m[1].second_food, \"Pizza\"); strcpy(m[1].third_food, \"Fried_Rice\"); m[1].first = 70; m[1].second = 100; m[1].third = 95; // Initialize the structure with // Banu_Hotel and some foods name // and their respective costs strcpy(m[2].hotel, \"Banu_Hotel\"); strcpy(m[2].first_food, \"Parotta\"); strcpy(m[2].second_food, \"Noodles\"); strcpy(m[2].third_food, \"Chicken_Rice\"); m[2].first = 15; m[2].second = 75; m[2].third = 80; // Initialize the structure with // SR_Bhavan hotel and some foods // name and their respective costs strcpy(m[3].hotel, \"SR_Bhavan\"); strcpy(m[3].first_food, \"Chicken_Biriyani\"); strcpy(m[3].second_food, \"Prawn\"); strcpy(m[3].third_food, \"Faloda\"); m[3].first = 90; m[3].second = 120; m[3].third = 35;}", "e": 13496, "s": 12443, "text": null }, { "code": "// Function that implements the// functionality search by hotelsvoid search_by_hotels(){ hotel_initialize(); printf(\"\\n\\nPlease Choose the\"); printf(\"hotels\\n\\n1) %s\\n2) %s\\n3) %s\", m[1].hotel, m[2].hotel, m[3].hotel); printf(\"\\n4) Exit\\n\\nPlease \"); printf(\"select the hotel\\t\"); scanf(\"%d\", &hotel_choice); if (hotel_choice > 4) { printf(\"Please Enter the\"); printf(\"valid choice\\n\\n\"); search_by_hotels(); } else if (hotel_choice == 4) exit(1); else hotels(hotel_choice);} void hotels(int hotel_choice){ total = 0; while (1) { // Displays the list of foods // available in selected hotel printf(\"\\n\\nList of foods available\"); printf(\"in %s\\n\\n1) %s\\tRs: %d\\n2)\", m[hotel_choice].hotel, m[hotel_choice].first_food, m[hotel_choice].first); printf(\"%s\\tRs: %d\\n3) %s\\tRs: %d\\n4)\", m[hotel_choice].second_food, m[hotel_choice].second, m[hotel_choice].third_food, m[hotel_choice].third); printf(\"Cart\\n5) Exit\\n\\nPlease Enter\"); printf(\"Your Choice\\t\"); scanf(\"%d\", &food_choice); // Get the input for no. of foods // to calculate the total amount if (food_choice == 1) { printf(\"Please Enter the \"); printf(\"Count of %s\\t\", m[hotel_choice].first_food); scanf(\"%d\", &n); total = total + (n * m[hotel_choice].first); } else if (food_choice == 2) { printf(\"Please Enter Count\"); printf(\"of %s\\t\", m[hotel_choice].second_food); scanf(\"%d\", &n); total = total + (n * m[hotel_choice].second); } else if (food_choice == 3) { printf(\"Please Enter the Count\"); printf(\"of %s\\t\", m[hotel_choice].third_food); scanf(\"%d\", &n); total = total + (n * m[hotel_choice].third); } // Once the user, completed their // order, they can go to cart // by giving choice as 4. else if (food_choice == 4) { cart(); } else if (food_choice == 5) { search_by_hotels(); } else { printf(\"Please Enter the\"); printf(\"valid Choice\\n\\n\"); } }}", "e": 15968, "s": 13496, "text": null }, { "code": "// Function to implement the// search by foodvoid search_by_food(){ total = 0; // Initialize all the hotels // and their foods hotel_initialize(); while (1) { printf(\"\\n\\nPlease choose the \"); printf(\"food\\n\\n1) %s\\t%d\\n2) %s\\t%d\", m[1].first_food, m[1].first, m[1].second_food, m[1].second); printf(\"\\n3) %s\\t%d\\n4) %s\\t%d\\n\", m[1].third_food, m[1].third, m[2].first_food, m[2].first); printf(\"5) %s\\t%d\\n6) %s\\t%d\\n\", m[2].second_food, m[2].second, m[2].third_food, m[2].third); printf(\"7) %s\\t%d\\n8) %s\\t%d\\n\", m[3].first_food, m[3].first, m[3].second_food, m[3].second); printf(\"9) %s\\t%d\\n10) Cart\\n\", m[3].third_food, m[3].third); printf(\"11) Exit\"); printf(\"\\nPlease Enter Your Choice\\t\"); scanf(\"%d\", &food); if (food > 10) { printf(\"Please Enter the \"); printf(\"valid choice\\n\\n\"); search_by_food(); } // Moves to the cart // functionality else if (food == 10) cart(); else if (food == 11) exit(1); // Call food_order functionality // to get the no of foods and // to calculate the total // amount of the order. else food_order(food); }}", "e": 17383, "s": 15968, "text": null }, { "code": "// Function to implement the cartvoid cart(){ printf(\"\\n\\n\\n\\n--------------Cart\"); printf(\"----------------\"); printf(\"\\nYour Total Order\"); printf(\"Amount is %d\\n\", total); printf(\"\\n\\nDo You wish to\"); printf(\"order (y=1/n=0):\"); scanf(\"%d\", &ch); if (ch == 1) { printf(\"\\n\\nThank You for your\"); printf(\"order!! Your Food is on \"); printf(\"the way. Welcome again!!\\n\\n\"); exit(1); } else if (ch == 0) { printf(\"Do You want to exit -1\"); printf(\"or Go back -0\"); scanf(\"%d\", &confirm); if (confirm == 1) { printf(\"\\n\\nOops! Your order is\"); printf(\"cancelled!! Exiting..\"); printf(\"Thank You visit again!\\n\"); exit(1); } else { printf(\"\\n\\nThank You\\n\\n\"); login(); } } else { printf(\"\\n\\nPlease Enter the \"); printf(\"correct choice\\n\\n\"); cart(); }}", "e": 18340, "s": 17383, "text": null }, { "code": "// C program to implement the Food// Ordering System#include <stdio.h>#include <string.h> // Structure to store the// user details (Signup details)struct details { char uname[100]; int age; char password[100]; char email[100]; char mobile[10];}; // Structure to store the// hotels and their food detailsstruct hotels { char hotel[100]; char first_food[20]; char second_food[20]; char third_food[20]; char fourth_food[25]; int first, second, third, fourth;}; struct hotels m[5];struct details s[100]; // Function to get the// input for new account.void signup(); // Function to check whether// the account is already// existed or notvoid account_check(); // Function to validate// all the input fields.int validate();void login();void cart();void search_by_hotels();void search_by_food();void food_order(int food); // Function to initialize the// hotels and food// structure dynamicallyvoid hotel_initialize();void hotels(int hotel_choice);int flag = 1, i, j = 0, count = 0, caps = 0;int small = 0, special = 0, numbers = 0;int success = 0, x, choice;char temp_name[100], temp_password1[100];char temp_password2[100], temp_email[100];char temp_mobile[100];int temp_age, total = 0, food_choice, n;int hotel_choice, search_choice, confirm;int ch, food, hotel_id; // Boilerplate Code for the// Food Ordering Systemint main(){ while (1) { printf(\"\" \"\\n\\nWelcome to Food \"); printf(\"Ordering System\\n\\n1)SIGNUP\\n\"); printf(\"2)LOGIN\\n3)EXIT\\n\\n\"); printf(\"Enter your choice\\t\"); scanf(\"%d\", &choice); switch (choice) { case 1: { signup(); break; } case 2: { login(); break; } case 3: { // exit(1); return 0; } default: { printf(\"\\nPlease Enter the \"); printf(\"valid choice\\n\"); break; } } }} // Function to create a new// user for the Food ordering// systemvoid signup(){ printf(\"Enter Your name\\t\"); scanf(\"%s\", temp_name); printf(\"Enter Your Age\\t\"); scanf(\"%d\", &temp_age); printf(\"Enter Your Email\\t\"); scanf(\"%s\", temp_email); printf(\"Enter Password\\t\"); scanf(\"%s\", temp_password1); printf(\"Confirm Password\\t\"); scanf(\"%s\", temp_password2); printf(\"Enter Your Mobile Number\\t\"); scanf(\"%s\", temp_mobile); // Function Call to validate // the user creation x = validate(); if (x == 1) account_check();} // Function to validate the user// for signup processint validate(){ // Validate the name for (i = 0; temp_name[i] != '\\0'; i++) { if (!((temp_name[i] >= 'a' && temp_name[i] <= 'z') || (temp_name[i] >= 'A' && temp_name[i] <= 'Z'))) { printf(\"\\nPlease Enter the\"); printf(\"valid Name\\n\"); flag = 0; break; } } if (flag == 1) { count = 0; // Validate the Email ID for (i = 0; temp_email[i] != '\\0'; i++) { if (temp_email[i] == '@' || temp_email[i] == '.') count++; } if (count >= 2 && strlen(temp_email) >= 5) { // Validating the Password and // Check whether it matches // with Conform Password if (!strcmp(temp_password1, temp_password2)) { if (strlen(temp_password1) >= 8 && strlen(temp_password1) <= 12) { caps = 0; small = 0; numbers = 0; special = 0; for (i = 0; temp_password1[i] != '\\0'; i++) { if (temp_password1[i] >= 'A' && temp_password1[i] <= 'Z') caps++; else if (temp_password1[i] >= 'a' && temp_password1[i] <= 'z') small++; else if (temp_password1[i] >= '0' && temp_password1[i] <= '9') numbers++; else if (temp_password1[i] == '@' || temp_password1[i] == '&' || temp_password1[i] == '#' || temp_password1[i] == '*') special++; } if (caps >= 1 && small >= 1 && numbers >= 1 && special >= 1) { // Validating the Input age if (temp_age != 0 && temp_age > 0) { // Validating the Input mobile // number if (strlen(temp_mobile) == 10) { for (i = 0; i < 10; i++) { if (temp_mobile[i] >= '0' && temp_mobile[i] <= '9') { success = 1; } else { printf(\"\\n\\nPlease\"); printf(\"Enter Valid \"); printf(\"Mobile \" \"Number\\n\\n\"); return 0; break; } } // Success is assigned with // value 1, Once every // inputs are correct. if (success == 1) return 1; } else { printf(\"\\n\\nPlease Enter the\"); printf(\"10 digit mobile\"); printf(\"number\\n\\n\"); return 0; } } else { printf(\"\\n\\nPlease Enter \"); printf(\"the valid age\\n\\n\"); return 0; } } else { printf(\"\\n\\nPlease Enter the\"); printf(\"strong password, Your \"); printf(\"password must contain \"); printf(\"atleast one uppercase, \"); printf(\"Lowercase, Number and \"); printf(\"special character\\n\\n\"); return 0; } } else { printf(\"\\nYour Password is very\"); printf(\"short\\nLength must \"); printf(\"between 8 to 12\\n\\n\"); return 0; } } else { printf(\"\\nPassword Mismatch\\n\\n\"); return 0; } } else { printf(\"\\nPlease Enter\" \" Valid E-Mail\\n\\n\"); return 0; } }} // Function to check if the account// already exists or notvoid account_check(){ for (i = 0; i < 100; i++) { // Check whether the email // and password are already // matched with existed account if (!(strcmp(temp_email, s[i].email) && strcmp(temp_password1, s[i].password))) { printf(\"\\n\\nAccount Already\"); printf(\"Existed. Please Login !!\\n\\n\"); main(); break; } } // if account does not already // existed, it creates a new // one with new inputs if (i == 100) { strcpy(s[j].uname, temp_name); s[j].age = temp_age; strcpy(s[j].password, temp_password1); strcpy(s[j].email, temp_email); strcpy(s[j].mobile, temp_mobile); j++; printf(\"\\n\\n\\nAccount Successfully\"); printf(\"Created!!\\n\\n\"); }} // Function to Login the usersvoid login(){ printf(\"\\n\\nLOGIN\\n\\n\"); printf(\"\\nEnter Your Email\\t\"); scanf(\"%s\", temp_email); printf(\"Enter Your Password\\t\"); scanf(\"%s\", temp_password1); for (i = 0; i < 100; i++) { // Check whether the input // email is already existed or not if (!strcmp(s[i].email, temp_email)) { // Check whether the password // is matched with the email or not if (!strcmp(s[i].password, temp_password1)) { printf(\"\\n\\nWelcome %s, \", s[i].uname); printf(\"Your are successfully \"); printf(\"logged in\\n\\nWe Provide \"); printf(\"two ways of search\\n1) \"); printf(\"Search By Hotels\\n2) \"); printf(\"Search by Food\\n3) \"); printf(\"Exit\\n\\nPlease Enter\"); printf(\"your choice\\t\"); scanf(\"%d\", &search_choice); // Getting the input whether // the user are going to search // /Order by hotels or search/ // order by food. switch (search_choice) { case 1: { search_by_hotels(); break; } case 2: { search_by_food(); break; } case 3: { // exit(1); return; } default: { printf(\"Please Enter \"); printf(\"the valid choice\\n\\n\"); break; } } break; } else { printf(\"\\n\\nInvalid Password! \"); printf(\"Please Enter the \"); printf(\"correct password\\n\\n\"); main(); break; } } else { printf(\"\\n\\nAccount doesn't \"); printf(\"exist, Please signup!!\\n\\n\"); main(); break; } }} // Function to implement the Hotel// initializervoid hotel_initialize(){ // Initializing the structure // with Aarya_bhavan hotel and // some foods name and // their respective costs. strcpy(m[1].hotel, \"Aarya_Bhavan\"); strcpy(m[1].first_food, \"Sandwich\"); strcpy(m[1].second_food, \"Pizza\"); strcpy(m[1].third_food, \"Fried_Rice\"); m[1].first = 70; m[1].second = 100; m[1].third = 95; // Initializing the structure with // Banu_Hotel and some foods name // and their respective costs. strcpy(m[2].hotel, \"Banu_Hotel\"); strcpy(m[2].first_food, \"Parotta\"); strcpy(m[2].second_food, \"Noodles\"); strcpy(m[2].third_food, \"Chicken_Rice\"); m[2].first = 15; m[2].second = 75; m[2].third = 80; // Initializing the structure with // SR_Bhavan hotel and some foods // name and their respective costs. strcpy(m[3].hotel, \"SR_Bhavan\"); strcpy(m[3].first_food, \"Chicken_Biriyani\"); strcpy(m[3].second_food, \"Prawn\"); strcpy(m[3].third_food, \"Faloda\"); m[3].first = 90; m[3].second = 120; m[3].third = 35;} // Function to implement the search// by hotelsvoid search_by_hotels(){ hotel_initialize(); printf(\"\" \"\\n\\nPlease Choose the\"); printf(\"hotels\\n\\n1) %s\\n2) %s\\n3) %s\", m[1].hotel, m[2].hotel, m[3].hotel); printf(\"\\n4) Exit\\n\\nPlease \"); printf(\"select the hotel\\t\"); scanf(\"%d\", &hotel_choice); if (hotel_choice > 4) { printf(\"Please Enter the\"); printf(\"valid choice\\n\\n\"); search_by_hotels(); } else if (hotel_choice == 4) // exit(1); return; else hotels(hotel_choice);} // Function to implement the hotelvoid hotels(int hotel_choice){ total = 0; while (1) { // Displays the list of // foods available in // selected hotel printf(\"\\n\\nList of foods available\"); printf(\"in %s\\n\\n1) %s\\tRs: %d\\n2)\", m[hotel_choice].hotel, m[hotel_choice].first_food, m[hotel_choice].first); printf(\"%s\\tRs: %d\\n3) %s\\tRs: %d\\n4)\", m[hotel_choice].second_food, m[hotel_choice].second, m[hotel_choice].third_food, m[hotel_choice].third); printf(\"Cart\\n5) Exit\\n\\nPlease Enter\"); printf(\"Your Choice\\t\"); scanf(\"%d\", &food_choice); // Get the input for no // of foods to calculate // the total amount if (food_choice == 1) { printf(\"Please Enter the \"); printf(\"Count of %s\\t\", m[hotel_choice].first_food); scanf(\"%d\", &n); total = total + (n * m[hotel_choice].first); } else if (food_choice == 2) { printf(\"Please Enter the Count\"); printf(\"of %s\\t\", m[hotel_choice].second_food); scanf(\"%d\", &n); total = total + (n * m[hotel_choice].second); } else if (food_choice == 3) { printf(\"Please Enter the Count\"); printf(\"of %s\\t\", m[hotel_choice].third_food); scanf(\"%d\", &n); total = total + (n * m[hotel_choice].third); } // Once the user, completed their // order, they can go to cart // by giving choice as 4. else if (food_choice == 4) { cart(); } else if (food_choice == 5) { search_by_hotels(); } else { printf(\"Please Enter the\"); printf(\"valid Choice\\n\\n\"); } }} void search_by_food(){ total = 0; // Initialize all the // hotels and their foods hotel_initialize(); while (1) { printf(\"\\n\\nPlease choose the \"); printf(\"food\\n\\n1) %s\\t%d\\n2) %s\\t%d\", m[1].first_food, m[1].first, m[1].second_food, m[1].second); printf(\"\\n3) %s\\t%d\\n4) %s\\t%d\\n\", m[1].third_food, m[1].third, m[2].first_food, m[2].first); printf(\"5) %s\\t%d\\n6) %s\\t%d\\n\", m[2].second_food, m[2].second, m[2].third_food, m[2].third); printf(\"7) %s\\t%d\\n8) %s\\t%d\\n\", m[3].first_food, m[3].first, m[3].second_food, m[3].second); printf(\"9) %s\\t%d\\n10) Cart\\n\", m[3].third_food, m[3].third); printf(\"11) Exit\"); printf(\"\\nPlease Enter Your Choice\\t\"); scanf(\"%d\", &food); if (food > 10) { printf(\"Please Enter the \"); printf(\"valid choice\\n\\n\"); search_by_food(); } // Moves to the cart // functionality else if (food == 10) cart(); else if (food == 11) // exit(1); return; // Call food_order functionality // to get the no of foods and // to calculate the total // amount of the order. else food_order(food); }} // Function to implement the food// order functionalityvoid food_order(int food){ if (food >= 1 && food <= 3) hotel_id = 1; else if (food >= 4 && food <= 6) hotel_id = 2; else hotel_id = 3; if ((food % 3) == 1) { printf(\"Please Enter the\"); printf(\" Count of %s\\t\", m[hotel_id].first_food); scanf(\"%d\", &n); total = total + (n * m[hotel_id].first); } else if ((food % 3) == 2) { printf(\"Please Enter the \"); printf(\"Count of %s\\t\", m[hotel_id].second_food); scanf(\"%d\", &n); total = total + (n * m[hotel_id].second); } else if ((food % 3) == 0) { printf(\"Please Enter the \"); printf(\"Count of %s\\t\", m[hotel_id].third_food); scanf(\"%d\", &n); total = total + (n * m[hotel_id].third); }} // Function to implement the cartvoid cart(){ printf(\"\\n\\n\\n\\n--------------Cart\"); printf(\"----------------\"); printf(\"\\nYour Total Order\"); printf(\"Amount is %d\\n\", total); printf(\"\\n\\nDo You wish to\"); printf(\"order (y=1/n=0):\"); scanf(\"%d\", &ch); if (ch == 1) { printf(\"\\n\\nThank You for your\"); printf(\"order!! Your Food is on \"); printf(\"the way. Welcome again!!\\n\\n\"); // exit(1); return; } else if (ch == 0) { printf(\"Do You want to exit -1\"); printf(\"or Go back -0\"); scanf(\"%d\", &confirm); if (confirm == 1) { printf(\"\\n\\nOops! Your order is\"); printf(\"cancelled!! Exiting..\"); printf(\"Thank You visit again!\\n\"); // exit(1); return; } else { printf(\"\\n\\nThank You\\n\\n\"); login(); } } else { printf(\"\\n\\nPlease Enter the \"); printf(\"correct choice\\n\\n\"); cart(); }}", "e": 35677, "s": 18340, "text": null }, { "code": null, "e": 35685, "s": 35677, "text": "Output:" }, { "code": null, "e": 35703, "s": 35685, "text": "Boilerplate Code:" }, { "code": null, "e": 35711, "s": 35703, "text": "Signup:" }, { "code": null, "e": 35718, "s": 35711, "text": "Login:" }, { "code": null, "e": 35728, "s": 35718, "text": "Validate:" }, { "code": null, "e": 35743, "s": 35728, "text": "Account Check:" }, { "code": null, "e": 35761, "s": 35743, "text": "Search By Hotels:" }, { "code": null, "e": 35777, "s": 35761, "text": "Search By Food:" }, { "code": null, "e": 35783, "s": 35777, "text": "Cart:" }, { "code": null, "e": 35797, "s": 35783, "text": "sumitgumber28" }, { "code": null, "e": 35810, "s": 35797, "text": "simmytarika5" }, { "code": null, "e": 35824, "s": 35810, "text": "C-programming" }, { "code": null, "e": 35835, "s": 35824, "text": "C Language" }, { "code": null, "e": 35846, "s": 35835, "text": "C Programs" }, { "code": null, "e": 35854, "s": 35846, "text": "Project" }, { "code": null, "e": 35873, "s": 35854, "text": "School Programming" } ]
C program to create copy of a singly Linked List using Recursion
20 Oct, 2020 Given a pointer to the head node of a Linked List, the task is to create a copy of the linked list using recursion. Examples:: Input: Head of following linked list1->2->3->4->NULLOutput: Original list: 1 -> 2 -> 3 -> 4 -> NULLDuplicate list: 1 -> 2 -> 3 -> 4 -> NULL Input: Head of following linked list1->2->3->4->5->NULLOutput: Original list: 1->2->3->4->5->NULL,Duplicate list: 1->2->3->4->5->NULL, Approach: Follow the steps below to solve the problem: Base case: if (head == NULL), then return NULL.Allocate the new Node in the Heap using malloc() & set its data.Recursively set the next pointer of the new Node by recurring for the remaining nodes.Return the head pointer of the duplicate node.Finally, print both the original linked list and the duplicate linked list. Base case: if (head == NULL), then return NULL. Allocate the new Node in the Heap using malloc() & set its data. Recursively set the next pointer of the new Node by recurring for the remaining nodes. Return the head pointer of the duplicate node. Finally, print both the original linked list and the duplicate linked list. Below is the implementation of the above approach: C // C program for the above approach#include <stdio.h>#include <stdlib.h> // Node for linked liststruct Node { int data; struct Node* next;}; // Function to print given linked listvoid printList(struct Node* head){ struct Node* ptr = head; while (ptr) { printf("%d -> ", ptr->data); ptr = ptr->next; } printf("NULL");} // Function to create a new nodevoid insert(struct Node** head_ref, int data){ // Allocate the memory for new Node // in the heap and set its data struct Node* newNode = (struct Node*)malloc( sizeof(struct Node)); newNode->data = data; // Set the next node pointer of the // new Node to point to the current // node of the list newNode->next = *head_ref; // Change the pointer of head to point // to the new Node *head_ref = newNode;} // Function to create a copy of a linked liststruct Node* copyList(struct Node* head){ if (head == NULL) { return NULL; } else { // Allocate the memory for new Node // in the heap and set its data struct Node* newNode = (struct Node*)malloc( sizeof(struct Node)); newNode->data = head->data; // Recursively set the next pointer of // the new Node by recurring for the // remaining nodes newNode->next = copyList(head->next); return newNode; }} // Function to create the new linked liststruct Node* create(int arr[], int N){ // Pointer to point the head node // of the singly linked list struct Node* head_ref = NULL; // Construct the linked list for (int i = N - 1; i >= 0; i--) { insert(&head_ref, arr[i]); } // Return the head pointer return head_ref;} // Function to create both the listsvoid printLists(struct Node* head_ref, struct Node* dup){ printf("Original list: "); // Print the original linked list printList(head_ref); printf("\nDuplicate list: "); // Print the duplicate linked list printList(dup);} // Driver Codeint main(void){ // Given nodes value int arr[] = { 1, 2, 3, 4, 5 }; int N = sizeof(arr) / sizeof(arr[0]); // Head of the original Linked list struct Node* head_ref = create(arr, N); // Head of the duplicate Linked List struct Node* dup = copyList(head_ref); printLists(head_ref, dup); return 0;} Original list: 1 -> 2 -> 3 -> 4 -> 5 -> NULL Duplicate list: 1 -> 2 -> 3 -> 4 -> 5 -> NULL Time Complexity: O(N)Auxiliary Space: O(N) C-Pointers C Programs Linked List Recursion Linked List Recursion 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 C program to find the length of a string Linked List | Set 1 (Introduction) Linked List | Set 2 (Inserting a node) Reverse a linked list Stack Data Structure (Introduction and Program) Linked List | Set 3 (Deleting a node)
[ { "code": null, "e": 28, "s": 0, "text": "\n20 Oct, 2020" }, { "code": null, "e": 144, "s": 28, "text": "Given a pointer to the head node of a Linked List, the task is to create a copy of the linked list using recursion." }, { "code": null, "e": 155, "s": 144, "text": "Examples::" }, { "code": null, "e": 295, "s": 155, "text": "Input: Head of following linked list1->2->3->4->NULLOutput: Original list: 1 -> 2 -> 3 -> 4 -> NULLDuplicate list: 1 -> 2 -> 3 -> 4 -> NULL" }, { "code": null, "e": 430, "s": 295, "text": "Input: Head of following linked list1->2->3->4->5->NULLOutput: Original list: 1->2->3->4->5->NULL,Duplicate list: 1->2->3->4->5->NULL," }, { "code": null, "e": 485, "s": 430, "text": "Approach: Follow the steps below to solve the problem:" }, { "code": null, "e": 804, "s": 485, "text": "Base case: if (head == NULL), then return NULL.Allocate the new Node in the Heap using malloc() & set its data.Recursively set the next pointer of the new Node by recurring for the remaining nodes.Return the head pointer of the duplicate node.Finally, print both the original linked list and the duplicate linked list." }, { "code": null, "e": 852, "s": 804, "text": "Base case: if (head == NULL), then return NULL." }, { "code": null, "e": 917, "s": 852, "text": "Allocate the new Node in the Heap using malloc() & set its data." }, { "code": null, "e": 1004, "s": 917, "text": "Recursively set the next pointer of the new Node by recurring for the remaining nodes." }, { "code": null, "e": 1051, "s": 1004, "text": "Return the head pointer of the duplicate node." }, { "code": null, "e": 1127, "s": 1051, "text": "Finally, print both the original linked list and the duplicate linked list." }, { "code": null, "e": 1178, "s": 1127, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 1180, "s": 1178, "text": "C" }, { "code": "// C program for the above approach#include <stdio.h>#include <stdlib.h> // Node for linked liststruct Node { int data; struct Node* next;}; // Function to print given linked listvoid printList(struct Node* head){ struct Node* ptr = head; while (ptr) { printf(\"%d -> \", ptr->data); ptr = ptr->next; } printf(\"NULL\");} // Function to create a new nodevoid insert(struct Node** head_ref, int data){ // Allocate the memory for new Node // in the heap and set its data struct Node* newNode = (struct Node*)malloc( sizeof(struct Node)); newNode->data = data; // Set the next node pointer of the // new Node to point to the current // node of the list newNode->next = *head_ref; // Change the pointer of head to point // to the new Node *head_ref = newNode;} // Function to create a copy of a linked liststruct Node* copyList(struct Node* head){ if (head == NULL) { return NULL; } else { // Allocate the memory for new Node // in the heap and set its data struct Node* newNode = (struct Node*)malloc( sizeof(struct Node)); newNode->data = head->data; // Recursively set the next pointer of // the new Node by recurring for the // remaining nodes newNode->next = copyList(head->next); return newNode; }} // Function to create the new linked liststruct Node* create(int arr[], int N){ // Pointer to point the head node // of the singly linked list struct Node* head_ref = NULL; // Construct the linked list for (int i = N - 1; i >= 0; i--) { insert(&head_ref, arr[i]); } // Return the head pointer return head_ref;} // Function to create both the listsvoid printLists(struct Node* head_ref, struct Node* dup){ printf(\"Original list: \"); // Print the original linked list printList(head_ref); printf(\"\\nDuplicate list: \"); // Print the duplicate linked list printList(dup);} // Driver Codeint main(void){ // Given nodes value int arr[] = { 1, 2, 3, 4, 5 }; int N = sizeof(arr) / sizeof(arr[0]); // Head of the original Linked list struct Node* head_ref = create(arr, N); // Head of the duplicate Linked List struct Node* dup = copyList(head_ref); printLists(head_ref, dup); return 0;}", "e": 3585, "s": 1180, "text": null }, { "code": null, "e": 3677, "s": 3585, "text": "Original list: 1 -> 2 -> 3 -> 4 -> 5 -> NULL\nDuplicate list: 1 -> 2 -> 3 -> 4 -> 5 -> NULL\n" }, { "code": null, "e": 3720, "s": 3677, "text": "Time Complexity: O(N)Auxiliary Space: O(N)" }, { "code": null, "e": 3731, "s": 3720, "text": "C-Pointers" }, { "code": null, "e": 3742, "s": 3731, "text": "C Programs" }, { "code": null, "e": 3754, "s": 3742, "text": "Linked List" }, { "code": null, "e": 3764, "s": 3754, "text": "Recursion" }, { "code": null, "e": 3776, "s": 3764, "text": "Linked List" }, { "code": null, "e": 3786, "s": 3776, "text": "Recursion" }, { "code": null, "e": 3884, "s": 3786, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3925, "s": 3884, "text": "C Program to read contents of Whole File" }, { "code": null, "e": 3956, "s": 3925, "text": "Producer Consumer Problem in C" }, { "code": null, "e": 4009, "s": 3956, "text": "Difference between break and continue statement in C" }, { "code": null, "e": 4031, "s": 4009, "text": "C Hello World Program" }, { "code": null, "e": 4072, "s": 4031, "text": "C program to find the length of a string" }, { "code": null, "e": 4107, "s": 4072, "text": "Linked List | Set 1 (Introduction)" }, { "code": null, "e": 4146, "s": 4107, "text": "Linked List | Set 2 (Inserting a node)" }, { "code": null, "e": 4168, "s": 4146, "text": "Reverse a linked list" }, { "code": null, "e": 4216, "s": 4168, "text": "Stack Data Structure (Introduction and Program)" } ]
R – Data Frames
02 Dec, 2021 R Programming Language is an open-source programming language that is widely used as a statistical software and data analysis tool. Data Frames in R Language are generic data objects of R which are used to store the tabular data. Data frames can also be interpreted as matrices where each column of a matrix can be of the different data types. DataFrame is made up of three principal components, the data, rows, and columns. To create a data frame in R use data.frame() command and then pass each of the vectors you have created as arguments to the function. Example: R # R program to create dataframe # creating a data framefriend.data <- data.frame( friend_id = c(1:5), friend_name = c("Sachin", "Sourav", "Dravid", "Sehwag", "Dhoni"), stringsAsFactors = FALSE)# print the data frameprint(friend.data) Output: friend_id friend_name 1 1 Sachin 2 2 Sourav 3 3 Dravid 4 4 Sehwag 5 5 Dhoni One can get the structure of the data frame using str() function in R. It can display even the internal structure of large lists which are nested. It provides one-liner output for the basic R objects letting the user know about the object and its constituents. Example: R # R program to get the# structure of the data frame # creating a data framefriend.data <- data.frame( friend_id = c(1:5), friend_name = c("Sachin", "Sourav", "Dravid", "Sehwag", "Dhoni"), stringsAsFactors = FALSE)# using str()print(str(friend.data)) Output: 'data.frame': 5 obs. of 2 variables: $ friend_id : int 1 2 3 4 5 $ friend_name: chr "Sachin" "Sourav" "Dravid" "Sehwag" ... NULL In R data frame, the statistical summary and nature of the data can be obtained by applying summary() function. It is a generic function used to produce result summaries of the results of various model fitting functions. The function invokes particular methods which depend on the class of the first argument. Example: R # R program to get the# summary of the data frame # creating a data framefriend.data <- data.frame( friend_id = c(1:5), friend_name = c("Sachin", "Sourav", "Dravid", "Sehwag", "Dhoni"), stringsAsFactors = FALSE)# using summary()print(summary(friend.data)) Output: friend_id friend_name Min. :1 Length:5 1st Qu.:2 Class :character Median :3 Mode :character Mean :3 3rd Qu.:4 Max. :5 Extract data from a data frame means that to access its rows or columns. One can extract a specific column from a data frame using its column name. Example: R # R program to extract# data from the data frame # creating a data framefriend.data <- data.frame( friend_id = c(1:5), friend_name = c("Sachin", "Sourav", "Dravid", "Sehwag", "Dhoni"), stringsAsFactors = FALSE) # Extracting friend_name columnresult <- data.frame(friend.data$friend_name)print(result) Output: friend.data.friend_name 1 Sachin 2 Sourav 3 Dravid 4 Sehwag 5 Dhoni A data frame in R can be expanded by adding new columns and rows to the already existing data frame. Example: R # R program to expand# the data frame # creating a data framefriend.data <- data.frame( friend_id = c(1:5), friend_name = c("Sachin", "Sourav", "Dravid", "Sehwag", "Dhoni"), stringsAsFactors = FALSE) # Expanding data framefriend.data$location <- c("Kolkata", "Delhi", "Bangalore", "Hyderabad", "Chennai")resultant <- friend.data# print the modified data frameprint(resultant) Output: friend_id friend_name location 1 1 Sachin Kolkata 2 2 Sourav Delhi 3 3 Dravid Bangalore 4 4 Sehwag Hyderabad 5 5 Dhoni Chennai In R, one can perform various types of operations on a data frame like accessing rows and columns, selecting the subset of the data frame, editing data frames, delete rows and columns in a data frame, etc. Please refer to DataFrame Operations in R to know about all types of operations that can be performed on a data frame. kumar_satyam noriarosedark Picked R-DataFrame R-dataStructures R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n02 Dec, 2021" }, { "code": null, "e": 478, "s": 52, "text": "R Programming Language is an open-source programming language that is widely used as a statistical software and data analysis tool. Data Frames in R Language are generic data objects of R which are used to store the tabular data. Data frames can also be interpreted as matrices where each column of a matrix can be of the different data types. DataFrame is made up of three principal components, the data, rows, and columns. " }, { "code": null, "e": 612, "s": 478, "text": "To create a data frame in R use data.frame() command and then pass each of the vectors you have created as arguments to the function." }, { "code": null, "e": 622, "s": 612, "text": "Example: " }, { "code": null, "e": 624, "s": 622, "text": "R" }, { "code": "# R program to create dataframe # creating a data framefriend.data <- data.frame( friend_id = c(1:5), friend_name = c(\"Sachin\", \"Sourav\", \"Dravid\", \"Sehwag\", \"Dhoni\"), stringsAsFactors = FALSE)# print the data frameprint(friend.data)", "e": 905, "s": 624, "text": null }, { "code": null, "e": 914, "s": 905, "text": "Output: " }, { "code": null, "e": 1062, "s": 914, "text": " friend_id friend_name\n1 1 Sachin\n2 2 Sourav\n3 3 Dravid\n4 4 Sehwag\n5 5 Dhoni" }, { "code": null, "e": 1324, "s": 1062, "text": "One can get the structure of the data frame using str() function in R. It can display even the internal structure of large lists which are nested. It provides one-liner output for the basic R objects letting the user know about the object and its constituents. " }, { "code": null, "e": 1334, "s": 1324, "text": "Example: " }, { "code": null, "e": 1336, "s": 1334, "text": "R" }, { "code": "# R program to get the# structure of the data frame # creating a data framefriend.data <- data.frame( friend_id = c(1:5), friend_name = c(\"Sachin\", \"Sourav\", \"Dravid\", \"Sehwag\", \"Dhoni\"), stringsAsFactors = FALSE)# using str()print(str(friend.data))", "e": 1633, "s": 1336, "text": null }, { "code": null, "e": 1642, "s": 1633, "text": "Output: " }, { "code": null, "e": 1780, "s": 1642, "text": "'data.frame': 5 obs. of 2 variables:\n $ friend_id : int 1 2 3 4 5\n $ friend_name: chr \"Sachin\" \"Sourav\" \"Dravid\" \"Sehwag\" ...\nNULL" }, { "code": null, "e": 2091, "s": 1780, "text": "In R data frame, the statistical summary and nature of the data can be obtained by applying summary() function. It is a generic function used to produce result summaries of the results of various model fitting functions. The function invokes particular methods which depend on the class of the first argument. " }, { "code": null, "e": 2101, "s": 2091, "text": "Example: " }, { "code": null, "e": 2103, "s": 2101, "text": "R" }, { "code": "# R program to get the# summary of the data frame # creating a data framefriend.data <- data.frame( friend_id = c(1:5), friend_name = c(\"Sachin\", \"Sourav\", \"Dravid\", \"Sehwag\", \"Dhoni\"), stringsAsFactors = FALSE)# using summary()print(summary(friend.data))", "e": 2406, "s": 2103, "text": null }, { "code": null, "e": 2415, "s": 2406, "text": "Output: " }, { "code": null, "e": 2622, "s": 2415, "text": " friend_id friend_name \n Min. :1 Length:5 \n 1st Qu.:2 Class :character \n Median :3 Mode :character \n Mean :3 \n 3rd Qu.:4 \n Max. :5 " }, { "code": null, "e": 2771, "s": 2622, "text": "Extract data from a data frame means that to access its rows or columns. One can extract a specific column from a data frame using its column name. " }, { "code": null, "e": 2781, "s": 2771, "text": "Example: " }, { "code": null, "e": 2783, "s": 2781, "text": "R" }, { "code": "# R program to extract# data from the data frame # creating a data framefriend.data <- data.frame( friend_id = c(1:5), friend_name = c(\"Sachin\", \"Sourav\", \"Dravid\", \"Sehwag\", \"Dhoni\"), stringsAsFactors = FALSE) # Extracting friend_name columnresult <- data.frame(friend.data$friend_name)print(result)", "e": 3131, "s": 2783, "text": null }, { "code": null, "e": 3140, "s": 3131, "text": "Output: " }, { "code": null, "e": 3298, "s": 3140, "text": " friend.data.friend_name\n1 Sachin\n2 Sourav\n3 Dravid\n4 Sehwag\n5 Dhoni" }, { "code": null, "e": 3400, "s": 3298, "text": "A data frame in R can be expanded by adding new columns and rows to the already existing data frame. " }, { "code": null, "e": 3410, "s": 3400, "text": "Example: " }, { "code": null, "e": 3412, "s": 3410, "text": "R" }, { "code": "# R program to expand# the data frame # creating a data framefriend.data <- data.frame( friend_id = c(1:5), friend_name = c(\"Sachin\", \"Sourav\", \"Dravid\", \"Sehwag\", \"Dhoni\"), stringsAsFactors = FALSE) # Expanding data framefriend.data$location <- c(\"Kolkata\", \"Delhi\", \"Bangalore\", \"Hyderabad\", \"Chennai\")resultant <- friend.data# print the modified data frameprint(resultant)", "e": 3879, "s": 3412, "text": null }, { "code": null, "e": 3888, "s": 3879, "text": "Output: " }, { "code": null, "e": 4094, "s": 3888, "text": " friend_id friend_name location\n1 1 Sachin Kolkata\n2 2 Sourav Delhi\n3 3 Dravid Bangalore\n4 4 Sehwag Hyderabad\n5 5 Dhoni Chennai" }, { "code": null, "e": 4419, "s": 4094, "text": "In R, one can perform various types of operations on a data frame like accessing rows and columns, selecting the subset of the data frame, editing data frames, delete rows and columns in a data frame, etc. Please refer to DataFrame Operations in R to know about all types of operations that can be performed on a data frame." }, { "code": null, "e": 4432, "s": 4419, "text": "kumar_satyam" }, { "code": null, "e": 4446, "s": 4432, "text": "noriarosedark" }, { "code": null, "e": 4453, "s": 4446, "text": "Picked" }, { "code": null, "e": 4465, "s": 4453, "text": "R-DataFrame" }, { "code": null, "e": 4482, "s": 4465, "text": "R-dataStructures" }, { "code": null, "e": 4493, "s": 4482, "text": "R Language" } ]
Hive – Alter Database
24 Nov, 2020 Apache Hive comes with an already created database with the name default. The default database can not be altered in the Hive because it is restricted. For every successfully created database, the Alteration can be done as per the user requirement. Alteration on the database is made to change its existing properties or characteristics. ALTER command can be used to perform alteration on the databases, tables. To perform the below operation make sure your hive is running. Below are the steps to launch a hive on your local system. Step 1: Start all your Hadoop Daemon start-dfs.sh # this will start namenode, datanode and secondary namenode start-yarn.sh # this will start node manager and resource manager jps # To check running daemons Step 2: Launch Hive hive With the help of the below command, we can add database properties or modify the properties we have added. DBPROPERTIES takes multiple arguments in the form of a key-value pair. Syntax: DATABASE or SCHEMA is the same thing we can use any name. SCHEMA in ALTER is added in hive 0.14.0 and later. ALTER (DATABASE|SCHEMA) <database_name> SET DBPROPERTIES ('<property_name>'='<property_value>',..); Example: Step 1: Create a database with the name student CREATE DATABASE student; Step 2: Use ALTER to add properties to the database ALTER DATABASE student SET DBPROPERTIES ( ' owner ' = ' GFG' , ' Date ' = ' 2020-5-6 '); Step 3: Describe the database to see the effect DESCRIBE DATABASE EXTENDED student; Step 4: Let’s change the existing property to see the effect. In our example, we are changing the owner from GFG to Geeks. ALTER DATABASE student SET DBPROPERTIES ( ' owner ' = ' Geeks ' , ' Date ' = ' 2020-5-6 '); We have successfully overridden the property with ALTER. With the help of the below command, we can change the database directory on HDFS. The LOCATION with ALTER is only available in Hive 2.2.1, 2.4.0, and later. One thing we should keep in mind that changing the database location does not transfer data to the newly specified location. It only changes the parent-directory location and the newly added data will be added to this new HDFS location. Syntax: ALTER (DATABASE|SCHEMA) <database_name> SET LOCATION 'Path_on_HDFS'; Example: Step 1: Describe the database student to see its parent-directory. By default, hive stores its data at /user/hive/warehouse on HDFS. DESCRIBE DATABASE EXTENDED student; Step 2: Use ALTER to change the parent-directory location (NOTE: /hive_db is the available directory on my HDFS ). ALTER DATABASE student SET LOCATION 'hdfs://localhost:9000/hive_db'; Step 3: Describe the database student to see the location is overridden or not. DESCRIBE DATABASE EXTENDED student; We have successfully changed the location of the student database. Now whatever tables you will add to this database will be made in /hive_db. The below command is used to set or change the user name and its ROLE. SET OWNER transfer the current user ownership to a new user or a new role. By default, the user who makes the database is set as the owner of that database. Syntax: ALTER DATABASE <database_name> SET OWNER [USER|ROLE] user_name or role_name; Example: Let’s Change the user name associated with the student database. DESCRIBE DATABASE EXTENDED student; # we have used it to see the current user info ALTER DATABASE student SET OWNER USER Ram; # with this we have changed the db owner from dikshant to Ram Now, change the role of ram to admin. ALTER DATABASE student SET OWNER ROLE admin; Apache-Hive Hadoop Hadoop Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Create Table in Hive? What is Hadoop Streaming? What is Schema On Read and Schema On Write in Hadoop? MapReduce - Understanding With Real-Life Example Apache Hive Hadoop - HDFS (Hadoop Distributed File System) Hive - Alter Table Import and Export Data using SQOOP Difference Between Hadoop and Apache Spark Difference Between Hadoop 2.x vs Hadoop 3.x
[ { "code": null, "e": 28, "s": 0, "text": "\n24 Nov, 2020" }, { "code": null, "e": 277, "s": 28, "text": "Apache Hive comes with an already created database with the name default. The default database can not be altered in the Hive because it is restricted. For every successfully created database, the Alteration can be done as per the user requirement." }, { "code": null, "e": 442, "s": 277, "text": "Alteration on the database is made to change its existing properties or characteristics. ALTER command can be used to perform alteration on the databases, tables. " }, { "code": null, "e": 564, "s": 442, "text": "To perform the below operation make sure your hive is running. Below are the steps to launch a hive on your local system." }, { "code": null, "e": 601, "s": 564, "text": "Step 1: Start all your Hadoop Daemon" }, { "code": null, "e": 841, "s": 601, "text": "start-dfs.sh # this will start namenode, datanode and secondary namenode\n\nstart-yarn.sh # this will start node manager and resource manager \n\njps # To check running daemons\n" }, { "code": null, "e": 861, "s": 841, "text": "Step 2: Launch Hive" }, { "code": null, "e": 867, "s": 861, "text": "hive\n" }, { "code": null, "e": 1045, "s": 867, "text": "With the help of the below command, we can add database properties or modify the properties we have added. DBPROPERTIES takes multiple arguments in the form of a key-value pair." }, { "code": null, "e": 1053, "s": 1045, "text": "Syntax:" }, { "code": null, "e": 1162, "s": 1053, "text": "DATABASE or SCHEMA is the same thing we can use any name. SCHEMA in ALTER is added in hive 0.14.0 and later." }, { "code": null, "e": 1264, "s": 1162, "text": "ALTER (DATABASE|SCHEMA) <database_name> SET DBPROPERTIES ('<property_name>'='<property_value>',..); \n" }, { "code": null, "e": 1273, "s": 1264, "text": "Example:" }, { "code": null, "e": 1322, "s": 1273, "text": "Step 1: Create a database with the name student " }, { "code": null, "e": 1348, "s": 1322, "text": "CREATE DATABASE student;\n" }, { "code": null, "e": 1400, "s": 1348, "text": "Step 2: Use ALTER to add properties to the database" }, { "code": null, "e": 1490, "s": 1400, "text": "ALTER DATABASE student SET DBPROPERTIES ( ' owner ' = ' GFG' , ' Date ' = ' 2020-5-6 ');\n" }, { "code": null, "e": 1540, "s": 1490, "text": "Step 3: Describe the database to see the effect" }, { "code": null, "e": 1577, "s": 1540, "text": "DESCRIBE DATABASE EXTENDED student;\n" }, { "code": null, "e": 1700, "s": 1577, "text": "Step 4: Let’s change the existing property to see the effect. In our example, we are changing the owner from GFG to Geeks." }, { "code": null, "e": 1793, "s": 1700, "text": "ALTER DATABASE student SET DBPROPERTIES ( ' owner ' = ' Geeks ' , ' Date ' = ' 2020-5-6 ');\n" }, { "code": null, "e": 1850, "s": 1793, "text": "We have successfully overridden the property with ALTER." }, { "code": null, "e": 2244, "s": 1850, "text": "With the help of the below command, we can change the database directory on HDFS. The LOCATION with ALTER is only available in Hive 2.2.1, 2.4.0, and later. One thing we should keep in mind that changing the database location does not transfer data to the newly specified location. It only changes the parent-directory location and the newly added data will be added to this new HDFS location." }, { "code": null, "e": 2252, "s": 2244, "text": "Syntax:" }, { "code": null, "e": 2322, "s": 2252, "text": "ALTER (DATABASE|SCHEMA) <database_name> SET LOCATION 'Path_on_HDFS';\n" }, { "code": null, "e": 2331, "s": 2322, "text": "Example:" }, { "code": null, "e": 2464, "s": 2331, "text": "Step 1: Describe the database student to see its parent-directory. By default, hive stores its data at /user/hive/warehouse on HDFS." }, { "code": null, "e": 2501, "s": 2464, "text": "DESCRIBE DATABASE EXTENDED student;\n" }, { "code": null, "e": 2616, "s": 2501, "text": "Step 2: Use ALTER to change the parent-directory location (NOTE: /hive_db is the available directory on my HDFS )." }, { "code": null, "e": 2686, "s": 2616, "text": "ALTER DATABASE student SET LOCATION 'hdfs://localhost:9000/hive_db';\n" }, { "code": null, "e": 2769, "s": 2686, "text": " Step 3: Describe the database student to see the location is overridden or not. " }, { "code": null, "e": 2806, "s": 2769, "text": "DESCRIBE DATABASE EXTENDED student;\n" }, { "code": null, "e": 2949, "s": 2806, "text": "We have successfully changed the location of the student database. Now whatever tables you will add to this database will be made in /hive_db." }, { "code": null, "e": 3177, "s": 2949, "text": "The below command is used to set or change the user name and its ROLE. SET OWNER transfer the current user ownership to a new user or a new role. By default, the user who makes the database is set as the owner of that database." }, { "code": null, "e": 3185, "s": 3177, "text": "Syntax:" }, { "code": null, "e": 3263, "s": 3185, "text": "ALTER DATABASE <database_name> SET OWNER [USER|ROLE] user_name or role_name;\n" }, { "code": null, "e": 3272, "s": 3263, "text": "Example:" }, { "code": null, "e": 3337, "s": 3272, "text": "Let’s Change the user name associated with the student database." }, { "code": null, "e": 3582, "s": 3337, "text": "DESCRIBE DATABASE EXTENDED student; # we have used it to see the current user info \n\nALTER DATABASE student SET OWNER USER Ram; # with this we have changed the db owner from dikshant\n to Ram \n" }, { "code": null, "e": 3620, "s": 3582, "text": "Now, change the role of ram to admin." }, { "code": null, "e": 3666, "s": 3620, "text": "ALTER DATABASE student SET OWNER ROLE admin;\n" }, { "code": null, "e": 3678, "s": 3666, "text": "Apache-Hive" }, { "code": null, "e": 3685, "s": 3678, "text": "Hadoop" }, { "code": null, "e": 3692, "s": 3685, "text": "Hadoop" }, { "code": null, "e": 3790, "s": 3692, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3819, "s": 3790, "text": "How to Create Table in Hive?" }, { "code": null, "e": 3845, "s": 3819, "text": "What is Hadoop Streaming?" }, { "code": null, "e": 3899, "s": 3845, "text": "What is Schema On Read and Schema On Write in Hadoop?" }, { "code": null, "e": 3948, "s": 3899, "text": "MapReduce - Understanding With Real-Life Example" }, { "code": null, "e": 3960, "s": 3948, "text": "Apache Hive" }, { "code": null, "e": 4007, "s": 3960, "text": "Hadoop - HDFS (Hadoop Distributed File System)" }, { "code": null, "e": 4026, "s": 4007, "text": "Hive - Alter Table" }, { "code": null, "e": 4061, "s": 4026, "text": "Import and Export Data using SQOOP" }, { "code": null, "e": 4104, "s": 4061, "text": "Difference Between Hadoop and Apache Spark" } ]
Implementation of LinkedList in Javascript
02 Dec, 2021 In this article, we will be implementing the LinkedList data structure in Javascript. LinkedList is the dynamic data structure, as we can add or remove elements at ease, and it can even grow as needed. Just like arrays, linked lists store elements sequentially, but don’t store the elements contiguously like an array. Now, Let’s see an example of a Linked List Node: Javascript // User defined class nodeclass Node { // constructor constructor(element) { this.element = element; this.next = null }} As in the above code, we define a class Node having two properties: element and next. Element holds the data of a node while next holds the pointer to the next node, which is initialized to the null value. Now, let’s see an implementation of the Linked List class: Javascript // linkedlist classclass LinkedList { constructor() { this.head = null; this.size = 0; } // functions to be implemented // add(element) // insertAt(element, location) // removeFrom(location) // removeElement(element) // Helper Methods // isEmpty // size_Of_List // PrintList} The above example shows a Linked List class with a constructor and a list of methods to be implemented. Linked List class has two properties: i.e. head and size, where the head stores the first node of a List, and size indicates the number of nodes in a list. Let’s implement each of these functions: 1. add(element) – It adds an element at the end of the list. Javascript // adds an element at the end// of listadd(element){ // creates a new node var node = new Node(element); // to store current node var current; // if list is Empty add the // element and make it head if (this.head == null) this.head = node; else { current = this.head; // iterate to the end of the // list while (current.next) { current = current.next; } // add node current.next = node; } this.size++;} In the order to add an element at the end of the list we consider the following : If the list is empty then add an element and it will be head If the list is not empty then iterate to the end of the list and add an element at the end of the list 2. insertAt(element, index) – It inserts an element at the given index in a list. Javascript // insert element at the position index// of the listinsertAt(element, index){ if (index < 0 || index > this.size) return console.log("Please enter a valid index."); else { // creates a new node var node = new Node(element); var curr, prev; curr = this.head; // add the element to the // first index if (index == 0) { node.next = this.head; this.head = node; } else { curr = this.head; var it = 0; // iterate over the list to find // the position to insert while (it < index) { it++; prev = curr; curr = curr.next; } // adding an element node.next = curr; prev.next = node; } this.size++; }} In order to add an element at the given index of the list we consider three conditions as follows: if the index is zero we add an element at the front of the list and make it head If the index is the last position of the list we append the element at the end of the list if the index is between 0 or size – 1 we iterate over to the index and add an element at that index 3. removeFrom(index) – It removes and returns an element from the list from the specified index Javascript // removes an element from the// specified locationremoveFrom(index){ if (index < 0 || index >= this.size) return console.log("Please Enter a valid index"); else { var curr, prev, it = 0; curr = this.head; prev = curr; // deleting first element if (index === 0) { this.head = curr.next; } else { // iterate over the list to the // position to removce an element while (it < index) { it++; prev = curr; curr = curr.next; } // remove the element prev.next = curr.next; } this.size--; // return the remove element return curr.element; }} In order to remove an element from the list we consider three conditions: If the index is 0 then we remove the head and make the next node head of the list if the index is size – 1 then we remove the last element from the list and make prev the last element if it’s in between 0 to size – 1 we remove the element by using prev and the current node 4. removeElement(element) – This method removes element from the list. It returns the removed element, or if it’s not found it returns -1. Javascript // removes a given element from the// listremoveElement(element){ var current = this.head; var prev = null; // iterate over the list while (current != null) { // comparing element with current // element if found then remove the // and return true if (current.element === element) { if (prev == null) { this.head = current.next; } else { prev.next = current.next; } this.size--; return current.element; } prev = current; current = current.next; } return -1;} The above method is just a modification of removeFrom(index), as it searches for an element and removes it, rather than removing it from a specified location Helper Methods Let’s declare some helper methods which are useful while working with LinkedList. 1. indexOf(element) – it returns the index of a given element if the element is in the list. Javascript // finds the index of elementindexOf(element){ var count = 0; var current = this.head; // iterate over the list while (current != null) { // compare each element of the list // with given element if (current.element === element) return count; count++; current = current.next; } // not found return -1;} In this method, we iterate over the list to find the index of an element. If it is not present in the list it returns -1 instead. 2. isEmpty() – it returns true if the list is empty. Javascript // checks the list for emptyisEmpty(){ return this.size == 0;} In this method we check for the size property of the LinkedList class, and if it’s zero then the list is empty. 3. size_of_list() – It returns the size of list Javascript // gives the size of the listsize_of_list(){ console.log(this.size);} 3. printList() – It prints the contents of the list. Javascript // prints the list itemsprintList(){ var curr = this.head; var str = ""; while (curr) { str += curr.element + " "; curr = curr.next; } console.log(str);} In this method, we iterate over the entire list and concatenate the elements of each node and print it. Note: Different helper methods can be declared in the LinkedList class as required. Implementation Now, let’s use the LinkedList class and its different methods described above. Javascript // creating an object for the// Linkedlist classvar ll = new LinkedList(); // testing isEmpty on an empty list// returns trueconsole.log(ll.isEmpty()); // adding element to the listll.add(10); // prints 10ll.printList(); // returns 1console.log(ll.size_of_list()); // adding more elements to the listll.add(20);ll.add(30);ll.add(40);ll.add(50); // returns 10 20 30 40 50ll.printList(); // prints 50 from the listconsole.log("is element removed ?" + ll.removeElement(50)); // prints 10 20 30 40ll.printList(); // returns 3console.log("Index of 40 " + ll.indexOf(40)); // insert 60 at second position// ll contains 10 20 60 30 40ll.insertAt(60, 2); ll.printList(); // returns falseconsole.log("is List Empty ? " + ll.isEmpty()); // remove 3rd element from the listconsole.log(ll.removeFrom(3)); // prints 10 20 60 40ll.printList(); Complete Code: Javascript class Node { // constructor constructor(element) { this.element = element; this.next = null }}// linkedlist classclass LinkedList { constructor() { this.head = null; this.size = 0; } // adds an element at the end // of list add(element) { // creates a new node var node = new Node(element); // to store current node var current; // if list is Empty add the // element and make it head if (this.head == null) this.head = node; else { current = this.head; // iterate to the end of the // list while (current.next) { current = current.next; } // add node current.next = node; } this.size++; } // insert element at the position index // of the list insertAt(element, index) { if (index < 0 || index > this.size) return console.log("Please enter a valid index."); else { // creates a new node var node = new Node(element); var curr, prev; curr = this.head; // add the element to the // first index if (index == 0) { node.next = this.head; this.head = node; } else { curr = this.head; var it = 0; // iterate over the list to find // the position to insert while (it < index) { it++; prev = curr; curr = curr.next; } // adding an element node.next = curr; prev.next = node; } this.size++; } } // removes an element from the // specified location removeFrom(index) { if (index < 0 || index >= this.size) return console.log("Please Enter a valid index"); else { var curr, prev, it = 0; curr = this.head; prev = curr; // deleting first element if (index === 0) { this.head = curr.next; } else { // iterate over the list to the // position to removce an element while (it < index) { it++; prev = curr; curr = curr.next; } // remove the element prev.next = curr.next; } this.size--; // return the remove element return curr.element; } } // removes a given element from the // list removeElement(element) { var current = this.head; var prev = null; // iterate over the list while (current != null) { // comparing element with current // element if found then remove the // and return true if (current.element === element) { if (prev == null) { this.head = current.next; } else { prev.next = current.next; } this.size--; return current.element; } prev = current; current = current.next; } return -1; } // finds the index of element indexOf(element) { var count = 0; var current = this.head; // iterate over the list while (current != null) { // compare each element of the list // with given element if (current.element === element) return count; count++; current = current.next; } // not found return -1; } // checks the list for empty isEmpty() { return this.size == 0; } // gives the size of the list size_of_list() { console.log(this.size); } // prints the list items printList() { var curr = this.head; var str = ""; while (curr) { str += curr.element + " "; curr = curr.next; } console.log(str); } } // creating an object for the// Linkedlist classvar ll = new LinkedList(); // testing isEmpty on an empty list// returns trueconsole.log(ll.isEmpty()); // adding element to the listll.add(10); // prints 10ll.printList(); // returns 1console.log(ll.size_of_list()); // adding more elements to the listll.add(20);ll.add(30);ll.add(40);ll.add(50); // returns 10 20 30 40 50ll.printList(); // prints 50 from the listconsole.log("is element removed ?" + ll.removeElement(50)); // prints 10 20 30 40ll.printList(); // returns 3console.log("Index of 40 " + ll.indexOf(40)); // insert 60 at second position// ll contains 10 20 60 30 40ll.insertAt(60, 2); ll.printList(); // returns falseconsole.log("is List Empty ? " + ll.isEmpty()); // remove 3rd element from the listconsole.log(ll.removeFrom(3)); // prints 10 20 60 40ll.printList(); Output: true 10 1 undefined 10 20 30 40 50 is element removed ?50 10 20 30 40 Index of 40 3 10 20 60 30 40 is List Empty ? false 30 10 20 60 40 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. 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. ajf412 Vijay Sirra AjayArjunBaalakrishnanKalaivani sahilgupta312000 aashishgajadhane singghakshay JavaScript-DS Articles JavaScript Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Time Complexity and Space Complexity SQL Interview Questions Understanding "extern" keyword in C SQL | Views Java Tutorial 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 Difference Between PUT and PATCH Request
[ { "code": null, "e": 53, "s": 25, "text": "\n02 Dec, 2021" }, { "code": null, "e": 423, "s": 53, "text": "In this article, we will be implementing the LinkedList data structure in Javascript. LinkedList is the dynamic data structure, as we can add or remove elements at ease, and it can even grow as needed. Just like arrays, linked lists store elements sequentially, but don’t store the elements contiguously like an array. Now, Let’s see an example of a Linked List Node: " }, { "code": null, "e": 434, "s": 423, "text": "Javascript" }, { "code": "// User defined class nodeclass Node { // constructor constructor(element) { this.element = element; this.next = null }}", "e": 581, "s": 434, "text": null }, { "code": null, "e": 848, "s": 581, "text": "As in the above code, we define a class Node having two properties: element and next. Element holds the data of a node while next holds the pointer to the next node, which is initialized to the null value. Now, let’s see an implementation of the Linked List class: " }, { "code": null, "e": 859, "s": 848, "text": "Javascript" }, { "code": "// linkedlist classclass LinkedList { constructor() { this.head = null; this.size = 0; } // functions to be implemented // add(element) // insertAt(element, location) // removeFrom(location) // removeElement(element) // Helper Methods // isEmpty // size_Of_List // PrintList}", "e": 1187, "s": 859, "text": null }, { "code": null, "e": 1490, "s": 1187, "text": "The above example shows a Linked List class with a constructor and a list of methods to be implemented. Linked List class has two properties: i.e. head and size, where the head stores the first node of a List, and size indicates the number of nodes in a list. Let’s implement each of these functions: " }, { "code": null, "e": 1553, "s": 1490, "text": "1. add(element) – It adds an element at the end of the list. " }, { "code": null, "e": 1564, "s": 1553, "text": "Javascript" }, { "code": "// adds an element at the end// of listadd(element){ // creates a new node var node = new Node(element); // to store current node var current; // if list is Empty add the // element and make it head if (this.head == null) this.head = node; else { current = this.head; // iterate to the end of the // list while (current.next) { current = current.next; } // add node current.next = node; } this.size++;}", "e": 2068, "s": 1564, "text": null }, { "code": null, "e": 2151, "s": 2068, "text": "In the order to add an element at the end of the list we consider the following : " }, { "code": null, "e": 2212, "s": 2151, "text": "If the list is empty then add an element and it will be head" }, { "code": null, "e": 2315, "s": 2212, "text": "If the list is not empty then iterate to the end of the list and add an element at the end of the list" }, { "code": null, "e": 2398, "s": 2315, "text": "2. insertAt(element, index) – It inserts an element at the given index in a list. " }, { "code": null, "e": 2409, "s": 2398, "text": "Javascript" }, { "code": "// insert element at the position index// of the listinsertAt(element, index){ if (index < 0 || index > this.size) return console.log(\"Please enter a valid index.\"); else { // creates a new node var node = new Node(element); var curr, prev; curr = this.head; // add the element to the // first index if (index == 0) { node.next = this.head; this.head = node; } else { curr = this.head; var it = 0; // iterate over the list to find // the position to insert while (it < index) { it++; prev = curr; curr = curr.next; } // adding an element node.next = curr; prev.next = node; } this.size++; }}", "e": 3257, "s": 2409, "text": null }, { "code": null, "e": 3357, "s": 3257, "text": "In order to add an element at the given index of the list we consider three conditions as follows: " }, { "code": null, "e": 3438, "s": 3357, "text": "if the index is zero we add an element at the front of the list and make it head" }, { "code": null, "e": 3529, "s": 3438, "text": "If the index is the last position of the list we append the element at the end of the list" }, { "code": null, "e": 3629, "s": 3529, "text": "if the index is between 0 or size – 1 we iterate over to the index and add an element at that index" }, { "code": null, "e": 3726, "s": 3629, "text": "3. removeFrom(index) – It removes and returns an element from the list from the specified index " }, { "code": null, "e": 3737, "s": 3726, "text": "Javascript" }, { "code": "// removes an element from the// specified locationremoveFrom(index){ if (index < 0 || index >= this.size) return console.log(\"Please Enter a valid index\"); else { var curr, prev, it = 0; curr = this.head; prev = curr; // deleting first element if (index === 0) { this.head = curr.next; } else { // iterate over the list to the // position to removce an element while (it < index) { it++; prev = curr; curr = curr.next; } // remove the element prev.next = curr.next; } this.size--; // return the remove element return curr.element; }}", "e": 4483, "s": 3737, "text": null }, { "code": null, "e": 4558, "s": 4483, "text": "In order to remove an element from the list we consider three conditions: " }, { "code": null, "e": 4640, "s": 4558, "text": "If the index is 0 then we remove the head and make the next node head of the list" }, { "code": null, "e": 4742, "s": 4640, "text": "if the index is size – 1 then we remove the last element from the list and make prev the last element" }, { "code": null, "e": 4832, "s": 4742, "text": "if it’s in between 0 to size – 1 we remove the element by using prev and the current node" }, { "code": null, "e": 4973, "s": 4832, "text": "4. removeElement(element) – This method removes element from the list. It returns the removed element, or if it’s not found it returns -1. " }, { "code": null, "e": 4984, "s": 4973, "text": "Javascript" }, { "code": "// removes a given element from the// listremoveElement(element){ var current = this.head; var prev = null; // iterate over the list while (current != null) { // comparing element with current // element if found then remove the // and return true if (current.element === element) { if (prev == null) { this.head = current.next; } else { prev.next = current.next; } this.size--; return current.element; } prev = current; current = current.next; } return -1;}", "e": 5596, "s": 4984, "text": null }, { "code": null, "e": 5754, "s": 5596, "text": "The above method is just a modification of removeFrom(index), as it searches for an element and removes it, rather than removing it from a specified location" }, { "code": null, "e": 5770, "s": 5754, "text": " Helper Methods" }, { "code": null, "e": 5854, "s": 5770, "text": "Let’s declare some helper methods which are useful while working with LinkedList. " }, { "code": null, "e": 5949, "s": 5854, "text": "1. indexOf(element) – it returns the index of a given element if the element is in the list. " }, { "code": null, "e": 5960, "s": 5949, "text": "Javascript" }, { "code": "// finds the index of elementindexOf(element){ var count = 0; var current = this.head; // iterate over the list while (current != null) { // compare each element of the list // with given element if (current.element === element) return count; count++; current = current.next; } // not found return -1;}", "e": 6332, "s": 5960, "text": null }, { "code": null, "e": 6462, "s": 6332, "text": "In this method, we iterate over the list to find the index of an element. If it is not present in the list it returns -1 instead." }, { "code": null, "e": 6516, "s": 6462, "text": "2. isEmpty() – it returns true if the list is empty. " }, { "code": null, "e": 6527, "s": 6516, "text": "Javascript" }, { "code": "// checks the list for emptyisEmpty(){ return this.size == 0;}", "e": 6593, "s": 6527, "text": null }, { "code": null, "e": 6705, "s": 6593, "text": "In this method we check for the size property of the LinkedList class, and if it’s zero then the list is empty." }, { "code": null, "e": 6754, "s": 6705, "text": "3. size_of_list() – It returns the size of list " }, { "code": null, "e": 6765, "s": 6754, "text": "Javascript" }, { "code": "// gives the size of the listsize_of_list(){ console.log(this.size);}", "e": 6838, "s": 6765, "text": null }, { "code": null, "e": 6892, "s": 6838, "text": "3. printList() – It prints the contents of the list. " }, { "code": null, "e": 6903, "s": 6892, "text": "Javascript" }, { "code": "// prints the list itemsprintList(){ var curr = this.head; var str = \"\"; while (curr) { str += curr.element + \" \"; curr = curr.next; } console.log(str);}", "e": 7086, "s": 6903, "text": null }, { "code": null, "e": 7190, "s": 7086, "text": "In this method, we iterate over the entire list and concatenate the elements of each node and print it." }, { "code": null, "e": 7276, "s": 7190, "text": "Note: Different helper methods can be declared in the LinkedList class as required. " }, { "code": null, "e": 7291, "s": 7276, "text": "Implementation" }, { "code": null, "e": 7371, "s": 7291, "text": "Now, let’s use the LinkedList class and its different methods described above. " }, { "code": null, "e": 7382, "s": 7371, "text": "Javascript" }, { "code": "// creating an object for the// Linkedlist classvar ll = new LinkedList(); // testing isEmpty on an empty list// returns trueconsole.log(ll.isEmpty()); // adding element to the listll.add(10); // prints 10ll.printList(); // returns 1console.log(ll.size_of_list()); // adding more elements to the listll.add(20);ll.add(30);ll.add(40);ll.add(50); // returns 10 20 30 40 50ll.printList(); // prints 50 from the listconsole.log(\"is element removed ?\" + ll.removeElement(50)); // prints 10 20 30 40ll.printList(); // returns 3console.log(\"Index of 40 \" + ll.indexOf(40)); // insert 60 at second position// ll contains 10 20 60 30 40ll.insertAt(60, 2); ll.printList(); // returns falseconsole.log(\"is List Empty ? \" + ll.isEmpty()); // remove 3rd element from the listconsole.log(ll.removeFrom(3)); // prints 10 20 60 40ll.printList();", "e": 8212, "s": 7382, "text": null }, { "code": null, "e": 8227, "s": 8212, "text": "Complete Code:" }, { "code": null, "e": 8238, "s": 8227, "text": "Javascript" }, { "code": "class Node { // constructor constructor(element) { this.element = element; this.next = null }}// linkedlist classclass LinkedList { constructor() { this.head = null; this.size = 0; } // adds an element at the end // of list add(element) { // creates a new node var node = new Node(element); // to store current node var current; // if list is Empty add the // element and make it head if (this.head == null) this.head = node; else { current = this.head; // iterate to the end of the // list while (current.next) { current = current.next; } // add node current.next = node; } this.size++; } // insert element at the position index // of the list insertAt(element, index) { if (index < 0 || index > this.size) return console.log(\"Please enter a valid index.\"); else { // creates a new node var node = new Node(element); var curr, prev; curr = this.head; // add the element to the // first index if (index == 0) { node.next = this.head; this.head = node; } else { curr = this.head; var it = 0; // iterate over the list to find // the position to insert while (it < index) { it++; prev = curr; curr = curr.next; } // adding an element node.next = curr; prev.next = node; } this.size++; } } // removes an element from the // specified location removeFrom(index) { if (index < 0 || index >= this.size) return console.log(\"Please Enter a valid index\"); else { var curr, prev, it = 0; curr = this.head; prev = curr; // deleting first element if (index === 0) { this.head = curr.next; } else { // iterate over the list to the // position to removce an element while (it < index) { it++; prev = curr; curr = curr.next; } // remove the element prev.next = curr.next; } this.size--; // return the remove element return curr.element; } } // removes a given element from the // list removeElement(element) { var current = this.head; var prev = null; // iterate over the list while (current != null) { // comparing element with current // element if found then remove the // and return true if (current.element === element) { if (prev == null) { this.head = current.next; } else { prev.next = current.next; } this.size--; return current.element; } prev = current; current = current.next; } return -1; } // finds the index of element indexOf(element) { var count = 0; var current = this.head; // iterate over the list while (current != null) { // compare each element of the list // with given element if (current.element === element) return count; count++; current = current.next; } // not found return -1; } // checks the list for empty isEmpty() { return this.size == 0; } // gives the size of the list size_of_list() { console.log(this.size); } // prints the list items printList() { var curr = this.head; var str = \"\"; while (curr) { str += curr.element + \" \"; curr = curr.next; } console.log(str); } } // creating an object for the// Linkedlist classvar ll = new LinkedList(); // testing isEmpty on an empty list// returns trueconsole.log(ll.isEmpty()); // adding element to the listll.add(10); // prints 10ll.printList(); // returns 1console.log(ll.size_of_list()); // adding more elements to the listll.add(20);ll.add(30);ll.add(40);ll.add(50); // returns 10 20 30 40 50ll.printList(); // prints 50 from the listconsole.log(\"is element removed ?\" + ll.removeElement(50)); // prints 10 20 30 40ll.printList(); // returns 3console.log(\"Index of 40 \" + ll.indexOf(40)); // insert 60 at second position// ll contains 10 20 60 30 40ll.insertAt(60, 2); ll.printList(); // returns falseconsole.log(\"is List Empty ? \" + ll.isEmpty()); // remove 3rd element from the listconsole.log(ll.removeFrom(3)); // prints 10 20 60 40ll.printList();", "e": 13274, "s": 8238, "text": null }, { "code": null, "e": 13282, "s": 13274, "text": "Output:" }, { "code": null, "e": 13430, "s": 13282, "text": " true\n 10\n 1\n undefined\n 10 20 30 40 50\n is element removed ?50\n 10 20 30 40\n Index of 40 3\n 10 20 60 30 40\n is List Empty ? false\n 30\n 10 20 60 40" }, { "code": null, "e": 13649, "s": 13430, "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": 14069, "s": 13649, "text": "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": 14076, "s": 14069, "text": "ajf412" }, { "code": null, "e": 14088, "s": 14076, "text": "Vijay Sirra" }, { "code": null, "e": 14120, "s": 14088, "text": "AjayArjunBaalakrishnanKalaivani" }, { "code": null, "e": 14137, "s": 14120, "text": "sahilgupta312000" }, { "code": null, "e": 14154, "s": 14137, "text": "aashishgajadhane" }, { "code": null, "e": 14167, "s": 14154, "text": "singghakshay" }, { "code": null, "e": 14181, "s": 14167, "text": "JavaScript-DS" }, { "code": null, "e": 14190, "s": 14181, "text": "Articles" }, { "code": null, "e": 14201, "s": 14190, "text": "JavaScript" }, { "code": null, "e": 14299, "s": 14201, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 14336, "s": 14299, "text": "Time Complexity and Space Complexity" }, { "code": null, "e": 14360, "s": 14336, "text": "SQL Interview Questions" }, { "code": null, "e": 14396, "s": 14360, "text": "Understanding \"extern\" keyword in C" }, { "code": null, "e": 14408, "s": 14396, "text": "SQL | Views" }, { "code": null, "e": 14422, "s": 14408, "text": "Java Tutorial" }, { "code": null, "e": 14483, "s": 14422, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 14555, "s": 14483, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 14595, "s": 14555, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 14648, "s": 14595, "text": "Hide or show elements in HTML using display property" } ]
PHP array_values() Function
30 Nov, 2021 In this article, we will see how to get an array value using the array_values() function in PHP, along with understanding their implementation through the example. The array_values() is an inbuilt PHP function is used to get an array of values from another array that may contain key-value pairs or just values. The function creates another array where it stores all the values and by default assigns numerical keys to the values. Syntax: array array_values($array) Parameters: This function takes only one parameter $array which is mandatory and refers to the original input array, from which values need to be fetched. Return Value: This function returns an array with the fetched values, indexed with the numerical keys. Consider the following examples. Here, we are using the concept of Associative arrays that are used to store key-value pairs. Input: $array = ("ram"=>25, "krishna"=>10, "aakash"=>20, "gaurav") Output: Array ( [0] => 25 [1] => 10 [2] => 20 [3] => gaurav ) Explanation: This array use named keys that we have assigned to them. For those array element that has not assigned any value, will display their index value. Input: $array = ("ram", "krishna", "aakash", "gaurav") Output: Array ( [0] => ram [1] => krishna [2] => aakash [3] => gaurav ) Explanation: This array displays the array item along with index value. Example: The below example illustrates the array_values() function in PHP. PHP <?php // PHP function to illustrate the use of array_values() function Return_Values($array) { return (array_values($array)); } $array = array("ram"=>25, "krishna"=>10, "aakash"=>20, "gaurav"); print_r(Return_Values($array));?> Output: Array ( [0] => 25 [1] => 10 [2] => 20 [3] => gaurav ) Reference: http://php.net/manual/en/function.array-values.php bhaskargeeksforgeeks PHP-array PHP-function PHP Web technologies Questions PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to fetch data from localserver database and display on HTML table using PHP ? Difference between HTTP GET and POST Methods Different ways for passing data to view in Laravel PHP | file_exists( ) Function PHP | Ternary Operator Installation of Node.js on Linux How to insert spaces/tabs in text using HTML/CSS? Remove elements from a JavaScript Array How to set the default value for an HTML <select> element ? How to set input type date in dd-mm-yyyy format using HTML ?
[ { "code": null, "e": 28, "s": 0, "text": "\n30 Nov, 2021" }, { "code": null, "e": 192, "s": 28, "text": "In this article, we will see how to get an array value using the array_values() function in PHP, along with understanding their implementation through the example." }, { "code": null, "e": 460, "s": 192, "text": "The array_values() is an inbuilt PHP function is used to get an array of values from another array that may contain key-value pairs or just values. The function creates another array where it stores all the values and by default assigns numerical keys to the values." }, { "code": null, "e": 468, "s": 460, "text": "Syntax:" }, { "code": null, "e": 495, "s": 468, "text": "array array_values($array)" }, { "code": null, "e": 650, "s": 495, "text": "Parameters: This function takes only one parameter $array which is mandatory and refers to the original input array, from which values need to be fetched." }, { "code": null, "e": 753, "s": 650, "text": "Return Value: This function returns an array with the fetched values, indexed with the numerical keys." }, { "code": null, "e": 879, "s": 753, "text": "Consider the following examples. Here, we are using the concept of Associative arrays that are used to store key-value pairs." }, { "code": null, "e": 1401, "s": 879, "text": "Input: $array = (\"ram\"=>25, \"krishna\"=>10, \"aakash\"=>20, \"gaurav\")\nOutput:\nArray\n(\n [0] => 25\n [1] => 10\n [2] => 20\n [3] => gaurav\n)\nExplanation: This array use named keys that we have assigned to them. \nFor those array element that has not assigned any value, will display \ntheir index value.\n\nInput: $array = (\"ram\", \"krishna\", \"aakash\", \"gaurav\")\nOutput:\nArray\n(\n [0] => ram\n [1] => krishna\n [2] => aakash\n [3] => gaurav\n)\nExplanation: This array displays the array item along with index value." }, { "code": null, "e": 1476, "s": 1401, "text": "Example: The below example illustrates the array_values() function in PHP." }, { "code": null, "e": 1480, "s": 1476, "text": "PHP" }, { "code": "<?php // PHP function to illustrate the use of array_values() function Return_Values($array) { return (array_values($array)); } $array = array(\"ram\"=>25, \"krishna\"=>10, \"aakash\"=>20, \"gaurav\"); print_r(Return_Values($array));?>", "e": 1721, "s": 1480, "text": null }, { "code": null, "e": 1729, "s": 1721, "text": "Output:" }, { "code": null, "e": 1799, "s": 1729, "text": "Array\n(\n [0] => 25\n [1] => 10\n [2] => 20\n [3] => gaurav\n)" }, { "code": null, "e": 1861, "s": 1799, "text": "Reference: http://php.net/manual/en/function.array-values.php" }, { "code": null, "e": 1882, "s": 1861, "text": "bhaskargeeksforgeeks" }, { "code": null, "e": 1892, "s": 1882, "text": "PHP-array" }, { "code": null, "e": 1905, "s": 1892, "text": "PHP-function" }, { "code": null, "e": 1909, "s": 1905, "text": "PHP" }, { "code": null, "e": 1936, "s": 1909, "text": "Web technologies Questions" }, { "code": null, "e": 1940, "s": 1936, "text": "PHP" }, { "code": null, "e": 2038, "s": 1940, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2120, "s": 2038, "text": "How to fetch data from localserver database and display on HTML table using PHP ?" }, { "code": null, "e": 2165, "s": 2120, "text": "Difference between HTTP GET and POST Methods" }, { "code": null, "e": 2216, "s": 2165, "text": "Different ways for passing data to view in Laravel" }, { "code": null, "e": 2246, "s": 2216, "text": "PHP | file_exists( ) Function" }, { "code": null, "e": 2269, "s": 2246, "text": "PHP | Ternary Operator" }, { "code": null, "e": 2302, "s": 2269, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 2352, "s": 2302, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 2392, "s": 2352, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 2452, "s": 2392, "text": "How to set the default value for an HTML <select> element ?" } ]
Smallest K digit number divisible by X
22 Jun, 2022 Integers X and K are given. The task is to find the smallest K-digit number divisible by X. Examples : Input : X = 83, K = 5 Output : 10043 10040 is the smallest 5 digit number that is multiple of 83. Input : X = 5, K = 2 Output : 10 A simple solution is to try all numbers starting from the smallest K digit number (which is 100...(K-1)times) and return the first number divisible by X. An efficient solution would be : Compute MIN : smallest K-digit number (1000...(K-1)times) If, MIN % X is 0, ans = MIN else, ans = (MIN + X) - ((MIN + X) % X)) This is because there will be a number in range [MIN...MIN+X] divisible by X. C++ Java Python3 C# PHP Javascript // C++ code to find smallest K-digit number// divisible by X#include <bits/stdc++.h>using namespace std; // Function to compute the resultint answer(int X, int K){ // Computing MIN int MIN = pow(10, K - 1); // MIN is the result if (MIN % X == 0) return MIN; // returning ans return ((MIN + X) - ((MIN + X) % X));} // Driver Codeint main(){ // Number whose divisible is to be found int X = 83; // Max K-digit divisible is to be found int K = 5; cout << answer(X, K);} // Java code to find smallest K-digit// number divisible by X import java.io.*;import java.lang.*; class GFG { public static double answer(double X, double K) { double i = 10; // Computing MIN double MIN = Math.pow(i, K - 1); // returning ans if (MIN % X == 0) return (MIN); else return ((MIN + X) - ((MIN + X) % X)); } public static void main(String[] args) { // Number whose divisible is to be found double X = 83; double K = 5; System.out.println((int)answer(X, K)); }} // Code contributed by Mohit Gupta_OMG <(0_o)> # Python code to find smallest K-digit # number divisible by X def answer(X, K): # Computing MAX MIN = pow(10, K-1) if(MIN % X == 0): return (MIN) else: return ((MIN + X) - ((MIN + X) % X)) X = 83;K = 5; print(answer(X, K)); # Code contributed by Mohit Gupta_OMG <(0_o)> // C# code to find smallest K-digit// number divisible by Xusing System; class GFG { // Function to compute the result public static double answer(double X, double K) { double i = 10; // Computing MIN double MIN = Math.Pow(i, K - 1); // returning ans if (MIN % X == 0) return MIN; else return ((MIN + X) - ((MIN + X) % X)); } // Driver code public static void Main() { // Number whose divisible is to be found double X = 83; double K = 5; Console.WriteLine((int)answer(X, K)); }} // This code is contributed by vt_m. <?php// PHP code to find smallest// K-digit number divisible by X // Function to compute// the resultfunction answer($X, $K){ // Computing MIN $MIN = pow(10, $K - 1); // MIN is the result if ($MIN % $X == 0) return $MIN; // returning ans return (($MIN + $X) - (($MIN + $X) % $X));} // Driver Code // Number whose divisible// is to be found$X = 83; // Max K-digit divisible// is to be found$K = 5; echo answer($X, $K); // This code is contributed by ajit?> <script> // Javascript code to find smallest// K-digit number divisible by X // Function to compute// the resultfunction answer(X, K){ // Computing MIN let MIN = Math.pow(10, K - 1); // MIN is the result if (MIN % X == 0) return MIN; // returning ans return ((MIN + X) - ((MIN + X) % X));} // Driver Code // Number whose divisible// is to be foundlet X = 83; // Max K-digit divisible// is to be foundlet K = 5; document.write(answer(X, K)); // This code is contributed by sravan kumar </script> Output : 10043 Time Complexity: O(logk) Auxiliary Space: O(1)This article is contributed by Rohit Thapliyal. 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 Akanksha_Rai Jaspreet Singh spp____ sravankumar8128 chandramauliguptach divisibility Numbers Mathematical Mathematical Numbers Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Algorithm to solve Rubik's Cube Merge two sorted arrays with O(1) extra space Program to print prime numbers from 1 to N. Find next greater number with same set of digits Segment Tree | Set 1 (Sum of given range) Count ways to reach the n'th stair Check if a number is Palindrome Count all possible paths from top left to bottom right of a mXn matrix Fizz Buzz Implementation Product of Array except itself
[ { "code": null, "e": 52, "s": 24, "text": "\n22 Jun, 2022" }, { "code": null, "e": 145, "s": 52, "text": "Integers X and K are given. The task is to find the smallest K-digit number divisible by X. " }, { "code": null, "e": 157, "s": 145, "text": "Examples : " }, { "code": null, "e": 289, "s": 157, "text": "Input : X = 83, K = 5\nOutput : 10043\n10040 is the smallest 5 digit\nnumber that is multiple of 83.\n\nInput : X = 5, K = 2\nOutput : 10" }, { "code": null, "e": 443, "s": 289, "text": "A simple solution is to try all numbers starting from the smallest K digit number (which is 100...(K-1)times) and return the first number divisible by X." }, { "code": null, "e": 478, "s": 443, "text": "An efficient solution would be : " }, { "code": null, "e": 684, "s": 478, "text": "Compute MIN : smallest K-digit number (1000...(K-1)times)\nIf, MIN % X is 0, ans = MIN\nelse, ans = (MIN + X) - ((MIN + X) % X))\nThis is because there will be a number in \nrange [MIN...MIN+X] divisible by X." }, { "code": null, "e": 688, "s": 684, "text": "C++" }, { "code": null, "e": 693, "s": 688, "text": "Java" }, { "code": null, "e": 701, "s": 693, "text": "Python3" }, { "code": null, "e": 704, "s": 701, "text": "C#" }, { "code": null, "e": 708, "s": 704, "text": "PHP" }, { "code": null, "e": 719, "s": 708, "text": "Javascript" }, { "code": "// C++ code to find smallest K-digit number// divisible by X#include <bits/stdc++.h>using namespace std; // Function to compute the resultint answer(int X, int K){ // Computing MIN int MIN = pow(10, K - 1); // MIN is the result if (MIN % X == 0) return MIN; // returning ans return ((MIN + X) - ((MIN + X) % X));} // Driver Codeint main(){ // Number whose divisible is to be found int X = 83; // Max K-digit divisible is to be found int K = 5; cout << answer(X, K);}", "e": 1230, "s": 719, "text": null }, { "code": "// Java code to find smallest K-digit// number divisible by X import java.io.*;import java.lang.*; class GFG { public static double answer(double X, double K) { double i = 10; // Computing MIN double MIN = Math.pow(i, K - 1); // returning ans if (MIN % X == 0) return (MIN); else return ((MIN + X) - ((MIN + X) % X)); } public static void main(String[] args) { // Number whose divisible is to be found double X = 83; double K = 5; System.out.println((int)answer(X, K)); }} // Code contributed by Mohit Gupta_OMG <(0_o)>", "e": 1864, "s": 1230, "text": null }, { "code": "# Python code to find smallest K-digit # number divisible by X def answer(X, K): # Computing MAX MIN = pow(10, K-1) if(MIN % X == 0): return (MIN) else: return ((MIN + X) - ((MIN + X) % X)) X = 83;K = 5; print(answer(X, K)); # Code contributed by Mohit Gupta_OMG <(0_o)>", "e": 2181, "s": 1864, "text": null }, { "code": "// C# code to find smallest K-digit// number divisible by Xusing System; class GFG { // Function to compute the result public static double answer(double X, double K) { double i = 10; // Computing MIN double MIN = Math.Pow(i, K - 1); // returning ans if (MIN % X == 0) return MIN; else return ((MIN + X) - ((MIN + X) % X)); } // Driver code public static void Main() { // Number whose divisible is to be found double X = 83; double K = 5; Console.WriteLine((int)answer(X, K)); }} // This code is contributed by vt_m.", "e": 2821, "s": 2181, "text": null }, { "code": "<?php// PHP code to find smallest// K-digit number divisible by X // Function to compute// the resultfunction answer($X, $K){ // Computing MIN $MIN = pow(10, $K - 1); // MIN is the result if ($MIN % $X == 0) return $MIN; // returning ans return (($MIN + $X) - (($MIN + $X) % $X));} // Driver Code // Number whose divisible// is to be found$X = 83; // Max K-digit divisible// is to be found$K = 5; echo answer($X, $K); // This code is contributed by ajit?>", "e": 3314, "s": 2821, "text": null }, { "code": "<script> // Javascript code to find smallest// K-digit number divisible by X // Function to compute// the resultfunction answer(X, K){ // Computing MIN let MIN = Math.pow(10, K - 1); // MIN is the result if (MIN % X == 0) return MIN; // returning ans return ((MIN + X) - ((MIN + X) % X));} // Driver Code // Number whose divisible// is to be foundlet X = 83; // Max K-digit divisible// is to be foundlet K = 5; document.write(answer(X, K)); // This code is contributed by sravan kumar </script>", "e": 3852, "s": 3314, "text": null }, { "code": null, "e": 3862, "s": 3852, "text": "Output : " }, { "code": null, "e": 3868, "s": 3862, "text": "10043" }, { "code": null, "e": 3893, "s": 3868, "text": "Time Complexity: O(logk)" }, { "code": null, "e": 4338, "s": 3893, "text": "Auxiliary Space: O(1)This article is contributed by Rohit Thapliyal. 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": 4343, "s": 4338, "text": "vt_m" }, { "code": null, "e": 4349, "s": 4343, "text": "jit_t" }, { "code": null, "e": 4362, "s": 4349, "text": "Akanksha_Rai" }, { "code": null, "e": 4377, "s": 4362, "text": "Jaspreet Singh" }, { "code": null, "e": 4385, "s": 4377, "text": "spp____" }, { "code": null, "e": 4401, "s": 4385, "text": "sravankumar8128" }, { "code": null, "e": 4421, "s": 4401, "text": "chandramauliguptach" }, { "code": null, "e": 4434, "s": 4421, "text": "divisibility" }, { "code": null, "e": 4442, "s": 4434, "text": "Numbers" }, { "code": null, "e": 4455, "s": 4442, "text": "Mathematical" }, { "code": null, "e": 4468, "s": 4455, "text": "Mathematical" }, { "code": null, "e": 4476, "s": 4468, "text": "Numbers" }, { "code": null, "e": 4574, "s": 4476, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4606, "s": 4574, "text": "Algorithm to solve Rubik's Cube" }, { "code": null, "e": 4652, "s": 4606, "text": "Merge two sorted arrays with O(1) extra space" }, { "code": null, "e": 4696, "s": 4652, "text": "Program to print prime numbers from 1 to N." }, { "code": null, "e": 4745, "s": 4696, "text": "Find next greater number with same set of digits" }, { "code": null, "e": 4787, "s": 4745, "text": "Segment Tree | Set 1 (Sum of given range)" }, { "code": null, "e": 4822, "s": 4787, "text": "Count ways to reach the n'th stair" }, { "code": null, "e": 4854, "s": 4822, "text": "Check if a number is Palindrome" }, { "code": null, "e": 4925, "s": 4854, "text": "Count all possible paths from top left to bottom right of a mXn matrix" }, { "code": null, "e": 4950, "s": 4925, "text": "Fizz Buzz Implementation" } ]
How to pass integer by reference in Java
09 May, 2019 Java is pass by value and it is not possible to pass integer by reference in Java directly. Objects created in Java are references which are passed by value. Thus it can be achieved by some methods which are as follows: By creating Wrapper Class: As we know that Integer is an immutable class, so we wrap an integer value in a mutable object through this method.Approach:Get the integer to be passedCreate an object of another class with this integerUsing wrapper class so as to wrap integer value in mutable object which can be changed or modifiedNow whenever you need the integer, you have to get it through the object of the classHence the Integer has been passed by referenceBelow is the implementation of the above approach:Example:// Java program to pass the integer by reference class Test { public Integer value; Test(Integer value) { // Using wrapper class // so as to wrap integer value // in mutable object // which can be changed or modified this.value = value; } @Override public String toString() { return String.valueOf(value); }} class Main { public static void modification(Test x) { x.value = 1000; } public static void main(String[] args) { Test k = new Test(50); modification(k); // Modified value gets printed System.out.println(k); }}Output:1000Wrapping primitive value using an array: This process of wrapping is done by using an array of length one.Approach:Get the integer to be passedThis process of wrapping is done by using an array of length one.Now whenever you need the integer, you have to get it through the object of the arrayHence the Integer has been passed by referenceBelow is the implementation of the above approach:Example:// Java program to pass the integer by reference class PassByReference { public static void increment(int[] array) { // increment in the actual value array[0]++; } public static void main(String[] args) { int k = 100; // wrapping is done // by using array of length one int[] array = { k }; // Reference is passed increment(array); // incremented value printed System.out.println(array[0]); }}Output:101Using AtomicInteger: This is a built in Java class which provides a single threaded environment.Approach:Get the integer to be passedCreate an AtomicInteger object by passing this integer as parameter to its constructorNow whenever you need the integer, you have to get it through the object of the AtomicIntegerHence the Integer has been passed by referenceBelow is the implementation of the above approach:Example:// Java program to pass the integer by reference import java.util.concurrent.atomic.AtomicInteger; class PassByReference { public static void setvalue(AtomicInteger x) { // setting new value // thus changing the actual value x.set(1000); } public static void main(String[] args) { // provides single threaded environment AtomicInteger k = new AtomicInteger(50); // passed by reference setvalue(k); System.out.println(k); }}Output:1000Using Apache MutableInt Class: We can use MutableInt class by importing the package from Commons Apache.Approach:Get the integer to be passedCreate an MutableInt object by passing this integer as parameter to its constructorNow whenever you need the integer, you have to get it through the object of the MutableIntHence the Integer has been passed by referenceBelow is the implementation of the above approach:Example:// Java program to pass the integer by reference import org.apache.commons.lang3.mutable.MutableInt; class Main { public static void increment(MutableInt k) { k.increment(); } public static void main(String[] args) { // Using Mutable Class whose object's fields // can be changed accordingly MutableInt k = new MutableInt(8); increment(k); System.out.println(k); }}Output:9 By creating Wrapper Class: As we know that Integer is an immutable class, so we wrap an integer value in a mutable object through this method.Approach:Get the integer to be passedCreate an object of another class with this integerUsing wrapper class so as to wrap integer value in mutable object which can be changed or modifiedNow whenever you need the integer, you have to get it through the object of the classHence the Integer has been passed by referenceBelow is the implementation of the above approach:Example:// Java program to pass the integer by reference class Test { public Integer value; Test(Integer value) { // Using wrapper class // so as to wrap integer value // in mutable object // which can be changed or modified this.value = value; } @Override public String toString() { return String.valueOf(value); }} class Main { public static void modification(Test x) { x.value = 1000; } public static void main(String[] args) { Test k = new Test(50); modification(k); // Modified value gets printed System.out.println(k); }}Output:1000 Approach: Get the integer to be passedCreate an object of another class with this integerUsing wrapper class so as to wrap integer value in mutable object which can be changed or modifiedNow whenever you need the integer, you have to get it through the object of the classHence the Integer has been passed by reference Get the integer to be passed Create an object of another class with this integer Using wrapper class so as to wrap integer value in mutable object which can be changed or modified Now whenever you need the integer, you have to get it through the object of the class Hence the Integer has been passed by reference Below is the implementation of the above approach: Example: // Java program to pass the integer by reference class Test { public Integer value; Test(Integer value) { // Using wrapper class // so as to wrap integer value // in mutable object // which can be changed or modified this.value = value; } @Override public String toString() { return String.valueOf(value); }} class Main { public static void modification(Test x) { x.value = 1000; } public static void main(String[] args) { Test k = new Test(50); modification(k); // Modified value gets printed System.out.println(k); }} Output: 1000 Wrapping primitive value using an array: This process of wrapping is done by using an array of length one.Approach:Get the integer to be passedThis process of wrapping is done by using an array of length one.Now whenever you need the integer, you have to get it through the object of the arrayHence the Integer has been passed by referenceBelow is the implementation of the above approach:Example:// Java program to pass the integer by reference class PassByReference { public static void increment(int[] array) { // increment in the actual value array[0]++; } public static void main(String[] args) { int k = 100; // wrapping is done // by using array of length one int[] array = { k }; // Reference is passed increment(array); // incremented value printed System.out.println(array[0]); }}Output:101 Approach: Get the integer to be passedThis process of wrapping is done by using an array of length one.Now whenever you need the integer, you have to get it through the object of the arrayHence the Integer has been passed by reference Get the integer to be passed This process of wrapping is done by using an array of length one. Now whenever you need the integer, you have to get it through the object of the array Hence the Integer has been passed by reference Below is the implementation of the above approach: Example: // Java program to pass the integer by reference class PassByReference { public static void increment(int[] array) { // increment in the actual value array[0]++; } public static void main(String[] args) { int k = 100; // wrapping is done // by using array of length one int[] array = { k }; // Reference is passed increment(array); // incremented value printed System.out.println(array[0]); }} Output: 101 Using AtomicInteger: This is a built in Java class which provides a single threaded environment.Approach:Get the integer to be passedCreate an AtomicInteger object by passing this integer as parameter to its constructorNow whenever you need the integer, you have to get it through the object of the AtomicIntegerHence the Integer has been passed by referenceBelow is the implementation of the above approach:Example:// Java program to pass the integer by reference import java.util.concurrent.atomic.AtomicInteger; class PassByReference { public static void setvalue(AtomicInteger x) { // setting new value // thus changing the actual value x.set(1000); } public static void main(String[] args) { // provides single threaded environment AtomicInteger k = new AtomicInteger(50); // passed by reference setvalue(k); System.out.println(k); }}Output:1000 Approach: Get the integer to be passedCreate an AtomicInteger object by passing this integer as parameter to its constructorNow whenever you need the integer, you have to get it through the object of the AtomicIntegerHence the Integer has been passed by reference Get the integer to be passed Create an AtomicInteger object by passing this integer as parameter to its constructor Now whenever you need the integer, you have to get it through the object of the AtomicInteger Hence the Integer has been passed by reference Below is the implementation of the above approach: Example: // Java program to pass the integer by reference import java.util.concurrent.atomic.AtomicInteger; class PassByReference { public static void setvalue(AtomicInteger x) { // setting new value // thus changing the actual value x.set(1000); } public static void main(String[] args) { // provides single threaded environment AtomicInteger k = new AtomicInteger(50); // passed by reference setvalue(k); System.out.println(k); }} Output: 1000 Using Apache MutableInt Class: We can use MutableInt class by importing the package from Commons Apache.Approach:Get the integer to be passedCreate an MutableInt object by passing this integer as parameter to its constructorNow whenever you need the integer, you have to get it through the object of the MutableIntHence the Integer has been passed by referenceBelow is the implementation of the above approach:Example:// Java program to pass the integer by reference import org.apache.commons.lang3.mutable.MutableInt; class Main { public static void increment(MutableInt k) { k.increment(); } public static void main(String[] args) { // Using Mutable Class whose object's fields // can be changed accordingly MutableInt k = new MutableInt(8); increment(k); System.out.println(k); }}Output:9 Approach: Get the integer to be passedCreate an MutableInt object by passing this integer as parameter to its constructorNow whenever you need the integer, you have to get it through the object of the MutableIntHence the Integer has been passed by reference Get the integer to be passed Create an MutableInt object by passing this integer as parameter to its constructor Now whenever you need the integer, you have to get it through the object of the MutableInt Hence the Integer has been passed by reference Below is the implementation of the above approach: Example: // Java program to pass the integer by reference import org.apache.commons.lang3.mutable.MutableInt; class Main { public static void increment(MutableInt k) { k.increment(); } public static void main(String[] args) { // Using Mutable Class whose object's fields // can be changed accordingly MutableInt k = new MutableInt(8); increment(k); System.out.println(k); }} Output: 9 Picked Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. 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 Stack Class in Java
[ { "code": null, "e": 52, "s": 24, "text": "\n09 May, 2019" }, { "code": null, "e": 272, "s": 52, "text": "Java is pass by value and it is not possible to pass integer by reference in Java directly. Objects created in Java are references which are passed by value. Thus it can be achieved by some methods which are as follows:" }, { "code": null, "e": 4145, "s": 272, "text": "By creating Wrapper Class: As we know that Integer is an immutable class, so we wrap an integer value in a mutable object through this method.Approach:Get the integer to be passedCreate an object of another class with this integerUsing wrapper class so as to wrap integer value in mutable object which can be changed or modifiedNow whenever you need the integer, you have to get it through the object of the classHence the Integer has been passed by referenceBelow is the implementation of the above approach:Example:// Java program to pass the integer by reference class Test { public Integer value; Test(Integer value) { // Using wrapper class // so as to wrap integer value // in mutable object // which can be changed or modified this.value = value; } @Override public String toString() { return String.valueOf(value); }} class Main { public static void modification(Test x) { x.value = 1000; } public static void main(String[] args) { Test k = new Test(50); modification(k); // Modified value gets printed System.out.println(k); }}Output:1000Wrapping primitive value using an array: This process of wrapping is done by using an array of length one.Approach:Get the integer to be passedThis process of wrapping is done by using an array of length one.Now whenever you need the integer, you have to get it through the object of the arrayHence the Integer has been passed by referenceBelow is the implementation of the above approach:Example:// Java program to pass the integer by reference class PassByReference { public static void increment(int[] array) { // increment in the actual value array[0]++; } public static void main(String[] args) { int k = 100; // wrapping is done // by using array of length one int[] array = { k }; // Reference is passed increment(array); // incremented value printed System.out.println(array[0]); }}Output:101Using AtomicInteger: This is a built in Java class which provides a single threaded environment.Approach:Get the integer to be passedCreate an AtomicInteger object by passing this integer as parameter to its constructorNow whenever you need the integer, you have to get it through the object of the AtomicIntegerHence the Integer has been passed by referenceBelow is the implementation of the above approach:Example:// Java program to pass the integer by reference import java.util.concurrent.atomic.AtomicInteger; class PassByReference { public static void setvalue(AtomicInteger x) { // setting new value // thus changing the actual value x.set(1000); } public static void main(String[] args) { // provides single threaded environment AtomicInteger k = new AtomicInteger(50); // passed by reference setvalue(k); System.out.println(k); }}Output:1000Using Apache MutableInt Class: We can use MutableInt class by importing the package from Commons Apache.Approach:Get the integer to be passedCreate an MutableInt object by passing this integer as parameter to its constructorNow whenever you need the integer, you have to get it through the object of the MutableIntHence the Integer has been passed by referenceBelow is the implementation of the above approach:Example:// Java program to pass the integer by reference import org.apache.commons.lang3.mutable.MutableInt; class Main { public static void increment(MutableInt k) { k.increment(); } public static void main(String[] args) { // Using Mutable Class whose object's fields // can be changed accordingly MutableInt k = new MutableInt(8); increment(k); System.out.println(k); }}Output:9" }, { "code": null, "e": 5324, "s": 4145, "text": "By creating Wrapper Class: As we know that Integer is an immutable class, so we wrap an integer value in a mutable object through this method.Approach:Get the integer to be passedCreate an object of another class with this integerUsing wrapper class so as to wrap integer value in mutable object which can be changed or modifiedNow whenever you need the integer, you have to get it through the object of the classHence the Integer has been passed by referenceBelow is the implementation of the above approach:Example:// Java program to pass the integer by reference class Test { public Integer value; Test(Integer value) { // Using wrapper class // so as to wrap integer value // in mutable object // which can be changed or modified this.value = value; } @Override public String toString() { return String.valueOf(value); }} class Main { public static void modification(Test x) { x.value = 1000; } public static void main(String[] args) { Test k = new Test(50); modification(k); // Modified value gets printed System.out.println(k); }}Output:1000" }, { "code": null, "e": 5334, "s": 5324, "text": "Approach:" }, { "code": null, "e": 5643, "s": 5334, "text": "Get the integer to be passedCreate an object of another class with this integerUsing wrapper class so as to wrap integer value in mutable object which can be changed or modifiedNow whenever you need the integer, you have to get it through the object of the classHence the Integer has been passed by reference" }, { "code": null, "e": 5672, "s": 5643, "text": "Get the integer to be passed" }, { "code": null, "e": 5724, "s": 5672, "text": "Create an object of another class with this integer" }, { "code": null, "e": 5823, "s": 5724, "text": "Using wrapper class so as to wrap integer value in mutable object which can be changed or modified" }, { "code": null, "e": 5909, "s": 5823, "text": "Now whenever you need the integer, you have to get it through the object of the class" }, { "code": null, "e": 5956, "s": 5909, "text": "Hence the Integer has been passed by reference" }, { "code": null, "e": 6007, "s": 5956, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 6016, "s": 6007, "text": "Example:" }, { "code": "// Java program to pass the integer by reference class Test { public Integer value; Test(Integer value) { // Using wrapper class // so as to wrap integer value // in mutable object // which can be changed or modified this.value = value; } @Override public String toString() { return String.valueOf(value); }} class Main { public static void modification(Test x) { x.value = 1000; } public static void main(String[] args) { Test k = new Test(50); modification(k); // Modified value gets printed System.out.println(k); }}", "e": 6667, "s": 6016, "text": null }, { "code": null, "e": 6675, "s": 6667, "text": "Output:" }, { "code": null, "e": 6680, "s": 6675, "text": "1000" }, { "code": null, "e": 7580, "s": 6680, "text": "Wrapping primitive value using an array: This process of wrapping is done by using an array of length one.Approach:Get the integer to be passedThis process of wrapping is done by using an array of length one.Now whenever you need the integer, you have to get it through the object of the arrayHence the Integer has been passed by referenceBelow is the implementation of the above approach:Example:// Java program to pass the integer by reference class PassByReference { public static void increment(int[] array) { // increment in the actual value array[0]++; } public static void main(String[] args) { int k = 100; // wrapping is done // by using array of length one int[] array = { k }; // Reference is passed increment(array); // incremented value printed System.out.println(array[0]); }}Output:101" }, { "code": null, "e": 7590, "s": 7580, "text": "Approach:" }, { "code": null, "e": 7815, "s": 7590, "text": "Get the integer to be passedThis process of wrapping is done by using an array of length one.Now whenever you need the integer, you have to get it through the object of the arrayHence the Integer has been passed by reference" }, { "code": null, "e": 7844, "s": 7815, "text": "Get the integer to be passed" }, { "code": null, "e": 7910, "s": 7844, "text": "This process of wrapping is done by using an array of length one." }, { "code": null, "e": 7996, "s": 7910, "text": "Now whenever you need the integer, you have to get it through the object of the array" }, { "code": null, "e": 8043, "s": 7996, "text": "Hence the Integer has been passed by reference" }, { "code": null, "e": 8094, "s": 8043, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 8103, "s": 8094, "text": "Example:" }, { "code": "// Java program to pass the integer by reference class PassByReference { public static void increment(int[] array) { // increment in the actual value array[0]++; } public static void main(String[] args) { int k = 100; // wrapping is done // by using array of length one int[] array = { k }; // Reference is passed increment(array); // incremented value printed System.out.println(array[0]); }}", "e": 8596, "s": 8103, "text": null }, { "code": null, "e": 8604, "s": 8596, "text": "Output:" }, { "code": null, "e": 8608, "s": 8604, "text": "101" }, { "code": null, "e": 9545, "s": 8608, "text": "Using AtomicInteger: This is a built in Java class which provides a single threaded environment.Approach:Get the integer to be passedCreate an AtomicInteger object by passing this integer as parameter to its constructorNow whenever you need the integer, you have to get it through the object of the AtomicIntegerHence the Integer has been passed by referenceBelow is the implementation of the above approach:Example:// Java program to pass the integer by reference import java.util.concurrent.atomic.AtomicInteger; class PassByReference { public static void setvalue(AtomicInteger x) { // setting new value // thus changing the actual value x.set(1000); } public static void main(String[] args) { // provides single threaded environment AtomicInteger k = new AtomicInteger(50); // passed by reference setvalue(k); System.out.println(k); }}Output:1000" }, { "code": null, "e": 9555, "s": 9545, "text": "Approach:" }, { "code": null, "e": 9809, "s": 9555, "text": "Get the integer to be passedCreate an AtomicInteger object by passing this integer as parameter to its constructorNow whenever you need the integer, you have to get it through the object of the AtomicIntegerHence the Integer has been passed by reference" }, { "code": null, "e": 9838, "s": 9809, "text": "Get the integer to be passed" }, { "code": null, "e": 9925, "s": 9838, "text": "Create an AtomicInteger object by passing this integer as parameter to its constructor" }, { "code": null, "e": 10019, "s": 9925, "text": "Now whenever you need the integer, you have to get it through the object of the AtomicInteger" }, { "code": null, "e": 10066, "s": 10019, "text": "Hence the Integer has been passed by reference" }, { "code": null, "e": 10117, "s": 10066, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 10126, "s": 10117, "text": "Example:" }, { "code": "// Java program to pass the integer by reference import java.util.concurrent.atomic.AtomicInteger; class PassByReference { public static void setvalue(AtomicInteger x) { // setting new value // thus changing the actual value x.set(1000); } public static void main(String[] args) { // provides single threaded environment AtomicInteger k = new AtomicInteger(50); // passed by reference setvalue(k); System.out.println(k); }}", "e": 10636, "s": 10126, "text": null }, { "code": null, "e": 10644, "s": 10636, "text": "Output:" }, { "code": null, "e": 10649, "s": 10644, "text": "1000" }, { "code": null, "e": 11509, "s": 10649, "text": "Using Apache MutableInt Class: We can use MutableInt class by importing the package from Commons Apache.Approach:Get the integer to be passedCreate an MutableInt object by passing this integer as parameter to its constructorNow whenever you need the integer, you have to get it through the object of the MutableIntHence the Integer has been passed by referenceBelow is the implementation of the above approach:Example:// Java program to pass the integer by reference import org.apache.commons.lang3.mutable.MutableInt; class Main { public static void increment(MutableInt k) { k.increment(); } public static void main(String[] args) { // Using Mutable Class whose object's fields // can be changed accordingly MutableInt k = new MutableInt(8); increment(k); System.out.println(k); }}Output:9" }, { "code": null, "e": 11519, "s": 11509, "text": "Approach:" }, { "code": null, "e": 11767, "s": 11519, "text": "Get the integer to be passedCreate an MutableInt object by passing this integer as parameter to its constructorNow whenever you need the integer, you have to get it through the object of the MutableIntHence the Integer has been passed by reference" }, { "code": null, "e": 11796, "s": 11767, "text": "Get the integer to be passed" }, { "code": null, "e": 11880, "s": 11796, "text": "Create an MutableInt object by passing this integer as parameter to its constructor" }, { "code": null, "e": 11971, "s": 11880, "text": "Now whenever you need the integer, you have to get it through the object of the MutableInt" }, { "code": null, "e": 12018, "s": 11971, "text": "Hence the Integer has been passed by reference" }, { "code": null, "e": 12069, "s": 12018, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 12078, "s": 12069, "text": "Example:" }, { "code": "// Java program to pass the integer by reference import org.apache.commons.lang3.mutable.MutableInt; class Main { public static void increment(MutableInt k) { k.increment(); } public static void main(String[] args) { // Using Mutable Class whose object's fields // can be changed accordingly MutableInt k = new MutableInt(8); increment(k); System.out.println(k); }}", "e": 12512, "s": 12078, "text": null }, { "code": null, "e": 12520, "s": 12512, "text": "Output:" }, { "code": null, "e": 12522, "s": 12520, "text": "9" }, { "code": null, "e": 12529, "s": 12522, "text": "Picked" }, { "code": null, "e": 12534, "s": 12529, "text": "Java" }, { "code": null, "e": 12539, "s": 12534, "text": "Java" }, { "code": null, "e": 12637, "s": 12539, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 12668, "s": 12637, "text": "How to iterate any Map in Java" }, { "code": null, "e": 12687, "s": 12668, "text": "Interfaces in Java" }, { "code": null, "e": 12717, "s": 12687, "text": "HashMap in Java with Examples" }, { "code": null, "e": 12732, "s": 12717, "text": "Stream In Java" }, { "code": null, "e": 12750, "s": 12732, "text": "ArrayList in Java" }, { "code": null, "e": 12770, "s": 12750, "text": "Collections in Java" }, { "code": null, "e": 12794, "s": 12770, "text": "Singleton Class in Java" }, { "code": null, "e": 12826, "s": 12794, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 12838, "s": 12826, "text": "Set in Java" } ]
Tensorflow.js tf.Tensor .toString() Method
17 May, 2021 Tensorflow.js is an open-source library developed by Google for running machine learning models and deep learning neural networks in the browser or node environment. The tf.tensor.toString() method is used to log the tensor in the human-readable form if you console.log() just tf.tensor then it will log the whole tensor object but after using the .toString() method it will log the tensor’s value. tf.tensor.toString(verbose?) Parameter: This function accepts single parameter which are illustrated below: verbose: A boolean value. If it is true then the details of the tensor (dtype, rank, shape, values) will be returned otherwise only the tensor value will be returned. Although this is an optional parameter and by default it is false. Return value: It returns the tensor value or tensor’s details (dtype, rank, shape, values) in string form. Example 1: In this example, we are logging the tensor value before and after applying the toString() method. Javascript // Importing the tensorflow.js libraryimport * as tf from "@tensorflow/tfjs" // Creating the tensorvar val1 = tf.tensor([1, 2]); // Applying the toString() methodvar val2 = val1.toString() // logging the tensorconsole.log(val1)console.log(val2) Output: Example 2: In this example, we apply the boolean parameters in the toString() method and see the results. Javascript // Importing the tensorflow.js libraryimport * as tf from "@tensorflow/tfjs" // Creating the tensorvar val = tf.tensor([1, 2]); // Applying the toString() methodvar val1 = val.toString(true)var val2 = val.toString(false)// logging the tensorconsole.log(val1)console.log(val2) Output: Tensor dtype: float32 rank: 1 shape: [2] values: [1, 2] Tensor [1, 2] bunnyram19 Picked Tensorflow.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 May, 2021" }, { "code": null, "e": 194, "s": 28, "text": "Tensorflow.js is an open-source library developed by Google for running machine learning models and deep learning neural networks in the browser or node environment." }, { "code": null, "e": 427, "s": 194, "text": "The tf.tensor.toString() method is used to log the tensor in the human-readable form if you console.log() just tf.tensor then it will log the whole tensor object but after using the .toString() method it will log the tensor’s value." }, { "code": null, "e": 456, "s": 427, "text": "tf.tensor.toString(verbose?)" }, { "code": null, "e": 535, "s": 456, "text": "Parameter: This function accepts single parameter which are illustrated below:" }, { "code": null, "e": 769, "s": 535, "text": "verbose: A boolean value. If it is true then the details of the tensor (dtype, rank, shape, values) will be returned otherwise only the tensor value will be returned. Although this is an optional parameter and by default it is false." }, { "code": null, "e": 876, "s": 769, "text": "Return value: It returns the tensor value or tensor’s details (dtype, rank, shape, values) in string form." }, { "code": null, "e": 985, "s": 876, "text": "Example 1: In this example, we are logging the tensor value before and after applying the toString() method." }, { "code": null, "e": 996, "s": 985, "text": "Javascript" }, { "code": "// Importing the tensorflow.js libraryimport * as tf from \"@tensorflow/tfjs\" // Creating the tensorvar val1 = tf.tensor([1, 2]); // Applying the toString() methodvar val2 = val1.toString() // logging the tensorconsole.log(val1)console.log(val2)", "e": 1243, "s": 996, "text": null }, { "code": null, "e": 1251, "s": 1243, "text": "Output:" }, { "code": null, "e": 1357, "s": 1251, "text": "Example 2: In this example, we apply the boolean parameters in the toString() method and see the results." }, { "code": null, "e": 1368, "s": 1357, "text": "Javascript" }, { "code": "// Importing the tensorflow.js libraryimport * as tf from \"@tensorflow/tfjs\" // Creating the tensorvar val = tf.tensor([1, 2]); // Applying the toString() methodvar val1 = val.toString(true)var val2 = val.toString(false)// logging the tensorconsole.log(val1)console.log(val2)", "e": 1646, "s": 1368, "text": null }, { "code": null, "e": 1654, "s": 1646, "text": "Output:" }, { "code": null, "e": 1742, "s": 1654, "text": "Tensor\n dtype: float32\n rank: 1\n shape: [2]\n values:\n [1, 2]\n Tensor\n [1, 2]" }, { "code": null, "e": 1753, "s": 1742, "text": "bunnyram19" }, { "code": null, "e": 1760, "s": 1753, "text": "Picked" }, { "code": null, "e": 1774, "s": 1760, "text": "Tensorflow.js" }, { "code": null, "e": 1785, "s": 1774, "text": "JavaScript" }, { "code": null, "e": 1802, "s": 1785, "text": "Web Technologies" } ]
Sum of minimum value of x and y satisfying the equation ax + by = c
10 Jun, 2022 Time ComGiven three integers a, b, and c representing a linear equation of the form ax + by = c, the task is to find the solution (x, y) of the given equation such that (x + y) is minimized. If no solution exists for the above equation then print “-1”. Note: x and y are non negative integers. Examples: Input: a = 2, b = 2, c = 0 Output: 0 Explanation: The given equation is 2x + 2y = 0. Therefore, x = 0 and y = 0 is the required solution with minimum value of (x + y). Input: a = 2, b = 2, c = 1 Output: -1 Explanation: The given equation is 2x + 2y = 1. No solution exists for the given equation for positive values of x and y. Approach: To solve the above problem, find any solution say (x, y) of the given Linear Diophantine Equation and then accordingly find value of x and to minimised the sum.Below is the solution (x’, y’) of the given equation: [Tex]y’ = y – k * \frac{a}{g} [/Tex] where g is gcd(a, b) and k is any integer. [Tex]x’ + y’ = x + y + k*\frac{b-a}{g} [/Tex] From the above equation we observe that: If a is less than b, we need to select the smallest possible value of K.Else, if a is greater than b, we need to select the largest possible value of K.If a = b, all solutions will have the same sum (x + y). If a is less than b, we need to select the smallest possible value of K. Else, if a is greater than b, we need to select the largest possible value of K. If a = b, all solutions will have the same sum (x + y). Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to find the gcd of a & b// by Euclid's method // x and y store solution of// equation ax + by = gint gcd(int a, int b, int* x, int* y){ if (b == 0) { *x = 1; *y = 0; return a; } int x1, y1; int store_gcd = gcd(b, a % b, &x1, &y1); // Euclidean Algorithm *x = y1; *y = x1 - y1 * (a / b); // store_gcd returns // the gcd of a and b return store_gcd;} // Function to find any// possible solutionint possible_solution(int a, int b, int c, int* x0, int* y0, int* g){ *g = gcd(fabs(a), fabs(b), x0, y0); // Condition if solution // does not exists if (c % *g) { return 0; } *x0 *= c / *g; *y0 *= c / *g; // Adjusting the sign // of x0 and y0 if (a < 0) *x0 *= -1; if (b < 0) *y0 *= -1; return 1;} // Function to shift solutionvoid shift_solution(int* x, int* y, int a, int b, int shift_var){ // Shifting to obtain // another solution *x += shift_var * b; *y -= shift_var * a;} // Function to find minimum// value of x and yint find_min_sum(int a, int b, int c){ int x, y, g; // g is the gcd of a and b if (!possible_solution(a, b, c, &x, &y, &g)) return -1; a /= g; b /= g; // Store sign of a and b int sign_a = a > 0 ? +1 : -1; int sign_b = b > 0 ? +1 : -1; shift_solution(&x, &y, a, b, -x / b); // If x is less than 0, then // shift solution if (x < 0) shift_solution(&x, &y, a, b, sign_b); int minx1 = x; shift_solution(&x, &y, a, b, y / a); // If y is less than 0, then // shift solution if (y < 0) shift_solution(&x, &y, a, b, -sign_a); int minx2 = x; if (minx2 > x) swap(minx2, x); int minx = max(minx1, minx2); // Find intersection such // that both x and y are positive if (minx > x) return -1; // miny is value of y // corresponding to minx int miny = (c - a * x) / b; // Returns minimum value of x+y return (miny + minx);} // Driver Codeint main(){ // Given a, b, and c int a = 2, b = 2, c = 0; // Function Call cout << find_min_sum(a, b, c) << "\n"; return 0;} // Java program for the above approachimport java.lang.*;class GFG{ public static int x = 0, y = 0, x1 = 0, y1 = 0;public static int x0 = 0, y0 = 0, g = 0; // Function to find the gcd of a & b// by Euclid's method // x and y store solution of// equation ax + by = g public static int gcd(int a, int b){ if (b == 0) { x = 1; y = 0; return a; } int store_gcd = gcd(b, a % b); // Euclidean Algorithm x = y1; y = x1 - y1 * (a / b); // store_gcd returns // the gcd of a and b return store_gcd;} // Function to find any// possible solutionpublic static int possible_solution(int a, int b, int c){ g = gcd(Math.abs(a), Math.abs(b)); // Condition if solution // does not exists if (c % g != 0) { return 0; } x0 *= c / g; y0 *= c / g; // Adjusting the sign // of x0 and y0 if (a < 0) x0 *= -1; if (b < 0) y0 *= -1; return 1;} // Function to shift solutionpublic static void shift_solution(int a, int b, int shift_var){ // Shifting to obtain // another solution x += shift_var * b; y -= shift_var * a;} // Function to find minimum// value of x and ypublic static int find_min_sum(int a, int b, int c){ int x = 0, y = 0, g = 0; // g is the gcd of a and b if (possible_solution(a, b, c) == 0) return -1; if (g != 0) { a /= g; b /= g; } // Store sign of a and b int sign_a = a > 0 ? + 1 : -1; int sign_b = b > 0 ? + 1 : -1; shift_solution(a, b, -x / b); // If x is less than 0, then // shift solution if (x < 0) shift_solution(a, b, sign_b); int minx1 = x; shift_solution(a, b, y / a); // If y is less than 0, then // shift solution if (y < 0) shift_solution(a, b, -sign_a); int minx2 = x; if (minx2 > x) { int temp = minx2; minx2 = x; x = temp; } int minx = Math.max(minx1, minx2); // Find intersection such // that both x and y are positive if (minx > x) return -1; // miny is value of y // corresponding to minx int miny = (c - a * x) / b; // Returns minimum value of x+y return (miny + minx);} // Driver Codepublic static void main(String[] args){ // Given a, b, and c int a = 2, b = 2, c = 0; // Function call System.out.println(find_min_sum(a, b, c));}} // This code is contributed by grand_master # Python3 program for the# above approach x, y, x1, y1 = 0, 0, 0, 0x0, y0, g = 0, 0, 0 # Function to find the gcd# of a & b by Euclid's method # x and y store solution of# equation ax + by = gdef gcd(a, b) : global x, y, x1, y1 if (b == 0) : x = 1 y = 0 return a store_gcd = gcd(b, a % b) # Euclidean Algorithm x = y1 y = x1 - y1 * (a // b) # store_gcd returns # the gcd of a and b return store_gcd # Function to find any# possible solutiondef possible_solution(a, b, c) : global x0, y0, g g = gcd(abs(a), abs(b)) # Condition if solution # does not exists if (c % g != 0) : return 0 x0 *= c // g y0 *= c // g # Adjusting the sign # of x0 and y0 if (a < 0) : x0 *= -1 if (b < 0) : y0 *= -1 return 1 # Function to shift solutiondef shift_solution(a, b, shift_var) : global x, y # Shifting to obtain # another solution x += shift_var * b y -= shift_var * a # Function to find minimum# value of x and ydef find_min_sum(a, b, c) : global x, y, g x, y, g = 0, 0, 0 # g is the gcd of a and b if (possible_solution(a, b, c) == 0) : return -1 if (g != 0) : a //= g b //= g # Store sign of a and b if a > 0 : sign_a = 1 else : sign_a = -1 if b > 0 : sign_b = 1 else : sign_b = -1 shift_solution(a, b, -x // b) # If x is less than 0, # then shift solution if (x < 0) : shift_solution(a, b, sign_b) minx1 = x shift_solution(a, b, y // a) # If y is less than 0, # then shift solution if (y < 0) : shift_solution(a, b, -sign_a) minx2 = x if (minx2 > x) : temp = minx2 minx2 = x x = temp minx = max(minx1, minx2) # Find intersection such # that both x and y are positive if (minx > x) : return -1 # miny is value of y # corresponding to minx miny = (c - a * x) // b # Returns minimum value # of x + y return (miny + minx) # Given a, b, and ca, b, c = 2, 2, 0 # Function callprint(find_min_sum(a, b, c)) # This code is contributed by divyesh072019 // C# program for the// above approachusing System;class GFG{ public static int x = 0, y = 0, x1 = 0, y1 = 0;public static int x0 = 0, y0 = 0, g = 0; // Function to find the gcd// of a & b by Euclid's method // x and y store solution of// equation ax + by = gpublic static int gcd(int a, int b){ if (b == 0) { x = 1; y = 0; return a; } int store_gcd = gcd(b, a % b); // Euclidean Algorithm x = y1; y = x1 - y1 * (a / b); // store_gcd returns // the gcd of a and b return store_gcd;} // Function to find any// possible solutionpublic static int possible_solution(int a, int b, int c){ g = gcd(Math.Abs(a), Math.Abs(b)); // Condition if solution // does not exists if (c % g != 0) { return 0; } x0 *= c / g; y0 *= c / g; // Adjusting the sign // of x0 and y0 if (a < 0) x0 *= -1; if (b < 0) y0 *= -1; return 1;} // Function to shift solutionpublic static void shift_solution(int a, int b, int shift_var){ // Shifting to obtain // another solution x += shift_var * b; y -= shift_var * a;} // Function to find minimum// value of x and ypublic static int find_min_sum(int a, int b, int c){ int x = 0, y = 0, g = 0; // g is the gcd of a and b if (possible_solution(a, b, c) == 0) return -1; if (g != 0) { a /= g; b /= g; } // Store sign of a and b int sign_a = a > 0 ? +1 : -1; int sign_b = b > 0 ? +1 : -1; shift_solution(a, b, -x / b); // If x is less than 0, // then shift solution if (x < 0) shift_solution(a, b, sign_b); int minx1 = x; shift_solution(a, b, y / a); // If y is less than 0, // then shift solution if (y < 0) shift_solution(a, b, -sign_a); int minx2 = x; if (minx2 > x) { int temp = minx2; minx2 = x; x = temp; } int minx = Math.Max(minx1, minx2); // Find intersection such // that both x and y are positive if (minx > x) return -1; // miny is value of y // corresponding to minx int miny = (c - a * x) / b; // Returns minimum value // of x + y return (miny + minx);} // Driver Codepublic static void Main(String[] args){ // Given a, b, and c int a = 2, b = 2, c = 0; // Function call Console.Write(find_min_sum(a, b, c));}} // This code is contributed by Chitranayal <script> // Javascript program for the above approach let x = 0, y = 0, x1 = 0, y1 = 0; let x0 = 0, y0 = 0, g = 0; // Function to find the gcd // of a & b by Euclid's method // x and y store solution of // equation ax + by = g function gcd(a, b) { if (b == 0) { x = 1; y = 0; return a; } let store_gcd = gcd(b, a % b); // Euclidean Algorithm x = y1; y = x1 - y1 * parseInt(a / b, 10); // store_gcd returns // the gcd of a and b return store_gcd; } // Function to find any // possible solution function possible_solution(a, b, c) { g = gcd(Math.abs(a), Math.abs(b)); // Condition if solution // does not exists if (c % g != 0) { return 0; } x0 *= parseInt(c / g, 10); y0 *= parseInt(c / g, 10); // Adjusting the sign // of x0 and y0 if (a < 0) x0 *= -1; if (b < 0) y0 *= -1; return 1; } // Function to shift solution function shift_solution(a, b, shift_var) { // Shifting to obtain // another solution x += shift_var * b; y -= shift_var * a; } // Function to find minimum // value of x and y function find_min_sum(a, b, c) { let x = 0, y = 0, g = 0; // g is the gcd of a and b if (possible_solution(a, b, c) == 0) return -1; if (g != 0) { a = parseInt(a / g, 10); b = parseInt(b / g, 10); } // Store sign of a and b let sign_a = a > 0 ? +1 : -1; let sign_b = b > 0 ? +1 : -1; shift_solution(a, b, parseInt(-x / b, 10)); // If x is less than 0, // then shift solution if (x < 0) shift_solution(a, b, sign_b); let minx1 = x; shift_solution(a, b, parseInt(y / a, 10)); // If y is less than 0, // then shift solution if (y < 0) shift_solution(a, b, -sign_a); let minx2 = x; if (minx2 > x) { let temp = minx2; minx2 = x; x = temp; } let minx = Math.max(minx1, minx2); // Find intersection such // that both x and y are positive if (minx > x) return -1; // miny is value of y // corresponding to minx let miny = parseInt((c - a * x) / b, 10); // Returns minimum value // of x + y return (miny + minx); } // Given a, b, and c let a = 2, b = 2, c = 0; // Function call document.write(find_min_sum(a, b, c)); </script> 0 Time Complexity: O(loga+logb) = O(logn) , time used to find gcd Auxiliary Space: O(1) , as no extra space is used grand_master ukasp divyesh072019 mukesh07 moraliser singhh3010 Algebra Articles Competitive Programming Mathematical Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n10 Jun, 2022" }, { "code": null, "e": 346, "s": 52, "text": "Time ComGiven three integers a, b, and c representing a linear equation of the form ax + by = c, the task is to find the solution (x, y) of the given equation such that (x + y) is minimized. If no solution exists for the above equation then print “-1”. Note: x and y are non negative integers." }, { "code": null, "e": 357, "s": 346, "text": "Examples: " }, { "code": null, "e": 525, "s": 357, "text": "Input: a = 2, b = 2, c = 0 Output: 0 Explanation: The given equation is 2x + 2y = 0. Therefore, x = 0 and y = 0 is the required solution with minimum value of (x + y)." }, { "code": null, "e": 687, "s": 525, "text": "Input: a = 2, b = 2, c = 1 Output: -1 Explanation: The given equation is 2x + 2y = 1. No solution exists for the given equation for positive values of x and y. " }, { "code": null, "e": 912, "s": 687, "text": "Approach: To solve the above problem, find any solution say (x, y) of the given Linear Diophantine Equation and then accordingly find value of x and to minimised the sum.Below is the solution (x’, y’) of the given equation: " }, { "code": null, "e": 964, "s": 912, "text": "[Tex]y’ = y – k * \\frac{a}{g} [/Tex] " }, { "code": null, "e": 1008, "s": 964, "text": "where g is gcd(a, b) and k is any integer. " }, { "code": null, "e": 1062, "s": 1008, "text": "[Tex]x’ + y’ = x + y + k*\\frac{b-a}{g} [/Tex]" }, { "code": null, "e": 1104, "s": 1062, "text": "From the above equation we observe that: " }, { "code": null, "e": 1312, "s": 1104, "text": "If a is less than b, we need to select the smallest possible value of K.Else, if a is greater than b, we need to select the largest possible value of K.If a = b, all solutions will have the same sum (x + y)." }, { "code": null, "e": 1385, "s": 1312, "text": "If a is less than b, we need to select the smallest possible value of K." }, { "code": null, "e": 1466, "s": 1385, "text": "Else, if a is greater than b, we need to select the largest possible value of K." }, { "code": null, "e": 1522, "s": 1466, "text": "If a = b, all solutions will have the same sum (x + y)." }, { "code": null, "e": 1573, "s": 1522, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 1577, "s": 1573, "text": "C++" }, { "code": null, "e": 1582, "s": 1577, "text": "Java" }, { "code": null, "e": 1590, "s": 1582, "text": "Python3" }, { "code": null, "e": 1593, "s": 1590, "text": "C#" }, { "code": null, "e": 1604, "s": 1593, "text": "Javascript" }, { "code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to find the gcd of a & b// by Euclid's method // x and y store solution of// equation ax + by = gint gcd(int a, int b, int* x, int* y){ if (b == 0) { *x = 1; *y = 0; return a; } int x1, y1; int store_gcd = gcd(b, a % b, &x1, &y1); // Euclidean Algorithm *x = y1; *y = x1 - y1 * (a / b); // store_gcd returns // the gcd of a and b return store_gcd;} // Function to find any// possible solutionint possible_solution(int a, int b, int c, int* x0, int* y0, int* g){ *g = gcd(fabs(a), fabs(b), x0, y0); // Condition if solution // does not exists if (c % *g) { return 0; } *x0 *= c / *g; *y0 *= c / *g; // Adjusting the sign // of x0 and y0 if (a < 0) *x0 *= -1; if (b < 0) *y0 *= -1; return 1;} // Function to shift solutionvoid shift_solution(int* x, int* y, int a, int b, int shift_var){ // Shifting to obtain // another solution *x += shift_var * b; *y -= shift_var * a;} // Function to find minimum// value of x and yint find_min_sum(int a, int b, int c){ int x, y, g; // g is the gcd of a and b if (!possible_solution(a, b, c, &x, &y, &g)) return -1; a /= g; b /= g; // Store sign of a and b int sign_a = a > 0 ? +1 : -1; int sign_b = b > 0 ? +1 : -1; shift_solution(&x, &y, a, b, -x / b); // If x is less than 0, then // shift solution if (x < 0) shift_solution(&x, &y, a, b, sign_b); int minx1 = x; shift_solution(&x, &y, a, b, y / a); // If y is less than 0, then // shift solution if (y < 0) shift_solution(&x, &y, a, b, -sign_a); int minx2 = x; if (minx2 > x) swap(minx2, x); int minx = max(minx1, minx2); // Find intersection such // that both x and y are positive if (minx > x) return -1; // miny is value of y // corresponding to minx int miny = (c - a * x) / b; // Returns minimum value of x+y return (miny + minx);} // Driver Codeint main(){ // Given a, b, and c int a = 2, b = 2, c = 0; // Function Call cout << find_min_sum(a, b, c) << \"\\n\"; return 0;}", "e": 3971, "s": 1604, "text": null }, { "code": "// Java program for the above approachimport java.lang.*;class GFG{ public static int x = 0, y = 0, x1 = 0, y1 = 0;public static int x0 = 0, y0 = 0, g = 0; // Function to find the gcd of a & b// by Euclid's method // x and y store solution of// equation ax + by = g public static int gcd(int a, int b){ if (b == 0) { x = 1; y = 0; return a; } int store_gcd = gcd(b, a % b); // Euclidean Algorithm x = y1; y = x1 - y1 * (a / b); // store_gcd returns // the gcd of a and b return store_gcd;} // Function to find any// possible solutionpublic static int possible_solution(int a, int b, int c){ g = gcd(Math.abs(a), Math.abs(b)); // Condition if solution // does not exists if (c % g != 0) { return 0; } x0 *= c / g; y0 *= c / g; // Adjusting the sign // of x0 and y0 if (a < 0) x0 *= -1; if (b < 0) y0 *= -1; return 1;} // Function to shift solutionpublic static void shift_solution(int a, int b, int shift_var){ // Shifting to obtain // another solution x += shift_var * b; y -= shift_var * a;} // Function to find minimum// value of x and ypublic static int find_min_sum(int a, int b, int c){ int x = 0, y = 0, g = 0; // g is the gcd of a and b if (possible_solution(a, b, c) == 0) return -1; if (g != 0) { a /= g; b /= g; } // Store sign of a and b int sign_a = a > 0 ? + 1 : -1; int sign_b = b > 0 ? + 1 : -1; shift_solution(a, b, -x / b); // If x is less than 0, then // shift solution if (x < 0) shift_solution(a, b, sign_b); int minx1 = x; shift_solution(a, b, y / a); // If y is less than 0, then // shift solution if (y < 0) shift_solution(a, b, -sign_a); int minx2 = x; if (minx2 > x) { int temp = minx2; minx2 = x; x = temp; } int minx = Math.max(minx1, minx2); // Find intersection such // that both x and y are positive if (minx > x) return -1; // miny is value of y // corresponding to minx int miny = (c - a * x) / b; // Returns minimum value of x+y return (miny + minx);} // Driver Codepublic static void main(String[] args){ // Given a, b, and c int a = 2, b = 2, c = 0; // Function call System.out.println(find_min_sum(a, b, c));}} // This code is contributed by grand_master", "e": 6537, "s": 3971, "text": null }, { "code": "# Python3 program for the# above approach x, y, x1, y1 = 0, 0, 0, 0x0, y0, g = 0, 0, 0 # Function to find the gcd# of a & b by Euclid's method # x and y store solution of# equation ax + by = gdef gcd(a, b) : global x, y, x1, y1 if (b == 0) : x = 1 y = 0 return a store_gcd = gcd(b, a % b) # Euclidean Algorithm x = y1 y = x1 - y1 * (a // b) # store_gcd returns # the gcd of a and b return store_gcd # Function to find any# possible solutiondef possible_solution(a, b, c) : global x0, y0, g g = gcd(abs(a), abs(b)) # Condition if solution # does not exists if (c % g != 0) : return 0 x0 *= c // g y0 *= c // g # Adjusting the sign # of x0 and y0 if (a < 0) : x0 *= -1 if (b < 0) : y0 *= -1 return 1 # Function to shift solutiondef shift_solution(a, b, shift_var) : global x, y # Shifting to obtain # another solution x += shift_var * b y -= shift_var * a # Function to find minimum# value of x and ydef find_min_sum(a, b, c) : global x, y, g x, y, g = 0, 0, 0 # g is the gcd of a and b if (possible_solution(a, b, c) == 0) : return -1 if (g != 0) : a //= g b //= g # Store sign of a and b if a > 0 : sign_a = 1 else : sign_a = -1 if b > 0 : sign_b = 1 else : sign_b = -1 shift_solution(a, b, -x // b) # If x is less than 0, # then shift solution if (x < 0) : shift_solution(a, b, sign_b) minx1 = x shift_solution(a, b, y // a) # If y is less than 0, # then shift solution if (y < 0) : shift_solution(a, b, -sign_a) minx2 = x if (minx2 > x) : temp = minx2 minx2 = x x = temp minx = max(minx1, minx2) # Find intersection such # that both x and y are positive if (minx > x) : return -1 # miny is value of y # corresponding to minx miny = (c - a * x) // b # Returns minimum value # of x + y return (miny + minx) # Given a, b, and ca, b, c = 2, 2, 0 # Function callprint(find_min_sum(a, b, c)) # This code is contributed by divyesh072019", "e": 8814, "s": 6537, "text": null }, { "code": "// C# program for the// above approachusing System;class GFG{ public static int x = 0, y = 0, x1 = 0, y1 = 0;public static int x0 = 0, y0 = 0, g = 0; // Function to find the gcd// of a & b by Euclid's method // x and y store solution of// equation ax + by = gpublic static int gcd(int a, int b){ if (b == 0) { x = 1; y = 0; return a; } int store_gcd = gcd(b, a % b); // Euclidean Algorithm x = y1; y = x1 - y1 * (a / b); // store_gcd returns // the gcd of a and b return store_gcd;} // Function to find any// possible solutionpublic static int possible_solution(int a, int b, int c){ g = gcd(Math.Abs(a), Math.Abs(b)); // Condition if solution // does not exists if (c % g != 0) { return 0; } x0 *= c / g; y0 *= c / g; // Adjusting the sign // of x0 and y0 if (a < 0) x0 *= -1; if (b < 0) y0 *= -1; return 1;} // Function to shift solutionpublic static void shift_solution(int a, int b, int shift_var){ // Shifting to obtain // another solution x += shift_var * b; y -= shift_var * a;} // Function to find minimum// value of x and ypublic static int find_min_sum(int a, int b, int c){ int x = 0, y = 0, g = 0; // g is the gcd of a and b if (possible_solution(a, b, c) == 0) return -1; if (g != 0) { a /= g; b /= g; } // Store sign of a and b int sign_a = a > 0 ? +1 : -1; int sign_b = b > 0 ? +1 : -1; shift_solution(a, b, -x / b); // If x is less than 0, // then shift solution if (x < 0) shift_solution(a, b, sign_b); int minx1 = x; shift_solution(a, b, y / a); // If y is less than 0, // then shift solution if (y < 0) shift_solution(a, b, -sign_a); int minx2 = x; if (minx2 > x) { int temp = minx2; minx2 = x; x = temp; } int minx = Math.Max(minx1, minx2); // Find intersection such // that both x and y are positive if (minx > x) return -1; // miny is value of y // corresponding to minx int miny = (c - a * x) / b; // Returns minimum value // of x + y return (miny + minx);} // Driver Codepublic static void Main(String[] args){ // Given a, b, and c int a = 2, b = 2, c = 0; // Function call Console.Write(find_min_sum(a, b, c));}} // This code is contributed by Chitranayal", "e": 11411, "s": 8814, "text": null }, { "code": "<script> // Javascript program for the above approach let x = 0, y = 0, x1 = 0, y1 = 0; let x0 = 0, y0 = 0, g = 0; // Function to find the gcd // of a & b by Euclid's method // x and y store solution of // equation ax + by = g function gcd(a, b) { if (b == 0) { x = 1; y = 0; return a; } let store_gcd = gcd(b, a % b); // Euclidean Algorithm x = y1; y = x1 - y1 * parseInt(a / b, 10); // store_gcd returns // the gcd of a and b return store_gcd; } // Function to find any // possible solution function possible_solution(a, b, c) { g = gcd(Math.abs(a), Math.abs(b)); // Condition if solution // does not exists if (c % g != 0) { return 0; } x0 *= parseInt(c / g, 10); y0 *= parseInt(c / g, 10); // Adjusting the sign // of x0 and y0 if (a < 0) x0 *= -1; if (b < 0) y0 *= -1; return 1; } // Function to shift solution function shift_solution(a, b, shift_var) { // Shifting to obtain // another solution x += shift_var * b; y -= shift_var * a; } // Function to find minimum // value of x and y function find_min_sum(a, b, c) { let x = 0, y = 0, g = 0; // g is the gcd of a and b if (possible_solution(a, b, c) == 0) return -1; if (g != 0) { a = parseInt(a / g, 10); b = parseInt(b / g, 10); } // Store sign of a and b let sign_a = a > 0 ? +1 : -1; let sign_b = b > 0 ? +1 : -1; shift_solution(a, b, parseInt(-x / b, 10)); // If x is less than 0, // then shift solution if (x < 0) shift_solution(a, b, sign_b); let minx1 = x; shift_solution(a, b, parseInt(y / a, 10)); // If y is less than 0, // then shift solution if (y < 0) shift_solution(a, b, -sign_a); let minx2 = x; if (minx2 > x) { let temp = minx2; minx2 = x; x = temp; } let minx = Math.max(minx1, minx2); // Find intersection such // that both x and y are positive if (minx > x) return -1; // miny is value of y // corresponding to minx let miny = parseInt((c - a * x) / b, 10); // Returns minimum value // of x + y return (miny + minx); } // Given a, b, and c let a = 2, b = 2, c = 0; // Function call document.write(find_min_sum(a, b, c)); </script>", "e": 13945, "s": 11411, "text": null }, { "code": null, "e": 13950, "s": 13948, "text": "0" }, { "code": null, "e": 14066, "s": 13952, "text": "Time Complexity: O(loga+logb) = O(logn) , time used to find gcd Auxiliary Space: O(1) , as no extra space is used" }, { "code": null, "e": 14079, "s": 14066, "text": "grand_master" }, { "code": null, "e": 14085, "s": 14079, "text": "ukasp" }, { "code": null, "e": 14099, "s": 14085, "text": "divyesh072019" }, { "code": null, "e": 14108, "s": 14099, "text": "mukesh07" }, { "code": null, "e": 14118, "s": 14108, "text": "moraliser" }, { "code": null, "e": 14129, "s": 14118, "text": "singhh3010" }, { "code": null, "e": 14137, "s": 14129, "text": "Algebra" }, { "code": null, "e": 14146, "s": 14137, "text": "Articles" }, { "code": null, "e": 14170, "s": 14146, "text": "Competitive Programming" }, { "code": null, "e": 14183, "s": 14170, "text": "Mathematical" }, { "code": null, "e": 14196, "s": 14183, "text": "Mathematical" } ]
OpenCV C++ Program for Face Detection
17 Jun, 2017 This program uses the OpenCV library to detect faces in a live stream from webcam or in a video file stored in the local machine. This program detects faces in real time and tracks it. It uses pre-trained XML classifiers for the same. The classifiers used in this program have facial features trained in them. Different classifiers can be used to detect different objects.Requirements for running the program:1) OpenCV must be installed on the local machine.2) Paths to the classifier XML files must be given before the execution of the program. These XML files can be found in the OpenCV directory “opencv/data/haarcascades”.3) Use 0 in capture.open(0) to play webcam feed.4) For detection in a local video provide the path to the video.(capture.open(“path_to_video”)).Implementation: // CPP program to detects face in a video // Include required header files from OpenCV directory#include "/usr/local/include/opencv2/objdetect.hpp"#include "/usr/local/include/opencv2/highgui.hpp"#include "/usr/local/include/opencv2/imgproc.hpp"#include <iostream> using namespace std;using namespace cv; // Function for Face Detectionvoid detectAndDraw( Mat& img, CascadeClassifier& cascade, CascadeClassifier& nestedCascade, double scale );string cascadeName, nestedCascadeName; int main( int argc, const char** argv ){ // VideoCapture class for playing video for which faces to be detected VideoCapture capture; Mat frame, image; // PreDefined trained XML classifiers with facial features CascadeClassifier cascade, nestedCascade; double scale=1; // Load classifiers from "opencv/data/haarcascades" directory nestedCascade.load( "../../haarcascade_eye_tree_eyeglasses.xml" ) ; // Change path before execution cascade.load( "../../haarcascade_frontalcatface.xml" ) ; // Start Video..1) 0 for WebCam 2) "Path to Video" for a Local Video capture.open(0); if( capture.isOpened() ) { // Capture frames from video and detect faces cout << "Face Detection Started...." << endl; while(1) { capture >> frame; if( frame.empty() ) break; Mat frame1 = frame.clone(); detectAndDraw( frame1, cascade, nestedCascade, scale ); char c = (char)waitKey(10); // Press q to exit from window if( c == 27 || c == 'q' || c == 'Q' ) break; } } else cout<<"Could not Open Camera"; return 0;} void detectAndDraw( Mat& img, CascadeClassifier& cascade, CascadeClassifier& nestedCascade, double scale){ vector<Rect> faces, faces2; Mat gray, smallImg; cvtColor( img, gray, COLOR_BGR2GRAY ); // Convert to Gray Scale double fx = 1 / scale; // Resize the Grayscale Image resize( gray, smallImg, Size(), fx, fx, INTER_LINEAR ); equalizeHist( smallImg, smallImg ); // Detect faces of different sizes using cascade classifier cascade.detectMultiScale( smallImg, faces, 1.1, 2, 0|CASCADE_SCALE_IMAGE, Size(30, 30) ); // Draw circles around the faces for ( size_t i = 0; i < faces.size(); i++ ) { Rect r = faces[i]; Mat smallImgROI; vector<Rect> nestedObjects; Point center; Scalar color = Scalar(255, 0, 0); // Color for Drawing tool int radius; double aspect_ratio = (double)r.width/r.height; if( 0.75 < aspect_ratio && aspect_ratio < 1.3 ) { center.x = cvRound((r.x + r.width*0.5)*scale); center.y = cvRound((r.y + r.height*0.5)*scale); radius = cvRound((r.width + r.height)*0.25*scale); circle( img, center, radius, color, 3, 8, 0 ); } else rectangle( img, cvPoint(cvRound(r.x*scale), cvRound(r.y*scale)), cvPoint(cvRound((r.x + r.width-1)*scale), cvRound((r.y + r.height-1)*scale)), color, 3, 8, 0); if( nestedCascade.empty() ) continue; smallImgROI = smallImg( r ); // Detection of eyes int the input image nestedCascade.detectMultiScale( smallImgROI, nestedObjects, 1.1, 2, 0|CASCADE_SCALE_IMAGE, Size(30, 30) ); // Draw circles around eyes for ( size_t j = 0; j < nestedObjects.size(); j++ ) { Rect nr = nestedObjects[j]; center.x = cvRound((r.x + nr.x + nr.width*0.5)*scale); center.y = cvRound((r.y + nr.y + nr.height*0.5)*scale); radius = cvRound((nr.width + nr.height)*0.25*scale); circle( img, center, radius, color, 3, 8, 0 ); } } // Show Processed Image with detected faces imshow( "Face Detection", img ); } Output: Face Detection Next Article: Opencv Python Program for face detectionReferences: 1) http://docs.opencv.org/2.4/modules/contrib/doc/facerec/facerec_tutorial.html2) http://docs.opencv.org/2.4/doc/tutorials/objdetect/cascade_classifier/cascade_classifier.html This article is contributed by Shashwat Jain. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Image-Processing OpenCV C++ Project CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Set in C++ Standard Template Library (STL) unordered_map in C++ STL vector erase() and clear() in C++ Substring in C++ Priority Queue in C++ Standard Template Library (STL) SDE SHEET - A Complete Guide for SDE Preparation Implementing Web Scraping in Python with BeautifulSoup Working with zip files in Python XML parsing in Python Python | Simple GUI calculator using Tkinter
[ { "code": null, "e": 54, "s": 26, "text": "\n17 Jun, 2017" }, { "code": null, "e": 840, "s": 54, "text": "This program uses the OpenCV library to detect faces in a live stream from webcam or in a video file stored in the local machine. This program detects faces in real time and tracks it. It uses pre-trained XML classifiers for the same. The classifiers used in this program have facial features trained in them. Different classifiers can be used to detect different objects.Requirements for running the program:1) OpenCV must be installed on the local machine.2) Paths to the classifier XML files must be given before the execution of the program. These XML files can be found in the OpenCV directory “opencv/data/haarcascades”.3) Use 0 in capture.open(0) to play webcam feed.4) For detection in a local video provide the path to the video.(capture.open(“path_to_video”)).Implementation:" }, { "code": "// CPP program to detects face in a video // Include required header files from OpenCV directory#include \"/usr/local/include/opencv2/objdetect.hpp\"#include \"/usr/local/include/opencv2/highgui.hpp\"#include \"/usr/local/include/opencv2/imgproc.hpp\"#include <iostream> using namespace std;using namespace cv; // Function for Face Detectionvoid detectAndDraw( Mat& img, CascadeClassifier& cascade, CascadeClassifier& nestedCascade, double scale );string cascadeName, nestedCascadeName; int main( int argc, const char** argv ){ // VideoCapture class for playing video for which faces to be detected VideoCapture capture; Mat frame, image; // PreDefined trained XML classifiers with facial features CascadeClassifier cascade, nestedCascade; double scale=1; // Load classifiers from \"opencv/data/haarcascades\" directory nestedCascade.load( \"../../haarcascade_eye_tree_eyeglasses.xml\" ) ; // Change path before execution cascade.load( \"../../haarcascade_frontalcatface.xml\" ) ; // Start Video..1) 0 for WebCam 2) \"Path to Video\" for a Local Video capture.open(0); if( capture.isOpened() ) { // Capture frames from video and detect faces cout << \"Face Detection Started....\" << endl; while(1) { capture >> frame; if( frame.empty() ) break; Mat frame1 = frame.clone(); detectAndDraw( frame1, cascade, nestedCascade, scale ); char c = (char)waitKey(10); // Press q to exit from window if( c == 27 || c == 'q' || c == 'Q' ) break; } } else cout<<\"Could not Open Camera\"; return 0;} void detectAndDraw( Mat& img, CascadeClassifier& cascade, CascadeClassifier& nestedCascade, double scale){ vector<Rect> faces, faces2; Mat gray, smallImg; cvtColor( img, gray, COLOR_BGR2GRAY ); // Convert to Gray Scale double fx = 1 / scale; // Resize the Grayscale Image resize( gray, smallImg, Size(), fx, fx, INTER_LINEAR ); equalizeHist( smallImg, smallImg ); // Detect faces of different sizes using cascade classifier cascade.detectMultiScale( smallImg, faces, 1.1, 2, 0|CASCADE_SCALE_IMAGE, Size(30, 30) ); // Draw circles around the faces for ( size_t i = 0; i < faces.size(); i++ ) { Rect r = faces[i]; Mat smallImgROI; vector<Rect> nestedObjects; Point center; Scalar color = Scalar(255, 0, 0); // Color for Drawing tool int radius; double aspect_ratio = (double)r.width/r.height; if( 0.75 < aspect_ratio && aspect_ratio < 1.3 ) { center.x = cvRound((r.x + r.width*0.5)*scale); center.y = cvRound((r.y + r.height*0.5)*scale); radius = cvRound((r.width + r.height)*0.25*scale); circle( img, center, radius, color, 3, 8, 0 ); } else rectangle( img, cvPoint(cvRound(r.x*scale), cvRound(r.y*scale)), cvPoint(cvRound((r.x + r.width-1)*scale), cvRound((r.y + r.height-1)*scale)), color, 3, 8, 0); if( nestedCascade.empty() ) continue; smallImgROI = smallImg( r ); // Detection of eyes int the input image nestedCascade.detectMultiScale( smallImgROI, nestedObjects, 1.1, 2, 0|CASCADE_SCALE_IMAGE, Size(30, 30) ); // Draw circles around eyes for ( size_t j = 0; j < nestedObjects.size(); j++ ) { Rect nr = nestedObjects[j]; center.x = cvRound((r.x + nr.x + nr.width*0.5)*scale); center.y = cvRound((r.y + nr.y + nr.height*0.5)*scale); radius = cvRound((nr.width + nr.height)*0.25*scale); circle( img, center, radius, color, 3, 8, 0 ); } } // Show Processed Image with detected faces imshow( \"Face Detection\", img ); }", "e": 4856, "s": 840, "text": null }, { "code": null, "e": 4864, "s": 4856, "text": "Output:" }, { "code": null, "e": 4879, "s": 4864, "text": "Face Detection" }, { "code": null, "e": 4945, "s": 4879, "text": "Next Article: Opencv Python Program for face detectionReferences:" }, { "code": null, "e": 5121, "s": 4945, "text": "1) http://docs.opencv.org/2.4/modules/contrib/doc/facerec/facerec_tutorial.html2) http://docs.opencv.org/2.4/doc/tutorials/objdetect/cascade_classifier/cascade_classifier.html" }, { "code": null, "e": 5422, "s": 5121, "text": "This article is contributed by Shashwat Jain. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 5547, "s": 5422, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 5564, "s": 5547, "text": "Image-Processing" }, { "code": null, "e": 5571, "s": 5564, "text": "OpenCV" }, { "code": null, "e": 5575, "s": 5571, "text": "C++" }, { "code": null, "e": 5583, "s": 5575, "text": "Project" }, { "code": null, "e": 5587, "s": 5583, "text": "CPP" }, { "code": null, "e": 5685, "s": 5587, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5728, "s": 5685, "text": "Set in C++ Standard Template Library (STL)" }, { "code": null, "e": 5753, "s": 5728, "text": "unordered_map in C++ STL" }, { "code": null, "e": 5787, "s": 5753, "text": "vector erase() and clear() in C++" }, { "code": null, "e": 5804, "s": 5787, "text": "Substring in C++" }, { "code": null, "e": 5858, "s": 5804, "text": "Priority Queue in C++ Standard Template Library (STL)" }, { "code": null, "e": 5907, "s": 5858, "text": "SDE SHEET - A Complete Guide for SDE Preparation" }, { "code": null, "e": 5962, "s": 5907, "text": "Implementing Web Scraping in Python with BeautifulSoup" }, { "code": null, "e": 5995, "s": 5962, "text": "Working with zip files in Python" }, { "code": null, "e": 6017, "s": 5995, "text": "XML parsing in Python" } ]
How to spin text on mouse hover using HTML and CSS?
27 Sep, 2021 The spinning of text on mouse hover is known as the Spin Effect or the Rotation Effect. In this effect, each alphabet of the word is rotated along with any one of the axes (preferably Y-axis). Each word is wrapped inside in <li> tag and then using CSS:hover Selector selector we will rotate each alphabet on Y-axis. We will divide this article into two sections, in the first section we will create the basic structure of the text that will spin. IN the second section we will make that text structure spinnable when the user the hover on that. Creating Structure: In this section we will create the structure by using HTML. HTML Code: In this we have created an unordered-list and wrap each alphabet inside an list-item(li). HTML <!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Spin Text</title> </head> <body> <ul> <li>G</li> <li>e</li> <li>e</li> <li>k</li> <li>s</li> <li>f</li> <li>o</li> <li>r</li> <li>G</li> <li>e</li> <li>e</li> <li>k</li> <li>s</li> </ul> </body></html> Designing Structure: In this section we will make that structure spinnable and add the little bit of decoration. CSS Code: First we have provide some basic styling like margin, padding and background. Then we have aligned our list-items horizontally using the float property. Finally, use the hover selector to rotate each alphabet along Y-axis on a particular degree. If you want you can use n-th child property to apply some delay to rotation of each alphabet.The use of n-th child comes to personal preferences and needs so if you feel like using it you can surely go for it. CSS <style> body { margin: 0; padding: 0; } ul { padding: 50px; margin: 0; position: absolute; top: 20%; left: 25%; } ul li { list-style: none; color: green; float: left; font-size: 40px; transition: 0.8s; } ul:hover li { transform: rotateY(360deg); }</style> Final Solution: It is the combination of the above two codes. HTML <!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Spin Text</title> <style> body { margin: 0; padding: 0; } ul { padding: 50px; margin: 0; position: absolute; top: 20%; left: 25%; } ul li { list-style: none; color: green; float: left; font-size: 40px; transition: 0.8s; } ul:hover li { transform: rotateY(360deg); } </style> </head> <body> <ul> <li>G</li> <li>e</li> <li>e</li> <li>k</li> <li>s</li> <li>f</li> <li>o</li> <li>r</li> <li>G</li> <li>e</li> <li>e</li> <li>k</li> <li>s</li> </ul> </body></html> Output: arorakashish0911 CSS-Misc HTML-Misc CSS HTML Web Technologies Web technologies Questions HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Types of CSS (Cascading Style Sheet) Design a Tribute Page using HTML & CSS How to set space between the flexbox ? How to position a div at the bottom of its container using CSS? How to Upload Image into Database and Display it using PHP ? REST API (Introduction) Hide or show elements in HTML using display property How to set the default value for an HTML <select> element ? How to set input type date in dd-mm-yyyy format using HTML ? Types of CSS (Cascading Style Sheet)
[ { "code": null, "e": 28, "s": 0, "text": "\n27 Sep, 2021" }, { "code": null, "e": 573, "s": 28, "text": "The spinning of text on mouse hover is known as the Spin Effect or the Rotation Effect. In this effect, each alphabet of the word is rotated along with any one of the axes (preferably Y-axis). Each word is wrapped inside in <li> tag and then using CSS:hover Selector selector we will rotate each alphabet on Y-axis. We will divide this article into two sections, in the first section we will create the basic structure of the text that will spin. IN the second section we will make that text structure spinnable when the user the hover on that." }, { "code": null, "e": 654, "s": 573, "text": "Creating Structure: In this section we will create the structure by using HTML. " }, { "code": null, "e": 756, "s": 654, "text": "HTML Code: In this we have created an unordered-list and wrap each alphabet inside an list-item(li). " }, { "code": null, "e": 761, "s": 756, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\" /> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" /> <title>Spin Text</title> </head> <body> <ul> <li>G</li> <li>e</li> <li>e</li> <li>k</li> <li>s</li> <li>f</li> <li>o</li> <li>r</li> <li>G</li> <li>e</li> <li>e</li> <li>k</li> <li>s</li> </ul> </body></html>", "e": 1310, "s": 761, "text": null }, { "code": null, "e": 1424, "s": 1310, "text": "Designing Structure: In this section we will make that structure spinnable and add the little bit of decoration. " }, { "code": null, "e": 1891, "s": 1424, "text": "CSS Code: First we have provide some basic styling like margin, padding and background. Then we have aligned our list-items horizontally using the float property. Finally, use the hover selector to rotate each alphabet along Y-axis on a particular degree. If you want you can use n-th child property to apply some delay to rotation of each alphabet.The use of n-th child comes to personal preferences and needs so if you feel like using it you can surely go for it. " }, { "code": null, "e": 1895, "s": 1891, "text": "CSS" }, { "code": "<style> body { margin: 0; padding: 0; } ul { padding: 50px; margin: 0; position: absolute; top: 20%; left: 25%; } ul li { list-style: none; color: green; float: left; font-size: 40px; transition: 0.8s; } ul:hover li { transform: rotateY(360deg); }</style>", "e": 2436, "s": 1895, "text": null }, { "code": null, "e": 2499, "s": 2436, "text": "Final Solution: It is the combination of the above two codes. " }, { "code": null, "e": 2504, "s": 2499, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\" /> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" /> <title>Spin Text</title> <style> body { margin: 0; padding: 0; } ul { padding: 50px; margin: 0; position: absolute; top: 20%; left: 25%; } ul li { list-style: none; color: green; float: left; font-size: 40px; transition: 0.8s; } ul:hover li { transform: rotateY(360deg); } </style> </head> <body> <ul> <li>G</li> <li>e</li> <li>e</li> <li>k</li> <li>s</li> <li>f</li> <li>o</li> <li>r</li> <li>G</li> <li>e</li> <li>e</li> <li>k</li> <li>s</li> </ul> </body></html>", "e": 3609, "s": 2504, "text": null }, { "code": null, "e": 3618, "s": 3609, "text": "Output: " }, { "code": null, "e": 3637, "s": 3620, "text": "arorakashish0911" }, { "code": null, "e": 3646, "s": 3637, "text": "CSS-Misc" }, { "code": null, "e": 3656, "s": 3646, "text": "HTML-Misc" }, { "code": null, "e": 3660, "s": 3656, "text": "CSS" }, { "code": null, "e": 3665, "s": 3660, "text": "HTML" }, { "code": null, "e": 3682, "s": 3665, "text": "Web Technologies" }, { "code": null, "e": 3709, "s": 3682, "text": "Web technologies Questions" }, { "code": null, "e": 3714, "s": 3709, "text": "HTML" }, { "code": null, "e": 3812, "s": 3714, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3849, "s": 3812, "text": "Types of CSS (Cascading Style Sheet)" }, { "code": null, "e": 3888, "s": 3849, "text": "Design a Tribute Page using HTML & CSS" }, { "code": null, "e": 3927, "s": 3888, "text": "How to set space between the flexbox ?" }, { "code": null, "e": 3991, "s": 3927, "text": "How to position a div at the bottom of its container using CSS?" }, { "code": null, "e": 4052, "s": 3991, "text": "How to Upload Image into Database and Display it using PHP ?" }, { "code": null, "e": 4076, "s": 4052, "text": "REST API (Introduction)" }, { "code": null, "e": 4129, "s": 4076, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 4189, "s": 4129, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 4250, "s": 4189, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" } ]
Zero Initialization in C++
10 Feb, 2022 Setting the initial value of an object to zero is called the zero initialization.Syntax: static T object; Tt = {} ; T {} ; char array [n] = " "; Zero initialization is performed in the following situations:- Zero is initialized for every named variable with static or thread-local storage duration that is not subject to constant initialization (since C++14), before any other initialization.Zero is initialized as part of value-initialization sequence for non-class types and for members of value-initialized class types that have no constructors.When a character array is initialized with a string literal which is very short, the remainder of the array is zero-initialized. Zero is initialized for every named variable with static or thread-local storage duration that is not subject to constant initialization (since C++14), before any other initialization. Zero is initialized as part of value-initialization sequence for non-class types and for members of value-initialized class types that have no constructors. When a character array is initialized with a string literal which is very short, the remainder of the array is zero-initialized. The effects of zero-initialization are: If T is a scalar type, the object is initialized to the value obtained by converting the integer literal 0 to T. If T is a non-union class type, each non-static data member and each base-class subobject is zero-initialized and padding is initialized to zero bits. If T is a union type, the object’s first non-static named data member is zero-initialized and padding is initialized to zero bits. If T is an array type, each array element is zero-initialized. If T is a reference type, no initialization is performed. Key Points: The static and thread-local variables are first zero-initialized and then initialized again as specified in the program, e.g. in the starting of a program, function-local static is first zero-initialized, and then its constructor is called when the function is first entered. If there is no initializer for the declaration of a non-class static, then default initialization does nothing, leaving the result of the earlier zero-initialization unmodified. A pointer which is zero-initialized is called a null pointer, even if the value of the null pointer is not integral zero. Below program illustrate zero initialization in C++: CPP // C++ code to demonstrate zero initialization #include <iostream>#include <string> struct foo { int x, y, z;}; double f[3]; // zero-initialized to three 0.0's int* p; // zero-initialized to null pointer value // zero-initialized to indeterminate value// then default-initialized to ""std::string s; int main(int argc, char* argv[]){ foo x = foo(); std::cout << x.x << x.y << x.z << '\n'; return 0;} 000 Reference: https://en.cppreference.com/w/cpp/language/zero_initialization gabaa406 chhabradhanvi cpp-data-types Picked Technical Scripter 2018 C++ Technical Scripter CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Sorting a vector in C++ Polymorphism in C++ Friend class and function in C++ std::string class in C++ Pair in C++ Standard Template Library (STL) Queue in C++ Standard Template Library (STL) Unordered Sets in C++ Standard Template Library List in C++ Standard Template Library (STL) std::find in C++ Inline Functions in C++
[ { "code": null, "e": 54, "s": 26, "text": "\n10 Feb, 2022" }, { "code": null, "e": 145, "s": 54, "text": "Setting the initial value of an object to zero is called the zero initialization.Syntax: " }, { "code": null, "e": 204, "s": 145, "text": "static T object;\n\nTt = {} ;\n\nT {} ;\n\nchar array [n] = \" \";" }, { "code": null, "e": 268, "s": 204, "text": "Zero initialization is performed in the following situations:- " }, { "code": null, "e": 737, "s": 268, "text": "Zero is initialized for every named variable with static or thread-local storage duration that is not subject to constant initialization (since C++14), before any other initialization.Zero is initialized as part of value-initialization sequence for non-class types and for members of value-initialized class types that have no constructors.When a character array is initialized with a string literal which is very short, the remainder of the array is zero-initialized." }, { "code": null, "e": 922, "s": 737, "text": "Zero is initialized for every named variable with static or thread-local storage duration that is not subject to constant initialization (since C++14), before any other initialization." }, { "code": null, "e": 1079, "s": 922, "text": "Zero is initialized as part of value-initialization sequence for non-class types and for members of value-initialized class types that have no constructors." }, { "code": null, "e": 1208, "s": 1079, "text": "When a character array is initialized with a string literal which is very short, the remainder of the array is zero-initialized." }, { "code": null, "e": 1250, "s": 1208, "text": "The effects of zero-initialization are: " }, { "code": null, "e": 1363, "s": 1250, "text": "If T is a scalar type, the object is initialized to the value obtained by converting the integer literal 0 to T." }, { "code": null, "e": 1514, "s": 1363, "text": "If T is a non-union class type, each non-static data member and each base-class subobject is zero-initialized and padding is initialized to zero bits." }, { "code": null, "e": 1645, "s": 1514, "text": "If T is a union type, the object’s first non-static named data member is zero-initialized and padding is initialized to zero bits." }, { "code": null, "e": 1708, "s": 1645, "text": "If T is an array type, each array element is zero-initialized." }, { "code": null, "e": 1766, "s": 1708, "text": "If T is a reference type, no initialization is performed." }, { "code": null, "e": 1780, "s": 1766, "text": "Key Points: " }, { "code": null, "e": 2234, "s": 1780, "text": "The static and thread-local variables are first zero-initialized and then initialized again as specified in the program, e.g. in the starting of a program, function-local static is first zero-initialized, and then its constructor is called when the function is first entered. If there is no initializer for the declaration of a non-class static, then default initialization does nothing, leaving the result of the earlier zero-initialization unmodified." }, { "code": null, "e": 2356, "s": 2234, "text": "A pointer which is zero-initialized is called a null pointer, even if the value of the null pointer is not integral zero." }, { "code": null, "e": 2411, "s": 2356, "text": "Below program illustrate zero initialization in C++: " }, { "code": null, "e": 2415, "s": 2411, "text": "CPP" }, { "code": "// C++ code to demonstrate zero initialization #include <iostream>#include <string> struct foo { int x, y, z;}; double f[3]; // zero-initialized to three 0.0's int* p; // zero-initialized to null pointer value // zero-initialized to indeterminate value// then default-initialized to \"\"std::string s; int main(int argc, char* argv[]){ foo x = foo(); std::cout << x.x << x.y << x.z << '\\n'; return 0;}", "e": 2837, "s": 2415, "text": null }, { "code": null, "e": 2841, "s": 2837, "text": "000" }, { "code": null, "e": 2918, "s": 2843, "text": "Reference: https://en.cppreference.com/w/cpp/language/zero_initialization " }, { "code": null, "e": 2927, "s": 2918, "text": "gabaa406" }, { "code": null, "e": 2941, "s": 2927, "text": "chhabradhanvi" }, { "code": null, "e": 2956, "s": 2941, "text": "cpp-data-types" }, { "code": null, "e": 2963, "s": 2956, "text": "Picked" }, { "code": null, "e": 2987, "s": 2963, "text": "Technical Scripter 2018" }, { "code": null, "e": 2991, "s": 2987, "text": "C++" }, { "code": null, "e": 3010, "s": 2991, "text": "Technical Scripter" }, { "code": null, "e": 3014, "s": 3010, "text": "CPP" }, { "code": null, "e": 3112, "s": 3014, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3136, "s": 3112, "text": "Sorting a vector in C++" }, { "code": null, "e": 3156, "s": 3136, "text": "Polymorphism in C++" }, { "code": null, "e": 3189, "s": 3156, "text": "Friend class and function in C++" }, { "code": null, "e": 3214, "s": 3189, "text": "std::string class in C++" }, { "code": null, "e": 3258, "s": 3214, "text": "Pair in C++ Standard Template Library (STL)" }, { "code": null, "e": 3303, "s": 3258, "text": "Queue in C++ Standard Template Library (STL)" }, { "code": null, "e": 3351, "s": 3303, "text": "Unordered Sets in C++ Standard Template Library" }, { "code": null, "e": 3395, "s": 3351, "text": "List in C++ Standard Template Library (STL)" }, { "code": null, "e": 3412, "s": 3395, "text": "std::find in C++" } ]
Read Lines from a File in R Programming - readLines() Function - GeeksforGeeks
01 Jul, 2020 readLines() function in R Language reads text lines from an input file. The readLines() function is perfect for text files since it reads the text line by line and creates character objects for each of the lines. Syntax: readLines(path) Parameter:path: path of the file Example 1: # R program to illustrate# readLines() function # Store currently used directorypath <- getwd() # Write example text to currently used directorywrite.table(x = "the first line\nthe second line\nthe third line", file = paste(path, "/my_txt.txt", sep = ""), row.names = FALSE, col.names = FALSE, quote = FALSE) # Apply readLines function to txt filemy_txt <- readLines(paste(path, "/my_txt.txt", sep = ""))my_txt Output: [1] "the first line" "the second line" "the third line" Example 2: # R program to illustrate# readLines() function # Store currently used directorypath <- getwd() # Write example text to currently used directorywrite.table(x = "the first line\nthe second line\nthe third line", file = paste(path, "/my_txt.txt", sep = ""), row.names = FALSE, col.names = FALSE, quote = FALSE) # Apply readLines function to first two linesmy_txt_ex2 <- readLines(paste(path, "/my_txt.txt", sep = ""), n = 2)my_txt_ex2 Output: [1] "the first line" "the second line" R-FileHandling R-Functions R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Replace specific values in column in R DataFrame ? How to change Row Names of DataFrame in R ? Filter data by multiple conditions in R using Dplyr Change Color of Bars in Barchart using ggplot2 in R Loops in R (for, while, repeat) Printing Output of an R Program How to Change Axis Scales in R Plots? How to Split Column Into Multiple Columns in R DataFrame? Group by function in R using Dplyr K-Means Clustering in R Programming
[ { "code": null, "e": 24419, "s": 24391, "text": "\n01 Jul, 2020" }, { "code": null, "e": 24632, "s": 24419, "text": "readLines() function in R Language reads text lines from an input file. The readLines() function is perfect for text files since it reads the text line by line and creates character objects for each of the lines." }, { "code": null, "e": 24656, "s": 24632, "text": "Syntax: readLines(path)" }, { "code": null, "e": 24689, "s": 24656, "text": "Parameter:path: path of the file" }, { "code": null, "e": 24700, "s": 24689, "text": "Example 1:" }, { "code": "# R program to illustrate# readLines() function # Store currently used directorypath <- getwd() # Write example text to currently used directorywrite.table(x = \"the first line\\nthe second line\\nthe third line\", file = paste(path, \"/my_txt.txt\", sep = \"\"), row.names = FALSE, col.names = FALSE, quote = FALSE) # Apply readLines function to txt filemy_txt <- readLines(paste(path, \"/my_txt.txt\", sep = \"\"))my_txt", "e": 25136, "s": 24700, "text": null }, { "code": null, "e": 25144, "s": 25136, "text": "Output:" }, { "code": null, "e": 25201, "s": 25144, "text": "[1] \"the first line\" \"the second line\" \"the third line\"" }, { "code": null, "e": 25212, "s": 25201, "text": "Example 2:" }, { "code": "# R program to illustrate# readLines() function # Store currently used directorypath <- getwd() # Write example text to currently used directorywrite.table(x = \"the first line\\nthe second line\\nthe third line\", file = paste(path, \"/my_txt.txt\", sep = \"\"), row.names = FALSE, col.names = FALSE, quote = FALSE) # Apply readLines function to first two linesmy_txt_ex2 <- readLines(paste(path, \"/my_txt.txt\", sep = \"\"), n = 2)my_txt_ex2", "e": 25693, "s": 25212, "text": null }, { "code": null, "e": 25701, "s": 25693, "text": "Output:" }, { "code": null, "e": 25741, "s": 25701, "text": "[1] \"the first line\" \"the second line\"" }, { "code": null, "e": 25756, "s": 25741, "text": "R-FileHandling" }, { "code": null, "e": 25768, "s": 25756, "text": "R-Functions" }, { "code": null, "e": 25779, "s": 25768, "text": "R Language" }, { "code": null, "e": 25877, "s": 25779, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25886, "s": 25877, "text": "Comments" }, { "code": null, "e": 25899, "s": 25886, "text": "Old Comments" }, { "code": null, "e": 25957, "s": 25899, "text": "How to Replace specific values in column in R DataFrame ?" }, { "code": null, "e": 26001, "s": 25957, "text": "How to change Row Names of DataFrame in R ?" }, { "code": null, "e": 26053, "s": 26001, "text": "Filter data by multiple conditions in R using Dplyr" }, { "code": null, "e": 26105, "s": 26053, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 26137, "s": 26105, "text": "Loops in R (for, while, repeat)" }, { "code": null, "e": 26169, "s": 26137, "text": "Printing Output of an R Program" }, { "code": null, "e": 26207, "s": 26169, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 26265, "s": 26207, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 26300, "s": 26265, "text": "Group by function in R using Dplyr" } ]
How to create a file upload button with HTML?
To how to create a file upload button with HTML, the code is as follows − Live Demo <!DOCTYPE html> <html> <head> <h1>File upload button example</h1> <p>Click on the "Choose File" button to upload a file:</p> <form> <input type="file" id="FILE" name="filename"> </form> </body> </html> The above code will produce the following output − On clicking the “Choose file” button −
[ { "code": null, "e": 1136, "s": 1062, "text": "To how to create a file upload button with HTML, the code is as follows −" }, { "code": null, "e": 1147, "s": 1136, "text": " Live Demo" }, { "code": null, "e": 1349, "s": 1147, "text": "<!DOCTYPE html>\n<html>\n<head>\n<h1>File upload button example</h1>\n<p>Click on the \"Choose File\" button to upload a file:</p>\n<form>\n<input type=\"file\" id=\"FILE\" name=\"filename\">\n</form>\n</body>\n</html>" }, { "code": null, "e": 1400, "s": 1349, "text": "The above code will produce the following output −" }, { "code": null, "e": 1439, "s": 1400, "text": "On clicking the “Choose file” button −" } ]
Automate and Supercharge Google Colab with JavaScript | by M Khorasani | Towards Data Science
Cloud computing is quickly becoming the weapon of choice for data scientists and firms alike, for all the right reasons too. With the resources that you are afforded and the granularly small fees associated with them, it’s really just a matter of basic arithmetic to discern between cloud and local computing. Over the years platforms the likes of Amazon Web Services, Microsoft Azure, Google Cloud Platform and others have competed to offer the most sophisticated, cutting-edge and yet most affordable services to their customers. Ironically Google as one of the pioneers of the tech industry, was somewhat late to the game and they are still making up for lost time. But with the induction of Google Colab several years ago, they have offered the world at large, a service that is simply unmatched for what you’re not paying for it. A quick look at the nearest products in terms of resource allocation, reveals that for every hour of using Colab you are saving an average of 16.3 cents. In fact the actual virtual machine that is provisioned for each Colab session would set you back $0.16 an hour itself, if you were to provision it yourself. The following table displays the most comparable virtual machines to Colab with their respective specifications and prices offered by Amazon Web Services, Microsoft Azure and Google Cloud Platform. In other words Colab is a lot of bang for no buck. Not to mention that Colab provides you with access to a GPU and TPU as well, which means that you are actually saving more than 16 cents an hour. And the best part about it is that literally anyone, anywhere in the world can access it on demand. Mind you that such goodness does come with limitations too. You are allowed to run sessions up to 12 hours maximum with an idle timeout of around half an hour. In addition, you may face programmatic bottlenecking if you are found to be overutilizing some of Colab’s resources such as it’s GPU and TPU. Even still, such restrictions are beyond lenient. Yet for good measure you are encouraged to use resources efficiently and without excess to avoid any service interruptions. There is a multitude of reasons as to why one would want to automate Colab: To run your Python scripts with time gaps to avoid overutilizing the available resources. Your script is a time critical program that needs to run at prescheduled times. Ensure that your program is closed upon completion or before a system timeout/shutdown. Regardless of the casus belli, you can indeed automate Colab by writing small snippets of JavaScript that will run on your browser’s console to interact and mimic button presses on the Colab interface in order to start and/or stop your session at certain times or with certain triggers. To insert and run the JavaScript snippets, please hit F12 on a browser of your choice to open the console. Then paste the JavaScript snippet into the command window and press enter. Subsequently the browser will run the code to automate Google Colab by simulating button clicks. To find the JavaScript paths of the buttons that need to be clicked on, please right click on the button and select ‘Inspect’ or alternatively use the ‘Select an element’ cursor in the browser console to find the associated paths as shown below. Please note that Google may dynamically change these paths. Scenario 1: Running/terminating session at a prescheduled time For our first scenario, we will run our Python script immediately (or after a certain number of seconds if required) and then we will terminate the session after a specified number of seconds. For this we will implement the following steps: Activate Colab sessionRun script (at a prescheduled time)Terminate session (at a prescheduled time) Activate Colab session Run script (at a prescheduled time) Terminate session (at a prescheduled time) The video below shows the JavaScript code automating Google Colab. Please find below the JavaScript code for this scenario: Scenario 2: Running/terminating sessions iteratively For our second scenario, we will run our Python script iteratively for as many iterations as required using the following steps: Activate Colab sessionRun script if number of iterations is less than specified numberTerminate session Activate Colab session Run script if number of iterations is less than specified number Terminate session Please find below the JavaScript code for this scenario: Scenario 3: Running/terminating session dynamically For our final scenario, we will run our Python script dynamically until it prompts us to terminate it. This is useful for scripts that have a dynamic or unknown runtime. The following steps will be implemented for this use case: Activate Colab sessionRun script until execution is finishedSend a message to the console log to trigger terminationTerminate session Activate Colab session Run script until execution is finished Send a message to the console log to trigger termination Terminate session To prompt our JavaScript program to terminate the session, we will append a line to the end of our Python script that will create an error. For instance we can attempt to divide by 0 which will prompt Colab to display an error message that will also be logged in the browser’s console. We can then use the same JavaScript program to continuously check to see if the length of the log exceeds 0, and as soon as it does it will terminate the session. Please find below the JavaScript code for this scenario: Google Colab connects seamlessly to Google Drive and this enables us to save the results of our execution persistently to our own drive. In addition, you can further automate your program by having your Python script read from a csv file in your Google Drive that can guide it to execute certain actions. For instance each time you run your script, it will initially check the first line in a Google Drive spreadsheet that tells it which column in a dataframe to manipulate, once the execution is complete the Python script deletes the first row and resaves the spreadsheet so that the next time it runs it will move on to the next column in your dataframe. Use the following code to access the ‘guide’ file from your Google Drive. guide = pd.read_csv('drive/MyDrive/ColabNotebooks/guide.csv')column_to_manipulate = guide.iloc[0][0] Once your execution is complete, simply omit the first row and resave the file to your Google Drive: guide = guide.iloc[1:]guide.to_csv('drive/MyDrive/ColabNotebooks/guide.csv',index=False) Google Colab and cloud computing in general offers unparalleled access to extensive computing resources that until recently was inaccessible to many. Such capabilities coupled with some automation using JavaScript can create endless opportunities while utilizing resources in a more efficient manner. Specifically in the case of Colab such an excellent product is best used without any excess to enable everyone in the community to benefit from such a bundle of goodness equally.
[ { "code": null, "e": 1007, "s": 172, "text": "Cloud computing is quickly becoming the weapon of choice for data scientists and firms alike, for all the right reasons too. With the resources that you are afforded and the granularly small fees associated with them, it’s really just a matter of basic arithmetic to discern between cloud and local computing. Over the years platforms the likes of Amazon Web Services, Microsoft Azure, Google Cloud Platform and others have competed to offer the most sophisticated, cutting-edge and yet most affordable services to their customers. Ironically Google as one of the pioneers of the tech industry, was somewhat late to the game and they are still making up for lost time. But with the induction of Google Colab several years ago, they have offered the world at large, a service that is simply unmatched for what you’re not paying for it." }, { "code": null, "e": 1516, "s": 1007, "text": "A quick look at the nearest products in terms of resource allocation, reveals that for every hour of using Colab you are saving an average of 16.3 cents. In fact the actual virtual machine that is provisioned for each Colab session would set you back $0.16 an hour itself, if you were to provision it yourself. The following table displays the most comparable virtual machines to Colab with their respective specifications and prices offered by Amazon Web Services, Microsoft Azure and Google Cloud Platform." }, { "code": null, "e": 2289, "s": 1516, "text": "In other words Colab is a lot of bang for no buck. Not to mention that Colab provides you with access to a GPU and TPU as well, which means that you are actually saving more than 16 cents an hour. And the best part about it is that literally anyone, anywhere in the world can access it on demand. Mind you that such goodness does come with limitations too. You are allowed to run sessions up to 12 hours maximum with an idle timeout of around half an hour. In addition, you may face programmatic bottlenecking if you are found to be overutilizing some of Colab’s resources such as it’s GPU and TPU. Even still, such restrictions are beyond lenient. Yet for good measure you are encouraged to use resources efficiently and without excess to avoid any service interruptions." }, { "code": null, "e": 2365, "s": 2289, "text": "There is a multitude of reasons as to why one would want to automate Colab:" }, { "code": null, "e": 2455, "s": 2365, "text": "To run your Python scripts with time gaps to avoid overutilizing the available resources." }, { "code": null, "e": 2535, "s": 2455, "text": "Your script is a time critical program that needs to run at prescheduled times." }, { "code": null, "e": 2623, "s": 2535, "text": "Ensure that your program is closed upon completion or before a system timeout/shutdown." }, { "code": null, "e": 2910, "s": 2623, "text": "Regardless of the casus belli, you can indeed automate Colab by writing small snippets of JavaScript that will run on your browser’s console to interact and mimic button presses on the Colab interface in order to start and/or stop your session at certain times or with certain triggers." }, { "code": null, "e": 3495, "s": 2910, "text": "To insert and run the JavaScript snippets, please hit F12 on a browser of your choice to open the console. Then paste the JavaScript snippet into the command window and press enter. Subsequently the browser will run the code to automate Google Colab by simulating button clicks. To find the JavaScript paths of the buttons that need to be clicked on, please right click on the button and select ‘Inspect’ or alternatively use the ‘Select an element’ cursor in the browser console to find the associated paths as shown below. Please note that Google may dynamically change these paths." }, { "code": null, "e": 3558, "s": 3495, "text": "Scenario 1: Running/terminating session at a prescheduled time" }, { "code": null, "e": 3799, "s": 3558, "text": "For our first scenario, we will run our Python script immediately (or after a certain number of seconds if required) and then we will terminate the session after a specified number of seconds. For this we will implement the following steps:" }, { "code": null, "e": 3899, "s": 3799, "text": "Activate Colab sessionRun script (at a prescheduled time)Terminate session (at a prescheduled time)" }, { "code": null, "e": 3922, "s": 3899, "text": "Activate Colab session" }, { "code": null, "e": 3958, "s": 3922, "text": "Run script (at a prescheduled time)" }, { "code": null, "e": 4001, "s": 3958, "text": "Terminate session (at a prescheduled time)" }, { "code": null, "e": 4068, "s": 4001, "text": "The video below shows the JavaScript code automating Google Colab." }, { "code": null, "e": 4125, "s": 4068, "text": "Please find below the JavaScript code for this scenario:" }, { "code": null, "e": 4178, "s": 4125, "text": "Scenario 2: Running/terminating sessions iteratively" }, { "code": null, "e": 4307, "s": 4178, "text": "For our second scenario, we will run our Python script iteratively for as many iterations as required using the following steps:" }, { "code": null, "e": 4411, "s": 4307, "text": "Activate Colab sessionRun script if number of iterations is less than specified numberTerminate session" }, { "code": null, "e": 4434, "s": 4411, "text": "Activate Colab session" }, { "code": null, "e": 4499, "s": 4434, "text": "Run script if number of iterations is less than specified number" }, { "code": null, "e": 4517, "s": 4499, "text": "Terminate session" }, { "code": null, "e": 4574, "s": 4517, "text": "Please find below the JavaScript code for this scenario:" }, { "code": null, "e": 4626, "s": 4574, "text": "Scenario 3: Running/terminating session dynamically" }, { "code": null, "e": 4855, "s": 4626, "text": "For our final scenario, we will run our Python script dynamically until it prompts us to terminate it. This is useful for scripts that have a dynamic or unknown runtime. The following steps will be implemented for this use case:" }, { "code": null, "e": 4989, "s": 4855, "text": "Activate Colab sessionRun script until execution is finishedSend a message to the console log to trigger terminationTerminate session" }, { "code": null, "e": 5012, "s": 4989, "text": "Activate Colab session" }, { "code": null, "e": 5051, "s": 5012, "text": "Run script until execution is finished" }, { "code": null, "e": 5108, "s": 5051, "text": "Send a message to the console log to trigger termination" }, { "code": null, "e": 5126, "s": 5108, "text": "Terminate session" }, { "code": null, "e": 5575, "s": 5126, "text": "To prompt our JavaScript program to terminate the session, we will append a line to the end of our Python script that will create an error. For instance we can attempt to divide by 0 which will prompt Colab to display an error message that will also be logged in the browser’s console. We can then use the same JavaScript program to continuously check to see if the length of the log exceeds 0, and as soon as it does it will terminate the session." }, { "code": null, "e": 5632, "s": 5575, "text": "Please find below the JavaScript code for this scenario:" }, { "code": null, "e": 6290, "s": 5632, "text": "Google Colab connects seamlessly to Google Drive and this enables us to save the results of our execution persistently to our own drive. In addition, you can further automate your program by having your Python script read from a csv file in your Google Drive that can guide it to execute certain actions. For instance each time you run your script, it will initially check the first line in a Google Drive spreadsheet that tells it which column in a dataframe to manipulate, once the execution is complete the Python script deletes the first row and resaves the spreadsheet so that the next time it runs it will move on to the next column in your dataframe." }, { "code": null, "e": 6364, "s": 6290, "text": "Use the following code to access the ‘guide’ file from your Google Drive." }, { "code": null, "e": 6465, "s": 6364, "text": "guide = pd.read_csv('drive/MyDrive/ColabNotebooks/guide.csv')column_to_manipulate = guide.iloc[0][0]" }, { "code": null, "e": 6566, "s": 6465, "text": "Once your execution is complete, simply omit the first row and resave the file to your Google Drive:" }, { "code": null, "e": 6655, "s": 6566, "text": "guide = guide.iloc[1:]guide.to_csv('drive/MyDrive/ColabNotebooks/guide.csv',index=False)" } ]
Print reverse of a string using recursion - GeeksforGeeks
19 Jul, 2021 Write a recursive function to print reverse of a given string. Program: C++ C Java Python C# PHP Javascript // C++ program to reverse a string using recursion#include <bits/stdc++.h>using namespace std; /* Function to print reverse of the passed string */void reverse(string str){ if(str.size() == 0) { return; } reverse(str.substr(1)); cout << str[0];} /* Driver program to test above function */int main(){ string a = "Geeks for Geeks"; reverse(a); return 0;} // This is code is contributed by rathbhupendra // C program to reverse a string using recursion# include <stdio.h> /* Function to print reverse of the passed string */void reverse(char *str){ if (*str) { reverse(str+1); printf("%c", *str); }} /* Driver program to test above function */int main(){ char a[] = "Geeks for Geeks"; reverse(a); return 0;} // Java program to reverse a string using recursion class StringReverse{ /* Function to print reverse of the passed string */ void reverse(String str) { if ((str==null)||(str.length() <= 1)) System.out.println(str); else { System.out.print(str.charAt(str.length()-1)); reverse(str.substring(0,str.length()-1)); } } /* Driver program to test above function */ public static void main(String[] args) { String str = "Geeks for Geeks"; StringReverse obj = new StringReverse(); obj.reverse(str); } } # Python program to reverse a string using recursion # Function to print reverse of the passed stringdef reverse(string): if len(string) == 0: return temp = string[0] reverse(string[1:]) print(temp, end='') # Driver program to test above functionstring = "Geeks for Geeks"reverse(string) # A single line statement to reverse string in python# string[::-1] # This code is contributed by Bhavya Jain // C# program to reverse// a string using recursionusing System; class GFG{ // Function to print reverse // of the passed string static void reverse(String str) { if ((str == null) || (str.Length <= 1)) Console.Write(str); else { Console.Write(str[str.Length-1]); reverse(str.Substring(0,(str.Length-1))); } } // Driver Code public static void Main() { String str = "Geeks for Geeks"; reverse(str); }} // This code is contributed by Sam007 <?php// PHP program to reverse// a string using recursion // Function to print reverse// of the passed stringfunction reverse($str){ if (($str == null) || (strlen($str) <= 1)) echo ($str); else { echo ($str[strlen($str) - 1]); reverse(substr($str, 0, (strlen($str) - 1))); }} // Driver Code$str = "Geeks for Geeks";reverse($str); // This code is contributed by// Manish Shaw(manishshaw1)?> <script> // JavaScript Program for the above approach /* Function to print reverse of the passed string */ function reverse(str, len) { if (len == str.length) { return; } reverse(str, len + 1); document.write(str[len]); } /* Driver program to test above function */ let a = "Geeks for Geeks"; reverse(a, 0); // This code is contributed by Potta Lokesh </script> Output: skeeG rof skeeG Explanation: Recursive function (reverse) takes string pointer (str) as input and calls itself with next location to passed pointer (str+1). Recursion continues this way when the pointer reaches ‘\0’, all functions accumulated in stack print char at passed location (str) and return one by one.Time Complexity: O(n^2) as substr() method has a time complexity of O(k) where k is the size of the returned string. So for every recursive call, we are reducing the size of the string by one, which leads to a series like (k-1)+(k-2)+...+1 = k*(k-1)/2 = O(k^2) = O(n^2)See Reverse a string for other methods to reverse string.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. manishshaw1 rajatdiptabiswas rathbhupendra sarthakb lokeshpotta20 Strings Strings Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Convert string to char array in C++ Caesar Cipher in Cryptography Array of Strings in C++ (5 Different Ways to Create) Reverse words in a given string Top 50 String Coding Problems for Interviews Length of the longest substring without repeating characters Check whether two strings are anagram of each other Reverse string in Python (5 different ways) Hill Cipher stringstream in C++ and its applications
[ { "code": null, "e": 24808, "s": 24780, "text": "\n19 Jul, 2021" }, { "code": null, "e": 24882, "s": 24808, "text": "Write a recursive function to print reverse of a given string. Program: " }, { "code": null, "e": 24886, "s": 24882, "text": "C++" }, { "code": null, "e": 24888, "s": 24886, "text": "C" }, { "code": null, "e": 24893, "s": 24888, "text": "Java" }, { "code": null, "e": 24900, "s": 24893, "text": "Python" }, { "code": null, "e": 24903, "s": 24900, "text": "C#" }, { "code": null, "e": 24907, "s": 24903, "text": "PHP" }, { "code": null, "e": 24918, "s": 24907, "text": "Javascript" }, { "code": "// C++ program to reverse a string using recursion#include <bits/stdc++.h>using namespace std; /* Function to print reverse of the passed string */void reverse(string str){ if(str.size() == 0) { return; } reverse(str.substr(1)); cout << str[0];} /* Driver program to test above function */int main(){ string a = \"Geeks for Geeks\"; reverse(a); return 0;} // This is code is contributed by rathbhupendra", "e": 25351, "s": 24918, "text": null }, { "code": "// C program to reverse a string using recursion# include <stdio.h> /* Function to print reverse of the passed string */void reverse(char *str){ if (*str) { reverse(str+1); printf(\"%c\", *str); }} /* Driver program to test above function */int main(){ char a[] = \"Geeks for Geeks\"; reverse(a); return 0;}", "e": 25679, "s": 25351, "text": null }, { "code": "// Java program to reverse a string using recursion class StringReverse{ /* Function to print reverse of the passed string */ void reverse(String str) { if ((str==null)||(str.length() <= 1)) System.out.println(str); else { System.out.print(str.charAt(str.length()-1)); reverse(str.substring(0,str.length()-1)); } } /* Driver program to test above function */ public static void main(String[] args) { String str = \"Geeks for Geeks\"; StringReverse obj = new StringReverse(); obj.reverse(str); } }", "e": 26286, "s": 25679, "text": null }, { "code": "# Python program to reverse a string using recursion # Function to print reverse of the passed stringdef reverse(string): if len(string) == 0: return temp = string[0] reverse(string[1:]) print(temp, end='') # Driver program to test above functionstring = \"Geeks for Geeks\"reverse(string) # A single line statement to reverse string in python# string[::-1] # This code is contributed by Bhavya Jain", "e": 26708, "s": 26286, "text": null }, { "code": "// C# program to reverse// a string using recursionusing System; class GFG{ // Function to print reverse // of the passed string static void reverse(String str) { if ((str == null) || (str.Length <= 1)) Console.Write(str); else { Console.Write(str[str.Length-1]); reverse(str.Substring(0,(str.Length-1))); } } // Driver Code public static void Main() { String str = \"Geeks for Geeks\"; reverse(str); }} // This code is contributed by Sam007", "e": 27256, "s": 26708, "text": null }, { "code": "<?php// PHP program to reverse// a string using recursion // Function to print reverse// of the passed stringfunction reverse($str){ if (($str == null) || (strlen($str) <= 1)) echo ($str); else { echo ($str[strlen($str) - 1]); reverse(substr($str, 0, (strlen($str) - 1))); }} // Driver Code$str = \"Geeks for Geeks\";reverse($str); // This code is contributed by// Manish Shaw(manishshaw1)?>", "e": 27697, "s": 27256, "text": null }, { "code": "<script> // JavaScript Program for the above approach /* Function to print reverse of the passed string */ function reverse(str, len) { if (len == str.length) { return; } reverse(str, len + 1); document.write(str[len]); } /* Driver program to test above function */ let a = \"Geeks for Geeks\"; reverse(a, 0); // This code is contributed by Potta Lokesh </script>", "e": 28181, "s": 27697, "text": null }, { "code": null, "e": 28191, "s": 28181, "text": "Output: " }, { "code": null, "e": 28207, "s": 28191, "text": "skeeG rof skeeG" }, { "code": null, "e": 28953, "s": 28207, "text": "Explanation: Recursive function (reverse) takes string pointer (str) as input and calls itself with next location to passed pointer (str+1). Recursion continues this way when the pointer reaches ‘\\0’, all functions accumulated in stack print char at passed location (str) and return one by one.Time Complexity: O(n^2) as substr() method has a time complexity of O(k) where k is the size of the returned string. So for every recursive call, we are reducing the size of the string by one, which leads to a series like (k-1)+(k-2)+...+1 = k*(k-1)/2 = O(k^2) = O(n^2)See Reverse a string for other methods to reverse string.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 28965, "s": 28953, "text": "manishshaw1" }, { "code": null, "e": 28982, "s": 28965, "text": "rajatdiptabiswas" }, { "code": null, "e": 28996, "s": 28982, "text": "rathbhupendra" }, { "code": null, "e": 29005, "s": 28996, "text": "sarthakb" }, { "code": null, "e": 29019, "s": 29005, "text": "lokeshpotta20" }, { "code": null, "e": 29027, "s": 29019, "text": "Strings" }, { "code": null, "e": 29035, "s": 29027, "text": "Strings" }, { "code": null, "e": 29133, "s": 29035, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29142, "s": 29133, "text": "Comments" }, { "code": null, "e": 29155, "s": 29142, "text": "Old Comments" }, { "code": null, "e": 29191, "s": 29155, "text": "Convert string to char array in C++" }, { "code": null, "e": 29221, "s": 29191, "text": "Caesar Cipher in Cryptography" }, { "code": null, "e": 29274, "s": 29221, "text": "Array of Strings in C++ (5 Different Ways to Create)" }, { "code": null, "e": 29306, "s": 29274, "text": "Reverse words in a given string" }, { "code": null, "e": 29351, "s": 29306, "text": "Top 50 String Coding Problems for Interviews" }, { "code": null, "e": 29412, "s": 29351, "text": "Length of the longest substring without repeating characters" }, { "code": null, "e": 29464, "s": 29412, "text": "Check whether two strings are anagram of each other" }, { "code": null, "e": 29508, "s": 29464, "text": "Reverse string in Python (5 different ways)" }, { "code": null, "e": 29520, "s": 29508, "text": "Hill Cipher" } ]
How to resolve "Could not find or load main class package" in Java?
Once you write a Java program you need to compile it using the javac command, this shows you the compile time errors occurred (if any). Once you resolve them and compile your program success fully, an executable file with the same name as your class name is generated in your current folder, with the .class extension. Then you need to execute it using the java command as − java class_name While executing, when JVM does not find a .class file with the specified name then a run time error occurs saying “Could not found or load main class” error as − D:\sample>java Example Error: Could not find or load main class Example Caused by: java.lang.ClassNotFoundException: Example To avoid this error, you need to specify the absolute (including packages) name of the .class file (just name) which is in the current directory. Following are the scenarios where this error could occur − Wrong class name − You might have specified the wrong class name. class Example { public static void main(String args[]){ System.out.println("This is an example class"); } } D:\>javac Example.java D:\>java Exmple Error: Could not find or load main class Exmple Caused by: java.lang.ClassNotFoundException: Exmple Solution − In this the class name is wrongly spelt, we need to correct it. D:\>javac Example.java D:\>java Example This is an example class Wrong case − You need to specify the name of the class with same case Example.java is different from example.java. class Example { public static void main(String args[]){ System.out.println("This is an example class"); } } D:\>java EXAMPLE Error: Could not find or load main class EXAMPLE Caused by: java.lang.NoClassDefFoundError: Example (wrong name: EXAMPLE) Solution − In this the class name is with wrong case it, it should be decorated. D:\>javac Example.java D:\>java Example This is an example class Wrong package − You might have created the .class file in a package and tried to execute without package name or with wrong package name. package sample; class Example { public static void main(String args[]){ System.out.println("This is an example class"); } } D:\>javac -d . Example.java D:\>java samp.Example Error: Could not find or load main class samp.Example Caused by: java.lang.ClassNotFoundException: samp.Example Solution − In this scenario we have mention the name of the wrong package While executing we need to specify the correct package name in which the .class file exists as − D:\>javac -d . Example.java D:\>java sample.Example This is an example class Inclusion of .class extension − While executing a file there is no need to include the .class extension in your program you just need to specify the name of the class file. D:\sample>java Example.class Error: Could not find or load main class Example.class Caused by: java.lang.ClassNotFoundException: Example.class Solution − The extension .class is not required while executing the program. D:\sample>java Example This is an example class
[ { "code": null, "e": 1198, "s": 1062, "text": "Once you write a Java program you need to compile it using the javac command, this shows you the compile time errors occurred (if any)." }, { "code": null, "e": 1381, "s": 1198, "text": "Once you resolve them and compile your program success fully, an executable file with the same name as your class name is generated in your current folder, with the .class extension." }, { "code": null, "e": 1437, "s": 1381, "text": "Then you need to execute it using the java command as −" }, { "code": null, "e": 1453, "s": 1437, "text": "java class_name" }, { "code": null, "e": 1615, "s": 1453, "text": "While executing, when JVM does not find a .class file with the specified name then a run time error occurs saying “Could not found or load main class” error as −" }, { "code": null, "e": 1740, "s": 1615, "text": "D:\\sample>java Example\nError: Could not find or load main class Example\nCaused by: java.lang.ClassNotFoundException: Example" }, { "code": null, "e": 1886, "s": 1740, "text": "To avoid this error, you need to specify the absolute (including packages) name of the .class file (just name) which is in the current directory." }, { "code": null, "e": 1945, "s": 1886, "text": "Following are the scenarios where this error could occur −" }, { "code": null, "e": 2011, "s": 1945, "text": "Wrong class name − You might have specified the wrong class name." }, { "code": null, "e": 2131, "s": 2011, "text": "class Example {\n public static void main(String args[]){\n System.out.println(\"This is an example class\");\n }\n}" }, { "code": null, "e": 2270, "s": 2131, "text": "D:\\>javac Example.java\nD:\\>java Exmple\nError: Could not find or load main class Exmple\nCaused by: java.lang.ClassNotFoundException: Exmple" }, { "code": null, "e": 2345, "s": 2270, "text": "Solution − In this the class name is wrongly spelt, we need to correct it." }, { "code": null, "e": 2410, "s": 2345, "text": "D:\\>javac Example.java\nD:\\>java Example\nThis is an example class" }, { "code": null, "e": 2525, "s": 2410, "text": "Wrong case − You need to specify the name of the class with same case Example.java is different from example.java." }, { "code": null, "e": 2645, "s": 2525, "text": "class Example {\n public static void main(String args[]){\n System.out.println(\"This is an example class\");\n }\n}" }, { "code": null, "e": 2784, "s": 2645, "text": "D:\\>java EXAMPLE\nError: Could not find or load main class EXAMPLE\nCaused by: java.lang.NoClassDefFoundError: Example (wrong name: EXAMPLE)" }, { "code": null, "e": 2865, "s": 2784, "text": "Solution − In this the class name is with wrong case it, it should be decorated." }, { "code": null, "e": 2930, "s": 2865, "text": "D:\\>javac Example.java\nD:\\>java Example\nThis is an example class" }, { "code": null, "e": 3068, "s": 2930, "text": "Wrong package − You might have created the .class file in a package and tried to execute without package name or with wrong package name." }, { "code": null, "e": 3204, "s": 3068, "text": "package sample;\nclass Example {\n public static void main(String args[]){\n System.out.println(\"This is an example class\");\n }\n}" }, { "code": null, "e": 3366, "s": 3204, "text": "D:\\>javac -d . Example.java\nD:\\>java samp.Example\nError: Could not find or load main class samp.Example\nCaused by: java.lang.ClassNotFoundException: samp.Example" }, { "code": null, "e": 3537, "s": 3366, "text": "Solution − In this scenario we have mention the name of the wrong package While executing we need to specify the correct package name in which the .class file exists as −" }, { "code": null, "e": 3614, "s": 3537, "text": "D:\\>javac -d . Example.java\nD:\\>java sample.Example\nThis is an example class" }, { "code": null, "e": 3787, "s": 3614, "text": "Inclusion of .class extension − While executing a file there is no need to include the .class extension in your program you just need to specify the name of the class file." }, { "code": null, "e": 3930, "s": 3787, "text": "D:\\sample>java Example.class\nError: Could not find or load main class Example.class\nCaused by: java.lang.ClassNotFoundException: Example.class" }, { "code": null, "e": 4007, "s": 3930, "text": "Solution − The extension .class is not required while executing the program." }, { "code": null, "e": 4055, "s": 4007, "text": "D:\\sample>java Example\nThis is an example class" } ]
How to display the date and time of a document when it is last modified in JavaScript?
A document in its lifetime will undergo many changes. Javascript has provided a command called document.lastModified to get the instance when the document is last modified. This command will provide the exact date and time of modification. Time = document.lastModified; In the following example, using the document.lastModified method the documents last modification date and time are displayed as shown in the output. Live Demo <html> <body> <script> document.write("This document is lastly modified on" + " " +document.lastModified); </script> </body> </html> This document is lastly modified on 07/29/2019 15:19:41 In the following example, using the document.lastModified method the documents last modification date and time are displayed as shown in the output. When I modified the document the date and time are 07/29/2019 15:26:23. Live Demo <html> <body> <p>This document was last modified <span id="modify"></span>.</p> <script> document.getElementById("modify").innerHTML = document.lastModified </script> </body> </html> This document was last modified 07/29/2019 15:26:23.
[ { "code": null, "e": 1304, "s": 1062, "text": "A document in its lifetime will undergo many changes. Javascript has provided a command called document.lastModified to get the instance when the document is last modified. This command will provide the exact date and time of modification. " }, { "code": null, "e": 1334, "s": 1304, "text": "Time = document.lastModified;" }, { "code": null, "e": 1483, "s": 1334, "text": "In the following example, using the document.lastModified method the documents last modification date and time are displayed as shown in the output." }, { "code": null, "e": 1493, "s": 1483, "text": "Live Demo" }, { "code": null, "e": 1626, "s": 1493, "text": "<html>\n<body>\n<script>\ndocument.write(\"This document is lastly modified on\" + \" \" +document.lastModified);\n</script>\n</body>\n</html>" }, { "code": null, "e": 1682, "s": 1626, "text": "This document is lastly modified on 07/29/2019 15:19:41" }, { "code": null, "e": 1903, "s": 1682, "text": "In the following example, using the document.lastModified method the documents last modification date and time are displayed as shown in the output. When I modified the document the date and time are 07/29/2019 15:26:23." }, { "code": null, "e": 1913, "s": 1903, "text": "Live Demo" }, { "code": null, "e": 2096, "s": 1913, "text": "<html>\n<body>\n<p>This document was last modified <span id=\"modify\"></span>.</p>\n<script>\ndocument.getElementById(\"modify\").innerHTML = document.lastModified\n</script>\n</body>\n</html>" }, { "code": null, "e": 2149, "s": 2096, "text": "This document was last modified 07/29/2019 15:26:23." } ]
Cleaning Missing Values in a Pandas Dataframe | by Andrei Teleron | Towards Data Science
Ways to visualize missing data and what to do with them using Python. When working on analyzing data, you’ll likely come across data that is missing (also called null values or NaNs). Data cleaning is an important part of the data analysis pipeline and making sure that it’s all tidy up will make your analysis much stronger. The only library you’ll need to import is pandas: import pandas as pd If you’re using the pandas library in Python and are constantly dealing with data that has missing values and need to get to your data analysis faster, then here’s a quick function that outputs a dataframe that tells you how many missing values and their percentages in each column: A little less readable version, but you can copy paste it in your code: def assess_NA(data): """ Returns a pandas dataframe denoting the total number of NA values and the percentage of NA values in each column. The column names are noted on the index. Parameters ---------- data: dataframe """ # pandas series denoting features and the sum of their null values null_sum = data.isnull().sum()# instantiate columns for missing data total = null_sum.sort_values(ascending=False) percent = ( ((null_sum / len(data.index))*100).round(2) ).sort_values(ascending=False) # concatenate along the columns to create the complete dataframe df_NA = pd.concat([total, percent], axis=1, keys=['Number of NA', 'Percent NA']) # drop rows that don't have any missing data; omit if you want to keep all rows df_NA = df_NA[ (df_NA.T != 0).any() ] return df_NA The only parameter you need to pass is a dataframe object. Here’s an example where we call the function assess_NA() on a dataframe with missing data called training , which then outputs the dataframe: df_NA . The rows represent the features of your dataframe and the columns provide information on your missing data. If there are no missing values, then it will just output an empty dataframe. Knowing this, you can be more informed on what to do with null values such as: Removing rows with themImpute using mean, median, 0, false, true, etc. Removing rows with them Impute using mean, median, 0, false, true, etc. This method is a simple, but messy way to handle missing values since in addition to removing these values, it can potentially remove data that aren’t null. You can call dropna() on your entire dataframe or on specific columns: # Drop rows with null valuesdf = df.dropna(axis=0)# Drop column_1 rows with null valuesdf['column_1'] = df['column_1'].dropna(axis=0) The axis parameter determines the dimension that the function will act on. axis=0 removes all rows that contain null values. axis=1 does nearly the same thing except it removes columns instead. Rather than dropping values with missing data, imputation looks to replace these values with another value — usually the mean or median of a specified column. There are benefits to using either. For example, if the column has a lot of outliers the median would probably be more useful since it is more resistant to them. This way, we are attempting to preserve aspects of the data. To do this, we can call the fillna() function on a dataframe column and specifying either mean() or median() as a parameter: # Impute with mean on column_1df['column_1'] = df['column_1'].fillna( df['column_1'].mean() )# Impute with median on column_1df['column_1'] = df['column_1'].fillna( df['column_1'].median() ) Besides mean and median, imputing missing data with 0 can also be a good idea in some cases: # Impute with value 0 on column_1df['column_1'] = df['column_1'].fillna(0) Knowing what path to take when handling missing data is largely dictated by domain-knowledge and what your intuition tells you about the data. This is gained step-by-step and by working with datasets that allow you to ask meaningful questions about them.
[ { "code": null, "e": 241, "s": 171, "text": "Ways to visualize missing data and what to do with them using Python." }, { "code": null, "e": 497, "s": 241, "text": "When working on analyzing data, you’ll likely come across data that is missing (also called null values or NaNs). Data cleaning is an important part of the data analysis pipeline and making sure that it’s all tidy up will make your analysis much stronger." }, { "code": null, "e": 547, "s": 497, "text": "The only library you’ll need to import is pandas:" }, { "code": null, "e": 567, "s": 547, "text": "import pandas as pd" }, { "code": null, "e": 850, "s": 567, "text": "If you’re using the pandas library in Python and are constantly dealing with data that has missing values and need to get to your data analysis faster, then here’s a quick function that outputs a dataframe that tells you how many missing values and their percentages in each column:" }, { "code": null, "e": 922, "s": 850, "text": "A little less readable version, but you can copy paste it in your code:" }, { "code": null, "e": 1754, "s": 922, "text": "def assess_NA(data): \"\"\" Returns a pandas dataframe denoting the total number of NA values and the percentage of NA values in each column. The column names are noted on the index. Parameters ---------- data: dataframe \"\"\" # pandas series denoting features and the sum of their null values null_sum = data.isnull().sum()# instantiate columns for missing data total = null_sum.sort_values(ascending=False) percent = ( ((null_sum / len(data.index))*100).round(2) ).sort_values(ascending=False) # concatenate along the columns to create the complete dataframe df_NA = pd.concat([total, percent], axis=1, keys=['Number of NA', 'Percent NA']) # drop rows that don't have any missing data; omit if you want to keep all rows df_NA = df_NA[ (df_NA.T != 0).any() ] return df_NA" }, { "code": null, "e": 1963, "s": 1754, "text": "The only parameter you need to pass is a dataframe object. Here’s an example where we call the function assess_NA() on a dataframe with missing data called training , which then outputs the dataframe: df_NA ." }, { "code": null, "e": 2148, "s": 1963, "text": "The rows represent the features of your dataframe and the columns provide information on your missing data. If there are no missing values, then it will just output an empty dataframe." }, { "code": null, "e": 2227, "s": 2148, "text": "Knowing this, you can be more informed on what to do with null values such as:" }, { "code": null, "e": 2298, "s": 2227, "text": "Removing rows with themImpute using mean, median, 0, false, true, etc." }, { "code": null, "e": 2322, "s": 2298, "text": "Removing rows with them" }, { "code": null, "e": 2370, "s": 2322, "text": "Impute using mean, median, 0, false, true, etc." }, { "code": null, "e": 2598, "s": 2370, "text": "This method is a simple, but messy way to handle missing values since in addition to removing these values, it can potentially remove data that aren’t null. You can call dropna() on your entire dataframe or on specific columns:" }, { "code": null, "e": 2732, "s": 2598, "text": "# Drop rows with null valuesdf = df.dropna(axis=0)# Drop column_1 rows with null valuesdf['column_1'] = df['column_1'].dropna(axis=0)" }, { "code": null, "e": 2926, "s": 2732, "text": "The axis parameter determines the dimension that the function will act on. axis=0 removes all rows that contain null values. axis=1 does nearly the same thing except it removes columns instead." }, { "code": null, "e": 3433, "s": 2926, "text": "Rather than dropping values with missing data, imputation looks to replace these values with another value — usually the mean or median of a specified column. There are benefits to using either. For example, if the column has a lot of outliers the median would probably be more useful since it is more resistant to them. This way, we are attempting to preserve aspects of the data. To do this, we can call the fillna() function on a dataframe column and specifying either mean() or median() as a parameter:" }, { "code": null, "e": 3624, "s": 3433, "text": "# Impute with mean on column_1df['column_1'] = df['column_1'].fillna( df['column_1'].mean() )# Impute with median on column_1df['column_1'] = df['column_1'].fillna( df['column_1'].median() )" }, { "code": null, "e": 3717, "s": 3624, "text": "Besides mean and median, imputing missing data with 0 can also be a good idea in some cases:" }, { "code": null, "e": 3792, "s": 3717, "text": "# Impute with value 0 on column_1df['column_1'] = df['column_1'].fillna(0)" } ]
How to save an Image in OpenCV using C++?
Here, we will understand how to save the OpenCV image to any location on your computer. OpenCV provides imwrite() function to save an image to a specified file. The file extension represents the image format. The actual format of the function is − imwrite("Destination/Name of the image with extension", Source Matrix) Here, "Destination" is where we want to save the image. In this program, we save the image as "Lakshmi.jpg". We can give any name to the image. The "Source Matrix" is the matrix where the image has been loaded. In this program, the image is loaded as "myImage" matrix. #include<iostream> #include<opencv2/highgui/highgui.hpp> using namespace cv; using namespace std; int main(int argc,const char** argv) { Mat myImage;//declaring a matrix named myImage// myImage = imread("lena.png");//loading the image named lena in the matrix// imwrite("lakshmi.jpg", myImage); waitKey(0);//wait till user press any key destroyWindow("MyWindow");//close the window and release allocate memory// cout << "Image is saved successfully....."; return 0; } Image is saved successfully...
[ { "code": null, "e": 1273, "s": 1062, "text": "Here, we will understand how to save the OpenCV image to any location on your computer. OpenCV provides imwrite() function to save an image to a specified file. The file extension represents the image format. " }, { "code": null, "e": 1312, "s": 1273, "text": "The actual format of the function is −" }, { "code": null, "e": 1383, "s": 1312, "text": "imwrite(\"Destination/Name of the image with extension\", Source Matrix)" }, { "code": null, "e": 1652, "s": 1383, "text": "Here, \"Destination\" is where we want to save the image. In this program, we save the image as \"Lakshmi.jpg\". We can give any name to the image. The \"Source Matrix\" is the matrix where the image has been loaded. In this program, the image is loaded as \"myImage\" matrix." }, { "code": null, "e": 2143, "s": 1652, "text": "#include<iostream>\n#include<opencv2/highgui/highgui.hpp>\nusing namespace cv;\nusing namespace std;\nint main(int argc,const char** argv) {\n Mat myImage;//declaring a matrix named myImage//\n myImage = imread(\"lena.png\");//loading the image named lena in the matrix//\n imwrite(\"lakshmi.jpg\", myImage); \n waitKey(0);//wait till user press any key\n destroyWindow(\"MyWindow\");//close the window and release allocate memory//\n cout << \"Image is saved successfully.....\";\n return 0;\n}" }, { "code": null, "e": 2174, "s": 2143, "text": "Image is saved successfully..." } ]
How to simulate discrete uniform random variable in R?
There is no function in base R to simulate discrete uniform random variable like we have for other random variables such as Normal, Poisson, Exponential etc. but we can simulate it using rdunif function of purrr package. The rdunif function has the following syntax − > rdunif(n, b , a) Here, n = Number of random values to return b = Maximum value of the distribution, it needs to be an integer because the distribution is discrete a = Minimum value of the distribution, it needs to be an integer because the distribution is discrete Let’s say you want to simulate 10 ages between 21 to 50. We can do this as follows − > library(purrr) > rdunif(10,b=50,a=21) [1] 38 33 28 36 48 32 47 27 29 24 Now suppose we want to simulate 10 ages and the maximum age is 100 then it can be done as shown below − > rdunif(10,100) [1] 2 80 50 50 82 68 45 72 81 25 We can also simulate discrete uniform distribution for negative integers as shown in the below example − > rdunif(10,10,-5) [1] 3 -1 -3 3 6 5 3 5 -5 9 We can also create a table of discrete uniform random variable. Let’s say we want to generate 20 random values between -3 and +3 then it can be done as shown below − > table(rdunif(20, 3, -3)) -3 -2 -1 0 1 3 2 4 4 3 3 4 https://www.tutorialspoint.com/what-is-the-use-of-tilde-operator-in-r
[ { "code": null, "e": 1283, "s": 1062, "text": "There is no function in base R to simulate discrete uniform random variable like we have for other random variables such as Normal, Poisson, Exponential etc. but we can simulate it using rdunif function of purrr package." }, { "code": null, "e": 1330, "s": 1283, "text": "The rdunif function has the following syntax −" }, { "code": null, "e": 1349, "s": 1330, "text": "> rdunif(n, b , a)" }, { "code": null, "e": 1355, "s": 1349, "text": "Here," }, { "code": null, "e": 1393, "s": 1355, "text": "n = Number of random values to return" }, { "code": null, "e": 1495, "s": 1393, "text": "b = Maximum value of the distribution, it needs to be an integer because the distribution is discrete" }, { "code": null, "e": 1597, "s": 1495, "text": "a = Minimum value of the distribution, it needs to be an integer because the distribution is discrete" }, { "code": null, "e": 1682, "s": 1597, "text": "Let’s say you want to simulate 10 ages between 21 to 50. We can do this as follows −" }, { "code": null, "e": 1756, "s": 1682, "text": "> library(purrr)\n> rdunif(10,b=50,a=21)\n[1] 38 33 28 36 48 32 47 27 29 24" }, { "code": null, "e": 1860, "s": 1756, "text": "Now suppose we want to simulate 10 ages and the maximum age is 100 then it can be done as shown below −" }, { "code": null, "e": 1910, "s": 1860, "text": "> rdunif(10,100)\n[1] 2 80 50 50 82 68 45 72 81 25" }, { "code": null, "e": 2015, "s": 1910, "text": "We can also simulate discrete uniform distribution for negative integers as shown in the below example −" }, { "code": null, "e": 2061, "s": 2015, "text": "> rdunif(10,10,-5)\n[1] 3 -1 -3 3 6 5 3 5 -5 9" }, { "code": null, "e": 2227, "s": 2061, "text": "We can also create a table of discrete uniform random variable. Let’s say we want to generate 20 random values between -3 and +3 then it can be done as shown below −" }, { "code": null, "e": 2282, "s": 2227, "text": "> table(rdunif(20, 3, -3))\n\n-3 -2 -1 0 1 3\n2 4 4 3 3 4" }, { "code": null, "e": 2352, "s": 2282, "text": "https://www.tutorialspoint.com/what-is-the-use-of-tilde-operator-in-r" } ]
DAX Math & Trigonometric - MOD function
Returns the remainder after a number is divided by a divisor. The result always has the same sign as the divisor. MOD (<number>, <divisor>) number The number for which you want to find the remainder after the division is performed. divisor The number by which you want to divide. A whole number. If the divisor is 0 (zero), MOD returns an error. = MOD (5,2) returns 1. = MOD (5, -2) returns -1. 53 Lectures 5.5 hours Abhay Gadiya 24 Lectures 2 hours Randy Minder 26 Lectures 4.5 hours Randy Minder Print Add Notes Bookmark this page
[ { "code": null, "e": 2115, "s": 2001, "text": "Returns the remainder after a number is divided by a divisor. The result always has the same sign as the divisor." }, { "code": null, "e": 2142, "s": 2115, "text": "MOD (<number>, <divisor>)\n" }, { "code": null, "e": 2149, "s": 2142, "text": "number" }, { "code": null, "e": 2234, "s": 2149, "text": "The number for which you want to find the remainder after the division is performed." }, { "code": null, "e": 2242, "s": 2234, "text": "divisor" }, { "code": null, "e": 2282, "s": 2242, "text": "The number by which you want to divide." }, { "code": null, "e": 2298, "s": 2282, "text": "A whole number." }, { "code": null, "e": 2348, "s": 2298, "text": "If the divisor is 0 (zero), MOD returns an error." }, { "code": null, "e": 2399, "s": 2348, "text": "= MOD (5,2) returns 1. \n= MOD (5, -2) returns -1. " }, { "code": null, "e": 2434, "s": 2399, "text": "\n 53 Lectures \n 5.5 hours \n" }, { "code": null, "e": 2448, "s": 2434, "text": " Abhay Gadiya" }, { "code": null, "e": 2481, "s": 2448, "text": "\n 24 Lectures \n 2 hours \n" }, { "code": null, "e": 2495, "s": 2481, "text": " Randy Minder" }, { "code": null, "e": 2530, "s": 2495, "text": "\n 26 Lectures \n 4.5 hours \n" }, { "code": null, "e": 2544, "s": 2530, "text": " Randy Minder" }, { "code": null, "e": 2551, "s": 2544, "text": " Print" }, { "code": null, "e": 2562, "s": 2551, "text": " Add Notes" } ]
Difference between ArrayList.clear() and ArrayList.removeAll() in java?
The ArrayList class in Java is a Resizable-array implementation of the List interface. It allows null values. The clear() method this class removes all the elements from the current List object. Live Demo import java.util.ArrayList; public class ClearExample { public static void main(String[] args){ //Instantiating an ArrayList object ArrayList<String> list = new ArrayList<String>(); list.add("JavaFX"); list.add("Java"); list.add("WebGL"); list.add("OpenCV"); list.add("Impala"); System.out.println("Contents of the Array List: \n"+list); //Removing the sub list list.clear(); System.out.println("Contents of the ArrayList object after invoking the clear() method: "+list); } } Contents of the Array List: [JavaFX, Java, WebGL, OpenCV, Impala] Contents of the ArrayList object after invoking the clear() method: [] Whereas, the removeAll() method of the ArrayList class accepts another collection object as a parameter and removes all the contents of it from the current ArrayList. Live Demo import java.util.ArrayList; public class ClearExample { public static void main(String[] args){ //Instantiating an ArrayList object ArrayList<String> list1 = new ArrayList<String>(); list1.add("JavaFX"); list1.add("Java"); list1.add("WebGL"); list1.add("OpenCV"); list1.add("OpenNLP"); list1.add("JOGL"); list1.add("Hadoop"); list1.add("HBase"); list1.add("Flume"); list1.add("Mahout"); list1.add("Impala"); System.out.println("Contents of the Array List1 : \n"+list1); ArrayList<String> list2 = new ArrayList<String>(); list2.add("JOGL"); list2.add("Hadoop"); list2.add("HBase"); list2.add("Flume"); list2.add("Mahout"); list2.add("Impala"); System.out.println("Contents of the Array List1 : \n"+list2); //Removing elements list1.removeAll(list2); System.out.println("Contents of the Array List after removal: \n"+list1); } } Contents of the Array List1 : [JavaFX, Java, WebGL, OpenCV, OpenNLP, JOGL, Hadoop, HBase, Flume, Mahout, Impala] Contents of the Array List1 : [JOGL, Hadoop, HBase, Flume, Mahout, Impala] Contents of the Array List after removal: [JavaFX, Java, WebGL, OpenCV, OpenNLP]
[ { "code": null, "e": 1172, "s": 1062, "text": "The ArrayList class in Java is a Resizable-array implementation of the List interface. It allows null values." }, { "code": null, "e": 1257, "s": 1172, "text": "The clear() method this class removes all the elements from the current List object." }, { "code": null, "e": 1268, "s": 1257, "text": " Live Demo" }, { "code": null, "e": 1817, "s": 1268, "text": "import java.util.ArrayList;\npublic class ClearExample {\n public static void main(String[] args){\n //Instantiating an ArrayList object\n ArrayList<String> list = new ArrayList<String>();\n list.add(\"JavaFX\");\n list.add(\"Java\");\n list.add(\"WebGL\");\n list.add(\"OpenCV\");\n list.add(\"Impala\");\n System.out.println(\"Contents of the Array List: \\n\"+list);\n //Removing the sub list\n list.clear();\n System.out.println(\"Contents of the ArrayList object after invoking the clear() method: \"+list);\n }\n}" }, { "code": null, "e": 1954, "s": 1817, "text": "Contents of the Array List:\n[JavaFX, Java, WebGL, OpenCV, Impala]\nContents of the ArrayList object after invoking the clear() method: []" }, { "code": null, "e": 2121, "s": 1954, "text": "Whereas, the removeAll() method of the ArrayList class accepts another collection object as a parameter and removes all the contents of it from the current ArrayList." }, { "code": null, "e": 2132, "s": 2121, "text": " Live Demo" }, { "code": null, "e": 3115, "s": 2132, "text": "import java.util.ArrayList;\npublic class ClearExample {\n public static void main(String[] args){\n //Instantiating an ArrayList object\n ArrayList<String> list1 = new ArrayList<String>();\n list1.add(\"JavaFX\");\n list1.add(\"Java\");\n list1.add(\"WebGL\");\n list1.add(\"OpenCV\");\n list1.add(\"OpenNLP\");\n list1.add(\"JOGL\");\n list1.add(\"Hadoop\");\n list1.add(\"HBase\");\n list1.add(\"Flume\");\n list1.add(\"Mahout\");\n list1.add(\"Impala\");\n System.out.println(\"Contents of the Array List1 : \\n\"+list1);\n ArrayList<String> list2 = new ArrayList<String>();\n list2.add(\"JOGL\");\n list2.add(\"Hadoop\");\n list2.add(\"HBase\");\n list2.add(\"Flume\");\n list2.add(\"Mahout\");\n list2.add(\"Impala\");\n System.out.println(\"Contents of the Array List1 : \\n\"+list2);\n //Removing elements\n list1.removeAll(list2);\n System.out.println(\"Contents of the Array List after removal: \\n\"+list1);\n }\n}" }, { "code": null, "e": 3384, "s": 3115, "text": "Contents of the Array List1 :\n[JavaFX, Java, WebGL, OpenCV, OpenNLP, JOGL, Hadoop, HBase, Flume, Mahout, Impala]\nContents of the Array List1 :\n[JOGL, Hadoop, HBase, Flume, Mahout, Impala]\nContents of the Array List after removal:\n[JavaFX, Java, WebGL, OpenCV, OpenNLP]" } ]
Time Functions in C#
The DateTime has methods and properties for Date and Time as well like how to get the number of hours or minutes of a day, etc. Let us only focus on the time functions − Refer MSDN (Microsoft Developer Network) for all the functions − Let us learn about a Time function i.e. AddMilliseconds(Double) to add the specified number of milliseconds to the value of this instance. Live Demo using System; public class Demo { public static void Main() { string dateFormat = "MM/dd/yyyy hh:mm:ss.fffffff"; DateTime dateCurrent = new DateTime(2018, 7, 23, 13, 0, 0); Console.WriteLine("Original date: {0} ({1:N0} ticks)\n", dateCurrent.ToString(dateFormat), dateCurrent.Ticks); DateTime dateNew = dateCurrent.AddMilliseconds(1); Console.WriteLine("Next date: {0} ({1:N0} ticks)", dateNew.ToString(dateFormat), dateNew.Ticks); } } Original date: 07/23/2018 01:00:00.0000000 (636,679,476,000,000,000 ticks) Next date: 07/23/2018 01:00:00.0010000 (636,679,476,000,010,000 ticks)
[ { "code": null, "e": 1190, "s": 1062, "text": "The DateTime has methods and properties for Date and Time as well like how to get the number of hours or minutes of a day, etc." }, { "code": null, "e": 1232, "s": 1190, "text": "Let us only focus on the time functions −" }, { "code": null, "e": 1297, "s": 1232, "text": "Refer MSDN (Microsoft Developer Network) for all the functions −" }, { "code": null, "e": 1436, "s": 1297, "text": "Let us learn about a Time function i.e. AddMilliseconds(Double) to add the specified number of milliseconds to the value of this instance." }, { "code": null, "e": 1447, "s": 1436, "text": " Live Demo" }, { "code": null, "e": 1940, "s": 1447, "text": "using System;\n\npublic class Demo {\n public static void Main() {\n string dateFormat = \"MM/dd/yyyy hh:mm:ss.fffffff\";\n DateTime dateCurrent = new DateTime(2018, 7, 23, 13, 0, 0);\n Console.WriteLine(\"Original date: {0} ({1:N0} ticks)\\n\", dateCurrent.ToString(dateFormat), dateCurrent.Ticks);\n\n DateTime dateNew = dateCurrent.AddMilliseconds(1);\n Console.WriteLine(\"Next date: {0} ({1:N0} ticks)\", dateNew.ToString(dateFormat), dateNew.Ticks);\n\n }\n}" }, { "code": null, "e": 2086, "s": 1940, "text": "Original date: 07/23/2018 01:00:00.0000000 (636,679,476,000,000,000 ticks)\nNext date: 07/23/2018 01:00:00.0010000 (636,679,476,000,010,000 ticks)" } ]
PyTorch Ignite Tutorial— Classifying Tiny ImageNet with EfficientNet | by Kenneth Leung | Towards Data Science
PyTorch is a powerful deep learning framework that has been adopted by tech giants like Tesla, OpenAI, and Microsoft for key research and production workloads. Its open-source nature means that PyTorch’s capabilities can be readily leveraged by the public as well. A problem with deep learning implementation is that the codes can quickly grow to become repetitive and overly lengthy. This has sparked the creation of high-level libraries to streamline these PyTorch codes, and one of which is PyTorch Ignite. This article provides a clearly explained walkthrough on how to use PyTorch Ignite to simplify the development of deep learning models in PyTorch. (1) About PyTorch Ignite(2) Step-by-Step Implementation(3) Wrapping things up PyTorch Ignite is a high-level library that helps with training and evaluating neural networks in PyTorch flexibly and transparently. It reduces the amount of code needed to build deep learning models while maintaining simplicity and maximum control throughout. The above image illustrates the extent to which PyTorch Ignite compresses pure PyTorch code into something more concise. Besides eliminating low-level codes, PyTorch Ignite also comes with utility support for metrics evaluation, experiment management, and model debugging. The demonstration task in this tutorial is to build an image classification deep learning model on the Tiny ImageNet dataset. Tiny ImageNet is a subset of the ImageNet dataset in the famous ImageNet Large Scale Visual Recognition Challenge (ILSVRC). The dataset contains 100,000 images of 200 classes (500 for each class) downsized to 64×64 colored images. Each class has 500 training images, 50 validation images, and 50 test images. Let’s get to the steps where we detail the use of PyTorch and Ignite to classify these images as accurately as possible. We will be using Google Colab since it offers free access to GPUs, which we can readily utilize. Feel free to follow along with this completed demo Colab notebook. Make sure that you have set your Colab runtime to GPU. Once done, execute the following steps as part of the initial setup: Install and import the necessary Python libraries Install and import the necessary Python libraries 2. Define GPU support for PyTorch (i.e., use CUDA). There are two ways to download the Tiny ImageNet dataset, namely: Download directly from Kaggle with the opendatasets library Use GNU wget package to download from the official Stanford site For this project, I used wget to retrieve the raw dataset (in a zip file). Once downloaded, we can unzip the zip file and set the respective folder paths for the extracted images. If done correctly, you should see the folders appear on the Colab sidebar: We define helper functions to make our lives easier later on. There are two groups of functions created, and they are to: Display single or a batch of sample images This allows us to visualize a random subset of images that we are working on. Create DataLoaders for the image datasets The job of a DataLoader is to generate mini-batches of data from a dataset, giving us the flexibility to choose from different sampling strategies and batch sizes. In the code above, we used the ImageFolder function from torchvision.datasets to generate datasets. For ImageFolder to work, images in training and validation folders must be arranged in the following structure: You will notice that the training folder meets the structure needed for ImageLoader in Step 3, but the validation folder does not. The images in the validation folder are all saved within a single folder, so we need to reorganize them into sub-folders based on their labels. The validation folder contains a val_annotations.txt file which comprises six tab-separated columns: filename, class label, and details of the bounding box (x,y coordinates, height, width). We extract the first two columns to save the pairs of filename and corresponding class labels in a dictionary. To find out what each class label means, you can read the words.txt file. For example: After that, we carry out the folder path reorganization: All pre-trained Torchvision models expect input images to be normalized in the same way (as part of pre-processing requirements). It requires these images to be in 3-channel RGB format of shape (3 x H x W), where H (height) and W (width) are at least 224 pixels. The pixel values then need to be normalized according to mean values of (0.485, 0.456, 0.406) and standard deviation values of (0.229, 0.224, 0.225). On top of that, we can introduce various transformations (e.g., center crops, random flips, etc.) to augment the image dataset and improve model performance. We place these transformations in a Torchvision Composewrapper to link them all together. We described the concept of DataLoaders in Step 3 and created a helper function for setting up DataLoaders. It is time to put the function to good use by creating DataLoaders for both the training and validation sets. We specify the transformation steps in Step 5 and define a batch size of 64. This means the DataLoader will push out 64 images each time it is called. The Torchvision models subpackage torchvision.modelscomprises numerous pre-trained models for us to use. This includes popular architectures such as ResNet-18, VGG16, GoogLeNet and ResNeXt-50. We will do something different for this project by selecting a pre-trained model that is not within the default list of Torchvision models. In particular, we will be using EfficientNet. EfficientNet is a convolutional neural network architecture and scaling method developed by Google in 2019. It has surpassed state-of-the-art accuracy with up to 10 times better efficiency (i.e., smaller and faster). The graphs below illustrate how EfficientNet (red line) outperforms other architectures in accuracy (on ImageNet) and computing resources. The different versions of EfficientNet (b0 to b7) differ based on the number of model parameters. A higher number of parameters leads to greater accuracy but at the expense of longer training time. We will use the PyTorch implementation of EfficientNet to set up an EfficientNet-B3 architecture for this tutorial. I chose B3 because it provides a nice balance between accuracy and training time. The PyTorch implementation of the newer EfficientNet v2 is coming soon, so stay tuned to this GitHub repo for the latest updates. The most suitable loss function for the image classification task is categorical cross-entropy loss. We will use a set of baseline values for model parameters such as learning rate, number of epochs, logging frequency, and type of optimizer. The main essence of the Ignite framework is the Engineclass, which executes processing functions over input data and returns an output. When we create a trainer engine, we are initializing a class that will be repeatedly called upon to train the model on batches of data generated by the DataLoaders. PyTorch Ignite comes with in-built helper functions to create trainer engines with just single lines of code. For our use case of supervised image classification, we utilize the create_supervised_trainerfunction. These engines also allow us to attach useful event handlers, such as a progress bar to monitor training. The metrics for image classification model evaluation are accuracy (for us to interpret the model’s performance) and cross-entropy loss (for the model to improve iteratively). You can also create your own custom metric before attaching it to an engine. For example, the F1 score can be derived arithmetically from the default Precision and Recall metrics: from ignite.metrics import Precision, Recallprecision = Precision(average=False)recall = Recall(average=False)F1 = (precision * recall * 2 / (precision + recall)).mean()F1.attach(engine, "F1") After defining evaluation metrics, we can initialize evaluator engines to evaluate model performance. The evaluator engine will take the model and evaluation metrics (from Step 10) as arguments. We define an evaluator engine for the training set and a separate evaluator engine for the validation set. This is because they have different roles in the whole model training process. The validation evaluator will be used to save the best model based on validation metrics, while the training evaluator will only be logging metrics from the training set. To improve the Engine’s flexibility, an event system is introduced to facilitate interactions on each step of the training run for events such as: Engine started/completed Epoch started/completed Batch iteration started/completed With the help of decorators, we can create custom codes known as event handlers. Event handlers are functions that are executed when specific events occur. For example, we can log the metrics upon completion of each iteration (Events.ITERATION_COMPLETED) and epoch (Events.EPOCH_COMPLETED). Furthermore, we want a checkpoint handler that saves our best models (as .pt files) based on validation accuracy. This is done easily with the helper method save_best_model_by_val_scorefrom the common module. In the functions accompanying each event, you will notice that we use variables and engines that we have already built in the earlier steps. Tensorboard is a useful toolkit to track and visualize metrics (such as loss and accuracy) as part of machine learning experimentation. PyTorch is integrated with Tensorboard, so we can start by creating a Tensorboard logger handler and specifying the directory to store the logs. With the Tensorboard logger initialized, we can attach output handlers to specify the events and corresponding metrics to save for visualization later on. Although we are using Tensorboard here, we can easily use other popular logging tools such as Weights and Biases, ClearML, and MLflow. Have a look at the common module documentation for more information. We have finally reached the stage where we can start the actual model training. We do this by getting the trainer engine to run on the training set DataLoader. Here is what the first training epoch looks like in Colab: With just one epoch, EfficientNet-B3 has already achieved an impressive validation accuracy of 61.1%. Once training is complete, we can run the following code to get the final evaluation metrics on the validation set: print(evaluator.state.metrics) The final accuracy score obtained after three epochs was 66.57%. We call a set of magic commands to load the Tensorboard within the Colab notebook. After executing the above commands, the following Tensorboard interface will load in the Colab notebook. This visual dashboard provides us with metrics information obtained from the training runs. In this tutorial, we covered the steps to leverage the flexibility and simplicity of the Ignite framework to build PyTorch deep learning models. PyTorch Ignite has many other functionalities to suit the needs of more complex neural network designs, so feel free to explore the documentation and example notebooks. For example, instead of the static learning rate used earlier, we can incorporate a learning rate scheduler (LRScheduler) handler to adjust the learning rate values during training. The flexibility also means that we can include other algorithms like FastAI’s learning rate finder in the setup. Project Links GitHub repo Colab Notebook I welcome you to join me on a data science learning journey. Follow this Medium page and check out my GitHub to stay in the loop of practical and educational data science content. Meanwhile, here’s wishing you the best of luck in the exam! PyTorch Ignite GitHub PyTorch Ignite documentation
[ { "code": null, "e": 332, "s": 172, "text": "PyTorch is a powerful deep learning framework that has been adopted by tech giants like Tesla, OpenAI, and Microsoft for key research and production workloads." }, { "code": null, "e": 437, "s": 332, "text": "Its open-source nature means that PyTorch’s capabilities can be readily leveraged by the public as well." }, { "code": null, "e": 682, "s": 437, "text": "A problem with deep learning implementation is that the codes can quickly grow to become repetitive and overly lengthy. This has sparked the creation of high-level libraries to streamline these PyTorch codes, and one of which is PyTorch Ignite." }, { "code": null, "e": 829, "s": 682, "text": "This article provides a clearly explained walkthrough on how to use PyTorch Ignite to simplify the development of deep learning models in PyTorch." }, { "code": null, "e": 907, "s": 829, "text": "(1) About PyTorch Ignite(2) Step-by-Step Implementation(3) Wrapping things up" }, { "code": null, "e": 1041, "s": 907, "text": "PyTorch Ignite is a high-level library that helps with training and evaluating neural networks in PyTorch flexibly and transparently." }, { "code": null, "e": 1169, "s": 1041, "text": "It reduces the amount of code needed to build deep learning models while maintaining simplicity and maximum control throughout." }, { "code": null, "e": 1290, "s": 1169, "text": "The above image illustrates the extent to which PyTorch Ignite compresses pure PyTorch code into something more concise." }, { "code": null, "e": 1442, "s": 1290, "text": "Besides eliminating low-level codes, PyTorch Ignite also comes with utility support for metrics evaluation, experiment management, and model debugging." }, { "code": null, "e": 1568, "s": 1442, "text": "The demonstration task in this tutorial is to build an image classification deep learning model on the Tiny ImageNet dataset." }, { "code": null, "e": 1692, "s": 1568, "text": "Tiny ImageNet is a subset of the ImageNet dataset in the famous ImageNet Large Scale Visual Recognition Challenge (ILSVRC)." }, { "code": null, "e": 1877, "s": 1692, "text": "The dataset contains 100,000 images of 200 classes (500 for each class) downsized to 64×64 colored images. Each class has 500 training images, 50 validation images, and 50 test images." }, { "code": null, "e": 1998, "s": 1877, "text": "Let’s get to the steps where we detail the use of PyTorch and Ignite to classify these images as accurately as possible." }, { "code": null, "e": 2162, "s": 1998, "text": "We will be using Google Colab since it offers free access to GPUs, which we can readily utilize. Feel free to follow along with this completed demo Colab notebook." }, { "code": null, "e": 2286, "s": 2162, "text": "Make sure that you have set your Colab runtime to GPU. Once done, execute the following steps as part of the initial setup:" }, { "code": null, "e": 2336, "s": 2286, "text": "Install and import the necessary Python libraries" }, { "code": null, "e": 2386, "s": 2336, "text": "Install and import the necessary Python libraries" }, { "code": null, "e": 2438, "s": 2386, "text": "2. Define GPU support for PyTorch (i.e., use CUDA)." }, { "code": null, "e": 2504, "s": 2438, "text": "There are two ways to download the Tiny ImageNet dataset, namely:" }, { "code": null, "e": 2564, "s": 2504, "text": "Download directly from Kaggle with the opendatasets library" }, { "code": null, "e": 2629, "s": 2564, "text": "Use GNU wget package to download from the official Stanford site" }, { "code": null, "e": 2809, "s": 2629, "text": "For this project, I used wget to retrieve the raw dataset (in a zip file). Once downloaded, we can unzip the zip file and set the respective folder paths for the extracted images." }, { "code": null, "e": 2884, "s": 2809, "text": "If done correctly, you should see the folders appear on the Colab sidebar:" }, { "code": null, "e": 3006, "s": 2884, "text": "We define helper functions to make our lives easier later on. There are two groups of functions created, and they are to:" }, { "code": null, "e": 3049, "s": 3006, "text": "Display single or a batch of sample images" }, { "code": null, "e": 3127, "s": 3049, "text": "This allows us to visualize a random subset of images that we are working on." }, { "code": null, "e": 3169, "s": 3127, "text": "Create DataLoaders for the image datasets" }, { "code": null, "e": 3333, "s": 3169, "text": "The job of a DataLoader is to generate mini-batches of data from a dataset, giving us the flexibility to choose from different sampling strategies and batch sizes." }, { "code": null, "e": 3545, "s": 3333, "text": "In the code above, we used the ImageFolder function from torchvision.datasets to generate datasets. For ImageFolder to work, images in training and validation folders must be arranged in the following structure:" }, { "code": null, "e": 3676, "s": 3545, "text": "You will notice that the training folder meets the structure needed for ImageLoader in Step 3, but the validation folder does not." }, { "code": null, "e": 3820, "s": 3676, "text": "The images in the validation folder are all saved within a single folder, so we need to reorganize them into sub-folders based on their labels." }, { "code": null, "e": 4010, "s": 3820, "text": "The validation folder contains a val_annotations.txt file which comprises six tab-separated columns: filename, class label, and details of the bounding box (x,y coordinates, height, width)." }, { "code": null, "e": 4121, "s": 4010, "text": "We extract the first two columns to save the pairs of filename and corresponding class labels in a dictionary." }, { "code": null, "e": 4208, "s": 4121, "text": "To find out what each class label means, you can read the words.txt file. For example:" }, { "code": null, "e": 4265, "s": 4208, "text": "After that, we carry out the folder path reorganization:" }, { "code": null, "e": 4395, "s": 4265, "text": "All pre-trained Torchvision models expect input images to be normalized in the same way (as part of pre-processing requirements)." }, { "code": null, "e": 4528, "s": 4395, "text": "It requires these images to be in 3-channel RGB format of shape (3 x H x W), where H (height) and W (width) are at least 224 pixels." }, { "code": null, "e": 4678, "s": 4528, "text": "The pixel values then need to be normalized according to mean values of (0.485, 0.456, 0.406) and standard deviation values of (0.229, 0.224, 0.225)." }, { "code": null, "e": 4836, "s": 4678, "text": "On top of that, we can introduce various transformations (e.g., center crops, random flips, etc.) to augment the image dataset and improve model performance." }, { "code": null, "e": 4926, "s": 4836, "text": "We place these transformations in a Torchvision Composewrapper to link them all together." }, { "code": null, "e": 5144, "s": 4926, "text": "We described the concept of DataLoaders in Step 3 and created a helper function for setting up DataLoaders. It is time to put the function to good use by creating DataLoaders for both the training and validation sets." }, { "code": null, "e": 5295, "s": 5144, "text": "We specify the transformation steps in Step 5 and define a batch size of 64. This means the DataLoader will push out 64 images each time it is called." }, { "code": null, "e": 5488, "s": 5295, "text": "The Torchvision models subpackage torchvision.modelscomprises numerous pre-trained models for us to use. This includes popular architectures such as ResNet-18, VGG16, GoogLeNet and ResNeXt-50." }, { "code": null, "e": 5674, "s": 5488, "text": "We will do something different for this project by selecting a pre-trained model that is not within the default list of Torchvision models. In particular, we will be using EfficientNet." }, { "code": null, "e": 5891, "s": 5674, "text": "EfficientNet is a convolutional neural network architecture and scaling method developed by Google in 2019. It has surpassed state-of-the-art accuracy with up to 10 times better efficiency (i.e., smaller and faster)." }, { "code": null, "e": 6030, "s": 5891, "text": "The graphs below illustrate how EfficientNet (red line) outperforms other architectures in accuracy (on ImageNet) and computing resources." }, { "code": null, "e": 6228, "s": 6030, "text": "The different versions of EfficientNet (b0 to b7) differ based on the number of model parameters. A higher number of parameters leads to greater accuracy but at the expense of longer training time." }, { "code": null, "e": 6426, "s": 6228, "text": "We will use the PyTorch implementation of EfficientNet to set up an EfficientNet-B3 architecture for this tutorial. I chose B3 because it provides a nice balance between accuracy and training time." }, { "code": null, "e": 6556, "s": 6426, "text": "The PyTorch implementation of the newer EfficientNet v2 is coming soon, so stay tuned to this GitHub repo for the latest updates." }, { "code": null, "e": 6657, "s": 6556, "text": "The most suitable loss function for the image classification task is categorical cross-entropy loss." }, { "code": null, "e": 6798, "s": 6657, "text": "We will use a set of baseline values for model parameters such as learning rate, number of epochs, logging frequency, and type of optimizer." }, { "code": null, "e": 6934, "s": 6798, "text": "The main essence of the Ignite framework is the Engineclass, which executes processing functions over input data and returns an output." }, { "code": null, "e": 7099, "s": 6934, "text": "When we create a trainer engine, we are initializing a class that will be repeatedly called upon to train the model on batches of data generated by the DataLoaders." }, { "code": null, "e": 7312, "s": 7099, "text": "PyTorch Ignite comes with in-built helper functions to create trainer engines with just single lines of code. For our use case of supervised image classification, we utilize the create_supervised_trainerfunction." }, { "code": null, "e": 7417, "s": 7312, "text": "These engines also allow us to attach useful event handlers, such as a progress bar to monitor training." }, { "code": null, "e": 7593, "s": 7417, "text": "The metrics for image classification model evaluation are accuracy (for us to interpret the model’s performance) and cross-entropy loss (for the model to improve iteratively)." }, { "code": null, "e": 7773, "s": 7593, "text": "You can also create your own custom metric before attaching it to an engine. For example, the F1 score can be derived arithmetically from the default Precision and Recall metrics:" }, { "code": null, "e": 7966, "s": 7773, "text": "from ignite.metrics import Precision, Recallprecision = Precision(average=False)recall = Recall(average=False)F1 = (precision * recall * 2 / (precision + recall)).mean()F1.attach(engine, \"F1\")" }, { "code": null, "e": 8161, "s": 7966, "text": "After defining evaluation metrics, we can initialize evaluator engines to evaluate model performance. The evaluator engine will take the model and evaluation metrics (from Step 10) as arguments." }, { "code": null, "e": 8347, "s": 8161, "text": "We define an evaluator engine for the training set and a separate evaluator engine for the validation set. This is because they have different roles in the whole model training process." }, { "code": null, "e": 8518, "s": 8347, "text": "The validation evaluator will be used to save the best model based on validation metrics, while the training evaluator will only be logging metrics from the training set." }, { "code": null, "e": 8665, "s": 8518, "text": "To improve the Engine’s flexibility, an event system is introduced to facilitate interactions on each step of the training run for events such as:" }, { "code": null, "e": 8690, "s": 8665, "text": "Engine started/completed" }, { "code": null, "e": 8714, "s": 8690, "text": "Epoch started/completed" }, { "code": null, "e": 8748, "s": 8714, "text": "Batch iteration started/completed" }, { "code": null, "e": 9039, "s": 8748, "text": "With the help of decorators, we can create custom codes known as event handlers. Event handlers are functions that are executed when specific events occur. For example, we can log the metrics upon completion of each iteration (Events.ITERATION_COMPLETED) and epoch (Events.EPOCH_COMPLETED)." }, { "code": null, "e": 9248, "s": 9039, "text": "Furthermore, we want a checkpoint handler that saves our best models (as .pt files) based on validation accuracy. This is done easily with the helper method save_best_model_by_val_scorefrom the common module." }, { "code": null, "e": 9389, "s": 9248, "text": "In the functions accompanying each event, you will notice that we use variables and engines that we have already built in the earlier steps." }, { "code": null, "e": 9525, "s": 9389, "text": "Tensorboard is a useful toolkit to track and visualize metrics (such as loss and accuracy) as part of machine learning experimentation." }, { "code": null, "e": 9670, "s": 9525, "text": "PyTorch is integrated with Tensorboard, so we can start by creating a Tensorboard logger handler and specifying the directory to store the logs." }, { "code": null, "e": 9825, "s": 9670, "text": "With the Tensorboard logger initialized, we can attach output handlers to specify the events and corresponding metrics to save for visualization later on." }, { "code": null, "e": 10029, "s": 9825, "text": "Although we are using Tensorboard here, we can easily use other popular logging tools such as Weights and Biases, ClearML, and MLflow. Have a look at the common module documentation for more information." }, { "code": null, "e": 10189, "s": 10029, "text": "We have finally reached the stage where we can start the actual model training. We do this by getting the trainer engine to run on the training set DataLoader." }, { "code": null, "e": 10248, "s": 10189, "text": "Here is what the first training epoch looks like in Colab:" }, { "code": null, "e": 10350, "s": 10248, "text": "With just one epoch, EfficientNet-B3 has already achieved an impressive validation accuracy of 61.1%." }, { "code": null, "e": 10466, "s": 10350, "text": "Once training is complete, we can run the following code to get the final evaluation metrics on the validation set:" }, { "code": null, "e": 10497, "s": 10466, "text": "print(evaluator.state.metrics)" }, { "code": null, "e": 10562, "s": 10497, "text": "The final accuracy score obtained after three epochs was 66.57%." }, { "code": null, "e": 10645, "s": 10562, "text": "We call a set of magic commands to load the Tensorboard within the Colab notebook." }, { "code": null, "e": 10842, "s": 10645, "text": "After executing the above commands, the following Tensorboard interface will load in the Colab notebook. This visual dashboard provides us with metrics information obtained from the training runs." }, { "code": null, "e": 10987, "s": 10842, "text": "In this tutorial, we covered the steps to leverage the flexibility and simplicity of the Ignite framework to build PyTorch deep learning models." }, { "code": null, "e": 11156, "s": 10987, "text": "PyTorch Ignite has many other functionalities to suit the needs of more complex neural network designs, so feel free to explore the documentation and example notebooks." }, { "code": null, "e": 11451, "s": 11156, "text": "For example, instead of the static learning rate used earlier, we can incorporate a learning rate scheduler (LRScheduler) handler to adjust the learning rate values during training. The flexibility also means that we can include other algorithms like FastAI’s learning rate finder in the setup." }, { "code": null, "e": 11465, "s": 11451, "text": "Project Links" }, { "code": null, "e": 11477, "s": 11465, "text": "GitHub repo" }, { "code": null, "e": 11492, "s": 11477, "text": "Colab Notebook" }, { "code": null, "e": 11732, "s": 11492, "text": "I welcome you to join me on a data science learning journey. Follow this Medium page and check out my GitHub to stay in the loop of practical and educational data science content. Meanwhile, here’s wishing you the best of luck in the exam!" }, { "code": null, "e": 11754, "s": 11732, "text": "PyTorch Ignite GitHub" } ]
Design an IIR Highpass Butterworth Filter using Bilinear Transformation Method in Scipy - Python - GeeksforGeeks
07 Jan, 2022 IIR stands for Infinite Impulse Response, It is one of the striking features of many linear-time invariant systems that are distinguished by having an impulse response h(t)/h(n) which does not become zero after some point but instead continues infinitely. It basically behaves just like an ordinary digital Highpass Butterworth Filter with an infinite impulse response. The specifications are as follows: Pass band frequency: 2-4 kHz Stop band frequency: 0-500 Hz Pass band ripple: 3dB Stop band attenuation: 20 dB Sampling frequency: 8 kHz We will plot the magnitude, phase, impulse, step response of the filter. Step-by-step Approach: Step 1: Importing all the necessary libraries. Python3 # import required libraryimport numpy as npimport scipy.signal as signalimport matplotlib.pyplot as plt Step 2: Defining user-defined functions mfreqz() and impz(). mfreqz is a function for magnitude and phase plot & impz is a function for impulse and step response. Python3 def mfreqz(b, a, Fs): # Compute frequency response of the filter # using signal.freqz function wz, hz = signal.freqz(b, a) # Calculate Magnitude from hz in dB Mag = 20*np.log10(abs(hz)) # Calculate phase angle in degree from hz Phase = np.unwrap(np.arctan2(np.imag(hz), np.real(hz)))*(180/np.pi) # Calculate frequency in Hz from wz Freq = wz*Fs/(2*np.pi) # START CODE HERE ### (≈ 1 line of code) # Plot filter magnitude and phase responses using subplot. fig = plt.figure(figsize=(10, 6)) # Plot Magnitude response sub1 = plt.subplot(2, 1, 1) sub1.plot(Freq, Mag, 'r', linewidth=2) sub1.axis([1, Fs/2, -100, 5]) sub1.set_title('Magnitude Response', fontsize=20) sub1.set_xlabel('Frequency [Hz]', fontsize=20) sub1.set_ylabel('Magnitude [dB]', fontsize=20) sub1.grid() # Plot phase angle sub2 = plt.subplot(2, 1, 2) sub2.plot(Freq, Phase, 'g', linewidth=2) sub2.set_ylabel('Phase (degree)', fontsize=20) sub2.set_xlabel(r'Frequency (Hz)', fontsize=20) sub2.set_title(r'Phase response', fontsize=20) sub2.grid() plt.subplots_adjust(hspace=0.5) fig.tight_layout() plt.show() # Define impz(b,a) to calculate impulse response# and step response of a system input: b= an array# containing numerator coefficients,a= an array containing #denominator coefficientsdef impz(b, a): # Define the impulse sequence of length 60 impulse = np.repeat(0., 60) impulse[0] = 1. x = np.arange(0, 60) # Compute the impulse response response = signal.lfilter(b, a, impulse) # Plot filter impulse and step response: fig = plt.figure(figsize=(10, 6)) plt.subplot(211) plt.stem(x, response, 'm', use_line_collection=True) plt.ylabel('Amplitude', fontsize=15) plt.xlabel(r'n (samples)', fontsize=15) plt.title(r'Impulse response', fontsize=15) plt.subplot(212) step = np.cumsum(response) # Compute step response of the system plt.stem(x, step, 'g', use_line_collection=True) plt.ylabel('Amplitude', fontsize=15) plt.xlabel(r'n (samples)', fontsize=15) plt.title(r'Step response', fontsize=15) plt.subplots_adjust(hspace=0.5) fig.tight_layout() plt.show() Step 3:Define variables with the given specifications of the filter. Python3 # Given specificationFs = 8000 # Sampling frequency in Hzfp = 2000 # Pass band frequency in Hzfs = 500 # Stop Band frequency in HzAp = 3 # Pass band ripple in dBAs = 20 # Stop band attenuation in dB # Compute Sampling parameterTd = 1/Fs Step 4:Computing the cut-off frequency Python3 # Compute cut-off frequency in radian/secwp = 2*np.pi*fp # pass band frequency in radian/secws = 2*np.pi*fs # stop band frequency in radian/sec Step 5: Pre-wrapping the cut-off frequency Python3 # Prewarp the analog frequencyOmega_p = (2/Td)*np.tan(wp*Td/2) # Prewarped analog passband frequencyOmega_s = (2/Td)*np.tan(ws*Td/2) # Prewarped analog stopband frequency Step 6: Computing the Butterworth Filter Python3 # Compute Butterworth filter order and cutoff frequencyN, wc = signal.buttord(Omega_p, Omega_s, Ap, As, analog=True) # Print the values of order and cut-off frequencyprint('Order of the filter=', N)print('Cut-off frequency=', wc) Output: Step 7: Design analog Butterworth filter using N and wc by signal.butter() function. Python3 # Design analog Butterworth filter using N and# wc by signal.butter functionb, a = signal.butter(N, wc, 'high', analog=True) # Perform bilinear Transformationz, p = signal.bilinear(b, a, fs=Fs) # Print numerator and denomerator coefficients # of the filterprint('Numerator Coefficients:', z)print('Denominator Coefficients:', p) Output: Step 8: Plotting the Magnitude & Phase Response Python3 # Call mfreqz function to plot the# magnitude and phase responsemfreqz(z, p, Fs) Output: Step 9: Plotting the impulse & step response Python3 # Call impz function to plot impulse and # step response of the filterimpz(z, p) Output: Below is the implementation: Python3 # import required libraryimport numpy as npimport scipy.signal as signalimport matplotlib.pyplot as plt # User defined functions mfreqz for # Magnitude & Phase Responsedef mfreqz(b, a, Fs): # Compute frequency response of the filter # using signal.freqz function wz, hz = signal.freqz(b, a) # Calculate Magnitude from hz in dB Mag = 20*np.log10(abs(hz)) # Calculate phase angle in degree from hz Phase = np.unwrap(np.arctan2(np.imag(hz), np.real(hz)))*(180/np.pi) # Calculate frequency in Hz from wz Freq = wz*Fs/(2*np.pi) # START CODE HERE ### (≈ 1 line of code) # Plot filter magnitude and phase responses using subplot. fig = plt.figure(figsize=(10, 6)) # Plot Magnitude response sub1 = plt.subplot(2, 1, 1) sub1.plot(Freq, Mag, 'r', linewidth=2) sub1.axis([1, Fs/2, -100, 5]) sub1.set_title('Magnitude Response', fontsize=20) sub1.set_xlabel('Frequency [Hz]', fontsize=20) sub1.set_ylabel('Magnitude [dB]', fontsize=20) sub1.grid() # Plot phase angle sub2 = plt.subplot(2, 1, 2) sub2.plot(Freq, Phase, 'g', linewidth=2) sub2.set_ylabel('Phase (degree)', fontsize=20) sub2.set_xlabel(r'Frequency (Hz)', fontsize=20) sub2.set_title(r'Phase response', fontsize=20) sub2.grid() plt.subplots_adjust(hspace=0.5) fig.tight_layout() plt.show() # Define impz(b,a) to calculate impulse # response and step response of a system# input: b= an array containing numerator # coefficients,a= an array containing #denominator coefficientsdef impz(b, a): # Define the impulse sequence of length 60 impulse = np.repeat(0., 60) impulse[0] = 1. x = np.arange(0, 60) # Compute the impulse response response = signal.lfilter(b, a, impulse) # Plot filter impulse and step response: fig = plt.figure(figsize=(10, 6)) plt.subplot(211) plt.stem(x, response, 'm', use_line_collection=True) plt.ylabel('Amplitude', fontsize=15) plt.xlabel(r'n (samples)', fontsize=15) plt.title(r'Impulse response', fontsize=15) plt.subplot(212) step = np.cumsum(response) # Compute step response of the system plt.stem(x, step, 'g', use_line_collection=True) plt.ylabel('Amplitude', fontsize=15) plt.xlabel(r'n (samples)', fontsize=15) plt.title(r'Step response', fontsize=15) plt.subplots_adjust(hspace=0.5) fig.tight_layout() plt.show() # Given specificationFs = 8000 # Sampling frequency in Hzfp = 2000 # Pass band frequency in Hzfs = 500 # Stop Band frequency in HzAp = 3 # Pass band ripple in dBAs = 20 # Stop band attenuation in dB # Compute Sampling parameterTd = 1/Fs # Compute cut-off frequency in radian/secwp = 2*np.pi*fp # pass band frequency in radian/secws = 2*np.pi*fs # stop band frequency in radian/sec # Prewarp the analog frequencyOmega_p = (2/Td)*np.tan(wp*Td/2) # Prewarped analog passband frequencyOmega_s = (2/Td)*np.tan(ws*Td/2) # Prewarped analog stopband frequency # Compute Butterworth filter order and cutoff frequencyN, wc = signal.buttord(Omega_p, Omega_s, Ap, As, analog=True) # Print the values of order and cut-off frequencyprint('Order of the filter=', N)print('Cut-off frequency=', wc) # Design analog Butterworth filter using N and# wc by signal.butter functionb, a = signal.butter(N, wc, 'high', analog=True) # Perform bilinear Transformationz, p = signal.bilinear(b, a, fs=Fs) # Print numerator and denomerator coefficients of the filterprint('Numerator Coefficients:', z)print('Denominator Coefficients:', p) # Call mfreqz function to plot the magnitude# and phase responsemfreqz(z, p, Fs) # Call impz function to plot impulse and step# response of the filterimpz(z, p) Output: gulshankumarar231 Data Visualization Python-scipy 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 drop one or multiple columns in Pandas Dataframe How To Convert Python Dictionary To JSON? Check if element exists in list in Python Selecting rows in pandas DataFrame based on conditions Defaultdict in Python Python | Get unique values from a list Python | os.path.join() method Create a directory in Python Python | Split string into list of characters
[ { "code": null, "e": 24292, "s": 24264, "text": "\n07 Jan, 2022" }, { "code": null, "e": 24548, "s": 24292, "text": "IIR stands for Infinite Impulse Response, It is one of the striking features of many linear-time invariant systems that are distinguished by having an impulse response h(t)/h(n) which does not become zero after some point but instead continues infinitely." }, { "code": null, "e": 24662, "s": 24548, "text": "It basically behaves just like an ordinary digital Highpass Butterworth Filter with an infinite impulse response." }, { "code": null, "e": 24699, "s": 24662, "text": "The specifications are as follows: " }, { "code": null, "e": 24728, "s": 24699, "text": "Pass band frequency: 2-4 kHz" }, { "code": null, "e": 24758, "s": 24728, "text": "Stop band frequency: 0-500 Hz" }, { "code": null, "e": 24780, "s": 24758, "text": "Pass band ripple: 3dB" }, { "code": null, "e": 24809, "s": 24780, "text": "Stop band attenuation: 20 dB" }, { "code": null, "e": 24835, "s": 24809, "text": "Sampling frequency: 8 kHz" }, { "code": null, "e": 24908, "s": 24835, "text": "We will plot the magnitude, phase, impulse, step response of the filter." }, { "code": null, "e": 24931, "s": 24908, "text": "Step-by-step Approach:" }, { "code": null, "e": 24978, "s": 24931, "text": "Step 1: Importing all the necessary libraries." }, { "code": null, "e": 24986, "s": 24978, "text": "Python3" }, { "code": "# import required libraryimport numpy as npimport scipy.signal as signalimport matplotlib.pyplot as plt", "e": 25090, "s": 24986, "text": null }, { "code": null, "e": 25253, "s": 25090, "text": "Step 2: Defining user-defined functions mfreqz() and impz(). mfreqz is a function for magnitude and phase plot & impz is a function for impulse and step response." }, { "code": null, "e": 25261, "s": 25253, "text": "Python3" }, { "code": "def mfreqz(b, a, Fs): # Compute frequency response of the filter # using signal.freqz function wz, hz = signal.freqz(b, a) # Calculate Magnitude from hz in dB Mag = 20*np.log10(abs(hz)) # Calculate phase angle in degree from hz Phase = np.unwrap(np.arctan2(np.imag(hz), np.real(hz)))*(180/np.pi) # Calculate frequency in Hz from wz Freq = wz*Fs/(2*np.pi) # START CODE HERE ### (≈ 1 line of code) # Plot filter magnitude and phase responses using subplot. fig = plt.figure(figsize=(10, 6)) # Plot Magnitude response sub1 = plt.subplot(2, 1, 1) sub1.plot(Freq, Mag, 'r', linewidth=2) sub1.axis([1, Fs/2, -100, 5]) sub1.set_title('Magnitude Response', fontsize=20) sub1.set_xlabel('Frequency [Hz]', fontsize=20) sub1.set_ylabel('Magnitude [dB]', fontsize=20) sub1.grid() # Plot phase angle sub2 = plt.subplot(2, 1, 2) sub2.plot(Freq, Phase, 'g', linewidth=2) sub2.set_ylabel('Phase (degree)', fontsize=20) sub2.set_xlabel(r'Frequency (Hz)', fontsize=20) sub2.set_title(r'Phase response', fontsize=20) sub2.grid() plt.subplots_adjust(hspace=0.5) fig.tight_layout() plt.show() # Define impz(b,a) to calculate impulse response# and step response of a system input: b= an array# containing numerator coefficients,a= an array containing #denominator coefficientsdef impz(b, a): # Define the impulse sequence of length 60 impulse = np.repeat(0., 60) impulse[0] = 1. x = np.arange(0, 60) # Compute the impulse response response = signal.lfilter(b, a, impulse) # Plot filter impulse and step response: fig = plt.figure(figsize=(10, 6)) plt.subplot(211) plt.stem(x, response, 'm', use_line_collection=True) plt.ylabel('Amplitude', fontsize=15) plt.xlabel(r'n (samples)', fontsize=15) plt.title(r'Impulse response', fontsize=15) plt.subplot(212) step = np.cumsum(response) # Compute step response of the system plt.stem(x, step, 'g', use_line_collection=True) plt.ylabel('Amplitude', fontsize=15) plt.xlabel(r'n (samples)', fontsize=15) plt.title(r'Step response', fontsize=15) plt.subplots_adjust(hspace=0.5) fig.tight_layout() plt.show()", "e": 27477, "s": 25261, "text": null }, { "code": null, "e": 27546, "s": 27477, "text": "Step 3:Define variables with the given specifications of the filter." }, { "code": null, "e": 27554, "s": 27546, "text": "Python3" }, { "code": "# Given specificationFs = 8000 # Sampling frequency in Hzfp = 2000 # Pass band frequency in Hzfs = 500 # Stop Band frequency in HzAp = 3 # Pass band ripple in dBAs = 20 # Stop band attenuation in dB # Compute Sampling parameterTd = 1/Fs", "e": 27797, "s": 27554, "text": null }, { "code": null, "e": 27836, "s": 27797, "text": "Step 4:Computing the cut-off frequency" }, { "code": null, "e": 27844, "s": 27836, "text": "Python3" }, { "code": "# Compute cut-off frequency in radian/secwp = 2*np.pi*fp # pass band frequency in radian/secws = 2*np.pi*fs # stop band frequency in radian/sec", "e": 27990, "s": 27844, "text": null }, { "code": null, "e": 28033, "s": 27990, "text": "Step 5: Pre-wrapping the cut-off frequency" }, { "code": null, "e": 28041, "s": 28033, "text": "Python3" }, { "code": "# Prewarp the analog frequencyOmega_p = (2/Td)*np.tan(wp*Td/2) # Prewarped analog passband frequencyOmega_s = (2/Td)*np.tan(ws*Td/2) # Prewarped analog stopband frequency", "e": 28214, "s": 28041, "text": null }, { "code": null, "e": 28255, "s": 28214, "text": "Step 6: Computing the Butterworth Filter" }, { "code": null, "e": 28263, "s": 28255, "text": "Python3" }, { "code": "# Compute Butterworth filter order and cutoff frequencyN, wc = signal.buttord(Omega_p, Omega_s, Ap, As, analog=True) # Print the values of order and cut-off frequencyprint('Order of the filter=', N)print('Cut-off frequency=', wc)", "e": 28494, "s": 28263, "text": null }, { "code": null, "e": 28502, "s": 28494, "text": "Output:" }, { "code": null, "e": 28587, "s": 28502, "text": "Step 7: Design analog Butterworth filter using N and wc by signal.butter() function." }, { "code": null, "e": 28595, "s": 28587, "text": "Python3" }, { "code": "# Design analog Butterworth filter using N and# wc by signal.butter functionb, a = signal.butter(N, wc, 'high', analog=True) # Perform bilinear Transformationz, p = signal.bilinear(b, a, fs=Fs) # Print numerator and denomerator coefficients # of the filterprint('Numerator Coefficients:', z)print('Denominator Coefficients:', p)", "e": 28926, "s": 28595, "text": null }, { "code": null, "e": 28934, "s": 28926, "text": "Output:" }, { "code": null, "e": 28982, "s": 28934, "text": "Step 8: Plotting the Magnitude & Phase Response" }, { "code": null, "e": 28990, "s": 28982, "text": "Python3" }, { "code": "# Call mfreqz function to plot the# magnitude and phase responsemfreqz(z, p, Fs)", "e": 29071, "s": 28990, "text": null }, { "code": null, "e": 29079, "s": 29071, "text": "Output:" }, { "code": null, "e": 29124, "s": 29079, "text": "Step 9: Plotting the impulse & step response" }, { "code": null, "e": 29132, "s": 29124, "text": "Python3" }, { "code": "# Call impz function to plot impulse and # step response of the filterimpz(z, p)", "e": 29213, "s": 29132, "text": null }, { "code": null, "e": 29221, "s": 29213, "text": "Output:" }, { "code": null, "e": 29250, "s": 29221, "text": "Below is the implementation:" }, { "code": null, "e": 29258, "s": 29250, "text": "Python3" }, { "code": "# import required libraryimport numpy as npimport scipy.signal as signalimport matplotlib.pyplot as plt # User defined functions mfreqz for # Magnitude & Phase Responsedef mfreqz(b, a, Fs): # Compute frequency response of the filter # using signal.freqz function wz, hz = signal.freqz(b, a) # Calculate Magnitude from hz in dB Mag = 20*np.log10(abs(hz)) # Calculate phase angle in degree from hz Phase = np.unwrap(np.arctan2(np.imag(hz), np.real(hz)))*(180/np.pi) # Calculate frequency in Hz from wz Freq = wz*Fs/(2*np.pi) # START CODE HERE ### (≈ 1 line of code) # Plot filter magnitude and phase responses using subplot. fig = plt.figure(figsize=(10, 6)) # Plot Magnitude response sub1 = plt.subplot(2, 1, 1) sub1.plot(Freq, Mag, 'r', linewidth=2) sub1.axis([1, Fs/2, -100, 5]) sub1.set_title('Magnitude Response', fontsize=20) sub1.set_xlabel('Frequency [Hz]', fontsize=20) sub1.set_ylabel('Magnitude [dB]', fontsize=20) sub1.grid() # Plot phase angle sub2 = plt.subplot(2, 1, 2) sub2.plot(Freq, Phase, 'g', linewidth=2) sub2.set_ylabel('Phase (degree)', fontsize=20) sub2.set_xlabel(r'Frequency (Hz)', fontsize=20) sub2.set_title(r'Phase response', fontsize=20) sub2.grid() plt.subplots_adjust(hspace=0.5) fig.tight_layout() plt.show() # Define impz(b,a) to calculate impulse # response and step response of a system# input: b= an array containing numerator # coefficients,a= an array containing #denominator coefficientsdef impz(b, a): # Define the impulse sequence of length 60 impulse = np.repeat(0., 60) impulse[0] = 1. x = np.arange(0, 60) # Compute the impulse response response = signal.lfilter(b, a, impulse) # Plot filter impulse and step response: fig = plt.figure(figsize=(10, 6)) plt.subplot(211) plt.stem(x, response, 'm', use_line_collection=True) plt.ylabel('Amplitude', fontsize=15) plt.xlabel(r'n (samples)', fontsize=15) plt.title(r'Impulse response', fontsize=15) plt.subplot(212) step = np.cumsum(response) # Compute step response of the system plt.stem(x, step, 'g', use_line_collection=True) plt.ylabel('Amplitude', fontsize=15) plt.xlabel(r'n (samples)', fontsize=15) plt.title(r'Step response', fontsize=15) plt.subplots_adjust(hspace=0.5) fig.tight_layout() plt.show() # Given specificationFs = 8000 # Sampling frequency in Hzfp = 2000 # Pass band frequency in Hzfs = 500 # Stop Band frequency in HzAp = 3 # Pass band ripple in dBAs = 20 # Stop band attenuation in dB # Compute Sampling parameterTd = 1/Fs # Compute cut-off frequency in radian/secwp = 2*np.pi*fp # pass band frequency in radian/secws = 2*np.pi*fs # stop band frequency in radian/sec # Prewarp the analog frequencyOmega_p = (2/Td)*np.tan(wp*Td/2) # Prewarped analog passband frequencyOmega_s = (2/Td)*np.tan(ws*Td/2) # Prewarped analog stopband frequency # Compute Butterworth filter order and cutoff frequencyN, wc = signal.buttord(Omega_p, Omega_s, Ap, As, analog=True) # Print the values of order and cut-off frequencyprint('Order of the filter=', N)print('Cut-off frequency=', wc) # Design analog Butterworth filter using N and# wc by signal.butter functionb, a = signal.butter(N, wc, 'high', analog=True) # Perform bilinear Transformationz, p = signal.bilinear(b, a, fs=Fs) # Print numerator and denomerator coefficients of the filterprint('Numerator Coefficients:', z)print('Denominator Coefficients:', p) # Call mfreqz function to plot the magnitude# and phase responsemfreqz(z, p, Fs) # Call impz function to plot impulse and step# response of the filterimpz(z, p)", "e": 32939, "s": 29258, "text": null }, { "code": null, "e": 32947, "s": 32939, "text": "Output:" }, { "code": null, "e": 32965, "s": 32947, "text": "gulshankumarar231" }, { "code": null, "e": 32984, "s": 32965, "text": "Data Visualization" }, { "code": null, "e": 32997, "s": 32984, "text": "Python-scipy" }, { "code": null, "e": 33004, "s": 32997, "text": "Python" }, { "code": null, "e": 33102, "s": 33004, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33134, "s": 33102, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 33190, "s": 33134, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 33232, "s": 33190, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 33274, "s": 33232, "text": "Check if element exists in list in Python" }, { "code": null, "e": 33329, "s": 33274, "text": "Selecting rows in pandas DataFrame based on conditions" }, { "code": null, "e": 33351, "s": 33329, "text": "Defaultdict in Python" }, { "code": null, "e": 33390, "s": 33351, "text": "Python | Get unique values from a list" }, { "code": null, "e": 33421, "s": 33390, "text": "Python | os.path.join() method" }, { "code": null, "e": 33450, "s": 33421, "text": "Create a directory in Python" } ]
Hotel Review NLP Classifier for The Hilton | by Ahilan Srivishnumohan | Towards Data Science
In this blog I will go over how I improved my classifier by implementing a neural network model for my NLP project on Hilton Hotel reviews. My model aimed to use sentiment analytics that can classify a review with a score between 1 and 5. Here is a link to the Github link for my project: www.github.com/awesomeahi95/Hotel_Review_NLP I will go over the goal, the processes, and the result of my project. In the modern day, public discussion and critiquing of products and services occurs beyond dedicated mediums, and now also takes place in the realm of social media, too. Online Hilton Hotel reviews are currently found on tripadvisor, trustpilot, and expedia. The majority of reviewers gave a score between 3 and 5, so if a new customer browses online reviews on any of the previously mentioned review sites, they may consider booking a room at the Hilton. What if they already made up their mind from hearing what a friend had to say? Potential customers, could have their hotel choice be influenced by a tweet. Opinions are shared constantly on social media platforms, and are read by their followers. The knowledge, of what these followers think about our hotel, from reading these online posts, could help us better understand the general public’s perception of our hotel. By using sentiment analysis, on existing hotel reviews from Tripadvisor.com, I created a model that can quantify on a scale of 1–5, how the author of a tweet on twitter, or a post on a reddit thread, feels about our hotel, and as a result, also how the readers think about us. If a review classifies to be less than a score of 3, this post/tweet could be looked into, find out why they had a negative opinion of our hotel, and in return fix the problem. A human could relatively easily classify the score (to some degree) of the review above, by just reading the text. We are accustomed to understanding how another person feels about a topic, from the words they use, and the context around it. For a computer to both interpret the opinion of a human and then understand the sentiment there a few stages: Breaking down words to their root form: Using techniques like stemmation and lemmatisation, to break down words like disgusting and disgusted to a root word, disgust. Tokenisation: Using regular expressions to break down the sentence to only words, and no punctuation. Removing Stopwords Words like ‘I’, ‘he’, ‘and’, etc are the most frequent words and could impact the value of other words, so we remove these words. As for my project, that was orientated around hotels, I also removed frequent words such as ‘hotel’, ‘room’, and ‘airport’. Vectorisation (THIS IS THE LEAST HUMAN STEP) Prior to the initial phase of modelling, I had 2 choices: count vectorisation (bag of words) and TF-IDF vectorisation. Both of these methods consider frequency of words as the general metric, although TF-IDF also compares the frequency with the entire corpus for a more meaningful metric. I decided to use TF-IDF vectorisation for my project. So my lemmatised review columns changed from this: To this: So, now a review was represented by a singular value associated to 138 of the most frequent words in my review corpus. I wasn’t too happy about the number of zeros I saw, despite it making sense. Modelling and Testing The machine learning phase. Here I experimented with 5 classification algorithms and 5 ensemble methods too, all with some hyperparameter tuning. For further detail please look at the 3rd Notebook in my Github Repo link I shared at the start of the blog. These were my results: I chose the Stacking (ensemble of Adaboost of Logistic Regression and Logistic Regression) model, as it had a decent training accuracy, and a reasonable validation accuracy. You might be thinking, these accuracies are in the 0.5 to 0.6 range, surely that’s not great. Well, considering this was a 5 way multiclass classification, the odds of randomly choosing one and getting it right was 0.2. Also, these are subjective scores, it can be hard even for a human to be on the dot with choosing the right score. This is better demonstrated with a confusion matrix. You can see most the time the model does predict the correct score, illustrated by the diagonal line. The majority of the error we saw (accuracy being in 50–60% range), you can see here, comes from the adjacent score, e.g. predicting a score of 1 but true score was 2. I was happy with this as the model would still be good enough to distinguish between great reviews, average reviews, and bad reviews. At this point the computer could interpret the inputted the text, and somewhat understand the sentinment from it. I wanted better. Why not make it more human? Neural networks are designed like the functionality of neurons in our brains, so that was probably the change I could make to better my model. Neural Network The preprocessing was a bit different before creating my neural network model. I created a dictionary with keys that were words, all the unique words in the corpus, and values, a number associated with each unique word. I also added 4 special keys for padding, start of review, unknown words, and unused words. In total I had 17317 word entries in the dictionary. This comes from 9405 reviews. word_index_dict['<PAD>'] = 0word_index_dict['<START>'] = 1word_index_dict['<UNK>'] = 2word_index_dict['<UNUSED>'] = 3 Pre-Indexing: Post-Indexing: As a final preprocessing step, I added a padding layer, with a max length of 250 words. Then I trained the model. Neural Network Architecture: The special layer for NLP here is the Embedding Layer. The words are mapped to vectors in a vector space, in my case 16 dimensional vectors. This time each word has a vector based on the words around it, the context. The vectorisation is different to the TF-IDF vectorisation from earlier, we aren’t just looking at frequency based metrics, but actually looking into the impact of each word, given the context. This is starting to feel more human. Now words like good, great, bad, and worse have some more meaningful numbers (vectors) associated with them. New reviews that the model can be tested on, won’t just contain some of these words, but also the words that surround it, that paint a better picture of what the writer of the review is trying to say. This picture could be better explained with more data but the current 9405 review will do a fine job. Testing Neural Network Model The testing accuracy of the model came to 0.5710 which is better than our previous model’s accuracy of 0.5077. So we have an improvement of 7% which is quite significant, but again the best way to observe this 5 way multi-class classifcation is by looking at a confusion matrix. As you can see, the model didn’t predict a review with a score of 5 as a score of 1 once or vice versa. The other mis-classified scores have improved, and the majority of the predictions are closer to the middle diagonal. Application I have designed a demo application of the model using Streamlit and Heroku, that you can try out here: www.hilton-hotel-app.herokuapp.com/ Use a bigger training dataset Try a deeper neural network Reduce complexity of classification to binary classification Implement other pre-made vectorisation methods — word2vec or GloVe
[ { "code": null, "e": 286, "s": 47, "text": "In this blog I will go over how I improved my classifier by implementing a neural network model for my NLP project on Hilton Hotel reviews. My model aimed to use sentiment analytics that can classify a review with a score between 1 and 5." }, { "code": null, "e": 381, "s": 286, "text": "Here is a link to the Github link for my project: www.github.com/awesomeahi95/Hotel_Review_NLP" }, { "code": null, "e": 451, "s": 381, "text": "I will go over the goal, the processes, and the result of my project." }, { "code": null, "e": 621, "s": 451, "text": "In the modern day, public discussion and critiquing of products and services occurs beyond dedicated mediums, and now also takes place in the realm of social media, too." }, { "code": null, "e": 907, "s": 621, "text": "Online Hilton Hotel reviews are currently found on tripadvisor, trustpilot, and expedia. The majority of reviewers gave a score between 3 and 5, so if a new customer browses online reviews on any of the previously mentioned review sites, they may consider booking a room at the Hilton." }, { "code": null, "e": 1327, "s": 907, "text": "What if they already made up their mind from hearing what a friend had to say? Potential customers, could have their hotel choice be influenced by a tweet. Opinions are shared constantly on social media platforms, and are read by their followers. The knowledge, of what these followers think about our hotel, from reading these online posts, could help us better understand the general public’s perception of our hotel." }, { "code": null, "e": 1781, "s": 1327, "text": "By using sentiment analysis, on existing hotel reviews from Tripadvisor.com, I created a model that can quantify on a scale of 1–5, how the author of a tweet on twitter, or a post on a reddit thread, feels about our hotel, and as a result, also how the readers think about us. If a review classifies to be less than a score of 3, this post/tweet could be looked into, find out why they had a negative opinion of our hotel, and in return fix the problem." }, { "code": null, "e": 2023, "s": 1781, "text": "A human could relatively easily classify the score (to some degree) of the review above, by just reading the text. We are accustomed to understanding how another person feels about a topic, from the words they use, and the context around it." }, { "code": null, "e": 2133, "s": 2023, "text": "For a computer to both interpret the opinion of a human and then understand the sentiment there a few stages:" }, { "code": null, "e": 2173, "s": 2133, "text": "Breaking down words to their root form:" }, { "code": null, "e": 2300, "s": 2173, "text": "Using techniques like stemmation and lemmatisation, to break down words like disgusting and disgusted to a root word, disgust." }, { "code": null, "e": 2314, "s": 2300, "text": "Tokenisation:" }, { "code": null, "e": 2402, "s": 2314, "text": "Using regular expressions to break down the sentence to only words, and no punctuation." }, { "code": null, "e": 2421, "s": 2402, "text": "Removing Stopwords" }, { "code": null, "e": 2675, "s": 2421, "text": "Words like ‘I’, ‘he’, ‘and’, etc are the most frequent words and could impact the value of other words, so we remove these words. As for my project, that was orientated around hotels, I also removed frequent words such as ‘hotel’, ‘room’, and ‘airport’." }, { "code": null, "e": 2689, "s": 2675, "text": "Vectorisation" }, { "code": null, "e": 2720, "s": 2689, "text": "(THIS IS THE LEAST HUMAN STEP)" }, { "code": null, "e": 3009, "s": 2720, "text": "Prior to the initial phase of modelling, I had 2 choices: count vectorisation (bag of words) and TF-IDF vectorisation. Both of these methods consider frequency of words as the general metric, although TF-IDF also compares the frequency with the entire corpus for a more meaningful metric." }, { "code": null, "e": 3114, "s": 3009, "text": "I decided to use TF-IDF vectorisation for my project. So my lemmatised review columns changed from this:" }, { "code": null, "e": 3123, "s": 3114, "text": "To this:" }, { "code": null, "e": 3242, "s": 3123, "text": "So, now a review was represented by a singular value associated to 138 of the most frequent words in my review corpus." }, { "code": null, "e": 3319, "s": 3242, "text": "I wasn’t too happy about the number of zeros I saw, despite it making sense." }, { "code": null, "e": 3341, "s": 3319, "text": "Modelling and Testing" }, { "code": null, "e": 3596, "s": 3341, "text": "The machine learning phase. Here I experimented with 5 classification algorithms and 5 ensemble methods too, all with some hyperparameter tuning. For further detail please look at the 3rd Notebook in my Github Repo link I shared at the start of the blog." }, { "code": null, "e": 3619, "s": 3596, "text": "These were my results:" }, { "code": null, "e": 4181, "s": 3619, "text": "I chose the Stacking (ensemble of Adaboost of Logistic Regression and Logistic Regression) model, as it had a decent training accuracy, and a reasonable validation accuracy. You might be thinking, these accuracies are in the 0.5 to 0.6 range, surely that’s not great. Well, considering this was a 5 way multiclass classification, the odds of randomly choosing one and getting it right was 0.2. Also, these are subjective scores, it can be hard even for a human to be on the dot with choosing the right score. This is better demonstrated with a confusion matrix." }, { "code": null, "e": 4584, "s": 4181, "text": "You can see most the time the model does predict the correct score, illustrated by the diagonal line. The majority of the error we saw (accuracy being in 50–60% range), you can see here, comes from the adjacent score, e.g. predicting a score of 1 but true score was 2. I was happy with this as the model would still be good enough to distinguish between great reviews, average reviews, and bad reviews." }, { "code": null, "e": 4698, "s": 4584, "text": "At this point the computer could interpret the inputted the text, and somewhat understand the sentinment from it." }, { "code": null, "e": 4715, "s": 4698, "text": "I wanted better." }, { "code": null, "e": 4886, "s": 4715, "text": "Why not make it more human? Neural networks are designed like the functionality of neurons in our brains, so that was probably the change I could make to better my model." }, { "code": null, "e": 4901, "s": 4886, "text": "Neural Network" }, { "code": null, "e": 4980, "s": 4901, "text": "The preprocessing was a bit different before creating my neural network model." }, { "code": null, "e": 5295, "s": 4980, "text": "I created a dictionary with keys that were words, all the unique words in the corpus, and values, a number associated with each unique word. I also added 4 special keys for padding, start of review, unknown words, and unused words. In total I had 17317 word entries in the dictionary. This comes from 9405 reviews." }, { "code": null, "e": 5413, "s": 5295, "text": "word_index_dict['<PAD>'] = 0word_index_dict['<START>'] = 1word_index_dict['<UNK>'] = 2word_index_dict['<UNUSED>'] = 3" }, { "code": null, "e": 5427, "s": 5413, "text": "Pre-Indexing:" }, { "code": null, "e": 5442, "s": 5427, "text": "Post-Indexing:" }, { "code": null, "e": 5556, "s": 5442, "text": "As a final preprocessing step, I added a padding layer, with a max length of 250 words. Then I trained the model." }, { "code": null, "e": 5585, "s": 5556, "text": "Neural Network Architecture:" }, { "code": null, "e": 5640, "s": 5585, "text": "The special layer for NLP here is the Embedding Layer." }, { "code": null, "e": 5996, "s": 5640, "text": "The words are mapped to vectors in a vector space, in my case 16 dimensional vectors. This time each word has a vector based on the words around it, the context. The vectorisation is different to the TF-IDF vectorisation from earlier, we aren’t just looking at frequency based metrics, but actually looking into the impact of each word, given the context." }, { "code": null, "e": 6033, "s": 5996, "text": "This is starting to feel more human." }, { "code": null, "e": 6445, "s": 6033, "text": "Now words like good, great, bad, and worse have some more meaningful numbers (vectors) associated with them. New reviews that the model can be tested on, won’t just contain some of these words, but also the words that surround it, that paint a better picture of what the writer of the review is trying to say. This picture could be better explained with more data but the current 9405 review will do a fine job." }, { "code": null, "e": 6474, "s": 6445, "text": "Testing Neural Network Model" }, { "code": null, "e": 6753, "s": 6474, "text": "The testing accuracy of the model came to 0.5710 which is better than our previous model’s accuracy of 0.5077. So we have an improvement of 7% which is quite significant, but again the best way to observe this 5 way multi-class classifcation is by looking at a confusion matrix." }, { "code": null, "e": 6975, "s": 6753, "text": "As you can see, the model didn’t predict a review with a score of 5 as a score of 1 once or vice versa. The other mis-classified scores have improved, and the majority of the predictions are closer to the middle diagonal." }, { "code": null, "e": 6987, "s": 6975, "text": "Application" }, { "code": null, "e": 7126, "s": 6987, "text": "I have designed a demo application of the model using Streamlit and Heroku, that you can try out here: www.hilton-hotel-app.herokuapp.com/" }, { "code": null, "e": 7156, "s": 7126, "text": "Use a bigger training dataset" }, { "code": null, "e": 7184, "s": 7156, "text": "Try a deeper neural network" }, { "code": null, "e": 7245, "s": 7184, "text": "Reduce complexity of classification to binary classification" } ]
Difference Between Where and Having Clause in SQL
In this post, we will understand the difference between WHERE clause and HAVING clause in SQL. It is used to filter the records from the table based on a specific condition. It is used to filter the records from the table based on a specific condition. It can be used without the ‘GROUP BY’ clause. It can be used without the ‘GROUP BY’ clause. It can be used with row operations. It can be used with row operations. It can’t contain the aggregate functions. It can’t contain the aggregate functions. It can be used with the ‘SELECT’, ‘UPDATE’, and ‘DELETE’ statements. It can be used with the ‘SELECT’, ‘UPDATE’, and ‘DELETE’ statements. It is used before the ‘GROUP BY’ clause if required. It is used before the ‘GROUP BY’ clause if required. It is used with a single row function such as ‘UPPER’, ‘LOWER’. It is used with a single row function such as ‘UPPER’, ‘LOWER’. It is used to filter out records from the groups based on a specific condition. It is used to filter out records from the groups based on a specific condition. It can’t be used without the ‘GROUP BY’ clause. It can’t be used without the ‘GROUP BY’ clause. It works with the column operation. It works with the column operation. It can contain the aggregate functions. It can contain the aggregate functions. It can only be used with the ‘SELECT’ statement. It can only be used with the ‘SELECT’ statement. It is used after the ‘GROUP BY’ clause. It is used after the ‘GROUP BY’ clause. It can be used with multiple row functions such as ‘SUM’, ‘COUNT’. It can be used with multiple row functions such as ‘SUM’, ‘COUNT’. SELECT column1, column2 FROM table1, table2 WHERE [ conditions ] GROUP BY column1, column2 HAVING [ conditions ] ORDER BY column1, column2
[ { "code": null, "e": 1157, "s": 1062, "text": "In this post, we will understand the difference between WHERE clause and HAVING clause in SQL." }, { "code": null, "e": 1236, "s": 1157, "text": "It is used to filter the records from the table based on a specific condition." }, { "code": null, "e": 1315, "s": 1236, "text": "It is used to filter the records from the table based on a specific condition." }, { "code": null, "e": 1361, "s": 1315, "text": "It can be used without the ‘GROUP BY’ clause." }, { "code": null, "e": 1407, "s": 1361, "text": "It can be used without the ‘GROUP BY’ clause." }, { "code": null, "e": 1443, "s": 1407, "text": "It can be used with row operations." }, { "code": null, "e": 1479, "s": 1443, "text": "It can be used with row operations." }, { "code": null, "e": 1521, "s": 1479, "text": "It can’t contain the aggregate functions." }, { "code": null, "e": 1563, "s": 1521, "text": "It can’t contain the aggregate functions." }, { "code": null, "e": 1632, "s": 1563, "text": "It can be used with the ‘SELECT’, ‘UPDATE’, and ‘DELETE’ statements." }, { "code": null, "e": 1701, "s": 1632, "text": "It can be used with the ‘SELECT’, ‘UPDATE’, and ‘DELETE’ statements." }, { "code": null, "e": 1754, "s": 1701, "text": "It is used before the ‘GROUP BY’ clause if required." }, { "code": null, "e": 1807, "s": 1754, "text": "It is used before the ‘GROUP BY’ clause if required." }, { "code": null, "e": 1871, "s": 1807, "text": "It is used with a single row function such as ‘UPPER’, ‘LOWER’." }, { "code": null, "e": 1935, "s": 1871, "text": "It is used with a single row function such as ‘UPPER’, ‘LOWER’." }, { "code": null, "e": 2015, "s": 1935, "text": "It is used to filter out records from the groups based on a specific condition." }, { "code": null, "e": 2095, "s": 2015, "text": "It is used to filter out records from the groups based on a specific condition." }, { "code": null, "e": 2143, "s": 2095, "text": "It can’t be used without the ‘GROUP BY’ clause." }, { "code": null, "e": 2191, "s": 2143, "text": "It can’t be used without the ‘GROUP BY’ clause." }, { "code": null, "e": 2227, "s": 2191, "text": "It works with the column operation." }, { "code": null, "e": 2263, "s": 2227, "text": "It works with the column operation." }, { "code": null, "e": 2303, "s": 2263, "text": "It can contain the aggregate functions." }, { "code": null, "e": 2343, "s": 2303, "text": "It can contain the aggregate functions." }, { "code": null, "e": 2392, "s": 2343, "text": "It can only be used with the ‘SELECT’ statement." }, { "code": null, "e": 2441, "s": 2392, "text": "It can only be used with the ‘SELECT’ statement." }, { "code": null, "e": 2481, "s": 2441, "text": "It is used after the ‘GROUP BY’ clause." }, { "code": null, "e": 2521, "s": 2481, "text": "It is used after the ‘GROUP BY’ clause." }, { "code": null, "e": 2588, "s": 2521, "text": "It can be used with multiple row functions such as ‘SUM’, ‘COUNT’." }, { "code": null, "e": 2655, "s": 2588, "text": "It can be used with multiple row functions such as ‘SUM’, ‘COUNT’." }, { "code": null, "e": 2794, "s": 2655, "text": "SELECT column1, column2\nFROM table1, table2\nWHERE [ conditions ]\nGROUP BY column1, column2\nHAVING [ conditions ]\nORDER BY column1, column2" } ]
Project Idea | Collaborative Editor Framework in Real Time - GeeksforGeeks
07 Feb, 2018 NOTE: Most of the contents are taken from Project Report.So you can also download it from drop box links are given down in (Following additional topics may also be provided) Block . Simply you can read it out . Collaborative Editor Framework in Real Time Introduction: A collaborative editor is a form of collaborative software application that allows several people to edit a document or a program collaboratively over a computer network. In real time collaborative editing users can edit the same file simultaneously, whereas in Non-real time collaborative editing, the users do not edit the same file at same time.Since there is very small number of open source solutions to achieve collaborative editing in any web application, we intend to develop a framework in JavaScript through which anyone can achieve this functionality easily.In order to solve the problem of concurrency in such a collaborative editing framework, we will be using operational transformation. Also in order to improve upon the traditional approach, we will consider using a hierarchical representation of text rather than the linear one.Real-time operation is an important aspect to be considered in the design of collaborative editors as users should be able to see the effects of their own actions immediately and those of other users as soon as possible. We will achieve this through web sockets The problem of concurrency in collaborative editing is a well researched problem. People have suggested turn taking algorithm (Greenberg, 1991) allowing only one active participant at a time. Such an algorithm lacks concurrency and locks the document. Other approaches like locking (Greenberg and Marwood, 1994) guarantees that users access objects in the shared workspace one at a time. Concurrent editing is allowed only if users are locking and editing different objects.The operational transformation approach has been identified as an appropriate approach for maintaining consistency of the copies of the shared document in real-time collaborative editing systems Google Wave, a real-time collaboration tool which has been in open beta for the last several months. The treeOPT algorithm (Ignat and Norrie, 2003) improves upon operational transformation by considering hierarchical representation of the shared document in their research paper.[2] The approach is claimed to be increasing the efficiency of operational transformation compared to traditional approaches. Conceptual framework: MethodologyIn order to ensure high responsiveness we will be using a replicated architecture where users will work on their own copy of the shared document. Only changes done are transmitted to other users.Here is the control flow of such architecture: Each collaborator will hold a copy of the shared document along with the server. Whenever any of the shared copies will be edited, operations are calculated and transmitted to the server. To ensure real time transmission, we will leverage the power of web sockets. In case different users are updating different part of the same document, server applies the changes to its copy and forwards the changes to other collaborators. In case different users are trying to update the same part of document (for e.g. trying to add string to same location), i.e., concurrency occurs, server will need to resolve the race condition and one of the collaborators will be able to commit its changes. Now the actual problem starts. The server’s copy of the document and copy of the other clients have diverged. The above problem of server’s copy and client’s copy being diverged can be represented through this image. Suppose server applied operation b on the document and client applied operation a on the document. This has caused both the copies to “diverge” from each other. In order to resolve the problem, or to “converge” both the copies to same version, we will use operational transformation. Operational transformation adjusts operation a with respect to b and operation b with respect to a. The final results must be such that the adjusted operations cause the diverged copies to converge. Mathematically this can be written as: OT(a, b) = (a', b') such that: apply(apply(str, a), b') = apply(apply(str, b) In other words transformation function takes two operations, one server and one client and produces a pair of operations. These operations can be applied to their counterpart’s end state to produce exactly the same state when complete . As the fig 2 shows, after applying operation b’ to client’s copy and operation a’ to server’s copy they are now in same state.Using operational transformation on a linear representation of text is not very efficient. In order to improve performance we will use the treeOPT algorithm’s approach. We will represent the text in hierarchical order Using operational transformation on a linear representation of text is not very efficient. In order to improve performance we will use the treeOPT algorithm’s approach. We will represent the text in hierarchical order. In such hierarchical representation, each node holds its own history. Operational transformation can now be applied on respective node rather than on the entire document. This reduces the overhead of going through history of entire text, as now we just have to go through history of only respective node. Data structures and Algorithms Tree operational Transformation Algorithm Definitions Node : A node N is a structure of the form N =, where Level: is a granularity level, level?{0, 1, 2, 3, 4}, corresponding to the element type represented by node (i.e. document, paragraph, sentence, word or character) Children: is an ordered list of nodes {child1, ..., childn}, level(childi)=level+1, for all i?{1, ..., n} Length : is the length of the node, Length = {1, if level = 4 ? length(childi), otherwise } History: is an ordered list of already executed operations on children nodes Content: is the content of the node, defined only for leaf nodes Content = { undefined, if level < 4 aCharacter, if level = 4 } Composite Operation: A composite operation is a structure of the form cOp=, where: - Level: is a granularity level, level?{1, 2, 3, 4} Type: is the type of the operation, type?{Insertion, Deletion} Position: is a vector of positions position[i]= position for the ith granularity level, i?{1, ..., level} - content is a node representing the content of the operation StateVector: is the state vector of the generating site Initiator: is the initiator site identifier. Given a new causally ready composite operation, cOp, the root node of the hierarchical representation of the local copy of the document, rootNode, and the number of levels in the hierarchical structure of the document, noLevels, the execution form of cOp is returned. treeOPT(rootNode, cOp, noLevels) { currentNode = rootNode; for (l = 1; l <= noLevels; l++) onew = Composite2Simple(cOp, l); eonew = Transform(onew, history(currentNode)); position(cOp)[l] = position(eonew); if (level(cOp) = l) return cOp; currentNode = childi(currentNode), where i=position(eonew); } Client – server communication protocol In order to ensure fast transfer of operation from one client to another we used websockets between client and servers.In order to avoid polling the database on repeated intervals, we used mongoDB which allows us to subscribe to live feed of database tables.Client is made using java and server is based on nodejs . Server works on $ node www { address: '0.0.0.0', family : 'IPv4', port: 3000 } Client request server to share file, now server will share the file though FileID present in MongoDB . It then add user to the requested client’s session using session manager and also can remove user from it.Whenever a change is made by client, operations are sent to history collection and client waits for server’s acknowledgement.If there are further changes on client’s side, they are stored in buffer until the server’s acknowledgement comes. All the changes in buffer are sent once the server acknowledges. Tools Used: Node.js: It is a JavaScript runtime built on chrome’s V8 JavaScript engine. Node.js uses an event-driven, non-blocking I/O model that makes it efficient. MongoDB: is a free and open-source cross-platform document-oriented database program. Classified as a NoSQL database program, MongoDB uses JSON-like documents with schemas. JavaFx: used for making client GUI. Robomongo: is a shell-centric cross-platform MongoDB management tool. Unlike most other MongoDB admin UI tools, Robomongo embeds the actual mongo shell in a tabbed interface with access to a shell command line as well as GUI interaction. Application:A real time collaborative integrated development environment can provide developers with the facility to collaborate over software projects over a network even when developers are thousand of miles away. Real-time Collaborative IDE provide developers with the ability to collaboratively write code, build and test it as well as share their projects with other developers. Chatting with other fellow developers over a project is also possible. Besides several other useful features of a complete IDE including saving snapshots, project management are also provided to ease the entire project development process. Following additional topics may also be provided:1) Github –https://github.com/agnu13/Collaborative-Editor-clientAll the description for running project is given in github repository 2) Project Report and Presentation – Project Documents 3)Base Paper – TreeOPT algorithm: Customizable collaborative editor relying on treeOPT algorithm(Ignat and Norrie, 2003) References Images: [1]. Divergence of server and client copies from online source: http://www.codecommit.com/blog/java/understanding-and-applyingoperational-transformation Citations: [1].Introduction to collaborative editors. From Wikipedia: https://en.wikipedia.org/wiki/Collaborative_real-time_editor [2].In favour of tree representation, excerpt taken from research paper on treeOPT algorithm: Customizable collaborative editor relying on treeOPT algorithm(Ignat and Norrie, 2003) [3].Explanation of basic OT, excerpt taken from online source: http://www.codecommit.com/blog/java/understanding-and-applyingoperational-transformation This article is contributed by Akash Sharan. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Project Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Banking Transaction System using Java How to write a good SRS for your Project E-commerce Website using Django Student record management system using linked list ML | Credit Card Fraud Detection GUI chat application using Tkinter in Python Pizza Shop Billing System using Java Swing How to generate and read QR code with Java using ZXing Library Python | Maintaining Grocery list Handling Ajax request in Django
[ { "code": null, "e": 24476, "s": 24448, "text": "\n07 Feb, 2018" }, { "code": null, "e": 24687, "s": 24476, "text": "NOTE: Most of the contents are taken from Project Report.So you can also download it from drop box links are given down in (Following additional topics may also be provided) Block . Simply you can read it out ." }, { "code": null, "e": 24731, "s": 24687, "text": "Collaborative Editor Framework in Real Time" }, { "code": null, "e": 24745, "s": 24731, "text": "Introduction:" }, { "code": null, "e": 25447, "s": 24745, "text": "A collaborative editor is a form of collaborative software application that allows several people to edit a document or a program collaboratively over a computer network. In real time collaborative editing users can edit the same file simultaneously, whereas in Non-real time collaborative editing, the users do not edit the same file at same time.Since there is very small number of open source solutions to achieve collaborative editing in any web application, we intend to develop a framework in JavaScript through which anyone can achieve this functionality easily.In order to solve the problem of concurrency in such a collaborative editing framework, we will be using operational transformation." }, { "code": null, "e": 25853, "s": 25447, "text": "Also in order to improve upon the traditional approach, we will consider using a hierarchical representation of text rather than the linear one.Real-time operation is an important aspect to be considered in the design of collaborative editors as users should be able to see the effects of their own actions immediately and those of other users as soon as possible. We will achieve this through web sockets" }, { "code": null, "e": 26105, "s": 25853, "text": "The problem of concurrency in collaborative editing is a well researched problem. People have suggested turn taking algorithm (Greenberg, 1991) allowing only one active participant at a time. Such an algorithm lacks concurrency and locks the document." }, { "code": null, "e": 26522, "s": 26105, "text": "Other approaches like locking (Greenberg and Marwood, 1994) guarantees that users access objects in the shared workspace one at a time. Concurrent editing is allowed only if users are locking and editing different objects.The operational transformation approach has been identified as an appropriate approach for maintaining consistency of the copies of the shared document in real-time collaborative editing systems" }, { "code": null, "e": 26623, "s": 26522, "text": "Google Wave, a real-time collaboration tool which has been in open beta for the last several months." }, { "code": null, "e": 26927, "s": 26623, "text": "The treeOPT algorithm (Ignat and Norrie, 2003) improves upon operational transformation by considering hierarchical representation of the shared document in their research paper.[2] The approach is claimed to be increasing the efficiency of operational transformation compared to traditional approaches." }, { "code": null, "e": 26949, "s": 26927, "text": "Conceptual framework:" }, { "code": null, "e": 27202, "s": 26949, "text": "MethodologyIn order to ensure high responsiveness we will be using a replicated architecture where users will work on their own copy of the shared document. Only changes done are transmitted to other users.Here is the control flow of such architecture:" }, { "code": null, "e": 27283, "s": 27202, "text": "Each collaborator will hold a copy of the shared document along with the server." }, { "code": null, "e": 27467, "s": 27283, "text": "Whenever any of the shared copies will be edited, operations are calculated and transmitted to the server. To ensure real time transmission, we will leverage the power of web sockets." }, { "code": null, "e": 27629, "s": 27467, "text": "In case different users are updating different part of the same document, server applies the changes to its copy and forwards the changes to other collaborators." }, { "code": null, "e": 27888, "s": 27629, "text": "In case different users are trying to update the same part of document (for e.g. trying to add string to same location), i.e., concurrency occurs, server will need to resolve the race condition and one of the collaborators will be able to commit its changes." }, { "code": null, "e": 27998, "s": 27888, "text": "Now the actual problem starts. The server’s copy of the document and copy of the other clients have diverged." }, { "code": null, "e": 28389, "s": 27998, "text": "The above problem of server’s copy and client’s copy being diverged can be represented through this image. Suppose server applied operation b on the document and client applied operation a on the document. This has caused both the copies to “diverge” from each other. In order to resolve the problem, or to “converge” both the copies to same version, we will use operational transformation." }, { "code": null, "e": 28627, "s": 28389, "text": "Operational transformation adjusts operation a with respect to b and operation b with respect to a. The final results must be such that the adjusted operations cause the diverged copies to converge. Mathematically this can be written as:" }, { "code": null, "e": 28707, "s": 28627, "text": "OT(a, b) = (a', b') such that:\napply(apply(str, a), b') = apply(apply(str, b) \n" }, { "code": null, "e": 29288, "s": 28707, "text": "In other words transformation function takes two operations, one server and one client and produces a pair of operations. These operations can be applied to their counterpart’s end state to produce exactly the same state when complete . As the fig 2 shows, after applying operation b’ to client’s copy and operation a’ to server’s copy they are now in same state.Using operational transformation on a linear representation of text is not very efficient. In order to improve performance we will use the treeOPT algorithm’s approach. We will represent the text in hierarchical order" }, { "code": null, "e": 29507, "s": 29288, "text": "Using operational transformation on a linear representation of text is not very efficient. In order to improve performance we will use the treeOPT algorithm’s approach. We will represent the text in hierarchical order." }, { "code": null, "e": 29812, "s": 29507, "text": "In such hierarchical representation, each node holds its own history. Operational transformation can now be applied on respective node rather than on the entire document. This reduces the overhead of going through history of entire text, as now we just have to go through history of only respective node." }, { "code": null, "e": 29843, "s": 29812, "text": "Data structures and Algorithms" }, { "code": null, "e": 29885, "s": 29843, "text": "Tree operational Transformation Algorithm" }, { "code": null, "e": 29897, "s": 29885, "text": "Definitions" }, { "code": null, "e": 30586, "s": 29897, "text": "Node : A node N is a structure of the form N =, where \nLevel: is a granularity level, level?{0, 1, 2, 3, 4},\ncorresponding to the element type represented by node \n(i.e. document, paragraph, sentence, word or character) \nChildren: is an ordered list of nodes \n{child1, ..., childn}, level(childi)=level+1, for all i?{1, ..., n} \nLength : is the length of the node,\n \nLength = {1, if level = 4 \n ? length(childi), otherwise \n }\n \nHistory: is an ordered list of already executed operations on children nodes \nContent: is the content of the node, defined only for leaf nodes \n\nContent = { undefined, if level < 4 \n aCharacter, if level = 4 \n } \n" }, { "code": null, "e": 31074, "s": 30586, "text": "Composite Operation: A composite operation \nis a structure of the form cOp=, where: - \nLevel: is a granularity level, level?{1, 2, 3, 4} \nType: is the type of the operation, type?{Insertion, Deletion} \nPosition: is a vector of positions \nposition[i]= position for the ith granularity level, i?{1, ..., level}\n- content is a node representing the content of the operation \nStateVector: is the state vector of the generating site \nInitiator: is the initiator site identifier.\n" }, { "code": null, "e": 31342, "s": 31074, "text": "Given a new causally ready composite operation, cOp, the root node of the hierarchical representation of the local copy of the document, rootNode, and the number of levels in the hierarchical structure of the document, noLevels, the execution form of cOp is returned." }, { "code": null, "e": 31680, "s": 31342, "text": "treeOPT(rootNode, cOp, noLevels) { \ncurrentNode = rootNode; \nfor (l = 1; l <= noLevels; l++) \nonew = Composite2Simple(cOp, l); \neonew = Transform(onew, history(currentNode)); \nposition(cOp)[l] = position(eonew); \nif (level(cOp) = l) \nreturn cOp; \n currentNode = childi(currentNode), where i=position(eonew); \n} \n \n" }, { "code": null, "e": 31719, "s": 31680, "text": "Client – server communication protocol" }, { "code": null, "e": 32051, "s": 31719, "text": "In order to ensure fast transfer of operation from one client to another we used websockets between client and servers.In order to avoid polling the database on repeated intervals, we used mongoDB which allows us to subscribe to live feed of database tables.Client is made using java and server is based on nodejs . Server works on" }, { "code": null, "e": 32122, "s": 32051, "text": " \n$ node www { address: '0.0.0.0', family : 'IPv4', port: 3000 } \n" }, { "code": null, "e": 32636, "s": 32122, "text": "Client request server to share file, now server will share the file though FileID present in MongoDB . It then add user to the requested client’s session using session manager and also can remove user from it.Whenever a change is made by client, operations are sent to history collection and client waits for server’s acknowledgement.If there are further changes on client’s side, they are stored in buffer until the server’s acknowledgement comes. All the changes in buffer are sent once the server acknowledges." }, { "code": null, "e": 32648, "s": 32636, "text": "Tools Used:" }, { "code": null, "e": 32802, "s": 32648, "text": "Node.js: It is a JavaScript runtime built on chrome’s V8 JavaScript engine. Node.js uses an event-driven, non-blocking I/O model that makes it efficient." }, { "code": null, "e": 32975, "s": 32802, "text": "MongoDB: is a free and open-source cross-platform document-oriented database program. Classified as a NoSQL database program, MongoDB uses JSON-like documents with schemas." }, { "code": null, "e": 33011, "s": 32975, "text": "JavaFx: used for making client GUI." }, { "code": null, "e": 33249, "s": 33011, "text": "Robomongo: is a shell-centric cross-platform MongoDB management tool. Unlike most other MongoDB admin UI tools, Robomongo embeds the actual mongo shell in a tabbed interface with access to a shell command line as well as GUI interaction." }, { "code": null, "e": 33873, "s": 33249, "text": "Application:A real time collaborative integrated development environment can provide developers with the facility to collaborate over software projects over a network even when developers are thousand of miles away. Real-time Collaborative IDE provide developers with the ability to collaboratively write code, build and test it as well as share their projects with other developers. Chatting with other fellow developers over a project is also possible. Besides several other useful features of a complete IDE including saving snapshots, project management are also provided to ease the entire project development process." }, { "code": null, "e": 34056, "s": 33873, "text": "Following additional topics may also be provided:1) Github –https://github.com/agnu13/Collaborative-Editor-clientAll the description for running project is given in github repository" }, { "code": null, "e": 34111, "s": 34056, "text": "2) Project Report and Presentation – Project Documents" }, { "code": null, "e": 34232, "s": 34111, "text": "3)Base Paper – TreeOPT algorithm: Customizable collaborative editor relying on treeOPT algorithm(Ignat and Norrie, 2003)" }, { "code": null, "e": 34243, "s": 34232, "text": "References" }, { "code": null, "e": 34404, "s": 34243, "text": "Images: [1]. Divergence of server and client copies from online source: http://www.codecommit.com/blog/java/understanding-and-applyingoperational-transformation" }, { "code": null, "e": 34415, "s": 34404, "text": "Citations:" }, { "code": null, "e": 34535, "s": 34415, "text": "[1].Introduction to collaborative editors. From Wikipedia: https://en.wikipedia.org/wiki/Collaborative_real-time_editor" }, { "code": null, "e": 34716, "s": 34535, "text": "[2].In favour of tree representation, excerpt taken from research paper on treeOPT algorithm: Customizable collaborative editor relying on treeOPT algorithm(Ignat and Norrie, 2003)" }, { "code": null, "e": 34868, "s": 34716, "text": "[3].Explanation of basic OT, excerpt taken from online source: http://www.codecommit.com/blog/java/understanding-and-applyingoperational-transformation" }, { "code": null, "e": 35168, "s": 34868, "text": "This article is contributed by Akash Sharan. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 35293, "s": 35168, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 35301, "s": 35293, "text": "Project" }, { "code": null, "e": 35399, "s": 35301, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 35408, "s": 35399, "text": "Comments" }, { "code": null, "e": 35421, "s": 35408, "text": "Old Comments" }, { "code": null, "e": 35459, "s": 35421, "text": "Banking Transaction System using Java" }, { "code": null, "e": 35500, "s": 35459, "text": "How to write a good SRS for your Project" }, { "code": null, "e": 35532, "s": 35500, "text": "E-commerce Website using Django" }, { "code": null, "e": 35583, "s": 35532, "text": "Student record management system using linked list" }, { "code": null, "e": 35616, "s": 35583, "text": "ML | Credit Card Fraud Detection" }, { "code": null, "e": 35661, "s": 35616, "text": "GUI chat application using Tkinter in Python" }, { "code": null, "e": 35704, "s": 35661, "text": "Pizza Shop Billing System using Java Swing" }, { "code": null, "e": 35767, "s": 35704, "text": "How to generate and read QR code with Java using ZXing Library" }, { "code": null, "e": 35801, "s": 35767, "text": "Python | Maintaining Grocery list" } ]