title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
Xamarin - Android Activity Lifecycle
When a user navigates through an Android App, a series of events occurs. For example, when a user launches an app, e.g., the Facebook App, it starts and becomes visible on the foreground to the user, onCreate() → onStart() → onResume(). If another activity starts, e.g., a phone call comes in, then the Facebook app will go to the background and the call comes to the foreground. We now have two processes running. onPause() --- > onStop() When the phone call ends, the Facebook app returns to the foreground. Three methods are called. onRestart() --- > onStart() --- > onResume() There are 7 lifecycle processes in an Android activity. They include − onCreate − It is called when the activity is first created. onCreate − It is called when the activity is first created. onStart − It is called when the activity starts and becomes visible to the user. onStart − It is called when the activity starts and becomes visible to the user. onResume − It is called when the activity starts interacting with the user. User input takes place at this stage. onResume − It is called when the activity starts interacting with the user. User input takes place at this stage. onPause − It is called when the activity runs in the background but has not yet been killed. onPause − It is called when the activity runs in the background but has not yet been killed. onStop − It is called when the activity is no longer visible to the user. onStop − It is called when the activity is no longer visible to the user. onRestart − It is called after the activity has stopped, before starting again. It is normally called when a user goes back to a previous activity that had been stopped. onRestart − It is called after the activity has stopped, before starting again. It is normally called when a user goes back to a previous activity that had been stopped. onDestroy − This is the final call before the activity is removed from the memory. onDestroy − This is the final call before the activity is removed from the memory. The following illustration shows the Android Activity Lifecycle −
[ { "code": null, "e": 2335, "s": 2098, "text": "When a user navigates through an Android App, a series of events occurs. For example, when a user launches an app, e.g., the Facebook App, it starts and becomes visible on the foreground to the user, onCreate() → onStart() → onResume()." }, { "code": null, "e": 2513, "s": 2335, "text": "If another activity starts, e.g., a phone call comes in, then the Facebook app will go to the background and the call comes to the foreground. We now have two processes running." }, { "code": null, "e": 2540, "s": 2513, "text": "onPause() --- > onStop()\n" }, { "code": null, "e": 2636, "s": 2540, "text": "When the phone call ends, the Facebook app returns to the foreground. Three methods are called." }, { "code": null, "e": 2682, "s": 2636, "text": "onRestart() --- > onStart() --- > onResume()\n" }, { "code": null, "e": 2753, "s": 2682, "text": "There are 7 lifecycle processes in an Android activity. They include −" }, { "code": null, "e": 2813, "s": 2753, "text": "onCreate − It is called when the activity is first created." }, { "code": null, "e": 2873, "s": 2813, "text": "onCreate − It is called when the activity is first created." }, { "code": null, "e": 2954, "s": 2873, "text": "onStart − It is called when the activity starts and becomes visible to the user." }, { "code": null, "e": 3035, "s": 2954, "text": "onStart − It is called when the activity starts and becomes visible to the user." }, { "code": null, "e": 3149, "s": 3035, "text": "onResume − It is called when the activity starts interacting with the user. User input takes place at this stage." }, { "code": null, "e": 3263, "s": 3149, "text": "onResume − It is called when the activity starts interacting with the user. User input takes place at this stage." }, { "code": null, "e": 3356, "s": 3263, "text": "onPause − It is called when the activity runs in the background but has not yet been killed." }, { "code": null, "e": 3449, "s": 3356, "text": "onPause − It is called when the activity runs in the background but has not yet been killed." }, { "code": null, "e": 3523, "s": 3449, "text": "onStop − It is called when the activity is no longer visible to the user." }, { "code": null, "e": 3597, "s": 3523, "text": "onStop − It is called when the activity is no longer visible to the user." }, { "code": null, "e": 3767, "s": 3597, "text": "onRestart − It is called after the activity has stopped, before starting again. It is normally called when a user goes back to a previous activity that had been stopped." }, { "code": null, "e": 3937, "s": 3767, "text": "onRestart − It is called after the activity has stopped, before starting again. It is normally called when a user goes back to a previous activity that had been stopped." }, { "code": null, "e": 4020, "s": 3937, "text": "onDestroy − This is the final call before the activity is removed from the memory." }, { "code": null, "e": 4103, "s": 4020, "text": "onDestroy − This is the final call before the activity is removed from the memory." } ]
How to Apply a function to multiple columns in Pandas?
24 Oct, 2021 Let us see how to apply a function to multiple columns in a Pandas DataFrame. To execute this task will be using the apply() function. This function applies a function along an axis of the DataFrame. Syntax : DataFrame.apply(parameters)Parameters : func : Function to apply to each column or row. axis : Axis along which the function is applied raw : Determines if row or column is passed as a Series or ndarray object. result_type : ‘expand’, ‘reduce’, ‘broadcast’, None; default None args : Positional arguments to pass to func in addition to the array/series. **kwds : Additional keyword arguments to pass as keywords arguments to func. Returns : Series or DataFrame Example 1 : Prepending “Geek” before every element in two columns. Python3 # import the moduleimport pandas as pd # creating a DataFramedf = pd.DataFrame({'String 1' :['Tom', 'Nick', 'Krish', 'Jack'], 'String 2' :['Jane', 'John', 'Doe', 'Mohan']}) # displaying the DataFramedisplay(df) # function for prepending 'Geek'def prepend_geek(name): return 'Geek ' + name # executing the functiondf[["String 1", "String 2"]] = df[["String 1", "String 2"]].apply(prepend_geek) # displaying the DataFramedisplay(df) Output : Example 2 : Multiplying the value of each element by 2 Python3 # import the moduleimport pandas as pd # creating a DataFramedf = pd.DataFrame({'Integers' :[1, 2, 3, 4, 5], 'Float' :[1.1, 2.2, 3.3, 4.4 ,5.5]}) # displaying the DataFramedisplay(df) # function for prepending 'Geek'def multiply_by_2(number): return 2 * number # executing the functiondf[["Integers", "Float"]] = df[["Integers", "Float"]].apply(multiply_by_2) # displaying the DataFramedisplay(df) Output : saurabh1990aror Python pandas-dataFrame Python Pandas-exercise Python-pandas 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 How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Iterate over a list in Python Python OOPs Concepts Convert integer to string in Python
[ { "code": null, "e": 28, "s": 0, "text": "\n24 Oct, 2021" }, { "code": null, "e": 164, "s": 28, "text": "Let us see how to apply a function to multiple columns in a Pandas DataFrame. To execute this task will be using the apply() function. " }, { "code": null, "e": 231, "s": 164, "text": "This function applies a function along an axis of the DataFrame. " }, { "code": null, "e": 282, "s": 231, "text": "Syntax : DataFrame.apply(parameters)Parameters : " }, { "code": null, "e": 330, "s": 282, "text": "func : Function to apply to each column or row." }, { "code": null, "e": 378, "s": 330, "text": "axis : Axis along which the function is applied" }, { "code": null, "e": 453, "s": 378, "text": "raw : Determines if row or column is passed as a Series or ndarray object." }, { "code": null, "e": 519, "s": 453, "text": "result_type : ‘expand’, ‘reduce’, ‘broadcast’, None; default None" }, { "code": null, "e": 596, "s": 519, "text": "args : Positional arguments to pass to func in addition to the array/series." }, { "code": null, "e": 673, "s": 596, "text": "**kwds : Additional keyword arguments to pass as keywords arguments to func." }, { "code": null, "e": 705, "s": 673, "text": "Returns : Series or DataFrame " }, { "code": null, "e": 774, "s": 705, "text": "Example 1 : Prepending “Geek” before every element in two columns. " }, { "code": null, "e": 782, "s": 774, "text": "Python3" }, { "code": "# import the moduleimport pandas as pd # creating a DataFramedf = pd.DataFrame({'String 1' :['Tom', 'Nick', 'Krish', 'Jack'], 'String 2' :['Jane', 'John', 'Doe', 'Mohan']}) # displaying the DataFramedisplay(df) # function for prepending 'Geek'def prepend_geek(name): return 'Geek ' + name # executing the functiondf[[\"String 1\", \"String 2\"]] = df[[\"String 1\", \"String 2\"]].apply(prepend_geek) # displaying the DataFramedisplay(df)", "e": 1234, "s": 782, "text": null }, { "code": null, "e": 1245, "s": 1234, "text": "Output : " }, { "code": null, "e": 1302, "s": 1245, "text": "Example 2 : Multiplying the value of each element by 2 " }, { "code": null, "e": 1310, "s": 1302, "text": "Python3" }, { "code": "# import the moduleimport pandas as pd # creating a DataFramedf = pd.DataFrame({'Integers' :[1, 2, 3, 4, 5], 'Float' :[1.1, 2.2, 3.3, 4.4 ,5.5]}) # displaying the DataFramedisplay(df) # function for prepending 'Geek'def multiply_by_2(number): return 2 * number # executing the functiondf[[\"Integers\", \"Float\"]] = df[[\"Integers\", \"Float\"]].apply(multiply_by_2) # displaying the DataFramedisplay(df)", "e": 1729, "s": 1310, "text": null }, { "code": null, "e": 1740, "s": 1729, "text": "Output : " }, { "code": null, "e": 1758, "s": 1742, "text": "saurabh1990aror" }, { "code": null, "e": 1782, "s": 1758, "text": "Python pandas-dataFrame" }, { "code": null, "e": 1805, "s": 1782, "text": "Python Pandas-exercise" }, { "code": null, "e": 1819, "s": 1805, "text": "Python-pandas" }, { "code": null, "e": 1826, "s": 1819, "text": "Python" }, { "code": null, "e": 1924, "s": 1826, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1942, "s": 1924, "text": "Python Dictionary" }, { "code": null, "e": 1984, "s": 1942, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 2006, "s": 1984, "text": "Enumerate() in Python" }, { "code": null, "e": 2041, "s": 2006, "text": "Read a file line by line in Python" }, { "code": null, "e": 2073, "s": 2041, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2102, "s": 2073, "text": "*args and **kwargs in Python" }, { "code": null, "e": 2129, "s": 2102, "text": "Python Classes and Objects" }, { "code": null, "e": 2159, "s": 2129, "text": "Iterate over a list in Python" }, { "code": null, "e": 2180, "s": 2159, "text": "Python OOPs Concepts" } ]
BigInteger bitLength() Method in Java
28 Jan, 2022 The java.math.BigInteger.bitLength() method returns the number of bits in the minimal two’s-complement representation of this BigInteger, excluding a sign bit. For positive BigIntegers, this is equivalent to the number of bits in the ordinary binary representation. The bitLength method Computes (ceil(log2(this < 0 ? -this : this+1))).Syntax: public int bitLength() Parameters: The method does not return any parameters.Return Value: The method is used to return the number of bits in the minimal two’s-complement representation of this BigInteger, excluding a sign bit.Examples: Input: value = 2300 Output: 12 Explanation: Binary signed 2's complement of 2300 = 0000100011111100 first four bits are singed bit so exclude them then remaining no of bits = 12. So bitLength in 0000100011111100 = 12. Input: value = 5482549 Output: 23 Below program illustrates the use of bitLength() method of BigInteger. Java // Program to demonstrate bitLength() method of BigInteger import java.math.*; public class GFG { public static void main(String[] args) { // Create BigInteger objects BigInteger biginteger = new BigInteger("2300"); // Call bitLength() method on bigInteger int count = biginteger.bitLength(); String result = "bitLength of " + biginteger + " is " + count; // Print result System.out.println(result); }} bitLength of 2300 is 12 Reference:https://docs.oracle.com/javase/7/docs/api/java/math/BigInteger.html#bitLength() sumitgumber28 Java-BigInteger Java-Functions java-math Java-math-package Java Java-BigInteger Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Object Oriented Programming (OOPs) Concept in Java How to iterate any Map in Java Interfaces in Java HashMap in Java with Examples ArrayList in Java Stream In Java Collections in Java Multidimensional Arrays in Java Singleton Class in Java Set in Java
[ { "code": null, "e": 28, "s": 0, "text": "\n28 Jan, 2022" }, { "code": null, "e": 374, "s": 28, "text": "The java.math.BigInteger.bitLength() method returns the number of bits in the minimal two’s-complement representation of this BigInteger, excluding a sign bit. For positive BigIntegers, this is equivalent to the number of bits in the ordinary binary representation. The bitLength method Computes (ceil(log2(this < 0 ? -this : this+1))).Syntax: " }, { "code": null, "e": 397, "s": 374, "text": "public int bitLength()" }, { "code": null, "e": 613, "s": 397, "text": "Parameters: The method does not return any parameters.Return Value: The method is used to return the number of bits in the minimal two’s-complement representation of this BigInteger, excluding a sign bit.Examples: " }, { "code": null, "e": 868, "s": 613, "text": "Input: value = 2300 \nOutput: 12\nExplanation:\nBinary signed 2's complement of 2300 = 0000100011111100\nfirst four bits are singed bit so exclude them then remaining \nno of bits = 12. So bitLength in 0000100011111100 = 12.\n\nInput: value = 5482549\nOutput: 23" }, { "code": null, "e": 941, "s": 868, "text": "Below program illustrates the use of bitLength() method of BigInteger. " }, { "code": null, "e": 946, "s": 941, "text": "Java" }, { "code": "// Program to demonstrate bitLength() method of BigInteger import java.math.*; public class GFG { public static void main(String[] args) { // Create BigInteger objects BigInteger biginteger = new BigInteger(\"2300\"); // Call bitLength() method on bigInteger int count = biginteger.bitLength(); String result = \"bitLength of \" + biginteger + \" is \" + count; // Print result System.out.println(result); }}", "e": 1421, "s": 946, "text": null }, { "code": null, "e": 1446, "s": 1421, "text": "bitLength of 2300 is 12" }, { "code": null, "e": 1539, "s": 1448, "text": "Reference:https://docs.oracle.com/javase/7/docs/api/java/math/BigInteger.html#bitLength() " }, { "code": null, "e": 1553, "s": 1539, "text": "sumitgumber28" }, { "code": null, "e": 1569, "s": 1553, "text": "Java-BigInteger" }, { "code": null, "e": 1584, "s": 1569, "text": "Java-Functions" }, { "code": null, "e": 1594, "s": 1584, "text": "java-math" }, { "code": null, "e": 1612, "s": 1594, "text": "Java-math-package" }, { "code": null, "e": 1617, "s": 1612, "text": "Java" }, { "code": null, "e": 1633, "s": 1617, "text": "Java-BigInteger" }, { "code": null, "e": 1638, "s": 1633, "text": "Java" }, { "code": null, "e": 1736, "s": 1638, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1787, "s": 1736, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 1818, "s": 1787, "text": "How to iterate any Map in Java" }, { "code": null, "e": 1837, "s": 1818, "text": "Interfaces in Java" }, { "code": null, "e": 1867, "s": 1837, "text": "HashMap in Java with Examples" }, { "code": null, "e": 1885, "s": 1867, "text": "ArrayList in Java" }, { "code": null, "e": 1900, "s": 1885, "text": "Stream In Java" }, { "code": null, "e": 1920, "s": 1900, "text": "Collections in Java" }, { "code": null, "e": 1952, "s": 1920, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 1976, "s": 1952, "text": "Singleton Class in Java" } ]
How to create a progress bar animation using HTML and CSS ? - GeeksforGeeks
03 Sep, 2021 In this mini Web Development project we will utilize CSS animations and create a progress bar using them. The progress bar will start from zero and go to a certain extent as we want. The progress bar is basically showing the expertise of a programmer in different languages in animated form. Prerequisite: Basics of HTML like tags, div, id, class and basics of CSS like margin, padding, color, font, and animations etc. Approach: First we will create basic structure using HTML. Inside the body tag, we will create a division and give it a class so that later it can be targeted using CSS. Inside that div, we will create several divs for each language that we want to showcase and use <h2> tag to name them e.g. HTML, CSS, C/C++, Java etc. In the CSS section, initially we will give margin, padding and background color to the body. After that we will target each h2 tag and give animation effect, font size, font color etc. In the CSS section, we will also give border box design to each component and assign orange color to beautify the design. Example: HTML <!DOCTYPE html><html lang="en"> <head> <style> * { margin: 0; padding: 0; box-sizing: border-box; } /* Styling the body of the page */ body { height: 100vh; display: flex; justify-content: center; align-items: center; background-color: #010101; } /* Stylingthe last h2 tag by giving margin bottom */ .progress-bar-container:not(:last-child) { margin-bottom: 50px; } /* Styling the h2 tag by giving color, letter spacing, font-size etc.*/ .progress-bar-container h2 { font-family: Arial, Helvetica, sans-serif; color: #eee; letter-spacing: 1px; font-size: 20px; } /* Styling the border and box effect of the progress bar*/ .progress-bar { width: 800px; height: 5px; margin-top: 10px; border: 1px solid #565656; border-radius: 5px; box-shadow: 0 0 10px rgb(245, 159, 0); } /* Stylingthe background color of each animation and border radius */ .percentage { display: block; height: 100%; background-color: orange; border-radius: 5px; animation: progress 1500ms ease-in 1; } /* Assigning width of each languages*/ .c { width: 85%; } .java { width: 70%; } .python { width: 55%; } .html { width: 75%; } .css { width: 65%; } .javascript { width: 55%; } /* Animating the progress bar by initially starting from 0*/ @keyframes progress { from { width: 0; } } </style></head> <body> <div class="skills"> <div class="progress-bar-container"> <h2>C/C++</h2> <div class="progress-bar"> <span class="percentage c"></span> </div> </div> <div class="progress-bar-container"> <h2>Java</h2> <div class="progress-bar"> <span class="percentage java"></span> </div> </div> <div class="progress-bar-container"> <h2>Python</h2> <div class="progress-bar"> <span class="percentage python"></span> </div> </div> <div class="progress-bar-container"> <h2>HTML</h2> <div class="progress-bar"> <span class="percentage html"></span> </div> </div> <div class="progress-bar-container"> <h2>CSS</h2> <div class="progress-bar"> <span class="percentage css"></span> </div> </div> <div class="progress-bar-container"> <h2>JavaScript</h2> <div class="progress-bar"> <span class="percentage javascript"></span> </div> </div> </div></body> </html> Output: Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. sagartomar9927 CSS-Properties CSS-Questions CSS-Selectors HTML-Questions CSS HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Design a web page using HTML and CSS How to set space between the flexbox ? Form validation using jQuery Search Bar using HTML, CSS and JavaScript How to style a checkbox using CSS? How to set the default value for an HTML <select> element ? Hide or show elements in HTML using display property How to set input type date in dd-mm-yyyy format using HTML ? REST API (Introduction) How to Insert Form Data into Database using PHP ?
[ { "code": null, "e": 26621, "s": 26593, "text": "\n03 Sep, 2021" }, { "code": null, "e": 26914, "s": 26621, "text": "In this mini Web Development project we will utilize CSS animations and create a progress bar using them. The progress bar will start from zero and go to a certain extent as we want. The progress bar is basically showing the expertise of a programmer in different languages in animated form. " }, { "code": null, "e": 27042, "s": 26914, "text": "Prerequisite: Basics of HTML like tags, div, id, class and basics of CSS like margin, padding, color, font, and animations etc." }, { "code": null, "e": 27052, "s": 27042, "text": "Approach:" }, { "code": null, "e": 27363, "s": 27052, "text": "First we will create basic structure using HTML. Inside the body tag, we will create a division and give it a class so that later it can be targeted using CSS. Inside that div, we will create several divs for each language that we want to showcase and use <h2> tag to name them e.g. HTML, CSS, C/C++, Java etc." }, { "code": null, "e": 27548, "s": 27363, "text": "In the CSS section, initially we will give margin, padding and background color to the body. After that we will target each h2 tag and give animation effect, font size, font color etc." }, { "code": null, "e": 27670, "s": 27548, "text": "In the CSS section, we will also give border box design to each component and assign orange color to beautify the design." }, { "code": null, "e": 27679, "s": 27670, "text": "Example:" }, { "code": null, "e": 27684, "s": 27679, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <style> * { margin: 0; padding: 0; box-sizing: border-box; } /* Styling the body of the page */ body { height: 100vh; display: flex; justify-content: center; align-items: center; background-color: #010101; } /* Stylingthe last h2 tag by giving margin bottom */ .progress-bar-container:not(:last-child) { margin-bottom: 50px; } /* Styling the h2 tag by giving color, letter spacing, font-size etc.*/ .progress-bar-container h2 { font-family: Arial, Helvetica, sans-serif; color: #eee; letter-spacing: 1px; font-size: 20px; } /* Styling the border and box effect of the progress bar*/ .progress-bar { width: 800px; height: 5px; margin-top: 10px; border: 1px solid #565656; border-radius: 5px; box-shadow: 0 0 10px rgb(245, 159, 0); } /* Stylingthe background color of each animation and border radius */ .percentage { display: block; height: 100%; background-color: orange; border-radius: 5px; animation: progress 1500ms ease-in 1; } /* Assigning width of each languages*/ .c { width: 85%; } .java { width: 70%; } .python { width: 55%; } .html { width: 75%; } .css { width: 65%; } .javascript { width: 55%; } /* Animating the progress bar by initially starting from 0*/ @keyframes progress { from { width: 0; } } </style></head> <body> <div class=\"skills\"> <div class=\"progress-bar-container\"> <h2>C/C++</h2> <div class=\"progress-bar\"> <span class=\"percentage c\"></span> </div> </div> <div class=\"progress-bar-container\"> <h2>Java</h2> <div class=\"progress-bar\"> <span class=\"percentage java\"></span> </div> </div> <div class=\"progress-bar-container\"> <h2>Python</h2> <div class=\"progress-bar\"> <span class=\"percentage python\"></span> </div> </div> <div class=\"progress-bar-container\"> <h2>HTML</h2> <div class=\"progress-bar\"> <span class=\"percentage html\"></span> </div> </div> <div class=\"progress-bar-container\"> <h2>CSS</h2> <div class=\"progress-bar\"> <span class=\"percentage css\"></span> </div> </div> <div class=\"progress-bar-container\"> <h2>JavaScript</h2> <div class=\"progress-bar\"> <span class=\"percentage javascript\"></span> </div> </div> </div></body> </html>", "e": 30819, "s": 27684, "text": null }, { "code": null, "e": 30827, "s": 30819, "text": "Output:" }, { "code": null, "e": 30964, "s": 30827, "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": 30979, "s": 30964, "text": "sagartomar9927" }, { "code": null, "e": 30994, "s": 30979, "text": "CSS-Properties" }, { "code": null, "e": 31008, "s": 30994, "text": "CSS-Questions" }, { "code": null, "e": 31022, "s": 31008, "text": "CSS-Selectors" }, { "code": null, "e": 31037, "s": 31022, "text": "HTML-Questions" }, { "code": null, "e": 31041, "s": 31037, "text": "CSS" }, { "code": null, "e": 31046, "s": 31041, "text": "HTML" }, { "code": null, "e": 31063, "s": 31046, "text": "Web Technologies" }, { "code": null, "e": 31068, "s": 31063, "text": "HTML" }, { "code": null, "e": 31166, "s": 31068, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31203, "s": 31166, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 31242, "s": 31203, "text": "How to set space between the flexbox ?" }, { "code": null, "e": 31271, "s": 31242, "text": "Form validation using jQuery" }, { "code": null, "e": 31313, "s": 31271, "text": "Search Bar using HTML, CSS and JavaScript" }, { "code": null, "e": 31348, "s": 31313, "text": "How to style a checkbox using CSS?" }, { "code": null, "e": 31408, "s": 31348, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 31461, "s": 31408, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 31522, "s": 31461, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" }, { "code": null, "e": 31546, "s": 31522, "text": "REST API (Introduction)" } ]
Print N lines of 4 numbers such that every pair among 4 numbers has a GCD K - GeeksforGeeks
11 Nov, 2021 Given N and K, the task is to print N lines where each line contains 4 numbers such that every among those 4 numbers has a GCD K and the maximum number used in N*4 should be minimized.Note: In case of multiple outputs, print any one. Examples: Input: N = 1, K = 1 Output: 1 2 3 5 Every pair among 1, 2, 3 and 5 gives a GCD K and the largest number among these is 5 which the minimum possible. Input: 2 2 Output: 2 4 6 22 14 18 10 16In the above input, the maximum number is 22, which is the minimum possible to make 2 lines of 4 numbers. Approach: The first observation is that if we can solve the given problem for K=1, we can solve the problem with GCD K by simply multiplying the answers with K. We know that any three consecutive odd numbers have a GCD 1 always when paired, so three numbers of every line can be easily obtained. Hence the lines will look like: 1 3 5 _ 7 9 11 _ 13 15 17 _ . . . An even number cannot be inserted always, because inserting 6 in third line will give GCD(6, 9) as 3. So the best number that can be inserted is a number between the first two off numbers of every line. Hence the pattern looks like: 1 2 3 5 7 8 9 11 13 14 15 17 . . . To obtain given GCD K, one can easily multiply K to the obtained numbers. Hence for i-th line: the first number will be k * (6*i+1)the second number will be k * (6*i+1)the third number will be k * (6*i+3)the fourth number will be k * (6*i+5) the first number will be k * (6*i+1) the second number will be k * (6*i+1) the third number will be k * (6*i+3) the fourth number will be k * (6*i+5) The maximum number among N*4 numbers will be k * (6*i – 1) Below is the implementation of the above approach. C++ Java Python3 PHP C# Javascript // C++ implementation of the// above approach #include <bits/stdc++.h>using namespace std; // Function to print N linesvoid printLines(int n, int k){ // Iterate N times to print N lines for (int i = 0; i < n; i++) { cout << k * (6 * i + 1) << " " << k * (6 * i + 2) << " " << k * (6 * i + 3) << " " << k * (6 * i + 5) << endl; }}// Driver Codeint main(){ int n = 2, k = 2; printLines(n, k); return 0;} // Java implementation of the// above approach import java.util.*;import java.lang.*;import java.io.*; class GFG{// Function to print N linesstatic void printLines(int n, int k){ // Iterate N times to print N lines for (int i = 0; i < n; i++) { System.out.println ( k * (6 * i + 1) + " " + k * (6 * i + 2) + " " + k * (6 * i + 3) + " " + k * (6 * i + 5) ); }}// Driver Codepublic static void main(String args[]){ int n = 2, k = 2; printLines(n, k);}} # Python implementation of the# above approach. # Function to print N linesdef printLines(n, k) : # Iterate N times to print N lines for i in range(n) : print( k * (6 * i + 1), k * (6 * i + 2), k * (6 * i + 3), k * (6 * i + 5)) # Driver code if __name__ == "__main__" : n, k = 2, 2 printLines(n, k) # This code is contributed by ANKITRAI1 <?php// Function to print N linesfunction printLines($n, $k){ // Iterate N times to print N lines for ($i = 0; $i < $n; $i++) { echo ($k * (6 * $i + 1)); echo (" "); echo ($k * (6 * $i + 2)); echo (" "); echo ($k * (6 * $i + 3)); echo (" "); echo ($k * (6 * $i + 5)); echo ("\n"); }} // Driver Code$n = 2;$k = 2;printLines($n, $k); // This code is contributed// by Shivi_Aggarwal?> // C# implementation of the// above approachusing System; class GFG{// Function to print N linesstatic void printLines(int n, int k){ // Iterate N times to print N lines for (int i = 0; i < n; i++) { Console.WriteLine ( k * (6 * i + 1) + " " + k * (6 * i + 2) + " " + k * (6 * i + 3) + " " + k * (6 * i + 5) ); }} // Driver Codepublic static void Main(){ int n = 2, k = 2; printLines(n, k);}} // This code is contributed// by Akanksha Rai(Abby_akku) <script>// javascript implementation of the// above approach // Function to print N lines function printLines(n , k) { // Iterate N times to print N lines for (i = 0; i < n; i++) { document.write(k * (6 * i + 1) + " " + k * (6 * i + 2) + " " + k * (6 * i + 3) + " " + k * (6 * i + 5)+"<br/>"); } } // Driver Code var n = 2, k = 2; printLines(n, k); // This code is contributed by umadevi9616</script> 2 4 6 10 14 16 18 22 Time Complexity: O(4*N)Auxiliary Space: O(1) ankthon Shivi_Aggarwal tufan_gupta2000 Akanksha_Rai subhammahato348 umadevi9616 ankita_saini GCD-LCM Competitive Programming Mathematical Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Multistage Graph (Shortest Path) Breadth First Traversal ( BFS ) on a 2D array Shortest path in a directed graph by Dijkstra’s algorithm 5 Best Books for Competitive Programming 5 Best Languages for Competitive Programming Program for Fibonacci numbers Write a program to print all permutations of a given string C++ Data Types Set in C++ Standard Template Library (STL) Coin Change | DP-7
[ { "code": null, "e": 26333, "s": 26305, "text": "\n11 Nov, 2021" }, { "code": null, "e": 26578, "s": 26333, "text": "Given N and K, the task is to print N lines where each line contains 4 numbers such that every among those 4 numbers has a GCD K and the maximum number used in N*4 should be minimized.Note: In case of multiple outputs, print any one. Examples: " }, { "code": null, "e": 26728, "s": 26578, "text": "Input: N = 1, K = 1 Output: 1 2 3 5 Every pair among 1, 2, 3 and 5 gives a GCD K and the largest number among these is 5 which the minimum possible. " }, { "code": null, "e": 26874, "s": 26728, "text": "Input: 2 2 Output: 2 4 6 22 14 18 10 16In the above input, the maximum number is 22, which is the minimum possible to make 2 lines of 4 numbers. " }, { "code": null, "e": 27203, "s": 26874, "text": "Approach: The first observation is that if we can solve the given problem for K=1, we can solve the problem with GCD K by simply multiplying the answers with K. We know that any three consecutive odd numbers have a GCD 1 always when paired, so three numbers of every line can be easily obtained. Hence the lines will look like: " }, { "code": null, "e": 27241, "s": 27203, "text": "1 3 5 _ \n7 9 11 _ \n13 15 17 _ \n.\n.\n." }, { "code": null, "e": 27476, "s": 27241, "text": "An even number cannot be inserted always, because inserting 6 in third line will give GCD(6, 9) as 3. So the best number that can be inserted is a number between the first two off numbers of every line. Hence the pattern looks like: " }, { "code": null, "e": 27517, "s": 27476, "text": "1 2 3 5 \n7 8 9 11 \n13 14 15 17 \n.\n.\n." }, { "code": null, "e": 27614, "s": 27517, "text": "To obtain given GCD K, one can easily multiply K to the obtained numbers. Hence for i-th line: " }, { "code": null, "e": 27761, "s": 27614, "text": "the first number will be k * (6*i+1)the second number will be k * (6*i+1)the third number will be k * (6*i+3)the fourth number will be k * (6*i+5)" }, { "code": null, "e": 27798, "s": 27761, "text": "the first number will be k * (6*i+1)" }, { "code": null, "e": 27836, "s": 27798, "text": "the second number will be k * (6*i+1)" }, { "code": null, "e": 27873, "s": 27836, "text": "the third number will be k * (6*i+3)" }, { "code": null, "e": 27911, "s": 27873, "text": "the fourth number will be k * (6*i+5)" }, { "code": null, "e": 28023, "s": 27911, "text": "The maximum number among N*4 numbers will be k * (6*i – 1) Below is the implementation of the above approach. " }, { "code": null, "e": 28027, "s": 28023, "text": "C++" }, { "code": null, "e": 28032, "s": 28027, "text": "Java" }, { "code": null, "e": 28040, "s": 28032, "text": "Python3" }, { "code": null, "e": 28044, "s": 28040, "text": "PHP" }, { "code": null, "e": 28047, "s": 28044, "text": "C#" }, { "code": null, "e": 28058, "s": 28047, "text": "Javascript" }, { "code": "// C++ implementation of the// above approach #include <bits/stdc++.h>using namespace std; // Function to print N linesvoid printLines(int n, int k){ // Iterate N times to print N lines for (int i = 0; i < n; i++) { cout << k * (6 * i + 1) << \" \" << k * (6 * i + 2) << \" \" << k * (6 * i + 3) << \" \" << k * (6 * i + 5) << endl; }}// Driver Codeint main(){ int n = 2, k = 2; printLines(n, k); return 0;}", "e": 28521, "s": 28058, "text": null }, { "code": "// Java implementation of the// above approach import java.util.*;import java.lang.*;import java.io.*; class GFG{// Function to print N linesstatic void printLines(int n, int k){ // Iterate N times to print N lines for (int i = 0; i < n; i++) { System.out.println ( k * (6 * i + 1) + \" \" + k * (6 * i + 2) + \" \" + k * (6 * i + 3) + \" \" + k * (6 * i + 5) ); }}// Driver Codepublic static void main(String args[]){ int n = 2, k = 2; printLines(n, k);}}", "e": 29027, "s": 28521, "text": null }, { "code": "# Python implementation of the# above approach. # Function to print N linesdef printLines(n, k) : # Iterate N times to print N lines for i in range(n) : print( k * (6 * i + 1), k * (6 * i + 2), k * (6 * i + 3), k * (6 * i + 5)) # Driver code if __name__ == \"__main__\" : n, k = 2, 2 printLines(n, k) # This code is contributed by ANKITRAI1", "e": 29441, "s": 29027, "text": null }, { "code": "<?php// Function to print N linesfunction printLines($n, $k){ // Iterate N times to print N lines for ($i = 0; $i < $n; $i++) { echo ($k * (6 * $i + 1)); echo (\" \"); echo ($k * (6 * $i + 2)); echo (\" \"); echo ($k * (6 * $i + 3)); echo (\" \"); echo ($k * (6 * $i + 5)); echo (\"\\n\"); }} // Driver Code$n = 2;$k = 2;printLines($n, $k); // This code is contributed// by Shivi_Aggarwal?>", "e": 29895, "s": 29441, "text": null }, { "code": "// C# implementation of the// above approachusing System; class GFG{// Function to print N linesstatic void printLines(int n, int k){ // Iterate N times to print N lines for (int i = 0; i < n; i++) { Console.WriteLine ( k * (6 * i + 1) + \" \" + k * (6 * i + 2) + \" \" + k * (6 * i + 3) + \" \" + k * (6 * i + 5) ); }} // Driver Codepublic static void Main(){ int n = 2, k = 2; printLines(n, k);}} // This code is contributed// by Akanksha Rai(Abby_akku)", "e": 30451, "s": 29895, "text": null }, { "code": "<script>// javascript implementation of the// above approach // Function to print N lines function printLines(n , k) { // Iterate N times to print N lines for (i = 0; i < n; i++) { document.write(k * (6 * i + 1) + \" \" + k * (6 * i + 2) + \" \" + k * (6 * i + 3) + \" \" + k * (6 * i + 5)+\"<br/>\"); } } // Driver Code var n = 2, k = 2; printLines(n, k); // This code is contributed by umadevi9616</script>", "e": 30960, "s": 30451, "text": null }, { "code": null, "e": 30981, "s": 30960, "text": "2 4 6 10\n14 16 18 22" }, { "code": null, "e": 31028, "s": 30983, "text": "Time Complexity: O(4*N)Auxiliary Space: O(1)" }, { "code": null, "e": 31036, "s": 31028, "text": "ankthon" }, { "code": null, "e": 31051, "s": 31036, "text": "Shivi_Aggarwal" }, { "code": null, "e": 31067, "s": 31051, "text": "tufan_gupta2000" }, { "code": null, "e": 31080, "s": 31067, "text": "Akanksha_Rai" }, { "code": null, "e": 31096, "s": 31080, "text": "subhammahato348" }, { "code": null, "e": 31108, "s": 31096, "text": "umadevi9616" }, { "code": null, "e": 31121, "s": 31108, "text": "ankita_saini" }, { "code": null, "e": 31129, "s": 31121, "text": "GCD-LCM" }, { "code": null, "e": 31153, "s": 31129, "text": "Competitive Programming" }, { "code": null, "e": 31166, "s": 31153, "text": "Mathematical" }, { "code": null, "e": 31179, "s": 31166, "text": "Mathematical" }, { "code": null, "e": 31277, "s": 31179, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31310, "s": 31277, "text": "Multistage Graph (Shortest Path)" }, { "code": null, "e": 31356, "s": 31310, "text": "Breadth First Traversal ( BFS ) on a 2D array" }, { "code": null, "e": 31414, "s": 31356, "text": "Shortest path in a directed graph by Dijkstra’s algorithm" }, { "code": null, "e": 31455, "s": 31414, "text": "5 Best Books for Competitive Programming" }, { "code": null, "e": 31500, "s": 31455, "text": "5 Best Languages for Competitive Programming" }, { "code": null, "e": 31530, "s": 31500, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 31590, "s": 31530, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 31605, "s": 31590, "text": "C++ Data Types" }, { "code": null, "e": 31648, "s": 31605, "text": "Set in C++ Standard Template Library (STL)" } ]
Join Pandas DataFrames matching by substring - GeeksforGeeks
07 Apr, 2021 Prerequisites: Pandas In this article, we will learn how to join two Data Frames matching by substring with python. join(): joins all the elements in an iteration into a single string lambda(): an anonymous method which is declared without a name and can accept any number of parameters find(): gets the initial appearance of any requisite value merge(): merges two dataframes Follow the below steps to join two data frames matched by substring. Create two DataFrames. Join two dataframes using cartesian product Join a duplicate column including equal values in all the DataFrames Join the new column At last, remove the added column in each DataFrame. Then we need to add a new column to the Data frame. To do this we will use the “lambda” along with “find” functions where the output is greater than zero. Now we print the joined data frames matched by substrings . Below is the implementation. Python3 import pandas as pd dataFrame1 = pd.DataFrame([['PQR', 'B1'], ['QRS', 'B2'], ['RDE', 'B3']], columns=['work_name', 'tag_name']) dataFrame2 = pd.DataFrame([['RR', 'T1'], ['QR', 'T2'], ['HG', 'T3'], ['PQ', 'T4']], columns=['sub_work_name', 'extra_tag_value']) dataFrame1['join'] = 1dataFrame2['join'] = 1 dataFrameFull = dataFrame1.merge( dataFrame2, on='join').drop('join', axis=1) dataFrame2.drop('join', axis=1, inplace=True) dataFrameFull['match'] = dataFrameFull.apply( lambda x: x.work_name.find(x.sub_work_name), axis=1).ge(0) print(dataFrameFull[dataFrameFull['match']]) Output: Picked Python pandas-dataFrame Python Pandas-exercise 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 ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python Classes and Objects How to drop one or multiple columns in Pandas Dataframe Defaultdict in Python Python | Get unique values from a list Python | os.path.join() method Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25563, "s": 25535, "text": "\n07 Apr, 2021" }, { "code": null, "e": 25585, "s": 25563, "text": "Prerequisites: Pandas" }, { "code": null, "e": 25680, "s": 25585, "text": "In this article, we will learn how to join two Data Frames matching by substring with python. " }, { "code": null, "e": 25748, "s": 25680, "text": "join(): joins all the elements in an iteration into a single string" }, { "code": null, "e": 25851, "s": 25748, "text": "lambda(): an anonymous method which is declared without a name and can accept any number of parameters" }, { "code": null, "e": 25910, "s": 25851, "text": "find(): gets the initial appearance of any requisite value" }, { "code": null, "e": 25941, "s": 25910, "text": "merge(): merges two dataframes" }, { "code": null, "e": 26010, "s": 25941, "text": "Follow the below steps to join two data frames matched by substring." }, { "code": null, "e": 26033, "s": 26010, "text": "Create two DataFrames." }, { "code": null, "e": 26077, "s": 26033, "text": "Join two dataframes using cartesian product" }, { "code": null, "e": 26146, "s": 26077, "text": "Join a duplicate column including equal values in all the DataFrames" }, { "code": null, "e": 26166, "s": 26146, "text": "Join the new column" }, { "code": null, "e": 26218, "s": 26166, "text": "At last, remove the added column in each DataFrame." }, { "code": null, "e": 26373, "s": 26218, "text": "Then we need to add a new column to the Data frame. To do this we will use the “lambda” along with “find” functions where the output is greater than zero." }, { "code": null, "e": 26433, "s": 26373, "text": "Now we print the joined data frames matched by substrings ." }, { "code": null, "e": 26462, "s": 26433, "text": "Below is the implementation." }, { "code": null, "e": 26470, "s": 26462, "text": "Python3" }, { "code": "import pandas as pd dataFrame1 = pd.DataFrame([['PQR', 'B1'], ['QRS', 'B2'], ['RDE', 'B3']], columns=['work_name', 'tag_name']) dataFrame2 = pd.DataFrame([['RR', 'T1'], ['QR', 'T2'], ['HG', 'T3'], ['PQ', 'T4']], columns=['sub_work_name', 'extra_tag_value']) dataFrame1['join'] = 1dataFrame2['join'] = 1 dataFrameFull = dataFrame1.merge( dataFrame2, on='join').drop('join', axis=1) dataFrame2.drop('join', axis=1, inplace=True) dataFrameFull['match'] = dataFrameFull.apply( lambda x: x.work_name.find(x.sub_work_name), axis=1).ge(0) print(dataFrameFull[dataFrameFull['match']])", "e": 27138, "s": 26470, "text": null }, { "code": null, "e": 27146, "s": 27138, "text": "Output:" }, { "code": null, "e": 27153, "s": 27146, "text": "Picked" }, { "code": null, "e": 27177, "s": 27153, "text": "Python pandas-dataFrame" }, { "code": null, "e": 27200, "s": 27177, "text": "Python Pandas-exercise" }, { "code": null, "e": 27214, "s": 27200, "text": "Python-pandas" }, { "code": null, "e": 27221, "s": 27214, "text": "Python" }, { "code": null, "e": 27319, "s": 27221, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27351, "s": 27319, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27393, "s": 27351, "text": "Check if element exists in list in Python" }, { "code": null, "e": 27435, "s": 27393, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 27462, "s": 27435, "text": "Python Classes and Objects" }, { "code": null, "e": 27518, "s": 27462, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 27540, "s": 27518, "text": "Defaultdict in Python" }, { "code": null, "e": 27579, "s": 27540, "text": "Python | Get unique values from a list" }, { "code": null, "e": 27610, "s": 27579, "text": "Python | os.path.join() method" }, { "code": null, "e": 27639, "s": 27610, "text": "Create a directory in Python" } ]
Python - Dictionary Values Division - GeeksforGeeks
29 Dec, 2019 Sometimes, while working with dictionaries, we might have utility problem in which we need to perform elementary operation among the common keys of dictionaries. This can be extended to any operation to be performed. Let’s discuss division of like key values and ways to solve it in this article. Method #1 : Using dictionary comprehension + keys()The combination of above two can be used to perform this particular task. This is just a shorthand to the longer method of loops and can be used to perform this task in one line. # Python3 code to demonstrate working of# Dictionary Values Division# Using dictionary comprehension + keys() # Initialize dictionariestest_dict1 = {'gfg' : 20, 'is' : 24, 'best' : 100}test_dict2 = {'gfg' : 10, 'is' : 6, 'best' : 10} # printing original dictionaries print("The original dictionary 1 : " + str(test_dict1))print("The original dictionary 2 : " + str(test_dict2)) # Using dictionary comprehension + keys()# Dictionary Values Divisionres = {key: test_dict1[key] // test_dict2.get(key, 0) for key in test_dict1.keys()} # printing result print("The divided dictionary is : " + str(res)) The original dictionary 1 : {'is': 24, 'best': 100, 'gfg': 20} The original dictionary 2 : {'is': 6, 'best': 10, 'gfg': 10} The divided dictionary is : {'is': 4, 'best': 10, 'gfg': 2} Method #2 : Using Counter() + “//” operatorThe combination of above method can be used to perform this particular task. In this, the Counter function converts the dictionary in the form in which the divide operator can perform the task of division. # Python3 code to demonstrate working of# Dictionary Values Division# Using Counter() + "//" operatorfrom collections import Counter # Initialize dictionariestest_dict1 = {'gfg' : 20, 'is' : 24, 'best' : 100}test_dict2 = {'gfg' : 10, 'is' : 6, 'best' : 10} # printing original dictionaries print("The original dictionary 1 : " + str(test_dict1))print("The original dictionary 2 : " + str(test_dict2)) # Using Counter() + "//" operator# Dictionary Values Divisiontemp1 = Counter(test_dict1)temp2 = Counter(test_dict2)res = Counter({key : temp1[key] // temp2[key] for key in temp1}) # printing result print("The division dictionary is : " + str(dict(res))) The original dictionary 1 : {'is': 24, 'best': 100, 'gfg': 20} The original dictionary 2 : {'is': 6, 'best': 10, 'gfg': 10} The divided dictionary is : {'is': 4, 'best': 10, 'gfg': 2} 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 ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? How to drop one or multiple columns in Pandas Dataframe Python Classes and Objects Defaultdict in Python Python | Get dictionary keys as a list Python | Split string into list of characters Python | Convert a list to dictionary How to print without newline in Python?
[ { "code": null, "e": 25537, "s": 25509, "text": "\n29 Dec, 2019" }, { "code": null, "e": 25834, "s": 25537, "text": "Sometimes, while working with dictionaries, we might have utility problem in which we need to perform elementary operation among the common keys of dictionaries. This can be extended to any operation to be performed. Let’s discuss division of like key values and ways to solve it in this article." }, { "code": null, "e": 26064, "s": 25834, "text": "Method #1 : Using dictionary comprehension + keys()The combination of above two can be used to perform this particular task. This is just a shorthand to the longer method of loops and can be used to perform this task in one line." }, { "code": "# Python3 code to demonstrate working of# Dictionary Values Division# Using dictionary comprehension + keys() # Initialize dictionariestest_dict1 = {'gfg' : 20, 'is' : 24, 'best' : 100}test_dict2 = {'gfg' : 10, 'is' : 6, 'best' : 10} # printing original dictionaries print(\"The original dictionary 1 : \" + str(test_dict1))print(\"The original dictionary 2 : \" + str(test_dict2)) # Using dictionary comprehension + keys()# Dictionary Values Divisionres = {key: test_dict1[key] // test_dict2.get(key, 0) for key in test_dict1.keys()} # printing result print(\"The divided dictionary is : \" + str(res))", "e": 26689, "s": 26064, "text": null }, { "code": null, "e": 26874, "s": 26689, "text": "The original dictionary 1 : {'is': 24, 'best': 100, 'gfg': 20}\nThe original dictionary 2 : {'is': 6, 'best': 10, 'gfg': 10}\nThe divided dictionary is : {'is': 4, 'best': 10, 'gfg': 2}\n" }, { "code": null, "e": 27125, "s": 26876, "text": "Method #2 : Using Counter() + “//” operatorThe combination of above method can be used to perform this particular task. In this, the Counter function converts the dictionary in the form in which the divide operator can perform the task of division." }, { "code": "# Python3 code to demonstrate working of# Dictionary Values Division# Using Counter() + \"//\" operatorfrom collections import Counter # Initialize dictionariestest_dict1 = {'gfg' : 20, 'is' : 24, 'best' : 100}test_dict2 = {'gfg' : 10, 'is' : 6, 'best' : 10} # printing original dictionaries print(\"The original dictionary 1 : \" + str(test_dict1))print(\"The original dictionary 2 : \" + str(test_dict2)) # Using Counter() + \"//\" operator# Dictionary Values Divisiontemp1 = Counter(test_dict1)temp2 = Counter(test_dict2)res = Counter({key : temp1[key] // temp2[key] for key in temp1}) # printing result print(\"The division dictionary is : \" + str(dict(res)))", "e": 27784, "s": 27125, "text": null }, { "code": null, "e": 27969, "s": 27784, "text": "The original dictionary 1 : {'is': 24, 'best': 100, 'gfg': 20}\nThe original dictionary 2 : {'is': 6, 'best': 10, 'gfg': 10}\nThe divided dictionary is : {'is': 4, 'best': 10, 'gfg': 2}\n" }, { "code": null, "e": 27996, "s": 27969, "text": "Python dictionary-programs" }, { "code": null, "e": 28003, "s": 27996, "text": "Python" }, { "code": null, "e": 28019, "s": 28003, "text": "Python Programs" }, { "code": null, "e": 28117, "s": 28019, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28149, "s": 28117, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28191, "s": 28149, "text": "Check if element exists in list in Python" }, { "code": null, "e": 28233, "s": 28191, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 28289, "s": 28233, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 28316, "s": 28289, "text": "Python Classes and Objects" }, { "code": null, "e": 28338, "s": 28316, "text": "Defaultdict in Python" }, { "code": null, "e": 28377, "s": 28338, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 28423, "s": 28377, "text": "Python | Split string into list of characters" }, { "code": null, "e": 28461, "s": 28423, "text": "Python | Convert a list to dictionary" } ]
Update a MySQL column with JSON format?
To display records like JSON format, use MySQL concat(). Let us first create a table − mysql> create table DemoTable1373 -> ( -> StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY, -> StudentDetails text -> ); Query OK, 0 rows affected (0.86 sec) Insert some records in the table using insert command. Here, we haven’t inserted anything − mysql> insert into DemoTable1373 values(); Query OK, 1 row affected (0.27 sec) mysql> insert into DemoTable1373 values(); Query OK, 1 row affected (0.08 sec) mysql> insert into DemoTable1373 values(); Query OK, 1 row affected (0.18 sec) Display all records from the table using select statement − mysql> select * from DemoTable1373; This will produce the following output − +-----------+----------------+ | StudentId | StudentDetails | +-----------+----------------+ | 1 | NULL | | 2 | NULL | | 3 | NULL | +-----------+----------------+ 3 rows in set (0.00 sec) Following is the query to update a MySQL field with JSON format − mysql> update DemoTable1373 set StudentDetails=concat("{" "StudentName:", " John ,"," StudentAge:", 21,","," StudentCountryName: "," US","} "); Query OK, 3 rows affected (0.14 sec) Rows matched: 3 Changed: 3 Warnings: 0 Let us check the table records once again − mysql> select * from DemoTable1373; This will produce the following output − +-----------+---------------------------------------------------------------+ | StudentId | StudentDetails | +-----------+---------------------------------------------------------------+ | 1 | {StudentName: John , StudentAge:21, StudentCountryName: US} | | 2 | {StudentName: John , StudentAge:21, StudentCountryName: US} | | 3 | {StudentName: John , StudentAge:21, StudentCountryName: US} | +-----------+---------------------------------------------------------------+ 3 rows in set (0.00 sec)
[ { "code": null, "e": 1149, "s": 1062, "text": "To display records like JSON format, use MySQL concat(). Let us first create a table −" }, { "code": null, "e": 1320, "s": 1149, "text": "mysql> create table DemoTable1373\n -> (\n -> StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY,\n -> StudentDetails text\n -> );\nQuery OK, 0 rows affected (0.86 sec)" }, { "code": null, "e": 1412, "s": 1320, "text": "Insert some records in the table using insert command. Here, we haven’t inserted anything −" }, { "code": null, "e": 1649, "s": 1412, "text": "mysql> insert into DemoTable1373 values();\nQuery OK, 1 row affected (0.27 sec)\nmysql> insert into DemoTable1373 values();\nQuery OK, 1 row affected (0.08 sec)\nmysql> insert into DemoTable1373 values();\nQuery OK, 1 row affected (0.18 sec)" }, { "code": null, "e": 1709, "s": 1649, "text": "Display all records from the table using select statement −" }, { "code": null, "e": 1745, "s": 1709, "text": "mysql> select * from DemoTable1373;" }, { "code": null, "e": 1786, "s": 1745, "text": "This will produce the following output −" }, { "code": null, "e": 2028, "s": 1786, "text": "+-----------+----------------+\n| StudentId | StudentDetails |\n+-----------+----------------+\n| 1 | NULL |\n| 2 | NULL |\n| 3 | NULL |\n+-----------+----------------+\n3 rows in set (0.00 sec)" }, { "code": null, "e": 2094, "s": 2028, "text": "Following is the query to update a MySQL field with JSON format −" }, { "code": null, "e": 2315, "s": 2094, "text": "mysql> update DemoTable1373 set StudentDetails=concat(\"{\" \"StudentName:\", \" John ,\",\" StudentAge:\", 21,\",\",\" StudentCountryName: \",\" US\",\"} \");\nQuery OK, 3 rows affected (0.14 sec)\nRows matched: 3 Changed: 3 Warnings: 0" }, { "code": null, "e": 2359, "s": 2315, "text": "Let us check the table records once again −" }, { "code": null, "e": 2395, "s": 2359, "text": "mysql> select * from DemoTable1373;" }, { "code": null, "e": 2436, "s": 2395, "text": "This will produce the following output −" }, { "code": null, "e": 3007, "s": 2436, "text": "+-----------+---------------------------------------------------------------+\n| StudentId | StudentDetails |\n+-----------+---------------------------------------------------------------+\n| 1 | {StudentName: John , StudentAge:21, StudentCountryName: US} |\n| 2 | {StudentName: John , StudentAge:21, StudentCountryName: US} |\n| 3 | {StudentName: John , StudentAge:21, StudentCountryName: US} |\n+-----------+---------------------------------------------------------------+\n3 rows in set (0.00 sec)" } ]
How to create a link to send email in HTML?
To create a link to send email, use <a> tag, with href attribute. The mailto link is added inside the <a> tag. Just keep in mind to add the email address where you want to receive the email in the mailto link. You can try to run the following code to create a link to send email in HTML. Live Demo <!DOCTYPE html> <html> <head> <title>HTML email link</title> </head> <body> <h2>Contact</h2> <p>For any queries: <a href="mailto:demo@example.com">Contact us</a></p> </body> </html>
[ { "code": null, "e": 1272, "s": 1062, "text": "To create a link to send email, use <a> tag, with href attribute. The mailto link is added inside the <a> tag. Just keep in mind to add the email address where you want to receive the email in the mailto link." }, { "code": null, "e": 1350, "s": 1272, "text": "You can try to run the following code to create a link to send email in HTML." }, { "code": null, "e": 1360, "s": 1350, "text": "Live Demo" }, { "code": null, "e": 1573, "s": 1360, "text": "<!DOCTYPE html>\n<html>\n <head>\n <title>HTML email link</title>\n </head>\n\n <body>\n <h2>Contact</h2>\n <p>For any queries: <a href=\"mailto:demo@example.com\">Contact us</a></p>\n </body>\n</html>" } ]
Find the list elements starting with specific letter in Python
In this article we will find all those elements from a list which start with specific letter. We use the lower function so that the test later can match with the first letter of the the elements in the list irrespective of the case. Then we use the index at 0 so that the first letter of the elements in a list are compared with the test letter. Live Demo listA = ['Mon', 'Tue', 'Wed', 'Thu'] # Test with letter test = 'T' # printing original list print("Given list\n " ,listA) # using lower and idx res = [idx for idx in listA if idx[0].lower() == test.lower()] # print result print("List elements starting with matching letter:\n " ,res) Running the above code gives us the following result − Given list ['Mon', 'Tue', 'Wed', 'Thu'] List elements starting with matching letter: ['Tue', 'Thu'] It is a very straight forward approach in which we use a function startswith. This function Returns true if the element starts with the test letter else it returns false. Live Demo listA = ['Mon', 'Tue', 'Wed', 'Thu'] # Test with letter test = 'T' # printing original list print("Given list\n " ,listA) # using startswith res = [idx for idx in listA if idx.lower().startswith(test.lower())] # print result print("List elements starting with matching letter:\n " ,res) Running the above code gives us the following result − Given list ['Mon', 'Tue', 'Wed', 'Thu'] List elements starting with matching letter: ['Tue', 'Thu']
[ { "code": null, "e": 1156, "s": 1062, "text": "In this article we will find all those elements from a list which start with specific letter." }, { "code": null, "e": 1408, "s": 1156, "text": "We use the lower function so that the test later can match with the first letter of the the elements in the list irrespective of the case. Then we use the index at 0 so that the first letter of the elements in a list are compared with the test letter." }, { "code": null, "e": 1419, "s": 1408, "text": " Live Demo" }, { "code": null, "e": 1703, "s": 1419, "text": "listA = ['Mon', 'Tue', 'Wed', 'Thu']\n# Test with letter\ntest = 'T'\n# printing original list\nprint(\"Given list\\n \" ,listA)\n# using lower and idx\nres = [idx for idx in listA if idx[0].lower() == test.lower()]\n# print result\nprint(\"List elements starting with matching letter:\\n \" ,res)" }, { "code": null, "e": 1758, "s": 1703, "text": "Running the above code gives us the following result −" }, { "code": null, "e": 1858, "s": 1758, "text": "Given list\n['Mon', 'Tue', 'Wed', 'Thu']\nList elements starting with matching letter:\n['Tue', 'Thu']" }, { "code": null, "e": 2029, "s": 1858, "text": "It is a very straight forward approach in which we use a function startswith. This function Returns true if the element starts with the test letter else it returns false." }, { "code": null, "e": 2040, "s": 2029, "text": " Live Demo" }, { "code": null, "e": 2327, "s": 2040, "text": "listA = ['Mon', 'Tue', 'Wed', 'Thu']\n# Test with letter\ntest = 'T'\n# printing original list\nprint(\"Given list\\n \" ,listA)\n# using startswith\nres = [idx for idx in listA if idx.lower().startswith(test.lower())]\n# print result\nprint(\"List elements starting with matching letter:\\n \" ,res)" }, { "code": null, "e": 2382, "s": 2327, "text": "Running the above code gives us the following result −" }, { "code": null, "e": 2482, "s": 2382, "text": "Given list\n['Mon', 'Tue', 'Wed', 'Thu']\nList elements starting with matching letter:\n['Tue', 'Thu']" } ]
How to create a text file and insert data to that file on Android using Kotlin?
This example demonstrates how to create a text file and insert data to that file on Android using Kotlin. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.xml. <?xml version="1.0" encoding="utf-8"?>? <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <TextView android:id="@+id/textView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_marginTop="70dp" android:background="#008080" android:padding="5dp" android:text="TutorialsPoint" android:textColor="#fff" android:textStyle="bold" />? <EditText android:id="@+id/editText" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@+id/textView" android:layout_marginTop="40dp" android:ems="10"> <requestFocus /> </EditText> <Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/editText" android:layout_centerInParent="true" android:layout_margin="5dp" android:background="@android:color/holo_orange_light" android:onClick="saveTextFile" android:text="Save File" android:textColor="@android:color/background_dark" android:textStyle="bold" /> </RelativeLayout> Step 3 − Add the following code to src/MainActivity.kt import android.content.Context import android.os.Bundle import android.view.View import android.widget.EditText import android.widget.Toast import androidx.appcompat.app.AppCompatActivity import java.io.FileOutputStream import java.io.OutputStreamWriter class MainActivity : AppCompatActivity() { lateinit var editText: EditText override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) title = "KotlinApp" editText = findViewById(R.id.editText) } fun saveTextFile(view: View) { try { val fileOutputStream: FileOutputStream = openFileOutput("mytextfile.txt", Context.MODE_PRIVATE) val outputWriter = OutputStreamWriter(fileOutputStream) outputWriter.write(editText.text.toString()) outputWriter.close() //display file saved message Toast.makeText(baseContext, "File saved successfully!", Toast.LENGTH_SHORT).show() } catch (e: Exception) { e.printStackTrace() } } } Step 4 − Add the following code to androidManifest.xml <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.q11"> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen
[ { "code": null, "e": 1168, "s": 1062, "text": "This example demonstrates how to create a text file and insert data to that file on Android using Kotlin." }, { "code": null, "e": 1297, "s": 1168, "text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project." }, { "code": null, "e": 1362, "s": 1297, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 2778, "s": 1362, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>?\n<RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n tools:context=\".MainActivity\">\n <TextView\n android:id=\"@+id/textView\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_centerHorizontal=\"true\"\n android:layout_marginTop=\"70dp\"\n android:background=\"#008080\"\n android:padding=\"5dp\"\n android:text=\"TutorialsPoint\"\n android:textColor=\"#fff\"\n android:textStyle=\"bold\" />?\n <EditText\n android:id=\"@+id/editText\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n android:layout_below=\"@+id/textView\"\n android:layout_marginTop=\"40dp\"\n android:ems=\"10\">\n <requestFocus />\n </EditText>\n <Button\n android:id=\"@+id/button1\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_below=\"@+id/editText\"\n android:layout_centerInParent=\"true\"\n android:layout_margin=\"5dp\"\n android:background=\"@android:color/holo_orange_light\"\n android:onClick=\"saveTextFile\"\n android:text=\"Save File\"\n android:textColor=\"@android:color/background_dark\"\n android:textStyle=\"bold\" />\n</RelativeLayout>" }, { "code": null, "e": 2833, "s": 2778, "text": "Step 3 − Add the following code to src/MainActivity.kt" }, { "code": null, "e": 3894, "s": 2833, "text": "import android.content.Context\nimport android.os.Bundle\nimport android.view.View\nimport android.widget.EditText\nimport android.widget.Toast\nimport androidx.appcompat.app.AppCompatActivity\nimport java.io.FileOutputStream\nimport java.io.OutputStreamWriter\nclass MainActivity : AppCompatActivity() {\n lateinit var editText: EditText\n override fun onCreate(savedInstanceState: Bundle?) {\n super.onCreate(savedInstanceState)\n setContentView(R.layout.activity_main)\n title = \"KotlinApp\"\n editText = findViewById(R.id.editText)\n }\n fun saveTextFile(view: View) {\n try {\n val fileOutputStream: FileOutputStream = openFileOutput(\"mytextfile.txt\", Context.MODE_PRIVATE)\n val outputWriter = OutputStreamWriter(fileOutputStream)\n outputWriter.write(editText.text.toString())\n outputWriter.close()\n //display file saved message\n Toast.makeText(baseContext, \"File saved successfully!\", Toast.LENGTH_SHORT).show()\n }\n catch (e: Exception) {\n e.printStackTrace()\n }\n }\n}" }, { "code": null, "e": 3949, "s": 3894, "text": "Step 4 − Add the following code to androidManifest.xml" }, { "code": null, "e": 4700, "s": 3949, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\n package=\"com.example.q11\">\n<uses-permission android:name=\"android.permission.WRITE_EXTERNAL_STORAGE\" />\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>" }, { "code": null, "e": 5049, "s": 4700, "text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen" } ]
Pascal - Records
Pascal arrays allow you to define type of variables that can hold several data items of the same kind but a record is another user-defined data type available in Pascal which allows you to combine data items of different kinds. Records consist of different fields. Suppose you want to keep track of your books in a library, you might want to track the following attributes about each book − Title Author Subject Book ID To define a record type, you may use the type declaration statement. The record type is defined as − type record-name = record field-1: field-type1; field-2: field-type2; ... field-n: field-typen; end; Here is the way you would declare the Book record − type Books = record title: packed array [1..50] of char; author: packed array [1..50] of char; subject: packed array [1..100] of char; book_id: integer; end; The record variables are defined in the usual way as var r1, r2, ... : record-name; Alternatively, you can directly define a record type variable as − var Books : record title: packed array [1..50] of char; author: packed array [1..50] of char; subject: packed array [1..100] of char; book_id: integer; end; To access any field of a record, we use the member access operator (.). The member access operator is coded as a period between the record variable name and the field that we wish to access. Following is the example to explain usage of structure − program exRecords; type Books = record title: packed array [1..50] of char; author: packed array [1..50] of char; subject: packed array [1..100] of char; book_id: longint; end; var Book1, Book2: Books; (* Declare Book1 and Book2 of type Books *) begin (* book 1 specification *) Book1.title := 'C Programming'; Book1.author := 'Nuha Ali '; Book1.subject := 'C Programming Tutorial'; Book1.book_id := 6495407; (* book 2 specification *) Book2.title := 'Telecom Billing'; Book2.author := 'Zara Ali'; Book2.subject := 'Telecom Billing Tutorial'; Book2.book_id := 6495700; (* print Book1 info *) writeln ('Book 1 title : ', Book1.title); writeln('Book 1 author : ', Book1.author); writeln( 'Book 1 subject : ', Book1.subject); writeln( 'Book 1 book_id : ', Book1.book_id); writeln; (* print Book2 info *) writeln ('Book 2 title : ', Book2.title); writeln('Book 2 author : ', Book2.author); writeln( 'Book 2 subject : ', Book2.subject); writeln( 'Book 2 book_id : ', Book2.book_id); end. When the above code is compiled and executed, it produces the following result − Book 1 title : C Programming Book 1 author : Nuha Ali Book 1 subject : C Programming Tutorial Book 1 book_id : 6495407 Book 2 title : Telecom Billing Book 2 author : Zara Ali Book 2 subject : Telecom Billing Tutorial Book 2 book_id : 6495700 You can pass a record as a subprogram argument in very similar way as you pass any other variable or pointer. You would access the record fields in the similar way as you have accessed in the above example − program exRecords; type Books = record title: packed array [1..50] of char; author: packed array [1..50] of char; subject: packed array [1..100] of char; book_id: longint; end; var Book1, Book2: Books; (* Declare Book1 and Book2 of type Books *) (* procedure declaration *) procedure printBook( var book: Books ); begin (* print Book info *) writeln ('Book title : ', book.title); writeln('Book author : ', book.author); writeln( 'Book subject : ', book.subject); writeln( 'Book book_id : ', book.book_id); end; begin (* book 1 specification *) Book1.title := 'C Programming'; Book1.author := 'Nuha Ali '; Book1.subject := 'C Programming Tutorial'; Book1.book_id := 6495407; (* book 2 specification *) Book2.title := 'Telecom Billing'; Book2.author := 'Zara Ali'; Book2.subject := 'Telecom Billing Tutorial'; Book2.book_id := 6495700; (* print Book1 info *) printbook(Book1); writeln; (* print Book2 info *) printbook(Book2); end. When the above code is compiled and executed, it produces the following result − Book 1 title : C Programming Book 1 author : Nuha Ali Book 1 subject : C Programming Tutorial Book 1 book_id : 6495407 Book 2 title : Telecom Billing Book 2 author : Zara Ali Book 2 subject : Telecom Billing Tutorial Book 2 book_id : 6495700 You can define pointers to records in very similar way as you define pointer to any other variable as follows − type record-ptr = ^ record-name; record-name = record field-1: field-type1; field-2: field-type2; ... field-n: field-typen; end; Now, you can store the address of a record type variable in the above-defined pointer variable. To declare a variable of the created pointer type, you use the var keyword − var r1, r2, ... : record-ptr; Before using these pointers, you must create storage for a record-name type variable, which will be manipulated by these pointers. new(r1); new(r2); To access the members of a record using a pointer to that record, you must use the ^. operator as follows − r1^.feild1 := value1; r1^.feild2 := value2; ... r1^fieldn := valuen; Finally, don't forget to dispose the used storage, when it is no longer in use − dispose(r1); dispose(r2); Let us re-write the first example using a pointer to the Books record. Hope this will be easy for you to understand the concept − program exRecords; type BooksPtr = ^ Books; Books = record title: packed array [1..50] of char; author: packed array [1..50] of char; subject: packed array [1..100] of char; book_id: longint; end; var (* Declare Book1 and Book2 of pointer type that refers to Book type *) Book1, Book2: BooksPtr; begin new(Book1); new(book2); (* book 1 specification *) Book1^.title := 'C Programming'; Book1^.author := 'Nuha Ali '; Book1^.subject := 'C Programming Tutorial'; Book1^.book_id := 6495407; (* book 2 specification *) Book2^.title := 'Telecom Billing'; Book2^.author := 'Zara Ali'; Book2^.subject := 'Telecom Billing Tutorial'; Book2^.book_id := 6495700; (* print Book1 info *) writeln ('Book 1 title : ', Book1^.title); writeln('Book 1 author : ', Book1^.author); writeln( 'Book 1 subject : ', Book1^.subject); writeln( 'Book 1 book_id : ', Book1^.book_id); (* print Book2 info *) writeln ('Book 2 title : ', Book2^.title); writeln('Book 2 author : ', Book2^.author); writeln( 'Book 2 subject : ', Book2^.subject); writeln( 'Book 2 book_id : ', Book2^.book_id); dispose(Book1); dispose(Book2); end. When the above code is compiled and executed, it produces the following result − Book 1 title : C Programming Book 1 author : Nuha Ali Book 1 subject : C Programming Tutorial Book 1 book_id : 6495407 Book 2 title : Telecom Billing Book 2 author : Zara Ali Book 2 subject : Telecom Billing Tutorial Book 2 book_id : 6495700 We have discussed that the members of a record can be accessed using the member access operator (.). This way the name of the record variable has to be written every time. The With statement provides an alternative way to do that. Look at the following code snippet taken from our first example − (* book 1 specification *) Book1.title := 'C Programming'; Book1.author := 'Nuha Ali '; Book1.subject := 'C Programming Tutorial'; Book1.book_id := 6495407; The same assignment could be written using the With statement as − (* book 1 specification *) With Book1 do begin title := 'C Programming'; author := 'Nuha Ali '; subject := 'C Programming Tutorial'; book_id := 6495407; end; 94 Lectures 8.5 hours Stone River ELearning Print Add Notes Bookmark this page
[ { "code": null, "e": 2311, "s": 2083, "text": "Pascal arrays allow you to define type of variables that can hold several data items of the same kind but a record is another user-defined data type available in Pascal which allows you to combine data items of different kinds." }, { "code": null, "e": 2474, "s": 2311, "text": "Records consist of different fields. Suppose you want to keep track of your books in a library, you might want to track the following attributes about each book −" }, { "code": null, "e": 2480, "s": 2474, "text": "Title" }, { "code": null, "e": 2487, "s": 2480, "text": "Author" }, { "code": null, "e": 2495, "s": 2487, "text": "Subject" }, { "code": null, "e": 2503, "s": 2495, "text": "Book ID" }, { "code": null, "e": 2604, "s": 2503, "text": "To define a record type, you may use the type declaration statement. The record type is defined as −" }, { "code": null, "e": 2717, "s": 2604, "text": "type\nrecord-name = record\n field-1: field-type1;\n field-2: field-type2;\n ...\n field-n: field-typen;\nend;" }, { "code": null, "e": 2769, "s": 2717, "text": "Here is the way you would declare the Book record −" }, { "code": null, "e": 2940, "s": 2769, "text": "type \nBooks = record\n title: packed array [1..50] of char;\n author: packed array [1..50] of char;\n subject: packed array [1..100] of char;\n book_id: integer;\nend;" }, { "code": null, "e": 2994, "s": 2940, "text": "The record variables are defined in the usual way as " }, { "code": null, "e": 3028, "s": 2994, "text": "var\n r1, r2, ... : record-name;" }, { "code": null, "e": 3095, "s": 3028, "text": "Alternatively, you can directly define a record type variable as −" }, { "code": null, "e": 3264, "s": 3095, "text": "var\nBooks : record\n title: packed array [1..50] of char;\n author: packed array [1..50] of char;\n subject: packed array [1..100] of char;\n book_id: integer;\nend;" }, { "code": null, "e": 3512, "s": 3264, "text": "To access any field of a record, we use the member access operator (.). The member access operator is coded as a period between the record variable name and the field that we wish to access. Following is the example to explain usage of structure −" }, { "code": null, "e": 4582, "s": 3512, "text": "program exRecords;\ntype\nBooks = record\n title: packed array [1..50] of char;\n author: packed array [1..50] of char;\n subject: packed array [1..100] of char;\n book_id: longint;\nend;\n\nvar\n Book1, Book2: Books; (* Declare Book1 and Book2 of type Books *)\n\nbegin\n (* book 1 specification *)\n Book1.title := 'C Programming';\n Book1.author := 'Nuha Ali '; \n Book1.subject := 'C Programming Tutorial';\n Book1.book_id := 6495407;\n\n (* book 2 specification *)\n Book2.title := 'Telecom Billing';\n Book2.author := 'Zara Ali';\n Book2.subject := 'Telecom Billing Tutorial';\n Book2.book_id := 6495700;\n \n (* print Book1 info *)\n writeln ('Book 1 title : ', Book1.title);\n writeln('Book 1 author : ', Book1.author);\n writeln( 'Book 1 subject : ', Book1.subject);\n writeln( 'Book 1 book_id : ', Book1.book_id);\n writeln; \n\n (* print Book2 info *)\n writeln ('Book 2 title : ', Book2.title);\n writeln('Book 2 author : ', Book2.author);\n writeln( 'Book 2 subject : ', Book2.subject);\n writeln( 'Book 2 book_id : ', Book2.book_id);\nend." }, { "code": null, "e": 4663, "s": 4582, "text": "When the above code is compiled and executed, it produces the following result −" }, { "code": null, "e": 4907, "s": 4663, "text": "Book 1 title : C Programming\nBook 1 author : Nuha Ali\nBook 1 subject : C Programming Tutorial\nBook 1 book_id : 6495407\n\nBook 2 title : Telecom Billing\nBook 2 author : Zara Ali\nBook 2 subject : Telecom Billing Tutorial\nBook 2 book_id : 6495700\n" }, { "code": null, "e": 5115, "s": 4907, "text": "You can pass a record as a subprogram argument in very similar way as you pass any other variable or pointer. You would access the record fields in the similar way as you have accessed in the above example −" }, { "code": null, "e": 6140, "s": 5115, "text": "program exRecords;\ntype\nBooks = record\n title: packed array [1..50] of char;\n author: packed array [1..50] of char;\n subject: packed array [1..100] of char;\n book_id: longint;\nend;\n\nvar\n Book1, Book2: Books; (* Declare Book1 and Book2 of type Books *)\n\n(* procedure declaration *)\nprocedure printBook( var book: Books );\n\nbegin\n (* print Book info *)\n writeln ('Book title : ', book.title);\n writeln('Book author : ', book.author);\n writeln( 'Book subject : ', book.subject);\n writeln( 'Book book_id : ', book.book_id);\nend;\n\nbegin\n (* book 1 specification *)\n Book1.title := 'C Programming';\n Book1.author := 'Nuha Ali '; \n Book1.subject := 'C Programming Tutorial';\n Book1.book_id := 6495407;\n \n (* book 2 specification *)\n Book2.title := 'Telecom Billing';\n Book2.author := 'Zara Ali';\n Book2.subject := 'Telecom Billing Tutorial';\n Book2.book_id := 6495700;\n \n (* print Book1 info *)\n printbook(Book1);\n writeln; \n\n (* print Book2 info *)\n printbook(Book2);\nend." }, { "code": null, "e": 6221, "s": 6140, "text": "When the above code is compiled and executed, it produces the following result −" }, { "code": null, "e": 6465, "s": 6221, "text": "Book 1 title : C Programming\nBook 1 author : Nuha Ali\nBook 1 subject : C Programming Tutorial\nBook 1 book_id : 6495407\n\nBook 2 title : Telecom Billing\nBook 2 author : Zara Ali\nBook 2 subject : Telecom Billing Tutorial\nBook 2 book_id : 6495700\n" }, { "code": null, "e": 6577, "s": 6465, "text": "You can define pointers to records in very similar way as you define pointer to any other variable as follows −" }, { "code": null, "e": 6718, "s": 6577, "text": "type\nrecord-ptr = ^ record-name;\nrecord-name = record\n field-1: field-type1;\n field-2: field-type2;\n ...\n field-n: field-typen;\nend;" }, { "code": null, "e": 6891, "s": 6718, "text": "Now, you can store the address of a record type variable in the above-defined pointer variable. To declare a variable of the created pointer type, you use the var keyword −" }, { "code": null, "e": 6924, "s": 6891, "text": "var\n r1, r2, ... : record-ptr;" }, { "code": null, "e": 7055, "s": 6924, "text": "Before using these pointers, you must create storage for a record-name type variable, which will be manipulated by these pointers." }, { "code": null, "e": 7073, "s": 7055, "text": "new(r1);\nnew(r2);" }, { "code": null, "e": 7181, "s": 7073, "text": "To access the members of a record using a pointer to that record, you must use the ^. operator as follows −" }, { "code": null, "e": 7250, "s": 7181, "text": "r1^.feild1 := value1;\nr1^.feild2 := value2;\n...\nr1^fieldn := valuen;" }, { "code": null, "e": 7331, "s": 7250, "text": "Finally, don't forget to dispose the used storage, when it is no longer in use −" }, { "code": null, "e": 7357, "s": 7331, "text": "dispose(r1);\ndispose(r2);" }, { "code": null, "e": 7487, "s": 7357, "text": "Let us re-write the first example using a pointer to the Books record. Hope this will be easy for you to understand the concept −" }, { "code": null, "e": 8698, "s": 7487, "text": "program exRecords;\ntype\nBooksPtr = ^ Books;\nBooks = record\n title: packed array [1..50] of char;\n author: packed array [1..50] of char;\n subject: packed array [1..100] of char;\n book_id: longint;\nend;\n\nvar\n (* Declare Book1 and Book2 of pointer type that refers to Book type *)\n Book1, Book2: BooksPtr; \n\nbegin\n new(Book1);\n new(book2);\n \n (* book 1 specification *)\n Book1^.title := 'C Programming';\n Book1^.author := 'Nuha Ali '; \n Book1^.subject := 'C Programming Tutorial';\n Book1^.book_id := 6495407;\n \n (* book 2 specification *)\n Book2^.title := 'Telecom Billing';\n Book2^.author := 'Zara Ali';\n Book2^.subject := 'Telecom Billing Tutorial';\n Book2^.book_id := 6495700;\n \n (* print Book1 info *)\n writeln ('Book 1 title : ', Book1^.title);\n writeln('Book 1 author : ', Book1^.author);\n writeln( 'Book 1 subject : ', Book1^.subject);\n writeln( 'Book 1 book_id : ', Book1^.book_id);\n \n (* print Book2 info *)\n writeln ('Book 2 title : ', Book2^.title);\n writeln('Book 2 author : ', Book2^.author);\n writeln( 'Book 2 subject : ', Book2^.subject);\n writeln( 'Book 2 book_id : ', Book2^.book_id);\n \n dispose(Book1); \n dispose(Book2);\nend." }, { "code": null, "e": 8779, "s": 8698, "text": "When the above code is compiled and executed, it produces the following result −" }, { "code": null, "e": 9023, "s": 8779, "text": "Book 1 title : C Programming\nBook 1 author : Nuha Ali\nBook 1 subject : C Programming Tutorial\nBook 1 book_id : 6495407\n\nBook 2 title : Telecom Billing\nBook 2 author : Zara Ali\nBook 2 subject : Telecom Billing Tutorial\nBook 2 book_id : 6495700\n" }, { "code": null, "e": 9254, "s": 9023, "text": "We have discussed that the members of a record can be accessed using the member access operator (.). This way the name of the record variable has to be written every time. The With statement provides an alternative way to do that." }, { "code": null, "e": 9320, "s": 9254, "text": "Look at the following code snippet taken from our first example −" }, { "code": null, "e": 9494, "s": 9320, "text": " (* book 1 specification *)\n Book1.title := 'C Programming';\n Book1.author := 'Nuha Ali '; \n Book1.subject := 'C Programming Tutorial';\n Book1.book_id := 6495407;" }, { "code": null, "e": 9561, "s": 9494, "text": "The same assignment could be written using the With statement as −" }, { "code": null, "e": 9733, "s": 9561, "text": "(* book 1 specification *)\nWith Book1 do\nbegin\n title := 'C Programming';\n author := 'Nuha Ali '; \n subject := 'C Programming Tutorial';\n book_id := 6495407;\nend;" }, { "code": null, "e": 9768, "s": 9733, "text": "\n 94 Lectures \n 8.5 hours \n" }, { "code": null, "e": 9791, "s": 9768, "text": " Stone River ELearning" }, { "code": null, "e": 9798, "s": 9791, "text": " Print" }, { "code": null, "e": 9809, "s": 9798, "text": " Add Notes" } ]
C++ Program to Implement Booth’s Multiplication Algorithm for Multiplication of 2 signed Numbers
Booth’s algorithm is a multiplication algorithm that multiplies two signed binary numbers in 2’s compliment notation. Booth used desk calculators that were faster at shifting than adding and created the algorithm to increase their speed. Begin Put multiplicand in BR and multiplier in QR and then the algorithm works as per the following conditions: 1. If Qn and Qn+1 are same i.e. 00 or 11 perform arithmetic shift by 1 bit. 2. If Qn Qn+1 = 10 do A= A + BR and perform arithmetic shift by 1 bit. 3. If Qn Qn+1 = 01 do A= A – BR and perform arithmetic shift by 1 bit. End #include<iostream> using namespace std; void add(int a[], int x[], int q); void complement(int a[], int n) { int i; int x[8] = { NULL }; x[0] = 1; for (i = 0; i < n; i++) { a[i] = (a[i] + 1) % 2; } add(a, x, n); } void add(int ac[], int x[], int q) { int i, c = 0; for (i = 0; i < q; i++) { ac[i] = ac[i] + x[i] + c; if (ac[i] > 1) { ac[i] = ac[i] % 2; c = 1; }else c = 0; } } void ashr(int ac[], int qr[], int &qn, int q) { int temp, i; temp = ac[0]; qn = qr[0]; cout << "\t\tashr\t\t"; for (i = 0; i < q - 1; i++) { ac[i] = ac[i + 1]; qr[i] = qr[i + 1]; } qr[q - 1] = temp; } void display(int ac[], int qr[], int qrn) { int i; for (i = qrn - 1; i >= 0; i--) cout << ac[i]; cout << " "; for (i = qrn - 1; i >= 0; i--) cout << qr[i]; } int main(int argc, char **argv) { int mt[10], br[10], qr[10], sc, ac[10] = { 0 }; int brn, qrn, i, qn, temp; cout << "\n--Enter the multiplicand and multipier in signed 2's complement form if negative--"; cout << "\n Number of multiplicand bit="; cin >> brn; cout << "\nmultiplicand="; for (i = brn - 1; i >= 0; i--) cin >> br[i]; //multiplicand for (i = brn - 1; i >= 0; i--) mt[i] = br[i]; complement(mt, brn); cout << "\nNo. of multiplier bit="; cin >> qrn; sc = qrn; cout << "Multiplier="; for (i = qrn - 1; i >= 0; i--) cin >> qr[i]; qn = 0; temp = 0; cout << "qn\tq[n+1]\t\tBR\t\tAC\tQR\t\tsc\n"; cout << "\t\t\tinitial\t\t"; display(ac, qr, qrn); cout << "\t\t" << sc << "\n"; while (sc != 0) { cout << qr[0] << "\t" << qn; if ((qn + qr[0]) == 1) { if (temp == 0) { add(ac, mt, qrn); cout << "\t\tsubtracting BR\t"; for (i = qrn - 1; i >= 0; i--) cout << ac[i]; temp = 1; } else if (temp == 1) { add(ac, br, qrn); cout << "\t\tadding BR\t"; for (i = qrn - 1; i >= 0; i--) cout << ac[i]; temp = 0; } cout << "\n\t"; ashr(ac, qr, qn, qrn); } else if (qn - qr[0] == 0) ashr(ac, qr, qn, qrn); display(ac, qr, qrn); cout << "\t"; sc--; cout << "\t" << sc << "\n"; } cout << "Result="; display(ac, qr, qrn); } --Enter the multiplicand and multipier in signed 2's complement form if negative-- Number of multiplicand bit=5 multiplicand=0 1 1 1 1 No. of multiplier bit=5 Multiplier=1 0 1 1 1 qn q[n+1] BR AC QR sc initial 00000 10111 5 1 0 subtracting BR 10001 ashr 11000 11011 4 1 1 ashr 11100 01101 3 1 1 ashr 11110 00110 2 0 1 adding BR 01101 ashr 00110 10011 1 1 0 subtracting BR 10111 ashr 11011 11001 0 Result=11011 11001
[ { "code": null, "e": 1300, "s": 1062, "text": "Booth’s algorithm is a multiplication algorithm that multiplies two signed binary numbers in 2’s compliment notation. Booth used desk calculators that were faster at shifting than adding and created the algorithm to increase their speed." }, { "code": null, "e": 1652, "s": 1300, "text": "Begin\n Put multiplicand in BR and multiplier in QR\n and then the algorithm works as per the following conditions:\n 1. If Qn and Qn+1 are same i.e. 00 or 11 perform arithmetic shift by 1 bit.\n 2. If Qn Qn+1 = 10 do A= A + BR and perform arithmetic shift by 1 bit.\n 3. If Qn Qn+1 = 01 do A= A – BR and perform arithmetic shift by 1 bit.\nEnd" }, { "code": null, "e": 4343, "s": 1652, "text": "#include<iostream>\nusing namespace std;\nvoid add(int a[], int x[], int q);\nvoid complement(int a[], int n) {\n int i;\n int x[8] = { NULL };\n x[0] = 1;\n for (i = 0; i < n; i++) {\n a[i] = (a[i] + 1) % 2;\n }\n add(a, x, n);\n}\nvoid add(int ac[], int x[], int q) {\n int i, c = 0;\n for (i = 0; i < q; i++) {\n ac[i] = ac[i] + x[i] + c;\n if (ac[i] > 1) {\n ac[i] = ac[i] % 2;\n c = 1;\n }else\n c = 0;\n }\n }\n void ashr(int ac[], int qr[], int &qn, int q) {\n int temp, i;\n temp = ac[0];\n qn = qr[0];\n cout << \"\\t\\tashr\\t\\t\";\n for (i = 0; i < q - 1; i++) {\n ac[i] = ac[i + 1];\n qr[i] = qr[i + 1];\n }\n qr[q - 1] = temp;\n }\n void display(int ac[], int qr[], int qrn) {\n int i;\n for (i = qrn - 1; i >= 0; i--)\n cout << ac[i];\n cout << \" \";\n for (i = qrn - 1; i >= 0; i--)\n cout << qr[i];\n }\n int main(int argc, char **argv) {\n int mt[10], br[10], qr[10], sc, ac[10] = { 0 };\n int brn, qrn, i, qn, temp;\n cout << \"\\n--Enter the multiplicand and multipier in signed 2's\n complement form if negative--\";\n cout << \"\\n Number of multiplicand bit=\";\n cin >> brn;\n cout << \"\\nmultiplicand=\";\n for (i = brn - 1; i >= 0; i--)\n cin >> br[i]; //multiplicand\n for (i = brn - 1; i >= 0; i--)\n mt[i] = br[i];\n complement(mt, brn);\n cout << \"\\nNo. of multiplier bit=\";\n cin >> qrn;\n sc = qrn;\n cout << \"Multiplier=\";\n for (i = qrn - 1; i >= 0; i--)\n cin >> qr[i];\n qn = 0;\n temp = 0;\n cout << \"qn\\tq[n+1]\\t\\tBR\\t\\tAC\\tQR\\t\\tsc\\n\";\n cout << \"\\t\\t\\tinitial\\t\\t\";\n display(ac, qr, qrn);\n cout << \"\\t\\t\" << sc << \"\\n\";\n while (sc != 0) {\n cout << qr[0] << \"\\t\" << qn;\n if ((qn + qr[0]) == 1) {\n if (temp == 0) {\n add(ac, mt, qrn);\n cout << \"\\t\\tsubtracting BR\\t\";\n for (i = qrn - 1; i >= 0; i--)\n cout << ac[i];\n temp = 1;\n }\n else if (temp == 1) {\n add(ac, br, qrn);\n cout << \"\\t\\tadding BR\\t\";\n for (i = qrn - 1; i >= 0; i--)\n cout << ac[i];\n temp = 0;\n }\n cout << \"\\n\\t\";\n ashr(ac, qr, qn, qrn);\n }\n else if (qn - qr[0] == 0)\n ashr(ac, qr, qn, qrn);\n display(ac, qr, qrn);\n cout << \"\\t\";\n sc--;\n cout << \"\\t\" << sc << \"\\n\";\n }\n cout << \"Result=\";\n display(ac, qr, qrn);\n}" }, { "code": null, "e": 4759, "s": 4343, "text": "--Enter the multiplicand and multipier in signed 2's complement form if\nnegative--\nNumber of multiplicand bit=5\nmultiplicand=0 1 1 1 1\nNo. of multiplier bit=5\nMultiplier=1 0 1 1 1\nqn q[n+1] BR AC QR sc\ninitial 00000 10111 5\n1 0 subtracting BR 10001\nashr 11000 11011 4\n1 1 ashr 11100 01101 3\n1 1 ashr 11110 00110 2\n0 1 adding BR 01101\nashr 00110 10011 1\n1 0 subtracting BR 10111\nashr 11011 11001 0\nResult=11011 11001" } ]
Postman with Newman & Jenkins
We can integrate Postman with Newman and Jenkins. Newman is used to verify and execute a Collection. To integrate Newman and Jenkins, we have to follow the below steps − Step1 − We have to complete the installation and configuration of Jenkins. The steps to perform this task is discussed in details in the below link − https://www.tutorialspoint.com/jenkins/jenkins_installation.htm Step2 − We have to install npm and Nodejs. For installation of Nodejs can be done from the below link − https://nodejs.org/en/download/current/ Step3 − The npm is allocated with Nodejs so once we download the Nodejs, the npm gets downloaded automatically. Step4 − We have to install Newman with the help of the command: npm install -g newman. Step5 − Open Terminal, navigate to the directory where the Collection is stored. Then run the command: newman run <"file name">. (The file name should always be in inverted quotes). Step6 − Once Jenkins is up and running, it provides an interface: https://localhost:8080. Then click on New Item in the top left corner of the Postman application. Step7 − Choose the option Freestyle Project, enter a project name then click on the OK button. Step8 − Click on the Source Code Management tab and move to the Build section. Select the option Execute shell from the Add build step up dropdown. Step9 − Add the below command in the Execute Shell edit box under the Build tab. newman run <file name> --supress-exit-code 1 The exit code means that Newman execution shall get stopped if any errors are encountered. Finally click on Save. Step10 − Click on Build Now from the left of the Jenkins application. Step11 − After the Build has completed, click on the Console Output link in the sidebar from the Build details screen to get the details of the Newman output.
[ { "code": null, "e": 1232, "s": 1062, "text": "We can integrate Postman with Newman and Jenkins. Newman is used to verify and execute a Collection. To integrate Newman and Jenkins, we have to follow the below steps −" }, { "code": null, "e": 1382, "s": 1232, "text": "Step1 − We have to complete the installation and configuration of Jenkins. The steps to perform this task is discussed in details in the below link −" }, { "code": null, "e": 1446, "s": 1382, "text": "https://www.tutorialspoint.com/jenkins/jenkins_installation.htm" }, { "code": null, "e": 1550, "s": 1446, "text": "Step2 − We have to install npm and Nodejs. For installation of Nodejs can be done from the below link −" }, { "code": null, "e": 1590, "s": 1550, "text": "https://nodejs.org/en/download/current/" }, { "code": null, "e": 1702, "s": 1590, "text": "Step3 − The npm is allocated with Nodejs so once we download the Nodejs, the npm gets downloaded automatically." }, { "code": null, "e": 1789, "s": 1702, "text": "Step4 − We have to install Newman with the help of the command: npm install -g newman." }, { "code": null, "e": 1971, "s": 1789, "text": "Step5 − Open Terminal, navigate to the directory where the Collection is stored. Then run the command: newman run <\"file name\">. (The file name should always be in inverted quotes)." }, { "code": null, "e": 2135, "s": 1971, "text": "Step6 − Once Jenkins is up and running, it provides an interface: https://localhost:8080. Then click on New Item in the top left corner of the Postman application." }, { "code": null, "e": 2230, "s": 2135, "text": "Step7 − Choose the option Freestyle Project, enter a project name then click on the OK button." }, { "code": null, "e": 2378, "s": 2230, "text": "Step8 − Click on the Source Code Management tab and move to the Build section. Select the option Execute shell from the Add build step up dropdown." }, { "code": null, "e": 2459, "s": 2378, "text": "Step9 − Add the below command in the Execute Shell edit box under the Build tab." }, { "code": null, "e": 2504, "s": 2459, "text": "newman run <file name> --supress-exit-code 1" }, { "code": null, "e": 2618, "s": 2504, "text": "The exit code means that Newman execution shall get stopped if any errors are encountered. Finally click on Save." }, { "code": null, "e": 2688, "s": 2618, "text": "Step10 − Click on Build Now from the left of the Jenkins application." }, { "code": null, "e": 2847, "s": 2688, "text": "Step11 − After the Build has completed, click on the Console Output link in the sidebar from the Build details screen to get the details of the Newman output." } ]
turtle.home() function in Python - GeeksforGeeks
21 Jul, 2020 The turtle module provides turtle graphics primitives, in both object-oriented and procedure-oriented ways. Because it uses Tkinter for the underlying graphics, it needs a version of Python installed with Tk support. This function is used to move the turtle to the origin i.e. coordinates (0,0). Whatever, the position of the turtle is, it sets to (0,0) with default direction (facing to east). Syntax : turtle.home() Below is the implementation of the above method with some examples : Example 1 : Python3 # import packageimport turtle # check turtle positionprint(turtle.position()) # motionturtle.forward(100) # check turtle positionprint(turtle.position()) # set turtle to hometurtle.home() # check turtle positionprint(turtle.position()) # motionturtle.right(90)turtle.forward(100) # check turtle positionprint(turtle.position()) # set turtle to hometurtle.home() # check turtle positionprint(turtle.position()) Output : (0.0, 0.0) (100.0, 0.0) (0.0, 0.0) (0.0, -100.0) (0.0, 0.0) Example 2 : Python3 # import packageimport turtle # set turtle speed to fastest# for bettrt understandingsturtle.speed(10) # method to draw a partdef fxn(): # motion turtle.circle(50,180) turtle.right(90) turtle.circle(50,180) # loop to draw patternfor i in range(12): fxn() # set turtle at home turtle.up() turtle.home() turtle.down() # set position turtle.left(30*(i+1)) Output : Python-turtle Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Install PIP on Windows ? How to drop one or multiple columns in Pandas Dataframe How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | Pandas dataframe.groupby() Python | Get unique values from a list Defaultdict in Python Python | os.path.join() method Python Classes and Objects Create a directory in Python
[ { "code": null, "e": 23901, "s": 23873, "text": "\n21 Jul, 2020" }, { "code": null, "e": 24118, "s": 23901, "text": "The turtle module provides turtle graphics primitives, in both object-oriented and procedure-oriented ways. Because it uses Tkinter for the underlying graphics, it needs a version of Python installed with Tk support." }, { "code": null, "e": 24296, "s": 24118, "text": "This function is used to move the turtle to the origin i.e. coordinates (0,0). Whatever, the position of the turtle is, it sets to (0,0) with default direction (facing to east)." }, { "code": null, "e": 24305, "s": 24296, "text": "Syntax :" }, { "code": null, "e": 24320, "s": 24305, "text": "turtle.home()\n" }, { "code": null, "e": 24389, "s": 24320, "text": "Below is the implementation of the above method with some examples :" }, { "code": null, "e": 24401, "s": 24389, "text": "Example 1 :" }, { "code": null, "e": 24409, "s": 24401, "text": "Python3" }, { "code": "# import packageimport turtle # check turtle positionprint(turtle.position()) # motionturtle.forward(100) # check turtle positionprint(turtle.position()) # set turtle to hometurtle.home() # check turtle positionprint(turtle.position()) # motionturtle.right(90)turtle.forward(100) # check turtle positionprint(turtle.position()) # set turtle to hometurtle.home() # check turtle positionprint(turtle.position())", "e": 24830, "s": 24409, "text": null }, { "code": null, "e": 24839, "s": 24830, "text": "Output :" }, { "code": null, "e": 24900, "s": 24839, "text": "(0.0, 0.0)\n(100.0, 0.0)\n(0.0, 0.0)\n(0.0, -100.0)\n(0.0, 0.0)\n" }, { "code": null, "e": 24912, "s": 24900, "text": "Example 2 :" }, { "code": null, "e": 24920, "s": 24912, "text": "Python3" }, { "code": "# import packageimport turtle # set turtle speed to fastest# for bettrt understandingsturtle.speed(10) # method to draw a partdef fxn(): # motion turtle.circle(50,180) turtle.right(90) turtle.circle(50,180) # loop to draw patternfor i in range(12): fxn() # set turtle at home turtle.up() turtle.home() turtle.down() # set position turtle.left(30*(i+1))", "e": 25301, "s": 24920, "text": null }, { "code": null, "e": 25310, "s": 25301, "text": "Output :" }, { "code": null, "e": 25324, "s": 25310, "text": "Python-turtle" }, { "code": null, "e": 25331, "s": 25324, "text": "Python" }, { "code": null, "e": 25429, "s": 25331, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25438, "s": 25429, "text": "Comments" }, { "code": null, "e": 25451, "s": 25438, "text": "Old Comments" }, { "code": null, "e": 25483, "s": 25451, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 25539, "s": 25483, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 25581, "s": 25539, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 25623, "s": 25581, "text": "Check if element exists in list in Python" }, { "code": null, "e": 25659, "s": 25623, "text": "Python | Pandas dataframe.groupby()" }, { "code": null, "e": 25698, "s": 25659, "text": "Python | Get unique values from a list" }, { "code": null, "e": 25720, "s": 25698, "text": "Defaultdict in Python" }, { "code": null, "e": 25751, "s": 25720, "text": "Python | os.path.join() method" }, { "code": null, "e": 25778, "s": 25751, "text": "Python Classes and Objects" } ]
What is ResultSet Concurrency in JDBC?
The concurrency of the ResultSet object determines whether its contents can be updated or not. The Connection interface provides 3 variants of the createStatement() method where one of the method's signature is as follows: Statement createStatement(int resultSetType, int resultSetConcurrency) This method accepts two integer type variables where one represents the type of the ResultSet and the other represents the Concurrency of the ResultSet. The ResultSet interface provides two values to specify the concurrency of the ResultSet. CONCUR_READ_ONLY: If you set this as a value of the concurrency while creating the ResultSet object you cannot update the contents of the ResultSet you can only read/retrieve them. CONCUR_READ_ONLY: If you set this as a value of the concurrency while creating the ResultSet object you cannot update the contents of the ResultSet you can only read/retrieve them. CONCUR_UPDATABLE: If you set this as a value of the concurrency while creating the ResultSet object you can update the contents of the ResultSet. CONCUR_UPDATABLE: If you set this as a value of the concurrency while creating the ResultSet object you can update the contents of the ResultSet. Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); Or, Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet. ResultSet.CONCUR_UPDATABLE);
[ { "code": null, "e": 1157, "s": 1062, "text": "The concurrency of the ResultSet object determines whether its contents can be updated or not." }, { "code": null, "e": 1285, "s": 1157, "text": "The Connection interface provides 3 variants of the createStatement() method where one of the method's signature is as follows:" }, { "code": null, "e": 1356, "s": 1285, "text": "Statement createStatement(int resultSetType, int resultSetConcurrency)" }, { "code": null, "e": 1509, "s": 1356, "text": "This method accepts two integer type variables where one represents the type of the ResultSet and the other represents the Concurrency of the ResultSet." }, { "code": null, "e": 1598, "s": 1509, "text": "The ResultSet interface provides two values to specify the concurrency of the ResultSet." }, { "code": null, "e": 1779, "s": 1598, "text": "CONCUR_READ_ONLY: If you set this as a value of the concurrency while creating the ResultSet object you cannot update the contents of the ResultSet you can only read/retrieve them." }, { "code": null, "e": 1960, "s": 1779, "text": "CONCUR_READ_ONLY: If you set this as a value of the concurrency while creating the ResultSet object you cannot update the contents of the ResultSet you can only read/retrieve them." }, { "code": null, "e": 2106, "s": 1960, "text": "CONCUR_UPDATABLE: If you set this as a value of the concurrency while creating the ResultSet object you can update the contents of the ResultSet." }, { "code": null, "e": 2252, "s": 2106, "text": "CONCUR_UPDATABLE: If you set this as a value of the concurrency while creating the ResultSet object you can update the contents of the ResultSet." }, { "code": null, "e": 2469, "s": 2252, "text": "Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,\nResultSet.CONCUR_READ_ONLY);\nOr,\nStatement stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.\nResultSet.CONCUR_UPDATABLE);" } ]
Print all subsequences of a string in C++
In this problem, we are given a string and we have to print all the subsequences of the string. The substring generated is created by deleting the elements of the string but the order remains the same(i.e. Order cannot be changed). Let’s take an example to understand the topic better − Input: xyz Output: x,y,z,xy,yz,xz,xyz Explanation − In the above example, we can see the only characters are deleted to create substring. No, rearranging takes place. There can be multiple methods to solve this problem, here we will discuss a few of them to understand methods. One is by selecting elements of the string and eliminating a few to create a sequence. In this method, we will pick a few elements and delete the rest to create the substring. import java.util.*; class Main{ public static ArrayList<String>subStringSeq=new ArrayList<String>(); public static void main(String[] args) { String s="pqrs"; System.out.println("All the substring found are :"); findSubString(s,""); System.out.println(subStringSeq); } public static void findSubString(String s, String ans) { if(s.length()==0){ subStringSeq.add(ans); return; } findSubString(s.substring(1),ans+s.charAt(0)) ; findSubString(s.substring(1),ans); } } All the substring found are − [pqrs, pqr, pqs, pq, prs, pr, ps, p, qrs, qr, qs, q, rs, r, s, ] Another method could be iterating over the string and generate substring. And dropping characters of the sequence to generate substrings. Here, we will use a list to store the substrings. And check if the sequence found is already found or not. import java.util.HashSet; public class Main{ static HashSet<String> subString = new HashSet<>(); static void findSubString(String str){ for (int i = 0; i < str.length(); i++) { for (int j = str.length(); j > i; j--) { String sub_str = str.substring(i, j); if (!subString.contains(sub_str)) subString.add(sub_str); for (int k = 1; k < sub_str.length() - 1; k++) { StringBuffer sb = new StringBuffer(sub_str); sb.deleteCharAt(k); if (!subString.contains(sb)); findSubString(sb.toString()); } } } } public static void main(String[] args){ String s = "pqrs"; System.out.println("The subsequence is "); findSubString(s); System.out.println(subString); } } The subsequence is [rs, pq, qr, pr, qs, ps, prs, p, pqr, q, r, s, pqs, qrs, pqrs] One more method can be fix characters and find substring. In this method we will fix elements of the string one by one and using these fixed characters, we will find the subsequence. Recursive calling of this method creates the required string subsequence. class Main { static void subString(String str, int n, int index, String curr){ if (index == n){ return; } System.out.print(curr + ", "); for (int i = index + 1; i < n; i++){ curr += str.charAt(i); subString(str, n, i, curr); curr = curr.substring(0, curr.length() - 1); } } static void printSubStrings(String str){ int index = -1; String curr = ""; subString(str, str.length(), index, curr); } public static void main(String[] args){ String str = "pqrs"; System.out.println("The subStrings are :") ; printSubStrings(str); } } The subStrings are − p, pq, pqr, pqrs, pqs, pr, prs, ps, q, qr, qrs, qs, r, rs, s
[ { "code": null, "e": 1294, "s": 1062, "text": "In this problem, we are given a string and we have to print all the subsequences of the string. The substring generated is created by deleting the elements of the string but the order remains the same(i.e. Order cannot be changed)." }, { "code": null, "e": 1349, "s": 1294, "text": "Let’s take an example to understand the topic better −" }, { "code": null, "e": 1387, "s": 1349, "text": "Input: xyz\nOutput: x,y,z,xy,yz,xz,xyz" }, { "code": null, "e": 1516, "s": 1387, "text": "Explanation − In the above example, we can see the only characters are deleted to create substring. No, rearranging takes place." }, { "code": null, "e": 1627, "s": 1516, "text": "There can be multiple methods to solve this problem, here we will discuss a few of them to understand methods." }, { "code": null, "e": 1803, "s": 1627, "text": "One is by selecting elements of the string and eliminating a few to create a\nsequence. In this method, we will pick a few elements and delete the rest to create the substring." }, { "code": null, "e": 2349, "s": 1803, "text": "import java.util.*;\nclass Main{\n public static ArrayList<String>subStringSeq=new ArrayList<String>();\n public static void main(String[] args) {\n String s=\"pqrs\";\n System.out.println(\"All the substring found are :\");\n findSubString(s,\"\");\n System.out.println(subStringSeq);\n }\n public static void findSubString(String s, String ans) {\n if(s.length()==0){\n subStringSeq.add(ans);\n return;\n }\n findSubString(s.substring(1),ans+s.charAt(0)) ;\n findSubString(s.substring(1),ans);\n }\n}" }, { "code": null, "e": 2379, "s": 2349, "text": "All the substring found are −" }, { "code": null, "e": 2444, "s": 2379, "text": "[pqrs, pqr, pqs, pq, prs, pr, ps, p, qrs, qr, qs, q, rs, r, s, ]" }, { "code": null, "e": 2689, "s": 2444, "text": "Another method could be iterating over the string and generate substring. And dropping characters of the sequence to generate substrings. Here, we will use a list to store the substrings. And check if the sequence found is already found or not." }, { "code": null, "e": 3535, "s": 2689, "text": "import java.util.HashSet;\npublic class Main{\n static HashSet<String> subString = new HashSet<>();\n static void findSubString(String str){\n for (int i = 0; i < str.length(); i++) {\n for (int j = str.length(); j > i; j--) {\n String sub_str = str.substring(i, j);\n if (!subString.contains(sub_str))\n subString.add(sub_str);\n for (int k = 1; k < sub_str.length() - 1; k++) {\n StringBuffer sb = new StringBuffer(sub_str);\n sb.deleteCharAt(k);\n if (!subString.contains(sb));\n findSubString(sb.toString());\n }\n }\n }\n }\n public static void main(String[] args){\n String s = \"pqrs\";\n System.out.println(\"The subsequence is \");\n findSubString(s);\n System.out.println(subString);\n }\n}" }, { "code": null, "e": 3554, "s": 3535, "text": "The subsequence is" }, { "code": null, "e": 3617, "s": 3554, "text": "[rs, pq, qr, pr, qs, ps, prs, p, pqr, q, r, s, pqs, qrs, pqrs]" }, { "code": null, "e": 3874, "s": 3617, "text": "One more method can be fix characters and find substring. In this method we will fix elements of the string one by one and using these fixed characters, we will find the subsequence. Recursive calling of this method creates the required string subsequence." }, { "code": null, "e": 4523, "s": 3874, "text": "class Main {\n static void subString(String str, int n,\n int index, String curr){\n if (index == n){\n return;\n }\n System.out.print(curr + \", \");\n for (int i = index + 1; i < n; i++){\n curr += str.charAt(i);\n subString(str, n, i, curr);\n curr = curr.substring(0, curr.length() - 1);\n }\n }\n static void printSubStrings(String str){\n int index = -1;\n String curr = \"\";\n subString(str, str.length(), index, curr);\n }\n public static void main(String[] args){\n String str = \"pqrs\";\n System.out.println(\"The subStrings are :\") ;\n printSubStrings(str);\n }\n}" }, { "code": null, "e": 4544, "s": 4523, "text": "The subStrings are −" }, { "code": null, "e": 4605, "s": 4544, "text": "p, pq, pqr, pqrs, pqs, pr, prs, ps, q, qr, qrs, qs, r, rs, s" } ]
SciPy - Optimize
The scipy.optimize package provides several commonly used optimization algorithms. This module contains the following aspects − Unconstrained and constrained minimization of multivariate scalar functions (minimize()) using a variety of algorithms (e.g. BFGS, Nelder-Mead simplex, Newton Conjugate Gradient, COBYLA or SLSQP) Unconstrained and constrained minimization of multivariate scalar functions (minimize()) using a variety of algorithms (e.g. BFGS, Nelder-Mead simplex, Newton Conjugate Gradient, COBYLA or SLSQP) Global (brute-force) optimization routines (e.g., anneal(), basinhopping()) Global (brute-force) optimization routines (e.g., anneal(), basinhopping()) Least-squares minimization (leastsq()) and curve fitting (curve_fit()) algorithms Least-squares minimization (leastsq()) and curve fitting (curve_fit()) algorithms Scalar univariate functions minimizers (minimize_scalar()) and root finders (newton()) Scalar univariate functions minimizers (minimize_scalar()) and root finders (newton()) Multivariate equation system solvers (root()) using a variety of algorithms (e.g. hybrid Powell, Levenberg-Marquardt or large-scale methods such as Newton-Krylov) Multivariate equation system solvers (root()) using a variety of algorithms (e.g. hybrid Powell, Levenberg-Marquardt or large-scale methods such as Newton-Krylov) The minimize() function provides a common interface to unconstrained and constrained minimization algorithms for multivariate scalar functions in scipy.optimize. To demonstrate the minimization function, consider the problem of minimizing the Rosenbrock function of the NN variables − $$f(x) = \sum_{i = 1}^{N-1} \:100(x_i - x_{i-1}^{2})$$ The minimum value of this function is 0, which is achieved when xi = 1. In the following example, the minimize() routine is used with the Nelder-Mead simplex algorithm (method = 'Nelder-Mead') (selected through the method parameter). Let us consider the following example. import numpy as np from scipy.optimize import minimize def rosen(x): x0 = np.array([1.3, 0.7, 0.8, 1.9, 1.2]) res = minimize(rosen, x0, method='nelder-mead') print(res.x) The above program will generate the following output. [7.93700741e+54 -5.41692163e+53 6.28769150e+53 1.38050484e+55 -4.14751333e+54] The simplex algorithm is probably the simplest way to minimize a fairly well-behaved function. It requires only function evaluations and is a good choice for simple minimization problems. However, because it does not use any gradient evaluations, it may take longer to find the minimum. Another optimization algorithm that needs only function calls to find the minimum is the Powell‘s method, which is available by setting method = 'powell' in the minimize() function. Solve a nonlinear least-squares problem with bounds on the variables. Given the residuals f(x) (an m-dimensional real function of n real variables) and the loss function rho(s) (a scalar function), least_squares find a local minimum of the cost function F(x). Let us consider the following example. In this example, we find a minimum of the Rosenbrock function without bounds on the independent variables. #Rosenbrock Function def fun_rosenbrock(x): return np.array([10 * (x[1] - x[0]**2), (1 - x[0])]) from scipy.optimize import least_squares input = np.array([2, 2]) res = least_squares(fun_rosenbrock, input) print res Notice that, we only provide the vector of the residuals. The algorithm constructs the cost function as a sum of squares of the residuals, which gives the Rosenbrock function. The exact minimum is at x = [1.0,1.0]. The above program will generate the following output. active_mask: array([ 0., 0.]) cost: 9.8669242910846867e-30 fun: array([ 4.44089210e-15, 1.11022302e-16]) grad: array([ -8.89288649e-14, 4.44089210e-14]) jac: array([[-20.00000015,10.],[ -1.,0.]]) message: '`gtol` termination condition is satisfied.' nfev: 3 njev: 3 optimality: 8.8928864934219529e-14 status: 1 success: True x: array([ 1., 1.]) Let us understand how root finding helps in SciPy. If one has a single-variable equation, there are four different root-finding algorithms, which can be tried. Each of these algorithms require the endpoints of an interval in which a root is expected (because the function changes signs). In general, brentq is the best choice, but the other methods may be useful in certain circumstances or for academic purposes. A problem closely related to finding the zeros of a function is the problem of finding a fixed point of a function. A fixed point of a function is the point at which evaluation of the function returns the point: g(x) = x. Clearly the fixed point of gg is the root of f(x) = g(x)−x. Equivalently, the root of ff is the fixed_point of g(x) = f(x)+x. The routine fixed_point provides a simple iterative method using the Aitkens sequence acceleration to estimate the fixed point of gg, if a starting point is given. Finding a root of a set of non-linear equations can be achieved using the root() function. Several methods are available, amongst which hybr (the default) and lm, respectively use the hybrid method of Powell and the Levenberg-Marquardt method from the MINPACK. The following example considers the single-variable transcendental equation. x2 + 2cos(x) = 0 A root of which can be found as follows − import numpy as np from scipy.optimize import root def func(x): return x*2 + 2 * np.cos(x) sol = root(func, 0.3) print sol The above program will generate the following output. fjac: array([[-1.]]) fun: array([ 2.22044605e-16]) message: 'The solution converged.' nfev: 10 qtf: array([ -2.77644574e-12]) r: array([-3.34722409]) status: 1 success: True x: array([-0.73908513]) Print Add Notes Bookmark this page
[ { "code": null, "e": 2015, "s": 1887, "text": "The scipy.optimize package provides several commonly used optimization algorithms. This module contains the following aspects −" }, { "code": null, "e": 2211, "s": 2015, "text": "Unconstrained and constrained minimization of multivariate scalar functions (minimize()) using a variety of algorithms (e.g. BFGS, Nelder-Mead simplex, Newton Conjugate Gradient, COBYLA or SLSQP)" }, { "code": null, "e": 2407, "s": 2211, "text": "Unconstrained and constrained minimization of multivariate scalar functions (minimize()) using a variety of algorithms (e.g. BFGS, Nelder-Mead simplex, Newton Conjugate Gradient, COBYLA or SLSQP)" }, { "code": null, "e": 2483, "s": 2407, "text": "Global (brute-force) optimization routines (e.g., anneal(), basinhopping())" }, { "code": null, "e": 2559, "s": 2483, "text": "Global (brute-force) optimization routines (e.g., anneal(), basinhopping())" }, { "code": null, "e": 2641, "s": 2559, "text": "Least-squares minimization (leastsq()) and curve fitting (curve_fit()) algorithms" }, { "code": null, "e": 2723, "s": 2641, "text": "Least-squares minimization (leastsq()) and curve fitting (curve_fit()) algorithms" }, { "code": null, "e": 2810, "s": 2723, "text": "Scalar univariate functions minimizers (minimize_scalar()) and root finders (newton())" }, { "code": null, "e": 2897, "s": 2810, "text": "Scalar univariate functions minimizers (minimize_scalar()) and root finders (newton())" }, { "code": null, "e": 3060, "s": 2897, "text": "Multivariate equation system solvers (root()) using a variety of algorithms (e.g. hybrid Powell, Levenberg-Marquardt or large-scale methods such as Newton-Krylov)" }, { "code": null, "e": 3223, "s": 3060, "text": "Multivariate equation system solvers (root()) using a variety of algorithms (e.g. hybrid Powell, Levenberg-Marquardt or large-scale methods such as Newton-Krylov)" }, { "code": null, "e": 3508, "s": 3223, "text": "The minimize() function provides a common interface to unconstrained and constrained minimization algorithms for multivariate scalar functions in scipy.optimize. To demonstrate the minimization function, consider the problem of minimizing the Rosenbrock function of the NN variables −" }, { "code": null, "e": 3563, "s": 3508, "text": "$$f(x) = \\sum_{i = 1}^{N-1} \\:100(x_i - x_{i-1}^{2})$$" }, { "code": null, "e": 3635, "s": 3563, "text": "The minimum value of this function is 0, which is achieved when xi = 1." }, { "code": null, "e": 3836, "s": 3635, "text": "In the following example, the minimize() routine is used with the Nelder-Mead simplex algorithm (method = 'Nelder-Mead') (selected through the method parameter). Let us consider the following example." }, { "code": null, "e": 4010, "s": 3836, "text": "import numpy as np\nfrom scipy.optimize import minimize\n\ndef rosen(x):\n\nx0 = np.array([1.3, 0.7, 0.8, 1.9, 1.2])\nres = minimize(rosen, x0, method='nelder-mead')\n\nprint(res.x)" }, { "code": null, "e": 4064, "s": 4010, "text": "The above program will generate the following output." }, { "code": null, "e": 4148, "s": 4064, "text": "[7.93700741e+54 -5.41692163e+53 6.28769150e+53 1.38050484e+55 -4.14751333e+54]\n" }, { "code": null, "e": 4435, "s": 4148, "text": "The simplex algorithm is probably the simplest way to minimize a fairly well-behaved function. It requires only function evaluations and is a good choice for simple minimization problems. However, because it does not use any gradient evaluations, it may take longer to find the minimum." }, { "code": null, "e": 4618, "s": 4435, "text": "Another optimization algorithm that needs only function calls to find the minimum is the Powell‘s method, which is available by setting method = 'powell' in the minimize() function. " }, { "code": null, "e": 4917, "s": 4618, "text": "Solve a nonlinear least-squares problem with bounds on the variables. Given the residuals f(x) (an m-dimensional real function of n real variables) and the loss function rho(s) (a scalar function), least_squares find a local minimum of the cost function F(x). Let us consider the following example." }, { "code": null, "e": 5024, "s": 4917, "text": "In this example, we find a minimum of the Rosenbrock function without bounds on the independent variables." }, { "code": null, "e": 5248, "s": 5024, "text": "#Rosenbrock Function\ndef fun_rosenbrock(x):\n return np.array([10 * (x[1] - x[0]**2), (1 - x[0])])\n \nfrom scipy.optimize import least_squares\ninput = np.array([2, 2])\nres = least_squares(fun_rosenbrock, input)\n\nprint res" }, { "code": null, "e": 5463, "s": 5248, "text": "Notice that, we only provide the vector of the residuals. The algorithm constructs the cost function as a sum of squares of the residuals, which gives the Rosenbrock function. The exact minimum is at x = [1.0,1.0]." }, { "code": null, "e": 5517, "s": 5463, "text": "The above program will generate the following output." }, { "code": null, "e": 5926, "s": 5517, "text": "active_mask: array([ 0., 0.])\n cost: 9.8669242910846867e-30\n fun: array([ 4.44089210e-15, 1.11022302e-16])\n grad: array([ -8.89288649e-14, 4.44089210e-14])\n jac: array([[-20.00000015,10.],[ -1.,0.]])\n message: '`gtol` termination condition is satisfied.'\n nfev: 3\n njev: 3\n optimality: 8.8928864934219529e-14\n status: 1\n success: True\n x: array([ 1., 1.])\n" }, { "code": null, "e": 5977, "s": 5926, "text": "Let us understand how root finding helps in SciPy." }, { "code": null, "e": 6340, "s": 5977, "text": "If one has a single-variable equation, there are four different root-finding algorithms, which can be tried. Each of these algorithms require the endpoints of an interval in which a root is expected (because the function changes signs). In general, brentq is the best choice, but the other methods may be useful in certain circumstances or for academic purposes." }, { "code": null, "e": 6852, "s": 6340, "text": "A problem closely related to finding the zeros of a function is the problem of finding a fixed point of a function. A fixed point of a function is the point at which evaluation of the function returns the point: g(x) = x. Clearly the fixed point of gg is the root of f(x) = g(x)−x. Equivalently, the root of ff is the fixed_point of g(x) = f(x)+x. The routine fixed_point provides a simple iterative method using the Aitkens sequence acceleration to estimate the fixed point of gg, if a starting point is given." }, { "code": null, "e": 7113, "s": 6852, "text": "Finding a root of a set of non-linear equations can be achieved using the root() function. Several methods are available, amongst which hybr (the default) and lm, respectively use the hybrid method of Powell and the Levenberg-Marquardt method from the MINPACK." }, { "code": null, "e": 7190, "s": 7113, "text": "The following example considers the single-variable transcendental equation." }, { "code": null, "e": 7207, "s": 7190, "text": "x2 + 2cos(x) = 0" }, { "code": null, "e": 7249, "s": 7207, "text": "A root of which can be found as follows −" }, { "code": null, "e": 7375, "s": 7249, "text": "import numpy as np\nfrom scipy.optimize import root\ndef func(x):\n return x*2 + 2 * np.cos(x)\nsol = root(func, 0.3)\nprint sol" }, { "code": null, "e": 7429, "s": 7375, "text": "The above program will generate the following output." }, { "code": null, "e": 7652, "s": 7429, "text": "fjac: array([[-1.]])\nfun: array([ 2.22044605e-16])\nmessage: 'The solution converged.'\n nfev: 10\n qtf: array([ -2.77644574e-12])\n r: array([-3.34722409])\n status: 1\n success: True\n x: array([-0.73908513])\n" }, { "code": null, "e": 7659, "s": 7652, "text": " Print" }, { "code": null, "e": 7670, "s": 7659, "text": " Add Notes" } ]
time.Parse() Function in Golang With Examples - GeeksforGeeks
19 Apr, 2020 In Go language, time packages supplies functionality for determining as well as viewing time. The Parse() function in Go language is used to parse a formatted string and then finds the time value that it forms. Moreover, this function is defined under the time package. Here, you need to import “time” package in order to use these functions. Syntax: func Parse(layout, value string) (Time, error) Here, layout specifies the format by displaying in what way the reference time, that is defined as Mon Jan 2 15:04:05 -0700 MST 2006 would be explained if it were the value. However, the previously defined layouts like UnixDate, ANSIC, RFC3339 etc, explain standard as well as suitable representations of the reference time. And the value parameter holds string. Where, the elements that are removed from the value are presumed to be zero and when zero is not possible then its assumed to be one. Return Value: It returns the time value that it represents. And if a time zone indicator is not present then it returns a time in UTC. Example 1: // Golang program to illustrate the usage of// time.Parse() function // Including main packagepackage main // Importing fmt and timeimport "fmt"import "time" // Calling mainfunc main() { // Declaring layout constant const layout = "Jan 2, 2006 at 3:04pm (MST)" // Calling Parse() method with its parameters tm, _ := time.Parse(layout, "Feb 4, 2014 at 6:05pm (PST)") // Returns output fmt.Println(tm)} Output: 2014-02-04 18:05:00 +0000 PST Here, the output returned is in PST as defined above and the layout constant and value used here are long-form of it. Example 2: // Golang program to illustrate the usage of// time.Parse() function // Including main packagepackage main // Importing fmt and timeimport "fmt"import "time" // Calling mainfunc main() { // Declaring layout constant const layout = "2006-Jan-02" // Calling Parse() method with its parameters tm, _ := time.Parse(layout, "2014-Feb-04") // Returns output fmt.Println(tm)} Output: 2014-02-04 00:00:00 +0000 UTC Here, the output returned is in UTC as there is no time zone indicator and the layout constant and value used here are short form of it. GoLang-time Go Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. strings.Replace() Function in Golang With Examples Arrays in Go How to Split a String in Golang? fmt.Sprintf() Function in Golang With Examples Golang Maps Slices in Golang Different Ways to Find the Type of Variable in Golang Inheritance in GoLang Interfaces in Golang How to Trim a String in Golang?
[ { "code": null, "e": 25795, "s": 25767, "text": "\n19 Apr, 2020" }, { "code": null, "e": 26138, "s": 25795, "text": "In Go language, time packages supplies functionality for determining as well as viewing time. The Parse() function in Go language is used to parse a formatted string and then finds the time value that it forms. Moreover, this function is defined under the time package. Here, you need to import “time” package in order to use these functions." }, { "code": null, "e": 26146, "s": 26138, "text": "Syntax:" }, { "code": null, "e": 26194, "s": 26146, "text": "func Parse(layout, value string) (Time, error)\n" }, { "code": null, "e": 26691, "s": 26194, "text": "Here, layout specifies the format by displaying in what way the reference time, that is defined as Mon Jan 2 15:04:05 -0700 MST 2006 would be explained if it were the value. However, the previously defined layouts like UnixDate, ANSIC, RFC3339 etc, explain standard as well as suitable representations of the reference time. And the value parameter holds string. Where, the elements that are removed from the value are presumed to be zero and when zero is not possible then its assumed to be one." }, { "code": null, "e": 26826, "s": 26691, "text": "Return Value: It returns the time value that it represents. And if a time zone indicator is not present then it returns a time in UTC." }, { "code": null, "e": 26837, "s": 26826, "text": "Example 1:" }, { "code": "// Golang program to illustrate the usage of// time.Parse() function // Including main packagepackage main // Importing fmt and timeimport \"fmt\"import \"time\" // Calling mainfunc main() { // Declaring layout constant const layout = \"Jan 2, 2006 at 3:04pm (MST)\" // Calling Parse() method with its parameters tm, _ := time.Parse(layout, \"Feb 4, 2014 at 6:05pm (PST)\") // Returns output fmt.Println(tm)}", "e": 27265, "s": 26837, "text": null }, { "code": null, "e": 27273, "s": 27265, "text": "Output:" }, { "code": null, "e": 27304, "s": 27273, "text": "2014-02-04 18:05:00 +0000 PST\n" }, { "code": null, "e": 27422, "s": 27304, "text": "Here, the output returned is in PST as defined above and the layout constant and value used here are long-form of it." }, { "code": null, "e": 27433, "s": 27422, "text": "Example 2:" }, { "code": "// Golang program to illustrate the usage of// time.Parse() function // Including main packagepackage main // Importing fmt and timeimport \"fmt\"import \"time\" // Calling mainfunc main() { // Declaring layout constant const layout = \"2006-Jan-02\" // Calling Parse() method with its parameters tm, _ := time.Parse(layout, \"2014-Feb-04\") // Returns output fmt.Println(tm)}", "e": 27829, "s": 27433, "text": null }, { "code": null, "e": 27837, "s": 27829, "text": "Output:" }, { "code": null, "e": 27868, "s": 27837, "text": "2014-02-04 00:00:00 +0000 UTC\n" }, { "code": null, "e": 28005, "s": 27868, "text": "Here, the output returned is in UTC as there is no time zone indicator and the layout constant and value used here are short form of it." }, { "code": null, "e": 28017, "s": 28005, "text": "GoLang-time" }, { "code": null, "e": 28029, "s": 28017, "text": "Go Language" }, { "code": null, "e": 28127, "s": 28029, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28178, "s": 28127, "text": "strings.Replace() Function in Golang With Examples" }, { "code": null, "e": 28191, "s": 28178, "text": "Arrays in Go" }, { "code": null, "e": 28224, "s": 28191, "text": "How to Split a String in Golang?" }, { "code": null, "e": 28271, "s": 28224, "text": "fmt.Sprintf() Function in Golang With Examples" }, { "code": null, "e": 28283, "s": 28271, "text": "Golang Maps" }, { "code": null, "e": 28300, "s": 28283, "text": "Slices in Golang" }, { "code": null, "e": 28354, "s": 28300, "text": "Different Ways to Find the Type of Variable in Golang" }, { "code": null, "e": 28376, "s": 28354, "text": "Inheritance in GoLang" }, { "code": null, "e": 28397, "s": 28376, "text": "Interfaces in Golang" } ]
Python EasyGUI – Integer Box - GeeksforGeeks
05 Sep, 2020 Integer Box : It is used to get the integer input from the user, input should be integer input not sting which happens in enter box. It displays the title, message to be displayed, place to enter a integer input and a pair of “Ok”, “Cancel” button which is used confirm the input. We can set some default integer value to the place where user enter text and we can also set lower and upper bound value which user can enter, below is how the enter box looks like In order to do this we will use integerbox method Syntax : integerbox(message, title, default_integer, lower_bound, upper_bound) Argument : It takes 5 arguments, first string i.e message/information to be displayed, second string i.e title of the window, third is integer which is default integer, forth and fifth are integer representing lower and upper bound respectively Return : It returns the entered integer and None if cancel is pressed Example :In this we will create a integer box with default integer and with lower and upper bound value, and will show the specific message on the screen according to the entered integer, below is the implementation # importing easygui modulefrom easygui import * # message to be displayedtext = "Enter Something (integer)" # window titletitle = "Window Title GfG" # default integerd_int = 10 # lower boundlower = 0 # upper boundupper = 99999 # creating a integer boxoutput = integerbox(text, title, d_int, lower, upper) # title for the message boxtitle = "Message Box" # creating a messagemessage = "Enterted Number : " + str(output) # creating a message boxmsg = msgbox(message, title) Output : Another Example :In this we will create a integer box and will show the specific message on the screen according to the entered integer, below is the implementation # importing easygui modulefrom easygui import * # message to be displayedtext = "Enter a number !!" # window titletitle = "Window Title GfG" # creating a integer boxoutput = integerbox(text, title) # title for the message boxtitle = "Message Box" # creating a messagemessage = "Enterted Number : " + str(output) # creating a message boxmsg = msgbox(message, title) Output : Python-EasyGUI Python-gui Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Iterate over a list in Python *args and **kwargs in Python Reading and Writing to text files in Python Create a Pandas DataFrame from Lists Check if element exists in list in Python
[ { "code": null, "e": 26033, "s": 26005, "text": "\n05 Sep, 2020" }, { "code": null, "e": 26495, "s": 26033, "text": "Integer Box : It is used to get the integer input from the user, input should be integer input not sting which happens in enter box. It displays the title, message to be displayed, place to enter a integer input and a pair of “Ok”, “Cancel” button which is used confirm the input. We can set some default integer value to the place where user enter text and we can also set lower and upper bound value which user can enter, below is how the enter box looks like" }, { "code": null, "e": 26545, "s": 26495, "text": "In order to do this we will use integerbox method" }, { "code": null, "e": 26624, "s": 26545, "text": "Syntax : integerbox(message, title, default_integer, lower_bound, upper_bound)" }, { "code": null, "e": 26869, "s": 26624, "text": "Argument : It takes 5 arguments, first string i.e message/information to be displayed, second string i.e title of the window, third is integer which is default integer, forth and fifth are integer representing lower and upper bound respectively" }, { "code": null, "e": 26939, "s": 26869, "text": "Return : It returns the entered integer and None if cancel is pressed" }, { "code": null, "e": 27155, "s": 26939, "text": "Example :In this we will create a integer box with default integer and with lower and upper bound value, and will show the specific message on the screen according to the entered integer, below is the implementation" }, { "code": "# importing easygui modulefrom easygui import * # message to be displayedtext = \"Enter Something (integer)\" # window titletitle = \"Window Title GfG\" # default integerd_int = 10 # lower boundlower = 0 # upper boundupper = 99999 # creating a integer boxoutput = integerbox(text, title, d_int, lower, upper) # title for the message boxtitle = \"Message Box\" # creating a messagemessage = \"Enterted Number : \" + str(output) # creating a message boxmsg = msgbox(message, title)", "e": 27636, "s": 27155, "text": null }, { "code": null, "e": 27645, "s": 27636, "text": "Output :" }, { "code": null, "e": 27810, "s": 27645, "text": "Another Example :In this we will create a integer box and will show the specific message on the screen according to the entered integer, below is the implementation" }, { "code": "# importing easygui modulefrom easygui import * # message to be displayedtext = \"Enter a number !!\" # window titletitle = \"Window Title GfG\" # creating a integer boxoutput = integerbox(text, title) # title for the message boxtitle = \"Message Box\" # creating a messagemessage = \"Enterted Number : \" + str(output) # creating a message boxmsg = msgbox(message, title)", "e": 28181, "s": 27810, "text": null }, { "code": null, "e": 28190, "s": 28181, "text": "Output :" }, { "code": null, "e": 28205, "s": 28190, "text": "Python-EasyGUI" }, { "code": null, "e": 28216, "s": 28205, "text": "Python-gui" }, { "code": null, "e": 28223, "s": 28216, "text": "Python" }, { "code": null, "e": 28321, "s": 28223, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28339, "s": 28321, "text": "Python Dictionary" }, { "code": null, "e": 28374, "s": 28339, "text": "Read a file line by line in Python" }, { "code": null, "e": 28406, "s": 28374, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28428, "s": 28406, "text": "Enumerate() in Python" }, { "code": null, "e": 28470, "s": 28428, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 28500, "s": 28470, "text": "Iterate over a list in Python" }, { "code": null, "e": 28529, "s": 28500, "text": "*args and **kwargs in Python" }, { "code": null, "e": 28573, "s": 28529, "text": "Reading and Writing to text files in Python" }, { "code": null, "e": 28610, "s": 28573, "text": "Create a Pandas DataFrame from Lists" } ]
How to Create/Add a New Virtual Disk for an Existing Linux Virtual Machine
This article helps you to create and add a new virtual disk to an existing Linux virtual machine on VMware. Here are some steps for adding a new SCSI based virtual disk on a CentOS Linux virtual machine. We are assuming that you are already familiar with Linux system administration skills and having knowledge of vCenter Server or vSphere Client. For a full description of the utilities mentioned in this article, please refer to the manuals. To add a new virtual disk for an existing Linux virtual machine, Log in as root on your Linux virtual machine. Run this below command and make note of the sdx entries, means list of existing hard disks. # ls /dev/sd* /dev/sda /dev/sda1 /dev/sda2 Log into the vCenter Server using the vSphere Client. In the vSphere Client inventory, right-click the virtual machine and select Edit Settings. Click the Hardware tab and click Add. Select Hard Disk and click Next. Complete the wizard. After adding the Hard disk to VMware/vSphere/vCenter it looks like this. Reboot the Linux virtual machine. # init 6 Log into the Virtual machine using the root credentials and run this command. # ls /dev/sd* /dev/sda /dev/sda1 /dev/sda2 /dev/sdb We will find new entry. Create an ext3 file system on the new disk using the new ‘sdb’ disk from the above list of disks # mkfs -t ext3 /dev/sdb mke2fs 1.41.12 (17-May-2010) /dev/sdb is entire device, not just one partition! Proceed anyway? (y,n) y Filesystem label= OS type: Linux Block size=4096 (log=2) Fragment size=4096 (log=2) Stride=0 blocks, Stripe width=0 blocks 1310720 inodes, 5242880 blocks 262144 blocks (5.00%) reserved for the super user First data block=0 Maximum filesystem blocks=4294967296 160 block groups 32768 blocks per group, 32768 fragments per group 8192 inodes per group Superblock backups stored on blocks: 32768, 98304, 163840, 229376, 294912, 819200, 884736, 1605632, 2654208, 4096000 Writing inode tables: done Creating journal (32768 blocks): done Writing superblocks and filesystem accounting information: done This filesystem will be automatically checked every 38 mounts or 180 days, whichever comes first. Use tune2fs -c or -i to override. You may see an alert that, you are performing this operation on an entire device, not a partition. That is correct, as you created a single virtual disk of the intended size. This is assuming you have specified the correct device. Caution: Ensure that you have the selected the right device, there is no undo. Run the fdisk command to verify the existence of the disk you created. # fdisk -l Disk /dev/sda: 21.5 GB, 21474836480 bytes 255 heads, 63 sectors/track, 2610 cylinders Units = cylinders of 16065 * 512 = 8225280 bytes Sector size (logical/physical): 512 bytes / 512 bytes I/O size (minimum/optimal): 512 bytes / 512 bytes Disk identifier: 0x000c664e Device Boot Start End Blocks Id System /dev/sda1 * 1 64 512000 83 Linux Partition 1 does not end on cylinder boundary. /dev/sda2 64 2611 20458496 8e Linux LVM Disk /dev/sdb: 21.5 GB, 21474836480 bytes 255 heads, 63 sectors/track, 2610 cylinders Units = cylinders of 16065 * 512 = 8225280 bytes Sector size (logical/physical): 512 bytes / 512 bytes I/O size (minimum/optimal): 512 bytes / 512 bytes Disk identifier: 0x00000000 Disk /dev/mapper/VolGroup-lv_root: 18.8 GB, 18798870528 bytes 255 heads, 63 sectors/track, 2285 cylinders Units = cylinders of 16065 * 512 = 8225280 bytes Sector size (logical/physical): 512 bytes / 512 bytes I/O size (minimum/optimal): 512 bytes / 512 bytes Disk identifier: 0x00000000 Disk /dev/mapper/VolGroup-lv_swap: 2147 MB, 2147483648 bytes 255 heads, 63 sectors/track, 261 cylinders Units = cylinders of 16065 * 512 = 8225280 bytes Sector size (logical/physical): 512 bytes / 512 bytes I/O size (minimum/optimal): 512 bytes / 512 bytes Disk identifier: 0x00000000 Run this command to create a mount point for the new disk and mount that disk # mkdir /newdisk # mount /dev/sdb /newdisk To verify the mount run below command – # df -h Filesystem Size Used Avail Use% Mounted on /dev/mapper/VolGroup-lv_root 18G 2.0G 15G 12% / tmpfs 491M 0 491M 0% /dev/shm /dev/sda1 477M 42M 411M 10% /boot /dev/sdb 20G 173M 19G 1% /newdisk Now the new disk is available to you for usage. To mount the new disk or volume automatically at the boot time follow the below procedure – Run this command to display the current /etc/fstab # cat /etc/fstab# # /etc/fstab # Created by anaconda on Thu Dec 3 20:25:38 2015 # # Accessible filesystems, by reference, are maintained under '/dev/disk' # See man pages fstab(5), findfs(8), mount(8) and/or blkid(8) for more info # /dev/mapper/VolGroup-lv_root / ext4 defaults 1 1 UUID=e1e6c609-a94f-400f-9dc5-93faf0aab358 /boot ext4 defaults 1 2 /dev/mapper/VolGroup-lv_swap swap swap defaults 0 0 tmpfs /dev/shm tmpfs defaults 0 0 devpts /dev/pts devpts gid=5,mode=620 0 0 sysfs /sys sysfs defaults 0 0 proc /proc proc defaults 0 0 Using a text editor to edit fstab and add this line to add the disk to /etc/fstab so that it is available across reboots /dev/sdb /newdisk ext3 defaults 1 3 After this configuration you are able to add new Virtual hard disk drives to existing Linux machines on VMware/vSphere/vCenter. This will help in the provision of a hard disk for backups or stored data to the existing Centos Linux machines.
[ { "code": null, "e": 1506, "s": 1062, "text": "This article helps you to create and add a new virtual disk to an existing Linux virtual machine on VMware. Here are some steps for adding a new SCSI based virtual disk on a CentOS Linux virtual machine. We are assuming that you are already familiar with Linux system administration skills and having knowledge of vCenter Server or vSphere Client. For a full description of the utilities mentioned in this article, please refer to the manuals." }, { "code": null, "e": 1709, "s": 1506, "text": "To add a new virtual disk for an existing Linux virtual machine, Log in as root on your Linux virtual machine. Run this below command and make note of the sdx entries, means list of existing hard disks." }, { "code": null, "e": 1752, "s": 1709, "text": "# ls /dev/sd*\n/dev/sda /dev/sda1 /dev/sda2" }, { "code": null, "e": 1806, "s": 1752, "text": "Log into the vCenter Server using the vSphere Client." }, { "code": null, "e": 1897, "s": 1806, "text": "In the vSphere Client inventory, right-click the virtual machine and select Edit Settings." }, { "code": null, "e": 1935, "s": 1897, "text": "Click the Hardware tab and click Add." }, { "code": null, "e": 1968, "s": 1935, "text": "Select Hard Disk and click Next." }, { "code": null, "e": 2062, "s": 1968, "text": "Complete the wizard. After adding the Hard disk to VMware/vSphere/vCenter it looks like this." }, { "code": null, "e": 2096, "s": 2062, "text": "Reboot the Linux virtual machine." }, { "code": null, "e": 2105, "s": 2096, "text": "# init 6" }, { "code": null, "e": 2183, "s": 2105, "text": "Log into the Virtual machine using the root credentials and run this command." }, { "code": null, "e": 2235, "s": 2183, "text": "# ls /dev/sd*\n/dev/sda /dev/sda1 /dev/sda2 /dev/sdb" }, { "code": null, "e": 2259, "s": 2235, "text": "We will find new entry." }, { "code": null, "e": 2356, "s": 2259, "text": "Create an ext3 file system on the new disk using the new ‘sdb’ disk from the above list of disks" }, { "code": null, "e": 3212, "s": 2356, "text": "# mkfs -t ext3 /dev/sdb\nmke2fs 1.41.12 (17-May-2010)\n/dev/sdb is entire device, not just one partition!\nProceed anyway? (y,n) y\nFilesystem label=\nOS type: Linux\nBlock size=4096 (log=2)\nFragment size=4096 (log=2)\nStride=0 blocks, Stripe width=0 blocks\n1310720 inodes, 5242880 blocks\n262144 blocks (5.00%) reserved for the super user\nFirst data block=0\nMaximum filesystem blocks=4294967296\n160 block groups\n32768 blocks per group, 32768 fragments per group\n8192 inodes per group\nSuperblock backups stored on blocks:\n32768, 98304, 163840, 229376, 294912, 819200, 884736, 1605632, 2654208,\n4096000\nWriting inode tables: done\nCreating journal (32768 blocks): done\nWriting superblocks and filesystem accounting information: done\n\nThis filesystem will be automatically checked every 38 mounts or\n180 days, whichever comes first. Use tune2fs -c or -i to override." }, { "code": null, "e": 3443, "s": 3212, "text": "You may see an alert that, you are performing this operation on an entire device, not a partition. That is correct, as you created a single virtual disk of the intended size. This is assuming you have specified the correct device." }, { "code": null, "e": 3522, "s": 3443, "text": "Caution: Ensure that you have the selected the right device, there is no undo." }, { "code": null, "e": 3593, "s": 3522, "text": "Run the fdisk command to verify the existence of the disk you created." }, { "code": null, "e": 4875, "s": 3593, "text": "# fdisk -l\nDisk /dev/sda: 21.5 GB, 21474836480 bytes\n255 heads, 63 sectors/track, 2610 cylinders\nUnits = cylinders of 16065 * 512 = 8225280 bytes\nSector size (logical/physical): 512 bytes / 512 bytes\nI/O size (minimum/optimal): 512 bytes / 512 bytes\nDisk identifier: 0x000c664e\n\nDevice Boot Start End Blocks Id System\n/dev/sda1 * 1 64 512000 83 Linux\nPartition 1 does not end on cylinder boundary.\n/dev/sda2 64 2611 20458496 8e Linux LVM\n\nDisk /dev/sdb: 21.5 GB, 21474836480 bytes\n255 heads, 63 sectors/track, 2610 cylinders\nUnits = cylinders of 16065 * 512 = 8225280 bytes\nSector size (logical/physical): 512 bytes / 512 bytes\nI/O size (minimum/optimal): 512 bytes / 512 bytes\nDisk identifier: 0x00000000\n\n\nDisk /dev/mapper/VolGroup-lv_root: 18.8 GB, 18798870528 bytes\n255 heads, 63 sectors/track, 2285 cylinders\nUnits = cylinders of 16065 * 512 = 8225280 bytes\nSector size (logical/physical): 512 bytes / 512 bytes\nI/O size (minimum/optimal): 512 bytes / 512 bytes\nDisk identifier: 0x00000000\n\n\nDisk /dev/mapper/VolGroup-lv_swap: 2147 MB, 2147483648 bytes\n255 heads, 63 sectors/track, 261 cylinders\nUnits = cylinders of 16065 * 512 = 8225280 bytes\nSector size (logical/physical): 512 bytes / 512 bytes\nI/O size (minimum/optimal): 512 bytes / 512 bytes\nDisk identifier: 0x00000000" }, { "code": null, "e": 4953, "s": 4875, "text": "Run this command to create a mount point for the new disk and mount that disk" }, { "code": null, "e": 4996, "s": 4953, "text": "# mkdir /newdisk\n# mount /dev/sdb /newdisk" }, { "code": null, "e": 5036, "s": 4996, "text": "To verify the mount run below command –" }, { "code": null, "e": 5233, "s": 5036, "text": "# df -h\nFilesystem Size Used Avail Use% Mounted on\n/dev/mapper/VolGroup-lv_root\n18G 2.0G 15G 12% /\ntmpfs 491M 0 491M 0% /dev/shm\n/dev/sda1 477M 42M 411M 10% /boot\n/dev/sdb 20G 173M 19G 1% /newdisk" }, { "code": null, "e": 5373, "s": 5233, "text": "Now the new disk is available to you for usage. To mount the new disk or volume automatically at the boot time follow the below procedure –" }, { "code": null, "e": 5424, "s": 5373, "text": "Run this command to display the current /etc/fstab" }, { "code": null, "e": 5961, "s": 5424, "text": "# cat /etc/fstab#\n# /etc/fstab\n# Created by anaconda on Thu Dec 3 20:25:38 2015\n#\n# Accessible filesystems, by reference, are maintained under '/dev/disk'\n# See man pages fstab(5), findfs(8), mount(8) and/or blkid(8) for more info\n#\n/dev/mapper/VolGroup-lv_root / ext4 defaults 1 1\nUUID=e1e6c609-a94f-400f-9dc5-93faf0aab358 /boot ext4 defaults 1 2\n/dev/mapper/VolGroup-lv_swap swap swap defaults 0 0\ntmpfs /dev/shm tmpfs defaults 0 0\ndevpts /dev/pts devpts gid=5,mode=620 0 0\nsysfs /sys sysfs defaults 0 0\nproc /proc proc defaults 0 0\n\n" }, { "code": null, "e": 6082, "s": 5961, "text": "Using a text editor to edit fstab and add this line to add the disk to /etc/fstab so that it is available across reboots" }, { "code": null, "e": 6118, "s": 6082, "text": "/dev/sdb /newdisk ext3 defaults 1 3" }, { "code": null, "e": 6359, "s": 6118, "text": "After this configuration you are able to add new Virtual hard disk drives to existing Linux machines on VMware/vSphere/vCenter. This will help in the provision of a hard disk for backups or stored data to the existing Centos Linux machines." } ]
AngularJS | json Filter - GeeksforGeeks
30 Apr, 2019 The json filter in AngularJs is used to convert a JavaScript object into a JSON. string.JavaScript object that we are using can be of any kind of JavaScript Object. Syntax: {{ object | json : spacing }} Where json is used to specifies that object should be displayed in JSON format and spacing is an optional parameter with default value 2 that specifies the number of spaces per indentation. Example 1:This example will display the marks of student in JSON <!DOCTYPE html><html> <head><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script> </head><body> <div ng-app="result" ng-controller="resultCtrl"> <h1>Result:</h1> <pre>{{marks | json}}</pre> </div> <script>var app = angular.module('result', []);app.controller('resultCtrl', function($scope) {$scope.marks = { "Math" : 98, "Computer" : 93, "Physics" : 95, "Chemistry" : 95, "English" : 74 };});</script> </body></html> Output : Example 2:This example will display fruits name in JSON with 10 spaces per indentation <!DOCTYPE html><html><head><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script></head><body> <div ng-app="fruit" ng-controller="fruitCtrl"> <h1>Fruits:</h1> <pre>{{fruit | json : 10}}</pre> </div> <script>var app = angular.module('fruit', []);app.controller('fruitCtrl', function($scope) { $scope.fruit = ["Apple", "Banana", "Mango"];});</script> </body></html> Output : Picked AngularJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Top 10 Angular Libraries For Web Developers Angular File Upload Auth Guards in Angular 9/10/11 Angular | keyup event What is AOT and JIT Compiler in Angular ? Roadmap to Become a Web Developer in 2022 Installation of Node.js on Linux How to fetch data from an API in ReactJS ? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 28271, "s": 28243, "text": "\n30 Apr, 2019" }, { "code": null, "e": 28436, "s": 28271, "text": "The json filter in AngularJs is used to convert a JavaScript object into a JSON. string.JavaScript object that we are using can be of any kind of JavaScript Object." }, { "code": null, "e": 28444, "s": 28436, "text": "Syntax:" }, { "code": null, "e": 28479, "s": 28444, "text": " {{ object | json : spacing }}\n" }, { "code": null, "e": 28669, "s": 28479, "text": "Where json is used to specifies that object should be displayed in JSON format and spacing is an optional parameter with default value 2 that specifies the number of spaces per indentation." }, { "code": null, "e": 28734, "s": 28669, "text": "Example 1:This example will display the marks of student in JSON" }, { "code": "<!DOCTYPE html><html> <head><script src=\"https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js\"></script> </head><body> <div ng-app=\"result\" ng-controller=\"resultCtrl\"> <h1>Result:</h1> <pre>{{marks | json}}</pre> </div> <script>var app = angular.module('result', []);app.controller('resultCtrl', function($scope) {$scope.marks = { \"Math\" : 98, \"Computer\" : 93, \"Physics\" : 95, \"Chemistry\" : 95, \"English\" : 74 };});</script> </body></html>", "e": 29241, "s": 28734, "text": null }, { "code": null, "e": 29250, "s": 29241, "text": "Output :" }, { "code": null, "e": 29337, "s": 29250, "text": "Example 2:This example will display fruits name in JSON with 10 spaces per indentation" }, { "code": "<!DOCTYPE html><html><head><script src=\"https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js\"></script></head><body> <div ng-app=\"fruit\" ng-controller=\"fruitCtrl\"> <h1>Fruits:</h1> <pre>{{fruit | json : 10}}</pre> </div> <script>var app = angular.module('fruit', []);app.controller('fruitCtrl', function($scope) { $scope.fruit = [\"Apple\", \"Banana\", \"Mango\"];});</script> </body></html>", "e": 29748, "s": 29337, "text": null }, { "code": null, "e": 29757, "s": 29748, "text": "Output :" }, { "code": null, "e": 29764, "s": 29757, "text": "Picked" }, { "code": null, "e": 29774, "s": 29764, "text": "AngularJS" }, { "code": null, "e": 29791, "s": 29774, "text": "Web Technologies" }, { "code": null, "e": 29889, "s": 29791, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29898, "s": 29889, "text": "Comments" }, { "code": null, "e": 29911, "s": 29898, "text": "Old Comments" }, { "code": null, "e": 29955, "s": 29911, "text": "Top 10 Angular Libraries For Web Developers" }, { "code": null, "e": 29975, "s": 29955, "text": "Angular File Upload" }, { "code": null, "e": 30006, "s": 29975, "text": "Auth Guards in Angular 9/10/11" }, { "code": null, "e": 30028, "s": 30006, "text": "Angular | keyup event" }, { "code": null, "e": 30070, "s": 30028, "text": "What is AOT and JIT Compiler in Angular ?" }, { "code": null, "e": 30112, "s": 30070, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 30145, "s": 30112, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 30188, "s": 30145, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 30250, "s": 30188, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" } ]
8085 program to find the factorial of a number - GeeksforGeeks
07 Sep, 2018 Problem – Write an assembly language program for calculating the factorial of a number using 8085 microprocessor. Example – Input : 04H Output : 18H as 04*03*02*01 = 24 in decimal => 18H In 8085 microprocessor, no direct instruction exists to multiply two numbers, so multiplication is done by repeated addition as 4×3 is equivalent to 4+4+4 (i.e., 3 times).Load 04H in D register -> Add 04H 3 times -> D register now contains 0CH -> Add 0CH 2 times -> D register now contains 18H -> Add 18H 1 time -> D register now contains 18H -> Output is 18H Algorithm – Load the data into register BTo start multiplication set D to 01HJump to step 7Decrements B to multiply previous numberJump to step 3 till value of B>0Take memory pointer to next location and store resultLoad E with contents of B and clear accumulatorRepeatedly add contents of D to accumulator E timesStore accumulator content to DGo to step 4 Load the data into register B To start multiplication set D to 01H Jump to step 7 Decrements B to multiply previous number Jump to step 3 till value of B>0 Take memory pointer to next location and store result Load E with contents of B and clear accumulator Repeatedly add contents of D to accumulator E times Store accumulator content to D Go to step 4 Explanation – First set register B with data.Set register D with data by calling MULTIPLY subroutine one time.Decrement B and add D to itself B times by calling MULTIPLY subroutine as 4*3 is equivalent to 4+4+4 (i.e., 3 times).Repeat the above step till B reaches 0 and then exit the program.The result is obtained in D register which is stored in memory First set register B with data. Set register D with data by calling MULTIPLY subroutine one time. Decrement B and add D to itself B times by calling MULTIPLY subroutine as 4*3 is equivalent to 4+4+4 (i.e., 3 times). Repeat the above step till B reaches 0 and then exit the program. The result is obtained in D register which is stored in memory aastha98 microprocessor system-programming Computer Organization & Architecture microprocessor Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Logical and Physical Address in Operating System Computer Organization and Architecture | Pipelining | Set 1 (Execution, Stages and Throughput) Architecture of 8085 microprocessor Computer Organization | RISC and CISC Memory Hierarchy Design and its Characteristics Pin diagram of 8086 microprocessor Architecture of 8086 Computer Organization | Booth's Algorithm Interrupts Flag register in 8085 microprocessor
[ { "code": null, "e": 25154, "s": 25126, "text": "\n07 Sep, 2018" }, { "code": null, "e": 25268, "s": 25154, "text": "Problem – Write an assembly language program for calculating the factorial of a number using 8085 microprocessor." }, { "code": null, "e": 25278, "s": 25268, "text": "Example –" }, { "code": null, "e": 25343, "s": 25278, "text": "Input : 04H\nOutput : 18H \nas 04*03*02*01 = 24 in decimal => 18H\n" }, { "code": null, "e": 25703, "s": 25343, "text": "In 8085 microprocessor, no direct instruction exists to multiply two numbers, so multiplication is done by repeated addition as 4×3 is equivalent to 4+4+4 (i.e., 3 times).Load 04H in D register -> Add 04H 3 times -> D register now contains 0CH -> Add 0CH 2 times -> D register now contains 18H -> Add 18H 1 time -> D register now contains 18H -> Output is 18H" }, { "code": null, "e": 25715, "s": 25703, "text": "Algorithm –" }, { "code": null, "e": 26060, "s": 25715, "text": "Load the data into register BTo start multiplication set D to 01HJump to step 7Decrements B to multiply previous numberJump to step 3 till value of B>0Take memory pointer to next location and store resultLoad E with contents of B and clear accumulatorRepeatedly add contents of D to accumulator E timesStore accumulator content to DGo to step 4" }, { "code": null, "e": 26090, "s": 26060, "text": "Load the data into register B" }, { "code": null, "e": 26127, "s": 26090, "text": "To start multiplication set D to 01H" }, { "code": null, "e": 26142, "s": 26127, "text": "Jump to step 7" }, { "code": null, "e": 26183, "s": 26142, "text": "Decrements B to multiply previous number" }, { "code": null, "e": 26216, "s": 26183, "text": "Jump to step 3 till value of B>0" }, { "code": null, "e": 26270, "s": 26216, "text": "Take memory pointer to next location and store result" }, { "code": null, "e": 26318, "s": 26270, "text": "Load E with contents of B and clear accumulator" }, { "code": null, "e": 26370, "s": 26318, "text": "Repeatedly add contents of D to accumulator E times" }, { "code": null, "e": 26401, "s": 26370, "text": "Store accumulator content to D" }, { "code": null, "e": 26414, "s": 26401, "text": "Go to step 4" }, { "code": null, "e": 26428, "s": 26414, "text": "Explanation –" }, { "code": null, "e": 26769, "s": 26428, "text": "First set register B with data.Set register D with data by calling MULTIPLY subroutine one time.Decrement B and add D to itself B times by calling MULTIPLY subroutine as 4*3 is equivalent to 4+4+4 (i.e., 3 times).Repeat the above step till B reaches 0 and then exit the program.The result is obtained in D register which is stored in memory" }, { "code": null, "e": 26801, "s": 26769, "text": "First set register B with data." }, { "code": null, "e": 26867, "s": 26801, "text": "Set register D with data by calling MULTIPLY subroutine one time." }, { "code": null, "e": 26985, "s": 26867, "text": "Decrement B and add D to itself B times by calling MULTIPLY subroutine as 4*3 is equivalent to 4+4+4 (i.e., 3 times)." }, { "code": null, "e": 27051, "s": 26985, "text": "Repeat the above step till B reaches 0 and then exit the program." }, { "code": null, "e": 27114, "s": 27051, "text": "The result is obtained in D register which is stored in memory" }, { "code": null, "e": 27123, "s": 27114, "text": "aastha98" }, { "code": null, "e": 27138, "s": 27123, "text": "microprocessor" }, { "code": null, "e": 27157, "s": 27138, "text": "system-programming" }, { "code": null, "e": 27194, "s": 27157, "text": "Computer Organization & Architecture" }, { "code": null, "e": 27209, "s": 27194, "text": "microprocessor" }, { "code": null, "e": 27307, "s": 27209, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27316, "s": 27307, "text": "Comments" }, { "code": null, "e": 27329, "s": 27316, "text": "Old Comments" }, { "code": null, "e": 27378, "s": 27329, "text": "Logical and Physical Address in Operating System" }, { "code": null, "e": 27473, "s": 27378, "text": "Computer Organization and Architecture | Pipelining | Set 1 (Execution, Stages and Throughput)" }, { "code": null, "e": 27509, "s": 27473, "text": "Architecture of 8085 microprocessor" }, { "code": null, "e": 27547, "s": 27509, "text": "Computer Organization | RISC and CISC" }, { "code": null, "e": 27595, "s": 27547, "text": "Memory Hierarchy Design and its Characteristics" }, { "code": null, "e": 27630, "s": 27595, "text": "Pin diagram of 8086 microprocessor" }, { "code": null, "e": 27651, "s": 27630, "text": "Architecture of 8086" }, { "code": null, "e": 27693, "s": 27651, "text": "Computer Organization | Booth's Algorithm" }, { "code": null, "e": 27704, "s": 27693, "text": "Interrupts" } ]
How to grep multiline search patterns in Linux?
In order to be able to grep multiple lines of pattern present in a file, we will make use of the number of grep command that Linux provides us with. But first, we must understand what a grep command is and how to use it on Linux. The grep command in Linux is used to filter searches in a file for a particular pattern of characters. It is one of the most used Linux utility commands to display the lines that contain the pattern that we are trying to search. Normally, the pattern that we are trying to search in the file is referred to as the regular expression. grep [options] pattern [files] While there are plenty of different options available to us, some of the most used are − -c : It lists only a count of the lines that match a pattern -h : displays the matched lines only. -i : Ignores, case for matching -l : prints filenames only -n : Display the matched lines and their line numbers. -v : It prints out all the lines that do not match the pattern Now, let’s consider a case where we want to find a particular pattern in all the files in a particular directory, say dir1. grep -rni "word" * In the above command replace the “word” placeholder with For that we make use of the command shown below − grep -rni "func main()" * The above command will try to find a string “func main()” in all the files in a particular directory and also in the subdirectories as well. main.go:120:func main() {} In case we only want to find a particular pattern in a single directory and not the subdirectories then we need to use the command shown below − grep -s "func main()" * Now suppose we have a text file named sample.txt whose content looks something like this. $ immukul@192 linux-questions-code % cat sample.txt blabla blabla foofoo here is the text2strike Just a pattern bar blabla blabla Now the command to search for multiline pattern is shown below grep -Pzo "(?s)^(\s*)\N*/foo/,/bar/p.*?{.*?^\1}" .txt foofoo here is the text2strike just a pattern bar
[ { "code": null, "e": 1292, "s": 1062, "text": "In order to be able to grep multiple lines of pattern present in a file, we will make use of the number of grep command that Linux provides us with. But first, we must understand what a grep command is and how to use it on Linux." }, { "code": null, "e": 1521, "s": 1292, "text": "The grep command in Linux is used to filter searches in a file for a particular pattern of characters. It is one of the most used Linux utility commands to display the lines that contain the pattern that we are trying to search." }, { "code": null, "e": 1626, "s": 1521, "text": "Normally, the pattern that we are trying to search in the file is referred to as the regular expression." }, { "code": null, "e": 1657, "s": 1626, "text": "grep [options] pattern [files]" }, { "code": null, "e": 1746, "s": 1657, "text": "While there are plenty of different options available to us, some of the most used are −" }, { "code": null, "e": 2022, "s": 1746, "text": "-c : It lists only a count of the lines that match a pattern\n-h : displays the matched lines only.\n-i : Ignores, case for matching\n-l : prints filenames only\n-n : Display the matched lines and their line numbers.\n-v : It prints out all the lines that do not match the pattern" }, { "code": null, "e": 2146, "s": 2022, "text": "Now, let’s consider a case where we want to find a particular pattern in all the files in a particular directory, say dir1." }, { "code": null, "e": 2165, "s": 2146, "text": "grep -rni \"word\" *" }, { "code": null, "e": 2222, "s": 2165, "text": "In the above command replace the “word” placeholder with" }, { "code": null, "e": 2272, "s": 2222, "text": "For that we make use of the command shown below −" }, { "code": null, "e": 2298, "s": 2272, "text": "grep -rni \"func main()\" *" }, { "code": null, "e": 2439, "s": 2298, "text": "The above command will try to find a string “func main()” in all the files in a particular directory and also in the subdirectories as well." }, { "code": null, "e": 2467, "s": 2439, "text": "main.go:120:func main() {}\n" }, { "code": null, "e": 2612, "s": 2467, "text": "In case we only want to find a particular pattern in a single directory and not the subdirectories then we need to use the command shown below −" }, { "code": null, "e": 2636, "s": 2612, "text": "grep -s \"func main()\" *" }, { "code": null, "e": 2726, "s": 2636, "text": "Now suppose we have a text file named sample.txt whose content looks something like this." }, { "code": null, "e": 2856, "s": 2726, "text": "$ immukul@192 linux-questions-code % cat sample.txt\nblabla\nblabla\nfoofoo\nhere\nis the\ntext2strike\nJust a pattern\nbar\nblabla\nblabla" }, { "code": null, "e": 2919, "s": 2856, "text": "Now the command to search for multiline pattern is shown below" }, { "code": null, "e": 2973, "s": 2919, "text": "grep -Pzo \"(?s)^(\\s*)\\N*/foo/,/bar/p.*?{.*?^\\1}\" .txt" }, { "code": null, "e": 3023, "s": 2973, "text": "foofoo\nhere\nis the\ntext2strike\njust a pattern\nbar" } ]
How can I rotate xtick labels through 90 degrees in Matplotlib?
To rotate xtick labels through 90 degrees, we can take the following steps − Make a list (x) of numbers. Make a list (x) of numbers. Add a subplot to the current figure. Add a subplot to the current figure. Set ticks on X-axis. Set ticks on X-axis. Set xtick labels and use rotate=90 as the arguments in the method. Set xtick labels and use rotate=90 as the arguments in the method. To display the figure, use show() method. To display the figure, use show() method. import matplotlib.pyplot as plt plt.rcParams["figure.figsize"] = [7.00, 3.50] plt.rcParams["figure.autolayout"] = True x = [1, 2, 3, 4] ax1 = plt.subplot() ax1.set_xticks(x) ax1.set_xticklabels(["one", "two", "three", "four"], rotation=90) plt.show()
[ { "code": null, "e": 1139, "s": 1062, "text": "To rotate xtick labels through 90 degrees, we can take the following steps −" }, { "code": null, "e": 1167, "s": 1139, "text": "Make a list (x) of numbers." }, { "code": null, "e": 1195, "s": 1167, "text": "Make a list (x) of numbers." }, { "code": null, "e": 1232, "s": 1195, "text": "Add a subplot to the current figure." }, { "code": null, "e": 1269, "s": 1232, "text": "Add a subplot to the current figure." }, { "code": null, "e": 1290, "s": 1269, "text": "Set ticks on X-axis." }, { "code": null, "e": 1311, "s": 1290, "text": "Set ticks on X-axis." }, { "code": null, "e": 1378, "s": 1311, "text": "Set xtick labels and use rotate=90 as the arguments in the method." }, { "code": null, "e": 1445, "s": 1378, "text": "Set xtick labels and use rotate=90 as the arguments in the method." }, { "code": null, "e": 1487, "s": 1445, "text": "To display the figure, use show() method." }, { "code": null, "e": 1529, "s": 1487, "text": "To display the figure, use show() method." }, { "code": null, "e": 1780, "s": 1529, "text": "import matplotlib.pyplot as plt\nplt.rcParams[\"figure.figsize\"] = [7.00, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\nx = [1, 2, 3, 4]\nax1 = plt.subplot()\nax1.set_xticks(x)\nax1.set_xticklabels([\"one\", \"two\", \"three\", \"four\"], rotation=90)\nplt.show()" } ]
Perl CGI Environment Variables
All the Perl CGI program will have access to the following environment variables. These variables play an important role while writing any CGI program in Perl. Here is a small Perl CGI program to list down all the CGI variables supported by your Web server. Click this link to see the result Get Environment #!/usr/bin/perl print "Content-type: text/html\n\n"; print "<font size=+1>Environment</font>\n"; foreach (sort keys %ENV) { print "<b>$_</b>: $ENV{$_}<br>\n"; } 1;
[ { "code": null, "e": 1222, "s": 1062, "text": "All the Perl CGI program will have access to the following environment variables. These variables play an important role while writing any CGI program in Perl." }, { "code": null, "e": 1370, "s": 1222, "text": "Here is a small Perl CGI program to list down all the CGI variables supported by your Web server. Click this link to see the result Get Environment" }, { "code": null, "e": 1537, "s": 1370, "text": "#!/usr/bin/perl\nprint \"Content-type: text/html\\n\\n\";\nprint \"<font size=+1>Environment</font>\\n\";\nforeach (sort keys %ENV) {\n print \"<b>$_</b>: $ENV{$_}<br>\\n\";\n}\n1;" } ]
JavaScript filter array by multiple strings?
To filter array by multiple strings, use for loop along with indexOf(). Following is the code − var details = [ 'My first Name is John and last Name is Smith', 'My first Name is John and last Name is Doe', 'Student first Name is John and last Name is Taylor' ]; var isPresent; var records = []; var matchWords = ['John', 'Doe']; for (var index = 0; index < details.length; index++){ isPresent = true; for (var outer = 0; outer< matchWords.length; outer++) { if (details[index].indexOf(matchWords[outer]) === -1) { isPresent = false; break; } } if (isPresent){ records.push(details[index]); } } console.log(records) To run the above program, you need to use the following command − node fileName.js. Here, my file name is demo151.js. This will produce the following output − PS C:\Users\Amit\JavaScript-code> node demo151.js [ 'My first Name is John and last Name is Doe'
[ { "code": null, "e": 1158, "s": 1062, "text": "To filter array by multiple strings, use for loop along with indexOf(). Following is the code −" }, { "code": null, "e": 1737, "s": 1158, "text": "var details = [\n 'My first Name is John and last Name is Smith',\n 'My first Name is John and last Name is Doe',\n 'Student first Name is John and last Name is Taylor'\n];\nvar isPresent;\nvar records = [];\nvar matchWords = ['John', 'Doe'];\nfor (var index = 0; index < details.length; index++){\n isPresent = true;\n for (var outer = 0; outer< matchWords.length; outer++) {\n if (details[index].indexOf(matchWords[outer]) === -1) {\n isPresent = false;\n break;\n }\n }\n if (isPresent){\n records.push(details[index]);\n }\n}\nconsole.log(records)" }, { "code": null, "e": 1803, "s": 1737, "text": "To run the above program, you need to use the following command −" }, { "code": null, "e": 1821, "s": 1803, "text": "node fileName.js." }, { "code": null, "e": 1855, "s": 1821, "text": "Here, my file name is demo151.js." }, { "code": null, "e": 1896, "s": 1855, "text": "This will produce the following output −" }, { "code": null, "e": 1993, "s": 1896, "text": "PS C:\\Users\\Amit\\JavaScript-code> node demo151.js\n[ 'My first Name is John and last Name is Doe'" } ]
MultiLingual Amazon Reviews Classification | by Priya Dwivedi | Towards Data Science
NLP is going to be the most transformational tech of this decade. And Transformer models are fuelling the advancement in NLP. In this blog, we look at an application of Transformers on multilingual data. Many businesses are now global in their reach and are collecting data in many languages. NLP is also building strong capabilities to deal with data in multiple languages. Transformer models can now be trained in many languages and seamlessly ingest text in them. This is amazing! In this blog, we use a pretrained multilingual XLM Roberta model and fine-tune it on a downstream classification task. XLM-Roberta has been pretrained in over 100 different languages! The model is able to give a state-of-the-art performance on a dataset with product reviews in multiple languages. I think this opens new opportunities for businesses to integrate data from their operations in different countries and generate valuable insights. The code for this model is available on my Colab Notebook here. I have also uploaded it to my GitHub here. The code here is a general-purpose code to run a classification using HuggingFace and the Datasets library. It can be modified easily to many other data sets and problems involving classification. For this blog, we use Amazon multilingual reviews corpus. This data set is made publicly available by Amazon and contains customer reviews across a variety of products in 6 different languages — English, Japanese, German, French, Spanish, and Chinese. The datasets library provides an easy API to download and access the data set. !pip install datasetsdataset = datasets.load_dataset('amazon_reviews_multi') The Data set has1.2MM reviews in the training set and 30K in the validation set. Each review has a title, category, text body and star rating. The star rating ranges from 1–5 with equal distribution across the 5 classes. An example of an English review with its rating is: Review: 'I’ve had good luck with this product when I’ve bought it in stores, but this particular one I bought though Amazon was watered down! The texture was much more viscous than any of the tubes I bought in person and it lasted me about half the time. You’re better off finding it in a shop than wasting your money on watered down face wash.'Rating: 2 We load the XML-Roberta model and use it to tokenize the text. The max length for text is set at 512 tokens. To improve model accuracy, we concatenate review_body, review_title and review_category. Since the actual data set is quite big, we train on 10% of the training sample. The shard functionality in the dataset library makes it easy to sample a fraction of the data for experimentation. The code to do this is below: dataset = dataset.shuffle(seed=123)train_dataset = dataset["train"].shard(index=1, num_shards=10)val_dataset = dataset['validation'].shard(index=1, num_shards=5) The tokenizer, encode_plus option is used to tokenize the text associated with the review body, review title and review category. The actual reviews have a star rating from 1 star to 5 stars. We convert this to target labels ranging from 0–4. To simplify the process of training, we use the Trainer library from HuggingFace. We load the pretrained XLM-Roberta-Base model using AutoModel functionality. from transformers import AutoModelForSequenceClassification, TrainingArguments, Trainerbatch_size = 8num_labels = 5model = AutoModelForSequenceClassification.from_pretrained('xlm-roberta-base', num_labels=num_labels) To instantiate the Trainer, we define two things: TrainingArguments — These include the location of our output directory, learning rate, batch size, num epochs etcCompute Metrics function for evaluation —We can define an evaluation metric that is run on val set during the training. TrainingArguments — These include the location of our output directory, learning rate, batch size, num epochs etc Compute Metrics function for evaluation —We can define an evaluation metric that is run on val set during the training. The datasets package also has many custom metrics defined. I love this functionality in the datasets library as it makes it very easy to calculate metrics ranging for bleu, rouge or custom SQuAD metrics on your data set. We first load the metric of our choice from the datasets library from datasets import load_metricmetric = load_metric('accuracy')f1_metric = load_metric('f1') The metric.compute() function can be used to get results. import numpy as npfake_preds = np.random.randint(1, 6, size=(64,))fake_labels = np.random.randint(1, 6, size=(64,))metric.compute(predictions=fake_preds, references=fake_labels)f1_metric.compute(predictions=fake_preds, references=fake_labels, average='weighted') To run it during training, we get predictions and labels from eval_pred and then run metric.compute(). That’s all!! To start training, now we can pass all these arguments to the Trainer. trainer = Trainer(model,args,train_dataset= encoded_train_dataset,eval_dataset=encoded_val_dataset,data_collator=SmartCollator(pad_token_id=tokenizer.pad_token_id),tokenizer=tokenizer,compute_metrics=compute_metrics) The model takes about 2 hours 20 minutes to train on a P100 instance on Colab. This is for a 10% sample of the training data set. The model gets to an accuracy of 59.9% which is slightly better than the accuracy of 59.2% reported in the paper that introduced the data set. Training on the full data set should further improve results. I want to touch on a couple of other cool things that can be used to improve training speed/model results The inspiration from this comes from the work here. During training time, we have to feed in samples of the same length. Since underlying text can be of different lengths, the typical approach is to pad everything to a max length. This is generally done at the full data set level where if the max length of the text is 512 tokens then everything is padded to that max length. However, this is inefficient. As an example, a sentence that is 20 tokens would also get padded to 512 tokens. Since attention is quadratic in computation, this would significantly slow down the training for such a sample. An optimization that can be done here is to pad to the max length in the batch instead of the max length in the data set. The code in my notebook does that by defining a smart data collator. Inside the data collator, the main block that does this is: max_size = max([len(ex['input_ids']) for ex in batch])for item in batch:batch_inputs += [pad_seq(item['input_ids'], max_size, self.pad_token_id)] This optimization cuts down training time in half! So very useful for a small block of code. Optuna is a hyperparameter searcher that can be easily integrated with the trainer class. It efficiently searches a large space of hyperparameters pruning unpromising trials early. For our experiment, we define the training arguments and the Trainer as before and let Optune optimize across a selected number of trials. trainer.hyperparameter_search(n_trials=15, direction=”maximize”) This blog shows how Transformer models can be used to work on multilingual data. We used HuggingFace Library and its many features to prepare our data and train it with just a few lines of code. The trained model has state-of-the-art results. The code is written in a very modular format and can be used for any type of classification problem. We also discuss features for dynamic padding to significantly speed up training and look at hyperparameter optimization to further improve results. I hope you give the code a try and train your own models. Please share your experience in the comments below. At Deep Learning Analytics, we are extremely passionate about using Machine Learning to solve real-world problems. We have helped many businesses deploy innovative AI-based solutions. Contact us through our website here if you see an opportunity to collaborate. XML-Roberta Paper HuggingFace Classification Notebook
[ { "code": null, "e": 656, "s": 172, "text": "NLP is going to be the most transformational tech of this decade. And Transformer models are fuelling the advancement in NLP. In this blog, we look at an application of Transformers on multilingual data. Many businesses are now global in their reach and are collecting data in many languages. NLP is also building strong capabilities to deal with data in multiple languages. Transformer models can now be trained in many languages and seamlessly ingest text in them. This is amazing!" }, { "code": null, "e": 1101, "s": 656, "text": "In this blog, we use a pretrained multilingual XLM Roberta model and fine-tune it on a downstream classification task. XLM-Roberta has been pretrained in over 100 different languages! The model is able to give a state-of-the-art performance on a dataset with product reviews in multiple languages. I think this opens new opportunities for businesses to integrate data from their operations in different countries and generate valuable insights." }, { "code": null, "e": 1208, "s": 1101, "text": "The code for this model is available on my Colab Notebook here. I have also uploaded it to my GitHub here." }, { "code": null, "e": 1405, "s": 1208, "text": "The code here is a general-purpose code to run a classification using HuggingFace and the Datasets library. It can be modified easily to many other data sets and problems involving classification." }, { "code": null, "e": 1736, "s": 1405, "text": "For this blog, we use Amazon multilingual reviews corpus. This data set is made publicly available by Amazon and contains customer reviews across a variety of products in 6 different languages — English, Japanese, German, French, Spanish, and Chinese. The datasets library provides an easy API to download and access the data set." }, { "code": null, "e": 1814, "s": 1736, "text": "!pip install datasetsdataset = datasets.load_dataset('amazon_reviews_multi')" }, { "code": null, "e": 2035, "s": 1814, "text": "The Data set has1.2MM reviews in the training set and 30K in the validation set. Each review has a title, category, text body and star rating. The star rating ranges from 1–5 with equal distribution across the 5 classes." }, { "code": null, "e": 2087, "s": 2035, "text": "An example of an English review with its rating is:" }, { "code": null, "e": 2442, "s": 2087, "text": "Review: 'I’ve had good luck with this product when I’ve bought it in stores, but this particular one I bought though Amazon was watered down! The texture was much more viscous than any of the tubes I bought in person and it lasted me about half the time. You’re better off finding it in a shop than wasting your money on watered down face wash.'Rating: 2" }, { "code": null, "e": 2640, "s": 2442, "text": "We load the XML-Roberta model and use it to tokenize the text. The max length for text is set at 512 tokens. To improve model accuracy, we concatenate review_body, review_title and review_category." }, { "code": null, "e": 2865, "s": 2640, "text": "Since the actual data set is quite big, we train on 10% of the training sample. The shard functionality in the dataset library makes it easy to sample a fraction of the data for experimentation. The code to do this is below:" }, { "code": null, "e": 3027, "s": 2865, "text": "dataset = dataset.shuffle(seed=123)train_dataset = dataset[\"train\"].shard(index=1, num_shards=10)val_dataset = dataset['validation'].shard(index=1, num_shards=5)" }, { "code": null, "e": 3270, "s": 3027, "text": "The tokenizer, encode_plus option is used to tokenize the text associated with the review body, review title and review category. The actual reviews have a star rating from 1 star to 5 stars. We convert this to target labels ranging from 0–4." }, { "code": null, "e": 3429, "s": 3270, "text": "To simplify the process of training, we use the Trainer library from HuggingFace. We load the pretrained XLM-Roberta-Base model using AutoModel functionality." }, { "code": null, "e": 3646, "s": 3429, "text": "from transformers import AutoModelForSequenceClassification, TrainingArguments, Trainerbatch_size = 8num_labels = 5model = AutoModelForSequenceClassification.from_pretrained('xlm-roberta-base', num_labels=num_labels)" }, { "code": null, "e": 3696, "s": 3646, "text": "To instantiate the Trainer, we define two things:" }, { "code": null, "e": 3929, "s": 3696, "text": "TrainingArguments — These include the location of our output directory, learning rate, batch size, num epochs etcCompute Metrics function for evaluation —We can define an evaluation metric that is run on val set during the training." }, { "code": null, "e": 4043, "s": 3929, "text": "TrainingArguments — These include the location of our output directory, learning rate, batch size, num epochs etc" }, { "code": null, "e": 4163, "s": 4043, "text": "Compute Metrics function for evaluation —We can define an evaluation metric that is run on val set during the training." }, { "code": null, "e": 4384, "s": 4163, "text": "The datasets package also has many custom metrics defined. I love this functionality in the datasets library as it makes it very easy to calculate metrics ranging for bleu, rouge or custom SQuAD metrics on your data set." }, { "code": null, "e": 4449, "s": 4384, "text": "We first load the metric of our choice from the datasets library" }, { "code": null, "e": 4543, "s": 4449, "text": "from datasets import load_metricmetric = load_metric('accuracy')f1_metric = load_metric('f1')" }, { "code": null, "e": 4601, "s": 4543, "text": "The metric.compute() function can be used to get results." }, { "code": null, "e": 4864, "s": 4601, "text": "import numpy as npfake_preds = np.random.randint(1, 6, size=(64,))fake_labels = np.random.randint(1, 6, size=(64,))metric.compute(predictions=fake_preds, references=fake_labels)f1_metric.compute(predictions=fake_preds, references=fake_labels, average='weighted')" }, { "code": null, "e": 4980, "s": 4864, "text": "To run it during training, we get predictions and labels from eval_pred and then run metric.compute(). That’s all!!" }, { "code": null, "e": 5051, "s": 4980, "text": "To start training, now we can pass all these arguments to the Trainer." }, { "code": null, "e": 5268, "s": 5051, "text": "trainer = Trainer(model,args,train_dataset= encoded_train_dataset,eval_dataset=encoded_val_dataset,data_collator=SmartCollator(pad_token_id=tokenizer.pad_token_id),tokenizer=tokenizer,compute_metrics=compute_metrics)" }, { "code": null, "e": 5398, "s": 5268, "text": "The model takes about 2 hours 20 minutes to train on a P100 instance on Colab. This is for a 10% sample of the training data set." }, { "code": null, "e": 5603, "s": 5398, "text": "The model gets to an accuracy of 59.9% which is slightly better than the accuracy of 59.2% reported in the paper that introduced the data set. Training on the full data set should further improve results." }, { "code": null, "e": 5709, "s": 5603, "text": "I want to touch on a couple of other cool things that can be used to improve training speed/model results" }, { "code": null, "e": 6309, "s": 5709, "text": "The inspiration from this comes from the work here. During training time, we have to feed in samples of the same length. Since underlying text can be of different lengths, the typical approach is to pad everything to a max length. This is generally done at the full data set level where if the max length of the text is 512 tokens then everything is padded to that max length. However, this is inefficient. As an example, a sentence that is 20 tokens would also get padded to 512 tokens. Since attention is quadratic in computation, this would significantly slow down the training for such a sample." }, { "code": null, "e": 6560, "s": 6309, "text": "An optimization that can be done here is to pad to the max length in the batch instead of the max length in the data set. The code in my notebook does that by defining a smart data collator. Inside the data collator, the main block that does this is:" }, { "code": null, "e": 6706, "s": 6560, "text": "max_size = max([len(ex['input_ids']) for ex in batch])for item in batch:batch_inputs += [pad_seq(item['input_ids'], max_size, self.pad_token_id)]" }, { "code": null, "e": 6799, "s": 6706, "text": "This optimization cuts down training time in half! So very useful for a small block of code." }, { "code": null, "e": 6980, "s": 6799, "text": "Optuna is a hyperparameter searcher that can be easily integrated with the trainer class. It efficiently searches a large space of hyperparameters pruning unpromising trials early." }, { "code": null, "e": 7119, "s": 6980, "text": "For our experiment, we define the training arguments and the Trainer as before and let Optune optimize across a selected number of trials." }, { "code": null, "e": 7184, "s": 7119, "text": "trainer.hyperparameter_search(n_trials=15, direction=”maximize”)" }, { "code": null, "e": 7676, "s": 7184, "text": "This blog shows how Transformer models can be used to work on multilingual data. We used HuggingFace Library and its many features to prepare our data and train it with just a few lines of code. The trained model has state-of-the-art results. The code is written in a very modular format and can be used for any type of classification problem. We also discuss features for dynamic padding to significantly speed up training and look at hyperparameter optimization to further improve results." }, { "code": null, "e": 7786, "s": 7676, "text": "I hope you give the code a try and train your own models. Please share your experience in the comments below." }, { "code": null, "e": 8048, "s": 7786, "text": "At Deep Learning Analytics, we are extremely passionate about using Machine Learning to solve real-world problems. We have helped many businesses deploy innovative AI-based solutions. Contact us through our website here if you see an opportunity to collaborate." }, { "code": null, "e": 8066, "s": 8048, "text": "XML-Roberta Paper" } ]
How to Clone tables in Delta Lake using Spark? | Towards Data Science
In Databricks delta lake, Clones are simply copies of your delta tables at a given snapshot in time, they have the same schema, structure, and partitioning as your source table. Once you create a clone the changes made to it do not affect the source table and vice-versa. This is a feature available in Databricks 7.2. Databricks Delta Lake supports two types of clones Shallow Clones: Shallow clones are simplistic copies of the delta table, meaning it is only a copy of the metadata of the source table and not the actual data itself. Because of that, it’s super fast and easy to create a shallow clone.Deep Clones: As the name suggests it’s a true copy of the source table. Shallow Clones: Shallow clones are simplistic copies of the delta table, meaning it is only a copy of the metadata of the source table and not the actual data itself. Because of that, it’s super fast and easy to create a shallow clone. Deep Clones: As the name suggests it’s a true copy of the source table. Cloning can open up a lot of doors in Delta Lake, primarily clones can play a significant role in archiving data and running short-lived test cases on your data set, the kind of experiments you want to keep secret from your source tables. For instance, you can test a workflow on a production table by creating a shallow clone and run your tests on the clone without corrupting the source data. Since a shallow clone is an instant copy you can quickly test optimization experiments to improve the performance of your queries and those changes remain on the clone. Another great use case for shallow clones, most often you would want to backfill or recalculate a large part of the historical data in your table. This can be easily realized using a shallow clone, run your backfill or recalculation on the clone, and then simply replace the original table with the clone when you are happy with it. Enough talk! Let’s get cloning and understand what goes on behind the scenes. Databricks offers a free community edition which is a really cool and powerful feature. As confessed by the authors themselves the entire book “Spark The Definitive Guide” was written using the community edition. Like most features, you can try out Delta Clones for free on the community edition. If you have not got a chance to set it up already, sign up today. It hardly takes a few minutes to sign up and spin up a cluster. Let’s set up some sample data for running our experiments. %sqlCreate database Person;Drop table if exists Person.Address;Create table Person.Address (addressId int,address string,customerId int,startDate string,endDate string)USING DELTALOCATION 'dbfs:/FileStore/DeltaClones/Address/' Insert some data into the table. %sqlinsert into Person.Addressselect 1 as addressId, "1 downing" as address, cast(rand()*10 as integer) as customerId, '2020-11-05' as startDate,null as endDateunionselect 2,"2 downing",cast(rand()*10 as integer), '2020-11-05',null Taking a quick look at the file structure, we should now have a delta table created with some parquet files to store the data and a _delta_log to track the transaction log. %fsls dbfs:/FileStore/DeltaClones/Address/ Let’s start by creating a shallow clone of our sample table. %sqlCreate or replace table Person.AddressShallowSHALLOW CLONE Person.AddressLOCATION 'dbfs:/FileStore/Clones/AddressShallow/' If we remember correctly from the definition, shallow clone just duplicates the metadata and not the actual data itself, let’s verify that claim. %fsls dbfs:/FileStore/Clones/AddressShallow/ Sweet! There are no files holding any data just the _delta_log, let’s check if we can query it by running a select. Shut the front door! We have a copy of our source table that we can easily query but, in reality, it's just a copy of the metadata. Using the input_file_name() function in our select query, it’s quite evident that the clone is reading files from the source table. Shallow clone essentially creates a new _delta_log that points to the original table files. If you analyze the transaction log of the shallow clone, you will see that the operation performed was a clone and there are literal pointers to the original table’s files. Now, let’s test the claim about isolation. Let’s make an update on our shallow clone. %sqlupdate Person.AddressShallowset endDate = '2021-01-01' Looking into the delta directory, we see that once you make a change to the clone data files start to appear. You can verify the same by running the select query over it. Now, the data is being read from the files that belong to the clone rather than the source table. So, that proves the theory of isolation. The shallow clone is the quickest way to duplicate your source table and run tons of experimentation on it without having to worry about destroying your source data. Now, go figure the use case! Let’s create a deep clone of our source table %sqlCreate or replace table Person.AddressDeepDEEP CLONE Person.AddressLOCATION 'dbfs:/FileStore/Clones/AddressDeep/' It may not be evident with the size of the table we have got here, but if it were a large table it would have taken a while to deep clone. Let’s do the same routine and check out the delta directory. You can instantly notice the difference between a shallow and deep clone, deep clones essentially make a true copy of your source table. Well, technically not a mirrored copy because a deep clone only clones the latest version of your source delta table. You do not get the history of transactions in your deep clone. You can verify that by describing the history of the deep clone and compare it with the history of your source table. For the remainder of it, deep clones behave exactly like shallow clones. Any or all changes made to the deep clones are isolated. Cloning in delta lake is not as difficult or controversial as cloning in genetics. There is so much potential with shallow clones, it makes working with large datasets slick, clean, and cost-effective. Yes, deep clones add a nice touch but I do not foresee see a huge need for it especially when you can use the “Create Table as Select” operation. What’s your take on Clones? Would love to know your thoughts and insights, especially on the kind of use cases that would justify using a deep clone. All the source code can be found here in this notebook. Do check it out!
[ { "code": null, "e": 491, "s": 172, "text": "In Databricks delta lake, Clones are simply copies of your delta tables at a given snapshot in time, they have the same schema, structure, and partitioning as your source table. Once you create a clone the changes made to it do not affect the source table and vice-versa. This is a feature available in Databricks 7.2." }, { "code": null, "e": 542, "s": 491, "text": "Databricks Delta Lake supports two types of clones" }, { "code": null, "e": 849, "s": 542, "text": "Shallow Clones: Shallow clones are simplistic copies of the delta table, meaning it is only a copy of the metadata of the source table and not the actual data itself. Because of that, it’s super fast and easy to create a shallow clone.Deep Clones: As the name suggests it’s a true copy of the source table." }, { "code": null, "e": 1085, "s": 849, "text": "Shallow Clones: Shallow clones are simplistic copies of the delta table, meaning it is only a copy of the metadata of the source table and not the actual data itself. Because of that, it’s super fast and easy to create a shallow clone." }, { "code": null, "e": 1157, "s": 1085, "text": "Deep Clones: As the name suggests it’s a true copy of the source table." }, { "code": null, "e": 1396, "s": 1157, "text": "Cloning can open up a lot of doors in Delta Lake, primarily clones can play a significant role in archiving data and running short-lived test cases on your data set, the kind of experiments you want to keep secret from your source tables." }, { "code": null, "e": 1721, "s": 1396, "text": "For instance, you can test a workflow on a production table by creating a shallow clone and run your tests on the clone without corrupting the source data. Since a shallow clone is an instant copy you can quickly test optimization experiments to improve the performance of your queries and those changes remain on the clone." }, { "code": null, "e": 2054, "s": 1721, "text": "Another great use case for shallow clones, most often you would want to backfill or recalculate a large part of the historical data in your table. This can be easily realized using a shallow clone, run your backfill or recalculation on the clone, and then simply replace the original table with the clone when you are happy with it." }, { "code": null, "e": 2132, "s": 2054, "text": "Enough talk! Let’s get cloning and understand what goes on behind the scenes." }, { "code": null, "e": 2345, "s": 2132, "text": "Databricks offers a free community edition which is a really cool and powerful feature. As confessed by the authors themselves the entire book “Spark The Definitive Guide” was written using the community edition." }, { "code": null, "e": 2559, "s": 2345, "text": "Like most features, you can try out Delta Clones for free on the community edition. If you have not got a chance to set it up already, sign up today. It hardly takes a few minutes to sign up and spin up a cluster." }, { "code": null, "e": 2618, "s": 2559, "text": "Let’s set up some sample data for running our experiments." }, { "code": null, "e": 2845, "s": 2618, "text": "%sqlCreate database Person;Drop table if exists Person.Address;Create table Person.Address (addressId int,address string,customerId int,startDate string,endDate string)USING DELTALOCATION 'dbfs:/FileStore/DeltaClones/Address/'" }, { "code": null, "e": 2878, "s": 2845, "text": "Insert some data into the table." }, { "code": null, "e": 3110, "s": 2878, "text": "%sqlinsert into Person.Addressselect 1 as addressId, \"1 downing\" as address, cast(rand()*10 as integer) as customerId, '2020-11-05' as startDate,null as endDateunionselect 2,\"2 downing\",cast(rand()*10 as integer), '2020-11-05',null" }, { "code": null, "e": 3283, "s": 3110, "text": "Taking a quick look at the file structure, we should now have a delta table created with some parquet files to store the data and a _delta_log to track the transaction log." }, { "code": null, "e": 3326, "s": 3283, "text": "%fsls dbfs:/FileStore/DeltaClones/Address/" }, { "code": null, "e": 3387, "s": 3326, "text": "Let’s start by creating a shallow clone of our sample table." }, { "code": null, "e": 3514, "s": 3387, "text": "%sqlCreate or replace table Person.AddressShallowSHALLOW CLONE Person.AddressLOCATION 'dbfs:/FileStore/Clones/AddressShallow/'" }, { "code": null, "e": 3660, "s": 3514, "text": "If we remember correctly from the definition, shallow clone just duplicates the metadata and not the actual data itself, let’s verify that claim." }, { "code": null, "e": 3705, "s": 3660, "text": "%fsls dbfs:/FileStore/Clones/AddressShallow/" }, { "code": null, "e": 3821, "s": 3705, "text": "Sweet! There are no files holding any data just the _delta_log, let’s check if we can query it by running a select." }, { "code": null, "e": 4085, "s": 3821, "text": "Shut the front door! We have a copy of our source table that we can easily query but, in reality, it's just a copy of the metadata. Using the input_file_name() function in our select query, it’s quite evident that the clone is reading files from the source table." }, { "code": null, "e": 4350, "s": 4085, "text": "Shallow clone essentially creates a new _delta_log that points to the original table files. If you analyze the transaction log of the shallow clone, you will see that the operation performed was a clone and there are literal pointers to the original table’s files." }, { "code": null, "e": 4436, "s": 4350, "text": "Now, let’s test the claim about isolation. Let’s make an update on our shallow clone." }, { "code": null, "e": 4495, "s": 4436, "text": "%sqlupdate Person.AddressShallowset endDate = '2021-01-01'" }, { "code": null, "e": 4605, "s": 4495, "text": "Looking into the delta directory, we see that once you make a change to the clone data files start to appear." }, { "code": null, "e": 4764, "s": 4605, "text": "You can verify the same by running the select query over it. Now, the data is being read from the files that belong to the clone rather than the source table." }, { "code": null, "e": 5000, "s": 4764, "text": "So, that proves the theory of isolation. The shallow clone is the quickest way to duplicate your source table and run tons of experimentation on it without having to worry about destroying your source data. Now, go figure the use case!" }, { "code": null, "e": 5046, "s": 5000, "text": "Let’s create a deep clone of our source table" }, { "code": null, "e": 5164, "s": 5046, "text": "%sqlCreate or replace table Person.AddressDeepDEEP CLONE Person.AddressLOCATION 'dbfs:/FileStore/Clones/AddressDeep/'" }, { "code": null, "e": 5303, "s": 5164, "text": "It may not be evident with the size of the table we have got here, but if it were a large table it would have taken a while to deep clone." }, { "code": null, "e": 5364, "s": 5303, "text": "Let’s do the same routine and check out the delta directory." }, { "code": null, "e": 5800, "s": 5364, "text": "You can instantly notice the difference between a shallow and deep clone, deep clones essentially make a true copy of your source table. Well, technically not a mirrored copy because a deep clone only clones the latest version of your source delta table. You do not get the history of transactions in your deep clone. You can verify that by describing the history of the deep clone and compare it with the history of your source table." }, { "code": null, "e": 5930, "s": 5800, "text": "For the remainder of it, deep clones behave exactly like shallow clones. Any or all changes made to the deep clones are isolated." }, { "code": null, "e": 6013, "s": 5930, "text": "Cloning in delta lake is not as difficult or controversial as cloning in genetics." }, { "code": null, "e": 6278, "s": 6013, "text": "There is so much potential with shallow clones, it makes working with large datasets slick, clean, and cost-effective. Yes, deep clones add a nice touch but I do not foresee see a huge need for it especially when you can use the “Create Table as Select” operation." }, { "code": null, "e": 6428, "s": 6278, "text": "What’s your take on Clones? Would love to know your thoughts and insights, especially on the kind of use cases that would justify using a deep clone." } ]
Find length of loop in linked list in C++
In this problem, we are given a linked list that might contain loops. Our task is to find the length of the loop in the linked list. Problem Description: we need to count the number of nodes in the loop if it contains a loop otherwise return -1. Let’s take an example to understand the problem, Input: linked-list : Output: 8 To solve the problem, we first need to check whether the linked list contains a loop. An approach to check this is using Floyd’s Cycle Finding Algorithm. In Floyd’s Cycle Finding Algorithm, we will traverse the linked list using two pointers. One slowPointer that increases by 1 and another one is fastPointer that increases by 2. If both numbers meet at some point then there exists a loop otherwise not. If there exists a loop, we need to count the number of nodes that are present in the loop. For this we will start from the point where slowPointer and fastPointer meet and then count the number of nodes traversed to get to the position back. Live Demo #include<bits/stdc++.h> using namespace std; struct Node { int data; struct Node* next; }; int countLoopNodespoint(struct Node *n) { int res = 1; struct Node *temp = n; while (temp->next != n) { res++; temp = temp->next; } return res; } int countLoopNode(struct Node *list) { struct Node *slowPtr = list, *fastPtr = list; while (slowPtr && fastPtr && fastPtr->next) { slowPtr = slowPtr->next; fastPtr = fastPtr->next->next; if (slowPtr == fastPtr) return countLoopNodespoint(slowPtr); } return 0; } struct Node *newNode(int key) { struct Node *temp = (struct Node*)malloc(sizeof(struct Node)); temp->data = key; temp->next = NULL; return temp; } int main() { struct Node *head = newNode(1); head->next = newNode(2); head->next->next = newNode(3); head->next->next->next = newNode(4); head->next->next->next->next = newNode(5); head->next->next->next->next->next = newNode(6); head->next->next->next->next->next->next = newNode(7); head->next->next->next->next->next->next->next = head->next; cout<<"The number of nodes in the loop are "<<countLoopNode(head); return 0; } The number of nodes in the loop are 6>]
[ { "code": null, "e": 1196, "s": 1062, "text": "In this problem, we are given a linked list that might contain loops. Our task is to find the length of the loop in the linked list. " }, { "code": null, "e": 1309, "s": 1196, "text": "Problem Description: we need to count the number of nodes in the loop if it contains a loop otherwise return -1." }, { "code": null, "e": 1359, "s": 1309, "text": "Let’s take an example to understand the problem, " }, { "code": null, "e": 1380, "s": 1359, "text": "Input: linked-list :" }, { "code": null, "e": 1390, "s": 1380, "text": "Output: 8" }, { "code": null, "e": 1545, "s": 1390, "text": "To solve the problem, we first need to check whether the linked list contains a loop. An approach to check this is using Floyd’s Cycle Finding Algorithm. " }, { "code": null, "e": 1797, "s": 1545, "text": "In Floyd’s Cycle Finding Algorithm, we will traverse the linked list using two pointers. One slowPointer that increases by 1 and another one is fastPointer that increases by 2. If both numbers meet at some point then there exists a loop otherwise not." }, { "code": null, "e": 2039, "s": 1797, "text": "If there exists a loop, we need to count the number of nodes that are present in the loop. For this we will start from the point where slowPointer and fastPointer meet and then count the number of nodes traversed to get to the position back." }, { "code": null, "e": 2049, "s": 2039, "text": "Live Demo" }, { "code": null, "e": 3252, "s": 2049, "text": "#include<bits/stdc++.h>\nusing namespace std;\n\nstruct Node {\n int data;\n struct Node* next;\n};\n\nint countLoopNodespoint(struct Node *n) {\n int res = 1;\n struct Node *temp = n;\n while (temp->next != n) {\n \n res++;\n temp = temp->next;\n }\n return res;\n}\n\nint countLoopNode(struct Node *list) {\n \n struct Node *slowPtr = list, *fastPtr = list;\n while (slowPtr && fastPtr && fastPtr->next) {\n slowPtr = slowPtr->next;\n fastPtr = fastPtr->next->next;\n\n if (slowPtr == fastPtr)\n return countLoopNodespoint(slowPtr);\n }\n return 0;\n}\n\nstruct Node *newNode(int key) {\n struct Node *temp = (struct Node*)malloc(sizeof(struct Node));\n temp->data = key;\n temp->next = NULL;\n return temp;\n}\n\nint main() {\n struct Node *head = newNode(1);\n head->next = newNode(2);\n head->next->next = newNode(3);\n head->next->next->next = newNode(4);\n head->next->next->next->next = newNode(5);\n head->next->next->next->next->next = newNode(6);\n head->next->next->next->next->next->next = newNode(7);\n head->next->next->next->next->next->next->next = head->next;\n\n cout<<\"The number of nodes in the loop are \"<<countLoopNode(head);\n\n return 0;\n}" }, { "code": null, "e": 3292, "s": 3252, "text": "The number of nodes in the loop are 6>]" } ]
Bash Scripting - How to check If File Exists - GeeksforGeeks
28 Nov, 2021 In this article, we will write a bash script to check if files exist or not. test [expression] [ expression ] [[ expression ]] Here, in expression, we write parameter and file name. Let us see some parameters that can be used in the expression: – –f: It returns True if the file exists as a common ( regular ) file. -d: it returns True if directory exists. -e: It returns True if any type of file exists. -c: It returns True if the character file exists. -r: It returns True if a readable file exists. –w: It returns True if a writable file exists. -x: It returns True if an executable file exists. -p: It returns True if the file exists as a pipe. -S: It returns True if the file exists as a socket. -s: it returns True if a file exists and the size of the file is not zero. -L: It returns True if the file of symbolic link exists. -g: It returns True if the file exists and hold set group id flag is set.. -G: It returns True if the file exists and holds the same group id that is in process. -k: It returns True if the file exists and the sticky bit flag is set. Now, there are some more parameters for comparison between the two files. -ef: It returns True if both files exist and indicate the same file. Example : FirstFile -ef SecondFile -nt: It returns True if FirstFile is newer than Secondfile. Example : FirstFile -nt FileOld -ot: It returns True if FirstFile is older than SecondFile. Example: FirstFile -ot SecondFile [ expression ]: First, create a file named ” FirstFile.sh ” and write the following script on it #!/bin/bash # using [ expression ] syntax and in place # of File.txt you can write your file name if [ -f "File.txt" ]; then # if file exist the it will be printed echo "File is exist" else # is it is not exist then it will be printed echo "File is not exist" fi Now save and run the file using the following command $ chmod +x ./FirstFile.sh $ ./FirstFile.sh Output : Output Note: As the ” File.txt ” is present in the system. So, it printed ” File is exists “. test [expression]: Now, modify the above script in ” FirstFile.sh ” as follows #!/bin/bash # using test expression syntax and in place # of File2.txt you can write your file name if test -f "File2.txt" ; then # if file exist the it will be printed echo "File is exist" else # is it is not exist then it will be printed echo "File is not exist" fi Now, again save and run the file using the following command $ chmod +x ./FirstFile.sh $ ./FirstFile.sh Output : Output Note: As the ” File2.txt ” is not present in the system. So, it printed ” File is not exist “. [[ expression ]]: Again modify the above script in ” FirstFile.sh ” as follows #!/bin/bash # using [[ expression ]] syntax and in place # of File3.txt you can write your file name if test -f "File3.txt" ; then # if file exist the it will be printed echo "File is exist" else # is it is not exist then it will be printed echo "File is not exist" fi Now, again save and run the file using the following command $ chmod +x ./FirstFile.sh $ ./FirstFile.sh Output : Output Note: As the ” File3.txt ” is present in the system. So, it printed ” File is exist “. Using -d parameter: Create a file named ” FirstDir.sh ” and write the following script in it !/bin/bash if [[ -d "GFG_dir" ]] ; # Here GFG_dir is directory and in place of GFG_dir you can write your Directory name then echo "Directory is exist" # If GFG_dir exist then it will be printed else echo "Directory is not exist" # If GFG_dir is not exist then it will be printed fi Now Save and run the file using the following command $ chmod +x ./FirstDir.sh $ ./FirstDir.sh Output : Output Note: As the ” GFG_dir ” is present in the system. So, it printed ” Directory is exist “. Similarly, you can use -f , -e , -w , -r , -c ,etc. ( according to their uses ) in place of -d for checking the existence of different types of files. Using -nt parameter Create a file name ” Comparison_File.sh ” and write the following script #!/bin/bash # New_file.txt and Old_File.txt are names of two files. if [[ "New_File.txt" -nt "Old_File.txt" ]] ; then # This will be printed if Condition is true echo "New_File.txt is newer than Old_File.txt" else # This will be printed if Condition is False echo "New_File.txt is not newer than Old_File.txt" fi Now Save and run the file using the following command $ chmod +x ./Comparison_File.sh $ ./Comparison_File.sh Output : Output Note: As both files are present in the system and ” New_File.txt ” is newer than ” Old_File.txt “ Create a file named ” Check_Exist.sh ” and write the following script in it #!/bin/bash # using ! before -f parameter to check if # file does not exist if [[ ! -f "GFG.txt" ]] ; then # This will printed if condition is True echo "File is not exist" else # This will be printed if condition if False echo "File is exist" fi Now Save and run the file using the following command $ chmod +x ./Check_Exist.sh $ ./Check_Exist.sh Output : Output Note: ” GFG.txt ” is not present in the system. So, it will print “File is not exist” Create a file named ” Geeks_File.sh ” and write the following script in it #!/bin/bash # If File exist then first statement will be # printed and if it is not exist then 2nd # statement will be printed. [ -f "GFG_File.txt" ] && echo "File is exist" || echo "File is not exist" Now Save and run the file using the following command $ chmod +x ./Geeks_File.sh $ ./Geeks_File.sh Output : Output Note: As the ” GFG_File.txt ” is present in the system. So, it printed ” File is exist “. Bash-Script Picked Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments scp command in Linux with Examples nohup Command in Linux with Examples mv command in Linux with examples Thread functions in C/C++ Docker - COPY Instruction chown command in Linux with Examples nslookup command in Linux with Examples SED command in Linux | Set 2 Named Pipe or FIFO with example C program uniq Command in LINUX with examples
[ { "code": null, "e": 24015, "s": 23987, "text": "\n28 Nov, 2021" }, { "code": null, "e": 24093, "s": 24015, "text": "In this article, we will write a bash script to check if files exist or not. " }, { "code": null, "e": 24111, "s": 24093, "text": "test [expression]" }, { "code": null, "e": 24126, "s": 24111, "text": "[ expression ]" }, { "code": null, "e": 24143, "s": 24126, "text": "[[ expression ]]" }, { "code": null, "e": 24263, "s": 24143, "text": "Here, in expression, we write parameter and file name. Let us see some parameters that can be used in the expression: –" }, { "code": null, "e": 24333, "s": 24263, "text": "–f: It returns True if the file exists as a common ( regular ) file." }, { "code": null, "e": 24374, "s": 24333, "text": "-d: it returns True if directory exists." }, { "code": null, "e": 24422, "s": 24374, "text": "-e: It returns True if any type of file exists." }, { "code": null, "e": 24472, "s": 24422, "text": "-c: It returns True if the character file exists." }, { "code": null, "e": 24519, "s": 24472, "text": "-r: It returns True if a readable file exists." }, { "code": null, "e": 24566, "s": 24519, "text": "–w: It returns True if a writable file exists." }, { "code": null, "e": 24616, "s": 24566, "text": "-x: It returns True if an executable file exists." }, { "code": null, "e": 24666, "s": 24616, "text": "-p: It returns True if the file exists as a pipe." }, { "code": null, "e": 24718, "s": 24666, "text": "-S: It returns True if the file exists as a socket." }, { "code": null, "e": 24793, "s": 24718, "text": "-s: it returns True if a file exists and the size of the file is not zero." }, { "code": null, "e": 24850, "s": 24793, "text": "-L: It returns True if the file of symbolic link exists." }, { "code": null, "e": 24925, "s": 24850, "text": "-g: It returns True if the file exists and hold set group id flag is set.." }, { "code": null, "e": 25012, "s": 24925, "text": "-G: It returns True if the file exists and holds the same group id that is in process." }, { "code": null, "e": 25084, "s": 25012, "text": " -k: It returns True if the file exists and the sticky bit flag is set." }, { "code": null, "e": 25158, "s": 25084, "text": "Now, there are some more parameters for comparison between the two files." }, { "code": null, "e": 25228, "s": 25158, "text": "-ef: It returns True if both files exist and indicate the same file. " }, { "code": null, "e": 25239, "s": 25228, "text": "Example : " }, { "code": null, "e": 25264, "s": 25239, "text": "FirstFile -ef SecondFile" }, { "code": null, "e": 25324, "s": 25264, "text": "-nt: It returns True if FirstFile is newer than Secondfile." }, { "code": null, "e": 25334, "s": 25324, "text": "Example :" }, { "code": null, "e": 25356, "s": 25334, "text": "FirstFile -nt FileOld" }, { "code": null, "e": 25416, "s": 25356, "text": "-ot: It returns True if FirstFile is older than SecondFile." }, { "code": null, "e": 25426, "s": 25416, "text": "Example: " }, { "code": null, "e": 25451, "s": 25426, "text": "FirstFile -ot SecondFile" }, { "code": null, "e": 25548, "s": 25451, "text": "[ expression ]: First, create a file named ” FirstFile.sh ” and write the following script on it" }, { "code": null, "e": 25818, "s": 25548, "text": "#!/bin/bash\n\n# using [ expression ] syntax and in place \n# of File.txt you can write your file name \nif [ -f \"File.txt\" ]; \nthen\n\n# if file exist the it will be printed \necho \"File is exist\"\nelse\n\n# is it is not exist then it will be printed\necho \"File is not exist\"\nfi" }, { "code": null, "e": 25872, "s": 25818, "text": "Now save and run the file using the following command" }, { "code": null, "e": 25915, "s": 25872, "text": "$ chmod +x ./FirstFile.sh\n$ ./FirstFile.sh" }, { "code": null, "e": 25925, "s": 25915, "text": "Output : " }, { "code": null, "e": 25932, "s": 25925, "text": "Output" }, { "code": null, "e": 26019, "s": 25932, "text": "Note: As the ” File.txt ” is present in the system. So, it printed ” File is exists “." }, { "code": null, "e": 26098, "s": 26019, "text": "test [expression]: Now, modify the above script in ” FirstFile.sh ” as follows" }, { "code": null, "e": 26371, "s": 26098, "text": "#!/bin/bash\n\n# using test expression syntax and in place \n# of File2.txt you can write your file name\nif test -f \"File2.txt\" ;\nthen\n\n# if file exist the it will be printed \necho \"File is exist\"\nelse\n\n# is it is not exist then it will be printed\necho \"File is not exist\"\nfi" }, { "code": null, "e": 26432, "s": 26371, "text": "Now, again save and run the file using the following command" }, { "code": null, "e": 26475, "s": 26432, "text": "$ chmod +x ./FirstFile.sh\n$ ./FirstFile.sh" }, { "code": null, "e": 26484, "s": 26475, "text": "Output :" }, { "code": null, "e": 26491, "s": 26484, "text": "Output" }, { "code": null, "e": 26586, "s": 26491, "text": "Note: As the ” File2.txt ” is not present in the system. So, it printed ” File is not exist “." }, { "code": null, "e": 26665, "s": 26586, "text": "[[ expression ]]: Again modify the above script in ” FirstFile.sh ” as follows" }, { "code": null, "e": 26939, "s": 26665, "text": "#!/bin/bash\n\n# using [[ expression ]] syntax and in place \n# of File3.txt you can write your file name\nif test -f \"File3.txt\" ;\nthen\n\n# if file exist the it will be printed \necho \"File is exist\"\nelse\n\n# is it is not exist then it will be printed\necho \"File is not exist\"\nfi" }, { "code": null, "e": 27000, "s": 26939, "text": "Now, again save and run the file using the following command" }, { "code": null, "e": 27043, "s": 27000, "text": "$ chmod +x ./FirstFile.sh\n$ ./FirstFile.sh" }, { "code": null, "e": 27052, "s": 27043, "text": "Output :" }, { "code": null, "e": 27059, "s": 27052, "text": "Output" }, { "code": null, "e": 27146, "s": 27059, "text": "Note: As the ” File3.txt ” is present in the system. So, it printed ” File is exist “." }, { "code": null, "e": 27239, "s": 27146, "text": "Using -d parameter: Create a file named ” FirstDir.sh ” and write the following script in it" }, { "code": null, "e": 27523, "s": 27239, "text": "!/bin/bash\nif [[ -d \"GFG_dir\" ]] ; # Here GFG_dir\n is directory and in place of GFG_dir you can write your Directory name\nthen\necho \"Directory is exist\" # If GFG_dir exist then it will be printed\nelse\necho \"Directory is not exist\" # If GFG_dir is not exist then it will be printed\nfi" }, { "code": null, "e": 27577, "s": 27523, "text": "Now Save and run the file using the following command" }, { "code": null, "e": 27618, "s": 27577, "text": "$ chmod +x ./FirstDir.sh\n$ ./FirstDir.sh" }, { "code": null, "e": 27627, "s": 27618, "text": "Output :" }, { "code": null, "e": 27634, "s": 27627, "text": "Output" }, { "code": null, "e": 27724, "s": 27634, "text": "Note: As the ” GFG_dir ” is present in the system. So, it printed ” Directory is exist “." }, { "code": null, "e": 27875, "s": 27724, "text": "Similarly, you can use -f , -e , -w , -r , -c ,etc. ( according to their uses ) in place of -d for checking the existence of different types of files." }, { "code": null, "e": 27895, "s": 27875, "text": "Using -nt parameter" }, { "code": null, "e": 27969, "s": 27895, "text": "Create a file name ” Comparison_File.sh ” and write the following script " }, { "code": null, "e": 28287, "s": 27969, "text": "#!/bin/bash\n\n# New_file.txt and Old_File.txt are names of two files.\nif [[ \"New_File.txt\" -nt \"Old_File.txt\" ]] ;\nthen\n\n# This will be printed if Condition is true\necho \"New_File.txt is newer than Old_File.txt\" \nelse\n\n# This will be printed if Condition is False\necho \"New_File.txt is not newer than Old_File.txt\"\nfi" }, { "code": null, "e": 28341, "s": 28287, "text": "Now Save and run the file using the following command" }, { "code": null, "e": 28396, "s": 28341, "text": "$ chmod +x ./Comparison_File.sh\n$ ./Comparison_File.sh" }, { "code": null, "e": 28405, "s": 28396, "text": "Output :" }, { "code": null, "e": 28412, "s": 28405, "text": "Output" }, { "code": null, "e": 28510, "s": 28412, "text": "Note: As both files are present in the system and ” New_File.txt ” is newer than ” Old_File.txt “" }, { "code": null, "e": 28587, "s": 28510, "text": "Create a file named ” Check_Exist.sh ” and write the following script in it " }, { "code": null, "e": 28838, "s": 28587, "text": "#!/bin/bash\n\n# using ! before -f parameter to check if \n# file does not exist\nif [[ ! -f \"GFG.txt\" ]] ;\nthen\n\n# This will printed if condition is True\necho \"File is not exist\"\nelse\n\n# This will be printed if condition if False\necho \"File is exist\"\nfi" }, { "code": null, "e": 28892, "s": 28838, "text": "Now Save and run the file using the following command" }, { "code": null, "e": 28939, "s": 28892, "text": "$ chmod +x ./Check_Exist.sh\n$ ./Check_Exist.sh" }, { "code": null, "e": 28948, "s": 28939, "text": "Output :" }, { "code": null, "e": 28955, "s": 28948, "text": "Output" }, { "code": null, "e": 29042, "s": 28955, "text": "Note: ” GFG.txt ” is not present in the system. So, it will print “File is not exist”" }, { "code": null, "e": 29117, "s": 29042, "text": "Create a file named ” Geeks_File.sh ” and write the following script in it" }, { "code": null, "e": 29320, "s": 29117, "text": "#!/bin/bash\n\n# If File exist then first statement will be\n# printed and if it is not exist then 2nd\n# statement will be printed.\n[ -f \"GFG_File.txt\" ] && echo \"File is exist\" || echo \"File is not exist\"" }, { "code": null, "e": 29374, "s": 29320, "text": "Now Save and run the file using the following command" }, { "code": null, "e": 29419, "s": 29374, "text": "$ chmod +x ./Geeks_File.sh\n$ ./Geeks_File.sh" }, { "code": null, "e": 29429, "s": 29419, "text": "Output : " }, { "code": null, "e": 29436, "s": 29429, "text": "Output" }, { "code": null, "e": 29526, "s": 29436, "text": "Note: As the ” GFG_File.txt ” is present in the system. So, it printed ” File is exist “." }, { "code": null, "e": 29538, "s": 29526, "text": "Bash-Script" }, { "code": null, "e": 29545, "s": 29538, "text": "Picked" }, { "code": null, "e": 29556, "s": 29545, "text": "Linux-Unix" }, { "code": null, "e": 29654, "s": 29556, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29663, "s": 29654, "text": "Comments" }, { "code": null, "e": 29676, "s": 29663, "text": "Old Comments" }, { "code": null, "e": 29711, "s": 29676, "text": "scp command in Linux with Examples" }, { "code": null, "e": 29748, "s": 29711, "text": "nohup Command in Linux with Examples" }, { "code": null, "e": 29782, "s": 29748, "text": "mv command in Linux with examples" }, { "code": null, "e": 29808, "s": 29782, "text": "Thread functions in C/C++" }, { "code": null, "e": 29834, "s": 29808, "text": "Docker - COPY Instruction" }, { "code": null, "e": 29871, "s": 29834, "text": "chown command in Linux with Examples" }, { "code": null, "e": 29911, "s": 29871, "text": "nslookup command in Linux with Examples" }, { "code": null, "e": 29940, "s": 29911, "text": "SED command in Linux | Set 2" }, { "code": null, "e": 29982, "s": 29940, "text": "Named Pipe or FIFO with example C program" } ]
LifecycleObserever with Activities in Android - GeeksforGeeks
05 May, 2021 LifecycleObserever is Observer is one of the Jetpack Architecture components and is an interface that observes and performs the specified task depending upon the Lifecycle owner’s Lifecycle changes. For example, MainActivity has its own lifecycle and itself is Lifecycle owner and we can implement the LifecycleObserever interface and attach this observer to MainActivity so that certain operations can be performed as the lifecycle of the MainActivity changes. In this article, it’s been demonstrated how the LifecycleObserever performs the tasks as Lifecycle owner’s lifecycle changes. Have a look at the following video to get an overview of the discussion. Note: This discussion is implemented using the Kotlin language. Step 1: Create an empty activity project Create an empty activity Android studio project and select Kotlin as the programming language. Refer Android | How to Create/Start a New Project in Android Studio? Step 2: Adding the required dependencies Add the following dependencies, to the app-level Gradle file. The dependencies are of the Lifecycle // Lifecycles only (without ViewModel or LiveData) implementation “androidx.lifecycle:lifecycle-runtime-ktx:2.3.1” // Annotation processor kapt “androidx.lifecycle:lifecycle-compiler:2.3.1” Note: The version may differ in future. And also enable the kapt plugin inside the plugins under the app-level gradle file. plugins { id ‘com.android.application’ id ‘kotlin-android’ id ‘kotlin-kapt’ } If unable to get how to add dependencies have look at the following images. Step 3: Working with acitivity_main.xml file The main layout of the application is the activity_main.xml file contains only one TextView. To implement the UI invoke the following code inside the activity_main.xml file. XML <?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".MainActivity"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:layout_marginTop="128dp" android:text="GEEKSFORGEEKS" android:textSize="24sp" /> </LinearLayout> Output UI: Step 4: Create a class that implements LifecycleObserver Create a class MainActivityObserver.kt which implements the LifecycleObserver interface which contains the functions to perform the assigned tasks, as and when the owner’s lifecycle changes. In this case, the owner is MainActivity.kt, which has its own lifecycle. through the following class, the changes in the lifecycle of MainActivity are observed. Invoke the following code inside the MainActivityObserver.kt file. Kotlin import android.util.Logimport androidx.lifecycle.Lifecycleimport androidx.lifecycle.LifecycleObserverimport androidx.lifecycle.OnLifecycleEvent class MainActivityObserver : LifecycleObserver { private val TAG = javaClass.simpleName // To observe the onCreate state of MainActivity // and perform the assigned tasks @OnLifecycleEvent(Lifecycle.Event.ON_CREATE) fun onCreatePerformTask() { // here for demonstration purpose the Log messages are printed in logcat // one may perform their own custom tasks Log.i(TAG, "I\'m inside Observer of MainActivity ON_CREATE") } // To observe the onResume state of MainActivity // and perform the assigned tasks @OnLifecycleEvent(Lifecycle.Event.ON_RESUME) fun onResumePerformTask() { // here for demonstration purpose the Log messages are printed in logcat // one may perform their own custom tasks Log.i(TAG, "I\'m inside Observer of MainActivity ON_RESUME") }} Step 5: Attaching the MainActivityObserver to the MainActivity.kt file Now there is a need to inform the activity by attaching the observer MainActivityObserver so that the desired tasks can be performed as the state of the activity changes. Invoke the following code inside the MainActivity.kt file. Kotlin import android.os.Bundleimport androidx.appcompat.app.AppCompatActivity class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // attach the MainActivityObserver // to the MainActivity as follows lifecycle.addObserver(MainActivityObserver()) }} Output: Here the output is being shown in the logcat as there is an info logging statement inside the observer class. Android-Jetpack Kotlin Android Android Kotlin Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Flutter - Custom Bottom Navigation Bar How to Read Data from SQLite Database in Android? How to Post Data to API using Retrofit in Android? Android Listview in Java with Example Retrofit with Kotlin Coroutine in Android Android UI Layouts Kotlin Array Retrofit with Kotlin Coroutine in Android Kotlin Setters and Getters
[ { "code": null, "e": 24725, "s": 24697, "text": "\n05 May, 2021" }, { "code": null, "e": 25386, "s": 24725, "text": "LifecycleObserever is Observer is one of the Jetpack Architecture components and is an interface that observes and performs the specified task depending upon the Lifecycle owner’s Lifecycle changes. For example, MainActivity has its own lifecycle and itself is Lifecycle owner and we can implement the LifecycleObserever interface and attach this observer to MainActivity so that certain operations can be performed as the lifecycle of the MainActivity changes. In this article, it’s been demonstrated how the LifecycleObserever performs the tasks as Lifecycle owner’s lifecycle changes. Have a look at the following video to get an overview of the discussion." }, { "code": null, "e": 25450, "s": 25386, "text": "Note: This discussion is implemented using the Kotlin language." }, { "code": null, "e": 25491, "s": 25450, "text": "Step 1: Create an empty activity project" }, { "code": null, "e": 25655, "s": 25491, "text": "Create an empty activity Android studio project and select Kotlin as the programming language. Refer Android | How to Create/Start a New Project in Android Studio?" }, { "code": null, "e": 25696, "s": 25655, "text": "Step 2: Adding the required dependencies" }, { "code": null, "e": 25796, "s": 25696, "text": "Add the following dependencies, to the app-level Gradle file. The dependencies are of the Lifecycle" }, { "code": null, "e": 25847, "s": 25796, "text": "// Lifecycles only (without ViewModel or LiveData)" }, { "code": null, "e": 25911, "s": 25847, "text": "implementation “androidx.lifecycle:lifecycle-runtime-ktx:2.3.1”" }, { "code": null, "e": 25935, "s": 25911, "text": "// Annotation processor" }, { "code": null, "e": 25986, "s": 25935, "text": "kapt “androidx.lifecycle:lifecycle-compiler:2.3.1”" }, { "code": null, "e": 26026, "s": 25986, "text": "Note: The version may differ in future." }, { "code": null, "e": 26110, "s": 26026, "text": "And also enable the kapt plugin inside the plugins under the app-level gradle file." }, { "code": null, "e": 26120, "s": 26110, "text": "plugins {" }, { "code": null, "e": 26152, "s": 26120, "text": " id ‘com.android.application’" }, { "code": null, "e": 26175, "s": 26152, "text": " id ‘kotlin-android’" }, { "code": null, "e": 26195, "s": 26175, "text": " id ‘kotlin-kapt’" }, { "code": null, "e": 26197, "s": 26195, "text": "}" }, { "code": null, "e": 26273, "s": 26197, "text": "If unable to get how to add dependencies have look at the following images." }, { "code": null, "e": 26318, "s": 26273, "text": "Step 3: Working with acitivity_main.xml file" }, { "code": null, "e": 26492, "s": 26318, "text": "The main layout of the application is the activity_main.xml file contains only one TextView. To implement the UI invoke the following code inside the activity_main.xml file." }, { "code": null, "e": 26496, "s": 26492, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:orientation=\"vertical\" tools:context=\".MainActivity\"> <TextView android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_gravity=\"center\" android:layout_marginTop=\"128dp\" android:text=\"GEEKSFORGEEKS\" android:textSize=\"24sp\" /> </LinearLayout>", "e": 27131, "s": 26496, "text": null }, { "code": null, "e": 27142, "s": 27131, "text": "Output UI:" }, { "code": null, "e": 27199, "s": 27142, "text": "Step 4: Create a class that implements LifecycleObserver" }, { "code": null, "e": 27618, "s": 27199, "text": "Create a class MainActivityObserver.kt which implements the LifecycleObserver interface which contains the functions to perform the assigned tasks, as and when the owner’s lifecycle changes. In this case, the owner is MainActivity.kt, which has its own lifecycle. through the following class, the changes in the lifecycle of MainActivity are observed. Invoke the following code inside the MainActivityObserver.kt file." }, { "code": null, "e": 27625, "s": 27618, "text": "Kotlin" }, { "code": "import android.util.Logimport androidx.lifecycle.Lifecycleimport androidx.lifecycle.LifecycleObserverimport androidx.lifecycle.OnLifecycleEvent class MainActivityObserver : LifecycleObserver { private val TAG = javaClass.simpleName // To observe the onCreate state of MainActivity // and perform the assigned tasks @OnLifecycleEvent(Lifecycle.Event.ON_CREATE) fun onCreatePerformTask() { // here for demonstration purpose the Log messages are printed in logcat // one may perform their own custom tasks Log.i(TAG, \"I\\'m inside Observer of MainActivity ON_CREATE\") } // To observe the onResume state of MainActivity // and perform the assigned tasks @OnLifecycleEvent(Lifecycle.Event.ON_RESUME) fun onResumePerformTask() { // here for demonstration purpose the Log messages are printed in logcat // one may perform their own custom tasks Log.i(TAG, \"I\\'m inside Observer of MainActivity ON_RESUME\") }}", "e": 28608, "s": 27625, "text": null }, { "code": null, "e": 28679, "s": 28608, "text": "Step 5: Attaching the MainActivityObserver to the MainActivity.kt file" }, { "code": null, "e": 28909, "s": 28679, "text": "Now there is a need to inform the activity by attaching the observer MainActivityObserver so that the desired tasks can be performed as the state of the activity changes. Invoke the following code inside the MainActivity.kt file." }, { "code": null, "e": 28916, "s": 28909, "text": "Kotlin" }, { "code": "import android.os.Bundleimport androidx.appcompat.app.AppCompatActivity class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // attach the MainActivityObserver // to the MainActivity as follows lifecycle.addObserver(MainActivityObserver()) }}", "e": 29323, "s": 28916, "text": null }, { "code": null, "e": 29332, "s": 29323, "text": "Output: " }, { "code": null, "e": 29442, "s": 29332, "text": "Here the output is being shown in the logcat as there is an info logging statement inside the observer class." }, { "code": null, "e": 29458, "s": 29442, "text": "Android-Jetpack" }, { "code": null, "e": 29473, "s": 29458, "text": "Kotlin Android" }, { "code": null, "e": 29481, "s": 29473, "text": "Android" }, { "code": null, "e": 29488, "s": 29481, "text": "Kotlin" }, { "code": null, "e": 29496, "s": 29488, "text": "Android" }, { "code": null, "e": 29594, "s": 29496, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29603, "s": 29594, "text": "Comments" }, { "code": null, "e": 29616, "s": 29603, "text": "Old Comments" }, { "code": null, "e": 29655, "s": 29616, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 29705, "s": 29655, "text": "How to Read Data from SQLite Database in Android?" }, { "code": null, "e": 29756, "s": 29705, "text": "How to Post Data to API using Retrofit in Android?" }, { "code": null, "e": 29794, "s": 29756, "text": "Android Listview in Java with Example" }, { "code": null, "e": 29836, "s": 29794, "text": "Retrofit with Kotlin Coroutine in Android" }, { "code": null, "e": 29855, "s": 29836, "text": "Android UI Layouts" }, { "code": null, "e": 29868, "s": 29855, "text": "Kotlin Array" }, { "code": null, "e": 29910, "s": 29868, "text": "Retrofit with Kotlin Coroutine in Android" } ]
Java Program to display time in 24-hour format
Use the SimpleDateFormat class to display time in 24-hour format. Set the format Date dt = new Date(); SimpleDateFormat dateFormat; dateFormat = new SimpleDateFormat("kk:mm:ss"); Now, the following will display time in 24-hour format dateFormat.format(dt) The following is an example Live Demo import java.text.SimpleDateFormat; import java.util.Date; public class Demo { public static void main(String[] argv) throws Exception { Date dt = new Date(); SimpleDateFormat dateFormat; dateFormat = new SimpleDateFormat("kk:mm:ss"); System.out.println("Time in 24 hr format = "+dateFormat.format(dt)); } } Time in 24 hr format = 11:40:52
[ { "code": null, "e": 1128, "s": 1062, "text": "Use the SimpleDateFormat class to display time in 24-hour format." }, { "code": null, "e": 1143, "s": 1128, "text": "Set the format" }, { "code": null, "e": 1241, "s": 1143, "text": "Date dt = new Date();\nSimpleDateFormat dateFormat;\ndateFormat = new SimpleDateFormat(\"kk:mm:ss\");" }, { "code": null, "e": 1296, "s": 1241, "text": "Now, the following will display time in 24-hour format" }, { "code": null, "e": 1318, "s": 1296, "text": "dateFormat.format(dt)" }, { "code": null, "e": 1346, "s": 1318, "text": "The following is an example" }, { "code": null, "e": 1357, "s": 1346, "text": " Live Demo" }, { "code": null, "e": 1694, "s": 1357, "text": "import java.text.SimpleDateFormat;\nimport java.util.Date;\npublic class Demo {\n public static void main(String[] argv) throws Exception {\n Date dt = new Date();\n SimpleDateFormat dateFormat;\n dateFormat = new SimpleDateFormat(\"kk:mm:ss\");\n System.out.println(\"Time in 24 hr format = \"+dateFormat.format(dt));\n }\n}" }, { "code": null, "e": 1726, "s": 1694, "text": "Time in 24 hr format = 11:40:52" } ]
Design an IIR Notch Filter to Denoise Signal using Python - GeeksforGeeks
02 Feb, 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. A Notch Filter is a bandstop filter with a very narrow stopband and two passbands, it actually highly attenuates/eliminates a particular frequency component from the input signal while leaving the amplitude of the other frequencies more or less unchanged. The specifications are as follows: Generate a signal of 15 Hz corrupted with 50 Hz power line frequency. Sampling frequency: 1 kHz Approach: Step 1: Importing all the necessary libraries. Python3 from scipy import signalimport matplotlib.pyplot as pltimport numpy as np Step 2: Defining the specifications of the IIR Bandpass Notch-Filter Python3 # Create/view notch filtersamp_freq = 1000 # Sample frequency (Hz)notch_freq = 50.0 # Frequency to be removed from signal (Hz)quality_factor = 20.0 # Quality factor Step 3: Python3 # Design a notch filter using signal.iirnotchb_notch, a_notch = signal.iirnotch(notch_freq, quality_factor, samp_freq) # Compute magnitude response of the designed filterfreq, h = signal.freqz(b_notch, a_notch, fs=2*np.pi) Step 4: Python3 fig = plt.figure(figsize=(8, 6)) # Plot magnitude response of the filterplt.plot(freq*samp_freq/(2*np.pi), 20 * np.log10(abs(h)), 'r', label='Bandpass filter', linewidth='2') plt.xlabel('Frequency [Hz]', fontsize=20)plt.ylabel('Magnitude [dB]', fontsize=20)plt.title('Notch Filter', fontsize=20)plt.grid() Output: Step 5: Python3 # Create and view signal that is a mixture# of two different frequenciesf1 = 15 # Frequency of 1st signal in Hzf2 = 50 # Frequency of 2nd signal in Hz # Set time vector# Generate 1000 sample sequence in 1 secn = np.linspace(0, 1, 1000) Step 6: Python3 # Generate the signal containing f1 and f2noisySignal = np.sin(2*np.pi*15*n) + np.sin(2*np.pi*50*n) + \ np.random.normal(0, .1, 1000)*0.03 Step 7: Python3 # Plottingfig = plt.figure(figsize=(8, 6))plt.subplot(211)plt.plot(n, noisySignal, color='r', linewidth=2)plt.xlabel('Time', fontsize=20)plt.ylabel('Magnitude', fontsize=18)plt.title('Noisy Signal', fontsize=20) Output: Step 8: Python3 # Apply notch filter to the noisy signal using signal.filtfiltoutputSignal = signal.filtfilt(b_notch, a_notch, noisySignal) Step 9: Python3 # Plot notch-filtered version of signalplt.subplot(212) # Plot output signal of notch filterplt.plot(n, outputSignal)plt.xlabel('Time', fontsize=20)plt.ylabel('Magnitude', fontsize=18)plt.title('Filtered Signal', fontsize=20)plt.subplots_adjust(hspace=0.5)fig.tight_layout()plt.show() Output: Below is the implementation: Python3 from scipy import signalimport matplotlib.pyplot as pltimport numpy as np # Create/view notch filtersamp_freq = 1000 # Sample frequency (Hz)notch_freq = 50.0 # Frequency to be removed from signal (Hz)quality_factor = 20.0 # Quality factor # Design a notch filter using signal.iirnotchb_notch, a_notch = signal.iirnotch(notch_freq, quality_factor, samp_freq) # Compute magnitude response of the designed filterfreq, h = signal.freqz(b_notch, a_notch, fs=samp_freq) fig = plt.figure(figsize=(8, 6)) # Plot magnitude response of the filterplt.plot(freq*samp_freq/(2*np.pi), 20 * np.log10(abs(h)), 'r', label='Bandpass filter', linewidth='2')plt.xlabel('Frequency [Hz]', fontsize=20)plt.ylabel('Magnitude [dB]', fontsize=20)plt.title('Notch Filter', fontsize=20)plt.grid() # Create and view signal that is a mixture of two different frequenciesf1 = 15 # Frequency of 1st signal in Hzf2 = 50 # Frequency of 2nd signal in Hz# Set time vectorn = np.linspace(0, 1, 1000) # Generate 1000 sample sequence in 1 sec # Generate the signal containing f1 and f2noisySignal = np.sin(2*np.pi*15*n) + np.sin(2*np.pi*50*n) + \ np.random.normal(0, .1, 1000)*0.03 # Plottingfig = plt.figure(figsize=(8, 6))plt.subplot(211)plt.plot(n, noisySignal, color='r', linewidth=2)plt.xlabel('Time', fontsize=20)plt.ylabel('Magnitude', fontsize=18)plt.title('Noisy Signal', fontsize=20) # Apply notch filter to the noisy signal using signal.filtfiltoutputSignal = signal.filtfilt(b_notch, a_notch, noisySignal) # Plot notch-filtered version of signalplt.subplot(212) # Plot output signal of notch filterplt.plot(n, outputSignal)plt.xlabel('Time', fontsize=20)plt.ylabel('Magnitude', fontsize=18)plt.title('Filtered Signal', fontsize=20)plt.subplots_adjust(hspace=0.5)fig.tight_layout()plt.show() Output: estevanlouw1 Data Visualization Python-matplotlib Python-scipy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Install PIP on Windows ? How to drop one or multiple columns in Pandas Dataframe Python OOPs Concepts Python | Get unique values from a list Check if element exists in list in Python Python Classes and Objects Python | os.path.join() method How To Convert Python Dictionary To JSON? Python | Pandas dataframe.groupby() Create a directory in Python
[ { "code": null, "e": 24212, "s": 24184, "text": "\n02 Feb, 2022" }, { "code": null, "e": 24468, "s": 24212, "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": 24724, "s": 24468, "text": "A Notch Filter is a bandstop filter with a very narrow stopband and two passbands, it actually highly attenuates/eliminates a particular frequency component from the input signal while leaving the amplitude of the other frequencies more or less unchanged." }, { "code": null, "e": 24761, "s": 24724, "text": "The specifications are as follows: " }, { "code": null, "e": 24831, "s": 24761, "text": "Generate a signal of 15 Hz corrupted with 50 Hz power line frequency." }, { "code": null, "e": 24857, "s": 24831, "text": "Sampling frequency: 1 kHz" }, { "code": null, "e": 24867, "s": 24857, "text": "Approach:" }, { "code": null, "e": 24914, "s": 24867, "text": "Step 1: Importing all the necessary libraries." }, { "code": null, "e": 24922, "s": 24914, "text": "Python3" }, { "code": "from scipy import signalimport matplotlib.pyplot as pltimport numpy as np", "e": 24996, "s": 24922, "text": null }, { "code": null, "e": 25065, "s": 24996, "text": "Step 2: Defining the specifications of the IIR Bandpass Notch-Filter" }, { "code": null, "e": 25073, "s": 25065, "text": "Python3" }, { "code": "# Create/view notch filtersamp_freq = 1000 # Sample frequency (Hz)notch_freq = 50.0 # Frequency to be removed from signal (Hz)quality_factor = 20.0 # Quality factor", "e": 25241, "s": 25073, "text": null }, { "code": null, "e": 25249, "s": 25241, "text": "Step 3:" }, { "code": null, "e": 25257, "s": 25249, "text": "Python3" }, { "code": "# Design a notch filter using signal.iirnotchb_notch, a_notch = signal.iirnotch(notch_freq, quality_factor, samp_freq) # Compute magnitude response of the designed filterfreq, h = signal.freqz(b_notch, a_notch, fs=2*np.pi)", "e": 25480, "s": 25257, "text": null }, { "code": null, "e": 25488, "s": 25480, "text": "Step 4:" }, { "code": null, "e": 25496, "s": 25488, "text": "Python3" }, { "code": "fig = plt.figure(figsize=(8, 6)) # Plot magnitude response of the filterplt.plot(freq*samp_freq/(2*np.pi), 20 * np.log10(abs(h)), 'r', label='Bandpass filter', linewidth='2') plt.xlabel('Frequency [Hz]', fontsize=20)plt.ylabel('Magnitude [dB]', fontsize=20)plt.title('Notch Filter', fontsize=20)plt.grid()", "e": 25810, "s": 25496, "text": null }, { "code": null, "e": 25818, "s": 25810, "text": "Output:" }, { "code": null, "e": 25826, "s": 25818, "text": "Step 5:" }, { "code": null, "e": 25834, "s": 25826, "text": "Python3" }, { "code": "# Create and view signal that is a mixture# of two different frequenciesf1 = 15 # Frequency of 1st signal in Hzf2 = 50 # Frequency of 2nd signal in Hz # Set time vector# Generate 1000 sample sequence in 1 secn = np.linspace(0, 1, 1000)", "e": 26072, "s": 25834, "text": null }, { "code": null, "e": 26080, "s": 26072, "text": "Step 6:" }, { "code": null, "e": 26088, "s": 26080, "text": "Python3" }, { "code": "# Generate the signal containing f1 and f2noisySignal = np.sin(2*np.pi*15*n) + np.sin(2*np.pi*50*n) + \\ np.random.normal(0, .1, 1000)*0.03", "e": 26230, "s": 26088, "text": null }, { "code": null, "e": 26238, "s": 26230, "text": "Step 7:" }, { "code": null, "e": 26246, "s": 26238, "text": "Python3" }, { "code": "# Plottingfig = plt.figure(figsize=(8, 6))plt.subplot(211)plt.plot(n, noisySignal, color='r', linewidth=2)plt.xlabel('Time', fontsize=20)plt.ylabel('Magnitude', fontsize=18)plt.title('Noisy Signal', fontsize=20)", "e": 26458, "s": 26246, "text": null }, { "code": null, "e": 26466, "s": 26458, "text": "Output:" }, { "code": null, "e": 26474, "s": 26466, "text": "Step 8:" }, { "code": null, "e": 26482, "s": 26474, "text": "Python3" }, { "code": "# Apply notch filter to the noisy signal using signal.filtfiltoutputSignal = signal.filtfilt(b_notch, a_notch, noisySignal)", "e": 26606, "s": 26482, "text": null }, { "code": null, "e": 26614, "s": 26606, "text": "Step 9:" }, { "code": null, "e": 26622, "s": 26614, "text": "Python3" }, { "code": "# Plot notch-filtered version of signalplt.subplot(212) # Plot output signal of notch filterplt.plot(n, outputSignal)plt.xlabel('Time', fontsize=20)plt.ylabel('Magnitude', fontsize=18)plt.title('Filtered Signal', fontsize=20)plt.subplots_adjust(hspace=0.5)fig.tight_layout()plt.show()", "e": 26907, "s": 26622, "text": null }, { "code": null, "e": 26915, "s": 26907, "text": "Output:" }, { "code": null, "e": 26944, "s": 26915, "text": "Below is the implementation:" }, { "code": null, "e": 26952, "s": 26944, "text": "Python3" }, { "code": "from scipy import signalimport matplotlib.pyplot as pltimport numpy as np # Create/view notch filtersamp_freq = 1000 # Sample frequency (Hz)notch_freq = 50.0 # Frequency to be removed from signal (Hz)quality_factor = 20.0 # Quality factor # Design a notch filter using signal.iirnotchb_notch, a_notch = signal.iirnotch(notch_freq, quality_factor, samp_freq) # Compute magnitude response of the designed filterfreq, h = signal.freqz(b_notch, a_notch, fs=samp_freq) fig = plt.figure(figsize=(8, 6)) # Plot magnitude response of the filterplt.plot(freq*samp_freq/(2*np.pi), 20 * np.log10(abs(h)), 'r', label='Bandpass filter', linewidth='2')plt.xlabel('Frequency [Hz]', fontsize=20)plt.ylabel('Magnitude [dB]', fontsize=20)plt.title('Notch Filter', fontsize=20)plt.grid() # Create and view signal that is a mixture of two different frequenciesf1 = 15 # Frequency of 1st signal in Hzf2 = 50 # Frequency of 2nd signal in Hz# Set time vectorn = np.linspace(0, 1, 1000) # Generate 1000 sample sequence in 1 sec # Generate the signal containing f1 and f2noisySignal = np.sin(2*np.pi*15*n) + np.sin(2*np.pi*50*n) + \\ np.random.normal(0, .1, 1000)*0.03 # Plottingfig = plt.figure(figsize=(8, 6))plt.subplot(211)plt.plot(n, noisySignal, color='r', linewidth=2)plt.xlabel('Time', fontsize=20)plt.ylabel('Magnitude', fontsize=18)plt.title('Noisy Signal', fontsize=20) # Apply notch filter to the noisy signal using signal.filtfiltoutputSignal = signal.filtfilt(b_notch, a_notch, noisySignal) # Plot notch-filtered version of signalplt.subplot(212) # Plot output signal of notch filterplt.plot(n, outputSignal)plt.xlabel('Time', fontsize=20)plt.ylabel('Magnitude', fontsize=18)plt.title('Filtered Signal', fontsize=20)plt.subplots_adjust(hspace=0.5)fig.tight_layout()plt.show()", "e": 28733, "s": 26952, "text": null }, { "code": null, "e": 28741, "s": 28733, "text": "Output:" }, { "code": null, "e": 28754, "s": 28741, "text": "estevanlouw1" }, { "code": null, "e": 28773, "s": 28754, "text": "Data Visualization" }, { "code": null, "e": 28791, "s": 28773, "text": "Python-matplotlib" }, { "code": null, "e": 28804, "s": 28791, "text": "Python-scipy" }, { "code": null, "e": 28811, "s": 28804, "text": "Python" }, { "code": null, "e": 28909, "s": 28811, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28918, "s": 28909, "text": "Comments" }, { "code": null, "e": 28931, "s": 28918, "text": "Old Comments" }, { "code": null, "e": 28963, "s": 28931, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 29019, "s": 28963, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 29040, "s": 29019, "text": "Python OOPs Concepts" }, { "code": null, "e": 29079, "s": 29040, "text": "Python | Get unique values from a list" }, { "code": null, "e": 29121, "s": 29079, "text": "Check if element exists in list in Python" }, { "code": null, "e": 29148, "s": 29121, "text": "Python Classes and Objects" }, { "code": null, "e": 29179, "s": 29148, "text": "Python | os.path.join() method" }, { "code": null, "e": 29221, "s": 29179, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 29257, "s": 29221, "text": "Python | Pandas dataframe.groupby()" } ]
Tryit Editor v3.7
Tryit: input type = radio
[]
How will you select a particular value in a dropdown without using the methods of Select class in Selenium?
We can select a particular value in a dropdown using the method of Select class by using findElements() method. import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import java.util.concurrent.TimeUnit; import java.util.List; import org.openqa.selenium.support.ui.Select; public class OptionsClick{ public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe"); WebDriver driver = new ChromeDriver(); String url = "https://www.tutorialspoint.com/tutor_connect/index.php"; driver.get(url); driver.manage().timeouts().implicitlyWait(12, TimeUnit.SECONDS); // getting the list of elements with the xpath List<WebElement> opt = driver.findElements(By.xpath("//select[@name=’selType’]//option")); int s = opt.size(); // Iterating through the list selecting the desired option for( int j = 0; j< opt.size();j++){ // if the option is By Subject click that option if( opt.get(j).getText().equals("By Subject")){ opt.get(j).click(); break; } } driver.quit(); } }
[ { "code": null, "e": 1174, "s": 1062, "text": "We can select a particular value in a dropdown using the method of Select class by using findElements() method." }, { "code": null, "e": 2328, "s": 1174, "text": "import org.openqa.selenium.By;\nimport org.openqa.selenium.WebDriver;\nimport org.openqa.selenium.WebElement;\nimport org.openqa.selenium.chrome.ChromeDriver;\nimport java.util.concurrent.TimeUnit;\nimport java.util.List;\nimport org.openqa.selenium.support.ui.Select;\npublic class OptionsClick{\n public static void main(String[] args) {\n System.setProperty(\"webdriver.chrome.driver\", \"C:\\\\Users\\\\ghs6kor\\\\Desktop\\\\Java\\\\chromedriver.exe\");\n WebDriver driver = new ChromeDriver();\n String url = \"https://www.tutorialspoint.com/tutor_connect/index.php\";\n driver.get(url);\n driver.manage().timeouts().implicitlyWait(12, TimeUnit.SECONDS);\n // getting the list of elements with the xpath\n List<WebElement> opt = driver.findElements(By.xpath(\"//select[@name=’selType’]//option\"));\n int s = opt.size();\n // Iterating through the list selecting the desired option\n for( int j = 0; j< opt.size();j++){\n // if the option is By Subject click that option\n if( opt.get(j).getText().equals(\"By Subject\")){\n opt.get(j).click();\n break;\n }\n }\n driver.quit();\n }\n}" } ]
Group Integers in Python
Suppose we have a list of numbers called nums, we have to check whether we can split the list into 1 or more groups such that: 1. Size of each group is greater than or equal to 2. 2. Sizes of all groups are same. 3. All the numbers present in each group are the same. So, if the input is like [3, 4, 6, 9, 4, 3, 6, 9], then the output will be True. To solve this, we will follow these steps − counts := a map where each key are distinct element and values are their frequencies temp := 0 for each count in counts, doif temp is same as 0, thentemp := counts[count]otherwise,temp := gcd of counts[count] and tempif temp is same as 1, thenreturn False if temp is same as 0, thentemp := counts[count] temp := counts[count] otherwise,temp := gcd of counts[count] and temp temp := gcd of counts[count] and temp if temp is same as 1, thenreturn False return False return True Let us see the following implementation to get better understanding − Live Demo from collections import Counter import math class Solution: def solve(self, nums): counts = Counter(nums) temp = 0 for count in counts: if temp == 0: temp = counts[count] else: temp = math.gcd(counts[count], temp) if temp == 1: return False return True ob = Solution() L = [3, 4, 6, 9, 4, 3, 6, 9] print(ob.solve(L)) [3, 4, 6, 9, 4, 3, 6, 9] True
[ { "code": null, "e": 1330, "s": 1062, "text": "Suppose we have a list of numbers called nums, we have to check whether we can split the list into 1 or more groups such that: 1. Size of each group is greater than or equal to 2. 2. Sizes of all groups are same. 3. All the numbers present in each group are the same." }, { "code": null, "e": 1411, "s": 1330, "text": "So, if the input is like [3, 4, 6, 9, 4, 3, 6, 9], then the output will be True." }, { "code": null, "e": 1455, "s": 1411, "text": "To solve this, we will follow these steps −" }, { "code": null, "e": 1540, "s": 1455, "text": "counts := a map where each key are distinct element and values are their frequencies" }, { "code": null, "e": 1550, "s": 1540, "text": "temp := 0" }, { "code": null, "e": 1711, "s": 1550, "text": "for each count in counts, doif temp is same as 0, thentemp := counts[count]otherwise,temp := gcd of counts[count] and tempif temp is same as 1, thenreturn False" }, { "code": null, "e": 1759, "s": 1711, "text": "if temp is same as 0, thentemp := counts[count]" }, { "code": null, "e": 1781, "s": 1759, "text": "temp := counts[count]" }, { "code": null, "e": 1829, "s": 1781, "text": "otherwise,temp := gcd of counts[count] and temp" }, { "code": null, "e": 1867, "s": 1829, "text": "temp := gcd of counts[count] and temp" }, { "code": null, "e": 1906, "s": 1867, "text": "if temp is same as 1, thenreturn False" }, { "code": null, "e": 1919, "s": 1906, "text": "return False" }, { "code": null, "e": 1931, "s": 1919, "text": "return True" }, { "code": null, "e": 2001, "s": 1931, "text": "Let us see the following implementation to get better understanding −" }, { "code": null, "e": 2012, "s": 2001, "text": " Live Demo" }, { "code": null, "e": 2425, "s": 2012, "text": "from collections import Counter\nimport math\nclass Solution:\n def solve(self, nums):\n counts = Counter(nums)\n temp = 0\n for count in counts:\n if temp == 0:\n temp = counts[count]\n else:\n temp = math.gcd(counts[count], temp)\n if temp == 1:\n return False\n return True\nob = Solution()\nL = [3, 4, 6, 9, 4, 3, 6, 9]\nprint(ob.solve(L))" }, { "code": null, "e": 2450, "s": 2425, "text": "[3, 4, 6, 9, 4, 3, 6, 9]" }, { "code": null, "e": 2455, "s": 2450, "text": "True" } ]
Design of 512x8 RAM using 128x8 RAM - GeeksforGeeks
23 Feb, 2021 If we see RAM physically then we notice that RAM is made up of a few chips. We can design the required RAM size using basic RAM chips. We can observe a basic RAM chip as follows: – CS1: –For chip select 1, the value should be 1CS2: –For chip select 2, the value should be 0.Read and Write: –Used for upcoming signals. CS1: –For chip select 1, the value should be 1 CS2: –For chip select 2, the value should be 0. Read and Write: –Used for upcoming signals. If we have n bit address and m bit words then our RAM size will be 2n x m. Example: n=7 bit, m=8 bit RAM size= 128 x 8 Given: – Basic RAM size = 128 x 8 Required RAM size = 512 x 8 To design a RAM size of 512×8 from 128×8, here are some calculations we need to do first – 1. Number of chips required: Number of chips required = Desired RAM Size/ Basic RAM Size =512x8/128x8 =4 chips 2. Address Bits: Required Size is 512 x 8 512 x 8= 29 x 8 Therefore, 9 bit address is required 3. Decoder Size:If the number of words is increasing them there will be a need for a decoder.In this case number of words is increasing (from 128 to 512). Size of decoder= number of times words increasing 128⇢512 words increased by 4 times Decoder Size= 2x4 Pictorial Description (Design of 512×8 RAM): From the above calculations, we see that we need four 128 x 8 RAM chips to design a 512 x 8 RAM size. If only the number of words is increasing then all chips will be arranged vertically. In this case, only the number of words is increasing (128-512) so all chips will be arranged vertically. In a 512 x 8 RAM, there is a 9-bit address, we will divide this 9-bit address into 2 and 7-bit addresses.The 2-bit address will be input as a 2 x 4 decoder, this decoder will have 4 output and the input will have 2 bits.The 4 output of the decoder will enable every RAM of 128 x 8 individually.Also, we can write 128 x 8 RAM chip as 27 x 8, every RAM chip will need a 7-bit address. We will connect the remaining 7-bit address line to every RAM.This 7-bit address will select any word from the 128 words of that RAM, the selected word will be the output as the 8-bit word in the output bus. In a 512 x 8 RAM, there is a 9-bit address, we will divide this 9-bit address into 2 and 7-bit addresses. The 2-bit address will be input as a 2 x 4 decoder, this decoder will have 4 output and the input will have 2 bits. The 4 output of the decoder will enable every RAM of 128 x 8 individually. Also, we can write 128 x 8 RAM chip as 27 x 8, every RAM chip will need a 7-bit address. We will connect the remaining 7-bit address line to every RAM. This 7-bit address will select any word from the 128 words of that RAM, the selected word will be the output as the 8-bit word in the output bus. Digital Electronics & Logic Design GATE CS Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Introduction to memory and memory units Ring Counter in Digital Logic n-bit Johnson Counter in Digital Logic Transmission Impairment in Data Communication Half Subtractor in Digital Logic Layers of OSI Model ACID Properties in DBMS Types of Operating Systems Normal Forms in DBMS Page Replacement Algorithms in Operating Systems
[ { "code": null, "e": 24382, "s": 24354, "text": "\n23 Feb, 2021" }, { "code": null, "e": 24518, "s": 24382, "text": "If we see RAM physically then we notice that RAM is made up of a few chips. We can design the required RAM size using basic RAM chips. " }, { "code": null, "e": 24564, "s": 24518, "text": "We can observe a basic RAM chip as follows: –" }, { "code": null, "e": 24701, "s": 24564, "text": "CS1: –For chip select 1, the value should be 1CS2: –For chip select 2, the value should be 0.Read and Write: –Used for upcoming signals." }, { "code": null, "e": 24748, "s": 24701, "text": "CS1: –For chip select 1, the value should be 1" }, { "code": null, "e": 24796, "s": 24748, "text": "CS2: –For chip select 2, the value should be 0." }, { "code": null, "e": 24840, "s": 24796, "text": "Read and Write: –Used for upcoming signals." }, { "code": null, "e": 24915, "s": 24840, "text": "If we have n bit address and m bit words then our RAM size will be 2n x m." }, { "code": null, "e": 24924, "s": 24915, "text": "Example:" }, { "code": null, "e": 24960, "s": 24924, "text": "n=7 bit, m=8 bit\nRAM size= 128 x 8 " }, { "code": null, "e": 24971, "s": 24960, "text": "Given: – " }, { "code": null, "e": 25025, "s": 24971, "text": "Basic RAM size = 128 x 8\nRequired RAM size = 512 x 8" }, { "code": null, "e": 25116, "s": 25025, "text": "To design a RAM size of 512×8 from 128×8, here are some calculations we need to do first –" }, { "code": null, "e": 25145, "s": 25116, "text": "1. Number of chips required:" }, { "code": null, "e": 25312, "s": 25145, "text": "Number of chips required = Desired RAM Size/ Basic RAM Size\n =512x8/128x8\n =4 chips" }, { "code": null, "e": 25329, "s": 25312, "text": "2. Address Bits:" }, { "code": null, "e": 25409, "s": 25329, "text": "Required Size is 512 x 8 \n512 x 8= 29 x 8\nTherefore, 9 bit address is required" }, { "code": null, "e": 25564, "s": 25409, "text": "3. Decoder Size:If the number of words is increasing them there will be a need for a decoder.In this case number of words is increasing (from 128 to 512)." }, { "code": null, "e": 25667, "s": 25564, "text": "Size of decoder= number of times words increasing\n128⇢512\nwords increased by 4 times\nDecoder Size= 2x4" }, { "code": null, "e": 25712, "s": 25667, "text": "Pictorial Description (Design of 512×8 RAM):" }, { "code": null, "e": 26005, "s": 25712, "text": "From the above calculations, we see that we need four 128 x 8 RAM chips to design a 512 x 8 RAM size. If only the number of words is increasing then all chips will be arranged vertically. In this case, only the number of words is increasing (128-512) so all chips will be arranged vertically." }, { "code": null, "e": 26596, "s": 26005, "text": "In a 512 x 8 RAM, there is a 9-bit address, we will divide this 9-bit address into 2 and 7-bit addresses.The 2-bit address will be input as a 2 x 4 decoder, this decoder will have 4 output and the input will have 2 bits.The 4 output of the decoder will enable every RAM of 128 x 8 individually.Also, we can write 128 x 8 RAM chip as 27 x 8, every RAM chip will need a 7-bit address. We will connect the remaining 7-bit address line to every RAM.This 7-bit address will select any word from the 128 words of that RAM, the selected word will be the output as the 8-bit word in the output bus." }, { "code": null, "e": 26702, "s": 26596, "text": "In a 512 x 8 RAM, there is a 9-bit address, we will divide this 9-bit address into 2 and 7-bit addresses." }, { "code": null, "e": 26818, "s": 26702, "text": "The 2-bit address will be input as a 2 x 4 decoder, this decoder will have 4 output and the input will have 2 bits." }, { "code": null, "e": 26893, "s": 26818, "text": "The 4 output of the decoder will enable every RAM of 128 x 8 individually." }, { "code": null, "e": 27045, "s": 26893, "text": "Also, we can write 128 x 8 RAM chip as 27 x 8, every RAM chip will need a 7-bit address. We will connect the remaining 7-bit address line to every RAM." }, { "code": null, "e": 27191, "s": 27045, "text": "This 7-bit address will select any word from the 128 words of that RAM, the selected word will be the output as the 8-bit word in the output bus." }, { "code": null, "e": 27226, "s": 27191, "text": "Digital Electronics & Logic Design" }, { "code": null, "e": 27234, "s": 27226, "text": "GATE CS" }, { "code": null, "e": 27332, "s": 27234, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27341, "s": 27332, "text": "Comments" }, { "code": null, "e": 27354, "s": 27341, "text": "Old Comments" }, { "code": null, "e": 27394, "s": 27354, "text": "Introduction to memory and memory units" }, { "code": null, "e": 27424, "s": 27394, "text": "Ring Counter in Digital Logic" }, { "code": null, "e": 27463, "s": 27424, "text": "n-bit Johnson Counter in Digital Logic" }, { "code": null, "e": 27509, "s": 27463, "text": "Transmission Impairment in Data Communication" }, { "code": null, "e": 27542, "s": 27509, "text": "Half Subtractor in Digital Logic" }, { "code": null, "e": 27562, "s": 27542, "text": "Layers of OSI Model" }, { "code": null, "e": 27586, "s": 27562, "text": "ACID Properties in DBMS" }, { "code": null, "e": 27613, "s": 27586, "text": "Types of Operating Systems" }, { "code": null, "e": 27634, "s": 27613, "text": "Normal Forms in DBMS" } ]
How To Make PCA Plot with R
23 Sep, 2021 Principal component analysis(PCA) in R programming is the analysis of the linear components of all existing attributes. Principal components are linear combinations (orthogonal transformation) of the original predictor in the dataset. It is a useful technique for EDA(Exploratory data analysis) and allowing you to better visualize the variations present in a dataset with many variables. It works best with numerical data values. In this process the principal components of data are calculated and are used for performing a change of basis on the data, sometimes using only the first few principal components while ignoring the rest. One can take PCA as a kind of linear transformation of the data on the basis of certain data spaces. This transformation fits the data into a coordinate system where the most significant variance is found on the first coordinate, and each subsequent coordinate is orthogonal to the last and has a lesser variance than the previous. We are gonna work on the ‘Iris’ dataset, which is built into R. It is a multivariate dataset that consists of data on 50 samples from each of three species of Iris (Iris setosa, Iris virginica, and Iris versicolor). R # structure of the iris# datasetstr(iris) # print the iris datasethead(iris) Output: As mentioned PCA works best with numerical data we will neglect the categorical variable Species. We are now left with a matrix of 4 columns and 150 rows which we will pass through prcomp( ) function for the principal component analysis. This function returns the results as an object of class ‘prcomp’. We will assign the output to a variable named iris.pca. R iris.pca <- prcomp(iris[,c(1:4)], center = TRUE, scale. = TRUE) # summary of the # prcomp objectsummary(iris.pca) Output: Here we get four principal components named PC1-4. Each of these explains a percentage of the total variation in the dataset. For example, PC1 explains nearly 72% of the total variance i.e. around three-fourth of the information of the dataset can be encapsulated by just that one Principal Component. PC2 explains 22% and so on. Let us take a glance at the structure of the PCA object so formed. R # structure of the pca objectstr(iris.pca) Output: While talking about plotting a PCA we generally refer to a scatterplot of the first two principal components PC1 and PC2. These plots reveal the features of data such as non-linearity and departure from normality. PC1 and PC2 are evaluated for each sample vector and plotted. The autoplot( ) function of the ‘ggfortify package’ gives ease in plotting PCA’s in R. R # loading librarylibrary(ggfortify)iris.pca.plot <- autoplot(iris.pca, data = iris, colour = 'Species') iris.pca.plot Output: For a better understanding of the linear transformation of features, biplot( ) function also be used to plot PCA. R biplot.iris.pca <- biplot(iris.pca)biplot.iris.pca Output: The X-axis of the biplot represents the first principal component where the petal length and petal width are combined and transformed into PC1 with some parts of sepal length and sepal width. Whereas the vertical part of the sepal length and sepal width forms the second principal component. For determining the ideal features which can be justified after performing PCA, the plot( ) function can be used to plot the precomp object. R plot.iris.pca <- plot(iris.pca, type="l")plot.iris.pca Output: In a screeplot the ‘arm-bend’ represents a decrease in cumulative contribution. The above plot shows the bend at the second principal component. Picked R-Charts R-Graphs R-plots R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n23 Sep, 2021" }, { "code": null, "e": 417, "s": 28, "text": "Principal component analysis(PCA) in R programming is the analysis of the linear components of all existing attributes. Principal components are linear combinations (orthogonal transformation) of the original predictor in the dataset. It is a useful technique for EDA(Exploratory data analysis) and allowing you to better visualize the variations present in a dataset with many variables." }, { "code": null, "e": 996, "s": 417, "text": "It works best with numerical data values. In this process the principal components of data are calculated and are used for performing a change of basis on the data, sometimes using only the first few principal components while ignoring the rest. One can take PCA as a kind of linear transformation of the data on the basis of certain data spaces. This transformation fits the data into a coordinate system where the most significant variance is found on the first coordinate, and each subsequent coordinate is orthogonal to the last and has a lesser variance than the previous. " }, { "code": null, "e": 1212, "s": 996, "text": "We are gonna work on the ‘Iris’ dataset, which is built into R. It is a multivariate dataset that consists of data on 50 samples from each of three species of Iris (Iris setosa, Iris virginica, and Iris versicolor)." }, { "code": null, "e": 1214, "s": 1212, "text": "R" }, { "code": "# structure of the iris# datasetstr(iris) # print the iris datasethead(iris)", "e": 1292, "s": 1214, "text": null }, { "code": null, "e": 1300, "s": 1292, "text": "Output:" }, { "code": null, "e": 1660, "s": 1300, "text": "As mentioned PCA works best with numerical data we will neglect the categorical variable Species. We are now left with a matrix of 4 columns and 150 rows which we will pass through prcomp( ) function for the principal component analysis. This function returns the results as an object of class ‘prcomp’. We will assign the output to a variable named iris.pca." }, { "code": null, "e": 1662, "s": 1660, "text": "R" }, { "code": "iris.pca <- prcomp(iris[,c(1:4)], center = TRUE, scale. = TRUE) # summary of the # prcomp objectsummary(iris.pca)", "e": 1813, "s": 1662, "text": null }, { "code": null, "e": 1821, "s": 1813, "text": "Output:" }, { "code": null, "e": 2152, "s": 1821, "text": "Here we get four principal components named PC1-4. Each of these explains a percentage of the total variation in the dataset. For example, PC1 explains nearly 72% of the total variance i.e. around three-fourth of the information of the dataset can be encapsulated by just that one Principal Component. PC2 explains 22% and so on. " }, { "code": null, "e": 2219, "s": 2152, "text": "Let us take a glance at the structure of the PCA object so formed." }, { "code": null, "e": 2221, "s": 2219, "text": "R" }, { "code": "# structure of the pca objectstr(iris.pca)", "e": 2264, "s": 2221, "text": null }, { "code": null, "e": 2272, "s": 2264, "text": "Output:" }, { "code": null, "e": 2549, "s": 2272, "text": "While talking about plotting a PCA we generally refer to a scatterplot of the first two principal components PC1 and PC2. These plots reveal the features of data such as non-linearity and departure from normality. PC1 and PC2 are evaluated for each sample vector and plotted. " }, { "code": null, "e": 2636, "s": 2549, "text": "The autoplot( ) function of the ‘ggfortify package’ gives ease in plotting PCA’s in R." }, { "code": null, "e": 2638, "s": 2636, "text": "R" }, { "code": "# loading librarylibrary(ggfortify)iris.pca.plot <- autoplot(iris.pca, data = iris, colour = 'Species') iris.pca.plot", "e": 2807, "s": 2638, "text": null }, { "code": null, "e": 2815, "s": 2807, "text": "Output:" }, { "code": null, "e": 2930, "s": 2815, "text": "For a better understanding of the linear transformation of features, biplot( ) function also be used to plot PCA." }, { "code": null, "e": 2932, "s": 2930, "text": "R" }, { "code": "biplot.iris.pca <- biplot(iris.pca)biplot.iris.pca", "e": 2983, "s": 2932, "text": null }, { "code": null, "e": 2991, "s": 2983, "text": "Output:" }, { "code": null, "e": 3283, "s": 2991, "text": "The X-axis of the biplot represents the first principal component where the petal length and petal width are combined and transformed into PC1 with some parts of sepal length and sepal width. Whereas the vertical part of the sepal length and sepal width forms the second principal component." }, { "code": null, "e": 3424, "s": 3283, "text": "For determining the ideal features which can be justified after performing PCA, the plot( ) function can be used to plot the precomp object." }, { "code": null, "e": 3426, "s": 3424, "text": "R" }, { "code": "plot.iris.pca <- plot(iris.pca, type=\"l\")plot.iris.pca", "e": 3481, "s": 3426, "text": null }, { "code": null, "e": 3489, "s": 3481, "text": "Output:" }, { "code": null, "e": 3634, "s": 3489, "text": "In a screeplot the ‘arm-bend’ represents a decrease in cumulative contribution. The above plot shows the bend at the second principal component." }, { "code": null, "e": 3641, "s": 3634, "text": "Picked" }, { "code": null, "e": 3650, "s": 3641, "text": "R-Charts" }, { "code": null, "e": 3659, "s": 3650, "text": "R-Graphs" }, { "code": null, "e": 3667, "s": 3659, "text": "R-plots" }, { "code": null, "e": 3678, "s": 3667, "text": "R Language" } ]
MD5 hash in Java
05 Aug, 2020 To calculate cryptographic hashing value in Java, MessageDigest Class is used, under the package java.security. MessageDigest Class provides following cryptographic hash function to find hash value of a text, they are:1. MD52. SHA-13. SHA-256 This Algorithms are initialize in static method called getInstance(). After selecting the algorithm it calculate the digest value and return the results in byte array. BigInteger class is used, which converts the resultant byte array into its sign-magnitude representation. This representation converts into hex format to get the MessageDigest Examples: Input : hello world Output : 5eb63bbbe01eeed093cb22bb8f5acdc3 Input : GeeksForGeeks Output : e39b9c178b2c9be4e99b141d956c6ff6 import java.math.BigInteger;import java.security.MessageDigest;import java.security.NoSuchAlgorithmException; // Java program to calculate MD5 hash valuepublic class MD5 { public static String getMd5(String input) { try { // Static getInstance method is called with hashing MD5 MessageDigest md = MessageDigest.getInstance("MD5"); // digest() method is called to calculate message digest // of an input digest() return array of byte byte[] messageDigest = md.digest(input.getBytes()); // Convert byte array into signum representation BigInteger no = new BigInteger(1, messageDigest); // Convert message digest into hex value String hashtext = no.toString(16); while (hashtext.length() < 32) { hashtext = "0" + hashtext; } return hashtext; } // For specifying wrong message digest algorithms catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } } // Driver code public static void main(String args[]) throws NoSuchAlgorithmException { String s = "GeeksForGeeks"; System.out.println("Your HashCode Generated by MD5 is: " + getMd5(s)); }} Output: Your HashCode Generated by MD5 is: e39b9c178b2c9be4e99b141d956c6ff6 References: Java Docs for MessageDigest Computer Networks Hash Java Programs Hash Computer Networks Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Differences between TCP and UDP Types of Network Topology RSA Algorithm in Cryptography TCP Server-Client implementation in C Socket Programming in Python Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum) What is Hashing | A Complete Tutorial Hashing | Set 1 (Introduction) Internal Working of HashMap in Java Count pairs with given sum
[ { "code": null, "e": 52, "s": 24, "text": "\n05 Aug, 2020" }, { "code": null, "e": 164, "s": 52, "text": "To calculate cryptographic hashing value in Java, MessageDigest Class is used, under the package java.security." }, { "code": null, "e": 295, "s": 164, "text": "MessageDigest Class provides following cryptographic hash function to find hash value of a text, they are:1. MD52. SHA-13. SHA-256" }, { "code": null, "e": 463, "s": 295, "text": "This Algorithms are initialize in static method called getInstance(). After selecting the algorithm it calculate the digest value and return the results in byte array." }, { "code": null, "e": 569, "s": 463, "text": "BigInteger class is used, which converts the resultant byte array into its sign-magnitude representation." }, { "code": null, "e": 639, "s": 569, "text": "This representation converts into hex format to get the MessageDigest" }, { "code": null, "e": 649, "s": 639, "text": "Examples:" }, { "code": null, "e": 777, "s": 649, "text": "Input : hello world\nOutput : 5eb63bbbe01eeed093cb22bb8f5acdc3\n\nInput : GeeksForGeeks\nOutput : e39b9c178b2c9be4e99b141d956c6ff6\n" }, { "code": "import java.math.BigInteger;import java.security.MessageDigest;import java.security.NoSuchAlgorithmException; // Java program to calculate MD5 hash valuepublic class MD5 { public static String getMd5(String input) { try { // Static getInstance method is called with hashing MD5 MessageDigest md = MessageDigest.getInstance(\"MD5\"); // digest() method is called to calculate message digest // of an input digest() return array of byte byte[] messageDigest = md.digest(input.getBytes()); // Convert byte array into signum representation BigInteger no = new BigInteger(1, messageDigest); // Convert message digest into hex value String hashtext = no.toString(16); while (hashtext.length() < 32) { hashtext = \"0\" + hashtext; } return hashtext; } // For specifying wrong message digest algorithms catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } } // Driver code public static void main(String args[]) throws NoSuchAlgorithmException { String s = \"GeeksForGeeks\"; System.out.println(\"Your HashCode Generated by MD5 is: \" + getMd5(s)); }}", "e": 2073, "s": 777, "text": null }, { "code": null, "e": 2081, "s": 2073, "text": "Output:" }, { "code": null, "e": 2149, "s": 2081, "text": "Your HashCode Generated by MD5 is: e39b9c178b2c9be4e99b141d956c6ff6" }, { "code": null, "e": 2189, "s": 2149, "text": "References: Java Docs for MessageDigest" }, { "code": null, "e": 2207, "s": 2189, "text": "Computer Networks" }, { "code": null, "e": 2212, "s": 2207, "text": "Hash" }, { "code": null, "e": 2226, "s": 2212, "text": "Java Programs" }, { "code": null, "e": 2231, "s": 2226, "text": "Hash" }, { "code": null, "e": 2249, "s": 2231, "text": "Computer Networks" }, { "code": null, "e": 2347, "s": 2249, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2379, "s": 2347, "text": "Differences between TCP and UDP" }, { "code": null, "e": 2405, "s": 2379, "text": "Types of Network Topology" }, { "code": null, "e": 2435, "s": 2405, "text": "RSA Algorithm in Cryptography" }, { "code": null, "e": 2473, "s": 2435, "text": "TCP Server-Client implementation in C" }, { "code": null, "e": 2502, "s": 2473, "text": "Socket Programming in Python" }, { "code": null, "e": 2587, "s": 2502, "text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)" }, { "code": null, "e": 2625, "s": 2587, "text": "What is Hashing | A Complete Tutorial" }, { "code": null, "e": 2656, "s": 2625, "text": "Hashing | Set 1 (Introduction)" }, { "code": null, "e": 2692, "s": 2656, "text": "Internal Working of HashMap in Java" } ]
k largest(or smallest) elements in an array
05 Jul, 2022 Write an efficient program for printing k largest elements in an array. Elements in an array can be in any order.For example: if the given array is [1, 23, 12, 9, 30, 2, 50] and you are asked for the largest 3 elements i.e., k = 3 then your program should print 50, 30, and 23. Method 1 (Use Bubble k times) Thanks to Shailendra for suggesting this approach. 1) Modify Bubble Sort to run the outer loop at most k times. 2) Print the last k elements of the array obtained in step 1.Time Complexity: O(n*k) Like Bubble sort, other sorting algorithms like Selection Sort can also be modified to get the k largest elements. Method 2 (Use temporary array) K largest elements from arr[0..n-1] 1) Store the first k elements in a temporary array temp[0..k-1]. 2) Find the smallest element in temp[], let the smallest element be min. 3-a) For each element x in arr[k] to arr[n-1]. O(n-k) If x is greater than the min then remove min from temp[] and insert x. 3-b)Then, determine the new min from temp[]. O(k) 4) Print final k elements of temp[] Time Complexity: O((n-k)*k). If we want the output sorted then O((n-k)*k + k*log(k))Thanks to nesamani1822 for suggesting this method. Method 3(Use Sorting) 1) Sort the elements in descending order in O(n*log(n)) 2) Print the first k numbers of the sorted array O(k). Following is the implementation of the above. C++ C Java Python C# PHP Javascript // C++ code for k largest elements in an array#include <bits/stdc++.h>using namespace std; void kLargest(int arr[], int n, int k){ // Sort the given array arr in reverse order. sort(arr, arr + n, greater<int>()); // Print the first kth largest elements for (int i = 0; i < k; i++) cout << arr[i] << " ";} // driver programint main(){ int arr[] = { 1, 23, 12, 9, 30, 2, 50 }; int n = sizeof(arr) / sizeof(arr[0]); int k = 3; kLargest(arr, n, k);} // This code is contributed by Aditya Kumar (adityakumar129) // C code for k largest elements in an array#include <stdio.h>#include <stdlib.h> // Compare function for qsortint cmpfunc(const void* a, const void* b){ return (*(int*)b - *(int*)a);} void kLargest(int arr[], int n, int k){ // Sort the given array arr in reverse order. qsort(arr, n, sizeof(int), cmpfunc); // Print the first kth largest elements for (int i = 0; i < k; i++) printf("%d ", arr[i]);} // driver programint main(){ int arr[] = { 1, 23, 12, 9, 30, 2, 50 }; int n = sizeof(arr) / sizeof(arr[0]); int k = 3; kLargest(arr, n, k);} // This code is contributed by Aditya Kumar (adityakumar129) // Java code for k largest elements in an arrayimport java.util.Arrays;import java.util.Collections;import java.util.ArrayList; class GFG { public static void kLargest(Integer[] arr, int k) { // Sort the given array arr in reverse order // This method doesn't work with primitive data // types. So, instead of int, Integer type // array will be used Arrays.sort(arr, Collections.reverseOrder()); // Print the first kth largest elements for (int i = 0; i < k; i++) System.out.print(arr[i] + " "); } //This code is contributed by Niraj Dubey public static ArrayList<Integer> kLargest(int[] arr, int k) { //Convert using stream Integer[] obj_array = Arrays.stream( arr ).boxed().toArray( Integer[] :: new); Arrays.sort(obj_array, Collections.reverseOrder()); ArrayList<Integer> list = new ArrayList<>(k); for (int i = 0; i < k; i++) list.add(obj_array[i]); return list; } public static void main(String[] args) { Integer arr[] = new Integer[] { 1, 23, 12, 9, 30, 2, 50 }; int k = 3; kLargest(arr, k); //This code is contributed by Niraj Dubey //What if primitive datatype array is passed and wanted to return in ArrayList<Integer> int[] prim_array = { 1, 23, 12, 9, 30, 2, 50 }; System.out.print(kLargest(prim_array, k)); }}// This code is contributed by Kamal Rawal ''' Python3 code for k largest elements in an array''' def kLargest(arr, k): # Sort the given array arr in reverse # order. arr.sort(reverse = True) # Print the first kth largest elements for i in range(k): print (arr[i], end =" ") # Driver programarr = [1, 23, 12, 9, 30, 2, 50]# n = len(arr)k = 3kLargest(arr, k) # This code is contributed by shreyanshi_arun. // C# code for k largest elements in an arrayusing System; class GFG { public static void kLargest(int[] arr, int k) { // Sort the given array arr in reverse order // This method doesn't work with primitive data // types. So, instead of int, Integer type // array will be used Array.Sort(arr); Array.Reverse(arr); // Print the first kth largest elements for (int i = 0; i < k; i++) Console.Write(arr[i] + " "); } // Driver code public static void Main(String[] args) { int[] arr = new int[] { 1, 23, 12, 9, 30, 2, 50 }; int k = 3; kLargest(arr, k); }} // This code contributed by Rajput-Ji <?php // PHP code for k largest // elements in an array function kLargest(&$arr, $n, $k){ // Sort the given array arr // in reverse order. rsort($arr); // Print the first kth // largest elements for ($i = 0; $i < $k; $i++) echo $arr[$i] . " ";} // Driver Code$arr = array(1, 23, 12, 9, 30, 2, 50);$n = sizeof($arr);$k = 3;kLargest($arr, $n, $k); // This code is contributed // by ChitraNayal?> <script> // JavaScript code for k largest// elements in an array function kLargest(arr, n, k){ // Sort the given array arr in reverse // order. arr.sort((a, b) => b - a); // Print the first kth largest elements for (let i = 0; i < k; i++) document.write(arr[i] + " ");} // driver program let arr = [ 1, 23, 12, 9, 30, 2, 50 ]; let n = arr.length; let k = 3; kLargest(arr, n, k); // This code is contributed by Manoj. </script> 50 30 23 Time complexity: O(n*log(n))Auxiliary Space: O(1) Method 4 (Use Max Heap) 1) Build a Max Heap tree in O(n) 2) Use Extract Max k times to get k maximum elements from the Max Heap O(k*log(n)) Time complexity: O(n + k*log(n)) Method 5(Use Order Statistics) 1) Use an order statistic algorithm to find the kth largest element. Please see the topic selection in worst-case linear time O(n) 2) Use QuickSort Partition algorithm to partition around the kth largest number O(n). 3) Sort the k-1 elements (elements greater than the kth largest element) O(k*log(k)). This step is needed only if the sorted output is required. Time complexity: O(n) if we don’t need the sorted output, otherwise O(n+k*log(k))Thanks to Shilpi for suggesting the first two approaches. Method 6 (Use Min Heap) This method is mainly an optimization of method 2. Instead of using temp[] array, use Min Heap.1) Build a Min Heap MH of the first k elements (arr[0] to arr[k-1]) of the given array. O(k*log(k))2) For each element, after the kth element (arr[k] to arr[n-1]), compare it with root of MH. ......a) If the element is greater than the root then make it root and call heapify for MH ......b) Else ignore it. // The step 2 is O((n-k)*log(k))3) Finally, MH has k largest elements, and the root of the MH is the kth largest element.Time Complexity: O(k*log(k) + (n-k)*log(k)) without sorted output. If sorted output is needed then O(k*log(k) + (n-k)*log(k) + k*log(k)) so overall it is O(k*log(k) + (n-k)*log(k)) All of the above methods can also be used to find the kth largest (or smallest) element. C++ Java Python3 C# Javascript #include <iostream>using namespace std; // Swap function to interchange// the value of variables x and yint swap(int& x, int& y){ int temp = x; x = y; y = temp;} // Min Heap Class// arr holds reference to an integer // array size indicate the number of// elements in Min Heapclass MinHeap { int size; int* arr; public: // Constructor to initialize the size and arr MinHeap(int size, int input[]); // Min Heapify function, that assumes that // 2*i+1 and 2*i+2 are min heap and fix the // heap property for i. void heapify(int i); // Build the min heap, by calling heapify // for all non-leaf nodes. void buildHeap();}; // Constructor to initialize data// members and creating mean heapMinHeap::MinHeap(int size, int input[]){ // Initializing arr and size this->size = size; this->arr = input; // Building the Min Heap buildHeap();} // Min Heapify function, that assumes// 2*i+1 and 2*i+2 are min heap and // fix min heap property for i void MinHeap::heapify(int i){ // If Leaf Node, Simply return if (i >= size / 2) return; // variable to store the smallest element // index out of i, 2*i+1 and 2*i+2 int smallest; // Index of left node int left = 2 * i + 1; // Index of right node int right = 2 * i + 2; // Select minimum from left node and // current node i, and store the minimum // index in smallest variable smallest = arr[left] < arr[i] ? left : i; // If right child exist, compare and // update the smallest variable if (right < size) smallest = arr[right] < arr[smallest] ? right : smallest; // If Node i violates the min heap // property, swap current node i with // smallest to fix the min-heap property // and recursively call heapify for node smallest. if (smallest != i) { swap(arr[i], arr[smallest]); heapify(smallest); }} // Build Min Heapvoid MinHeap::buildHeap(){ // Calling Heapify for all non leaf nodes for (int i = size / 2 - 1; i >= 0; i--) { heapify(i); }} void FirstKelements(int arr[],int size,int k){ // Creating Min Heap for given // array with only k elements MinHeap* m = new MinHeap(k, arr); // Loop For each element in array // after the kth element for (int i = k; i < size; i++) { // if current element is smaller // than minimum element, do nothing // and continue to next element if (arr[0] > arr[i]) continue; // Otherwise Change minimum element to // current element, and call heapify to // restore the heap property else { arr[0] = arr[i]; m->heapify(0); } } // Now min heap contains k maximum // elements, Iterate and print for (int i = 0; i < k; i++) { cout << arr[i] << " "; }}// Driver Programint main(){ int arr[] = { 11, 3, 2, 1, 15, 5, 4, 45, 88, 96, 50, 45 }; int size = sizeof(arr) / sizeof(arr[0]); // Size of Min Heap int k = 3; FirstKelements(arr,size,k); return 0;}// This code is contributed by Ankur Goel import java.io.*;import java.util.*; class GFG{ public static void FirstKelements(int arr[], int size, int k){ // Creating Min Heap for given // array with only k elements // Create min heap with priority queue PriorityQueue<Integer> minHeap = new PriorityQueue<>(); for(int i = 0; i < k; i++) { minHeap.add(arr[i]); } // Loop For each element in array // after the kth element for(int i = k; i < size; i++) { // If current element is smaller // than minimum ((top element of // the minHeap) element, do nothing // and continue to next element if (minHeap.peek() > arr[i]) continue; // Otherwise Change minimum element // (top element of the minHeap) to // current element by polling out // the top element of the minHeap else { minHeap.poll(); minHeap.add(arr[i]); } } // Now min heap contains k maximum // elements, Iterate and print Iterator iterator = minHeap.iterator(); while (iterator.hasNext()) { System.out.print(iterator.next() + " "); } } // Driver codepublic static void main (String[] args){ int arr[] = { 11, 3, 2, 1, 15, 5, 4, 45, 88, 96, 50, 45 }; int size = arr.length; // Size of Min Heap int k = 3; FirstKelements(arr, size, k);}} // This code is contributed by Vansh Sethi def FirstKelements(arr,size,k): # Creating Min Heap for given # array with only k elements # Create min heap with priority queue minHeap = [] for i in range(k): minHeap.append(arr[i]) # Loop For each element in array # after the kth element for i in range(k, size): minHeap.sort() # If current element is smaller # than minimum ((top element of # the minHeap) element, do nothing # and continue to next element if (minHeap[0] > arr[i]): continue # Otherwise Change minimum element # (top element of the minHeap) to # current element by polling out # the top element of the minHeap else: minHeap.pop(0) minHeap.append(arr[i]) # Now min heap contains k maximum # elements, Iterate and print for i in minHeap: print(i, end = " ") # Driver codearr=[11, 3, 2, 1, 15, 5, 4,45, 88, 96, 50, 45]size = len(arr) # Size of Min Heapk=3FirstKelements(arr, size, k) # This code is contributed by avanitrachhadiya2155 using System;using System.Collections.Generic;public class GFG{ public static void FirstKelements(int []arr, int size, int k){ // Creating Min Heap for given // array with only k elements // Create min heap with priority queue List<int> minHeap = new List<int>(); for(int i = 0; i < k; i++) { minHeap.Add(arr[i]); } // Loop For each element in array // after the kth element for(int i = k; i < size; i++) { minHeap.Sort(); // If current element is smaller // than minimum ((top element of // the minHeap) element, do nothing // and continue to next element if (minHeap[0] > arr[i]) continue; // Otherwise Change minimum element // (top element of the minHeap) to // current element by polling out // the top element of the minHeap else { minHeap.RemoveAt(0); minHeap.Add(arr[i]); } } // Now min heap contains k maximum // elements, Iterate and print foreach (int i in minHeap) { Console.Write(i + " "); } } // Driver codepublic static void Main(String[] args){ int []arr = { 11, 3, 2, 1, 15, 5, 4, 45, 88, 96, 50, 45 }; int size = arr.Length; // Size of Min Heap int k = 3; FirstKelements(arr, size, k);}} // This code is contributed by aashish1995. <script> function FirstKelements(arr , size , k) { // Creating Min Heap for given // array with only k elements // Create min heap with priority queue var minHeap = []; for (var i = 0; i < k; i++) { minHeap.push(arr[i]); } // Loop For each element in array // after the kth element for (var i = k; i < size; i++) { minHeap.sort((a,b)=>a-b); // If current element is smaller // than minimum ((top element of // the minHeap) element, do nothing // and continue to next element if (minHeap[minHeap.length-3] > arr[i]) continue; // Otherwise Change minimum element // (top element of the minHeap) to // current element by polling out // the top element of the minHeap else { minHeap.reverse(); minHeap.pop(); minHeap.reverse(); minHeap.push(arr[i]); } } // Now min heap contains k maximum // elements, Iterate and print for (var iterator of minHeap) { document.write(iterator + " "); } } // Driver code var arr = [11, 3, 2, 1, 15, 5, 4, 45, 88, 96, 50, 45]; var size = arr.length; // Size of Min Heap var k = 3; FirstKelements(arr, size, k); // This code is contributed by gauravrajput1</script> 50 88 96 Time Complexity: O(nlogn)Auxiliary Space: O(n) Method 7(Using Quick Sort partitioning algorithm): Choose a pivot number.if K is lesser than the pivot_Index then repeat the step.if K == pivot_Index : Print the array (low to pivot to get K-smallest elements and (n-pivot_Index) to n for K-largest elements)if K > pivot_Index : Repeat the steps for right part. Choose a pivot number. if K is lesser than the pivot_Index then repeat the step. if K == pivot_Index : Print the array (low to pivot to get K-smallest elements and (n-pivot_Index) to n for K-largest elements) if K > pivot_Index : Repeat the steps for right part. We can improve on the standard quicksort algorithm by using the random() function. Instead of using the pivot element as the last element, we can randomly choose the pivot element. The worst-case time complexity of this version is O(n2) and the average time complexity is O(n). Following is the implementation of the above algorithm: C++ Java Python3 C# Javascript #include <bits/stdc++.h>using namespace std; //picks up last element between start and endint findPivot(int a[], int start, int end){ // Selecting the pivot element int pivot = a[end]; // Initially partition-index will be // at starting int pIndex = start; for (int i = start; i < end; i++) { // If an element is lesser than pivot, swap it. if (a[i] <= pivot) { swap(a[i], a[pIndex]); // Incrementing pIndex for further // swapping. pIndex++; } } // Lastly swapping or the // correct position of pivot swap(a[pIndex], a[end]); return pIndex;} //THIS PART OF CODE IS CONTRIBUTED BY - rjrachit//Picks up random pivot element between start and endint findRandomPivot(int arr[], int start, int end){ int n = end - start + 1; // Selecting the random pivot index int pivotInd = random()%n; swap(arr[end],arr[start+pivotInd]); int pivot = arr[end]; //initialising pivoting point to start index pivotInd = start; for (int i = start; i < end; i++) { // If an element is lesser than pivot, swap it. if (arr[i] <= pivot) { swap(arr[i], arr[pivotInd]); // Incrementing pivotIndex for further // swapping. pivotInd++; } } // Lastly swapping or the // correct position of pivot swap(arr[pivotInd], arr[end]); return pivotInd;}//THIS PART OF CODE IS CONTRIBUTED BY - rjrachit void SmallestLargest(int a[], int low, int high, int k, int n){ if (low == high) return; else { int pivotIndex = findRandomPivot(a, low, high); if (k == pivotIndex) { cout << k << " smallest elements are : "; for (int i = 0; i < pivotIndex; i++) cout << a[i] << " "; cout << endl; cout << k << " largest elements are : "; for (int i = (n - pivotIndex); i < n; i++) cout << a[i] << " "; } else if (k < pivotIndex) SmallestLargest(a, low, pivotIndex - 1, k, n); else if (k > pivotIndex) SmallestLargest(a, pivotIndex + 1, high, k, n); }} // Driver Codeint main(){ int a[] = { 11, 3, 2, 1, 15, 5, 4, 45, 88, 96, 50, 45 }; int n = sizeof(a) / sizeof(a[0]); int low = 0; int high = n - 1; // Lets assume k is 3 int k = 3; // Function Call SmallestLargest(a, low, high, k, n); return 0;} import java.util.*; class GFG{ //picks up last element between start and end static int findPivot(int a[], int start, int end) { // Selecting the pivot element int pivot = a[end]; // Initially partition-index will be // at starting int pIndex = start; for (int i = start; i < end; i++) { // If an element is lesser than pivot, swap it. if (a[i] <= pivot) { int temp =a[i]; a[i]= a[pIndex]; a[pIndex] = temp; // Incrementing pIndex for further // swapping. pIndex++; } } // Lastly swapping or the // correct position of pivot int temp = a[pIndex]; a[pIndex] = a[end]; a[end] = temp; return pIndex; } //THIS PART OF CODE IS CONTRIBUTED BY - rjrachit //Picks up random pivot element between start and end static int findRandomPivot(int arr[], int start, int end) { int n = end - start + 1; // Selecting the random pivot index int pivotInd = (int) ((Math.random()*1000000)%n); int temp = arr[end]; arr[end] = arr[start+pivotInd]; arr[start+pivotInd] = temp; int pivot = arr[end]; //initialising pivoting point to start index pivotInd = start; for (int i = start; i < end; i++) { // If an element is lesser than pivot, swap it. if (arr[i] <= pivot) { int temp1 = arr[i]; arr[i]= arr[pivotInd]; arr[pivotInd] = temp1; // Incrementing pivotIndex for further // swapping. pivotInd++; } } // Lastly swapping or the // correct position of pivot int tep = arr[pivotInd]; arr[pivotInd] = arr[end]; arr[end] = tep; return pivotInd; } //THIS PART OF CODE IS CONTRIBUTED BY - rjrachit static void SmallestLargest(int a[], int low, int high, int k, int n) { if (low == high) return; else { int pivotIndex = findRandomPivot(a, low, high); if (k == pivotIndex) { System.out.print(k+ " smallest elements are : "); for (int i = 0; i < pivotIndex; i++) System.out.print(a[i]+ " "); System.out.println(); System.out.print(k+ " largest elements are : "); for (int i = (n - pivotIndex); i < n; i++) System.out.print(a[i]+ " "); } else if (k < pivotIndex) SmallestLargest(a, low, pivotIndex - 1, k, n); else if (k > pivotIndex) SmallestLargest(a, pivotIndex + 1, high, k, n); } } // Driver Code public static void main(String[] args) { int a[] = { 11, 3, 2, 1, 15, 5, 4, 45, 88, 96, 50, 45 }; int n = a.length; int low = 0; int high = n - 1; // Lets assume k is 3 int k = 3; // Function Call SmallestLargest(a, low, high, k, n); }} // This code is contributed by Rajput-Ji # Python program to implement above approach # picks up last element between start and endimport random def findPivot(a, start, end): # Selecting the pivot element pivot = a[end] # Initially partition-index will be # at starting pIndex = start for i in range(start,end): # If an element is lesser than pivot, swap it. if (a[i] <= pivot): a[i],a[pIndex] = a[pIndex],a[i] # Incrementing pIndex for further # swapping. pIndex += 1 # Lastly swapping or the # correct position of pivot a[end],a[pIndex] = a[pIndex],a[end] return pIndex #THIS PART OF CODE IS CONTRIBUTED BY - rjrachit#Picks up random pivot element between start and enddef findRandomPivot(arr, start, end): n = end - start + 1 # Selecting the random pivot index pivotInd = (int((random.random()*1000000))%n) arr[end],arr[start+pivotInd] = arr[start+pivotInd],arr[end] pivot = arr[end] #initialising pivoting poto start index pivotInd = start for i in range(start,end): # If an element is lesser than pivot, swap it. if (arr[i] <= pivot): arr[i],arr[pivotInd] = arr[pivotInd],arr[i] # Incrementing pivotIndex for further # swapping. pivotInd += 1 # Lastly swapping or the # correct position of pivot arr[pivotInd],arr[end] = arr[end],arr[pivotInd] return pivotInd def SmallestLargest(a, low, high, k, n): if (low == high): return else: pivotIndex = findRandomPivot(a, low, high) if (k == pivotIndex): print(str(k)+ " smallest elements are :",end=" ") for i in range(pivotIndex): print(a[i],end = " ") print() print(str(k)+ " largest elements are :",end=" ") for i in range(n - pivotIndex,n): print(a[i],end=" ") elif (k < pivotIndex): SmallestLargest(a, low, pivotIndex - 1, k, n) elif (k > pivotIndex): SmallestLargest(a, pivotIndex + 1, high, k, n) # Driver codea = [ 11, 3, 2, 1, 15, 5, 4, 45, 88, 96, 50, 45 ]n = len(a) low = 0high = n - 1 # assume k is 3k = 3 # Function CallSmallestLargest(a, low, high, k, n) # This code is contributed by shinjanpatra using System;using System.Text; public class GFG { // picks up last element between start and end static int findPivot(int []a, int start, int end) { // Selecting the pivot element int pivot = a[end]; // Initially partition-index will be // at starting int pIndex = start; for (int i = start; i < end; i++) { // If an element is lesser than pivot, swap it. if (a[i] <= pivot) { int temp6 = a[i]; a[i] = a[pIndex]; a[pIndex] = temp6; // Incrementing pIndex for further // swapping. pIndex++; } } // Lastly swapping or the // correct position of pivot int temp = a[pIndex]; a[pIndex] = a[end]; a[end] = temp; return pIndex; } // THIS PART OF CODE IS CONTRIBUTED BY - rjrachit // Picks up random pivot element between start and end static int findRandomPivot(int []arr, int start, int end) { int n = end - start + 1; // Selecting the random pivot index Random _random = new Random(); var randomNumber = _random.Next(0, n); int pivotInd = randomNumber; int temp = arr[end]; arr[end] = arr[start + pivotInd]; arr[start + pivotInd] = temp; int pivot = arr[end]; // initialising pivoting point to start index pivotInd = start; for (int i = start; i < end; i++) { // If an element is lesser than pivot, swap it. if (arr[i] <= pivot) { int temp1 = arr[i]; arr[i] = arr[pivotInd]; arr[pivotInd] = temp1; // Incrementing pivotIndex for further // swapping. pivotInd++; } } // Lastly swapping or the // correct position of pivot int tep = arr[pivotInd]; arr[pivotInd] = arr[end]; arr[end] = tep; return pivotInd; } static void SmallestLargest(int []a, int low, int high, int k, int n) { if (low == high) return; else { int pivotIndex = findRandomPivot(a, low, high); if (k == pivotIndex) { Console.Write(k + " smallest elements are : "); for (int i = 0; i < pivotIndex; i++) Console.Write(a[i] + " "); Console.WriteLine(); Console.Write(k + " largest elements are : "); for (int i = (n - pivotIndex); i < n; i++) Console.Write(a[i] + " "); } else if (k < pivotIndex) SmallestLargest(a, low, pivotIndex - 1, k, n); else if (k > pivotIndex) SmallestLargest(a, pivotIndex + 1, high, k, n); } } // Driver Code public static void Main(String[] args) { int []a = { 11, 3, 2, 1, 15, 5, 4, 45, 88, 96, 50, 45 }; int n = a.Length; int low = 0; int high = n - 1; // Lets assume k is 3 int k = 3; // Function Call SmallestLargest(a, low, high, k, n); }} // This code is contributed by Rajput-Ji <script> // JavaScript code to implement the approach //picks up last element between start and end function findPivot( a, start, end) { // Selecting the pivot element let pivot = a[end]; // Initially partition-index will be // at starting let pIndex = start; for (let i = start; i < end; i++) { // If an element is lesser than pivot, swap it. if (a[i] <= pivot) { let temp =a[i]; a[i]= a[pIndex]; a[pIndex] = temp; // Incrementing pIndex for further // swapping. pIndex++; } } // Lastly swapping or the // correct position of pivot let temp = a[pIndex]; a[pIndex] = a[end]; a[end] = temp; return pIndex; } //THIS PART OF CODE IS CONTRIBUTED BY - rjrachit //Picks up random pivot element between start and end function findRandomPivot(arr, start, end) { let n = end - start + 1; // Selecting the random pivot index let pivotInd = (parseInt((Math.random()*1000000))%n); let temp = arr[end]; arr[end] = arr[start+pivotInd]; arr[start+pivotInd] = temp; let pivot = arr[end]; //initialising pivoting point to start index pivotInd = start; for (let i = start; i < end; i++) { // If an element is lesser than pivot, swap it. if (arr[i] <= pivot) { let temp1 = arr[i]; arr[i]= arr[pivotInd]; arr[pivotInd] = temp1; // Incrementing pivotIndex for further // swapping. pivotInd++; } } // Lastly swapping or the // correct position of pivot let tep = arr[pivotInd]; arr[pivotInd] = arr[end]; arr[end] = tep; return pivotInd; } //THIS PART OF CODE IS CONTRIBUTED BY - rjrachit function SmallestLargest( a, low, high, k, n) { if (low == high) return; else { let pivotIndex = findRandomPivot(a, low, high); if (k == pivotIndex) { document.write(k+ " smallest elements are : "); for (let i = 0; i < pivotIndex; i++) document.write(a[i]+ " "); document.write("<br/>"); document.write(k+ " largest elements are : "); for (let i = (n - pivotIndex); i < n; i++) document.write(a[i]+ " "); } else if (k < pivotIndex) SmallestLargest(a, low, pivotIndex - 1, k, n); else if (k > pivotIndex) SmallestLargest(a, pivotIndex + 1, high, k, n); } } // Driver code let a = [ 11, 3, 2, 1, 15, 5, 4, 45, 88, 96, 50, 45 ]; let n = a.length; let low = 0; let high = n - 1; // Lets assume k is 3 let k = 3; // Function Call SmallestLargest(a, low, high, k, n); // This code is contributed by sanjoy_62.</script> 3 smallest elements are : 3 2 1 3 largest elements are : 96 50 88 Time Complexity: O(nlogn)Auxiliary Space: O(1) Method 8(Using priority queue STL library):In this approach, we can efficiently print the k largest/smallest elements of an array using a priority queue in O(n*log(k)) time complexity. First, we push k elements into the priority queue from the array. From there on, after every insertion of an array element, we will pop the element at the top of priority_queue. In the case of the k largest element, the priority_queue will be in increasing order, and thus top most element will be the smallest so we are removing it. Similarly, in the case of the k smallest element, the priority_queue is in decreasing order and hence the top most element is the largest one so we will remove it. In this fashion whole array is traversed and the priority queue of size k is printed which contains k largest/smallest elements. Below is the implementation of the above approach: C++ Java // C++ code for k largest/ smallest elements in an array#include <bits/stdc++.h>using namespace std; // Function to find k largest array elementvoid kLargest(vector<int>& v, int N, int K){ // Implementation using // a Priority Queue priority_queue<int, vector<int>, greater<int> >pq; for (int i = 0; i < N; ++i) { // Insert elements into // the priority queue pq.push(v[i]); // If size of the priority // queue exceeds k if (pq.size() > K) { pq.pop(); } } // Print the k largest element while(!pq.empty()) { cout << pq.top() <<" "; pq.pop(); } cout<<endl;} // Function to find k smallest array elementvoid kSmalest(vector<int>& v, int N, int K){ // Implementation using // a Priority Queue priority_queue<int> pq; for (int i = 0; i < N; ++i) { // Insert elements into // the priority queue pq.push(v[i]); // If size of the priority // queue exceeds k if (pq.size() > K) { pq.pop(); } } // Print the k smallest element while(!pq.empty()) { cout << pq.top() <<" "; pq.pop(); } } // driver programint main(){ // Given array vector<int> arr = { 11, 3, 2, 1, 15, 5, 4, 45, 88, 96, 50, 45 }; // Size of array int n = arr.size(); int k = 3; cout<<k<<" largest elements are : "; kLargest(arr, n, k); cout<<k<<" smallest elements are : "; kSmalest(arr, n, k);} // This code is contributed by Pushpesh Raj. // Java code for k largest/ smallest elements in an arrayimport java.util.*; class GFG { // Function to find k largest array element static void kLargest(int a[], int n, int k) { // Implementation using // a Priority Queue PriorityQueue<Integer> pq = new PriorityQueue<Integer>(); for (int i = 0; i < n; ++i) { // Insert elements into // the priority queue pq.add(a[i]); // If size of the priority // queue exceeds k if (pq.size() > k) { pq.poll(); } } // Print the k largest element while (!pq.isEmpty()) { System.out.print(pq.peek() + " "); pq.poll(); } System.out.println(); } // Function to find k smallest array element static void kSmallest(int a[], int n, int k) { // Implementation using // a Priority Queue PriorityQueue<Integer> pq = new PriorityQueue<Integer>( Collections.reverseOrder()); for (int i = 0; i < n; ++i) { // Insert elements into // the priority queue pq.add(a[i]); // If size of the priority // queue exceeds k if (pq.size() > k) { pq.poll(); } } // Print the k largest element while (!pq.isEmpty()) { System.out.print(pq.peek() + " "); pq.poll(); } } // Driver Code public static void main(String[] args) { int a[] = { 11, 3, 2, 1, 15, 5, 4, 45, 88, 96, 50, 45 }; int n = a.length; int k = 3; System.out.print(k + " largest elements are : "); // Function Call kLargest(a, n, k); System.out.print(k + " smallest elements are : "); // Function Call kSmallest(a, n, k); }} // This code is contributed by Aarti_Rathi 3 largest elements are : 50 88 96 3 smallest elements are : 3 2 1 Time Complexity: O(n*log(k))Auxiliary Space: O(k) Please write comments if you find any of the above explanations/algorithms incorrect, or find better ways to solve the same problem.References: http://en.wikipedia.org/wiki/Selection_algorithm ukasp erikest Rajput-Ji Ankur Goel sethivansh6 nirajd24 aashish1995 avanitrachhadiya2155 imsushant12 rjrachit mank1083 shivansh20127 chand25 punamsingh628700 GauravRajput1 clintra sanjoy_62 shinjanpatra sweetyty pushpeshrajdx01 _shinchancode adityakumar129 mayanksingh5399 Amazon Microsoft Order-Statistics Samsung Walmart Arrays Heap Searching Sorting Amazon Microsoft Samsung Walmart Arrays Searching Sorting Heap Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Multidimensional Arrays in Java Introduction to Arrays Subset Sum Problem | DP-25 Introduction to Data Structures Python | Using 2D arrays/lists the right way HeapSort Binary Heap Introduction to Data Structures Huffman Coding | Greedy Algo-3 Sliding Window Maximum (Maximum of all subarrays of size k)
[ { "code": null, "e": 54, "s": 26, "text": "\n05 Jul, 2022" }, { "code": null, "e": 332, "s": 54, "text": "Write an efficient program for printing k largest elements in an array. Elements in an array can be in any order.For example: if the given array is [1, 23, 12, 9, 30, 2, 50] and you are asked for the largest 3 elements i.e., k = 3 then your program should print 50, 30, and 23." }, { "code": null, "e": 560, "s": 332, "text": "Method 1 (Use Bubble k times) Thanks to Shailendra for suggesting this approach. 1) Modify Bubble Sort to run the outer loop at most k times. 2) Print the last k elements of the array obtained in step 1.Time Complexity: O(n*k) " }, { "code": null, "e": 675, "s": 560, "text": "Like Bubble sort, other sorting algorithms like Selection Sort can also be modified to get the k largest elements." }, { "code": null, "e": 742, "s": 675, "text": "Method 2 (Use temporary array) K largest elements from arr[0..n-1]" }, { "code": null, "e": 1091, "s": 742, "text": "1) Store the first k elements in a temporary array temp[0..k-1]. 2) Find the smallest element in temp[], let the smallest element be min. 3-a) For each element x in arr[k] to arr[n-1]. O(n-k) If x is greater than the min then remove min from temp[] and insert x. 3-b)Then, determine the new min from temp[]. O(k) 4) Print final k elements of temp[]" }, { "code": null, "e": 1227, "s": 1091, "text": "Time Complexity: O((n-k)*k). If we want the output sorted then O((n-k)*k + k*log(k))Thanks to nesamani1822 for suggesting this method. " }, { "code": null, "e": 1361, "s": 1227, "text": "Method 3(Use Sorting) 1) Sort the elements in descending order in O(n*log(n)) 2) Print the first k numbers of the sorted array O(k). " }, { "code": null, "e": 1409, "s": 1361, "text": "Following is the implementation of the above. " }, { "code": null, "e": 1413, "s": 1409, "text": "C++" }, { "code": null, "e": 1415, "s": 1413, "text": "C" }, { "code": null, "e": 1420, "s": 1415, "text": "Java" }, { "code": null, "e": 1427, "s": 1420, "text": "Python" }, { "code": null, "e": 1430, "s": 1427, "text": "C#" }, { "code": null, "e": 1434, "s": 1430, "text": "PHP" }, { "code": null, "e": 1445, "s": 1434, "text": "Javascript" }, { "code": "// C++ code for k largest elements in an array#include <bits/stdc++.h>using namespace std; void kLargest(int arr[], int n, int k){ // Sort the given array arr in reverse order. sort(arr, arr + n, greater<int>()); // Print the first kth largest elements for (int i = 0; i < k; i++) cout << arr[i] << \" \";} // driver programint main(){ int arr[] = { 1, 23, 12, 9, 30, 2, 50 }; int n = sizeof(arr) / sizeof(arr[0]); int k = 3; kLargest(arr, n, k);} // This code is contributed by Aditya Kumar (adityakumar129)", "e": 1988, "s": 1445, "text": null }, { "code": "// C code for k largest elements in an array#include <stdio.h>#include <stdlib.h> // Compare function for qsortint cmpfunc(const void* a, const void* b){ return (*(int*)b - *(int*)a);} void kLargest(int arr[], int n, int k){ // Sort the given array arr in reverse order. qsort(arr, n, sizeof(int), cmpfunc); // Print the first kth largest elements for (int i = 0; i < k; i++) printf(\"%d \", arr[i]);} // driver programint main(){ int arr[] = { 1, 23, 12, 9, 30, 2, 50 }; int n = sizeof(arr) / sizeof(arr[0]); int k = 3; kLargest(arr, n, k);} // This code is contributed by Aditya Kumar (adityakumar129)", "e": 2628, "s": 1988, "text": null }, { "code": "// Java code for k largest elements in an arrayimport java.util.Arrays;import java.util.Collections;import java.util.ArrayList; class GFG { public static void kLargest(Integer[] arr, int k) { // Sort the given array arr in reverse order // This method doesn't work with primitive data // types. So, instead of int, Integer type // array will be used Arrays.sort(arr, Collections.reverseOrder()); // Print the first kth largest elements for (int i = 0; i < k; i++) System.out.print(arr[i] + \" \"); } //This code is contributed by Niraj Dubey public static ArrayList<Integer> kLargest(int[] arr, int k) { //Convert using stream Integer[] obj_array = Arrays.stream( arr ).boxed().toArray( Integer[] :: new); Arrays.sort(obj_array, Collections.reverseOrder()); ArrayList<Integer> list = new ArrayList<>(k); for (int i = 0; i < k; i++) list.add(obj_array[i]); return list; } public static void main(String[] args) { Integer arr[] = new Integer[] { 1, 23, 12, 9, 30, 2, 50 }; int k = 3; kLargest(arr, k); //This code is contributed by Niraj Dubey //What if primitive datatype array is passed and wanted to return in ArrayList<Integer> int[] prim_array = { 1, 23, 12, 9, 30, 2, 50 }; System.out.print(kLargest(prim_array, k)); }}// This code is contributed by Kamal Rawal", "e": 4146, "s": 2628, "text": null }, { "code": "''' Python3 code for k largest elements in an array''' def kLargest(arr, k): # Sort the given array arr in reverse # order. arr.sort(reverse = True) # Print the first kth largest elements for i in range(k): print (arr[i], end =\" \") # Driver programarr = [1, 23, 12, 9, 30, 2, 50]# n = len(arr)k = 3kLargest(arr, k) # This code is contributed by shreyanshi_arun.", "e": 4535, "s": 4146, "text": null }, { "code": "// C# code for k largest elements in an arrayusing System; class GFG { public static void kLargest(int[] arr, int k) { // Sort the given array arr in reverse order // This method doesn't work with primitive data // types. So, instead of int, Integer type // array will be used Array.Sort(arr); Array.Reverse(arr); // Print the first kth largest elements for (int i = 0; i < k; i++) Console.Write(arr[i] + \" \"); } // Driver code public static void Main(String[] args) { int[] arr = new int[] { 1, 23, 12, 9, 30, 2, 50 }; int k = 3; kLargest(arr, k); }} // This code contributed by Rajput-Ji", "e": 5271, "s": 4535, "text": null }, { "code": "<?php // PHP code for k largest // elements in an array function kLargest(&$arr, $n, $k){ // Sort the given array arr // in reverse order. rsort($arr); // Print the first kth // largest elements for ($i = 0; $i < $k; $i++) echo $arr[$i] . \" \";} // Driver Code$arr = array(1, 23, 12, 9, 30, 2, 50);$n = sizeof($arr);$k = 3;kLargest($arr, $n, $k); // This code is contributed // by ChitraNayal?>", "e": 5713, "s": 5271, "text": null }, { "code": "<script> // JavaScript code for k largest// elements in an array function kLargest(arr, n, k){ // Sort the given array arr in reverse // order. arr.sort((a, b) => b - a); // Print the first kth largest elements for (let i = 0; i < k; i++) document.write(arr[i] + \" \");} // driver program let arr = [ 1, 23, 12, 9, 30, 2, 50 ]; let n = arr.length; let k = 3; kLargest(arr, n, k); // This code is contributed by Manoj. </script>", "e": 6183, "s": 5713, "text": null }, { "code": null, "e": 6193, "s": 6183, "text": "50 30 23 " }, { "code": null, "e": 6243, "s": 6193, "text": "Time complexity: O(n*log(n))Auxiliary Space: O(1)" }, { "code": null, "e": 6383, "s": 6243, "text": "Method 4 (Use Max Heap) 1) Build a Max Heap tree in O(n) 2) Use Extract Max k times to get k maximum elements from the Max Heap O(k*log(n))" }, { "code": null, "e": 6417, "s": 6383, "text": "Time complexity: O(n + k*log(n)) " }, { "code": null, "e": 6810, "s": 6417, "text": "Method 5(Use Order Statistics) 1) Use an order statistic algorithm to find the kth largest element. Please see the topic selection in worst-case linear time O(n) 2) Use QuickSort Partition algorithm to partition around the kth largest number O(n). 3) Sort the k-1 elements (elements greater than the kth largest element) O(k*log(k)). This step is needed only if the sorted output is required." }, { "code": null, "e": 6949, "s": 6810, "text": "Time complexity: O(n) if we don’t need the sorted output, otherwise O(n+k*log(k))Thanks to Shilpi for suggesting the first two approaches." }, { "code": null, "e": 7678, "s": 6949, "text": "Method 6 (Use Min Heap) This method is mainly an optimization of method 2. Instead of using temp[] array, use Min Heap.1) Build a Min Heap MH of the first k elements (arr[0] to arr[k-1]) of the given array. O(k*log(k))2) For each element, after the kth element (arr[k] to arr[n-1]), compare it with root of MH. ......a) If the element is greater than the root then make it root and call heapify for MH ......b) Else ignore it. // The step 2 is O((n-k)*log(k))3) Finally, MH has k largest elements, and the root of the MH is the kth largest element.Time Complexity: O(k*log(k) + (n-k)*log(k)) without sorted output. If sorted output is needed then O(k*log(k) + (n-k)*log(k) + k*log(k)) so overall it is O(k*log(k) + (n-k)*log(k))" }, { "code": null, "e": 7767, "s": 7678, "text": "All of the above methods can also be used to find the kth largest (or smallest) element." }, { "code": null, "e": 7771, "s": 7767, "text": "C++" }, { "code": null, "e": 7776, "s": 7771, "text": "Java" }, { "code": null, "e": 7784, "s": 7776, "text": "Python3" }, { "code": null, "e": 7787, "s": 7784, "text": "C#" }, { "code": null, "e": 7798, "s": 7787, "text": "Javascript" }, { "code": "#include <iostream>using namespace std; // Swap function to interchange// the value of variables x and yint swap(int& x, int& y){ int temp = x; x = y; y = temp;} // Min Heap Class// arr holds reference to an integer // array size indicate the number of// elements in Min Heapclass MinHeap { int size; int* arr; public: // Constructor to initialize the size and arr MinHeap(int size, int input[]); // Min Heapify function, that assumes that // 2*i+1 and 2*i+2 are min heap and fix the // heap property for i. void heapify(int i); // Build the min heap, by calling heapify // for all non-leaf nodes. void buildHeap();}; // Constructor to initialize data// members and creating mean heapMinHeap::MinHeap(int size, int input[]){ // Initializing arr and size this->size = size; this->arr = input; // Building the Min Heap buildHeap();} // Min Heapify function, that assumes// 2*i+1 and 2*i+2 are min heap and // fix min heap property for i void MinHeap::heapify(int i){ // If Leaf Node, Simply return if (i >= size / 2) return; // variable to store the smallest element // index out of i, 2*i+1 and 2*i+2 int smallest; // Index of left node int left = 2 * i + 1; // Index of right node int right = 2 * i + 2; // Select minimum from left node and // current node i, and store the minimum // index in smallest variable smallest = arr[left] < arr[i] ? left : i; // If right child exist, compare and // update the smallest variable if (right < size) smallest = arr[right] < arr[smallest] ? right : smallest; // If Node i violates the min heap // property, swap current node i with // smallest to fix the min-heap property // and recursively call heapify for node smallest. if (smallest != i) { swap(arr[i], arr[smallest]); heapify(smallest); }} // Build Min Heapvoid MinHeap::buildHeap(){ // Calling Heapify for all non leaf nodes for (int i = size / 2 - 1; i >= 0; i--) { heapify(i); }} void FirstKelements(int arr[],int size,int k){ // Creating Min Heap for given // array with only k elements MinHeap* m = new MinHeap(k, arr); // Loop For each element in array // after the kth element for (int i = k; i < size; i++) { // if current element is smaller // than minimum element, do nothing // and continue to next element if (arr[0] > arr[i]) continue; // Otherwise Change minimum element to // current element, and call heapify to // restore the heap property else { arr[0] = arr[i]; m->heapify(0); } } // Now min heap contains k maximum // elements, Iterate and print for (int i = 0; i < k; i++) { cout << arr[i] << \" \"; }}// Driver Programint main(){ int arr[] = { 11, 3, 2, 1, 15, 5, 4, 45, 88, 96, 50, 45 }; int size = sizeof(arr) / sizeof(arr[0]); // Size of Min Heap int k = 3; FirstKelements(arr,size,k); return 0;}// This code is contributed by Ankur Goel", "e": 10983, "s": 7798, "text": null }, { "code": "import java.io.*;import java.util.*; class GFG{ public static void FirstKelements(int arr[], int size, int k){ // Creating Min Heap for given // array with only k elements // Create min heap with priority queue PriorityQueue<Integer> minHeap = new PriorityQueue<>(); for(int i = 0; i < k; i++) { minHeap.add(arr[i]); } // Loop For each element in array // after the kth element for(int i = k; i < size; i++) { // If current element is smaller // than minimum ((top element of // the minHeap) element, do nothing // and continue to next element if (minHeap.peek() > arr[i]) continue; // Otherwise Change minimum element // (top element of the minHeap) to // current element by polling out // the top element of the minHeap else { minHeap.poll(); minHeap.add(arr[i]); } } // Now min heap contains k maximum // elements, Iterate and print Iterator iterator = minHeap.iterator(); while (iterator.hasNext()) { System.out.print(iterator.next() + \" \"); } } // Driver codepublic static void main (String[] args){ int arr[] = { 11, 3, 2, 1, 15, 5, 4, 45, 88, 96, 50, 45 }; int size = arr.length; // Size of Min Heap int k = 3; FirstKelements(arr, size, k);}} // This code is contributed by Vansh Sethi", "e": 12537, "s": 10983, "text": null }, { "code": "def FirstKelements(arr,size,k): # Creating Min Heap for given # array with only k elements # Create min heap with priority queue minHeap = [] for i in range(k): minHeap.append(arr[i]) # Loop For each element in array # after the kth element for i in range(k, size): minHeap.sort() # If current element is smaller # than minimum ((top element of # the minHeap) element, do nothing # and continue to next element if (minHeap[0] > arr[i]): continue # Otherwise Change minimum element # (top element of the minHeap) to # current element by polling out # the top element of the minHeap else: minHeap.pop(0) minHeap.append(arr[i]) # Now min heap contains k maximum # elements, Iterate and print for i in minHeap: print(i, end = \" \") # Driver codearr=[11, 3, 2, 1, 15, 5, 4,45, 88, 96, 50, 45]size = len(arr) # Size of Min Heapk=3FirstKelements(arr, size, k) # This code is contributed by avanitrachhadiya2155", "e": 13657, "s": 12537, "text": null }, { "code": "using System;using System.Collections.Generic;public class GFG{ public static void FirstKelements(int []arr, int size, int k){ // Creating Min Heap for given // array with only k elements // Create min heap with priority queue List<int> minHeap = new List<int>(); for(int i = 0; i < k; i++) { minHeap.Add(arr[i]); } // Loop For each element in array // after the kth element for(int i = k; i < size; i++) { minHeap.Sort(); // If current element is smaller // than minimum ((top element of // the minHeap) element, do nothing // and continue to next element if (minHeap[0] > arr[i]) continue; // Otherwise Change minimum element // (top element of the minHeap) to // current element by polling out // the top element of the minHeap else { minHeap.RemoveAt(0); minHeap.Add(arr[i]); } } // Now min heap contains k maximum // elements, Iterate and print foreach (int i in minHeap) { Console.Write(i + \" \"); } } // Driver codepublic static void Main(String[] args){ int []arr = { 11, 3, 2, 1, 15, 5, 4, 45, 88, 96, 50, 45 }; int size = arr.Length; // Size of Min Heap int k = 3; FirstKelements(arr, size, k);}} // This code is contributed by aashish1995. ", "e": 15154, "s": 13657, "text": null }, { "code": "<script> function FirstKelements(arr , size , k) { // Creating Min Heap for given // array with only k elements // Create min heap with priority queue var minHeap = []; for (var i = 0; i < k; i++) { minHeap.push(arr[i]); } // Loop For each element in array // after the kth element for (var i = k; i < size; i++) { minHeap.sort((a,b)=>a-b); // If current element is smaller // than minimum ((top element of // the minHeap) element, do nothing // and continue to next element if (minHeap[minHeap.length-3] > arr[i]) continue; // Otherwise Change minimum element // (top element of the minHeap) to // current element by polling out // the top element of the minHeap else { minHeap.reverse(); minHeap.pop(); minHeap.reverse(); minHeap.push(arr[i]); } } // Now min heap contains k maximum // elements, Iterate and print for (var iterator of minHeap) { document.write(iterator + \" \"); } } // Driver code var arr = [11, 3, 2, 1, 15, 5, 4, 45, 88, 96, 50, 45]; var size = arr.length; // Size of Min Heap var k = 3; FirstKelements(arr, size, k); // This code is contributed by gauravrajput1</script>", "e": 16649, "s": 15154, "text": null }, { "code": null, "e": 16659, "s": 16649, "text": "50 88 96 " }, { "code": null, "e": 16706, "s": 16659, "text": "Time Complexity: O(nlogn)Auxiliary Space: O(n)" }, { "code": null, "e": 16757, "s": 16706, "text": "Method 7(Using Quick Sort partitioning algorithm):" }, { "code": null, "e": 17018, "s": 16757, "text": "Choose a pivot number.if K is lesser than the pivot_Index then repeat the step.if K == pivot_Index : Print the array (low to pivot to get K-smallest elements and (n-pivot_Index) to n for K-largest elements)if K > pivot_Index : Repeat the steps for right part." }, { "code": null, "e": 17041, "s": 17018, "text": "Choose a pivot number." }, { "code": null, "e": 17099, "s": 17041, "text": "if K is lesser than the pivot_Index then repeat the step." }, { "code": null, "e": 17227, "s": 17099, "text": "if K == pivot_Index : Print the array (low to pivot to get K-smallest elements and (n-pivot_Index) to n for K-largest elements)" }, { "code": null, "e": 17282, "s": 17227, "text": "if K > pivot_Index : Repeat the steps for right part." }, { "code": null, "e": 17560, "s": 17282, "text": "We can improve on the standard quicksort algorithm by using the random() function. Instead of using the pivot element as the last element, we can randomly choose the pivot element. The worst-case time complexity of this version is O(n2) and the average time complexity is O(n)." }, { "code": null, "e": 17616, "s": 17560, "text": "Following is the implementation of the above algorithm:" }, { "code": null, "e": 17620, "s": 17616, "text": "C++" }, { "code": null, "e": 17625, "s": 17620, "text": "Java" }, { "code": null, "e": 17633, "s": 17625, "text": "Python3" }, { "code": null, "e": 17636, "s": 17633, "text": "C#" }, { "code": null, "e": 17647, "s": 17636, "text": "Javascript" }, { "code": "#include <bits/stdc++.h>using namespace std; //picks up last element between start and endint findPivot(int a[], int start, int end){ // Selecting the pivot element int pivot = a[end]; // Initially partition-index will be // at starting int pIndex = start; for (int i = start; i < end; i++) { // If an element is lesser than pivot, swap it. if (a[i] <= pivot) { swap(a[i], a[pIndex]); // Incrementing pIndex for further // swapping. pIndex++; } } // Lastly swapping or the // correct position of pivot swap(a[pIndex], a[end]); return pIndex;} //THIS PART OF CODE IS CONTRIBUTED BY - rjrachit//Picks up random pivot element between start and endint findRandomPivot(int arr[], int start, int end){ int n = end - start + 1; // Selecting the random pivot index int pivotInd = random()%n; swap(arr[end],arr[start+pivotInd]); int pivot = arr[end]; //initialising pivoting point to start index pivotInd = start; for (int i = start; i < end; i++) { // If an element is lesser than pivot, swap it. if (arr[i] <= pivot) { swap(arr[i], arr[pivotInd]); // Incrementing pivotIndex for further // swapping. pivotInd++; } } // Lastly swapping or the // correct position of pivot swap(arr[pivotInd], arr[end]); return pivotInd;}//THIS PART OF CODE IS CONTRIBUTED BY - rjrachit void SmallestLargest(int a[], int low, int high, int k, int n){ if (low == high) return; else { int pivotIndex = findRandomPivot(a, low, high); if (k == pivotIndex) { cout << k << \" smallest elements are : \"; for (int i = 0; i < pivotIndex; i++) cout << a[i] << \" \"; cout << endl; cout << k << \" largest elements are : \"; for (int i = (n - pivotIndex); i < n; i++) cout << a[i] << \" \"; } else if (k < pivotIndex) SmallestLargest(a, low, pivotIndex - 1, k, n); else if (k > pivotIndex) SmallestLargest(a, pivotIndex + 1, high, k, n); }} // Driver Codeint main(){ int a[] = { 11, 3, 2, 1, 15, 5, 4, 45, 88, 96, 50, 45 }; int n = sizeof(a) / sizeof(a[0]); int low = 0; int high = n - 1; // Lets assume k is 3 int k = 3; // Function Call SmallestLargest(a, low, high, k, n); return 0;}", "e": 20194, "s": 17647, "text": null }, { "code": "import java.util.*; class GFG{ //picks up last element between start and end static int findPivot(int a[], int start, int end) { // Selecting the pivot element int pivot = a[end]; // Initially partition-index will be // at starting int pIndex = start; for (int i = start; i < end; i++) { // If an element is lesser than pivot, swap it. if (a[i] <= pivot) { int temp =a[i]; a[i]= a[pIndex]; a[pIndex] = temp; // Incrementing pIndex for further // swapping. pIndex++; } } // Lastly swapping or the // correct position of pivot int temp = a[pIndex]; a[pIndex] = a[end]; a[end] = temp; return pIndex; } //THIS PART OF CODE IS CONTRIBUTED BY - rjrachit //Picks up random pivot element between start and end static int findRandomPivot(int arr[], int start, int end) { int n = end - start + 1; // Selecting the random pivot index int pivotInd = (int) ((Math.random()*1000000)%n); int temp = arr[end]; arr[end] = arr[start+pivotInd]; arr[start+pivotInd] = temp; int pivot = arr[end]; //initialising pivoting point to start index pivotInd = start; for (int i = start; i < end; i++) { // If an element is lesser than pivot, swap it. if (arr[i] <= pivot) { int temp1 = arr[i]; arr[i]= arr[pivotInd]; arr[pivotInd] = temp1; // Incrementing pivotIndex for further // swapping. pivotInd++; } } // Lastly swapping or the // correct position of pivot int tep = arr[pivotInd]; arr[pivotInd] = arr[end]; arr[end] = tep; return pivotInd; } //THIS PART OF CODE IS CONTRIBUTED BY - rjrachit static void SmallestLargest(int a[], int low, int high, int k, int n) { if (low == high) return; else { int pivotIndex = findRandomPivot(a, low, high); if (k == pivotIndex) { System.out.print(k+ \" smallest elements are : \"); for (int i = 0; i < pivotIndex; i++) System.out.print(a[i]+ \" \"); System.out.println(); System.out.print(k+ \" largest elements are : \"); for (int i = (n - pivotIndex); i < n; i++) System.out.print(a[i]+ \" \"); } else if (k < pivotIndex) SmallestLargest(a, low, pivotIndex - 1, k, n); else if (k > pivotIndex) SmallestLargest(a, pivotIndex + 1, high, k, n); } } // Driver Code public static void main(String[] args) { int a[] = { 11, 3, 2, 1, 15, 5, 4, 45, 88, 96, 50, 45 }; int n = a.length; int low = 0; int high = n - 1; // Lets assume k is 3 int k = 3; // Function Call SmallestLargest(a, low, high, k, n); }} // This code is contributed by Rajput-Ji ", "e": 22976, "s": 20194, "text": null }, { "code": "# Python program to implement above approach # picks up last element between start and endimport random def findPivot(a, start, end): # Selecting the pivot element pivot = a[end] # Initially partition-index will be # at starting pIndex = start for i in range(start,end): # If an element is lesser than pivot, swap it. if (a[i] <= pivot): a[i],a[pIndex] = a[pIndex],a[i] # Incrementing pIndex for further # swapping. pIndex += 1 # Lastly swapping or the # correct position of pivot a[end],a[pIndex] = a[pIndex],a[end] return pIndex #THIS PART OF CODE IS CONTRIBUTED BY - rjrachit#Picks up random pivot element between start and enddef findRandomPivot(arr, start, end): n = end - start + 1 # Selecting the random pivot index pivotInd = (int((random.random()*1000000))%n) arr[end],arr[start+pivotInd] = arr[start+pivotInd],arr[end] pivot = arr[end] #initialising pivoting poto start index pivotInd = start for i in range(start,end): # If an element is lesser than pivot, swap it. if (arr[i] <= pivot): arr[i],arr[pivotInd] = arr[pivotInd],arr[i] # Incrementing pivotIndex for further # swapping. pivotInd += 1 # Lastly swapping or the # correct position of pivot arr[pivotInd],arr[end] = arr[end],arr[pivotInd] return pivotInd def SmallestLargest(a, low, high, k, n): if (low == high): return else: pivotIndex = findRandomPivot(a, low, high) if (k == pivotIndex): print(str(k)+ \" smallest elements are :\",end=\" \") for i in range(pivotIndex): print(a[i],end = \" \") print() print(str(k)+ \" largest elements are :\",end=\" \") for i in range(n - pivotIndex,n): print(a[i],end=\" \") elif (k < pivotIndex): SmallestLargest(a, low, pivotIndex - 1, k, n) elif (k > pivotIndex): SmallestLargest(a, pivotIndex + 1, high, k, n) # Driver codea = [ 11, 3, 2, 1, 15, 5, 4, 45, 88, 96, 50, 45 ]n = len(a) low = 0high = n - 1 # assume k is 3k = 3 # Function CallSmallestLargest(a, low, high, k, n) # This code is contributed by shinjanpatra", "e": 25314, "s": 22976, "text": null }, { "code": "using System;using System.Text; public class GFG { // picks up last element between start and end static int findPivot(int []a, int start, int end) { // Selecting the pivot element int pivot = a[end]; // Initially partition-index will be // at starting int pIndex = start; for (int i = start; i < end; i++) { // If an element is lesser than pivot, swap it. if (a[i] <= pivot) { int temp6 = a[i]; a[i] = a[pIndex]; a[pIndex] = temp6; // Incrementing pIndex for further // swapping. pIndex++; } } // Lastly swapping or the // correct position of pivot int temp = a[pIndex]; a[pIndex] = a[end]; a[end] = temp; return pIndex; } // THIS PART OF CODE IS CONTRIBUTED BY - rjrachit // Picks up random pivot element between start and end static int findRandomPivot(int []arr, int start, int end) { int n = end - start + 1; // Selecting the random pivot index Random _random = new Random(); var randomNumber = _random.Next(0, n); int pivotInd = randomNumber; int temp = arr[end]; arr[end] = arr[start + pivotInd]; arr[start + pivotInd] = temp; int pivot = arr[end]; // initialising pivoting point to start index pivotInd = start; for (int i = start; i < end; i++) { // If an element is lesser than pivot, swap it. if (arr[i] <= pivot) { int temp1 = arr[i]; arr[i] = arr[pivotInd]; arr[pivotInd] = temp1; // Incrementing pivotIndex for further // swapping. pivotInd++; } } // Lastly swapping or the // correct position of pivot int tep = arr[pivotInd]; arr[pivotInd] = arr[end]; arr[end] = tep; return pivotInd; } static void SmallestLargest(int []a, int low, int high, int k, int n) { if (low == high) return; else { int pivotIndex = findRandomPivot(a, low, high); if (k == pivotIndex) { Console.Write(k + \" smallest elements are : \"); for (int i = 0; i < pivotIndex; i++) Console.Write(a[i] + \" \"); Console.WriteLine(); Console.Write(k + \" largest elements are : \"); for (int i = (n - pivotIndex); i < n; i++) Console.Write(a[i] + \" \"); } else if (k < pivotIndex) SmallestLargest(a, low, pivotIndex - 1, k, n); else if (k > pivotIndex) SmallestLargest(a, pivotIndex + 1, high, k, n); } } // Driver Code public static void Main(String[] args) { int []a = { 11, 3, 2, 1, 15, 5, 4, 45, 88, 96, 50, 45 }; int n = a.Length; int low = 0; int high = n - 1; // Lets assume k is 3 int k = 3; // Function Call SmallestLargest(a, low, high, k, n); }} // This code is contributed by Rajput-Ji", "e": 28098, "s": 25314, "text": null }, { "code": "<script> // JavaScript code to implement the approach //picks up last element between start and end function findPivot( a, start, end) { // Selecting the pivot element let pivot = a[end]; // Initially partition-index will be // at starting let pIndex = start; for (let i = start; i < end; i++) { // If an element is lesser than pivot, swap it. if (a[i] <= pivot) { let temp =a[i]; a[i]= a[pIndex]; a[pIndex] = temp; // Incrementing pIndex for further // swapping. pIndex++; } } // Lastly swapping or the // correct position of pivot let temp = a[pIndex]; a[pIndex] = a[end]; a[end] = temp; return pIndex; } //THIS PART OF CODE IS CONTRIBUTED BY - rjrachit //Picks up random pivot element between start and end function findRandomPivot(arr, start, end) { let n = end - start + 1; // Selecting the random pivot index let pivotInd = (parseInt((Math.random()*1000000))%n); let temp = arr[end]; arr[end] = arr[start+pivotInd]; arr[start+pivotInd] = temp; let pivot = arr[end]; //initialising pivoting point to start index pivotInd = start; for (let i = start; i < end; i++) { // If an element is lesser than pivot, swap it. if (arr[i] <= pivot) { let temp1 = arr[i]; arr[i]= arr[pivotInd]; arr[pivotInd] = temp1; // Incrementing pivotIndex for further // swapping. pivotInd++; } } // Lastly swapping or the // correct position of pivot let tep = arr[pivotInd]; arr[pivotInd] = arr[end]; arr[end] = tep; return pivotInd; } //THIS PART OF CODE IS CONTRIBUTED BY - rjrachit function SmallestLargest( a, low, high, k, n) { if (low == high) return; else { let pivotIndex = findRandomPivot(a, low, high); if (k == pivotIndex) { document.write(k+ \" smallest elements are : \"); for (let i = 0; i < pivotIndex; i++) document.write(a[i]+ \" \"); document.write(\"<br/>\"); document.write(k+ \" largest elements are : \"); for (let i = (n - pivotIndex); i < n; i++) document.write(a[i]+ \" \"); } else if (k < pivotIndex) SmallestLargest(a, low, pivotIndex - 1, k, n); else if (k > pivotIndex) SmallestLargest(a, pivotIndex + 1, high, k, n); } } // Driver code let a = [ 11, 3, 2, 1, 15, 5, 4, 45, 88, 96, 50, 45 ]; let n = a.length; let low = 0; let high = n - 1; // Lets assume k is 3 let k = 3; // Function Call SmallestLargest(a, low, high, k, n); // This code is contributed by sanjoy_62.</script>", "e": 30835, "s": 28098, "text": null }, { "code": null, "e": 30909, "s": 30835, "text": "3 smallest elements are : 3 2 1 \n3 largest elements are : 96 50 88 " }, { "code": null, "e": 30956, "s": 30909, "text": "Time Complexity: O(nlogn)Auxiliary Space: O(1)" }, { "code": null, "e": 31768, "s": 30956, "text": "Method 8(Using priority queue STL library):In this approach, we can efficiently print the k largest/smallest elements of an array using a priority queue in O(n*log(k)) time complexity. First, we push k elements into the priority queue from the array. From there on, after every insertion of an array element, we will pop the element at the top of priority_queue. In the case of the k largest element, the priority_queue will be in increasing order, and thus top most element will be the smallest so we are removing it. Similarly, in the case of the k smallest element, the priority_queue is in decreasing order and hence the top most element is the largest one so we will remove it. In this fashion whole array is traversed and the priority queue of size k is printed which contains k largest/smallest elements." }, { "code": null, "e": 31819, "s": 31768, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 31823, "s": 31819, "text": "C++" }, { "code": null, "e": 31828, "s": 31823, "text": "Java" }, { "code": "// C++ code for k largest/ smallest elements in an array#include <bits/stdc++.h>using namespace std; // Function to find k largest array elementvoid kLargest(vector<int>& v, int N, int K){ // Implementation using // a Priority Queue priority_queue<int, vector<int>, greater<int> >pq; for (int i = 0; i < N; ++i) { // Insert elements into // the priority queue pq.push(v[i]); // If size of the priority // queue exceeds k if (pq.size() > K) { pq.pop(); } } // Print the k largest element while(!pq.empty()) { cout << pq.top() <<\" \"; pq.pop(); } cout<<endl;} // Function to find k smallest array elementvoid kSmalest(vector<int>& v, int N, int K){ // Implementation using // a Priority Queue priority_queue<int> pq; for (int i = 0; i < N; ++i) { // Insert elements into // the priority queue pq.push(v[i]); // If size of the priority // queue exceeds k if (pq.size() > K) { pq.pop(); } } // Print the k smallest element while(!pq.empty()) { cout << pq.top() <<\" \"; pq.pop(); } } // driver programint main(){ // Given array vector<int> arr = { 11, 3, 2, 1, 15, 5, 4, 45, 88, 96, 50, 45 }; // Size of array int n = arr.size(); int k = 3; cout<<k<<\" largest elements are : \"; kLargest(arr, n, k); cout<<k<<\" smallest elements are : \"; kSmalest(arr, n, k);} // This code is contributed by Pushpesh Raj.", "e": 33390, "s": 31828, "text": null }, { "code": "// Java code for k largest/ smallest elements in an arrayimport java.util.*; class GFG { // Function to find k largest array element static void kLargest(int a[], int n, int k) { // Implementation using // a Priority Queue PriorityQueue<Integer> pq = new PriorityQueue<Integer>(); for (int i = 0; i < n; ++i) { // Insert elements into // the priority queue pq.add(a[i]); // If size of the priority // queue exceeds k if (pq.size() > k) { pq.poll(); } } // Print the k largest element while (!pq.isEmpty()) { System.out.print(pq.peek() + \" \"); pq.poll(); } System.out.println(); } // Function to find k smallest array element static void kSmallest(int a[], int n, int k) { // Implementation using // a Priority Queue PriorityQueue<Integer> pq = new PriorityQueue<Integer>( Collections.reverseOrder()); for (int i = 0; i < n; ++i) { // Insert elements into // the priority queue pq.add(a[i]); // If size of the priority // queue exceeds k if (pq.size() > k) { pq.poll(); } } // Print the k largest element while (!pq.isEmpty()) { System.out.print(pq.peek() + \" \"); pq.poll(); } } // Driver Code public static void main(String[] args) { int a[] = { 11, 3, 2, 1, 15, 5, 4, 45, 88, 96, 50, 45 }; int n = a.length; int k = 3; System.out.print(k + \" largest elements are : \"); // Function Call kLargest(a, n, k); System.out.print(k + \" smallest elements are : \"); // Function Call kSmallest(a, n, k); }} // This code is contributed by Aarti_Rathi", "e": 35348, "s": 33390, "text": null }, { "code": null, "e": 35416, "s": 35348, "text": "3 largest elements are : 50 88 96 \n3 smallest elements are : 3 2 1 " }, { "code": null, "e": 35466, "s": 35416, "text": "Time Complexity: O(n*log(k))Auxiliary Space: O(k)" }, { "code": null, "e": 35659, "s": 35466, "text": "Please write comments if you find any of the above explanations/algorithms incorrect, or find better ways to solve the same problem.References: http://en.wikipedia.org/wiki/Selection_algorithm" }, { "code": null, "e": 35665, "s": 35659, "text": "ukasp" }, { "code": null, "e": 35673, "s": 35665, "text": "erikest" }, { "code": null, "e": 35683, "s": 35673, "text": "Rajput-Ji" }, { "code": null, "e": 35694, "s": 35683, "text": "Ankur Goel" }, { "code": null, "e": 35706, "s": 35694, "text": "sethivansh6" }, { "code": null, "e": 35715, "s": 35706, "text": "nirajd24" }, { "code": null, "e": 35727, "s": 35715, "text": "aashish1995" }, { "code": null, "e": 35748, "s": 35727, "text": "avanitrachhadiya2155" }, { "code": null, "e": 35760, "s": 35748, "text": "imsushant12" }, { "code": null, "e": 35769, "s": 35760, "text": "rjrachit" }, { "code": null, "e": 35778, "s": 35769, "text": "mank1083" }, { "code": null, "e": 35792, "s": 35778, "text": "shivansh20127" }, { "code": null, "e": 35800, "s": 35792, "text": "chand25" }, { "code": null, "e": 35817, "s": 35800, "text": "punamsingh628700" }, { "code": null, "e": 35831, "s": 35817, "text": "GauravRajput1" }, { "code": null, "e": 35839, "s": 35831, "text": "clintra" }, { "code": null, "e": 35849, "s": 35839, "text": "sanjoy_62" }, { "code": null, "e": 35862, "s": 35849, "text": "shinjanpatra" }, { "code": null, "e": 35871, "s": 35862, "text": "sweetyty" }, { "code": null, "e": 35887, "s": 35871, "text": "pushpeshrajdx01" }, { "code": null, "e": 35901, "s": 35887, "text": "_shinchancode" }, { "code": null, "e": 35916, "s": 35901, "text": "adityakumar129" }, { "code": null, "e": 35932, "s": 35916, "text": "mayanksingh5399" }, { "code": null, "e": 35939, "s": 35932, "text": "Amazon" }, { "code": null, "e": 35949, "s": 35939, "text": "Microsoft" }, { "code": null, "e": 35966, "s": 35949, "text": "Order-Statistics" }, { "code": null, "e": 35974, "s": 35966, "text": "Samsung" }, { "code": null, "e": 35982, "s": 35974, "text": "Walmart" }, { "code": null, "e": 35989, "s": 35982, "text": "Arrays" }, { "code": null, "e": 35994, "s": 35989, "text": "Heap" }, { "code": null, "e": 36004, "s": 35994, "text": "Searching" }, { "code": null, "e": 36012, "s": 36004, "text": "Sorting" }, { "code": null, "e": 36019, "s": 36012, "text": "Amazon" }, { "code": null, "e": 36029, "s": 36019, "text": "Microsoft" }, { "code": null, "e": 36037, "s": 36029, "text": "Samsung" }, { "code": null, "e": 36045, "s": 36037, "text": "Walmart" }, { "code": null, "e": 36052, "s": 36045, "text": "Arrays" }, { "code": null, "e": 36062, "s": 36052, "text": "Searching" }, { "code": null, "e": 36070, "s": 36062, "text": "Sorting" }, { "code": null, "e": 36075, "s": 36070, "text": "Heap" }, { "code": null, "e": 36173, "s": 36075, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 36205, "s": 36173, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 36228, "s": 36205, "text": "Introduction to Arrays" }, { "code": null, "e": 36255, "s": 36228, "text": "Subset Sum Problem | DP-25" }, { "code": null, "e": 36287, "s": 36255, "text": "Introduction to Data Structures" }, { "code": null, "e": 36332, "s": 36287, "text": "Python | Using 2D arrays/lists the right way" }, { "code": null, "e": 36341, "s": 36332, "text": "HeapSort" }, { "code": null, "e": 36353, "s": 36341, "text": "Binary Heap" }, { "code": null, "e": 36385, "s": 36353, "text": "Introduction to Data Structures" }, { "code": null, "e": 36416, "s": 36385, "text": "Huffman Coding | Greedy Algo-3" } ]
How to change size of labels in the Bokeh legend?
12 Jul, 2021 In this article, we will be learning about how to change the size of labels in bokeh legend. Legend plays a very important role in bokeh. With the help of legend, we can point to various types of glyphs in a plot that bokeh provides us, and can customize them according to our choice. Along with that, we can also change various properties of the glyphs text shown in a box in a plot. Apart from that, there are various attributes that we can use to customize a legend. Some of the attributes that can be used to customize a glyph: legend.label_text_font, legend.label_text_font_size, legend.location, legend.title, legend.orientation and, legend.clicking_policy. Now, before proceeding further, we must be sure to have bokeh installed on our local device. If not, then open a command prompt and type the following command: pip install bokeh Now we are ready to go. It is necessary to install bokeh, else the functionalities won’t work. So, let us move to the implementation of the above concept. Example 1: In the following example, we will be changing the font size of the labels using bokeh legend and along with that, we will be learning some other features too. Python3 # importing numpy package fro python libraryimport numpy as np # import figure and show for creating# and showing the plot from bokeh.plottingfrom bokeh.plotting import figure, show # Initialising a variable x with# 100 values from 0 to 20x = np.linspace(0, 20, 100) # initialising y with double values of# xy = x*2 # Creating an empty figure with plot height and# width as 600p1 = figure(plot_width=600, plot_height=600) # Creating the plot with points# in the shape of the circlep1.circle(x, y, legend_label="Line 1") # Creating the plot with points# in the shape of the squarep1.square(x, 2*y, legend_label="Line 2", color="red", line_width=4) # using legend we are labelling the title of the# Glyph boxp1.legend.title = 'Example Title' # Labelling the X-Axisp1.xaxis.axis_label = "X Axis" # Labelling the Y-Axisp1.yaxis.axis_label = "Y-Axis" # Setting up the location of the# box that differentiates the two# linesp1.legend.location = "top_left" # Increasing the title of the box# to 30ptp1.legend.title_text_font_size = '30pt' # Increasing the labels of the box# to 30ptp1.legend.label_text_font_size = "30pt" # Showing the above plotshow(p1) Output: Explanation: In the above code, after initializing all the necessary packages from the libraries and modules, we are creating two points x and y which are a list of arbitrary values. Now we will be plotting those values in our graph. So, for that, we are creating an empty figure/plot whose plot width and height are given as 600. After that, we are plotting the two graphs where points on the first graph are in the shape of a circle and the points on the second graph are in the shape of a square. Apart from the different colors of the two graphs, in order to differentiate between them, we are creating a box where we are providing the labels for both the glyphs using legend_label and we are also giving a title to that box. Now comes the main implementation i.e changing the size of the labels using bokeh legend. So, by using legend.label_text_font_size we are customizing the size of the labels and glyphs in the box, and since we have given a title to the box, legend.label_text_font_size helps us to change the size of the title. Along with changing the size, we are also changing its orientation i.e on the top-left corner using legend.location. Example 2: Now, in the second example, lets us explore some more attributes of how to change sizes using legend. In the example below, instead of using label_text_font_size, we can also use glyph_height, glyph_width, label_height, label_width which are responsible for changing the labels and the glyph sizes separately in the label box differentiating all the lines. Let us move to the main implementation now. Python3 # importing numpy as npimport numpy as np # importing figure and show from# bokeh.plottingfrom bokeh.plotting import figure, show # creating a list of numbers from 0-10x = np.arange(11) # Creating square of the numbers and# storing it in yy = x**2 # Creating an array of random values in# zz = [1, 6, 1, 4, 8, 6, 2, 6, 4, 9, 10] # Creating a plot with plot width and height# as 600p = figure(plot_height=600, plot_width=600) # Plotting first line in the form of circlep.circle(x, y, legend_label="Line 1") # Creating first line in the form of linep.line(x, y, legend_label="Line 1") # Creating fifth line in the form of linep.diamond(z, x*2, legend_label="Line 5") # Creating second line in the form of linep.hex(z, x, legend_label="Line 2", color="red") # Creating third line in the form of linep.square(x, y*2, legend_label="Line 3") # Creating forth line in the form of linep.inverted_triangle(x, y*3, legend_label="Line 4") # Increasing the glyph heightp.legend.glyph_height = 50 # increasing the glyph widthp.legend.glyph_width = 90 # Increasing the glyph's label heightp.legend.label_height = 50 # Increasing the glyph's label heightp.legend.label_width = 50 # showing the above plotshow(p) Output: Explanation: In the above code, we have imported numpy package along with the figure and show for plot creation and showing. After importing the packages, we are creating three different lists of numbers which are then plotted against each other in graphical format. They are of different shapes. Using legend in bokeh, we are labeling them differently, and using the following attributes mentioned above, we are changing the size of the glyphs and the labels separately which also affects the box size. surinderdawra388 Picked Python-Bokeh Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to iterate through Excel rows in Python? Rotate axis tick labels in Seaborn and Matplotlib Deque in Python Queue in Python Defaultdict in Python Check if element exists in list in Python Python Classes and Objects Bar Plot in Matplotlib reduce() in Python Python | Get unique values from a list
[ { "code": null, "e": 28, "s": 0, "text": "\n12 Jul, 2021" }, { "code": null, "e": 498, "s": 28, "text": "In this article, we will be learning about how to change the size of labels in bokeh legend. Legend plays a very important role in bokeh. With the help of legend, we can point to various types of glyphs in a plot that bokeh provides us, and can customize them according to our choice. Along with that, we can also change various properties of the glyphs text shown in a box in a plot. Apart from that, there are various attributes that we can use to customize a legend." }, { "code": null, "e": 692, "s": 498, "text": "Some of the attributes that can be used to customize a glyph: legend.label_text_font, legend.label_text_font_size, legend.location, legend.title, legend.orientation and, legend.clicking_policy." }, { "code": null, "e": 852, "s": 692, "text": "Now, before proceeding further, we must be sure to have bokeh installed on our local device. If not, then open a command prompt and type the following command:" }, { "code": null, "e": 871, "s": 852, "text": "pip install bokeh " }, { "code": null, "e": 1027, "s": 871, "text": "Now we are ready to go. It is necessary to install bokeh, else the functionalities won’t work. So, let us move to the implementation of the above concept. " }, { "code": null, "e": 1038, "s": 1027, "text": "Example 1:" }, { "code": null, "e": 1197, "s": 1038, "text": "In the following example, we will be changing the font size of the labels using bokeh legend and along with that, we will be learning some other features too." }, { "code": null, "e": 1205, "s": 1197, "text": "Python3" }, { "code": "# importing numpy package fro python libraryimport numpy as np # import figure and show for creating# and showing the plot from bokeh.plottingfrom bokeh.plotting import figure, show # Initialising a variable x with# 100 values from 0 to 20x = np.linspace(0, 20, 100) # initialising y with double values of# xy = x*2 # Creating an empty figure with plot height and# width as 600p1 = figure(plot_width=600, plot_height=600) # Creating the plot with points# in the shape of the circlep1.circle(x, y, legend_label=\"Line 1\") # Creating the plot with points# in the shape of the squarep1.square(x, 2*y, legend_label=\"Line 2\", color=\"red\", line_width=4) # using legend we are labelling the title of the# Glyph boxp1.legend.title = 'Example Title' # Labelling the X-Axisp1.xaxis.axis_label = \"X Axis\" # Labelling the Y-Axisp1.yaxis.axis_label = \"Y-Axis\" # Setting up the location of the# box that differentiates the two# linesp1.legend.location = \"top_left\" # Increasing the title of the box# to 30ptp1.legend.title_text_font_size = '30pt' # Increasing the labels of the box# to 30ptp1.legend.label_text_font_size = \"30pt\" # Showing the above plotshow(p1)", "e": 2363, "s": 1205, "text": null }, { "code": null, "e": 2371, "s": 2363, "text": "Output:" }, { "code": null, "e": 2384, "s": 2371, "text": "Explanation:" }, { "code": null, "e": 3528, "s": 2384, "text": "In the above code, after initializing all the necessary packages from the libraries and modules, we are creating two points x and y which are a list of arbitrary values. Now we will be plotting those values in our graph. So, for that, we are creating an empty figure/plot whose plot width and height are given as 600. After that, we are plotting the two graphs where points on the first graph are in the shape of a circle and the points on the second graph are in the shape of a square. Apart from the different colors of the two graphs, in order to differentiate between them, we are creating a box where we are providing the labels for both the glyphs using legend_label and we are also giving a title to that box. Now comes the main implementation i.e changing the size of the labels using bokeh legend. So, by using legend.label_text_font_size we are customizing the size of the labels and glyphs in the box, and since we have given a title to the box, legend.label_text_font_size helps us to change the size of the title. Along with changing the size, we are also changing its orientation i.e on the top-left corner using legend.location." }, { "code": null, "e": 3539, "s": 3528, "text": "Example 2:" }, { "code": null, "e": 3940, "s": 3539, "text": "Now, in the second example, lets us explore some more attributes of how to change sizes using legend. In the example below, instead of using label_text_font_size, we can also use glyph_height, glyph_width, label_height, label_width which are responsible for changing the labels and the glyph sizes separately in the label box differentiating all the lines. Let us move to the main implementation now." }, { "code": null, "e": 3948, "s": 3940, "text": "Python3" }, { "code": "# importing numpy as npimport numpy as np # importing figure and show from# bokeh.plottingfrom bokeh.plotting import figure, show # creating a list of numbers from 0-10x = np.arange(11) # Creating square of the numbers and# storing it in yy = x**2 # Creating an array of random values in# zz = [1, 6, 1, 4, 8, 6, 2, 6, 4, 9, 10] # Creating a plot with plot width and height# as 600p = figure(plot_height=600, plot_width=600) # Plotting first line in the form of circlep.circle(x, y, legend_label=\"Line 1\") # Creating first line in the form of linep.line(x, y, legend_label=\"Line 1\") # Creating fifth line in the form of linep.diamond(z, x*2, legend_label=\"Line 5\") # Creating second line in the form of linep.hex(z, x, legend_label=\"Line 2\", color=\"red\") # Creating third line in the form of linep.square(x, y*2, legend_label=\"Line 3\") # Creating forth line in the form of linep.inverted_triangle(x, y*3, legend_label=\"Line 4\") # Increasing the glyph heightp.legend.glyph_height = 50 # increasing the glyph widthp.legend.glyph_width = 90 # Increasing the glyph's label heightp.legend.label_height = 50 # Increasing the glyph's label heightp.legend.label_width = 50 # showing the above plotshow(p)", "e": 5145, "s": 3948, "text": null }, { "code": null, "e": 5153, "s": 5145, "text": "Output:" }, { "code": null, "e": 5166, "s": 5153, "text": "Explanation:" }, { "code": null, "e": 5658, "s": 5166, "text": "In the above code, we have imported numpy package along with the figure and show for plot creation and showing. After importing the packages, we are creating three different lists of numbers which are then plotted against each other in graphical format. They are of different shapes. Using legend in bokeh, we are labeling them differently, and using the following attributes mentioned above, we are changing the size of the glyphs and the labels separately which also affects the box size. " }, { "code": null, "e": 5675, "s": 5658, "text": "surinderdawra388" }, { "code": null, "e": 5682, "s": 5675, "text": "Picked" }, { "code": null, "e": 5695, "s": 5682, "text": "Python-Bokeh" }, { "code": null, "e": 5702, "s": 5695, "text": "Python" }, { "code": null, "e": 5800, "s": 5702, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5845, "s": 5800, "text": "How to iterate through Excel rows in Python?" }, { "code": null, "e": 5895, "s": 5845, "text": "Rotate axis tick labels in Seaborn and Matplotlib" }, { "code": null, "e": 5911, "s": 5895, "text": "Deque in Python" }, { "code": null, "e": 5927, "s": 5911, "text": "Queue in Python" }, { "code": null, "e": 5949, "s": 5927, "text": "Defaultdict in Python" }, { "code": null, "e": 5991, "s": 5949, "text": "Check if element exists in list in Python" }, { "code": null, "e": 6018, "s": 5991, "text": "Python Classes and Objects" }, { "code": null, "e": 6041, "s": 6018, "text": "Bar Plot in Matplotlib" }, { "code": null, "e": 6060, "s": 6041, "text": "reduce() in Python" } ]
Reference to Array in C++
29 Jun, 2021 Reference to an array means aliasing an array while retaining its identity. Reference to an array will not be an int* but an int[]. Let us discuss this in detail by discussing the difference between these two. This is quite weird that int[] is the same as int* but still compiler perspective on both is entirely different. The major two differences are as follows: int[] for the compiler is an array, so it provides an iterator for this (that’s why we have For-Each Loop) but int* is just a pointer to an integer. This could just be a pointer to integer or pointer to the beginning of integer array which totally depends upon our perspective. Hence, no For-Each loop in this case.For compiler, a and b are the same data type i.e int* here for compiler they are just int* pointing to address. But for compiler type of as an array is int[2] and type of b as an array is int[3] which are completely different from each other. Again just the compiler’s perspective. For better understanding let the two arrays be int a[2], int b[3]. int[] for the compiler is an array, so it provides an iterator for this (that’s why we have For-Each Loop) but int* is just a pointer to an integer. This could just be a pointer to integer or pointer to the beginning of integer array which totally depends upon our perspective. Hence, no For-Each loop in this case. For compiler, a and b are the same data type i.e int* here for compiler they are just int* pointing to address. But for compiler type of as an array is int[2] and type of b as an array is int[3] which are completely different from each other. Again just the compiler’s perspective. For better understanding let the two arrays be int a[2], int b[3]. Implementation: Passing an array to function in a classical way. Later on, trying to call for-each loop on it, a clear difference can be obtained. Example: C++ // C++ Program to demonstrate Above Approach // Importing input output stream to take input// and to display anything on the console#include <iostream> using namespace std; // Method 1// To print array elementsvoid print(int arr[], size_t n){ // Iterating over elements on an array // using the foreach loop for (int element : arr) { // Print the elements of the array cout << element << " "; } // New line as all the desired elements are printed cout << endl;} // Method 2// Main driver methodint main(){ // Declaring and initializing Integer array with // custom input entries int a[]{ 1, 2, 3, 4 }; size_t size = sizeof(a) / sizeof(a[0]); // Calling the Method1 as created above // in the main) method to // print array elements print(a, size);} Output: test.cpp: In function 'void print(int*, size_t)': test.cpp:5:21: error: 'begin' was not declared in this scope for(int element: arr){ Output Explanation: Here it is clear that int* doesn’t have any information about the underlying array but if you pass an array by reference using the template the above code will work. As reference array retains information about underlying array and its type would be int[4], not int*. Now let us discuss a reference to an array. Methods: Naive method Reference to an Array Naive method Reference to an Array Method 1: Naive method First most the common way that comes into our mind is described below syntactically. This is clearly a Naive approach as it loses its array identity. int a[] = {1, 2, 3, 4}; int *b = a; Note: int a[] = b; will not work as array can only be initialized using aggregate object Method 2: Reference to Array The size needs to be mentioned as int[x] and int[y] are different data types from the compiler’s perspective. Reference to array needs to be initialized at the time of declaration. (&name) is not redundant. It has its own meaning. Syntax: data_type (&name)[size] = array; Note: data_type &name[size] is incorrect because it means an array of reference to some datatype which is clearly meaningless. By doing so we have “name” of data type int (&) [] which is, of course, different from int[] Example: C++ // C++ Program to demonstrate Reference to an Array // Importing input output classes#include <iostream>using namespace std; // Main driver methodint main(){ // Creating and initializing an integer array // Custom input entries int a[]{ 1, 2, 3, 4 }; // int (&b)[] = a; // Declaring this way wont work as an error will be // thrown invalid initialization of reference of type // ‘int (&)[]’ from expression of type ‘int [4]’ Here // you see compiler referred to "a" as int [4] not int* int(&b)[4] = a; // Iterating over elements using foreach loop for (int e : b) { // Print the elements of the array cout << e << " "; }} 1 2 3 4 Code_Mech adnanirshad158 simranarora5sos cpp-array C++ CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n29 Jun, 2021" }, { "code": null, "e": 419, "s": 54, "text": "Reference to an array means aliasing an array while retaining its identity. Reference to an array will not be an int* but an int[]. Let us discuss this in detail by discussing the difference between these two. This is quite weird that int[] is the same as int* but still compiler perspective on both is entirely different. The major two differences are as follows:" }, { "code": null, "e": 1083, "s": 419, "text": "int[] for the compiler is an array, so it provides an iterator for this (that’s why we have For-Each Loop) but int* is just a pointer to an integer. This could just be a pointer to integer or pointer to the beginning of integer array which totally depends upon our perspective. Hence, no For-Each loop in this case.For compiler, a and b are the same data type i.e int* here for compiler they are just int* pointing to address. But for compiler type of as an array is int[2] and type of b as an array is int[3] which are completely different from each other. Again just the compiler’s perspective. For better understanding let the two arrays be int a[2], int b[3]." }, { "code": null, "e": 1399, "s": 1083, "text": "int[] for the compiler is an array, so it provides an iterator for this (that’s why we have For-Each Loop) but int* is just a pointer to an integer. This could just be a pointer to integer or pointer to the beginning of integer array which totally depends upon our perspective. Hence, no For-Each loop in this case." }, { "code": null, "e": 1748, "s": 1399, "text": "For compiler, a and b are the same data type i.e int* here for compiler they are just int* pointing to address. But for compiler type of as an array is int[2] and type of b as an array is int[3] which are completely different from each other. Again just the compiler’s perspective. For better understanding let the two arrays be int a[2], int b[3]." }, { "code": null, "e": 1765, "s": 1748, "text": "Implementation: " }, { "code": null, "e": 1814, "s": 1765, "text": "Passing an array to function in a classical way." }, { "code": null, "e": 1896, "s": 1814, "text": "Later on, trying to call for-each loop on it, a clear difference can be obtained." }, { "code": null, "e": 1905, "s": 1896, "text": "Example:" }, { "code": null, "e": 1909, "s": 1905, "text": "C++" }, { "code": "// C++ Program to demonstrate Above Approach // Importing input output stream to take input// and to display anything on the console#include <iostream> using namespace std; // Method 1// To print array elementsvoid print(int arr[], size_t n){ // Iterating over elements on an array // using the foreach loop for (int element : arr) { // Print the elements of the array cout << element << \" \"; } // New line as all the desired elements are printed cout << endl;} // Method 2// Main driver methodint main(){ // Declaring and initializing Integer array with // custom input entries int a[]{ 1, 2, 3, 4 }; size_t size = sizeof(a) / sizeof(a[0]); // Calling the Method1 as created above // in the main) method to // print array elements print(a, size);}", "e": 2718, "s": 1909, "text": null }, { "code": null, "e": 2728, "s": 2718, "text": " Output: " }, { "code": null, "e": 2866, "s": 2728, "text": "test.cpp: In function 'void print(int*, size_t)':\ntest.cpp:5:21: error: 'begin' was not declared in this scope\n for(int element: arr){" }, { "code": null, "e": 2886, "s": 2866, "text": "Output Explanation:" }, { "code": null, "e": 3155, "s": 2886, "text": "Here it is clear that int* doesn’t have any information about the underlying array but if you pass an array by reference using the template the above code will work. As reference array retains information about underlying array and its type would be int[4], not int*. " }, { "code": null, "e": 3199, "s": 3155, "text": "Now let us discuss a reference to an array." }, { "code": null, "e": 3208, "s": 3199, "text": "Methods:" }, { "code": null, "e": 3243, "s": 3208, "text": "Naive method Reference to an Array" }, { "code": null, "e": 3257, "s": 3243, "text": "Naive method " }, { "code": null, "e": 3279, "s": 3257, "text": "Reference to an Array" }, { "code": null, "e": 3302, "s": 3279, "text": "Method 1: Naive method" }, { "code": null, "e": 3452, "s": 3302, "text": "First most the common way that comes into our mind is described below syntactically. This is clearly a Naive approach as it loses its array identity." }, { "code": null, "e": 3488, "s": 3452, "text": "int a[] = {1, 2, 3, 4};\nint *b = a;" }, { "code": null, "e": 3577, "s": 3488, "text": "Note: int a[] = b; will not work as array can only be initialized using aggregate object" }, { "code": null, "e": 3607, "s": 3577, "text": "Method 2: Reference to Array " }, { "code": null, "e": 3717, "s": 3607, "text": "The size needs to be mentioned as int[x] and int[y] are different data types from the compiler’s perspective." }, { "code": null, "e": 3788, "s": 3717, "text": "Reference to array needs to be initialized at the time of declaration." }, { "code": null, "e": 3838, "s": 3788, "text": "(&name) is not redundant. It has its own meaning." }, { "code": null, "e": 3847, "s": 3838, "text": "Syntax: " }, { "code": null, "e": 3880, "s": 3847, "text": "data_type (&name)[size] = array;" }, { "code": null, "e": 4100, "s": 3880, "text": "Note: data_type &name[size] is incorrect because it means an array of reference to some datatype which is clearly meaningless. By doing so we have “name” of data type int (&) [] which is, of course, different from int[]" }, { "code": null, "e": 4110, "s": 4100, "text": "Example: " }, { "code": null, "e": 4114, "s": 4110, "text": "C++" }, { "code": "// C++ Program to demonstrate Reference to an Array // Importing input output classes#include <iostream>using namespace std; // Main driver methodint main(){ // Creating and initializing an integer array // Custom input entries int a[]{ 1, 2, 3, 4 }; // int (&b)[] = a; // Declaring this way wont work as an error will be // thrown invalid initialization of reference of type // ‘int (&)[]’ from expression of type ‘int [4]’ Here // you see compiler referred to \"a\" as int [4] not int* int(&b)[4] = a; // Iterating over elements using foreach loop for (int e : b) { // Print the elements of the array cout << e << \" \"; }}", "e": 4789, "s": 4114, "text": null }, { "code": null, "e": 4797, "s": 4789, "text": "1 2 3 4" }, { "code": null, "e": 4809, "s": 4799, "text": "Code_Mech" }, { "code": null, "e": 4824, "s": 4809, "text": "adnanirshad158" }, { "code": null, "e": 4840, "s": 4824, "text": "simranarora5sos" }, { "code": null, "e": 4850, "s": 4840, "text": "cpp-array" }, { "code": null, "e": 4854, "s": 4850, "text": "C++" }, { "code": null, "e": 4858, "s": 4854, "text": "CPP" } ]
Python program to print even length words in a string
29 May, 2022 Given a string. The task is to print all words with even length in the given string. Examples: Input: s = "This is a python language" Output: This is python language Input: s = "i am laxmi" Output: am Method: Finding even length words using for loop and if statement and without using the def function. First split the given string using the split() function and then iterate the words of a string using for loop. Calculate the length of each word using the len() function. If the length is even, then print the word. Python3 # Python code# To print even length words in string #input stringn="This is a python language"#splitting the words in a given strings=n.split(" ")for i in s: #checking the length of words if len(i)%2==0: print(i) # this code is contributed by gangarajula laxmi This is python language Approach: Split the string using split() function. Iterate in the words of a string using for loop. Calculate the length of the word using len() function. If the length is even, then print the word. Below is the Python implementation of the above approach: Python3 # Python3 program to print# even length words in a string def printWords(s): # split the string s = s.split(' ') # iterate in words of string for word in s: # if length is even if len(word)%2==0: print(word) # Driver Codes = "i am muskan"printWords(s) am muskan ankthon laxmigangarajula03 Python string-programs python-basics python-string Python Python Programs School Programming Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Convert integer to string in Python Python OOPs Concepts 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": 52, "s": 24, "text": "\n29 May, 2022" }, { "code": null, "e": 137, "s": 52, "text": "Given a string. The task is to print all words with even length in the given string." }, { "code": null, "e": 148, "s": 137, "text": "Examples: " }, { "code": null, "e": 300, "s": 148, "text": "Input: s = \"This is a python language\"\nOutput: This\n is\n python\n language\nInput: s = \"i am laxmi\"\nOutput: am" }, { "code": null, "e": 617, "s": 300, "text": "Method: Finding even length words using for loop and if statement and without using the def function. First split the given string using the split() function and then iterate the words of a string using for loop. Calculate the length of each word using the len() function. If the length is even, then print the word." }, { "code": null, "e": 625, "s": 617, "text": "Python3" }, { "code": "# Python code# To print even length words in string #input stringn=\"This is a python language\"#splitting the words in a given strings=n.split(\" \")for i in s: #checking the length of words if len(i)%2==0: print(i) # this code is contributed by gangarajula laxmi", "e": 891, "s": 625, "text": null }, { "code": null, "e": 916, "s": 891, "text": "This\nis\npython\nlanguage\n" }, { "code": null, "e": 1174, "s": 916, "text": "Approach: Split the string using split() function. Iterate in the words of a string using for loop. Calculate the length of the word using len() function. If the length is even, then print the word. Below is the Python implementation of the above approach: " }, { "code": null, "e": 1182, "s": 1174, "text": "Python3" }, { "code": "# Python3 program to print# even length words in a string def printWords(s): # split the string s = s.split(' ') # iterate in words of string for word in s: # if length is even if len(word)%2==0: print(word) # Driver Codes = \"i am muskan\"printWords(s)", "e": 1491, "s": 1182, "text": null }, { "code": null, "e": 1502, "s": 1491, "text": "am\nmuskan\n" }, { "code": null, "e": 1510, "s": 1502, "text": "ankthon" }, { "code": null, "e": 1529, "s": 1510, "text": "laxmigangarajula03" }, { "code": null, "e": 1552, "s": 1529, "text": "Python string-programs" }, { "code": null, "e": 1566, "s": 1552, "text": "python-basics" }, { "code": null, "e": 1580, "s": 1566, "text": "python-string" }, { "code": null, "e": 1587, "s": 1580, "text": "Python" }, { "code": null, "e": 1603, "s": 1587, "text": "Python Programs" }, { "code": null, "e": 1622, "s": 1603, "text": "School Programming" }, { "code": null, "e": 1720, "s": 1622, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1752, "s": 1720, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 1781, "s": 1752, "text": "*args and **kwargs in Python" }, { "code": null, "e": 1808, "s": 1781, "text": "Python Classes and Objects" }, { "code": null, "e": 1844, "s": 1808, "text": "Convert integer to string in Python" }, { "code": null, "e": 1865, "s": 1844, "text": "Python OOPs Concepts" }, { "code": null, "e": 1887, "s": 1865, "text": "Defaultdict in Python" }, { "code": null, "e": 1926, "s": 1887, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 1964, "s": 1926, "text": "Python | Convert a list to dictionary" }, { "code": null, "e": 2013, "s": 1964, "text": "Python | Convert string dictionary to dictionary" } ]
Differences and Applications of List, Tuple, Set and Dictionary in Python
30 Jan, 2022 Lists: are just like dynamic sized arrays, declared in other languages (vector in C++ and ArrayList in Java). Lists need not be homogeneous always which makes it the most powerful tool in Python. Tuple: A Tuple is a collection of Python objects separated by commas. In some ways, a tuple is similar to a list in terms of indexing, nested objects, and repetition but a tuple is immutable, unlike lists that are mutable. Set: A Set is an unordered collection data type that is iterable, mutable, and has no duplicate elements. Python’s set class represents the mathematical notion of a set. Dictionary: in Python is an ordered (since Py 3.7) [unordered (Py 3.6 & prior)] collection of data values, used to store data values like a map, which, unlike other Data Types that hold only a single value as an element, Dictionary holds key:value pair. Key-value is provided in the dictionary to make it more optimized. List, Tuple, Set, and Dictionary are the data structures in python that are used to store and organize the data in an efficient manner. Tuple can be represented by ( ) Creating an empty list l=[] Creating an empty Tuple t=() Creating a set a=set() b=set(a) Creating an empty dictionary d={} Below is the program for implementation of List, tuple, set, and dictionary: Python3 # Python3 program for explaining# use of list, tuple, set and# dictionary # Listsl = [] # Adding Element into listl.append(5)l.append(10)print("Adding 5 and 10 in list", l) # Popping Elements from listl.pop()print("Popped one element from list", l)print() # Sets = set() # Adding element into sets.add(5)s.add(10)print("Adding 5 and 10 in set", s) # Removing element from sets.remove(5)print("Removing 5 from set", s)print() # Tuplet = tuple(l) # Tuples are immutableprint("Tuple", t)print() # Dictionaryd = {} # Adding the key value paird[5] = "Five"d[10] = "Ten"print("Dictionary", d) # Removing key-value pairdel d[10]print("Dictionary", d) Adding 5 and 10 in list [5, 10] Popped one element from list [5] Adding 5 and 10 in set {10, 5} Removing 5 from set {10} Tuple (5,) Dictionary {5: 'Five', 10: 'Ten'} Dictionary {5: 'Five'} List: Used in JSON format Useful for Array operations Used in Databases Tuple: Used to insert records in the database through SQL query at a time.Ex: (1.’sravan’, 34).(2.’geek’, 35) Used in parentheses checker Set: Finding unique elements Join operations Dictionary: Used to create a data frame with lists Used in JSON surinderdawra388 w0hm0xnhdyk12cu4wsge4penk19t9nyan6aem2nc Python dictionary-programs python-list python-set python-tuple Articles Data Structures Difference Between Python Python Programs Data Structures python-list python-set Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Must Do Questions for Companies like TCS, CTS, HCL, IBM ... Const keyword in C++ Service-Oriented Architecture Advantages and Disadvantages of Linked List What's the difference between Scripting and Programming Languages? DSA Sheet by Love Babbar SDE SHEET - A Complete Guide for SDE Preparation Top 50 Array Coding Problems for Interviews Introduction to Data Structures Doubly Linked List | Set 1 (Introduction and Insertion)
[ { "code": null, "e": 52, "s": 24, "text": "\n30 Jan, 2022" }, { "code": null, "e": 248, "s": 52, "text": "Lists: are just like dynamic sized arrays, declared in other languages (vector in C++ and ArrayList in Java). Lists need not be homogeneous always which makes it the most powerful tool in Python." }, { "code": null, "e": 471, "s": 248, "text": "Tuple: A Tuple is a collection of Python objects separated by commas. In some ways, a tuple is similar to a list in terms of indexing, nested objects, and repetition but a tuple is immutable, unlike lists that are mutable." }, { "code": null, "e": 641, "s": 471, "text": "Set: A Set is an unordered collection data type that is iterable, mutable, and has no duplicate elements. Python’s set class represents the mathematical notion of a set." }, { "code": null, "e": 962, "s": 641, "text": "Dictionary: in Python is an ordered (since Py 3.7) [unordered (Py 3.6 & prior)] collection of data values, used to store data values like a map, which, unlike other Data Types that hold only a single value as an element, Dictionary holds key:value pair. Key-value is provided in the dictionary to make it more optimized." }, { "code": null, "e": 1098, "s": 962, "text": "List, Tuple, Set, and Dictionary are the data structures in python that are used to store and organize the data in an efficient manner." }, { "code": null, "e": 1128, "s": 1098, "text": "Tuple can be represented by " }, { "code": null, "e": 1132, "s": 1128, "text": "( )" }, { "code": null, "e": 1155, "s": 1132, "text": "Creating an empty list" }, { "code": null, "e": 1160, "s": 1155, "text": "l=[]" }, { "code": null, "e": 1184, "s": 1160, "text": "Creating an empty Tuple" }, { "code": null, "e": 1189, "s": 1184, "text": "t=()" }, { "code": null, "e": 1204, "s": 1189, "text": "Creating a set" }, { "code": null, "e": 1212, "s": 1204, "text": "a=set()" }, { "code": null, "e": 1221, "s": 1212, "text": "b=set(a)" }, { "code": null, "e": 1250, "s": 1221, "text": "Creating an empty dictionary" }, { "code": null, "e": 1255, "s": 1250, "text": "d={}" }, { "code": null, "e": 1332, "s": 1255, "text": "Below is the program for implementation of List, tuple, set, and dictionary:" }, { "code": null, "e": 1340, "s": 1332, "text": "Python3" }, { "code": "# Python3 program for explaining# use of list, tuple, set and# dictionary # Listsl = [] # Adding Element into listl.append(5)l.append(10)print(\"Adding 5 and 10 in list\", l) # Popping Elements from listl.pop()print(\"Popped one element from list\", l)print() # Sets = set() # Adding element into sets.add(5)s.add(10)print(\"Adding 5 and 10 in set\", s) # Removing element from sets.remove(5)print(\"Removing 5 from set\", s)print() # Tuplet = tuple(l) # Tuples are immutableprint(\"Tuple\", t)print() # Dictionaryd = {} # Adding the key value paird[5] = \"Five\"d[10] = \"Ten\"print(\"Dictionary\", d) # Removing key-value pairdel d[10]print(\"Dictionary\", d)", "e": 1984, "s": 1340, "text": null }, { "code": null, "e": 2176, "s": 1984, "text": "Adding 5 and 10 in list [5, 10]\nPopped one element from list [5]\n\nAdding 5 and 10 in set {10, 5}\nRemoving 5 from set {10}\n\nTuple (5,)\n\nDictionary {5: 'Five', 10: 'Ten'}\nDictionary {5: 'Five'}" }, { "code": null, "e": 2182, "s": 2176, "text": "List:" }, { "code": null, "e": 2202, "s": 2182, "text": "Used in JSON format" }, { "code": null, "e": 2230, "s": 2202, "text": "Useful for Array operations" }, { "code": null, "e": 2248, "s": 2230, "text": "Used in Databases" }, { "code": null, "e": 2255, "s": 2248, "text": "Tuple:" }, { "code": null, "e": 2358, "s": 2255, "text": "Used to insert records in the database through SQL query at a time.Ex: (1.’sravan’, 34).(2.’geek’, 35)" }, { "code": null, "e": 2386, "s": 2358, "text": "Used in parentheses checker" }, { "code": null, "e": 2391, "s": 2386, "text": "Set:" }, { "code": null, "e": 2415, "s": 2391, "text": "Finding unique elements" }, { "code": null, "e": 2431, "s": 2415, "text": "Join operations" }, { "code": null, "e": 2443, "s": 2431, "text": "Dictionary:" }, { "code": null, "e": 2482, "s": 2443, "text": "Used to create a data frame with lists" }, { "code": null, "e": 2495, "s": 2482, "text": "Used in JSON" }, { "code": null, "e": 2512, "s": 2495, "text": "surinderdawra388" }, { "code": null, "e": 2553, "s": 2512, "text": "w0hm0xnhdyk12cu4wsge4penk19t9nyan6aem2nc" }, { "code": null, "e": 2580, "s": 2553, "text": "Python dictionary-programs" }, { "code": null, "e": 2592, "s": 2580, "text": "python-list" }, { "code": null, "e": 2603, "s": 2592, "text": "python-set" }, { "code": null, "e": 2616, "s": 2603, "text": "python-tuple" }, { "code": null, "e": 2625, "s": 2616, "text": "Articles" }, { "code": null, "e": 2641, "s": 2625, "text": "Data Structures" }, { "code": null, "e": 2660, "s": 2641, "text": "Difference Between" }, { "code": null, "e": 2667, "s": 2660, "text": "Python" }, { "code": null, "e": 2683, "s": 2667, "text": "Python Programs" }, { "code": null, "e": 2699, "s": 2683, "text": "Data Structures" }, { "code": null, "e": 2711, "s": 2699, "text": "python-list" }, { "code": null, "e": 2722, "s": 2711, "text": "python-set" }, { "code": null, "e": 2820, "s": 2722, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2880, "s": 2820, "text": "Must Do Questions for Companies like TCS, CTS, HCL, IBM ..." }, { "code": null, "e": 2901, "s": 2880, "text": "Const keyword in C++" }, { "code": null, "e": 2931, "s": 2901, "text": "Service-Oriented Architecture" }, { "code": null, "e": 2975, "s": 2931, "text": "Advantages and Disadvantages of Linked List" }, { "code": null, "e": 3042, "s": 2975, "text": "What's the difference between Scripting and Programming Languages?" }, { "code": null, "e": 3067, "s": 3042, "text": "DSA Sheet by Love Babbar" }, { "code": null, "e": 3116, "s": 3067, "text": "SDE SHEET - A Complete Guide for SDE Preparation" }, { "code": null, "e": 3160, "s": 3116, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 3192, "s": 3160, "text": "Introduction to Data Structures" } ]
React JS useMemo Hook
27 Oct, 2020 The useMemo is a hook used in the functional component of react that returns a memoized value. In Computer Science, memoization is a concept used in general when we don’t need to recompute the function with a given argument for the next time as it returns the cached result. A memoized function remembers the results of output for a given set of inputs. For example, if there is a function to add two numbers, and we give the parameter as 1 and 2 for the first time the function will add these two numbers and return 3, but if the same inputs come again then we will return the cached value i.e 3 and not compute with the add function again. In react also, we use this concept, whenever in the React component, the state and props do not change the component and the component does not re-render, it shows the same output. The useMemo hook is used to improve performance in our React application. Syntax: const memoizedValue = useMemo(functionThatReturnsValue, arrayDepencies) Example: When we don’t use the useMemo Hook. Javascript import React, {useState} from 'react'; function App() { const [number, setNumber] = useState(0) const squaredNum = squareNum(number); const [counter, setCounter] = useState(0); // Change the state to the input const onChangeHandler = (e) => { setNumber(e.target.value); } // Increases the counter by 1 const counterHander = () => { setCounter(counter + 1); } return ( <div className="App"> <h1>Welcome to Geeksforgeeks</h1> <input type="number" placeholder="Enter a number" value={number} onChange={onChangeHandler}> </input> <div>OUTPUT: {squaredNum}</div> <button onClick= {counterHander}>Counter ++</button> <div>Counter : {counter}</div> </div> );} // function to square the valuefunction squareNum(number){ console.log("Squaring will be done!"); return Math.pow(number, 2);} export default App; Output: In the above example, we have an App component and this component is doing two things one is squaring a number on the given input and incrementing the counter. We have two states here number and counter, whenever any of the states change the component re-renders. For example, if we change the input value of the number the function squareNum runs, and if increment the counter again the function squareNum runs. We can see this on the console. In this case, we can see that even if we changed the input number once, but clicked on-increment counter multiple times our function squareNum got executed whenever we clicked the increment counter button multiple times. This is happening because the App component re-renders whenever we change the state of the counter. Now let’s solve this problem using the useMemo hook. Example: When we use useMemo Hook Javascript import React, {useState} from 'react'; function App() { const [number, setNumber] = useState(0) // Using useMemo const squaredNum = useMemo(()=> { return squareNum(number); }, [number]) const [counter, setCounter] = useState(0); // Change the state to the input const onChangeHandler = (e) => { setNumber(e.target.value); } // Increases the counter by 1 const counterHander = () => { setCounter(counter + 1); } return ( <div className="App"> <h1>Welcome to Geeksforgeeks</h1> <input type="number" placeholder="Enter a number" value={number} onChange={onChangeHandler}> </input> <div>OUTPUT: {squaredNum}</div> <button onClick= {counterHander}>Counter ++</button> <div>Counter : {counter}</div> </div> );} // function to square the valuefunction squareNum(number){ console.log("Squaring will be done!"); return Math.pow(number, 2);} export default App; Output: Now in the above example, we have used the user memo hook, here the function that returns the value i.e squareNum is passed inside the useMemo and inside the array dependencies, we have used the number as the squareNum will run only when the number changes. If we increase the counter and the number remains the same in the input field the squareNum doesn’t run again. Let’s see the output below. Now we can see in the console that the squareNum is running only when there is a change in the input box and not when the button of the increment counter is clicked. Note: Memorization is never free, we are trading space for time. react-js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between var, let and const keywords in JavaScript How to fetch data from an API in ReactJS ? Differences between Functional Components and Class Components in React Remove elements from a JavaScript Array REST API (Introduction) Difference Between PUT and PATCH Request Roadmap to Learn JavaScript For Beginners How to float three div side by side using CSS? ReactJS | Router How to get character array from string in JavaScript?
[ { "code": null, "e": 54, "s": 26, "text": "\n27 Oct, 2020" }, { "code": null, "e": 951, "s": 54, "text": "The useMemo is a hook used in the functional component of react that returns a memoized value. In Computer Science, memoization is a concept used in general when we don’t need to recompute the function with a given argument for the next time as it returns the cached result. A memoized function remembers the results of output for a given set of inputs. For example, if there is a function to add two numbers, and we give the parameter as 1 and 2 for the first time the function will add these two numbers and return 3, but if the same inputs come again then we will return the cached value i.e 3 and not compute with the add function again. In react also, we use this concept, whenever in the React component, the state and props do not change the component and the component does not re-render, it shows the same output. The useMemo hook is used to improve performance in our React application." }, { "code": null, "e": 959, "s": 951, "text": "Syntax:" }, { "code": null, "e": 1068, "s": 959, "text": "const memoizedValue = useMemo(functionThatReturnsValue, \n arrayDepencies)\n" }, { "code": null, "e": 1113, "s": 1068, "text": "Example: When we don’t use the useMemo Hook." }, { "code": null, "e": 1124, "s": 1113, "text": "Javascript" }, { "code": "import React, {useState} from 'react'; function App() { const [number, setNumber] = useState(0) const squaredNum = squareNum(number); const [counter, setCounter] = useState(0); // Change the state to the input const onChangeHandler = (e) => { setNumber(e.target.value); } // Increases the counter by 1 const counterHander = () => { setCounter(counter + 1); } return ( <div className=\"App\"> <h1>Welcome to Geeksforgeeks</h1> <input type=\"number\" placeholder=\"Enter a number\" value={number} onChange={onChangeHandler}> </input> <div>OUTPUT: {squaredNum}</div> <button onClick= {counterHander}>Counter ++</button> <div>Counter : {counter}</div> </div> );} // function to square the valuefunction squareNum(number){ console.log(\"Squaring will be done!\"); return Math.pow(number, 2);} export default App;", "e": 2004, "s": 1124, "text": null }, { "code": null, "e": 2458, "s": 2004, "text": "Output: In the above example, we have an App component and this component is doing two things one is squaring a number on the given input and incrementing the counter. We have two states here number and counter, whenever any of the states change the component re-renders. For example, if we change the input value of the number the function squareNum runs, and if increment the counter again the function squareNum runs. We can see this on the console. " }, { "code": null, "e": 2779, "s": 2458, "text": "In this case, we can see that even if we changed the input number once, but clicked on-increment counter multiple times our function squareNum got executed whenever we clicked the increment counter button multiple times. This is happening because the App component re-renders whenever we change the state of the counter." }, { "code": null, "e": 2832, "s": 2779, "text": "Now let’s solve this problem using the useMemo hook." }, { "code": null, "e": 2866, "s": 2832, "text": "Example: When we use useMemo Hook" }, { "code": null, "e": 2877, "s": 2866, "text": "Javascript" }, { "code": "import React, {useState} from 'react'; function App() { const [number, setNumber] = useState(0) // Using useMemo const squaredNum = useMemo(()=> { return squareNum(number); }, [number]) const [counter, setCounter] = useState(0); // Change the state to the input const onChangeHandler = (e) => { setNumber(e.target.value); } // Increases the counter by 1 const counterHander = () => { setCounter(counter + 1); } return ( <div className=\"App\"> <h1>Welcome to Geeksforgeeks</h1> <input type=\"number\" placeholder=\"Enter a number\" value={number} onChange={onChangeHandler}> </input> <div>OUTPUT: {squaredNum}</div> <button onClick= {counterHander}>Counter ++</button> <div>Counter : {counter}</div> </div> );} // function to square the valuefunction squareNum(number){ console.log(\"Squaring will be done!\"); return Math.pow(number, 2);} export default App;", "e": 3814, "s": 2877, "text": null }, { "code": null, "e": 4219, "s": 3814, "text": "Output: Now in the above example, we have used the user memo hook, here the function that returns the value i.e squareNum is passed inside the useMemo and inside the array dependencies, we have used the number as the squareNum will run only when the number changes. If we increase the counter and the number remains the same in the input field the squareNum doesn’t run again. Let’s see the output below." }, { "code": null, "e": 4385, "s": 4219, "text": "Now we can see in the console that the squareNum is running only when there is a change in the input box and not when the button of the increment counter is clicked." }, { "code": null, "e": 4451, "s": 4385, "text": "Note: Memorization is never free, we are trading space for time. " }, { "code": null, "e": 4460, "s": 4451, "text": "react-js" }, { "code": null, "e": 4477, "s": 4460, "text": "Web Technologies" }, { "code": null, "e": 4575, "s": 4477, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4636, "s": 4575, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 4679, "s": 4636, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 4751, "s": 4679, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 4791, "s": 4751, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 4815, "s": 4791, "text": "REST API (Introduction)" }, { "code": null, "e": 4856, "s": 4815, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 4898, "s": 4856, "text": "Roadmap to Learn JavaScript For Beginners" }, { "code": null, "e": 4945, "s": 4898, "text": "How to float three div side by side using CSS?" }, { "code": null, "e": 4962, "s": 4945, "text": "ReactJS | Router" } ]
Check if two given circles touch or intersect each other
22 Jun, 2022 There are two circle A and B with their centres C1(x1, y1) and C2(x2, y2) and radius R1 and R2. Task is to check both circles A and B touch each other or not. Examples : Input : C1 = (3, 4) C2 = (14, 18) R1 = 5, R2 = 8 Output : Circles do not touch each other. Input : C1 = (2, 3) C2 = (15, 28) R1 = 12, R2 = 10 Output : Circles intersect with each other. Input : C1 = (-10, 8) C2 = (14, -24) R1 = 30, R2 = 10 Input : -10 8 14 -24 30 10 Output : Circle touch each other. Approach: Distance between centres C1 and C2 is calculated as C1C2 = sqrt((x1 – x2)2 + (y1 – y2)2). There are three condition arises. If C1C2 == R1 + R2: Circle A and B are touch to each other.If C1C2 > R1 + R2: Circle A and B are not touch to each other.If C1C2 < R1 + R2: Circle intersects each other. If C1C2 == R1 + R2: Circle A and B are touch to each other. If C1C2 > R1 + R2: Circle A and B are not touch to each other. If C1C2 < R1 + R2: Circle intersects each other. Below is the implementation of the above approach: C++ Java Python3 C# PHP Javascript // C++ program to check if two// circles touch each other or not.#include <bits/stdc++.h>using namespace std; int circle(int x1, int y1, int x2, int y2, int r1, int r2){ int distSq = (x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2); int radSumSq = (r1 + r2) * (r1 + r2); if (distSq == radSumSq) return 1; else if (distSq > radSumSq) return -1; else return 0;} // Driver codeint main(){ int x1 = -10, y1 = 8; int x2 = 14, y2 = -24; int r1 = 30, r2 = 10; int t = circle(x1, y1, x2, y2, r1, r2); if (t == 1) cout << "Circle touch to" << " each other."; else if (t < 0) cout << "Circle not touch" << " to each other."; else cout << "Circle intersect" << " to each other."; return 0;} // Java program to check if two// circles touch each other or not.import java.io.*; class GFG{ static int circle(int x1, int y1, int x2, int y2, int r1, int r2) { int distSq = (x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2); int radSumSq = (r1 + r2) * (r1 + r2); if (distSq == radSumSq) return 1; else if (distSq > radSumSq) return -1; else return 0; } // Driver code public static void main (String[] args) { int x1 = -10, y1 = 8; int x2 = 14, y2 = -24; int r1 = 30, r2 = 10; int t = circle(x1, y1, x2, y2, r1, r2); if (t == 1) System.out.println ( "Circle touch to" + " each other."); else if (t < 0) System.out.println ( "Circle not touch" + " to each other."); else System.out.println ( "Circle intersect" + " to each other."); }} // This article is contributed by vt_m. # Python3 program to# check if two circles touch# each other or not. def circle(x1, y1, x2, y2, r1, r2): distSq = (x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2); radSumSq = (r1 + r2) * (r1 + r2); if (distSq == radSumSq): return 1 else if (distSq > radSumSq): return -1 else: return 0 # Driver codex1 = -10y1 = 8x2 = 14y2 = -24r1 = 30r2 = 10 t = circle(x1, y1, x2, y2, r1, r2)if (t == 1): print("Circle touch to each other.")else if (t < 0): print("Circle not touch to each other.")else: print("Circle intersect to each other.") # This code is contributed by# Smitha Dinesh Semwal // C# program to check if two// circles touch each other or not.using System; class GFG{ static int circle(int x1, int y1, int x2, int y2, int r1, int r2) { int distSq = (x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2); int radSumSq = (r1 + r2) * (r1 + r2); if (distSq == radSumSq) return 1; else if (distSq > radSumSq) return -1; else return 0; } // Driver code public static void Main () { int x1 = -10, y1 = 8; int x2 = 14, y2 = -24; int r1 = 30, r2 = 10; int t = circle(x1, y1, x2, y2, r1, r2); if (t == 1) Console.WriteLine ( "Circle touch" + " to each other."); else if (t < 0) Console.WriteLine( "Circle not touch" + " to each other."); else Console.WriteLine ( "Circle intersect" + " to each other."); }} // This code is contributed by vt_m. <?php// PHP program to check if two// circles touch each other or not. function circle($x1, $y1, $x2, $y2, $r1, $r2){ $distSq = ($x1 - $x2) * ($x1 - $x2) + ($y1 - $y2) * ($y1 - $y2); $radSumSq = ($r1 + $r2) * ($r1 + $r2); if ($distSq == $radSumSq) return 1; else if ($distSq > $radSumSq) return -1; else return 0;} // Driver code$x1 = -10; $y1 = 8;$x2 = 14; $y2 = -24;$r1 = 30; $r2 = 10;$t = circle($x1, $y1, $x2, $y2, $r1, $r2);if ($t == 1) echo "Circle touch to each other.";else if ($t < 0) echo "Circle not touch to each other.";else echo "Circle intersect to each other."; // This code is contributed by vt_m.?> <script> // JavaScript program to check if two// circles touch each other or not. function circle(x1, y1, x2, y2, r1, r2) { let distSq = (x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2); let radSumSq = (r1 + r2) * (r1 + r2); if (distSq == radSumSq) return 1; else if (distSq > radSumSq) return -1; else return 0; } // Driver Code let x1 = -10, y1 = 8; let x2 = 14, y2 = -24; let r1 = 30, r2 = 10; let t = circle(x1, y1, x2, y2, r1, r2); if (t == 1) document.write ( "Circle touch to" + " each other."); else if (t < 0) document.write( "Circle not touch" + " to each other."); else document.write ( "Circle intersect" + " to each other."); // This code is contributed by susmitakundugoaldanga.</script> Circle touch to each other. Time Complexity: O(1) Auxiliary Space: O(1) This article is contributed by Aarti_Rathi and Dharmendra kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. 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 susmitakundugoaldanga ysachin2314 simranarora5sos simmytarika5 RishabhPrabhu adi1212 circle Geometric Mathematical Misc Misc Mathematical Misc Geometric Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Program for distance between two points on earth Find if two rectangles overlap Check whether triangle is valid or not if sides are given Line Clipping | Set 1 (Cohen–Sutherland Algorithm) Program for Point of Intersection of Two Lines 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": 52, "s": 24, "text": "\n22 Jun, 2022" }, { "code": null, "e": 211, "s": 52, "text": "There are two circle A and B with their centres C1(x1, y1) and C2(x2, y2) and radius R1 and R2. Task is to check both circles A and B touch each other or not." }, { "code": null, "e": 224, "s": 211, "text": "Examples : " }, { "code": null, "e": 595, "s": 224, "text": "Input : C1 = (3, 4)\n C2 = (14, 18)\n R1 = 5, R2 = 8\nOutput : Circles do not touch each other.\n\nInput : C1 = (2, 3)\n C2 = (15, 28)\n R1 = 12, R2 = 10\nOutput : Circles intersect with each other.\n\nInput : C1 = (-10, 8)\n C2 = (14, -24)\n R1 = 30, R2 = 10\nInput : -10 8\n 14 -24 \n 30 10\nOutput : Circle touch each other." }, { "code": null, "e": 606, "s": 595, "text": "Approach: " }, { "code": null, "e": 658, "s": 606, "text": "Distance between centres C1 and C2 is calculated as" }, { "code": null, "e": 697, "s": 658, "text": " C1C2 = sqrt((x1 – x2)2 + (y1 – y2)2)." }, { "code": null, "e": 731, "s": 697, "text": "There are three condition arises." }, { "code": null, "e": 901, "s": 731, "text": "If C1C2 == R1 + R2: Circle A and B are touch to each other.If C1C2 > R1 + R2: Circle A and B are not touch to each other.If C1C2 < R1 + R2: Circle intersects each other." }, { "code": null, "e": 961, "s": 901, "text": "If C1C2 == R1 + R2: Circle A and B are touch to each other." }, { "code": null, "e": 1024, "s": 961, "text": "If C1C2 > R1 + R2: Circle A and B are not touch to each other." }, { "code": null, "e": 1073, "s": 1024, "text": "If C1C2 < R1 + R2: Circle intersects each other." }, { "code": null, "e": 1125, "s": 1073, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 1129, "s": 1125, "text": "C++" }, { "code": null, "e": 1134, "s": 1129, "text": "Java" }, { "code": null, "e": 1142, "s": 1134, "text": "Python3" }, { "code": null, "e": 1145, "s": 1142, "text": "C#" }, { "code": null, "e": 1149, "s": 1145, "text": "PHP" }, { "code": null, "e": 1160, "s": 1149, "text": "Javascript" }, { "code": "// C++ program to check if two// circles touch each other or not.#include <bits/stdc++.h>using namespace std; int circle(int x1, int y1, int x2, int y2, int r1, int r2){ int distSq = (x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2); int radSumSq = (r1 + r2) * (r1 + r2); if (distSq == radSumSq) return 1; else if (distSq > radSumSq) return -1; else return 0;} // Driver codeint main(){ int x1 = -10, y1 = 8; int x2 = 14, y2 = -24; int r1 = 30, r2 = 10; int t = circle(x1, y1, x2, y2, r1, r2); if (t == 1) cout << \"Circle touch to\" << \" each other.\"; else if (t < 0) cout << \"Circle not touch\" << \" to each other.\"; else cout << \"Circle intersect\" << \" to each other.\"; return 0;}", "e": 1998, "s": 1160, "text": null }, { "code": "// Java program to check if two// circles touch each other or not.import java.io.*; class GFG{ static int circle(int x1, int y1, int x2, int y2, int r1, int r2) { int distSq = (x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2); int radSumSq = (r1 + r2) * (r1 + r2); if (distSq == radSumSq) return 1; else if (distSq > radSumSq) return -1; else return 0; } // Driver code public static void main (String[] args) { int x1 = -10, y1 = 8; int x2 = 14, y2 = -24; int r1 = 30, r2 = 10; int t = circle(x1, y1, x2, y2, r1, r2); if (t == 1) System.out.println ( \"Circle touch to\" + \" each other.\"); else if (t < 0) System.out.println ( \"Circle not touch\" + \" to each other.\"); else System.out.println ( \"Circle intersect\" + \" to each other.\"); }} // This article is contributed by vt_m.", "e": 3115, "s": 1998, "text": null }, { "code": "# Python3 program to# check if two circles touch# each other or not. def circle(x1, y1, x2, y2, r1, r2): distSq = (x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2); radSumSq = (r1 + r2) * (r1 + r2); if (distSq == radSumSq): return 1 else if (distSq > radSumSq): return -1 else: return 0 # Driver codex1 = -10y1 = 8x2 = 14y2 = -24r1 = 30r2 = 10 t = circle(x1, y1, x2, y2, r1, r2)if (t == 1): print(\"Circle touch to each other.\")else if (t < 0): print(\"Circle not touch to each other.\")else: print(\"Circle intersect to each other.\") # This code is contributed by# Smitha Dinesh Semwal", "e": 3743, "s": 3115, "text": null }, { "code": "// C# program to check if two// circles touch each other or not.using System; class GFG{ static int circle(int x1, int y1, int x2, int y2, int r1, int r2) { int distSq = (x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2); int radSumSq = (r1 + r2) * (r1 + r2); if (distSq == radSumSq) return 1; else if (distSq > radSumSq) return -1; else return 0; } // Driver code public static void Main () { int x1 = -10, y1 = 8; int x2 = 14, y2 = -24; int r1 = 30, r2 = 10; int t = circle(x1, y1, x2, y2, r1, r2); if (t == 1) Console.WriteLine ( \"Circle touch\" + \" to each other.\"); else if (t < 0) Console.WriteLine( \"Circle not touch\" + \" to each other.\"); else Console.WriteLine ( \"Circle intersect\" + \" to each other.\"); }} // This code is contributed by vt_m.", "e": 4829, "s": 3743, "text": null }, { "code": "<?php// PHP program to check if two// circles touch each other or not. function circle($x1, $y1, $x2, $y2, $r1, $r2){ $distSq = ($x1 - $x2) * ($x1 - $x2) + ($y1 - $y2) * ($y1 - $y2); $radSumSq = ($r1 + $r2) * ($r1 + $r2); if ($distSq == $radSumSq) return 1; else if ($distSq > $radSumSq) return -1; else return 0;} // Driver code$x1 = -10; $y1 = 8;$x2 = 14; $y2 = -24;$r1 = 30; $r2 = 10;$t = circle($x1, $y1, $x2, $y2, $r1, $r2);if ($t == 1) echo \"Circle touch to each other.\";else if ($t < 0) echo \"Circle not touch to each other.\";else echo \"Circle intersect to each other.\"; // This code is contributed by vt_m.?>", "e": 5530, "s": 4829, "text": null }, { "code": "<script> // JavaScript program to check if two// circles touch each other or not. function circle(x1, y1, x2, y2, r1, r2) { let distSq = (x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2); let radSumSq = (r1 + r2) * (r1 + r2); if (distSq == radSumSq) return 1; else if (distSq > radSumSq) return -1; else return 0; } // Driver Code let x1 = -10, y1 = 8; let x2 = 14, y2 = -24; let r1 = 30, r2 = 10; let t = circle(x1, y1, x2, y2, r1, r2); if (t == 1) document.write ( \"Circle touch to\" + \" each other.\"); else if (t < 0) document.write( \"Circle not touch\" + \" to each other.\"); else document.write ( \"Circle intersect\" + \" to each other.\"); // This code is contributed by susmitakundugoaldanga.</script>", "e": 6546, "s": 5530, "text": null }, { "code": null, "e": 6574, "s": 6546, "text": "Circle touch to each other." }, { "code": null, "e": 6618, "s": 6574, "text": "Time Complexity: O(1) Auxiliary Space: O(1)" }, { "code": null, "e": 7059, "s": 6618, "text": "This article is contributed by Aarti_Rathi and Dharmendra kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. 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": 7064, "s": 7059, "text": "vt_m" }, { "code": null, "e": 7086, "s": 7064, "text": "susmitakundugoaldanga" }, { "code": null, "e": 7098, "s": 7086, "text": "ysachin2314" }, { "code": null, "e": 7114, "s": 7098, "text": "simranarora5sos" }, { "code": null, "e": 7127, "s": 7114, "text": "simmytarika5" }, { "code": null, "e": 7141, "s": 7127, "text": "RishabhPrabhu" }, { "code": null, "e": 7149, "s": 7141, "text": "adi1212" }, { "code": null, "e": 7156, "s": 7149, "text": "circle" }, { "code": null, "e": 7166, "s": 7156, "text": "Geometric" }, { "code": null, "e": 7179, "s": 7166, "text": "Mathematical" }, { "code": null, "e": 7184, "s": 7179, "text": "Misc" }, { "code": null, "e": 7189, "s": 7184, "text": "Misc" }, { "code": null, "e": 7202, "s": 7189, "text": "Mathematical" }, { "code": null, "e": 7207, "s": 7202, "text": "Misc" }, { "code": null, "e": 7217, "s": 7207, "text": "Geometric" }, { "code": null, "e": 7315, "s": 7217, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 7364, "s": 7315, "text": "Program for distance between two points on earth" }, { "code": null, "e": 7395, "s": 7364, "text": "Find if two rectangles overlap" }, { "code": null, "e": 7453, "s": 7395, "text": "Check whether triangle is valid or not if sides are given" }, { "code": null, "e": 7504, "s": 7453, "text": "Line Clipping | Set 1 (Cohen–Sutherland Algorithm)" }, { "code": null, "e": 7551, "s": 7504, "text": "Program for Point of Intersection of Two Lines" }, { "code": null, "e": 7581, "s": 7551, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 7624, "s": 7581, "text": "Set in C++ Standard Template Library (STL)" }, { "code": null, "e": 7684, "s": 7624, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 7699, "s": 7684, "text": "C++ Data Types" } ]
Count subsequences in first string which are anagrams of the second string
06 Jul, 2022 Given two strings str1 and str2 of length n1 and n2 respectively. The problem is to count all the subsequences of str1 which are anagrams of str2. Examples: Input : str1 = "abacd", str2 = "abc" Output : 2 Index of characters in the 2 subsequences are: {0, 1, 3} = {a, b, c} = abc and {1, 2, 3} = {b, a, c} = bac The above two subsequences of str1 are anagrams of str2. Input : str1 = "geeksforgeeks", str2 = "geeks" Output : 48 Approach: Create two arrays freq1[] and freq2[] each of size ’26’ implemented as hash tables to store the frequencies of each character of str1 and str2 respectively. Let n1 and n2 be the lengths of str1 and str2 respectively. Now implement the following algorithm: countSubsequences(str1, str2) for i = 0 to n1-1 freq1[str1[i] - 'a']++ for i = 0 n2-1 freq2[str2[i] - 'a']++ Initialize count = 1 for i = 0 to 25 if freq2[i] != 0 then if freq2[i] <= freq1[i] then count = count * binomialCoeff(freq1[i], freq2[i]) else return 0 return count Let freq1[i] is represented as n and freq2[i] as r. Now, binomialCoeff(n, r) mentioned in the algorithm above is nothing but binomial coefficient nCr .Refer this post for its implementation.Explanation: Let frequency of some character say ch in ‘str2’ is ‘x’ and in ‘str1’ is ‘y’. If y < x, then no subsequence of ‘str1’ exists which could be an anagram of ‘str2’. Otherwise, yCx gives the number of occurrences of ch selected which will contribute to the total count of required subsequences. C++ Java Python C# PHP Javascript // C++ implementation to// count subsequences in// first string which are // anagrams of the second// string#include <bits/stdc++.h>using namespace std; #define SIZE 26 // Returns value of Binomial// Coefficient C(n, k)int binomialCoeff(int n, int k){ int res = 1; // Since C(n, k) = C(n, n-k) if (k > n - k) k = n - k; // Calculate value of // [n * (n-1) *---* (n-k+1)] / // [k * (k-1) *----* 1] for (int i = 0; i < k; ++i) { res *= (n - i); res /= (i + 1); } return res;} // function to count subsequences// in first string which are// anagrams of the second stringint countSubsequences(string str1, string str2){ // hash tables to store frequencies // of each character int freq1[SIZE], freq2[SIZE]; int n1 = str1.size(); int n2 = str2.size(); // Initialize memset(freq1, 0, sizeof(freq1)); memset(freq2, 0, sizeof(freq2)); // store frequency of each // character of 'str1' for (int i = 0; i < n1; i++) freq1[str1[i] - 'a']++; // store frequency of each // character of 'str2' for (int i = 0; i < n2; i++) freq2[str2[i] - 'a']++; // to store the total count // of subsequences int count = 1; for (int i = 0; i < SIZE; i++) // if character (i + 'a') // exists in 'str2' if (freq2[i] != 0) { // if this character's frequency // in 'str2' in less than or // equal to its frequency in // 'str1' then accumulate its // contribution to the count // of subsequences. If its // frequency in 'str1' is 'n' // and in 'str2' is 'r', then // its contribution will be nCr, // where C is the binomial // coefficient. if (freq2[i] <= freq1[i]) count = count * binomialCoeff(freq1[i], freq2[i]); // else return 0 as there could // be no subsequence which is an // anagram of 'str2' else return 0; } // required count of subsequences return count;} // Driver program to test aboveint main(){ string str1 = "abacd"; string str2 = "abc"; cout << "Count = " << countSubsequences(str1, str2); return 0;} // Java implementation to// count subsequences in// first string which are// anagrams of the second// stringimport java.util.*;import java.lang.*; public class GfG{ public final static int SIZE = 26; // Returns value of Binomial // Coefficient C(n, k) public static int binomialCoeff(int n, int k) { int res = 1; // Since C(n, k) = C(n, n-k) if (k > n - k) k = n - k; // Calculate value of // [n * (n-1) *---* (n-k+1)] / // [k * (k-1) *----* 1] for (int i = 0; i < k; ++i) { res *= (n - i); res /= (i + 1); } return res; } // function to count subsequences // in first string which are // anagrams of the second string public static int countSubsequences(String str, String str3) { // hash tables to store frequencies // of each character int[] freq1 = new int [SIZE]; int[] freq2 = new int [SIZE]; char[] str1 = str.toCharArray(); char[] str2 = str3.toCharArray(); int n1 = str.length(); int n2 = str3.length(); // store frequency of each // character of 'str1' for (int i = 0; i < n1; i++) freq1[str1[i] - 'a']++; // store frequency of each // character of 'str2' for (int i = 0; i < n2; i++) freq2[str2[i] - 'a']++; // to store the total count // of subsequences int count = 1; for (int i = 0; i < SIZE; i++) // if character (i + 'a') // exists in 'str2' if (freq2[i] != 0) { // if this character's frequency // in 'str2' in less than or // equal to its frequency in // 'str1' then accumulate its // contribution to the count // of subsequences. If its // frequency in 'str1' is 'n' // and in 'str2' is 'r', then // its contribution will be nCr, // where C is the binomial // coefficient. if (freq2[i] <= freq1[i]) count = count * binomialCoeff(freq1[i], freq2[i]); // else return 0 as there could // be no subsequence which is an // anagram of 'str2' else return 0; } // required count of subsequences return count; } // Driver function public static void main(String argc[]) { String str1 = "abacd"; String str2 = "abc"; System.out.println("Count = " + countSubsequences(str1, str2)); }} /* This code is contributed by Sagar Shukla */ # Python3 implementation to count# subsequences in first which are# anagrams of the second # import libraryimport numpy as np SIZE = 26 # Returns value of Binomial# Coefficient C(n, k)def binomialCoeff(n, k): res = 1 # Since C(n, k) = C(n, n-k) if (k > n - k): k = n - k # Calculate value of # [n * (n-1) *---* (n-k+1)] / # [k * (k-1) *----* 1] for i in range(0, k): res = res * (n - i) res = int(res / (i + 1)) return res # Function to count subsequences# in first which are anagrams# of the seconddef countSubsequences(str1, str2): # Hash tables to store frequencies # of each character freq1 = np.zeros(26, dtype = np.int) freq2 = np.zeros(26, dtype = np.int) n1 = len(str1) n2 = len(str2) # Store frequency of each # character of 'str1' for i in range(0, n1): freq1[ord(str1[i]) - ord('a') ] += 1 # Store frequency of each # character of 'str2' for i in range(0, n2): freq2[ord(str2[i]) - ord('a')] += 1 # To store the total count # of subsequences count = 1 for i in range(0, SIZE): # if character (i + 'a') # exists in 'str2' if (freq2[i] != 0): # if this character's frequency # in 'str2' in less than or # equal to its frequency in # 'str1' then accumulate its # contribution to the count # of subsequences. If its # frequency in 'str1' is 'n' # and in 'str2' is 'r', then # its contribution will be nCr, # where C is the binomial # coefficient. if (freq2[i] <= freq1[i]): count = count * binomialCoeff(freq1[i], freq2[i]) # else return 0 as there could # be no subsequence which is an # anagram of 'str2' else: return 0 # required count of subsequences return count # Driver codestr1 = "abacd"str2 = "abc"ans = countSubsequences(str1, str2)print ("Count = ", ans) # This code contributed by saloni1297 // C# implementation to// count subsequences in// first string which are// anagrams of the second// stringusing System; class GfG { public static int SIZE = 26; // Returns value of Binomial // Coefficient C(n, k) public static int binomialCoeff(int n, int k) { int res = 1; // Since C(n, k) = C(n, n-k) if (k > n - k) k = n - k; // Calculate value of // [n * (n-1) *---* (n-k+1)] / // [k * (k-1) *----* 1] for (int i = 0; i < k; ++i) { res *= (n - i); res /= (i + 1); } return res; } // function to count subsequences // in first string which are // anagrams of the second string public static int countSubsequences(String str, String str3) { // hash tables to store frequencies // of each character int[] freq1 = new int [SIZE]; int[] freq2 = new int [SIZE]; char[] str1 = str.ToCharArray(); char[] str2 = str3.ToCharArray(); int n1 = str.Length; int n2 = str3.Length; // store frequency of each // character of 'str1' for (int i = 0; i < n1; i++) freq1[str1[i] - 'a']++; // store frequency of each // character of 'str2' for (int i = 0; i < n2; i++) freq2[str2[i] - 'a']++; // to store the total count // of subsequences int count = 1; for (int i = 0; i < SIZE; i++) // if character (i + 'a') // exists in 'str2' if (freq2[i] != 0) { // if this character's frequency // in 'str2' in less than or // equal to its frequency in // 'str1' then accumulate its // contribution to the count // of subsequences. If its // frequency in 'str1' is 'n' // and in 'str2' is 'r', then // its contribution will be nCr, // where C is the binomial // coefficient. if (freq2[i] <= freq1[i]) count = count * binomialCoeff(freq1[i], freq2[i]); // else return 0 as there could // be no subsequence which is an // anagram of 'str2' else return 0; } // required count of subsequences return count; } // Driver code public static void Main(String[] argc) { String str1 = "abacd"; String str2 = "abc"; Console.Write("Count = " + countSubsequences(str1, str2)); }} // This code is contributed by parashar <?php// PHP implementation to// count subsequences in// first $which are// anagrams of the second// string$SIZE = 26; // Returns value of Binomial// Coefficient C(n, k)function binomialCoeff($n, $k){ $res = 1; // Since C(n, k) = C(n, n-k) if ($k > $n - $k) $k = $n - $k; // Calculate value of // [n * (n-1) *---* (n-k+1)] / // [k * (k-1) *----* 1] for ($i = 0; $i < $k; ++$i) { $res *= ($n - $i); $res /= ($i + 1); } return $res;} // function to count// subsequences in// first string which// are anagrams of the// second stringfunction countSubsequences($str1, $str2){ global $SIZE; // hash tables to // store frequencies // of each character $freq1 = array(); $freq2 = array(); // Initialize for ($i = 0; $i < $SIZE; $i++) { $freq1[$i] = 0; $freq2[$i] = 0; } $n1 = strlen($str1); $n2 = strlen($str2); // store frequency of each // character of 'str1' for ($i = 0; $i < $n1; $i++) $freq1[ord($str1[$i]) - ord('a')]++; // store frequency of each // character of 'str2' for ($i = 0; $i < $n2; $i++) $freq2[ord($str2[$i]) - ord('a')]++; // to store the total count // of subsequences $count = 1; for ($i = 0; $i < $SIZE; $i++) // if character (i + 'a') // exists in 'str2' if ($freq2[$i] != 0) { // if this character's frequency // in 'str2' in less than or // equal to its frequency in // 'str1' then accumulate its // contribution to the count // of subsequences. If its // frequency in 'str1' is 'n' // and in 'str2' is 'r', then // its contribution will be nCr, // where C is the binomial // coefficient. if ($freq2[$i] <= $freq1[$i]) $count = $count * binomialCoeff($freq1[$i], $freq2[$i]); // else return 0 as there // could be no subsequence // which is an anagram of // 'str2' else return 0; } // required count // of subsequences return $count;} // Driver Code$str1 = "abacd";$str2 = "abc";echo ("Count = ". countSubsequences($str1, $str2)); // This code is contributed by// Manish Shaw(manishshaw1)?> <script> // JavaScript implementation to// count subsequences in// first string which are // anagrams of the second// string var SIZE = 26 // Returns value of Binomial// Coefficient C(n, k)function binomialCoeff(n, k){ var res = 1; // Since C(n, k) = C(n, n-k) if (k > n - k) k = n - k; // Calculate value of // [n * (n-1) *---* (n-k+1)] / // [k * (k-1) *----* 1] for (var i = 0; i < k; ++i) { res *= (n - i); res /= (i + 1); } return res;} // function to count subsequences// in first string which are// anagrams of the second stringfunction countSubsequences(str1, str2){ // hash tables to store frequencies // of each character var freq1 = Array(SIZE).fill(0), freq2 = Array(SIZE).fill(0); var n1 = str1.length; var n2 = str2.length; // store frequency of each // character of 'str1' for (var i = 0; i < n1; i++) freq1[str1[i].charCodeAt(0) - 'a'.charCodeAt(0)]++; // store frequency of each // character of 'str2' for (var i = 0; i < n2; i++) freq2[str2[i].charCodeAt(0) - 'a'.charCodeAt(0)]++; // to store the total count // of subsequences var count = 1; for (var i = 0; i < SIZE; i++) // if character (i + 'a') // exists in 'str2' if (freq2[i] != 0) { // if this character's frequency // in 'str2' in less than or // equal to its frequency in // 'str1' then accumulate its // contribution to the count // of subsequences. If its // frequency in 'str1' is 'n' // and in 'str2' is 'r', then // its contribution will be nCr, // where C is the binomial // coefficient. if (freq2[i] <= freq1[i]) count = count * binomialCoeff(freq1[i], freq2[i]); // else return 0 as there could // be no subsequence which is an // anagram of 'str2' else return 0; } // required count of subsequences return count;} // Driver program to test abovevar str1 = "abacd";var str2 = "abc";document.write( "Count = " + countSubsequences(str1, str2)); </script> Output: Count = 2 Time Complexity: O(n1 + n2) + O(max), where max is the maximum frequency. Auxiliary space: O(26). Please suggest if someone has a better solution which is more efficient in terms of space and time.This article is contributed by Aarti_Rathi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above parashar manishshaw1 shubham_singh hritikbhatnagar2182 itsok codewithshinchan anagram subsequence Strings Strings anagram Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n06 Jul, 2022" }, { "code": null, "e": 213, "s": 54, "text": "Given two strings str1 and str2 of length n1 and n2 respectively. The problem is to count all the subsequences of str1 which are anagrams of str2. Examples: " }, { "code": null, "e": 487, "s": 213, "text": "Input : str1 = \"abacd\", str2 = \"abc\"\nOutput : 2\nIndex of characters in the 2 subsequences are:\n{0, 1, 3} = {a, b, c} = abc and\n{1, 2, 3} = {b, a, c} = bac\nThe above two subsequences of str1 \nare anagrams of str2.\n\nInput : str1 = \"geeksforgeeks\", str2 = \"geeks\" \nOutput : 48" }, { "code": null, "e": 757, "s": 489, "text": "Approach: Create two arrays freq1[] and freq2[] each of size ’26’ implemented as hash tables to store the frequencies of each character of str1 and str2 respectively. Let n1 and n2 be the lengths of str1 and str2 respectively. Now implement the following algorithm: " }, { "code": null, "e": 1140, "s": 757, "text": "countSubsequences(str1, str2)\n for i = 0 to n1-1\n freq1[str1[i] - 'a']++\n for i = 0 n2-1 \n freq2[str2[i] - 'a']++\n\n Initialize count = 1 \n for i = 0 to 25\n if freq2[i] != 0 then\n if freq2[i] <= freq1[i] then\n count = count * binomialCoeff(freq1[i], freq2[i])\n else\n return 0 \n return count" }, { "code": null, "e": 1635, "s": 1140, "text": "Let freq1[i] is represented as n and freq2[i] as r. Now, binomialCoeff(n, r) mentioned in the algorithm above is nothing but binomial coefficient nCr .Refer this post for its implementation.Explanation: Let frequency of some character say ch in ‘str2’ is ‘x’ and in ‘str1’ is ‘y’. If y < x, then no subsequence of ‘str1’ exists which could be an anagram of ‘str2’. Otherwise, yCx gives the number of occurrences of ch selected which will contribute to the total count of required subsequences. " }, { "code": null, "e": 1639, "s": 1635, "text": "C++" }, { "code": null, "e": 1644, "s": 1639, "text": "Java" }, { "code": null, "e": 1651, "s": 1644, "text": "Python" }, { "code": null, "e": 1654, "s": 1651, "text": "C#" }, { "code": null, "e": 1658, "s": 1654, "text": "PHP" }, { "code": null, "e": 1669, "s": 1658, "text": "Javascript" }, { "code": "// C++ implementation to// count subsequences in// first string which are // anagrams of the second// string#include <bits/stdc++.h>using namespace std; #define SIZE 26 // Returns value of Binomial// Coefficient C(n, k)int binomialCoeff(int n, int k){ int res = 1; // Since C(n, k) = C(n, n-k) if (k > n - k) k = n - k; // Calculate value of // [n * (n-1) *---* (n-k+1)] / // [k * (k-1) *----* 1] for (int i = 0; i < k; ++i) { res *= (n - i); res /= (i + 1); } return res;} // function to count subsequences// in first string which are// anagrams of the second stringint countSubsequences(string str1, string str2){ // hash tables to store frequencies // of each character int freq1[SIZE], freq2[SIZE]; int n1 = str1.size(); int n2 = str2.size(); // Initialize memset(freq1, 0, sizeof(freq1)); memset(freq2, 0, sizeof(freq2)); // store frequency of each // character of 'str1' for (int i = 0; i < n1; i++) freq1[str1[i] - 'a']++; // store frequency of each // character of 'str2' for (int i = 0; i < n2; i++) freq2[str2[i] - 'a']++; // to store the total count // of subsequences int count = 1; for (int i = 0; i < SIZE; i++) // if character (i + 'a') // exists in 'str2' if (freq2[i] != 0) { // if this character's frequency // in 'str2' in less than or // equal to its frequency in // 'str1' then accumulate its // contribution to the count // of subsequences. If its // frequency in 'str1' is 'n' // and in 'str2' is 'r', then // its contribution will be nCr, // where C is the binomial // coefficient. if (freq2[i] <= freq1[i]) count = count * binomialCoeff(freq1[i], freq2[i]); // else return 0 as there could // be no subsequence which is an // anagram of 'str2' else return 0; } // required count of subsequences return count;} // Driver program to test aboveint main(){ string str1 = \"abacd\"; string str2 = \"abc\"; cout << \"Count = \" << countSubsequences(str1, str2); return 0;}", "e": 3988, "s": 1669, "text": null }, { "code": "// Java implementation to// count subsequences in// first string which are// anagrams of the second// stringimport java.util.*;import java.lang.*; public class GfG{ public final static int SIZE = 26; // Returns value of Binomial // Coefficient C(n, k) public static int binomialCoeff(int n, int k) { int res = 1; // Since C(n, k) = C(n, n-k) if (k > n - k) k = n - k; // Calculate value of // [n * (n-1) *---* (n-k+1)] / // [k * (k-1) *----* 1] for (int i = 0; i < k; ++i) { res *= (n - i); res /= (i + 1); } return res; } // function to count subsequences // in first string which are // anagrams of the second string public static int countSubsequences(String str, String str3) { // hash tables to store frequencies // of each character int[] freq1 = new int [SIZE]; int[] freq2 = new int [SIZE]; char[] str1 = str.toCharArray(); char[] str2 = str3.toCharArray(); int n1 = str.length(); int n2 = str3.length(); // store frequency of each // character of 'str1' for (int i = 0; i < n1; i++) freq1[str1[i] - 'a']++; // store frequency of each // character of 'str2' for (int i = 0; i < n2; i++) freq2[str2[i] - 'a']++; // to store the total count // of subsequences int count = 1; for (int i = 0; i < SIZE; i++) // if character (i + 'a') // exists in 'str2' if (freq2[i] != 0) { // if this character's frequency // in 'str2' in less than or // equal to its frequency in // 'str1' then accumulate its // contribution to the count // of subsequences. If its // frequency in 'str1' is 'n' // and in 'str2' is 'r', then // its contribution will be nCr, // where C is the binomial // coefficient. if (freq2[i] <= freq1[i]) count = count * binomialCoeff(freq1[i], freq2[i]); // else return 0 as there could // be no subsequence which is an // anagram of 'str2' else return 0; } // required count of subsequences return count; } // Driver function public static void main(String argc[]) { String str1 = \"abacd\"; String str2 = \"abc\"; System.out.println(\"Count = \" + countSubsequences(str1, str2)); }} /* This code is contributed by Sagar Shukla */", "e": 6811, "s": 3988, "text": null }, { "code": "# Python3 implementation to count# subsequences in first which are# anagrams of the second # import libraryimport numpy as np SIZE = 26 # Returns value of Binomial# Coefficient C(n, k)def binomialCoeff(n, k): res = 1 # Since C(n, k) = C(n, n-k) if (k > n - k): k = n - k # Calculate value of # [n * (n-1) *---* (n-k+1)] / # [k * (k-1) *----* 1] for i in range(0, k): res = res * (n - i) res = int(res / (i + 1)) return res # Function to count subsequences# in first which are anagrams# of the seconddef countSubsequences(str1, str2): # Hash tables to store frequencies # of each character freq1 = np.zeros(26, dtype = np.int) freq2 = np.zeros(26, dtype = np.int) n1 = len(str1) n2 = len(str2) # Store frequency of each # character of 'str1' for i in range(0, n1): freq1[ord(str1[i]) - ord('a') ] += 1 # Store frequency of each # character of 'str2' for i in range(0, n2): freq2[ord(str2[i]) - ord('a')] += 1 # To store the total count # of subsequences count = 1 for i in range(0, SIZE): # if character (i + 'a') # exists in 'str2' if (freq2[i] != 0): # if this character's frequency # in 'str2' in less than or # equal to its frequency in # 'str1' then accumulate its # contribution to the count # of subsequences. If its # frequency in 'str1' is 'n' # and in 'str2' is 'r', then # its contribution will be nCr, # where C is the binomial # coefficient. if (freq2[i] <= freq1[i]): count = count * binomialCoeff(freq1[i], freq2[i]) # else return 0 as there could # be no subsequence which is an # anagram of 'str2' else: return 0 # required count of subsequences return count # Driver codestr1 = \"abacd\"str2 = \"abc\"ans = countSubsequences(str1, str2)print (\"Count = \", ans) # This code contributed by saloni1297", "e": 8914, "s": 6811, "text": null }, { "code": "// C# implementation to// count subsequences in// first string which are// anagrams of the second// stringusing System; class GfG { public static int SIZE = 26; // Returns value of Binomial // Coefficient C(n, k) public static int binomialCoeff(int n, int k) { int res = 1; // Since C(n, k) = C(n, n-k) if (k > n - k) k = n - k; // Calculate value of // [n * (n-1) *---* (n-k+1)] / // [k * (k-1) *----* 1] for (int i = 0; i < k; ++i) { res *= (n - i); res /= (i + 1); } return res; } // function to count subsequences // in first string which are // anagrams of the second string public static int countSubsequences(String str, String str3) { // hash tables to store frequencies // of each character int[] freq1 = new int [SIZE]; int[] freq2 = new int [SIZE]; char[] str1 = str.ToCharArray(); char[] str2 = str3.ToCharArray(); int n1 = str.Length; int n2 = str3.Length; // store frequency of each // character of 'str1' for (int i = 0; i < n1; i++) freq1[str1[i] - 'a']++; // store frequency of each // character of 'str2' for (int i = 0; i < n2; i++) freq2[str2[i] - 'a']++; // to store the total count // of subsequences int count = 1; for (int i = 0; i < SIZE; i++) // if character (i + 'a') // exists in 'str2' if (freq2[i] != 0) { // if this character's frequency // in 'str2' in less than or // equal to its frequency in // 'str1' then accumulate its // contribution to the count // of subsequences. If its // frequency in 'str1' is 'n' // and in 'str2' is 'r', then // its contribution will be nCr, // where C is the binomial // coefficient. if (freq2[i] <= freq1[i]) count = count * binomialCoeff(freq1[i], freq2[i]); // else return 0 as there could // be no subsequence which is an // anagram of 'str2' else return 0; } // required count of subsequences return count; } // Driver code public static void Main(String[] argc) { String str1 = \"abacd\"; String str2 = \"abc\"; Console.Write(\"Count = \" + countSubsequences(str1, str2)); }} // This code is contributed by parashar", "e": 11727, "s": 8914, "text": null }, { "code": "<?php// PHP implementation to// count subsequences in// first $which are// anagrams of the second// string$SIZE = 26; // Returns value of Binomial// Coefficient C(n, k)function binomialCoeff($n, $k){ $res = 1; // Since C(n, k) = C(n, n-k) if ($k > $n - $k) $k = $n - $k; // Calculate value of // [n * (n-1) *---* (n-k+1)] / // [k * (k-1) *----* 1] for ($i = 0; $i < $k; ++$i) { $res *= ($n - $i); $res /= ($i + 1); } return $res;} // function to count// subsequences in// first string which// are anagrams of the// second stringfunction countSubsequences($str1, $str2){ global $SIZE; // hash tables to // store frequencies // of each character $freq1 = array(); $freq2 = array(); // Initialize for ($i = 0; $i < $SIZE; $i++) { $freq1[$i] = 0; $freq2[$i] = 0; } $n1 = strlen($str1); $n2 = strlen($str2); // store frequency of each // character of 'str1' for ($i = 0; $i < $n1; $i++) $freq1[ord($str1[$i]) - ord('a')]++; // store frequency of each // character of 'str2' for ($i = 0; $i < $n2; $i++) $freq2[ord($str2[$i]) - ord('a')]++; // to store the total count // of subsequences $count = 1; for ($i = 0; $i < $SIZE; $i++) // if character (i + 'a') // exists in 'str2' if ($freq2[$i] != 0) { // if this character's frequency // in 'str2' in less than or // equal to its frequency in // 'str1' then accumulate its // contribution to the count // of subsequences. If its // frequency in 'str1' is 'n' // and in 'str2' is 'r', then // its contribution will be nCr, // where C is the binomial // coefficient. if ($freq2[$i] <= $freq1[$i]) $count = $count * binomialCoeff($freq1[$i], $freq2[$i]); // else return 0 as there // could be no subsequence // which is an anagram of // 'str2' else return 0; } // required count // of subsequences return $count;} // Driver Code$str1 = \"abacd\";$str2 = \"abc\";echo (\"Count = \". countSubsequences($str1, $str2)); // This code is contributed by// Manish Shaw(manishshaw1)?>", "e": 14213, "s": 11727, "text": null }, { "code": "<script> // JavaScript implementation to// count subsequences in// first string which are // anagrams of the second// string var SIZE = 26 // Returns value of Binomial// Coefficient C(n, k)function binomialCoeff(n, k){ var res = 1; // Since C(n, k) = C(n, n-k) if (k > n - k) k = n - k; // Calculate value of // [n * (n-1) *---* (n-k+1)] / // [k * (k-1) *----* 1] for (var i = 0; i < k; ++i) { res *= (n - i); res /= (i + 1); } return res;} // function to count subsequences// in first string which are// anagrams of the second stringfunction countSubsequences(str1, str2){ // hash tables to store frequencies // of each character var freq1 = Array(SIZE).fill(0), freq2 = Array(SIZE).fill(0); var n1 = str1.length; var n2 = str2.length; // store frequency of each // character of 'str1' for (var i = 0; i < n1; i++) freq1[str1[i].charCodeAt(0) - 'a'.charCodeAt(0)]++; // store frequency of each // character of 'str2' for (var i = 0; i < n2; i++) freq2[str2[i].charCodeAt(0) - 'a'.charCodeAt(0)]++; // to store the total count // of subsequences var count = 1; for (var i = 0; i < SIZE; i++) // if character (i + 'a') // exists in 'str2' if (freq2[i] != 0) { // if this character's frequency // in 'str2' in less than or // equal to its frequency in // 'str1' then accumulate its // contribution to the count // of subsequences. If its // frequency in 'str1' is 'n' // and in 'str2' is 'r', then // its contribution will be nCr, // where C is the binomial // coefficient. if (freq2[i] <= freq1[i]) count = count * binomialCoeff(freq1[i], freq2[i]); // else return 0 as there could // be no subsequence which is an // anagram of 'str2' else return 0; } // required count of subsequences return count;} // Driver program to test abovevar str1 = \"abacd\";var str2 = \"abc\";document.write( \"Count = \" + countSubsequences(str1, str2)); </script>", "e": 16497, "s": 14213, "text": null }, { "code": null, "e": 16507, "s": 16497, "text": "Output: " }, { "code": null, "e": 16517, "s": 16507, "text": "Count = 2" }, { "code": null, "e": 16591, "s": 16517, "text": "Time Complexity: O(n1 + n2) + O(max), where max is the maximum frequency." }, { "code": null, "e": 16616, "s": 16591, "text": "Auxiliary space: O(26). " }, { "code": null, "e": 16884, "s": 16616, "text": "Please suggest if someone has a better solution which is more efficient in terms of space and time.This article is contributed by Aarti_Rathi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above " }, { "code": null, "e": 16893, "s": 16884, "text": "parashar" }, { "code": null, "e": 16905, "s": 16893, "text": "manishshaw1" }, { "code": null, "e": 16919, "s": 16905, "text": "shubham_singh" }, { "code": null, "e": 16939, "s": 16919, "text": "hritikbhatnagar2182" }, { "code": null, "e": 16945, "s": 16939, "text": "itsok" }, { "code": null, "e": 16962, "s": 16945, "text": "codewithshinchan" }, { "code": null, "e": 16970, "s": 16962, "text": "anagram" }, { "code": null, "e": 16982, "s": 16970, "text": "subsequence" }, { "code": null, "e": 16990, "s": 16982, "text": "Strings" }, { "code": null, "e": 16998, "s": 16990, "text": "Strings" }, { "code": null, "e": 17006, "s": 16998, "text": "anagram" } ]
What is the purpose of a function prototype in C/C++?
Here we will see what are the purpose of using function prototypes in C or C++. The function prototypes are used to tell the compiler about the number of arguments and about the required datatypes of a function parameter, it also tells about the return type of the function. By this information, the compiler cross-checks the function signatures before calling it. If the function prototypes are not mentioned, then the program may be compiled with some warnings, and sometimes generate some strange output. If some function is called somewhere, but its body is not defined yet, that is defined after the current line, then it may generate problems. The compiler does not find what is the function and what is its signature. In that case, we need to function prototypes. If the function is defined before then we do not need prototypes. #include<stdio.h> main() { function(50); } void function(int x) { printf("The value of x is: %d", x); } The value of x is: 50 This shows the output, but it is showing some warning like below: [Warning] conflicting types for 'function' [Note] previous implicit declaration of 'function' was here Now using function prototypes, it is executing without any problem. #include<stdio.h> void function(int); //prototype main() { function(50); } void function(int x) { printf("The value of x is: %d", x); } The value of x is: 50
[ { "code": null, "e": 1695, "s": 1187, "text": "Here we will see what are the purpose of using function prototypes in C or C++. The function prototypes are used to tell the compiler about the number of arguments and about the required datatypes of a function parameter, it also tells about the return type of the function. By this information, the compiler cross-checks the function signatures before calling it. If the function prototypes are not mentioned, then the program may be compiled with some warnings, and sometimes generate some strange output." }, { "code": null, "e": 2024, "s": 1695, "text": "If some function is called somewhere, but its body is not defined yet, that is defined after the current line, then it may generate problems. The compiler does not find what is the function and what is its signature. In that case, we need to function prototypes. If the function is defined before then we do not need prototypes." }, { "code": null, "e": 2134, "s": 2024, "text": "#include<stdio.h>\nmain() {\n function(50);\n}\nvoid function(int x) {\n printf(\"The value of x is: %d\", x);\n}" }, { "code": null, "e": 2156, "s": 2134, "text": "The value of x is: 50" }, { "code": null, "e": 2222, "s": 2156, "text": "This shows the output, but it is showing some warning like below:" }, { "code": null, "e": 2325, "s": 2222, "text": "[Warning] conflicting types for 'function'\n[Note] previous implicit declaration of 'function' was here" }, { "code": null, "e": 2393, "s": 2325, "text": "Now using function prototypes, it is executing without any problem." }, { "code": null, "e": 2535, "s": 2393, "text": "#include<stdio.h>\nvoid function(int); //prototype\nmain() {\n function(50);\n}\nvoid function(int x) {\n printf(\"The value of x is: %d\", x);\n}" }, { "code": null, "e": 2557, "s": 2535, "text": "The value of x is: 50" } ]
Python | Find the Number Occurring Odd Number of Times using Lambda expression and reduce function
20 Oct, 2018 Given an array of positive integers. All numbers occur even number of times except one number which occurs odd number of times. Find the number in O(n) time & constant space. Examples: Input : [1, 2, 3, 2, 3, 1, 3] Output : 3 We have existing solution for this problem please refer Find the Number Occurring Odd Number of Times link. we will solve this problem in python quickly using Reduce(expression, iterable) method. # Python program to Find the Number # Occurring Odd Number of Times# using Lambda expression and reduce function from functools import reduce def oddTimes(input): # write lambda expression and apply # reduce function over input list # until single value is left # expression reduces value of a ^ b into single value # a starts from 0 and b from 1 # ((((((1 ^ 2)^3)^2)^3)^1)^3) print (reduce(lambda a, b: a ^ b, input)) # Driver programif __name__ == "__main__": input = [1, 2, 3, 2, 3, 1, 3] oddTimes(input) Output: 3 python-lambda python-string 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 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": "\n20 Oct, 2018" }, { "code": null, "e": 203, "s": 28, "text": "Given an array of positive integers. All numbers occur even number of times except one number which occurs odd number of times. Find the number in O(n) time & constant space." }, { "code": null, "e": 213, "s": 203, "text": "Examples:" }, { "code": null, "e": 257, "s": 213, "text": "Input : [1, 2, 3, 2, 3, 1, 3]\nOutput : 3\n" }, { "code": null, "e": 453, "s": 257, "text": "We have existing solution for this problem please refer Find the Number Occurring Odd Number of Times link. we will solve this problem in python quickly using Reduce(expression, iterable) method." }, { "code": "# Python program to Find the Number # Occurring Odd Number of Times# using Lambda expression and reduce function from functools import reduce def oddTimes(input): # write lambda expression and apply # reduce function over input list # until single value is left # expression reduces value of a ^ b into single value # a starts from 0 and b from 1 # ((((((1 ^ 2)^3)^2)^3)^1)^3) print (reduce(lambda a, b: a ^ b, input)) # Driver programif __name__ == \"__main__\": input = [1, 2, 3, 2, 3, 1, 3] oddTimes(input)", "e": 998, "s": 453, "text": null }, { "code": null, "e": 1006, "s": 998, "text": "Output:" }, { "code": null, "e": 1009, "s": 1006, "text": "3\n" }, { "code": null, "e": 1023, "s": 1009, "text": "python-lambda" }, { "code": null, "e": 1037, "s": 1023, "text": "python-string" }, { "code": null, "e": 1044, "s": 1037, "text": "Python" }, { "code": null, "e": 1142, "s": 1044, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1174, "s": 1142, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 1201, "s": 1174, "text": "Python Classes and Objects" }, { "code": null, "e": 1222, "s": 1201, "text": "Python OOPs Concepts" }, { "code": null, "e": 1245, "s": 1222, "text": "Introduction To PYTHON" }, { "code": null, "e": 1301, "s": 1245, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 1332, "s": 1301, "text": "Python | os.path.join() method" }, { "code": null, "e": 1374, "s": 1332, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 1416, "s": 1374, "text": "Check if element exists in list in Python" }, { "code": null, "e": 1455, "s": 1416, "text": "Python | datetime.timedelta() function" } ]
Multiset of Tuples in C++ with Examples
24 Jan, 2022 What is a tuple? A tuple in C++ is an object which binds a group of elements together. The elements can be similar as well as different data types. The elements of tuples are initialized as in the order in which they will be accessed. Syntax: tuple<data_type1, data_type2, dataType3, ....> myTuple Here,dataType1, dataType2, dataType3 . . . . are similar or dissimilar data types Functions associated with a tuple: 1. make_tuple(): make_tuple() is used to assign tuple with values. The values passed should be in order with the values declared in the tuple. Syntax: myTuple = make_tuple(value1, value2, value3,....) 2. get(): get() is used to access the tuple values and modify them, it accepts the index and tuple name as arguments to access a particular tuple element. Syntax: get<index>(myTuple) Here,index is the index of the element we want to access in myTuple. Indexing in a tuple begins with zero. What is a multiset? A multiset is a type of associative container that is similar to a set but in the case of a multiset, all elements are necessary to be pairwise distinct. In simple words, there can be more than one element with the same value. Syntax: multiset<dataType> myMultiset; Here,dataType is a data type. Functions associated with multiset: begin(): Returns an iterator to the first element in the multiset. end(): Returns an iterator to the theoretical element that follows the last element in the multiset. size(): Returns the number of elements in the multiset. max_size(): Returns the maximum number of elements that the multiset can hold. empty(): Returns whether the multiset is empty. A multiset of tuples can be quite useful when an algorithm requires a complex data structure. This article focuses on how to create a multiset of tuples in C++. Note that for simplicity a tuple of three elements is taken into consideration but a tuple can contain more or fewer elements also. Multiset of tuples A multiset of tuples is a multiset in which each of the elements is a tuple. Syntax: multiset<tuple<dataType1, dataType2, dataType3>> multisetOfTuples; Here,dataType1, dataType2, dataType3 are similar or dissimilar data types. Example 1: Below is the C++ program to implement a multiset of tuples: C++ // C++ program to illustrate the// implementation of multiset of// tuples#include <bits/stdc++.h>using namespace std; // Function to print multiset contentsvoid print(multiset<tuple<int, int, int> >& multisetOfTuples) { // Iterating over multisetOfTuples elements for (auto x : multisetOfTuples) { // Each element is a tuple itself tuple<int, int, int> tp = x; // Printing tuple elements cout << get<0>(tp) << ' ' << get<1>(tp) << ' ' << get<2>(tp) << '\n'; }} // Driver codeint main(){ // Declaring a multiset of tuples multiset<tuple<int, int, int> > multisetOfTuples; // Initializing tuples tuple<int, int, int> tuple1; tuple1 = make_tuple(4, 2, 3); tuple<int, int, int> tuple2; tuple2 = make_tuple(2, 3, 5); tuple<int, int, int> tuple3; tuple3 = make_tuple(2, 3, 5); tuple<int, int, int> tuple4; tuple4 = make_tuple(2, 1, 4); tuple<int, int, int> tuple5; tuple5 = make_tuple(4, 2, 3); // Inserting into multiset multisetOfTuples.insert(tuple1); multisetOfTuples.insert(tuple2); multisetOfTuples.insert(tuple3); multisetOfTuples.insert(tuple4); multisetOfTuples.insert(tuple5); // Calling print function print(multisetOfTuples); return 0;} Output: 2 1 42 3 52 3 54 2 34 2 3 Explanation: In the above output, there is a total of five tuples are present in the multiset out of which (2, 3, 5) and (4, 2, 3) occur twice. By default, tuples are arranged in non-descending order in the multiset and follow the below logic: In the multiset, if the first value of two tuples is equal then the second value of tuples is compared and if it is also equal then the third value is compared.But it is always possible to pass a comparator to a set. In the multiset, if the first value of two tuples is equal then the second value of tuples is compared and if it is also equal then the third value is compared. But it is always possible to pass a comparator to a set. Example 2: Below is the C++ program to demonstrate passing a comparator to the multiset which arranges a multiset of tuples elements in non-ascending order. C++ // C++ program to demonstrate the// implementation of multiset of// tuples by using custom comparator#include <bits/stdc++.h>using namespace std; // Comparator for arranging elements// in non-ascending order We can// always modify the comparator as// per the requirementstruct cmp{ // Arranging multiset elements in // non-ascending order bool operator()(const tuple<int, int, int>& x, const tuple<int, int, int>& y) { // If first elements of corresponding // tuples are equal if (get<0>(x) == get<0>(y)) { // If second elements of corresponding // tuples are equal if (get<1>(x) == get<1>(y)) return get<2>(x) > get<2>(y); return get<1>(x) > get<1>(y); } return get<0>(x) > get<0>(y); }}; // Function to print multiset elementsvoid print(multiset<tuple<int, int, int>, cmp>& multisetOfTuples){ for (auto x : multisetOfTuples) { // Each element of the multiset is // tuple itself tuple<int, int, int> tp = x; // Printing tuple elements cout << get<0>(tp) << ' ' << get<1>(tp) << ' ' << get<2>(tp) << '\n'; }} // Driver codeint main(){ // Declaring a multiset of tuples multiset<tuple<int, int, int>, cmp> multisetOfTuples; // Initializing tuples tuple<int, int, int> tuple1; tuple1 = make_tuple(1, 2, 3); tuple<int, int, int> tuple2; tuple2 = make_tuple(2, 3, 5); tuple<int, int, int> tuple3; tuple3 = make_tuple(2, 3, 5); tuple<int, int, int> tuple4; tuple4 = make_tuple(2, 1, 4); tuple<int, int, int> tuple5; tuple5 = make_tuple(5, 8, 4); // Inserting into multiset multisetOfTuples.insert(tuple1); multisetOfTuples.insert(tuple2); multisetOfTuples.insert(tuple3); multisetOfTuples.insert(tuple4); multisetOfTuples.insert(tuple5); // Calling print function print(multisetOfTuples); return 0;} Output: 5 8 42 3 52 3 52 1 41 2 3 Explanation: In the above output, elements in the multiset are arranged according to non-ascending order. The tuple with values (2, 3, 5) has two copies in the multiset. surindertarika1234 bhuwanesh varshagumber28 cpp-multiset cpp-tuple STL C++ STL CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Bitwise Operators in C/C++ Priority Queue in C++ Standard Template Library (STL) Set in C++ Standard Template Library (STL) vector erase() and clear() in C++ unordered_map in C++ STL Substring in C++ Object Oriented Programming in C++ The C++ Standard Template Library (STL) Inheritance in C++ C++ Classes and Objects
[ { "code": null, "e": 28, "s": 0, "text": "\n24 Jan, 2022" }, { "code": null, "e": 45, "s": 28, "text": "What is a tuple?" }, { "code": null, "e": 263, "s": 45, "text": "A tuple in C++ is an object which binds a group of elements together. The elements can be similar as well as different data types. The elements of tuples are initialized as in the order in which they will be accessed." }, { "code": null, "e": 271, "s": 263, "text": "Syntax:" }, { "code": null, "e": 327, "s": 271, "text": "tuple<data_type1, data_type2, dataType3, ....> myTuple " }, { "code": null, "e": 409, "s": 327, "text": "Here,dataType1, dataType2, dataType3 . . . . are similar or dissimilar data types" }, { "code": null, "e": 444, "s": 409, "text": "Functions associated with a tuple:" }, { "code": null, "e": 587, "s": 444, "text": "1. make_tuple(): make_tuple() is used to assign tuple with values. The values passed should be in order with the values declared in the tuple." }, { "code": null, "e": 595, "s": 587, "text": "Syntax:" }, { "code": null, "e": 645, "s": 595, "text": "myTuple = make_tuple(value1, value2, value3,....)" }, { "code": null, "e": 800, "s": 645, "text": "2. get(): get() is used to access the tuple values and modify them, it accepts the index and tuple name as arguments to access a particular tuple element." }, { "code": null, "e": 808, "s": 800, "text": "Syntax:" }, { "code": null, "e": 828, "s": 808, "text": "get<index>(myTuple)" }, { "code": null, "e": 936, "s": 828, "text": "Here,index is the index of the element we want to access in myTuple. Indexing in a tuple begins with zero. " }, { "code": null, "e": 956, "s": 936, "text": "What is a multiset?" }, { "code": null, "e": 1183, "s": 956, "text": "A multiset is a type of associative container that is similar to a set but in the case of a multiset, all elements are necessary to be pairwise distinct. In simple words, there can be more than one element with the same value." }, { "code": null, "e": 1191, "s": 1183, "text": "Syntax:" }, { "code": null, "e": 1222, "s": 1191, "text": "multiset<dataType> myMultiset;" }, { "code": null, "e": 1252, "s": 1222, "text": "Here,dataType is a data type." }, { "code": null, "e": 1290, "s": 1252, "text": "Functions associated with multiset: " }, { "code": null, "e": 1357, "s": 1290, "text": "begin(): Returns an iterator to the first element in the multiset." }, { "code": null, "e": 1458, "s": 1357, "text": "end(): Returns an iterator to the theoretical element that follows the last element in the multiset." }, { "code": null, "e": 1514, "s": 1458, "text": "size(): Returns the number of elements in the multiset." }, { "code": null, "e": 1593, "s": 1514, "text": "max_size(): Returns the maximum number of elements that the multiset can hold." }, { "code": null, "e": 1641, "s": 1593, "text": "empty(): Returns whether the multiset is empty." }, { "code": null, "e": 1934, "s": 1641, "text": "A multiset of tuples can be quite useful when an algorithm requires a complex data structure. This article focuses on how to create a multiset of tuples in C++. Note that for simplicity a tuple of three elements is taken into consideration but a tuple can contain more or fewer elements also." }, { "code": null, "e": 1953, "s": 1934, "text": "Multiset of tuples" }, { "code": null, "e": 2031, "s": 1953, "text": "A multiset of tuples is a multiset in which each of the elements is a tuple. " }, { "code": null, "e": 2039, "s": 2031, "text": "Syntax:" }, { "code": null, "e": 2106, "s": 2039, "text": "multiset<tuple<dataType1, dataType2, dataType3>> multisetOfTuples;" }, { "code": null, "e": 2181, "s": 2106, "text": "Here,dataType1, dataType2, dataType3 are similar or dissimilar data types." }, { "code": null, "e": 2252, "s": 2181, "text": "Example 1: Below is the C++ program to implement a multiset of tuples:" }, { "code": null, "e": 2256, "s": 2252, "text": "C++" }, { "code": "// C++ program to illustrate the// implementation of multiset of// tuples#include <bits/stdc++.h>using namespace std; // Function to print multiset contentsvoid print(multiset<tuple<int, int, int> >& multisetOfTuples) { // Iterating over multisetOfTuples elements for (auto x : multisetOfTuples) { // Each element is a tuple itself tuple<int, int, int> tp = x; // Printing tuple elements cout << get<0>(tp) << ' ' << get<1>(tp) << ' ' << get<2>(tp) << '\\n'; }} // Driver codeint main(){ // Declaring a multiset of tuples multiset<tuple<int, int, int> > multisetOfTuples; // Initializing tuples tuple<int, int, int> tuple1; tuple1 = make_tuple(4, 2, 3); tuple<int, int, int> tuple2; tuple2 = make_tuple(2, 3, 5); tuple<int, int, int> tuple3; tuple3 = make_tuple(2, 3, 5); tuple<int, int, int> tuple4; tuple4 = make_tuple(2, 1, 4); tuple<int, int, int> tuple5; tuple5 = make_tuple(4, 2, 3); // Inserting into multiset multisetOfTuples.insert(tuple1); multisetOfTuples.insert(tuple2); multisetOfTuples.insert(tuple3); multisetOfTuples.insert(tuple4); multisetOfTuples.insert(tuple5); // Calling print function print(multisetOfTuples); return 0;}", "e": 3486, "s": 2256, "text": null }, { "code": null, "e": 3494, "s": 3486, "text": "Output:" }, { "code": null, "e": 3520, "s": 3494, "text": "2 1 42 3 52 3 54 2 34 2 3" }, { "code": null, "e": 3533, "s": 3520, "text": "Explanation:" }, { "code": null, "e": 3764, "s": 3533, "text": "In the above output, there is a total of five tuples are present in the multiset out of which (2, 3, 5) and (4, 2, 3) occur twice. By default, tuples are arranged in non-descending order in the multiset and follow the below logic:" }, { "code": null, "e": 3981, "s": 3764, "text": "In the multiset, if the first value of two tuples is equal then the second value of tuples is compared and if it is also equal then the third value is compared.But it is always possible to pass a comparator to a set." }, { "code": null, "e": 4142, "s": 3981, "text": "In the multiset, if the first value of two tuples is equal then the second value of tuples is compared and if it is also equal then the third value is compared." }, { "code": null, "e": 4199, "s": 4142, "text": "But it is always possible to pass a comparator to a set." }, { "code": null, "e": 4356, "s": 4199, "text": "Example 2: Below is the C++ program to demonstrate passing a comparator to the multiset which arranges a multiset of tuples elements in non-ascending order." }, { "code": null, "e": 4360, "s": 4356, "text": "C++" }, { "code": "// C++ program to demonstrate the// implementation of multiset of// tuples by using custom comparator#include <bits/stdc++.h>using namespace std; // Comparator for arranging elements// in non-ascending order We can// always modify the comparator as// per the requirementstruct cmp{ // Arranging multiset elements in // non-ascending order bool operator()(const tuple<int, int, int>& x, const tuple<int, int, int>& y) { // If first elements of corresponding // tuples are equal if (get<0>(x) == get<0>(y)) { // If second elements of corresponding // tuples are equal if (get<1>(x) == get<1>(y)) return get<2>(x) > get<2>(y); return get<1>(x) > get<1>(y); } return get<0>(x) > get<0>(y); }}; // Function to print multiset elementsvoid print(multiset<tuple<int, int, int>, cmp>& multisetOfTuples){ for (auto x : multisetOfTuples) { // Each element of the multiset is // tuple itself tuple<int, int, int> tp = x; // Printing tuple elements cout << get<0>(tp) << ' ' << get<1>(tp) << ' ' << get<2>(tp) << '\\n'; }} // Driver codeint main(){ // Declaring a multiset of tuples multiset<tuple<int, int, int>, cmp> multisetOfTuples; // Initializing tuples tuple<int, int, int> tuple1; tuple1 = make_tuple(1, 2, 3); tuple<int, int, int> tuple2; tuple2 = make_tuple(2, 3, 5); tuple<int, int, int> tuple3; tuple3 = make_tuple(2, 3, 5); tuple<int, int, int> tuple4; tuple4 = make_tuple(2, 1, 4); tuple<int, int, int> tuple5; tuple5 = make_tuple(5, 8, 4); // Inserting into multiset multisetOfTuples.insert(tuple1); multisetOfTuples.insert(tuple2); multisetOfTuples.insert(tuple3); multisetOfTuples.insert(tuple4); multisetOfTuples.insert(tuple5); // Calling print function print(multisetOfTuples); return 0;}", "e": 6321, "s": 4360, "text": null }, { "code": null, "e": 6329, "s": 6321, "text": "Output:" }, { "code": null, "e": 6355, "s": 6329, "text": "5 8 42 3 52 3 52 1 41 2 3" }, { "code": null, "e": 6368, "s": 6355, "text": "Explanation:" }, { "code": null, "e": 6525, "s": 6368, "text": "In the above output, elements in the multiset are arranged according to non-ascending order. The tuple with values (2, 3, 5) has two copies in the multiset." }, { "code": null, "e": 6544, "s": 6525, "text": "surindertarika1234" }, { "code": null, "e": 6554, "s": 6544, "text": "bhuwanesh" }, { "code": null, "e": 6569, "s": 6554, "text": "varshagumber28" }, { "code": null, "e": 6582, "s": 6569, "text": "cpp-multiset" }, { "code": null, "e": 6592, "s": 6582, "text": "cpp-tuple" }, { "code": null, "e": 6596, "s": 6592, "text": "STL" }, { "code": null, "e": 6600, "s": 6596, "text": "C++" }, { "code": null, "e": 6604, "s": 6600, "text": "STL" }, { "code": null, "e": 6608, "s": 6604, "text": "CPP" }, { "code": null, "e": 6706, "s": 6608, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6733, "s": 6706, "text": "Bitwise Operators in C/C++" }, { "code": null, "e": 6787, "s": 6733, "text": "Priority Queue in C++ Standard Template Library (STL)" }, { "code": null, "e": 6830, "s": 6787, "text": "Set in C++ Standard Template Library (STL)" }, { "code": null, "e": 6864, "s": 6830, "text": "vector erase() and clear() in C++" }, { "code": null, "e": 6889, "s": 6864, "text": "unordered_map in C++ STL" }, { "code": null, "e": 6906, "s": 6889, "text": "Substring in C++" }, { "code": null, "e": 6941, "s": 6906, "text": "Object Oriented Programming in C++" }, { "code": null, "e": 6981, "s": 6941, "text": "The C++ Standard Template Library (STL)" }, { "code": null, "e": 7000, "s": 6981, "text": "Inheritance in C++" } ]
JavaScript String trim() Method
07 Oct, 2021 Below is the example of the String trim() Method. Example: JavaScript <script>function func() { var str = "GeeksforGeeks "; var st = str.trim(); document.write(st);}func();</script> Output: GeeksForGeeks str.trim() method is used to remove the white spaces from both the ends of the given string. Syntax: str.trim() Return value: This method returns a new string, without any of the leading or the trailing white spaces. Examples for the above method are provided below: Example 1: var str = "GeeksforGeeks "; var st = str.trim(); print(st); Output: GeeksForGeeks In this example the trim() method removes all the leading and the trailing spaces in the string str. Example 2: var str = " GeeksforGeeks"; var st = str.trim(); print(st); Output: GeeksForGeeks In this example the trim() method removes all the leading and the trailing spaces in the string str. Codes for the above method are provided below: Program 1: JavaScript <script>// JavaScript Program to illustrate trim() method function func() { // Original string containing whitespace var str = "GeeksforGeeks "; // Trimmed string var st = str.trim(); document.write(st);} func();</script> Output: GeeksForGeeks Program 2: JavaScript <script>// JavaScript Program to illustrate trim() method function func() { // Original string containing whitespace var str = " GeeksforGeeks"; // Trimmed string var st = str.trim(); document.write(st); }func();</script> Output: GeeksForGeeks str.trimLeft() str.trimLeft() method is used to remove the white spaces from the start of the given string. It does not affect the trailing white spaces. Syntax: str.trimLeft() Return value: This method returns a new string, without any of the leading white spaces. Examples for the above method are provided below: Example 1: var str = " GeeksforGeeks "; var st = str.trimLeft(); print(st); Output: GeeksForGeeks In this example the trimLeft() method removes all the leading spaces, but the trailing spaces in the string str remain as they are. Example 2: var str = " GeeksforGeeks"; var st = str.trim(); print(st); Output: GeeksForGeeks In this example the trimLeft() method removes all the leading spaces from str. Codes for the above method are provided below: Program 1: JavaScript <script>// JavaScript Program to illustrate trimLeft()// function function func() { // Original string containing whitespace var str = "GeeksforGeeks "; // Trimmed string var st = str.trimLeft(); document.write(st); } func();</script> Output: GeeksForGeeks Program 2: JavaScript <script>// JavaScript Program to illustrate trimLeft()// function function func() { // Original string containing whitespace var str = " GeeksforGeeks"; // Trimmed string var st = str.trimLeft(); document.write(st); }func();</script> Output: GeeksForGeeks str.trimRight() str.trimRight() method is used to remove the white spaces from the end of the given string. It does not affect the white spaces at the start of the string. Syntax: str.trimRight() Return value: This method returns a new string, without any of the trailing white spaces. Examples for the above method are provided below: Example 1: var str = "GeeksforGeeks "; var st = str.trimRight(); print(st); Output: GeeksForGeeks In this example the trimRight() method removes all the trailing spaces from the string str. Example 2: var str = " GeeksforGeeks"; var st = str.trimRight(); print(st); Output: GeeksForGeeks In this example the trimRight() method does not remove the leading spaces from str. Codes for the above method are provided below: Program 1: JavaScript // JavaScript Program to illustrate trimRight()// function<script>function func() { // Original string containing whitespace var str = "GeeksforGeeks "; // Trimmed string var st = str.trimRight(); document.write(st); }func();</script> Output: GeeksForGeeks Program 2: JavaScript <script>// JavaScript Program to illustrate trimRight()// function function func() { // Original string containing whitespace var str = " GeeksforGeeks"; // Trimmed string var st = str.trimRight(); document.write(st); } func();</script> Output: GeeksForGeeks Supported Browser: Chrome 4 and above Edge 12 and above Firefox 3.5 and above Internet Explorer 10 and above Opera 10.5 and above Safari 5 and above sweetyty ysachin2314 JavaScript-Methods javascript-string JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between var, let and const keywords in JavaScript Remove elements from a JavaScript Array Differences between Functional Components and Class Components in React Roadmap to Learn JavaScript For Beginners Difference Between PUT and PATCH Request Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ?
[ { "code": null, "e": 52, "s": 24, "text": "\n07 Oct, 2021" }, { "code": null, "e": 103, "s": 52, "text": "Below is the example of the String trim() Method. " }, { "code": null, "e": 112, "s": 103, "text": "Example:" }, { "code": null, "e": 123, "s": 112, "text": "JavaScript" }, { "code": "<script>function func() { var str = \"GeeksforGeeks \"; var st = str.trim(); document.write(st);}func();</script>", "e": 249, "s": 123, "text": null }, { "code": null, "e": 257, "s": 249, "text": "Output:" }, { "code": null, "e": 271, "s": 257, "text": "GeeksForGeeks" }, { "code": null, "e": 364, "s": 271, "text": "str.trim() method is used to remove the white spaces from both the ends of the given string." }, { "code": null, "e": 374, "s": 364, "text": "Syntax: " }, { "code": null, "e": 385, "s": 374, "text": "str.trim()" }, { "code": null, "e": 491, "s": 385, "text": "Return value: This method returns a new string, without any of the leading or the trailing white spaces. " }, { "code": null, "e": 541, "s": 491, "text": "Examples for the above method are provided below:" }, { "code": null, "e": 553, "s": 541, "text": "Example 1: " }, { "code": null, "e": 618, "s": 553, "text": "var str = \"GeeksforGeeks \";\nvar st = str.trim();\nprint(st);" }, { "code": null, "e": 628, "s": 618, "text": "Output: " }, { "code": null, "e": 642, "s": 628, "text": "GeeksForGeeks" }, { "code": null, "e": 743, "s": 642, "text": "In this example the trim() method removes all the leading and the trailing spaces in the string str." }, { "code": null, "e": 756, "s": 743, "text": "Example 2: " }, { "code": null, "e": 818, "s": 756, "text": "var str = \" GeeksforGeeks\";\nvar st = str.trim();\nprint(st);" }, { "code": null, "e": 828, "s": 818, "text": "Output: " }, { "code": null, "e": 842, "s": 828, "text": "GeeksForGeeks" }, { "code": null, "e": 943, "s": 842, "text": "In this example the trim() method removes all the leading and the trailing spaces in the string str." }, { "code": null, "e": 990, "s": 943, "text": "Codes for the above method are provided below:" }, { "code": null, "e": 1003, "s": 990, "text": "Program 1: " }, { "code": null, "e": 1014, "s": 1003, "text": "JavaScript" }, { "code": "<script>// JavaScript Program to illustrate trim() method function func() { // Original string containing whitespace var str = \"GeeksforGeeks \"; // Trimmed string var st = str.trim(); document.write(st);} func();</script>", "e": 1258, "s": 1014, "text": null }, { "code": null, "e": 1267, "s": 1258, "text": "Output: " }, { "code": null, "e": 1281, "s": 1267, "text": "GeeksForGeeks" }, { "code": null, "e": 1294, "s": 1281, "text": "Program 2: " }, { "code": null, "e": 1305, "s": 1294, "text": "JavaScript" }, { "code": "<script>// JavaScript Program to illustrate trim() method function func() { // Original string containing whitespace var str = \" GeeksforGeeks\"; // Trimmed string var st = str.trim(); document.write(st); }func();</script>", "e": 1546, "s": 1305, "text": null }, { "code": null, "e": 1555, "s": 1546, "text": "Output: " }, { "code": null, "e": 1569, "s": 1555, "text": "GeeksForGeeks" }, { "code": null, "e": 1724, "s": 1569, "text": "str.trimLeft() str.trimLeft() method is used to remove the white spaces from the start of the given string. It does not affect the trailing white spaces. " }, { "code": null, "e": 1734, "s": 1724, "text": "Syntax: " }, { "code": null, "e": 1749, "s": 1734, "text": "str.trimLeft()" }, { "code": null, "e": 1839, "s": 1749, "text": "Return value: This method returns a new string, without any of the leading white spaces. " }, { "code": null, "e": 1889, "s": 1839, "text": "Examples for the above method are provided below:" }, { "code": null, "e": 1902, "s": 1889, "text": "Example 1: " }, { "code": null, "e": 1977, "s": 1902, "text": "var str = \" GeeksforGeeks \";\nvar st = str.trimLeft();\nprint(st);" }, { "code": null, "e": 1987, "s": 1977, "text": "Output: " }, { "code": null, "e": 2001, "s": 1987, "text": "GeeksForGeeks" }, { "code": null, "e": 2133, "s": 2001, "text": "In this example the trimLeft() method removes all the leading spaces, but the trailing spaces in the string str remain as they are." }, { "code": null, "e": 2146, "s": 2133, "text": "Example 2: " }, { "code": null, "e": 2208, "s": 2146, "text": "var str = \" GeeksforGeeks\";\nvar st = str.trim();\nprint(st);" }, { "code": null, "e": 2218, "s": 2208, "text": "Output: " }, { "code": null, "e": 2232, "s": 2218, "text": "GeeksForGeeks" }, { "code": null, "e": 2311, "s": 2232, "text": "In this example the trimLeft() method removes all the leading spaces from str." }, { "code": null, "e": 2358, "s": 2311, "text": "Codes for the above method are provided below:" }, { "code": null, "e": 2371, "s": 2358, "text": "Program 1: " }, { "code": null, "e": 2382, "s": 2371, "text": "JavaScript" }, { "code": "<script>// JavaScript Program to illustrate trimLeft()// function function func() { // Original string containing whitespace var str = \"GeeksforGeeks \"; // Trimmed string var st = str.trimLeft(); document.write(st); } func();</script>", "e": 2639, "s": 2382, "text": null }, { "code": null, "e": 2648, "s": 2639, "text": "Output: " }, { "code": null, "e": 2669, "s": 2648, "text": "GeeksForGeeks " }, { "code": null, "e": 2681, "s": 2669, "text": "Program 2: " }, { "code": null, "e": 2692, "s": 2681, "text": "JavaScript" }, { "code": "<script>// JavaScript Program to illustrate trimLeft()// function function func() { // Original string containing whitespace var str = \" GeeksforGeeks\"; // Trimmed string var st = str.trimLeft(); document.write(st); }func();</script>", "e": 2945, "s": 2692, "text": null }, { "code": null, "e": 2954, "s": 2945, "text": "Output: " }, { "code": null, "e": 2968, "s": 2954, "text": "GeeksForGeeks" }, { "code": null, "e": 3140, "s": 2968, "text": "str.trimRight() str.trimRight() method is used to remove the white spaces from the end of the given string. It does not affect the white spaces at the start of the string." }, { "code": null, "e": 3149, "s": 3140, "text": "Syntax: " }, { "code": null, "e": 3165, "s": 3149, "text": "str.trimRight()" }, { "code": null, "e": 3256, "s": 3165, "text": "Return value: This method returns a new string, without any of the trailing white spaces. " }, { "code": null, "e": 3306, "s": 3256, "text": "Examples for the above method are provided below:" }, { "code": null, "e": 3319, "s": 3306, "text": "Example 1: " }, { "code": null, "e": 3389, "s": 3319, "text": "var str = \"GeeksforGeeks \";\nvar st = str.trimRight();\nprint(st);" }, { "code": null, "e": 3399, "s": 3389, "text": "Output: " }, { "code": null, "e": 3413, "s": 3399, "text": "GeeksForGeeks" }, { "code": null, "e": 3505, "s": 3413, "text": "In this example the trimRight() method removes all the trailing spaces from the string str." }, { "code": null, "e": 3518, "s": 3505, "text": "Example 2: " }, { "code": null, "e": 3585, "s": 3518, "text": "var str = \" GeeksforGeeks\";\nvar st = str.trimRight();\nprint(st);" }, { "code": null, "e": 3595, "s": 3585, "text": "Output: " }, { "code": null, "e": 3614, "s": 3595, "text": " GeeksForGeeks" }, { "code": null, "e": 3698, "s": 3614, "text": "In this example the trimRight() method does not remove the leading spaces from str." }, { "code": null, "e": 3745, "s": 3698, "text": "Codes for the above method are provided below:" }, { "code": null, "e": 3758, "s": 3745, "text": "Program 1: " }, { "code": null, "e": 3769, "s": 3758, "text": "JavaScript" }, { "code": "// JavaScript Program to illustrate trimRight()// function<script>function func() { // Original string containing whitespace var str = \"GeeksforGeeks \"; // Trimmed string var st = str.trimRight(); document.write(st); }func();</script>", "e": 4026, "s": 3769, "text": null }, { "code": null, "e": 4035, "s": 4026, "text": "Output: " }, { "code": null, "e": 4056, "s": 4035, "text": "GeeksForGeeks " }, { "code": null, "e": 4068, "s": 4056, "text": "Program 2: " }, { "code": null, "e": 4079, "s": 4068, "text": "JavaScript" }, { "code": "<script>// JavaScript Program to illustrate trimRight()// function function func() { // Original string containing whitespace var str = \" GeeksforGeeks\"; // Trimmed string var st = str.trimRight(); document.write(st); } func();</script>", "e": 4335, "s": 4079, "text": null }, { "code": null, "e": 4344, "s": 4335, "text": "Output: " }, { "code": null, "e": 4363, "s": 4344, "text": " GeeksForGeeks" }, { "code": null, "e": 4384, "s": 4365, "text": "Supported Browser:" }, { "code": null, "e": 4403, "s": 4384, "text": "Chrome 4 and above" }, { "code": null, "e": 4421, "s": 4403, "text": "Edge 12 and above" }, { "code": null, "e": 4443, "s": 4421, "text": "Firefox 3.5 and above" }, { "code": null, "e": 4474, "s": 4443, "text": "Internet Explorer 10 and above" }, { "code": null, "e": 4495, "s": 4474, "text": "Opera 10.5 and above" }, { "code": null, "e": 4514, "s": 4495, "text": "Safari 5 and above" }, { "code": null, "e": 4523, "s": 4514, "text": "sweetyty" }, { "code": null, "e": 4535, "s": 4523, "text": "ysachin2314" }, { "code": null, "e": 4554, "s": 4535, "text": "JavaScript-Methods" }, { "code": null, "e": 4572, "s": 4554, "text": "javascript-string" }, { "code": null, "e": 4583, "s": 4572, "text": "JavaScript" }, { "code": null, "e": 4600, "s": 4583, "text": "Web Technologies" }, { "code": null, "e": 4698, "s": 4600, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4759, "s": 4698, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 4799, "s": 4759, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 4871, "s": 4799, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 4913, "s": 4871, "text": "Roadmap to Learn JavaScript For Beginners" }, { "code": null, "e": 4954, "s": 4913, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 4987, "s": 4954, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 5049, "s": 4987, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 5110, "s": 5049, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 5160, "s": 5110, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Reverse string without using any temporary variable
07 Jul, 2022 We are given a string. We are also given indexes of first and last characters in string. The task is to reverse the string without using any extra variable. Examples: Input : str = "abc" Output : str = "cba" Input : str = "GeeksforGeeks" Output : str = "skeeGrofskeeG" If we take a look at program to reverse a string or array, all we need to do is swap two characters. The idea is to use XOR for swapping the variable. Below is the implementation of the idea. C++ Java Python3 C# Javascript // C++ Program to reverse a string without// using temp variable#include <bits/stdc++.h>using namespace std; // Function to reverse string and return reversed stringstring reversingString(string str, int start, int end){ // Iterate loop upto start not equal to end while (start < end) { // XOR for swapping the variable str[start] ^= str[end]; str[end] ^= str[start]; str[start] ^= str[end]; ++start; --end; } return str;} // Driver Codeint main(){ string s = "GeeksforGeeks"; cout << reversingString(s, 0, 12); return 0;} // Java Program to reverse a string without// using temp variableimport java.util.*; class GFG { // Function to reverse string and// return reversed stringstatic String reversingString(char []str, int start, int end){ // Iterate loop upto start not equal to end while (start < end) { // XOR for swapping the variable str[start] ^= str[end]; str[end] ^= str[start]; str[start] ^= str[end]; ++start; --end; } return String.valueOf(str);} // Driver Codepublic static void main(String[] args) { String s = "GeeksforGeeks"; System.out.println(reversingString (s.toCharArray(), 0, 12));}} // This code is contributed by 29AjayKumar # Python3 Program to reverse a string # without using temp variable # Function to reverse string and # return reversed stringdef reversingString(str, start, end): # Iterate loop upto start not equal to end while (start < end): # XOR for swapping the variable str = (str[:start] + chr(ord(str[start]) ^ ord(str[end])) + str[start + 1:]); str = (str[:end] + chr(ord(str[start]) ^ ord(str[end])) + str[end + 1:]); str = (str[:start] + chr(ord(str[start]) ^ ord(str[end])) + str[start + 1:]); start += 1; end -= 1; return str; # Driver Codes = "GeeksforGeeks";print(reversingString(s, 0, 12)); # This code is contributed by 29AjayKumar // C# Program to reverse a string without// using temp variableusing System; class GFG { // Function to reverse string and// return reversed stringstatic String reversingString(char []str, int start, int end){ // Iterate loop upto start // not equal to end while (start < end) { // XOR for swapping the variable str[start] ^= str[end]; str[end] ^= str[start]; str[start] ^= str[end]; ++start; --end; } return String.Join("", str);} // Driver Codepublic static void Main(String[] args) { String s = "GeeksforGeeks"; Console.WriteLine(reversingString (s.ToCharArray(), 0, 12));}} // This code is contributed by 29AjayKumar <script> // Javascript program to reverse a string// without using temp variable // Function to reverse string and// return reversed stringfunction reversingString(str, start, end){ // Iterate loop upto start not // equal to end while (start < end) { // XOR for swapping the variable str[start] = String.fromCharCode( str[start].charCodeAt(0) ^ str[end].charCodeAt(0)); str[end] = String.fromCharCode( str[end].charCodeAt(0) ^ str[start].charCodeAt(0)); str[start] = String.fromCharCode( str[start].charCodeAt(0) ^ str[end].charCodeAt(0)); ++start; --end; } return(str).join("");} // Driver Codelet s = "GeeksforGeeks";document.write(reversingString( s.split(""), 0, 12)); // This code is contributed by rag2127 </script> Output: skeeGrofskeeG Time Complexity: O(n) Auxiliary Space: O(1) Chapters descriptions off, selected captions settings, opens captions settings dialog captions off, selected English default, selected This is a modal window. Beginning of dialog window. Escape will cancel and close the window. End of dialog window. If we are allowed to library function, we can also use the idea discussed in quickly reverse a string in C++. We don’t even need indexes of first and last characters. C++ Java Python3 C# Javascript // Reversing a string using reverse()#include<bits/stdc++.h>using namespace std; int main(){ string str = "geeksforgeeks"; // Reverse str[begin..end] reverse(str.begin(), str.end()); cout << str; return 0;} // Reversing a string using reverse()class GFG {public static void main(String[] args){ StringBuilder str = new StringBuilder("geeksforgeeks"); // Reverse str[begin..end] str.reverse(); System.out.println(str);}} // This code is contributed // by PrinciRaj1992 # Reversing a string using reverse()str = "geeksforgeeks"; # Reverse str[begin..end]str = "".join(reversed(str)) print(str); # This code is contributed by 29AjayKumar // Reversing a string using reverse()using System;using System.Linq; class GFG {public static void Main(String[] args){ String str = "geeksforgeeks"; // Reverse str[begin..end] str = new string(str.Reverse().ToArray()); Console.WriteLine(str);}} // This code is contributed by 29AjayKumar <script> // Reversing a string using reverse() function reverseString(str) { return str.split("").reverse().join(""); } var str = ("geeksforgeeks"); document.write(reverseString(str)); // This code is contributed by todaysgaurav </script> Output: skeegrofskeeg Time complexity : O(n) Auxiliary Space : O(1) This article is contributed by Aarti_Rathi and Mr. Somesh Awasthi. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. 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. princiraj1992 29AjayKumar todaysgaurav rag2127 simmytarika5 adnanirshad158 a7977370173 codewithrathi Bitwise-XOR Strings Strings Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Top 50 String Coding Problems for Interviews What is Data Structure: Types, Classifications and Applications Print all the duplicates in the input string Print all subsequences of a string A Program to check if strings are rotations of each other or not String class in Java | Set 1 Find if a string is interleaved of two other strings | DP-33 Remove first and last character of a string in Java Find the smallest window in a string containing all characters of another string Program to count occurrence of a given character in a string
[ { "code": null, "e": 54, "s": 26, "text": "\n07 Jul, 2022" }, { "code": null, "e": 211, "s": 54, "text": "We are given a string. We are also given indexes of first and last characters in string. The task is to reverse the string without using any extra variable." }, { "code": null, "e": 222, "s": 211, "text": "Examples: " }, { "code": null, "e": 328, "s": 222, "text": "Input : str = \"abc\"\nOutput : str = \"cba\" \n\nInput : str = \"GeeksforGeeks\"\nOutput : str = \"skeeGrofskeeG\"" }, { "code": null, "e": 522, "s": 328, "text": "If we take a look at program to reverse a string or array, all we need to do is swap two characters. The idea is to use XOR for swapping the variable. Below is the implementation of the idea. " }, { "code": null, "e": 526, "s": 522, "text": "C++" }, { "code": null, "e": 531, "s": 526, "text": "Java" }, { "code": null, "e": 539, "s": 531, "text": "Python3" }, { "code": null, "e": 542, "s": 539, "text": "C#" }, { "code": null, "e": 553, "s": 542, "text": "Javascript" }, { "code": "// C++ Program to reverse a string without// using temp variable#include <bits/stdc++.h>using namespace std; // Function to reverse string and return reversed stringstring reversingString(string str, int start, int end){ // Iterate loop upto start not equal to end while (start < end) { // XOR for swapping the variable str[start] ^= str[end]; str[end] ^= str[start]; str[start] ^= str[end]; ++start; --end; } return str;} // Driver Codeint main(){ string s = \"GeeksforGeeks\"; cout << reversingString(s, 0, 12); return 0;}", "e": 1146, "s": 553, "text": null }, { "code": "// Java Program to reverse a string without// using temp variableimport java.util.*; class GFG { // Function to reverse string and// return reversed stringstatic String reversingString(char []str, int start, int end){ // Iterate loop upto start not equal to end while (start < end) { // XOR for swapping the variable str[start] ^= str[end]; str[end] ^= str[start]; str[start] ^= str[end]; ++start; --end; } return String.valueOf(str);} // Driver Codepublic static void main(String[] args) { String s = \"GeeksforGeeks\"; System.out.println(reversingString (s.toCharArray(), 0, 12));}} // This code is contributed by 29AjayKumar", "e": 1923, "s": 1146, "text": null }, { "code": "# Python3 Program to reverse a string # without using temp variable # Function to reverse string and # return reversed stringdef reversingString(str, start, end): # Iterate loop upto start not equal to end while (start < end): # XOR for swapping the variable str = (str[:start] + chr(ord(str[start]) ^ ord(str[end])) + str[start + 1:]); str = (str[:end] + chr(ord(str[start]) ^ ord(str[end])) + str[end + 1:]); str = (str[:start] + chr(ord(str[start]) ^ ord(str[end])) + str[start + 1:]); start += 1; end -= 1; return str; # Driver Codes = \"GeeksforGeeks\";print(reversingString(s, 0, 12)); # This code is contributed by 29AjayKumar", "e": 2813, "s": 1923, "text": null }, { "code": "// C# Program to reverse a string without// using temp variableusing System; class GFG { // Function to reverse string and// return reversed stringstatic String reversingString(char []str, int start, int end){ // Iterate loop upto start // not equal to end while (start < end) { // XOR for swapping the variable str[start] ^= str[end]; str[end] ^= str[start]; str[start] ^= str[end]; ++start; --end; } return String.Join(\"\", str);} // Driver Codepublic static void Main(String[] args) { String s = \"GeeksforGeeks\"; Console.WriteLine(reversingString (s.ToCharArray(), 0, 12));}} // This code is contributed by 29AjayKumar", "e": 3590, "s": 2813, "text": null }, { "code": "<script> // Javascript program to reverse a string// without using temp variable // Function to reverse string and// return reversed stringfunction reversingString(str, start, end){ // Iterate loop upto start not // equal to end while (start < end) { // XOR for swapping the variable str[start] = String.fromCharCode( str[start].charCodeAt(0) ^ str[end].charCodeAt(0)); str[end] = String.fromCharCode( str[end].charCodeAt(0) ^ str[start].charCodeAt(0)); str[start] = String.fromCharCode( str[start].charCodeAt(0) ^ str[end].charCodeAt(0)); ++start; --end; } return(str).join(\"\");} // Driver Codelet s = \"GeeksforGeeks\";document.write(reversingString( s.split(\"\"), 0, 12)); // This code is contributed by rag2127 </script>", "e": 4479, "s": 3590, "text": null }, { "code": null, "e": 4488, "s": 4479, "text": "Output: " }, { "code": null, "e": 4502, "s": 4488, "text": "skeeGrofskeeG" }, { "code": null, "e": 4546, "s": 4502, "text": "Time Complexity: O(n) Auxiliary Space: O(1)" }, { "code": null, "e": 4555, "s": 4546, "text": "Chapters" }, { "code": null, "e": 4582, "s": 4555, "text": "descriptions off, selected" }, { "code": null, "e": 4632, "s": 4582, "text": "captions settings, opens captions settings dialog" }, { "code": null, "e": 4655, "s": 4632, "text": "captions off, selected" }, { "code": null, "e": 4663, "s": 4655, "text": "English" }, { "code": null, "e": 4681, "s": 4663, "text": "default, selected" }, { "code": null, "e": 4705, "s": 4681, "text": "This is a modal window." }, { "code": null, "e": 4774, "s": 4705, "text": "Beginning of dialog window. Escape will cancel and close the window." }, { "code": null, "e": 4796, "s": 4774, "text": "End of dialog window." }, { "code": null, "e": 4964, "s": 4796, "text": "If we are allowed to library function, we can also use the idea discussed in quickly reverse a string in C++. We don’t even need indexes of first and last characters. " }, { "code": null, "e": 4968, "s": 4964, "text": "C++" }, { "code": null, "e": 4973, "s": 4968, "text": "Java" }, { "code": null, "e": 4981, "s": 4973, "text": "Python3" }, { "code": null, "e": 4984, "s": 4981, "text": "C#" }, { "code": null, "e": 4995, "s": 4984, "text": "Javascript" }, { "code": "// Reversing a string using reverse()#include<bits/stdc++.h>using namespace std; int main(){ string str = \"geeksforgeeks\"; // Reverse str[begin..end] reverse(str.begin(), str.end()); cout << str; return 0;}", "e": 5225, "s": 4995, "text": null }, { "code": "// Reversing a string using reverse()class GFG {public static void main(String[] args){ StringBuilder str = new StringBuilder(\"geeksforgeeks\"); // Reverse str[begin..end] str.reverse(); System.out.println(str);}} // This code is contributed // by PrinciRaj1992", "e": 5505, "s": 5225, "text": null }, { "code": "# Reversing a string using reverse()str = \"geeksforgeeks\"; # Reverse str[begin..end]str = \"\".join(reversed(str)) print(str); # This code is contributed by 29AjayKumar", "e": 5683, "s": 5505, "text": null }, { "code": "// Reversing a string using reverse()using System;using System.Linq; class GFG {public static void Main(String[] args){ String str = \"geeksforgeeks\"; // Reverse str[begin..end] str = new string(str.Reverse().ToArray()); Console.WriteLine(str);}} // This code is contributed by 29AjayKumar", "e": 6009, "s": 5683, "text": null }, { "code": "<script> // Reversing a string using reverse() function reverseString(str) { return str.split(\"\").reverse().join(\"\"); } var str = (\"geeksforgeeks\"); document.write(reverseString(str)); // This code is contributed by todaysgaurav </script>", "e": 6290, "s": 6009, "text": null }, { "code": null, "e": 6299, "s": 6290, "text": "Output: " }, { "code": null, "e": 6313, "s": 6299, "text": "skeegrofskeeg" }, { "code": null, "e": 6359, "s": 6313, "text": "Time complexity : O(n) Auxiliary Space : O(1)" }, { "code": null, "e": 6802, "s": 6359, "text": "This article is contributed by Aarti_Rathi and Mr. Somesh Awasthi. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. 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": 6818, "s": 6804, "text": "princiraj1992" }, { "code": null, "e": 6830, "s": 6818, "text": "29AjayKumar" }, { "code": null, "e": 6843, "s": 6830, "text": "todaysgaurav" }, { "code": null, "e": 6851, "s": 6843, "text": "rag2127" }, { "code": null, "e": 6864, "s": 6851, "text": "simmytarika5" }, { "code": null, "e": 6879, "s": 6864, "text": "adnanirshad158" }, { "code": null, "e": 6891, "s": 6879, "text": "a7977370173" }, { "code": null, "e": 6905, "s": 6891, "text": "codewithrathi" }, { "code": null, "e": 6917, "s": 6905, "text": "Bitwise-XOR" }, { "code": null, "e": 6925, "s": 6917, "text": "Strings" }, { "code": null, "e": 6933, "s": 6925, "text": "Strings" }, { "code": null, "e": 7031, "s": 6933, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 7076, "s": 7031, "text": "Top 50 String Coding Problems for Interviews" }, { "code": null, "e": 7140, "s": 7076, "text": "What is Data Structure: Types, Classifications and Applications" }, { "code": null, "e": 7185, "s": 7140, "text": "Print all the duplicates in the input string" }, { "code": null, "e": 7220, "s": 7185, "text": "Print all subsequences of a string" }, { "code": null, "e": 7285, "s": 7220, "text": "A Program to check if strings are rotations of each other or not" }, { "code": null, "e": 7314, "s": 7285, "text": "String class in Java | Set 1" }, { "code": null, "e": 7375, "s": 7314, "text": "Find if a string is interleaved of two other strings | DP-33" }, { "code": null, "e": 7427, "s": 7375, "text": "Remove first and last character of a string in Java" }, { "code": null, "e": 7508, "s": 7427, "text": "Find the smallest window in a string containing all characters of another string" } ]
Elasticsearch meets BERT: Building Search Engine with Elasticsearch and BERT | by Hironsan | Towards Data Science
In this post, we use a pre-trained BERT model and Elasticsearch to build a search engine. Elasticsearch has recently released text similarity search with vector fields. On the other hand, you can convert text into a fixed-length vector using BERT. So once we convert documents into vectors by BERT and store them into Elasticsearch, we can search similar documents with Elasticsearch and BERT. This post implements a search engine with Elasticsearch and BERT by the following architecture. Here, we use Docker to divide the whole system into three parts: application, BERT, and Elasticsearch. The purpose is to make it easier to scale each service. I show you only important part in this post, but the entire system is written in docker-compose.yamlin the following GitHub repository. Please take a look at the repository: https://github.com/Hironsan/bertsearch The plan for this post is: Download a pre-trained BERT modelSetting environment variablesLaunching Docker containerCreating Elasticsearch indexCreating documentsIndexing document Download a pre-trained BERT model Setting environment variables Launching Docker container Creating Elasticsearch index Creating documents Indexing document First, download a pre-trained BERT model. The following command is an example of downloading an English model: $ wget https://storage.googleapis.com/bert_models/2018_10_18/cased_L-12_H-768_A-12.zip$ unzip cased_L-12_H-768_A-12.zip You need to set a pre-trained BERT model and Elasticsearch’s index name as environment variables. These variables are used in Docker containers. Below is an example that specifies jobsearch as index name and ./cased_L-12_H-768_A-12 as model’s path: $ export PATH_MODEL=./cased_L-12_H-768_A-12$ export INDEX_NAME=jobsearch Now, let’s launch Docker containers by using Docker compose. There are three containers to launch here: application container, BERT container, and Elasticsearch container. Check docker-compose.yaml for more details. $ docker-compose up Note that I recommend you that you should assign more memory(over 8GB) to Docker. Because BERT container needs large memory. You can use the create index API to add a new index to an Elasticsearch cluster. When creating an index, you can specify the following: Settings for the index Mappings for fields in the index Index aliases For example, if you want to create jobsearch index with title, text and text_vector fields, you can create the index by the following command: $ python example/create_index.py --index_file=example/index.json --index_name=jobsearch# index.json{ "settings": { "number_of_shards": 2, "number_of_replicas": 1 }, "mappings": { "dynamic": "true", "_source": { "enabled": "true" }, "properties": { "title": { "type": "text" }, "text": { "type": "text" }, "text_vector": { "type": "dense_vector", "dims": 768 } } }} CAUTION: The dims value of text_vector must need to match the dims of a pre-trained BERT model. Once you created an index, you’re ready to index some document. The point here is to convert your document into a vector using BERT. The resulting vector is stored in the text_vector field. Let’s convert your data into a JSON document: $ python example/create_documents.py --data=example/example.csv --index_name=jobsearch# example/example.csv"Title","Description""Saleswoman","lorem ipsum""Software Developer","lorem ipsum""Chief Financial Officer","lorem ipsum""General Manager","lorem ipsum""Network Administrator","lorem ipsum" After finishing the script, you can get a JSON document like follows: # documents.jsonl{"_op_type": "index", "_index": "jobsearch", "text": "lorem ipsum", "title": "Saleswoman", "text_vector": [...]}{"_op_type": "index", "_index": "jobsearch", "text": "lorem ipsum", "title": "Software Developer", "text_vector": [...]}{"_op_type": "index", "_index": "jobsearch", "text": "lorem ipsum", "title": "Chief Financial Officer", "text_vector": [...]}... After converting your data into a JSON, you can add a JSON document to the specified index and makes it searchable. $ python example/index_documents.py Go to http://127.0.0.1:5000. Below is an example of a job search. You can see that the “I’m looking for a lawyer” query returns jobs like “Legal assistant” and “Lawyer”. In this post, we implemented the search engine with Elasticsearch and BERT. Although there is a problem with the execution speed of BERT, it is easy to scale by treating BERT as an independent container like this architecture, so I think that the problem can be solved. I hope this article will be useful to you.
[ { "code": null, "e": 566, "s": 172, "text": "In this post, we use a pre-trained BERT model and Elasticsearch to build a search engine. Elasticsearch has recently released text similarity search with vector fields. On the other hand, you can convert text into a fixed-length vector using BERT. So once we convert documents into vectors by BERT and store them into Elasticsearch, we can search similar documents with Elasticsearch and BERT." }, { "code": null, "e": 821, "s": 566, "text": "This post implements a search engine with Elasticsearch and BERT by the following architecture. Here, we use Docker to divide the whole system into three parts: application, BERT, and Elasticsearch. The purpose is to make it easier to scale each service." }, { "code": null, "e": 995, "s": 821, "text": "I show you only important part in this post, but the entire system is written in docker-compose.yamlin the following GitHub repository. Please take a look at the repository:" }, { "code": null, "e": 1034, "s": 995, "text": "https://github.com/Hironsan/bertsearch" }, { "code": null, "e": 1061, "s": 1034, "text": "The plan for this post is:" }, { "code": null, "e": 1213, "s": 1061, "text": "Download a pre-trained BERT modelSetting environment variablesLaunching Docker containerCreating Elasticsearch indexCreating documentsIndexing document" }, { "code": null, "e": 1247, "s": 1213, "text": "Download a pre-trained BERT model" }, { "code": null, "e": 1277, "s": 1247, "text": "Setting environment variables" }, { "code": null, "e": 1304, "s": 1277, "text": "Launching Docker container" }, { "code": null, "e": 1333, "s": 1304, "text": "Creating Elasticsearch index" }, { "code": null, "e": 1352, "s": 1333, "text": "Creating documents" }, { "code": null, "e": 1370, "s": 1352, "text": "Indexing document" }, { "code": null, "e": 1481, "s": 1370, "text": "First, download a pre-trained BERT model. The following command is an example of downloading an English model:" }, { "code": null, "e": 1601, "s": 1481, "text": "$ wget https://storage.googleapis.com/bert_models/2018_10_18/cased_L-12_H-768_A-12.zip$ unzip cased_L-12_H-768_A-12.zip" }, { "code": null, "e": 1850, "s": 1601, "text": "You need to set a pre-trained BERT model and Elasticsearch’s index name as environment variables. These variables are used in Docker containers. Below is an example that specifies jobsearch as index name and ./cased_L-12_H-768_A-12 as model’s path:" }, { "code": null, "e": 1923, "s": 1850, "text": "$ export PATH_MODEL=./cased_L-12_H-768_A-12$ export INDEX_NAME=jobsearch" }, { "code": null, "e": 2139, "s": 1923, "text": "Now, let’s launch Docker containers by using Docker compose. There are three containers to launch here: application container, BERT container, and Elasticsearch container. Check docker-compose.yaml for more details." }, { "code": null, "e": 2159, "s": 2139, "text": "$ docker-compose up" }, { "code": null, "e": 2284, "s": 2159, "text": "Note that I recommend you that you should assign more memory(over 8GB) to Docker. Because BERT container needs large memory." }, { "code": null, "e": 2420, "s": 2284, "text": "You can use the create index API to add a new index to an Elasticsearch cluster. When creating an index, you can specify the following:" }, { "code": null, "e": 2443, "s": 2420, "text": "Settings for the index" }, { "code": null, "e": 2476, "s": 2443, "text": "Mappings for fields in the index" }, { "code": null, "e": 2490, "s": 2476, "text": "Index aliases" }, { "code": null, "e": 2633, "s": 2490, "text": "For example, if you want to create jobsearch index with title, text and text_vector fields, you can create the index by the following command:" }, { "code": null, "e": 3086, "s": 2633, "text": "$ python example/create_index.py --index_file=example/index.json --index_name=jobsearch# index.json{ \"settings\": { \"number_of_shards\": 2, \"number_of_replicas\": 1 }, \"mappings\": { \"dynamic\": \"true\", \"_source\": { \"enabled\": \"true\" }, \"properties\": { \"title\": { \"type\": \"text\" }, \"text\": { \"type\": \"text\" }, \"text_vector\": { \"type\": \"dense_vector\", \"dims\": 768 } } }}" }, { "code": null, "e": 3182, "s": 3086, "text": "CAUTION: The dims value of text_vector must need to match the dims of a pre-trained BERT model." }, { "code": null, "e": 3418, "s": 3182, "text": "Once you created an index, you’re ready to index some document. The point here is to convert your document into a vector using BERT. The resulting vector is stored in the text_vector field. Let’s convert your data into a JSON document:" }, { "code": null, "e": 3714, "s": 3418, "text": "$ python example/create_documents.py --data=example/example.csv --index_name=jobsearch# example/example.csv\"Title\",\"Description\"\"Saleswoman\",\"lorem ipsum\"\"Software Developer\",\"lorem ipsum\"\"Chief Financial Officer\",\"lorem ipsum\"\"General Manager\",\"lorem ipsum\"\"Network Administrator\",\"lorem ipsum\"" }, { "code": null, "e": 3784, "s": 3714, "text": "After finishing the script, you can get a JSON document like follows:" }, { "code": null, "e": 4162, "s": 3784, "text": "# documents.jsonl{\"_op_type\": \"index\", \"_index\": \"jobsearch\", \"text\": \"lorem ipsum\", \"title\": \"Saleswoman\", \"text_vector\": [...]}{\"_op_type\": \"index\", \"_index\": \"jobsearch\", \"text\": \"lorem ipsum\", \"title\": \"Software Developer\", \"text_vector\": [...]}{\"_op_type\": \"index\", \"_index\": \"jobsearch\", \"text\": \"lorem ipsum\", \"title\": \"Chief Financial Officer\", \"text_vector\": [...]}..." }, { "code": null, "e": 4278, "s": 4162, "text": "After converting your data into a JSON, you can add a JSON document to the specified index and makes it searchable." }, { "code": null, "e": 4314, "s": 4278, "text": "$ python example/index_documents.py" }, { "code": null, "e": 4484, "s": 4314, "text": "Go to http://127.0.0.1:5000. Below is an example of a job search. You can see that the “I’m looking for a lawyer” query returns jobs like “Legal assistant” and “Lawyer”." } ]
Java program to find the sum of elements of an array
To find the sum of elements of an array. create an empty variable. (sum) Initialize it with 0 in a loop. Traverse through each element (or get each element from the user) add each element to sum. Print sum. import java.util.Arrays; import java.util.Scanner; public class SumOfElementsOfAnArray { public static void main(String args[]){ System.out.println("Enter the required size of the array :: "); Scanner s = new Scanner(System.in); int size = s.nextInt(); int myArray[] = new int [size]; int sum = 0; System.out.println("Enter the elements of the array one by one "); for(int i=0; i<size; i++){ myArray[i] = s.nextInt(); sum = sum + myArray[i]; } System.out.println("Elements of the array are: "+Arrays.toString(myArray)); System.out.println("Sum of the elements of the array ::"+sum); } } Enter the required size of the array :: 5 Enter the elements of the array one by one 45 12 55 78 445 Elements of the array are: [45, 12, 55, 78, 445] Sum of the elements of the array ::635
[ { "code": null, "e": 1103, "s": 1062, "text": "To find the sum of elements of an array." }, { "code": null, "e": 1135, "s": 1103, "text": "create an empty variable. (sum)" }, { "code": null, "e": 1167, "s": 1135, "text": "Initialize it with 0 in a loop." }, { "code": null, "e": 1258, "s": 1167, "text": "Traverse through each element (or get each element from the user) add each element to sum." }, { "code": null, "e": 1269, "s": 1258, "text": "Print sum." }, { "code": null, "e": 1941, "s": 1269, "text": "import java.util.Arrays;\nimport java.util.Scanner;\npublic class SumOfElementsOfAnArray {\n public static void main(String args[]){\n System.out.println(\"Enter the required size of the array :: \");\n Scanner s = new Scanner(System.in);\n int size = s.nextInt();\n int myArray[] = new int [size];\n int sum = 0;\n System.out.println(\"Enter the elements of the array one by one \");\n\n for(int i=0; i<size; i++){\n myArray[i] = s.nextInt();\n sum = sum + myArray[i];\n }\n System.out.println(\"Elements of the array are: \"+Arrays.toString(myArray));\n System.out.println(\"Sum of the elements of the array ::\"+sum);\n }\n}" }, { "code": null, "e": 2130, "s": 1941, "text": "Enter the required size of the array ::\n5\nEnter the elements of the array one by one\n45\n12\n55\n78\n445\nElements of the array are: [45, 12, 55, 78, 445]\nSum of the elements of the array ::635" } ]
Area of the largest square that can be formed from the given length sticks using Hashing - GeeksforGeeks
06 Apr, 2021 Given an array arr[] of N integers representing the heights of the sticks. The task is to find the area of the largest square that can be formed using these sticks and the count of such squares. Note that a single side of the square can only use a single stick.Examples: Input: arr[] = {5, 3, 2, 3, 6, 3, 3} Output: Area = 9 Count = 1 Side of the square will be 3 and only one such square is possible.Input: arr[] = {2, 2, 2, 9, 2, 2, 2, 2, 2} Output: Area = 4 Count = 2 Approach: Count the frequencies of all the elements of the array. Now, starting from the maximum (in order to maximize the area) find the first frequency which is at least 4 so that a square can be formed then the area can be calculated as freq[i] * freq[i] and the count of such squares will be freq[i] / 4.Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to find the area of the largest// square that can be formed// and the count of such squaresvoid findMaxSquare(int arr[], int n){ // Maximum value from the array int maxVal = *max_element(arr, arr + n); // Update the frequencies of // the array elements int freq[maxVal + 1] = { 0 }; for (int i = 0; i < n; i++) freq[arr[i]]++; // Starting from the maximum length sticks // in order to maximize the area for (int i = maxVal; i > 0; i--) { // The count of sticks with the current // length has to be at least 4 // in order to form a square if (freq[i] >= 4) { cout << "Area = " << (pow(i, 2)); cout << "\nCount = " << (freq[i] / 4); return; } } // Impossible to form a square cout << "-1";} // Driver codeint main(){ int arr[] = { 2, 2, 2, 9, 2, 2, 2, 2, 2 }; int n = sizeof(arr) / sizeof(arr[0]); findMaxSquare(arr, n); return 0;} // Java implementation of the approachimport java.util.*; class GFG{ // Function to find the area of the largest// square that can be formed// and the count of such squaresstatic void findMaxSquare(int arr[], int n){ // Maximum value from the array int maxVal = Arrays.stream(arr).max().getAsInt(); // Update the frequencies of // the array elements int []freq = new int[maxVal + 1]; for (int i = 0; i < n; i++) freq[arr[i]]++; // Starting from the maximum length sticks // in order to maximize the area for (int i = maxVal; i > 0; i--) { // The count of sticks with the current // length has to be at least 4 // in order to form a square if (freq[i] >= 4) { System.out.print("Area = " + (Math.pow(i, 2))); System.out.print("\nCount = " + (freq[i] / 4)); return; } } // Impossible to form a square System.out.print("-1");} // Driver codepublic static void main(String[] args){ int arr[] = { 2, 2, 2, 9, 2, 2, 2, 2, 2 }; int n = arr.length; findMaxSquare(arr, n);}} // This code is contributed by Princi Singh # Python3 implementation of the approach # Function to find the area of the largest# square that can be formed# and the count of such squaresdef findMaxSquare(arr, n) : # Maximum value from the array maxVal = max(arr); # Update the frequencies of # the array elements freq = [0] * (maxVal + 1) ; for i in range(n) : freq[arr[i]] += 1; # Starting from the maximum length sticks # in order to maximize the area for i in range(maxVal, 0, -1) : # The count of sticks with the current # length has to be at least 4 # in order to form a square if (freq[i] >= 4) : print("Area = ", pow(i, 2)); print("Count =", freq[i] // 4); return; # Impossible to form a square print("-1"); # Driver codeif __name__ == "__main__" : arr = [ 2, 2, 2, 9, 2, 2, 2, 2, 2 ]; n = len(arr); findMaxSquare(arr, n); # This code is contributed by AnkitRai01 // C# implementation of the approachusing System;using System.Linq; class GFG{ // Function to find the area of the largest// square that can be formed// and the count of such squaresstatic void findMaxSquare(int []arr, int n){ // Maximum value from the array int maxVal = arr.Max(); // Update the frequencies of // the array elements int []freq = new int[maxVal + 1]; for (int i = 0; i < n; i++) freq[arr[i]]++; // Starting from the maximum length sticks // in order to maximize the area for (int i = maxVal; i > 0; i--) { // The count of sticks with the current // length has to be at least 4 // in order to form a square if (freq[i] >= 4) { Console.Write("Area = " + (Math.Pow(i, 2))); Console.Write("\nCount = " + (freq[i] / 4)); return; } } // Impossible to form a square Console.Write("-1");} // Driver codepublic static void Main(String[] args){ int []arr = { 2, 2, 2, 9, 2, 2, 2, 2, 2 }; int n = arr.Length; findMaxSquare(arr, n);}} // This code is contributed by 29AjayKumar <script> // Javascript implementation of the approach // Function to find the area of the largest// square that can be formed// and the count of such squaresfunction findMaxSquare(arr, n){ // Maximum value from the array var maxVal = Math.max(...arr); // Update the frequencies of // the array elements var freq = Array(maxVal + 1).fill(0); for (var i = 0; i < n; i++) freq[arr[i]]++; // Starting from the maximum length sticks // in order to maximize the area for (var i = maxVal; i > 0; i--) { // The count of sticks with the current // length has to be at least 4 // in order to form a square if (freq[i] >= 4) { document.write("Area = " + (Math.pow(i, 2))); document.write("<br>Count = " + (freq[i] / 4)); return; } } // Impossible to form a square document.write("-1");} // Driver codevar arr = [ 2, 2, 2, 9, 2, 2, 2, 2, 2 ];var n = arr.length;findMaxSquare(arr, n); </script> Area = 4 Count = 2 Time Complexity: O(n) Auxiliary Space: O(n) ankthon princi singh 29AjayKumar subham348 rrrtnx frequency-counting Arrays Hash Arrays Hash Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Stack Data Structure (Introduction and Program) Multidimensional Arrays in Java Queue | Set 1 (Introduction and Array Implementation) Linear Search Python | Using 2D arrays/lists the right way Hashing | Set 1 (Introduction) Quadratic Probing in Hashing Hashing | Set 3 (Open Addressing) Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum) Internal Working of HashMap in Java
[ { "code": null, "e": 24411, "s": 24383, "text": "\n06 Apr, 2021" }, { "code": null, "e": 24683, "s": 24411, "text": "Given an array arr[] of N integers representing the heights of the sticks. The task is to find the area of the largest square that can be formed using these sticks and the count of such squares. Note that a single side of the square can only use a single stick.Examples: " }, { "code": null, "e": 24884, "s": 24683, "text": "Input: arr[] = {5, 3, 2, 3, 6, 3, 3} Output: Area = 9 Count = 1 Side of the square will be 3 and only one such square is possible.Input: arr[] = {2, 2, 2, 9, 2, 2, 2, 2, 2} Output: Area = 4 Count = 2 " }, { "code": null, "e": 25244, "s": 24884, "text": "Approach: Count the frequencies of all the elements of the array. Now, starting from the maximum (in order to maximize the area) find the first frequency which is at least 4 so that a square can be formed then the area can be calculated as freq[i] * freq[i] and the count of such squares will be freq[i] / 4.Below is the implementation of the above approach: " }, { "code": null, "e": 25248, "s": 25244, "text": "C++" }, { "code": null, "e": 25253, "s": 25248, "text": "Java" }, { "code": null, "e": 25261, "s": 25253, "text": "Python3" }, { "code": null, "e": 25264, "s": 25261, "text": "C#" }, { "code": null, "e": 25275, "s": 25264, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to find the area of the largest// square that can be formed// and the count of such squaresvoid findMaxSquare(int arr[], int n){ // Maximum value from the array int maxVal = *max_element(arr, arr + n); // Update the frequencies of // the array elements int freq[maxVal + 1] = { 0 }; for (int i = 0; i < n; i++) freq[arr[i]]++; // Starting from the maximum length sticks // in order to maximize the area for (int i = maxVal; i > 0; i--) { // The count of sticks with the current // length has to be at least 4 // in order to form a square if (freq[i] >= 4) { cout << \"Area = \" << (pow(i, 2)); cout << \"\\nCount = \" << (freq[i] / 4); return; } } // Impossible to form a square cout << \"-1\";} // Driver codeint main(){ int arr[] = { 2, 2, 2, 9, 2, 2, 2, 2, 2 }; int n = sizeof(arr) / sizeof(arr[0]); findMaxSquare(arr, n); return 0;}", "e": 26329, "s": 25275, "text": null }, { "code": "// Java implementation of the approachimport java.util.*; class GFG{ // Function to find the area of the largest// square that can be formed// and the count of such squaresstatic void findMaxSquare(int arr[], int n){ // Maximum value from the array int maxVal = Arrays.stream(arr).max().getAsInt(); // Update the frequencies of // the array elements int []freq = new int[maxVal + 1]; for (int i = 0; i < n; i++) freq[arr[i]]++; // Starting from the maximum length sticks // in order to maximize the area for (int i = maxVal; i > 0; i--) { // The count of sticks with the current // length has to be at least 4 // in order to form a square if (freq[i] >= 4) { System.out.print(\"Area = \" + (Math.pow(i, 2))); System.out.print(\"\\nCount = \" + (freq[i] / 4)); return; } } // Impossible to form a square System.out.print(\"-1\");} // Driver codepublic static void main(String[] args){ int arr[] = { 2, 2, 2, 9, 2, 2, 2, 2, 2 }; int n = arr.length; findMaxSquare(arr, n);}} // This code is contributed by Princi Singh", "e": 27528, "s": 26329, "text": null }, { "code": "# Python3 implementation of the approach # Function to find the area of the largest# square that can be formed# and the count of such squaresdef findMaxSquare(arr, n) : # Maximum value from the array maxVal = max(arr); # Update the frequencies of # the array elements freq = [0] * (maxVal + 1) ; for i in range(n) : freq[arr[i]] += 1; # Starting from the maximum length sticks # in order to maximize the area for i in range(maxVal, 0, -1) : # The count of sticks with the current # length has to be at least 4 # in order to form a square if (freq[i] >= 4) : print(\"Area = \", pow(i, 2)); print(\"Count =\", freq[i] // 4); return; # Impossible to form a square print(\"-1\"); # Driver codeif __name__ == \"__main__\" : arr = [ 2, 2, 2, 9, 2, 2, 2, 2, 2 ]; n = len(arr); findMaxSquare(arr, n); # This code is contributed by AnkitRai01", "e": 28471, "s": 27528, "text": null }, { "code": "// C# implementation of the approachusing System;using System.Linq; class GFG{ // Function to find the area of the largest// square that can be formed// and the count of such squaresstatic void findMaxSquare(int []arr, int n){ // Maximum value from the array int maxVal = arr.Max(); // Update the frequencies of // the array elements int []freq = new int[maxVal + 1]; for (int i = 0; i < n; i++) freq[arr[i]]++; // Starting from the maximum length sticks // in order to maximize the area for (int i = maxVal; i > 0; i--) { // The count of sticks with the current // length has to be at least 4 // in order to form a square if (freq[i] >= 4) { Console.Write(\"Area = \" + (Math.Pow(i, 2))); Console.Write(\"\\nCount = \" + (freq[i] / 4)); return; } } // Impossible to form a square Console.Write(\"-1\");} // Driver codepublic static void Main(String[] args){ int []arr = { 2, 2, 2, 9, 2, 2, 2, 2, 2 }; int n = arr.Length; findMaxSquare(arr, n);}} // This code is contributed by 29AjayKumar", "e": 29638, "s": 28471, "text": null }, { "code": "<script> // Javascript implementation of the approach // Function to find the area of the largest// square that can be formed// and the count of such squaresfunction findMaxSquare(arr, n){ // Maximum value from the array var maxVal = Math.max(...arr); // Update the frequencies of // the array elements var freq = Array(maxVal + 1).fill(0); for (var i = 0; i < n; i++) freq[arr[i]]++; // Starting from the maximum length sticks // in order to maximize the area for (var i = maxVal; i > 0; i--) { // The count of sticks with the current // length has to be at least 4 // in order to form a square if (freq[i] >= 4) { document.write(\"Area = \" + (Math.pow(i, 2))); document.write(\"<br>Count = \" + (freq[i] / 4)); return; } } // Impossible to form a square document.write(\"-1\");} // Driver codevar arr = [ 2, 2, 2, 9, 2, 2, 2, 2, 2 ];var n = arr.length;findMaxSquare(arr, n); </script>", "e": 30636, "s": 29638, "text": null }, { "code": null, "e": 30655, "s": 30636, "text": "Area = 4\nCount = 2" }, { "code": null, "e": 30679, "s": 30657, "text": "Time Complexity: O(n)" }, { "code": null, "e": 30701, "s": 30679, "text": "Auxiliary Space: O(n)" }, { "code": null, "e": 30709, "s": 30701, "text": "ankthon" }, { "code": null, "e": 30722, "s": 30709, "text": "princi singh" }, { "code": null, "e": 30734, "s": 30722, "text": "29AjayKumar" }, { "code": null, "e": 30744, "s": 30734, "text": "subham348" }, { "code": null, "e": 30751, "s": 30744, "text": "rrrtnx" }, { "code": null, "e": 30770, "s": 30751, "text": "frequency-counting" }, { "code": null, "e": 30777, "s": 30770, "text": "Arrays" }, { "code": null, "e": 30782, "s": 30777, "text": "Hash" }, { "code": null, "e": 30789, "s": 30782, "text": "Arrays" }, { "code": null, "e": 30794, "s": 30789, "text": "Hash" }, { "code": null, "e": 30892, "s": 30794, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30901, "s": 30892, "text": "Comments" }, { "code": null, "e": 30914, "s": 30901, "text": "Old Comments" }, { "code": null, "e": 30962, "s": 30914, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 30994, "s": 30962, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 31048, "s": 30994, "text": "Queue | Set 1 (Introduction and Array Implementation)" }, { "code": null, "e": 31062, "s": 31048, "text": "Linear Search" }, { "code": null, "e": 31107, "s": 31062, "text": "Python | Using 2D arrays/lists the right way" }, { "code": null, "e": 31138, "s": 31107, "text": "Hashing | Set 1 (Introduction)" }, { "code": null, "e": 31167, "s": 31138, "text": "Quadratic Probing in Hashing" }, { "code": null, "e": 31201, "s": 31167, "text": "Hashing | Set 3 (Open Addressing)" }, { "code": null, "e": 31286, "s": 31201, "text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)" } ]
Set two Matplotlib imshow plots to have the same colormap scale
To set two matplotlib imshow() plots to have the same colormap scale, we can take the following Set the figure size and adjust the padding between and around the subplots. Create d1 and d2 matrices using Numpy. Get the resultant matrix to get the maximum and minmum value. Use amin and amax methods for minimum and maximum values. Create a new figure or activate an existing figure. Add an '~.axes.Axes' to the figure as part of a subplot arrangement, with nrows=1, ncols=2 at index 1 Using imshow() method with vmin and vmax, define the data range that the colormap covers. Repeat steps 6 and 7 with data To display the figure, use show() method. import numpy as np from matplotlib import pyplot as plt plt.rcParams["figure.figsize"] = [7.50, 3.50] plt.rcParams["figure.autolayout"] = True data1 = np.random.randn(4, 4) data2 = np.random.randn(4, 4) resultant = np.array([data1, data2]) min_val, max_val = np.amin(resultant), np.amax(resultant) fig = plt.figure() ax = fig.add_subplot(1, 2, 1) ax.imshow(data1, cmap="plasma", vmin=min_val, vmax=max_val) ax2 = fig.add_subplot(1, 2, 2) ax2.imshow(data2, cmap="plasma", vmin=min_val, vmax=max_val) plt.show()
[ { "code": null, "e": 1158, "s": 1062, "text": "To set two matplotlib imshow() plots to have the same colormap scale, we can take the following" }, { "code": null, "e": 1234, "s": 1158, "text": "Set the figure size and adjust the padding between and around the subplots." }, { "code": null, "e": 1273, "s": 1234, "text": "Create d1 and d2 matrices using Numpy." }, { "code": null, "e": 1335, "s": 1273, "text": "Get the resultant matrix to get the maximum and minmum value." }, { "code": null, "e": 1393, "s": 1335, "text": "Use amin and amax methods for minimum and maximum values." }, { "code": null, "e": 1445, "s": 1393, "text": "Create a new figure or activate an existing figure." }, { "code": null, "e": 1547, "s": 1445, "text": "Add an '~.axes.Axes' to the figure as part of a subplot arrangement, with nrows=1,\nncols=2 at index 1" }, { "code": null, "e": 1637, "s": 1547, "text": "Using imshow() method with vmin and vmax, define the data range that the colormap covers." }, { "code": null, "e": 1668, "s": 1637, "text": "Repeat steps 6 and 7 with data" }, { "code": null, "e": 1710, "s": 1668, "text": "To display the figure, use show() method." }, { "code": null, "e": 2226, "s": 1710, "text": "import numpy as np\nfrom matplotlib import pyplot as plt\n\nplt.rcParams[\"figure.figsize\"] = [7.50, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\n\ndata1 = np.random.randn(4, 4)\ndata2 = np.random.randn(4, 4)\n\nresultant = np.array([data1, data2])\nmin_val, max_val = np.amin(resultant), np.amax(resultant)\nfig = plt.figure()\n\nax = fig.add_subplot(1, 2, 1)\nax.imshow(data1, cmap=\"plasma\", vmin=min_val, vmax=max_val)\n\nax2 = fig.add_subplot(1, 2, 2)\nax2.imshow(data2, cmap=\"plasma\", vmin=min_val, vmax=max_val)\n\nplt.show()" } ]
MySQL Tryit Editor v1.0
SELECT MIN(Price) AS SmallestPrice FROM Products; ​ Edit the SQL Statement, and click "Run SQL" to see the result. This SQL-Statement is not supported in the WebSQL Database. The example still works, because it uses a modified version of SQL. Your browser does not support WebSQL. Your are now using a light-version of the Try-SQL Editor, with a read-only Database. If you switch to a browser with WebSQL support, you can try any SQL statement, and play with the Database as much as you like. The Database can also be restored at any time. Our Try-SQL Editor uses WebSQL to demonstrate SQL. A Database-object is created in your browser, for testing purposes. You can try any SQL statement, and play with the Database as much as you like. The Database can be restored at any time, simply by clicking the "Restore Database" button. WebSQL stores a Database locally, on the user's computer. Each user gets their own Database object. WebSQL is supported in Chrome, Safari, and Opera. If you use another browser you will still be able to use our Try SQL Editor, but a different version, using a server-based ASP application, with a read-only Access Database, where users are not allowed to make any changes to the data.
[ { "code": null, "e": 35, "s": 0, "text": "SELECT MIN(Price) AS SmallestPrice" }, { "code": null, "e": 51, "s": 35, "text": "FROM Products; " }, { "code": null, "e": 53, "s": 51, "text": "​" }, { "code": null, "e": 125, "s": 62, "text": "Edit the SQL Statement, and click \"Run SQL\" to see the result." }, { "code": null, "e": 185, "s": 125, "text": "This SQL-Statement is not supported in the WebSQL Database." }, { "code": null, "e": 253, "s": 185, "text": "The example still works, because it uses a modified version of SQL." }, { "code": null, "e": 291, "s": 253, "text": "Your browser does not support WebSQL." }, { "code": null, "e": 376, "s": 291, "text": "Your are now using a light-version of the Try-SQL Editor, with a read-only Database." }, { "code": null, "e": 550, "s": 376, "text": "If you switch to a browser with WebSQL support, you can try any SQL statement, and play with the Database as much as you like. The Database can also be restored at any time." }, { "code": null, "e": 601, "s": 550, "text": "Our Try-SQL Editor uses WebSQL to demonstrate SQL." }, { "code": null, "e": 669, "s": 601, "text": "A Database-object is created in your browser, for testing purposes." }, { "code": null, "e": 840, "s": 669, "text": "You can try any SQL statement, and play with the Database as much as you like. The Database can be restored at any time, simply by clicking the \"Restore Database\" button." }, { "code": null, "e": 940, "s": 840, "text": "WebSQL stores a Database locally, on the user's computer. Each user gets their own Database object." }, { "code": null, "e": 990, "s": 940, "text": "WebSQL is supported in Chrome, Safari, and Opera." } ]
Programming a slideshow with HTML and CSS
16 Dec, 2021 In this article, we will know how to build the slideshow using HTML & CSS. A slideshow can be used to display text or images that continuously scroll from one slide to the other to display its content. This article shows an approach to building a slideshow with the use of only HTML and CSS. It consumes less browser memory and takes less computation power as there is no JavaScript involved. JavaScript-based sliders make the web page slower and also do not work if the user has disabled JavaScript in the browser. It uses the approach of using animation keyframes to scroll through each of the slides by modifying each of the slide’s margin-left properties during the animation. The animation type can be specified so that the slides can be animated as per the required duration and effect. We will divide the task into two sections ie., in the first, we will decorate the structure by using only HTML and in the second section, we will decorate the structure by using CSS. Approach: For building the slideshow or carousel, we will follow the below approach. To display the text content on each slide, we have defined a separate div section that will carry content for each slide. We have the slide-wrapper class to carry all the slide frame that facilitates implementing the same animation effect as well as other CSS properties to each slide. We have used the overflow property so that it will clip the extra content, and the rest of the content will be invisible if the content of an element is too big to fit in the specified area. The float property is used in order to align the contents to the left. We have used :nth-child() selector in order to apply the background color that will match the elements based on their position in a group of siblings. It matches every element that is the nth-child. In order to define the animation for the slideshow, the keyframes property will be used to scroll through each of the slides by modifying the margin-left property for each of the slides during the animation. First Section: This section contains the HTML portion of the page. The slides that have to be shown are defined with their corresponding text. HTML <html><head> <title>HTML and CSS Slideshow</title></head> <body> <!-- Define the slideshow container --> <div id="slideshow"> <div class="slide-wrapper"> <!-- Define each of the slides and write the content --> <div class="slide"> <h1 class="slide-number"> GeeksforGeeks </h1> </div> <div class="slide"> <h1 class="slide-number"> A computer science portal </h1> </div> <div class="slide"> <h1 class="slide-number"> This is an example of </h1> </div> <div class="slide"> <h1 class="slide-number"> Slideshow with HTML and CSS only </h1> </div> </div> </div></body></html> Second Section: This section consists of all the styling that would be used to make the slideshow. The animation to be used to move each of the slides is defined by setting the margin-left property as required for every slide. This gives it an appearance of smoothly transitioning between each of the slides. CSS body { font-family: Helvetica, sans-serif; padding: 5%; text-align: center; font-size: 50;} /* Styling the area of the slides */#slideshow { overflow: hidden; height: 510px; width: 728px; margin: 0 auto;} /* Style each of the sideswith a fixed width and height */.slide { float: left; height: 510px; width: 728px;} /* Add animation to the slides */.slide-wrapper { /* Calculate the total width on the basis of number of slides */ width: calc(728px * 4); /* Specify the animation with the duration and speed */ animation: slide 10s ease infinite;} /* Set the background colorof each of the slides */.slide:nth-child(1) { background: green;} .slide:nth-child(2) { background: pink;} .slide:nth-child(3) { background: red;} .slide:nth-child(4) { background: yellow;} /* Define the animationfor the slideshow */@keyframes slide { /* Calculate the margin-left for each of the slides */ 20% { margin-left: 0px; } 40% { margin-left: calc(-728px * 1); } 60% { margin-left: calc(-728px * 2); } 80% { margin-left: calc(-728px * 3); }} Complete Code: Here, we will combine the above two sections into one to achieve the mentioned task. HTML <!DOCTYPE html><html><head> <title>HTML and CSS Slideshow</title> <style> body { font-family: Helvetica, sans-serif; padding: 5%; text-align: center; font-size: 50; } /* Styling the area of the slides */ #slideshow { overflow: hidden; height: 510px; width: 728px; margin: 0 auto; } /* Style each of the sides with a fixed width and height */ .slide { float: left; height: 510px; width: 728px; } /* Add animation to the slides */ .slide-wrapper { /* Calculate the total width on the basis of number of slides */ width: calc(728px * 4); /* Specify the animation with the duration and speed */ animation: slide 10s ease infinite; } /* Set the background color of each of the slides */ .slide:nth-child(1) { background: green; } .slide:nth-child(2) { background: pink; } .slide:nth-child(3) { background: red; } .slide:nth-child(4) { background: yellow; } /* Define the animation for the slideshow */ @keyframes slide { /* Calculate the margin-left for each of the slides */ 20% { margin-left: 0px; } 40% { margin-left: calc(-728px * 1); } 60% { margin-left: calc(-728px * 2); } 80% { margin-left: calc(-728px * 3); } } </style></head> <body> <!-- Define the slideshow container --> <div id="slideshow"> <div class="slide-wrapper"> <!-- Define each of the slides and write the content --> <div class="slide"> <h1 class="slide-number"> GeeksforGeeks </h1> </div> <div class="slide"> <h1 class="slide-number"> A computer science portal </h1> </div> <div class="slide"> <h1 class="slide-number"> This is an example of </h1> </div> <div class="slide"> <h1 class="slide-number"> Slideshow with HTML and CSS only </h1> </div> </div> </div></body></html> Output: Slideshow using HTML & CSS bhaskargeeksforgeeks CSS-Basics HTML-Basics Picked CSS HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to update Node.js and NPM to next version ? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS? How to create footer to stay at the bottom of a Web page? CSS to put icon inside an input element in a form How to update Node.js and NPM to next version ? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS? REST API (Introduction) Hide or show elements in HTML using display property
[ { "code": null, "e": 52, "s": 24, "text": "\n16 Dec, 2021" }, { "code": null, "e": 568, "s": 52, "text": "In this article, we will know how to build the slideshow using HTML & CSS. A slideshow can be used to display text or images that continuously scroll from one slide to the other to display its content. This article shows an approach to building a slideshow with the use of only HTML and CSS. It consumes less browser memory and takes less computation power as there is no JavaScript involved. JavaScript-based sliders make the web page slower and also do not work if the user has disabled JavaScript in the browser." }, { "code": null, "e": 1028, "s": 568, "text": "It uses the approach of using animation keyframes to scroll through each of the slides by modifying each of the slide’s margin-left properties during the animation. The animation type can be specified so that the slides can be animated as per the required duration and effect. We will divide the task into two sections ie., in the first, we will decorate the structure by using only HTML and in the second section, we will decorate the structure by using CSS." }, { "code": null, "e": 1113, "s": 1028, "text": "Approach: For building the slideshow or carousel, we will follow the below approach." }, { "code": null, "e": 1235, "s": 1113, "text": "To display the text content on each slide, we have defined a separate div section that will carry content for each slide." }, { "code": null, "e": 1399, "s": 1235, "text": "We have the slide-wrapper class to carry all the slide frame that facilitates implementing the same animation effect as well as other CSS properties to each slide." }, { "code": null, "e": 1661, "s": 1399, "text": "We have used the overflow property so that it will clip the extra content, and the rest of the content will be invisible if the content of an element is too big to fit in the specified area. The float property is used in order to align the contents to the left." }, { "code": null, "e": 1860, "s": 1661, "text": "We have used :nth-child() selector in order to apply the background color that will match the elements based on their position in a group of siblings. It matches every element that is the nth-child." }, { "code": null, "e": 2068, "s": 1860, "text": "In order to define the animation for the slideshow, the keyframes property will be used to scroll through each of the slides by modifying the margin-left property for each of the slides during the animation." }, { "code": null, "e": 2211, "s": 2068, "text": "First Section: This section contains the HTML portion of the page. The slides that have to be shown are defined with their corresponding text." }, { "code": null, "e": 2216, "s": 2211, "text": "HTML" }, { "code": "<html><head> <title>HTML and CSS Slideshow</title></head> <body> <!-- Define the slideshow container --> <div id=\"slideshow\"> <div class=\"slide-wrapper\"> <!-- Define each of the slides and write the content --> <div class=\"slide\"> <h1 class=\"slide-number\"> GeeksforGeeks </h1> </div> <div class=\"slide\"> <h1 class=\"slide-number\"> A computer science portal </h1> </div> <div class=\"slide\"> <h1 class=\"slide-number\"> This is an example of </h1> </div> <div class=\"slide\"> <h1 class=\"slide-number\"> Slideshow with HTML and CSS only </h1> </div> </div> </div></body></html>", "e": 3139, "s": 2216, "text": null }, { "code": null, "e": 3448, "s": 3139, "text": "Second Section: This section consists of all the styling that would be used to make the slideshow. The animation to be used to move each of the slides is defined by setting the margin-left property as required for every slide. This gives it an appearance of smoothly transitioning between each of the slides." }, { "code": null, "e": 3452, "s": 3448, "text": "CSS" }, { "code": "body { font-family: Helvetica, sans-serif; padding: 5%; text-align: center; font-size: 50;} /* Styling the area of the slides */#slideshow { overflow: hidden; height: 510px; width: 728px; margin: 0 auto;} /* Style each of the sideswith a fixed width and height */.slide { float: left; height: 510px; width: 728px;} /* Add animation to the slides */.slide-wrapper { /* Calculate the total width on the basis of number of slides */ width: calc(728px * 4); /* Specify the animation with the duration and speed */ animation: slide 10s ease infinite;} /* Set the background colorof each of the slides */.slide:nth-child(1) { background: green;} .slide:nth-child(2) { background: pink;} .slide:nth-child(3) { background: red;} .slide:nth-child(4) { background: yellow;} /* Define the animationfor the slideshow */@keyframes slide { /* Calculate the margin-left for each of the slides */ 20% { margin-left: 0px; } 40% { margin-left: calc(-728px * 1); } 60% { margin-left: calc(-728px * 2); } 80% { margin-left: calc(-728px * 3); }}", "e": 4524, "s": 3452, "text": null }, { "code": null, "e": 4624, "s": 4524, "text": "Complete Code: Here, we will combine the above two sections into one to achieve the mentioned task." }, { "code": null, "e": 4629, "s": 4624, "text": "HTML" }, { "code": "<!DOCTYPE html><html><head> <title>HTML and CSS Slideshow</title> <style> body { font-family: Helvetica, sans-serif; padding: 5%; text-align: center; font-size: 50; } /* Styling the area of the slides */ #slideshow { overflow: hidden; height: 510px; width: 728px; margin: 0 auto; } /* Style each of the sides with a fixed width and height */ .slide { float: left; height: 510px; width: 728px; } /* Add animation to the slides */ .slide-wrapper { /* Calculate the total width on the basis of number of slides */ width: calc(728px * 4); /* Specify the animation with the duration and speed */ animation: slide 10s ease infinite; } /* Set the background color of each of the slides */ .slide:nth-child(1) { background: green; } .slide:nth-child(2) { background: pink; } .slide:nth-child(3) { background: red; } .slide:nth-child(4) { background: yellow; } /* Define the animation for the slideshow */ @keyframes slide { /* Calculate the margin-left for each of the slides */ 20% { margin-left: 0px; } 40% { margin-left: calc(-728px * 1); } 60% { margin-left: calc(-728px * 2); } 80% { margin-left: calc(-728px * 3); } } </style></head> <body> <!-- Define the slideshow container --> <div id=\"slideshow\"> <div class=\"slide-wrapper\"> <!-- Define each of the slides and write the content --> <div class=\"slide\"> <h1 class=\"slide-number\"> GeeksforGeeks </h1> </div> <div class=\"slide\"> <h1 class=\"slide-number\"> A computer science portal </h1> </div> <div class=\"slide\"> <h1 class=\"slide-number\"> This is an example of </h1> </div> <div class=\"slide\"> <h1 class=\"slide-number\"> Slideshow with HTML and CSS only </h1> </div> </div> </div></body></html>", "e": 7051, "s": 4629, "text": null }, { "code": null, "e": 7059, "s": 7051, "text": "Output:" }, { "code": null, "e": 7086, "s": 7059, "text": "Slideshow using HTML & CSS" }, { "code": null, "e": 7107, "s": 7086, "text": "bhaskargeeksforgeeks" }, { "code": null, "e": 7118, "s": 7107, "text": "CSS-Basics" }, { "code": null, "e": 7130, "s": 7118, "text": "HTML-Basics" }, { "code": null, "e": 7137, "s": 7130, "text": "Picked" }, { "code": null, "e": 7141, "s": 7137, "text": "CSS" }, { "code": null, "e": 7146, "s": 7141, "text": "HTML" }, { "code": null, "e": 7163, "s": 7146, "text": "Web Technologies" }, { "code": null, "e": 7168, "s": 7163, "text": "HTML" }, { "code": null, "e": 7266, "s": 7168, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 7314, "s": 7266, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 7376, "s": 7314, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 7426, "s": 7376, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 7484, "s": 7426, "text": "How to create footer to stay at the bottom of a Web page?" }, { "code": null, "e": 7534, "s": 7484, "text": "CSS to put icon inside an input element in a form" }, { "code": null, "e": 7582, "s": 7534, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 7644, "s": 7582, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 7694, "s": 7644, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 7718, "s": 7694, "text": "REST API (Introduction)" } ]
Reverse a doubly linked list in groups of given size
03 Jul, 2022 Given a doubly linked list containing n nodes. The problem is to reverse every group of k nodes in the list. Examples: Prerequisite: Reverse a doubly linked list | Set-2. Approach: Create a recursive function say reverse(head, k). This function receives the head or the first node of each group of k nodes. It reverses those groups of k nodes by applying the approach discussed in Reverse a doubly linked list | Set-2. After reversing the group of k nodes the function checks whether next group of nodes exists in the list or not. If a group exists then it makes a recursive call to itself with the first node of the next group and makes the necessary adjustments with the next and previous links of that group. Finally, it returns the new head node of the reversed group. C++ Java Python3 C# Javascript // C++ implementation to reverse a doubly linked list// in groups of given size#include <bits/stdc++.h> using namespace std; // a node of the doubly linked liststruct Node { int data; Node *next, *prev;}; // function to get a new nodeNode* getNode(int data){ // allocate space Node* new_node = (Node*)malloc(sizeof(Node)); // put in the data new_node->data = data; new_node->next = new_node->prev = NULL; return new_node;} // function to insert a node at the beginning// of the Doubly Linked Listvoid push(Node** head_ref, Node* new_node){ // since we are adding at the beginning, // prev is always NULL new_node->prev = NULL; // link the old list off the new node new_node->next = (*head_ref); // change prev of head node to new node if ((*head_ref) != NULL) (*head_ref)->prev = new_node; // move the head to point to the new node (*head_ref) = new_node;} // function to reverse a doubly linked list// in groups of given sizeNode* revListInGroupOfGivenSize(Node* head, int k){ Node *current = head; Node* next = NULL; Node* newHead = NULL; int count = 0; // reversing the current group of k // or less than k nodes by adding // them at the beginning of list // 'newHead' while (current != NULL && count < k) { next = current->next; push(&newHead, current); current = next; count++; } // if next group exists then making the desired // adjustments in the link if (next != NULL) { head->next = revListInGroupOfGivenSize(next, k); head->next->prev = head; } // pointer to the new head of the // reversed group // pointer to the new head should point to NULL, otherwise you won't be able to traverse list in reverse order using 'prev' newHead->prev = NULL; return newHead;} // Function to print nodes in a// given doubly linked listvoid printList(Node* head){ while (head != NULL) { cout << head->data << " "; head = head->next; }} // Driver program to test aboveint main(){ // Start with the empty list Node* head = NULL; // Create doubly linked: 10<->8<->4<->2 push(&head, getNode(2)); push(&head, getNode(4)); push(&head, getNode(8)); push(&head, getNode(10)); int k = 2; cout << "Original list: "; printList(head); // Reverse doubly linked list in groups of // size 'k' head = revListInGroupOfGivenSize(head, k); cout << "\nModified list: "; printList(head); return 0;} // Java implementation to reverse a doubly linked list // in groups of given size import java.io.*;import java.util.*; // Represents a node of doubly linked listclass Node{ int data; Node next, prev;} class GFG { // function to get a new node static Node getNode(int data) { // allocating node Node new_node = new Node(); new_node.data = data; new_node.next = new_node.prev = null; return new_node; } // function to insert a node at the beginning // of the Doubly Linked List static Node push(Node head, Node new_node) { // since we are adding at the beginning, // prev is always NULL new_node.prev = null; // link the old list off the new node new_node.next = head; // change prev of head node to new node if (head != null) head.prev = new_node; // move the head to point to the new node head = new_node; return head; } // function to reverse a doubly linked list // in groups of given size static Node revListInGroupOfGivenSize(Node head, int k) { Node current = head; Node next = null; Node newHead = null; int count = 0; // reversing the current group of k // or less than k nodes by adding // them at the beginning of list // 'newHead' while (current != null && count < k) { next = current.next; newHead = push(newHead, current); current = next; count++; } // if next group exists then making the desired // adjustments in the link if (next != null) { head.next = revListInGroupOfGivenSize(next, k); head.next.prev = head; } // pointer to the new head of the // reversed group return newHead; } // Function to print nodes in a // given doubly linked list static void printList(Node head) { while (head != null) { System.out.print(head.data + " "); head = head.next; } } // Driver code public static void main(String args[]) { // Start with the empty list Node head = null; // Create doubly linked: 10<->8<->4<->2 head = push(head, getNode(2)); head = push(head, getNode(4)); head = push(head, getNode(8)); head = push(head, getNode(10)); int k = 2; System.out.print("Original list: "); printList(head); // Reverse doubly linked list in groups of // size 'k' head = revListInGroupOfGivenSize(head, k); System.out.print("\nModified list: "); printList(head); }} // This code is contributed by rachana soma # Python implementation to reverse a doubly linked list# in groups of given size # Link list node class Node: def __init__(self, data): self.data = data self.next = next # function to get a new nodedef getNode(data): # allocate space new_node = Node(0) # put in the data new_node.data = data new_node.next = new_node.prev = None return new_node # function to insert a node at the beginning# of the Doubly Linked Listdef push(head_ref, new_node): # since we are adding at the beginning, # prev is always None new_node.prev = None # link the old list off the new node new_node.next = (head_ref) # change prev of head node to new node if ((head_ref) != None): (head_ref).prev = new_node # move the head to point to the new node (head_ref) = new_node return head_ref # function to reverse a doubly linked list# in groups of given sizedef revListInGroupOfGivenSize( head, k): current = head next = None newHead = None count = 0 # reversing the current group of k # or less than k nodes by adding # them at the beginning of list # 'newHead' while (current != None and count < k): next = current.next newHead = push(newHead, current) current = next count = count + 1 # if next group exists then making the desired # adjustments in the link if (next != None): head.next = revListInGroupOfGivenSize(next, k) head.next.prev = head # pointer to the new head of the # reversed group return newHead # Function to print nodes in a# given doubly linked listdef printList(head): while (head != None): print( head.data , end=" ") head = head.next # Driver program to test above # Start with the empty listhead = None # Create doubly linked: 10<.8<.4<.2 head = push(head, getNode(2))head = push(head, getNode(4))head = push(head, getNode(8))head = push(head, getNode(10)) k = 2 print("Original list: ")printList(head) # Reverse doubly linked list in groups of # size 'k'head = revListInGroupOfGivenSize(head, k) print("\nModified list: ")printList(head) # This code is contributed by Arnab Kundu // C# implementation to reverse a doubly linked list // in groups of given size using System; // Represents a node of doubly linked list public class Node { public int data; public Node next, prev; } class GFG { // function to get a new node static Node getNode(int data) { // allocating node Node new_node = new Node(); new_node.data = data; new_node.next = new_node.prev = null; return new_node; } // function to insert a node at the beginning // of the Doubly Linked List static Node push(Node head, Node new_node) { // since we are adding at the beginning, // prev is always NULL new_node.prev = null; // link the old list off the new node new_node.next = head; // change prev of head node to new node if (head != null) head.prev = new_node; // move the head to point to the new node head = new_node; return head; } // function to reverse a doubly linked list // in groups of given size static Node revListInGroupOfGivenSize(Node head, int k) { Node current = head; Node next = null; Node newHead = null; int count = 0; // reversing the current group of k // or less than k nodes by adding // them at the beginning of list // 'newHead' while (current != null && count < k) { next = current.next; newHead = push(newHead, current); current = next; count++; } // if next group exists then making the desired // adjustments in the link if (next != null) { head.next = revListInGroupOfGivenSize(next, k); head.next.prev = head; } // pointer to the new head of the // reversed group return newHead; } // Function to print nodes in a // given doubly linked list static void printList(Node head) { while (head != null) { Console.Write(head.data + " "); head = head.next; } } // Driver code public static void Main(String []args) { // Start with the empty list Node head = null; // Create doubly linked: 10<->8<->4<->2 head = push(head, getNode(2)); head = push(head, getNode(4)); head = push(head, getNode(8)); head = push(head, getNode(10)); int k = 2; Console.Write("Original list: "); printList(head); // Reverse doubly linked list in groups of // size 'k' head = revListInGroupOfGivenSize(head, k); Console.Write("\nModified list: "); printList(head); } } // This code is contributed by Arnab Kundu <script>// javascript implementation to reverse a doubly linked list // in groups of given size // Represents a node of doubly linked listclass Node { constructor() { this.data = 0; this.prev = null; this.next = null; }} // function to get a new node function getNode(data) { // allocating nodevar new_node = new Node(); new_node.data = data; new_node.next = new_node.prev = null; return new_node; } // function to insert a node at the beginning // of the Doubly Linked List function push(head, new_node) { // since we are adding at the beginning, // prev is always NULL new_node.prev = null; // link the old list off the new node new_node.next = head; // change prev of head node to new node if (head != null) head.prev = new_node; // move the head to point to the new node head = new_node; return head; } // function to reverse a doubly linked list // in groups of given size function revListInGroupOfGivenSize(head , k) {var current = head;var next = null;var newHead = null; var count = 0; // reversing the current group of k // or less than k nodes by adding // them at the beginning of list // 'newHead' while (current != null && count < k) { next = current.next; newHead = push(newHead, current); current = next; count++; } // if next group exists then making the desired // adjustments in the link if (next != null) { head.next = revListInGroupOfGivenSize(next, k); head.next.prev = head; } // pointer to the new head of the // reversed group return newHead; } // Function to print nodes in a // given doubly linked list function printList(head) { while (head != null) { document.write(head.data + " "); head = head.next; } } // Driver code // Start with the empty listvar head = null; // Create doubly linked: 10<->8<->4<->2 head = push(head, getNode(2)); head = push(head, getNode(4)); head = push(head, getNode(8)); head = push(head, getNode(10)); var k = 2; document.write("Original list: "); printList(head); // Reverse doubly linked list in groups of // size 'k' head = revListInGroupOfGivenSize(head, k); document.write("<br/>Modified list: "); printList(head); // This code contributed by aashish1995</script> Original list: 10 8 4 2 Modified list: 8 10 2 4 Time Complexity: O(n). We can further simplify the implementation of this algorithm using the same idea with recursion in just one function. C++ Java Python3 C# Javascript #include <iostream>using namespace std;struct Node { int data; Node *next, *prev;};// function to add Node at the end of a Doubly LinkedListNode* insertAtEnd(Node* head, int data){ Node* new_node = new Node(); new_node->data = data; new_node->next = NULL; Node* temp = head; if (head == NULL) { new_node->prev = NULL; head = new_node; return head; } while (temp->next != NULL) { temp = temp->next; } temp->next = new_node; new_node->prev = temp; return head;}// function to print Doubly LinkedListvoid printDLL(Node* head){ while (head != NULL) { cout << head->data << " "; head = head->next; } cout << endl;}// function to Reverse a doubly linked list// in groups of given sizeNode* reverseByN(Node* head, int k){ if (!head) return NULL; head->prev = NULL; Node *temp, *curr = head, *newHead; int count = 0; while (curr != NULL && count < k) { newHead = curr; temp = curr->prev; curr->prev = curr->next; curr->next = temp; curr = curr->prev; count++; } // checking if the reversed LinkedList size is // equal to K or not // if it is not equal to k that means we have reversed // the last set of size K and we don't need to call the // recursive function if (count >= k) { Node* rest = reverseByN(curr, k); head->next = rest; if (rest != NULL) // it is required for prev link otherwise u wont // be backtrack list due to broken links rest->prev = head; } return newHead;}int main(){ Node* head; for (int i = 1; i <= 10; i++) { head = insertAtEnd(head, i); } printDLL(head); int n = 4; head = reverseByN(head, n); printDLL(head);} import java.io.*; class Node { int data; Node next, prev;} class GFG { // Function to add Node at the end of a // Doubly LinkedList static Node insertAtEnd(Node head, int data) { Node new_node = new Node(); new_node.data = data; new_node.next = null; Node temp = head; if (head == null) { new_node.prev = null; head = new_node; return head; } while (temp.next != null) { temp = temp.next; } temp.next = new_node; new_node.prev = temp; return head; } // Function to print Doubly LinkedList static void printDLL(Node head) { while (head != null) { System.out.print(head.data + " "); head = head.next; } System.out.println(); } // Function to Reverse a doubly linked list // in groups of given size static Node reverseByN(Node head, int k) { if (head == null) return null; head.prev = null; Node temp; Node curr = head; Node newHead = null; int count = 0; while (curr != null && count < k) { newHead = curr; temp = curr.prev; curr.prev = curr.next; curr.next = temp; curr = curr.prev; count++; } // Checking if the reversed LinkedList size is // equal to K or not. If it is not equal to k // that means we have reversed the last set of // size K and we don't need to call the // recursive function if (count >= k) { Node rest = reverseByN(curr, k); head.next = rest; if (rest != null) // it is required for prev link otherwise u // wont be backtrack list due to broken // links rest.prev = head; } return newHead; } // Driver code public static void main(String[] args) { Node head = null; for (int i = 1; i <= 10; i++) { head = insertAtEnd(head, i); } printDLL(head); int n = 4; head = reverseByN(head, n); printDLL(head); }} // This code is contributed by avanitrachhadiya2155 class Node: def __init__(self): self.data = 0; self.next = None; self.next = None; # Function to add Node at the end of a# Doubly LinkedListdef insertAtEnd(head, data): new_Node = Node(); new_Node.data = data; new_Node.next = None; temp = head; if (head == None): new_Node.prev = None; head = new_Node; return head; while (temp.next != None): temp = temp.next; temp.next = new_Node; new_Node.prev = temp; return head; # Function to prDoubly LinkedListdef printDLL(head): while (head != None): print(head.data, end=" "); head = head.next; print(); # Function to Reverse a doubly linked list# in groups of given sizedef reverseByN(head, k): if (head == None): return None; head.prev = None; temp=None; curr = head; newHead = None; count = 0; while (curr != None and count < k): newHead = curr; temp = curr.prev; curr.prev = curr.next; curr.next = temp; curr = curr.prev; count += 1; # Checking if the reversed LinkedList size is # equal to K or not. If it is not equal to k # that means we have reversed the last set of # size K and we don't need to call the # recursive function if (count >= k): rest = reverseByN(curr, k); head.next = rest; if (rest != None): # it is required for prev link otherwise u # wont be backtrack list due to broken # links rest.prev = head; return newHead; # Driver codeif __name__ == '__main__': head = None; for i in range(1,11): head = insertAtEnd(head, i); printDLL(head); n = 4; head = reverseByN(head, n); printDLL(head); # This code contributed by umadevi9616 using System;using System.Collections.Generic; public class GFG { public class Node { public int data; public Node next, prev; } // Function to add Node at the end of a // Doubly List static Node insertAtEnd(Node head, int data) { Node new_node = new Node(); new_node.data = data; new_node.next = null; Node temp = head; if (head == null) { new_node.prev = null; head = new_node; return head; } while (temp.next != null) { temp = temp.next; } temp.next = new_node; new_node.prev = temp; return head; } // Function to print Doubly List static void printDLL(Node head) { while (head != null) { Console.Write(head.data + " "); head = head.next; } Console.WriteLine(); } // Function to Reverse a doubly linked list // in groups of given size static Node reverseByN(Node head, int k) { if (head == null) return null; head.prev = null; Node temp; Node curr = head; Node newHead = null; int count = 0; while (curr != null && count < k) { newHead = curr; temp = curr.prev; curr.prev = curr.next; curr.next = temp; curr = curr.prev; count++; } // Checking if the reversed List size is // equal to K or not. If it is not equal to k // that means we have reversed the last set of // size K and we don't need to call the // recursive function if (count >= k) { Node rest = reverseByN(curr, k); head.next = rest; if (rest != null) // it is required for prev link otherwise u // wont be backtrack list due to broken // links rest.prev = head; } return newHead; } // Driver code public static void Main(String[] args) { Node head = null; for (int i = 1; i <= 10; i++) { head = insertAtEnd(head, i); } printDLL(head); int n = 4; head = reverseByN(head, n); printDLL(head); }} // This code is contributed by umadevi9616 <script> class Node { constructor() { this.data = 0; this.next = null; this.prev = null; }};// function to add Node at the end of a Doubly LinkedListfunction insertAtEnd(head, data){ var new_node = new Node(); new_node.data = data; new_node.next = null; var temp = head; if (head == null) { new_node.prev = null; head = new_node; return head; } while (temp.next != null) { temp = temp.next; } temp.next = new_node; new_node.prev = temp; return head;}// function to print Doubly LinkedListfunction printDLL(head){ while (head != null) { document.write( head.data + " "); head = head.next; } document.write("<br>");}// function to Reverse a doubly linked list// in groups of given sizefunction reverseByN(head, k){ if (!head) return null; head.prev = null; var temp, curr = head, newHead; var count = 0; while (curr != null && count < k) { newHead = curr; temp = curr.prev; curr.prev = curr.next; curr.next = temp; curr = curr.prev; count++; } // checking if the reversed LinkedList size is // equal to K or not // if it is not equal to k that means we have reversed // the last set of size K and we don't need to call the // recursive function if (count >= k) { var rest = reverseByN(curr, k) head.next = rest; if(rest != null) /it is required for prev link otherwise u wont be backtrack list due to broken links rest.prev = head; } return newHead;} var head;for (var i = 1; i <= 10; i++) { head = insertAtEnd(head, i);}printDLL(head);var n = 4;head = reverseByN(head, n);printDLL(head); </script> 1 2 3 4 5 6 7 8 9 10 4 3 2 1 8 7 6 5 10 9 Another approach (Iterative Method) : Here we will be using the iterative method in which we will begin from head node and reverse k nodes in the group. After reversing the k nodes we will continue this process with the next node after the k node until it becomes null. We will the achieving the desired result in only a single pass of the linked list with the time complexity of O(n) and space complexity of O(1). C++ Java Python3 C# Javascript // C++ implementation to reverse a doubly linked list// in groups of given size without recursion// Iterative Method #include <iostream>using namespace std; // Represents a node of doubly linked liststruct Node { int data; Node *next, *prev;}; // function to get a new nodeNode* getNode(int data){ // allocating node Node* new_node = new Node(); new_node->data = data; new_node->next = new_node->prev = NULL; return new_node;} // function to insert a node at the beginning// of the Doubly Linked ListNode* push(Node* head, Node* new_node){ // since we are adding at the beginning, // prev is always NULL new_node->prev = NULL; // link the old list off the new node new_node->next = head; // change prev of head node to new node if (head != NULL) head->prev = new_node; // move the head to point to the new node head = new_node; return head;} // function to reverse a doubly linked list// in groups of given sizeNode* revListInGroupOfGivenSize(Node* head, int k){ if (!head) return head; Node* st = head; Node* globprev = NULL; Node* ans = NULL; while (st) { int count = 1; // to count k nodes Node* curr = st; Node* prev = NULL; Node* next = NULL; while (curr && count <= k) { // reversing k nodes next = curr->next; curr->prev = next; curr->next = prev; prev = curr; curr = next; count++; } if (!ans) { ans = prev; // to store ans i.e the new head ans->prev = NULL; } if (!globprev) globprev = st; // assigning the last node of the // reversed k nodes else { globprev->next = prev; prev->prev = globprev; // connecting last node of last // k group to the first node of // present k group globprev = st; } st = curr; // advancing the pointer for the next k // group } return ans;} // Function to print nodes in a// given doubly linked listvoid printList(Node* head){ while (head) { cout << head->data << " "; head = head->next; }} // Driver codeint main(){ // Start with the empty list Node* head = NULL; // Create doubly linked: 10<->8<->4<->2 head = push(head, getNode(2)); head = push(head, getNode(4)); head = push(head, getNode(8)); head = push(head, getNode(10)); int k = 2; cout << "Original list: "; printList(head); // Reverse doubly linked list in groups of // size 'k' head = revListInGroupOfGivenSize(head, k); cout << "\nModified list: "; printList(head); return 0;} // This code is contributed by Tapesh (tapeshdua420) // Java implementation to reverse a doubly linked list// in groups of given size without recursion// Iterative Method import java.io.*;import java.util.*; // Represents a node of doubly linked listclass Node { int data; Node next, prev;} class GFG { // function to get a new node static Node getNode(int data) { // allocating node Node new_node = new Node(); new_node.data = data; new_node.next = new_node.prev = null; return new_node; } // function to insert a node at the beginning // of the Doubly Linked List static Node push(Node head, Node new_node) { // since we are adding at the beginning, // prev is always NULL new_node.prev = null; // link the old list off the new node new_node.next = head; // change prev of head node to new node if (head != null) head.prev = new_node; // move the head to point to the new node head = new_node; return head; } // function to reverse a doubly linked list // in groups of given size static Node revListInGroupOfGivenSize(Node head, int k) { if (head == null) return head; Node st = head; Node globprev = null; Node ans = null; while (st != null) { int count = 1; // to count k nodes Node curr = st; Node prev = null; Node next = null; while (curr != null && count <= k) { // reversing k nodes next = curr.next; curr.prev = next; curr.next = prev; prev = curr; curr = next; count++; } if (ans == null) { ans = prev; // to store ans i.e the new head ans.prev = null; } if (globprev == null) { globprev = st; // assigning the last node of // the reversed k nodes } else { globprev.next = prev; prev.prev = globprev; // connecting last node of // last k group to the first // node of present k group globprev = st; } st = curr; // advancing the pointer for the next // k group } return ans; } // Function to print nodes in a // given doubly linked list static void printList(Node head) { while (head != null) { System.out.print(head.data + " "); head = head.next; } } // Driver code public static void main(String args[]) { // Start with the empty list Node head = null; // Create doubly linked: 10<->8<->4<->2 head = push(head, getNode(2)); head = push(head, getNode(4)); head = push(head, getNode(8)); head = push(head, getNode(10)); int k = 2; System.out.print("Original list: "); printList(head); // Reverse doubly linked list in groups of // size 'k' head = revListInGroupOfGivenSize(head, k); System.out.print("\nModified list: "); printList(head); }} // This code is contributed by Chayan Sharma # Python implementation to reverse a doubly# linked list in groups of given size without recursion# Iterative method. # Represents a node of doubly linked list.class Node: def __init__(self, data): self.data = data self.next = None # Function to get a new Node.def getNode(data): # allocating node new_node = Node(0) new_node.data = data new_node.next = new_node.prev = None return new_node # Function to insert a node at the beginning of the doubly linked list. def push(head, new_node): # since we are adding at the beginning, prev is always null. new_node.prev = None # link the old list off the new node. new_node.next = head # change prev of head node to new node. if ((head) != None): head.prev = new_node # move the head to point to the new node. head = new_node return head # Function to print nodes in given doubly linked list. def printList(head): while (head): print(head.data, end=" ") head = head.next # Function to reverse a doubly linked list in groups of given size. def revListInGroupOfGivenSize(head, k): if head is None: return head st = head globprev, ans = None, None while (st != None): # Count the number of nodes. count = 1 curr = st prev, next_node = None, None while (curr != None and count <= k): # Reversing k nodes. next_node = curr.next curr.prev = next_node curr.next = prev prev = curr curr = next_node count += 1 if ans is None: ans = prev ans.prev = None if globprev is None: globprev = st else: globprev.next = prev prev.prev = globprev globprev = st st = curr return ans # Start with the empty list.head = None # Create a doubly linked list: 10<->8<->4<->2head = push(head, getNode(2))head = push(head, getNode(4))head = push(head, getNode(8))head = push(head, getNode(10)) print("Original list:", end=" ")printList(head) k = 2 # Reverse doubly linked list in groups of size 'k'head = revListInGroupOfGivenSize(head, k) print("\nModified list:", end=" ")printList(head) # This code is contributed by lokesh (lokeshmvs21). // C# implementation to reverse a doubly linked list in// groups of given size without recursion Iterative Methodusing System; // Represents a node of doubly linked listpublic class Node { public int data; public Node next, prev;} public class GFG { // Function to get a new Node. static Node getNode(int data) { // allocating a new node. Node new_node = new Node(); new_node.data = data; new_node.next = new_node.prev = null; return new_node; } // Function to insert a node at the beginning of the // doubly linked list. static Node push(Node head, Node new_node) { // since we are adding at the beginning, prev is // always null. new_node.prev = null; // link the old list off the new node. new_node.next = head; // change prev of head node to new node. if (head != null) { head.prev = new_node; } // move the head to point to the new node. head = new_node; return head; } // Function to print nodes in a given doubly linked // list. static void printList(Node head) { while (head != null) { Console.Write(head.data + " "); head = head.next; } } // Function to reverse a doubly linked list in groups of // given size static Node revListInGroupOfGivenSize(Node head, int k) { if (head == null) { return head; } Node st = head; Node globprev = null; Node ans = null; while (st != null) { // count the number of nodes. int count = 1; Node curr = st; Node prev = null; Node next = null; // reversing k nodes. while (curr != null && count <= k) { next = curr.next; curr.prev = next; curr.next = prev; prev = curr; curr = next; count++; } if (ans == null) { // to store ans i.e the new head ans = prev; ans.prev = null; } if (globprev == null) { // assigning the last node of the reveresd k // nodes. globprev = st; } else { globprev.next = prev; prev.prev = globprev; // connecting last node of last k group to // the first node of present k group globprev = st; } // advancing the pointer for the next k group st = curr; } return ans; } static public void Main() { // Start with the empty list. Node head = null; // Create doubly linked list : 10<->8<->4<->2 head = push(head, getNode(2)); head = push(head, getNode(4)); head = push(head, getNode(8)); head = push(head, getNode(10)); Console.Write("Original list: "); printList(head); int k = 2; // Reverse doubly linked list in groups of size 'k' head = revListInGroupOfGivenSize(head, k); Console.Write("\nModified list: "); printList(head); }} // This code is contributed by lokesh (lokeshmvs21) <script>// Javascript implementation to reverse a doubly linked list// in groups of given size without recursion// Iterative Method // Represents a node of doubly linked listclass Node { constructor() { this.data = null; this.next = null; this.prev = null; }} // function to get a new nodefunction getNode(data) { // allocating node let new_node = new Node(); new_node.data = data; new_node.next = new_node.prev = null; return new_node;} // function to insert a node at the beginning// of the Doubly Linked Listfunction push(head, new_node) { // since we are adding at the beginning, // prev is always NULL new_node.prev = null; // link the old list off the new node new_node.next = head; // change prev of head node to new node if (head != null) head.prev = new_node; // move the head to point to the new node head = new_node; return head;} // function to reverse a doubly linked list// in groups of given sizefunction revListInGroupOfGivenSize(head, k) { if (head == null) return head; let st = head; let globprev = null; let ans = null; while (st != null) { let count = 1; // to count k nodes let curr = st; let prev = null; let next = null; while (curr != null && count <= k) { // reversing k nodes next = curr.next; curr.prev = next; curr.next = prev; prev = curr; curr = next; count++; } if (ans == null) { ans = prev; // to store ans i.e the new head ans.prev = null; } if (globprev == null) { globprev = st; // assigning the last node of // the reversed k nodes } else { globprev.next = prev; prev.prev = globprev; // connecting last node of // last k group to the first // node of present k group globprev = st; } st = curr; // advancing the pointer for the next // k group } return ans;} // Function to print nodes in a// given doubly linked listfunction printList(head) { while (head != null) { document.write(head.data + " "); head = head.next; }} // Driver code // Start with the empty listlet head = null; // Create doubly linked: 10<->8<->4<->2head = push(head, getNode(2));head = push(head, getNode(4));head = push(head, getNode(8));head = push(head, getNode(10)); let k = 2; document.write("Original list: ");printList(head); // Reverse doubly linked list in groups of// size 'k'head = revListInGroupOfGivenSize(head, k); document.write("<br>Modified list: ");printList(head); // This code is contributed by Saurabh Jaiswal</script> Original list: 10 8 4 2 Modified list: 8 10 2 4 Time Complexity: O(n) , where n is the number of nodes in the original listAuxiliary Space: O(1) rachana soma andrew1234 nidhi_biet aashish1995 hungrywolf rutvik_56 avanitrachhadiya2155 ruhelaa48 sanjeeverma ankita_saini umadevi9616 arorakashish0911 slayinu chayansharmacs27 krithikakartik17 _saurabh_jaiswal tapeshdua420 lokeshmvs21 doubly linked list Reverse Linked List Linked List Reverse Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n03 Jul, 2022" }, { "code": null, "e": 163, "s": 54, "text": "Given a doubly linked list containing n nodes. The problem is to reverse every group of k nodes in the list." }, { "code": null, "e": 175, "s": 163, "text": "Examples: " }, { "code": null, "e": 227, "s": 175, "text": "Prerequisite: Reverse a doubly linked list | Set-2." }, { "code": null, "e": 830, "s": 227, "text": "Approach: Create a recursive function say reverse(head, k). This function receives the head or the first node of each group of k nodes. It reverses those groups of k nodes by applying the approach discussed in Reverse a doubly linked list | Set-2. After reversing the group of k nodes the function checks whether next group of nodes exists in the list or not. If a group exists then it makes a recursive call to itself with the first node of the next group and makes the necessary adjustments with the next and previous links of that group. Finally, it returns the new head node of the reversed group. " }, { "code": null, "e": 834, "s": 830, "text": "C++" }, { "code": null, "e": 839, "s": 834, "text": "Java" }, { "code": null, "e": 847, "s": 839, "text": "Python3" }, { "code": null, "e": 850, "s": 847, "text": "C#" }, { "code": null, "e": 861, "s": 850, "text": "Javascript" }, { "code": "// C++ implementation to reverse a doubly linked list// in groups of given size#include <bits/stdc++.h> using namespace std; // a node of the doubly linked liststruct Node { int data; Node *next, *prev;}; // function to get a new nodeNode* getNode(int data){ // allocate space Node* new_node = (Node*)malloc(sizeof(Node)); // put in the data new_node->data = data; new_node->next = new_node->prev = NULL; return new_node;} // function to insert a node at the beginning// of the Doubly Linked Listvoid push(Node** head_ref, Node* new_node){ // since we are adding at the beginning, // prev is always NULL new_node->prev = NULL; // link the old list off the new node new_node->next = (*head_ref); // change prev of head node to new node if ((*head_ref) != NULL) (*head_ref)->prev = new_node; // move the head to point to the new node (*head_ref) = new_node;} // function to reverse a doubly linked list// in groups of given sizeNode* revListInGroupOfGivenSize(Node* head, int k){ Node *current = head; Node* next = NULL; Node* newHead = NULL; int count = 0; // reversing the current group of k // or less than k nodes by adding // them at the beginning of list // 'newHead' while (current != NULL && count < k) { next = current->next; push(&newHead, current); current = next; count++; } // if next group exists then making the desired // adjustments in the link if (next != NULL) { head->next = revListInGroupOfGivenSize(next, k); head->next->prev = head; } // pointer to the new head of the // reversed group // pointer to the new head should point to NULL, otherwise you won't be able to traverse list in reverse order using 'prev' newHead->prev = NULL; return newHead;} // Function to print nodes in a// given doubly linked listvoid printList(Node* head){ while (head != NULL) { cout << head->data << \" \"; head = head->next; }} // Driver program to test aboveint main(){ // Start with the empty list Node* head = NULL; // Create doubly linked: 10<->8<->4<->2 push(&head, getNode(2)); push(&head, getNode(4)); push(&head, getNode(8)); push(&head, getNode(10)); int k = 2; cout << \"Original list: \"; printList(head); // Reverse doubly linked list in groups of // size 'k' head = revListInGroupOfGivenSize(head, k); cout << \"\\nModified list: \"; printList(head); return 0;}", "e": 3430, "s": 861, "text": null }, { "code": "// Java implementation to reverse a doubly linked list // in groups of given size import java.io.*;import java.util.*; // Represents a node of doubly linked listclass Node{ int data; Node next, prev;} class GFG { // function to get a new node static Node getNode(int data) { // allocating node Node new_node = new Node(); new_node.data = data; new_node.next = new_node.prev = null; return new_node; } // function to insert a node at the beginning // of the Doubly Linked List static Node push(Node head, Node new_node) { // since we are adding at the beginning, // prev is always NULL new_node.prev = null; // link the old list off the new node new_node.next = head; // change prev of head node to new node if (head != null) head.prev = new_node; // move the head to point to the new node head = new_node; return head; } // function to reverse a doubly linked list // in groups of given size static Node revListInGroupOfGivenSize(Node head, int k) { Node current = head; Node next = null; Node newHead = null; int count = 0; // reversing the current group of k // or less than k nodes by adding // them at the beginning of list // 'newHead' while (current != null && count < k) { next = current.next; newHead = push(newHead, current); current = next; count++; } // if next group exists then making the desired // adjustments in the link if (next != null) { head.next = revListInGroupOfGivenSize(next, k); head.next.prev = head; } // pointer to the new head of the // reversed group return newHead; } // Function to print nodes in a // given doubly linked list static void printList(Node head) { while (head != null) { System.out.print(head.data + \" \"); head = head.next; } } // Driver code public static void main(String args[]) { // Start with the empty list Node head = null; // Create doubly linked: 10<->8<->4<->2 head = push(head, getNode(2)); head = push(head, getNode(4)); head = push(head, getNode(8)); head = push(head, getNode(10)); int k = 2; System.out.print(\"Original list: \"); printList(head); // Reverse doubly linked list in groups of // size 'k' head = revListInGroupOfGivenSize(head, k); System.out.print(\"\\nModified list: \"); printList(head); }} // This code is contributed by rachana soma", "e": 6260, "s": 3430, "text": null }, { "code": "# Python implementation to reverse a doubly linked list# in groups of given size # Link list node class Node: def __init__(self, data): self.data = data self.next = next # function to get a new nodedef getNode(data): # allocate space new_node = Node(0) # put in the data new_node.data = data new_node.next = new_node.prev = None return new_node # function to insert a node at the beginning# of the Doubly Linked Listdef push(head_ref, new_node): # since we are adding at the beginning, # prev is always None new_node.prev = None # link the old list off the new node new_node.next = (head_ref) # change prev of head node to new node if ((head_ref) != None): (head_ref).prev = new_node # move the head to point to the new node (head_ref) = new_node return head_ref # function to reverse a doubly linked list# in groups of given sizedef revListInGroupOfGivenSize( head, k): current = head next = None newHead = None count = 0 # reversing the current group of k # or less than k nodes by adding # them at the beginning of list # 'newHead' while (current != None and count < k): next = current.next newHead = push(newHead, current) current = next count = count + 1 # if next group exists then making the desired # adjustments in the link if (next != None): head.next = revListInGroupOfGivenSize(next, k) head.next.prev = head # pointer to the new head of the # reversed group return newHead # Function to print nodes in a# given doubly linked listdef printList(head): while (head != None): print( head.data , end=\" \") head = head.next # Driver program to test above # Start with the empty listhead = None # Create doubly linked: 10<.8<.4<.2 head = push(head, getNode(2))head = push(head, getNode(4))head = push(head, getNode(8))head = push(head, getNode(10)) k = 2 print(\"Original list: \")printList(head) # Reverse doubly linked list in groups of # size 'k'head = revListInGroupOfGivenSize(head, k) print(\"\\nModified list: \")printList(head) # This code is contributed by Arnab Kundu", "e": 8501, "s": 6260, "text": null }, { "code": "// C# implementation to reverse a doubly linked list // in groups of given size using System; // Represents a node of doubly linked list public class Node { public int data; public Node next, prev; } class GFG { // function to get a new node static Node getNode(int data) { // allocating node Node new_node = new Node(); new_node.data = data; new_node.next = new_node.prev = null; return new_node; } // function to insert a node at the beginning // of the Doubly Linked List static Node push(Node head, Node new_node) { // since we are adding at the beginning, // prev is always NULL new_node.prev = null; // link the old list off the new node new_node.next = head; // change prev of head node to new node if (head != null) head.prev = new_node; // move the head to point to the new node head = new_node; return head; } // function to reverse a doubly linked list // in groups of given size static Node revListInGroupOfGivenSize(Node head, int k) { Node current = head; Node next = null; Node newHead = null; int count = 0; // reversing the current group of k // or less than k nodes by adding // them at the beginning of list // 'newHead' while (current != null && count < k) { next = current.next; newHead = push(newHead, current); current = next; count++; } // if next group exists then making the desired // adjustments in the link if (next != null) { head.next = revListInGroupOfGivenSize(next, k); head.next.prev = head; } // pointer to the new head of the // reversed group return newHead; } // Function to print nodes in a // given doubly linked list static void printList(Node head) { while (head != null) { Console.Write(head.data + \" \"); head = head.next; } } // Driver code public static void Main(String []args) { // Start with the empty list Node head = null; // Create doubly linked: 10<->8<->4<->2 head = push(head, getNode(2)); head = push(head, getNode(4)); head = push(head, getNode(8)); head = push(head, getNode(10)); int k = 2; Console.Write(\"Original list: \"); printList(head); // Reverse doubly linked list in groups of // size 'k' head = revListInGroupOfGivenSize(head, k); Console.Write(\"\\nModified list: \"); printList(head); } } // This code is contributed by Arnab Kundu", "e": 11387, "s": 8501, "text": null }, { "code": "<script>// javascript implementation to reverse a doubly linked list // in groups of given size // Represents a node of doubly linked listclass Node { constructor() { this.data = 0; this.prev = null; this.next = null; }} // function to get a new node function getNode(data) { // allocating nodevar new_node = new Node(); new_node.data = data; new_node.next = new_node.prev = null; return new_node; } // function to insert a node at the beginning // of the Doubly Linked List function push(head, new_node) { // since we are adding at the beginning, // prev is always NULL new_node.prev = null; // link the old list off the new node new_node.next = head; // change prev of head node to new node if (head != null) head.prev = new_node; // move the head to point to the new node head = new_node; return head; } // function to reverse a doubly linked list // in groups of given size function revListInGroupOfGivenSize(head , k) {var current = head;var next = null;var newHead = null; var count = 0; // reversing the current group of k // or less than k nodes by adding // them at the beginning of list // 'newHead' while (current != null && count < k) { next = current.next; newHead = push(newHead, current); current = next; count++; } // if next group exists then making the desired // adjustments in the link if (next != null) { head.next = revListInGroupOfGivenSize(next, k); head.next.prev = head; } // pointer to the new head of the // reversed group return newHead; } // Function to print nodes in a // given doubly linked list function printList(head) { while (head != null) { document.write(head.data + \" \"); head = head.next; } } // Driver code // Start with the empty listvar head = null; // Create doubly linked: 10<->8<->4<->2 head = push(head, getNode(2)); head = push(head, getNode(4)); head = push(head, getNode(8)); head = push(head, getNode(10)); var k = 2; document.write(\"Original list: \"); printList(head); // Reverse doubly linked list in groups of // size 'k' head = revListInGroupOfGivenSize(head, k); document.write(\"<br/>Modified list: \"); printList(head); // This code contributed by aashish1995</script>", "e": 14035, "s": 11387, "text": null }, { "code": null, "e": 14085, "s": 14035, "text": "Original list: 10 8 4 2 \nModified list: 8 10 2 4 " }, { "code": null, "e": 14109, "s": 14085, "text": "Time Complexity: O(n). " }, { "code": null, "e": 14227, "s": 14109, "text": "We can further simplify the implementation of this algorithm using the same idea with recursion in just one function." }, { "code": null, "e": 14231, "s": 14227, "text": "C++" }, { "code": null, "e": 14236, "s": 14231, "text": "Java" }, { "code": null, "e": 14244, "s": 14236, "text": "Python3" }, { "code": null, "e": 14247, "s": 14244, "text": "C#" }, { "code": null, "e": 14258, "s": 14247, "text": "Javascript" }, { "code": "#include <iostream>using namespace std;struct Node { int data; Node *next, *prev;};// function to add Node at the end of a Doubly LinkedListNode* insertAtEnd(Node* head, int data){ Node* new_node = new Node(); new_node->data = data; new_node->next = NULL; Node* temp = head; if (head == NULL) { new_node->prev = NULL; head = new_node; return head; } while (temp->next != NULL) { temp = temp->next; } temp->next = new_node; new_node->prev = temp; return head;}// function to print Doubly LinkedListvoid printDLL(Node* head){ while (head != NULL) { cout << head->data << \" \"; head = head->next; } cout << endl;}// function to Reverse a doubly linked list// in groups of given sizeNode* reverseByN(Node* head, int k){ if (!head) return NULL; head->prev = NULL; Node *temp, *curr = head, *newHead; int count = 0; while (curr != NULL && count < k) { newHead = curr; temp = curr->prev; curr->prev = curr->next; curr->next = temp; curr = curr->prev; count++; } // checking if the reversed LinkedList size is // equal to K or not // if it is not equal to k that means we have reversed // the last set of size K and we don't need to call the // recursive function if (count >= k) { Node* rest = reverseByN(curr, k); head->next = rest; if (rest != NULL) // it is required for prev link otherwise u wont // be backtrack list due to broken links rest->prev = head; } return newHead;}int main(){ Node* head; for (int i = 1; i <= 10; i++) { head = insertAtEnd(head, i); } printDLL(head); int n = 4; head = reverseByN(head, n); printDLL(head);}", "e": 16055, "s": 14258, "text": null }, { "code": "import java.io.*; class Node { int data; Node next, prev;} class GFG { // Function to add Node at the end of a // Doubly LinkedList static Node insertAtEnd(Node head, int data) { Node new_node = new Node(); new_node.data = data; new_node.next = null; Node temp = head; if (head == null) { new_node.prev = null; head = new_node; return head; } while (temp.next != null) { temp = temp.next; } temp.next = new_node; new_node.prev = temp; return head; } // Function to print Doubly LinkedList static void printDLL(Node head) { while (head != null) { System.out.print(head.data + \" \"); head = head.next; } System.out.println(); } // Function to Reverse a doubly linked list // in groups of given size static Node reverseByN(Node head, int k) { if (head == null) return null; head.prev = null; Node temp; Node curr = head; Node newHead = null; int count = 0; while (curr != null && count < k) { newHead = curr; temp = curr.prev; curr.prev = curr.next; curr.next = temp; curr = curr.prev; count++; } // Checking if the reversed LinkedList size is // equal to K or not. If it is not equal to k // that means we have reversed the last set of // size K and we don't need to call the // recursive function if (count >= k) { Node rest = reverseByN(curr, k); head.next = rest; if (rest != null) // it is required for prev link otherwise u // wont be backtrack list due to broken // links rest.prev = head; } return newHead; } // Driver code public static void main(String[] args) { Node head = null; for (int i = 1; i <= 10; i++) { head = insertAtEnd(head, i); } printDLL(head); int n = 4; head = reverseByN(head, n); printDLL(head); }} // This code is contributed by avanitrachhadiya2155", "e": 18322, "s": 16055, "text": null }, { "code": "class Node: def __init__(self): self.data = 0; self.next = None; self.next = None; # Function to add Node at the end of a# Doubly LinkedListdef insertAtEnd(head, data): new_Node = Node(); new_Node.data = data; new_Node.next = None; temp = head; if (head == None): new_Node.prev = None; head = new_Node; return head; while (temp.next != None): temp = temp.next; temp.next = new_Node; new_Node.prev = temp; return head; # Function to prDoubly LinkedListdef printDLL(head): while (head != None): print(head.data, end=\" \"); head = head.next; print(); # Function to Reverse a doubly linked list# in groups of given sizedef reverseByN(head, k): if (head == None): return None; head.prev = None; temp=None; curr = head; newHead = None; count = 0; while (curr != None and count < k): newHead = curr; temp = curr.prev; curr.prev = curr.next; curr.next = temp; curr = curr.prev; count += 1; # Checking if the reversed LinkedList size is # equal to K or not. If it is not equal to k # that means we have reversed the last set of # size K and we don't need to call the # recursive function if (count >= k): rest = reverseByN(curr, k); head.next = rest; if (rest != None): # it is required for prev link otherwise u # wont be backtrack list due to broken # links rest.prev = head; return newHead; # Driver codeif __name__ == '__main__': head = None; for i in range(1,11): head = insertAtEnd(head, i); printDLL(head); n = 4; head = reverseByN(head, n); printDLL(head); # This code contributed by umadevi9616 ", "e": 20168, "s": 18322, "text": null }, { "code": "using System;using System.Collections.Generic; public class GFG { public class Node { public int data; public Node next, prev; } // Function to add Node at the end of a // Doubly List static Node insertAtEnd(Node head, int data) { Node new_node = new Node(); new_node.data = data; new_node.next = null; Node temp = head; if (head == null) { new_node.prev = null; head = new_node; return head; } while (temp.next != null) { temp = temp.next; } temp.next = new_node; new_node.prev = temp; return head; } // Function to print Doubly List static void printDLL(Node head) { while (head != null) { Console.Write(head.data + \" \"); head = head.next; } Console.WriteLine(); } // Function to Reverse a doubly linked list // in groups of given size static Node reverseByN(Node head, int k) { if (head == null) return null; head.prev = null; Node temp; Node curr = head; Node newHead = null; int count = 0; while (curr != null && count < k) { newHead = curr; temp = curr.prev; curr.prev = curr.next; curr.next = temp; curr = curr.prev; count++; } // Checking if the reversed List size is // equal to K or not. If it is not equal to k // that means we have reversed the last set of // size K and we don't need to call the // recursive function if (count >= k) { Node rest = reverseByN(curr, k); head.next = rest; if (rest != null) // it is required for prev link otherwise u // wont be backtrack list due to broken // links rest.prev = head; } return newHead; } // Driver code public static void Main(String[] args) { Node head = null; for (int i = 1; i <= 10; i++) { head = insertAtEnd(head, i); } printDLL(head); int n = 4; head = reverseByN(head, n); printDLL(head); }} // This code is contributed by umadevi9616", "e": 22476, "s": 20168, "text": null }, { "code": "<script> class Node { constructor() { this.data = 0; this.next = null; this.prev = null; }};// function to add Node at the end of a Doubly LinkedListfunction insertAtEnd(head, data){ var new_node = new Node(); new_node.data = data; new_node.next = null; var temp = head; if (head == null) { new_node.prev = null; head = new_node; return head; } while (temp.next != null) { temp = temp.next; } temp.next = new_node; new_node.prev = temp; return head;}// function to print Doubly LinkedListfunction printDLL(head){ while (head != null) { document.write( head.data + \" \"); head = head.next; } document.write(\"<br>\");}// function to Reverse a doubly linked list// in groups of given sizefunction reverseByN(head, k){ if (!head) return null; head.prev = null; var temp, curr = head, newHead; var count = 0; while (curr != null && count < k) { newHead = curr; temp = curr.prev; curr.prev = curr.next; curr.next = temp; curr = curr.prev; count++; } // checking if the reversed LinkedList size is // equal to K or not // if it is not equal to k that means we have reversed // the last set of size K and we don't need to call the // recursive function if (count >= k) { var rest = reverseByN(curr, k) head.next = rest; if(rest != null) /it is required for prev link otherwise u wont be backtrack list due to broken links rest.prev = head; } return newHead;} var head;for (var i = 1; i <= 10; i++) { head = insertAtEnd(head, i);}printDLL(head);var n = 4;head = reverseByN(head, n);printDLL(head); </script>", "e": 24240, "s": 22476, "text": null }, { "code": null, "e": 24284, "s": 24240, "text": "1 2 3 4 5 6 7 8 9 10 \n4 3 2 1 8 7 6 5 10 9 " }, { "code": null, "e": 24701, "s": 24284, "text": "Another approach (Iterative Method) : Here we will be using the iterative method in which we will begin from head node and reverse k nodes in the group. After reversing the k nodes we will continue this process with the next node after the k node until it becomes null. We will the achieving the desired result in only a single pass of the linked list with the time complexity of O(n) and space complexity of O(1). " }, { "code": null, "e": 24705, "s": 24701, "text": "C++" }, { "code": null, "e": 24710, "s": 24705, "text": "Java" }, { "code": null, "e": 24718, "s": 24710, "text": "Python3" }, { "code": null, "e": 24721, "s": 24718, "text": "C#" }, { "code": null, "e": 24732, "s": 24721, "text": "Javascript" }, { "code": "// C++ implementation to reverse a doubly linked list// in groups of given size without recursion// Iterative Method #include <iostream>using namespace std; // Represents a node of doubly linked liststruct Node { int data; Node *next, *prev;}; // function to get a new nodeNode* getNode(int data){ // allocating node Node* new_node = new Node(); new_node->data = data; new_node->next = new_node->prev = NULL; return new_node;} // function to insert a node at the beginning// of the Doubly Linked ListNode* push(Node* head, Node* new_node){ // since we are adding at the beginning, // prev is always NULL new_node->prev = NULL; // link the old list off the new node new_node->next = head; // change prev of head node to new node if (head != NULL) head->prev = new_node; // move the head to point to the new node head = new_node; return head;} // function to reverse a doubly linked list// in groups of given sizeNode* revListInGroupOfGivenSize(Node* head, int k){ if (!head) return head; Node* st = head; Node* globprev = NULL; Node* ans = NULL; while (st) { int count = 1; // to count k nodes Node* curr = st; Node* prev = NULL; Node* next = NULL; while (curr && count <= k) { // reversing k nodes next = curr->next; curr->prev = next; curr->next = prev; prev = curr; curr = next; count++; } if (!ans) { ans = prev; // to store ans i.e the new head ans->prev = NULL; } if (!globprev) globprev = st; // assigning the last node of the // reversed k nodes else { globprev->next = prev; prev->prev = globprev; // connecting last node of last // k group to the first node of // present k group globprev = st; } st = curr; // advancing the pointer for the next k // group } return ans;} // Function to print nodes in a// given doubly linked listvoid printList(Node* head){ while (head) { cout << head->data << \" \"; head = head->next; }} // Driver codeint main(){ // Start with the empty list Node* head = NULL; // Create doubly linked: 10<->8<->4<->2 head = push(head, getNode(2)); head = push(head, getNode(4)); head = push(head, getNode(8)); head = push(head, getNode(10)); int k = 2; cout << \"Original list: \"; printList(head); // Reverse doubly linked list in groups of // size 'k' head = revListInGroupOfGivenSize(head, k); cout << \"\\nModified list: \"; printList(head); return 0;} // This code is contributed by Tapesh (tapeshdua420)", "e": 27580, "s": 24732, "text": null }, { "code": "// Java implementation to reverse a doubly linked list// in groups of given size without recursion// Iterative Method import java.io.*;import java.util.*; // Represents a node of doubly linked listclass Node { int data; Node next, prev;} class GFG { // function to get a new node static Node getNode(int data) { // allocating node Node new_node = new Node(); new_node.data = data; new_node.next = new_node.prev = null; return new_node; } // function to insert a node at the beginning // of the Doubly Linked List static Node push(Node head, Node new_node) { // since we are adding at the beginning, // prev is always NULL new_node.prev = null; // link the old list off the new node new_node.next = head; // change prev of head node to new node if (head != null) head.prev = new_node; // move the head to point to the new node head = new_node; return head; } // function to reverse a doubly linked list // in groups of given size static Node revListInGroupOfGivenSize(Node head, int k) { if (head == null) return head; Node st = head; Node globprev = null; Node ans = null; while (st != null) { int count = 1; // to count k nodes Node curr = st; Node prev = null; Node next = null; while (curr != null && count <= k) { // reversing k nodes next = curr.next; curr.prev = next; curr.next = prev; prev = curr; curr = next; count++; } if (ans == null) { ans = prev; // to store ans i.e the new head ans.prev = null; } if (globprev == null) { globprev = st; // assigning the last node of // the reversed k nodes } else { globprev.next = prev; prev.prev = globprev; // connecting last node of // last k group to the first // node of present k group globprev = st; } st = curr; // advancing the pointer for the next // k group } return ans; } // Function to print nodes in a // given doubly linked list static void printList(Node head) { while (head != null) { System.out.print(head.data + \" \"); head = head.next; } } // Driver code public static void main(String args[]) { // Start with the empty list Node head = null; // Create doubly linked: 10<->8<->4<->2 head = push(head, getNode(2)); head = push(head, getNode(4)); head = push(head, getNode(8)); head = push(head, getNode(10)); int k = 2; System.out.print(\"Original list: \"); printList(head); // Reverse doubly linked list in groups of // size 'k' head = revListInGroupOfGivenSize(head, k); System.out.print(\"\\nModified list: \"); printList(head); }} // This code is contributed by Chayan Sharma", "e": 30931, "s": 27580, "text": null }, { "code": "# Python implementation to reverse a doubly# linked list in groups of given size without recursion# Iterative method. # Represents a node of doubly linked list.class Node: def __init__(self, data): self.data = data self.next = None # Function to get a new Node.def getNode(data): # allocating node new_node = Node(0) new_node.data = data new_node.next = new_node.prev = None return new_node # Function to insert a node at the beginning of the doubly linked list. def push(head, new_node): # since we are adding at the beginning, prev is always null. new_node.prev = None # link the old list off the new node. new_node.next = head # change prev of head node to new node. if ((head) != None): head.prev = new_node # move the head to point to the new node. head = new_node return head # Function to print nodes in given doubly linked list. def printList(head): while (head): print(head.data, end=\" \") head = head.next # Function to reverse a doubly linked list in groups of given size. def revListInGroupOfGivenSize(head, k): if head is None: return head st = head globprev, ans = None, None while (st != None): # Count the number of nodes. count = 1 curr = st prev, next_node = None, None while (curr != None and count <= k): # Reversing k nodes. next_node = curr.next curr.prev = next_node curr.next = prev prev = curr curr = next_node count += 1 if ans is None: ans = prev ans.prev = None if globprev is None: globprev = st else: globprev.next = prev prev.prev = globprev globprev = st st = curr return ans # Start with the empty list.head = None # Create a doubly linked list: 10<->8<->4<->2head = push(head, getNode(2))head = push(head, getNode(4))head = push(head, getNode(8))head = push(head, getNode(10)) print(\"Original list:\", end=\" \")printList(head) k = 2 # Reverse doubly linked list in groups of size 'k'head = revListInGroupOfGivenSize(head, k) print(\"\\nModified list:\", end=\" \")printList(head) # This code is contributed by lokesh (lokeshmvs21).", "e": 33235, "s": 30931, "text": null }, { "code": "// C# implementation to reverse a doubly linked list in// groups of given size without recursion Iterative Methodusing System; // Represents a node of doubly linked listpublic class Node { public int data; public Node next, prev;} public class GFG { // Function to get a new Node. static Node getNode(int data) { // allocating a new node. Node new_node = new Node(); new_node.data = data; new_node.next = new_node.prev = null; return new_node; } // Function to insert a node at the beginning of the // doubly linked list. static Node push(Node head, Node new_node) { // since we are adding at the beginning, prev is // always null. new_node.prev = null; // link the old list off the new node. new_node.next = head; // change prev of head node to new node. if (head != null) { head.prev = new_node; } // move the head to point to the new node. head = new_node; return head; } // Function to print nodes in a given doubly linked // list. static void printList(Node head) { while (head != null) { Console.Write(head.data + \" \"); head = head.next; } } // Function to reverse a doubly linked list in groups of // given size static Node revListInGroupOfGivenSize(Node head, int k) { if (head == null) { return head; } Node st = head; Node globprev = null; Node ans = null; while (st != null) { // count the number of nodes. int count = 1; Node curr = st; Node prev = null; Node next = null; // reversing k nodes. while (curr != null && count <= k) { next = curr.next; curr.prev = next; curr.next = prev; prev = curr; curr = next; count++; } if (ans == null) { // to store ans i.e the new head ans = prev; ans.prev = null; } if (globprev == null) { // assigning the last node of the reveresd k // nodes. globprev = st; } else { globprev.next = prev; prev.prev = globprev; // connecting last node of last k group to // the first node of present k group globprev = st; } // advancing the pointer for the next k group st = curr; } return ans; } static public void Main() { // Start with the empty list. Node head = null; // Create doubly linked list : 10<->8<->4<->2 head = push(head, getNode(2)); head = push(head, getNode(4)); head = push(head, getNode(8)); head = push(head, getNode(10)); Console.Write(\"Original list: \"); printList(head); int k = 2; // Reverse doubly linked list in groups of size 'k' head = revListInGroupOfGivenSize(head, k); Console.Write(\"\\nModified list: \"); printList(head); }} // This code is contributed by lokesh (lokeshmvs21)", "e": 36536, "s": 33235, "text": null }, { "code": "<script>// Javascript implementation to reverse a doubly linked list// in groups of given size without recursion// Iterative Method // Represents a node of doubly linked listclass Node { constructor() { this.data = null; this.next = null; this.prev = null; }} // function to get a new nodefunction getNode(data) { // allocating node let new_node = new Node(); new_node.data = data; new_node.next = new_node.prev = null; return new_node;} // function to insert a node at the beginning// of the Doubly Linked Listfunction push(head, new_node) { // since we are adding at the beginning, // prev is always NULL new_node.prev = null; // link the old list off the new node new_node.next = head; // change prev of head node to new node if (head != null) head.prev = new_node; // move the head to point to the new node head = new_node; return head;} // function to reverse a doubly linked list// in groups of given sizefunction revListInGroupOfGivenSize(head, k) { if (head == null) return head; let st = head; let globprev = null; let ans = null; while (st != null) { let count = 1; // to count k nodes let curr = st; let prev = null; let next = null; while (curr != null && count <= k) { // reversing k nodes next = curr.next; curr.prev = next; curr.next = prev; prev = curr; curr = next; count++; } if (ans == null) { ans = prev; // to store ans i.e the new head ans.prev = null; } if (globprev == null) { globprev = st; // assigning the last node of // the reversed k nodes } else { globprev.next = prev; prev.prev = globprev; // connecting last node of // last k group to the first // node of present k group globprev = st; } st = curr; // advancing the pointer for the next // k group } return ans;} // Function to print nodes in a// given doubly linked listfunction printList(head) { while (head != null) { document.write(head.data + \" \"); head = head.next; }} // Driver code // Start with the empty listlet head = null; // Create doubly linked: 10<->8<->4<->2head = push(head, getNode(2));head = push(head, getNode(4));head = push(head, getNode(8));head = push(head, getNode(10)); let k = 2; document.write(\"Original list: \");printList(head); // Reverse doubly linked list in groups of// size 'k'head = revListInGroupOfGivenSize(head, k); document.write(\"<br>Modified list: \");printList(head); // This code is contributed by Saurabh Jaiswal</script>", "e": 39337, "s": 36536, "text": null }, { "code": null, "e": 39387, "s": 39337, "text": "Original list: 10 8 4 2 \nModified list: 8 10 2 4 " }, { "code": null, "e": 39484, "s": 39387, "text": "Time Complexity: O(n) , where n is the number of nodes in the original listAuxiliary Space: O(1)" }, { "code": null, "e": 39497, "s": 39484, "text": "rachana soma" }, { "code": null, "e": 39508, "s": 39497, "text": "andrew1234" }, { "code": null, "e": 39519, "s": 39508, "text": "nidhi_biet" }, { "code": null, "e": 39531, "s": 39519, "text": "aashish1995" }, { "code": null, "e": 39542, "s": 39531, "text": "hungrywolf" }, { "code": null, "e": 39552, "s": 39542, "text": "rutvik_56" }, { "code": null, "e": 39573, "s": 39552, "text": "avanitrachhadiya2155" }, { "code": null, "e": 39583, "s": 39573, "text": "ruhelaa48" }, { "code": null, "e": 39595, "s": 39583, "text": "sanjeeverma" }, { "code": null, "e": 39608, "s": 39595, "text": "ankita_saini" }, { "code": null, "e": 39620, "s": 39608, "text": "umadevi9616" }, { "code": null, "e": 39637, "s": 39620, "text": "arorakashish0911" }, { "code": null, "e": 39645, "s": 39637, "text": "slayinu" }, { "code": null, "e": 39662, "s": 39645, "text": "chayansharmacs27" }, { "code": null, "e": 39679, "s": 39662, "text": "krithikakartik17" }, { "code": null, "e": 39696, "s": 39679, "text": "_saurabh_jaiswal" }, { "code": null, "e": 39709, "s": 39696, "text": "tapeshdua420" }, { "code": null, "e": 39721, "s": 39709, "text": "lokeshmvs21" }, { "code": null, "e": 39740, "s": 39721, "text": "doubly linked list" }, { "code": null, "e": 39748, "s": 39740, "text": "Reverse" }, { "code": null, "e": 39760, "s": 39748, "text": "Linked List" }, { "code": null, "e": 39772, "s": 39760, "text": "Linked List" }, { "code": null, "e": 39780, "s": 39772, "text": "Reverse" } ]
Java Program to Implement HashTables with Linear Probing
17 Jun, 2021 Hashing is a technique that is used to uniquely identify a specific object from a group of similar objects. Suppose an object is to be assigned a key to it to make searching easy. To store the key/value pair, one can use a simple array like a data structure where keys (integers) can be used directly as an index to store values. However, in cases where the keys are large and cannot be used directly as an index, one should use hashing. In hashing, large keys are converted into small keys by using hash functions. The values are then stored in a data structure called hash table. Linear Probing, It may happen that the hashing technique is used to create an already used index of the array. In such a case, we can search for the next empty location in the array by looking into the next cell until we find an empty cell. This technique is called linear probing. There are three basic operations linked with linear probing which are as follows: Search Insert Delete Implementation: Hash tables with linear probing by making a helper class and testing this in the main class. Example Java // Java Program to Implement Hash Tables with Linear Probing // Importing all classes from// java.util package// Importing all input output classesimport java.io.*;import java.util.*;// Importing Scanner class as in do-while// inputs are entered at run-time when// menu is popped to user to perform desired actionimport java.util.Scanner; // Helper class - LinearProbingHashTableclass LinearProbingHashTable { // Member variables of this class private int currentSize, maxSize; private String[] keys; private String[] vals; // Constructor of this class public LinearProbingHashTable(int capacity) { currentSize = 0; maxSize = capacity; keys = new String[maxSize]; vals = new String[maxSize]; } // Method 1 // Function to clear hash table public void makeEmpty() { currentSize = 0; keys = new String[maxSize]; vals = new String[maxSize]; } // Method 2 // Function to get size of hash table public int getSize() { return currentSize; } // Method 3 // Function to check if hash table is full public boolean isFull() { return currentSize == maxSize; } // Method 4 // Function to check if hash table is empty public boolean isEmpty() { return getSize() == 0; } // Method 5 // Function to check if hash table contains a key public boolean contains(String key) { return get(key) != null; } // Method 6 // Function to get hash code of a given key private int hash(String key) { return key.hashCode() % maxSize; } // Method 7 // Function to insert key-value pair public void insert(String key, String val) { int tmp = hash(key); int i = tmp; // Do-while loop // Do part for performing actions do { if (keys[i] == null) { keys[i] = key; vals[i] = val; currentSize++; return; } if (keys[i].equals(key)) { vals[i] = val; return; } i = (i + 1) % maxSize; } // Do-while loop // while part for condition check while (i != tmp); } // Method 8 // Function to get value for a given key public String get(String key) { int i = hash(key); while (keys[i] != null) { if (keys[i].equals(key)) return vals[i]; i = (i + 1) % maxSize; } return null; } // Method 9 // Function to remove key and its value public void remove(String key) { if (!contains(key)) return; // Find position key and delete int i = hash(key); while (!key.equals(keys[i])) i = (i + 1) % maxSize; keys[i] = vals[i] = null; // rehash all keys for (i = (i + 1) % maxSize; keys[i] != null; i = (i + 1) % maxSize) { String tmp1 = keys[i], tmp2 = vals[i]; keys[i] = vals[i] = null; currentSize--; insert(tmp1, tmp2); } currentSize--; } // Method 10 // Function to print HashTable public void printHashTable() { System.out.println("\nHash Table: "); for (int i = 0; i < maxSize; i++) if (keys[i] != null) System.out.println(keys[i] + " " + vals[i]); System.out.println(); }} // Main testing class// Main Class for LinearProbingHashTableTestpublic class GFG { // Main driver method public static void main(String[] args) { // Creating a scanner object // to take input from user Scanner scan = new Scanner(System.in); // Display messages System.out.println("Hash Table Test\n\n"); System.out.println("Enter size"); // maxSizeake object of LinearProbingHashTable LinearProbingHashTable lpht = new LinearProbingHashTable(scan.nextInt()); char ch; // Do-while loop // Do part for performing actions do // Menu is displayed // LinearProbingHashTable operations performed as // per keys Users enter 'y' to continue 'n' if // entered by user , the program terminates { // Menu // Display messages System.out.println("\nHash Table Operations\n"); System.out.println("1. insert "); System.out.println("2. remove"); System.out.println("3. get"); System.out.println("4. clear"); System.out.println("5. size"); // Reading integer using nextInt() int choice = scan.nextInt(); // Switch case switch (choice) { // Case 1 case 1: // Display message System.out.println("Enter key and value"); lpht.insert(scan.next(), scan.next()); // Break statement to terminate a case break; // Case 2 case 2: // Display message System.out.println("Enter key"); lpht.remove(scan.next()); // Break statement to terminate a case break; // Case 3 case 3: // Print statements System.out.println("Enter key"); System.out.println("Value = " + lpht.get(scan.next())); // Break statement to terminate a case break; // Case 4 case 4: lpht.makeEmpty(); // Print statement System.out.println("Hash Table Cleared\n"); // Break statement to terminate a case break; // Case 5 case 5: // Print statement System.out.println("Size = " + lpht.getSize()); break; // Default case // Executed when mentioned switch cases are not // matched default: // Print statement System.out.println("Wrong Entry \n "); // Break statement break; } // Display hash table lpht.printHashTable(); // Display message asking the user whether // he/she wants to continue System.out.println( "\nDo you want to continue (Type y or n) \n"); // Reading character using charAt() method to // fetch ch = scan.next().charAt(0); } while (ch == 'Y' || ch == 'y'); }} Output: Random action performed over Hash Table Size is entered as : 5 Two key-value pairs are insertedG 121F 212 G 121 F 212 Later Hash table is cleared sweetyty saurabh1990aror Java-Collections Java-HashTable Picked Technical Scripter 2020 Java Java Programs Technical Scripter Java Java-Collections Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Introduction to Java Constructors in Java Exceptions in Java Generics in Java Java Programming Examples Convert Double to Integer in Java Implementing a Linked List in Java using Class Factory method design pattern in Java Java Program to Remove Duplicate Elements From the Array
[ { "code": null, "e": 52, "s": 24, "text": "\n17 Jun, 2021" }, { "code": null, "e": 917, "s": 52, "text": "Hashing is a technique that is used to uniquely identify a specific object from a group of similar objects. Suppose an object is to be assigned a key to it to make searching easy. To store the key/value pair, one can use a simple array like a data structure where keys (integers) can be used directly as an index to store values. However, in cases where the keys are large and cannot be used directly as an index, one should use hashing. In hashing, large keys are converted into small keys by using hash functions. The values are then stored in a data structure called hash table. Linear Probing, It may happen that the hashing technique is used to create an already used index of the array. In such a case, we can search for the next empty location in the array by looking into the next cell until we find an empty cell. This technique is called linear probing. " }, { "code": null, "e": 999, "s": 917, "text": "There are three basic operations linked with linear probing which are as follows:" }, { "code": null, "e": 1006, "s": 999, "text": "Search" }, { "code": null, "e": 1013, "s": 1006, "text": "Insert" }, { "code": null, "e": 1020, "s": 1013, "text": "Delete" }, { "code": null, "e": 1129, "s": 1020, "text": "Implementation: Hash tables with linear probing by making a helper class and testing this in the main class." }, { "code": null, "e": 1137, "s": 1129, "text": "Example" }, { "code": null, "e": 1142, "s": 1137, "text": "Java" }, { "code": "// Java Program to Implement Hash Tables with Linear Probing // Importing all classes from// java.util package// Importing all input output classesimport java.io.*;import java.util.*;// Importing Scanner class as in do-while// inputs are entered at run-time when// menu is popped to user to perform desired actionimport java.util.Scanner; // Helper class - LinearProbingHashTableclass LinearProbingHashTable { // Member variables of this class private int currentSize, maxSize; private String[] keys; private String[] vals; // Constructor of this class public LinearProbingHashTable(int capacity) { currentSize = 0; maxSize = capacity; keys = new String[maxSize]; vals = new String[maxSize]; } // Method 1 // Function to clear hash table public void makeEmpty() { currentSize = 0; keys = new String[maxSize]; vals = new String[maxSize]; } // Method 2 // Function to get size of hash table public int getSize() { return currentSize; } // Method 3 // Function to check if hash table is full public boolean isFull() { return currentSize == maxSize; } // Method 4 // Function to check if hash table is empty public boolean isEmpty() { return getSize() == 0; } // Method 5 // Function to check if hash table contains a key public boolean contains(String key) { return get(key) != null; } // Method 6 // Function to get hash code of a given key private int hash(String key) { return key.hashCode() % maxSize; } // Method 7 // Function to insert key-value pair public void insert(String key, String val) { int tmp = hash(key); int i = tmp; // Do-while loop // Do part for performing actions do { if (keys[i] == null) { keys[i] = key; vals[i] = val; currentSize++; return; } if (keys[i].equals(key)) { vals[i] = val; return; } i = (i + 1) % maxSize; } // Do-while loop // while part for condition check while (i != tmp); } // Method 8 // Function to get value for a given key public String get(String key) { int i = hash(key); while (keys[i] != null) { if (keys[i].equals(key)) return vals[i]; i = (i + 1) % maxSize; } return null; } // Method 9 // Function to remove key and its value public void remove(String key) { if (!contains(key)) return; // Find position key and delete int i = hash(key); while (!key.equals(keys[i])) i = (i + 1) % maxSize; keys[i] = vals[i] = null; // rehash all keys for (i = (i + 1) % maxSize; keys[i] != null; i = (i + 1) % maxSize) { String tmp1 = keys[i], tmp2 = vals[i]; keys[i] = vals[i] = null; currentSize--; insert(tmp1, tmp2); } currentSize--; } // Method 10 // Function to print HashTable public void printHashTable() { System.out.println(\"\\nHash Table: \"); for (int i = 0; i < maxSize; i++) if (keys[i] != null) System.out.println(keys[i] + \" \" + vals[i]); System.out.println(); }} // Main testing class// Main Class for LinearProbingHashTableTestpublic class GFG { // Main driver method public static void main(String[] args) { // Creating a scanner object // to take input from user Scanner scan = new Scanner(System.in); // Display messages System.out.println(\"Hash Table Test\\n\\n\"); System.out.println(\"Enter size\"); // maxSizeake object of LinearProbingHashTable LinearProbingHashTable lpht = new LinearProbingHashTable(scan.nextInt()); char ch; // Do-while loop // Do part for performing actions do // Menu is displayed // LinearProbingHashTable operations performed as // per keys Users enter 'y' to continue 'n' if // entered by user , the program terminates { // Menu // Display messages System.out.println(\"\\nHash Table Operations\\n\"); System.out.println(\"1. insert \"); System.out.println(\"2. remove\"); System.out.println(\"3. get\"); System.out.println(\"4. clear\"); System.out.println(\"5. size\"); // Reading integer using nextInt() int choice = scan.nextInt(); // Switch case switch (choice) { // Case 1 case 1: // Display message System.out.println(\"Enter key and value\"); lpht.insert(scan.next(), scan.next()); // Break statement to terminate a case break; // Case 2 case 2: // Display message System.out.println(\"Enter key\"); lpht.remove(scan.next()); // Break statement to terminate a case break; // Case 3 case 3: // Print statements System.out.println(\"Enter key\"); System.out.println(\"Value = \" + lpht.get(scan.next())); // Break statement to terminate a case break; // Case 4 case 4: lpht.makeEmpty(); // Print statement System.out.println(\"Hash Table Cleared\\n\"); // Break statement to terminate a case break; // Case 5 case 5: // Print statement System.out.println(\"Size = \" + lpht.getSize()); break; // Default case // Executed when mentioned switch cases are not // matched default: // Print statement System.out.println(\"Wrong Entry \\n \"); // Break statement break; } // Display hash table lpht.printHashTable(); // Display message asking the user whether // he/she wants to continue System.out.println( \"\\nDo you want to continue (Type y or n) \\n\"); // Reading character using charAt() method to // fetch ch = scan.next().charAt(0); } while (ch == 'Y' || ch == 'y'); }}", "e": 7821, "s": 1142, "text": null }, { "code": null, "e": 7833, "s": 7824, "text": "Output: " }, { "code": null, "e": 7876, "s": 7835, "text": "Random action performed over Hash Table " }, { "code": null, "e": 7899, "s": 7876, "text": "Size is entered as : 5" }, { "code": null, "e": 7942, "s": 7899, "text": "Two key-value pairs are insertedG 121F 212" }, { "code": null, "e": 7948, "s": 7942, "text": "G 121" }, { "code": null, "e": 7954, "s": 7948, "text": "F 212" }, { "code": null, "e": 7982, "s": 7954, "text": "Later Hash table is cleared" }, { "code": null, "e": 7993, "s": 7984, "text": "sweetyty" }, { "code": null, "e": 8009, "s": 7993, "text": "saurabh1990aror" }, { "code": null, "e": 8026, "s": 8009, "text": "Java-Collections" }, { "code": null, "e": 8041, "s": 8026, "text": "Java-HashTable" }, { "code": null, "e": 8048, "s": 8041, "text": "Picked" }, { "code": null, "e": 8072, "s": 8048, "text": "Technical Scripter 2020" }, { "code": null, "e": 8077, "s": 8072, "text": "Java" }, { "code": null, "e": 8091, "s": 8077, "text": "Java Programs" }, { "code": null, "e": 8110, "s": 8091, "text": "Technical Scripter" }, { "code": null, "e": 8115, "s": 8110, "text": "Java" }, { "code": null, "e": 8132, "s": 8115, "text": "Java-Collections" }, { "code": null, "e": 8230, "s": 8132, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 8245, "s": 8230, "text": "Stream In Java" }, { "code": null, "e": 8266, "s": 8245, "text": "Introduction to Java" }, { "code": null, "e": 8287, "s": 8266, "text": "Constructors in Java" }, { "code": null, "e": 8306, "s": 8287, "text": "Exceptions in Java" }, { "code": null, "e": 8323, "s": 8306, "text": "Generics in Java" }, { "code": null, "e": 8349, "s": 8323, "text": "Java Programming Examples" }, { "code": null, "e": 8383, "s": 8349, "text": "Convert Double to Integer in Java" }, { "code": null, "e": 8430, "s": 8383, "text": "Implementing a Linked List in Java using Class" }, { "code": null, "e": 8468, "s": 8430, "text": "Factory method design pattern in Java" } ]
Matplotlib.pyplot.subplots() in Python
11 Apr, 2020 Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. Pyplot is a state-based interface to a Matplotlib module which provides a MATLAB-like interface. Sample Code # sample codeimport matplotlib.pyplot as plt plt.plot([1, 2, 3, 4], [16, 4, 1, 8]) plt.show() Output: The subplots() function in pyplot module of matplotlib library is used to create a figure and a set of subplots. Syntax: matplotlib.pyplot.subplots(nrows=1, ncols=1, sharex=False, sharey=False, squeeze=True, subplot_kw=None, gridspec_kw=None, **fig_kw) Parameters: This method accept the following parameters that are described below: nrows, ncols : These parameter are the number of rows/columns of the subplot grid. sharex, sharey : These parameter controls sharing of properties among x (sharex) or y (sharey) axes. squeeze : This parameter is an optional parameter and it contains boolean value with default as True. num: This parameter is the pyplot.figure keyword that sets the figure number or label. subplot_kwd: This parameter is the dict with keywords passed to the add_subplot call used to create each subplot. gridspec_kw: This parameter is the dict with keywords passed to the GridSpec constructor used to create the grid the subplots are placed on. Returns: This method return the following values. fig : This method return the figure layout. ax : This method return the axes.Axes object or array of Axes objects. Below examples illustrate the matplotlib.pyplot.subplots() function in matplotlib.pyplot: Example #1: # Implementation of matplotlib functionimport numpy as npimport matplotlib.pyplot as plt # First create some toy data:x = np.linspace(0, 2 * np.pi, 400)y = np.sin(x**2) fig, ax = plt.subplots()ax.plot(x, y)ax.set_title('Simple plot') fig.suptitle('matplotlib.pyplot.subplots() Example')plt.show() Output: Example #2: # Implementation of matplotlib functionimport numpy as npimport matplotlib.pyplot as plt # First create some toy data:x = np.linspace(0, 1.5 * np.pi, 100)y = np.sin(x**2)+np.cos(x**2) fig, axs = plt.subplots(2, 2, subplot_kw = dict(polar = True))axs[0, 0].plot(x, y)axs[1, 1].scatter(x, y) fig.suptitle('matplotlib.pyplot.subplots() Example')plt.show() Output: Python-matplotlib 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": "\n11 Apr, 2020" }, { "code": null, "e": 247, "s": 52, "text": "Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. Pyplot is a state-based interface to a Matplotlib module which provides a MATLAB-like interface." }, { "code": null, "e": 259, "s": 247, "text": "Sample Code" }, { "code": "# sample codeimport matplotlib.pyplot as plt plt.plot([1, 2, 3, 4], [16, 4, 1, 8]) plt.show() ", "e": 358, "s": 259, "text": null }, { "code": null, "e": 366, "s": 358, "text": "Output:" }, { "code": null, "e": 479, "s": 366, "text": "The subplots() function in pyplot module of matplotlib library is used to create a figure and a set of subplots." }, { "code": null, "e": 619, "s": 479, "text": "Syntax: matplotlib.pyplot.subplots(nrows=1, ncols=1, sharex=False, sharey=False, squeeze=True, subplot_kw=None, gridspec_kw=None, **fig_kw)" }, { "code": null, "e": 701, "s": 619, "text": "Parameters: This method accept the following parameters that are described below:" }, { "code": null, "e": 784, "s": 701, "text": "nrows, ncols : These parameter are the number of rows/columns of the subplot grid." }, { "code": null, "e": 885, "s": 784, "text": "sharex, sharey : These parameter controls sharing of properties among x (sharex) or y (sharey) axes." }, { "code": null, "e": 987, "s": 885, "text": "squeeze : This parameter is an optional parameter and it contains boolean value with default as True." }, { "code": null, "e": 1074, "s": 987, "text": "num: This parameter is the pyplot.figure keyword that sets the figure number or label." }, { "code": null, "e": 1188, "s": 1074, "text": "subplot_kwd: This parameter is the dict with keywords passed to the add_subplot call used to create each subplot." }, { "code": null, "e": 1329, "s": 1188, "text": "gridspec_kw: This parameter is the dict with keywords passed to the GridSpec constructor used to create the grid the subplots are placed on." }, { "code": null, "e": 1379, "s": 1329, "text": "Returns: This method return the following values." }, { "code": null, "e": 1423, "s": 1379, "text": "fig : This method return the figure layout." }, { "code": null, "e": 1494, "s": 1423, "text": "ax : This method return the axes.Axes object or array of Axes objects." }, { "code": null, "e": 1584, "s": 1494, "text": "Below examples illustrate the matplotlib.pyplot.subplots() function in matplotlib.pyplot:" }, { "code": null, "e": 1596, "s": 1584, "text": "Example #1:" }, { "code": "# Implementation of matplotlib functionimport numpy as npimport matplotlib.pyplot as plt # First create some toy data:x = np.linspace(0, 2 * np.pi, 400)y = np.sin(x**2) fig, ax = plt.subplots()ax.plot(x, y)ax.set_title('Simple plot') fig.suptitle('matplotlib.pyplot.subplots() Example')plt.show()", "e": 1898, "s": 1596, "text": null }, { "code": null, "e": 1906, "s": 1898, "text": "Output:" }, { "code": null, "e": 1918, "s": 1906, "text": "Example #2:" }, { "code": "# Implementation of matplotlib functionimport numpy as npimport matplotlib.pyplot as plt # First create some toy data:x = np.linspace(0, 1.5 * np.pi, 100)y = np.sin(x**2)+np.cos(x**2) fig, axs = plt.subplots(2, 2, subplot_kw = dict(polar = True))axs[0, 0].plot(x, y)axs[1, 1].scatter(x, y) fig.suptitle('matplotlib.pyplot.subplots() Example')plt.show()", "e": 2297, "s": 1918, "text": null }, { "code": null, "e": 2305, "s": 2297, "text": "Output:" }, { "code": null, "e": 2323, "s": 2305, "text": "Python-matplotlib" }, { "code": null, "e": 2330, "s": 2323, "text": "Python" }, { "code": null, "e": 2428, "s": 2330, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2446, "s": 2428, "text": "Python Dictionary" }, { "code": null, "e": 2488, "s": 2446, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 2510, "s": 2488, "text": "Enumerate() in Python" }, { "code": null, "e": 2545, "s": 2510, "text": "Read a file line by line in Python" }, { "code": null, "e": 2571, "s": 2545, "text": "Python String | replace()" }, { "code": null, "e": 2603, "s": 2571, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2632, "s": 2603, "text": "*args and **kwargs in Python" }, { "code": null, "e": 2659, "s": 2632, "text": "Python Classes and Objects" }, { "code": null, "e": 2680, "s": 2659, "text": "Python OOPs Concepts" } ]
Find all pairs in an Array in sorted order with minimum absolute difference
04 Jan, 2022 Given an integer array arr[] of size N, the task is to find all distinct pairs having minimum absolute difference and print them in ascending order. Examples: Input: arr[] = {4, 2, 1, 3}Output: {1, 2}, {2, 3}, {3, 4}Explanation: The minimum absolute difference between pairs is 1. Input: arr[] = {1, 3, 8, 10, 15}Output: {1, 3}, {8, 10}Explanation: The minimum absolute difference between the pairs {1, 3}, {8, 10} is 2. Approach: The idea is to consider the absolute difference of the adjacent elements of the sorted array. Follow the steps below to solve the problem: Sort the given array arr[]. Compare all adjacent pairs in the sorted array and find the minimum absolute difference between all adjacent pairs. Finally, print all the adjacent pairs having differences equal to the minimum absolute difference. Below is the implementation of the above code: C++ Java Python3 C# Javascript // C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to return all// pairs having minimal absolute differencevector<vector<int> > minAbsDiffPairs(vector<int>& arr){ vector<vector<int> > ans; int n = arr.size(); // Sort the array sort(arr.begin(), arr.end()); // Stores the minimal absolute difference int minDiff = INT_MAX; for (int i = 0; i < n - 1; i++) minDiff = min(minDiff, abs(arr[i] - arr[i + 1])); for (int i = 0; i < n - 1; i++) { vector<int> pair; if (abs(arr[i] - arr[i + 1]) == minDiff) { pair.push_back(min(arr[i], arr[i + 1])); pair.push_back(max(arr[i], arr[i + 1])); ans.push_back(pair); } } return ans;} // Driver Codeint main(){ vector<int> arr = { 4, 2, 1, 3 }; int N = (sizeof arr) / (sizeof arr[0]); vector<vector<int> > pairs = minAbsDiffPairs(arr); // Print all pairs for (auto v : pairs) cout << v[0] << " " << v[1] << endl; return 0;} // Java program for the above approachimport java.util.ArrayList;import java.util.Collections; class GFG{ // Function to return all // pairs having minimal absolute difference static ArrayList<ArrayList<Integer>> minAbsDiffPairs(ArrayList<Integer> arr) { ArrayList<ArrayList<Integer>> ans = new ArrayList<ArrayList<Integer>>(); int n = arr.size(); // Sort the array Collections.sort(arr); // Stores the minimal absolute difference int minDiff = Integer.MAX_VALUE; for (int i = 0; i < n - 1; i++) minDiff = Math.min(minDiff, Math.abs(arr.get(i) - arr.get(i + 1))); for (int i = 0; i < n - 1; i++) { ArrayList<Integer> pair = new ArrayList<Integer>(); if (Math.abs(arr.get(i) - arr.get(i + 1)) == minDiff) { pair.add(Math.min(arr.get(i), arr.get(i + 1))); pair.add(Math.max(arr.get(i), arr.get(i + 1))); ans.add(pair); } } return ans; } // Driver Code public static void main(String args[]) { ArrayList<Integer> arr = new ArrayList<Integer>(); arr.add(4); arr.add(2); arr.add(1); arr.add(3); ArrayList<ArrayList<Integer>> pairs = minAbsDiffPairs(arr); // Print all pairs // System.out.println(pairs); for (ArrayList<Integer> v : pairs) { for (int w : v) System.out.print(w + " "); System.out.println(""); } }} // This code is contributed by saurabh_jaiswal. # Python3 program for the above approachimport math as Math # Function to return all pairs having# minimal absolute differencedef minAbsDiffPairs(arr): ans = [] n = len(arr) # Sort the array arr.sort() # Stores the minimal absolute difference minDiff = 10 ** 9 for i in range(n - 1): minDiff = min(minDiff, Math.fabs(arr[i] - arr[i + 1])) for i in range(n - 1): pair = [] if (Math.fabs(arr[i] - arr[i + 1]) == minDiff): pair.append(min(arr[i], arr[i + 1])) pair.append(max(arr[i], arr[i + 1])) ans.append(pair) return ans # Driver Codearr = [ 4, 2, 1, 3 ]N = len(arr) pairs = minAbsDiffPairs(arr) # Print all pairsfor v in pairs: print(f"{v[0]} {v[1]}") # This code is contributed by gfgking // C# program for the above approachusing System;using System.Collections.Generic; class GFG{ // Function to return all // pairs having minimal Absolute difference static List<List<int>> minAbsDiffPairs(List<int> arr) { List<List<int>> ans = new List<List<int>>(); int n = arr.Count; // Sort the array arr.Sort(); // Stores the minimal Absolute difference int minDiff = int.MaxValue; for (int i = 0; i < n - 1; i++) minDiff = Math.Min(minDiff, Math.Abs(arr[i] - arr[i + 1])); for (int i = 0; i < n - 1; i++) { List<int> pair = new List<int>(); if (Math.Abs(arr[i] - arr[i + 1]) == minDiff) { pair.Add(Math.Min(arr[i], arr[i + 1])); pair.Add(Math.Max(arr[i], arr[i + 1])); ans.Add(pair); } } return ans; } // Driver Code public static void Main() { List<int> arr = new List<int>(); arr.Add(4); arr.Add(2); arr.Add(1); arr.Add(3); List<List<int>> pairs = minAbsDiffPairs(arr); // Print all pairs // System.out.println(pairs); foreach (List<int> v in pairs) { foreach (int w in v) Console.Write(w + " "); Console.WriteLine(""); } }} // This code is contributed by saurabh_jaiswal. <script> // JavaScript code for the above approach // Function to return all // pairs having minimal absolute difference function minAbsDiffPairs(arr) { let ans = []; let n = arr.length; // Sort the array arr.sort(function (a, b) { return a - b }) // Stores the minimal absolute difference let minDiff = Number.MAX_VALUE; for (let i = 0; i < n - 1; i++) minDiff = Math.min(minDiff, Math.abs(arr[i] - arr[i + 1])); for (let i = 0; i < n - 1; i++) { let pair = []; if (Math.abs(arr[i] - arr[i + 1]) == minDiff) { pair.push(Math.min(arr[i], arr[i + 1])); pair.push(Math.max(arr[i], arr[i + 1])); ans.push(pair); } } return ans; } // Driver Code let arr = [4, 2, 1, 3]; let N = arr.length; let pairs = minAbsDiffPairs(arr); // Print all pairs for (let v of pairs) document.write(v[0] + " " + v[1] + '<br>') // This code is contributed by Potta Lokesh </script> 1 2 2 3 3 4 Time Complexity: O(NlogN)Auxiliary Space: O(N) lokeshpotta20 gfgking _saurabh_jaiswal Algo-Geek 2021 Algo Geek Arrays Mathematical Sorting Arrays Mathematical Sorting Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Generate all Binary Strings of length N with equal count of 0s and 1s Count of ordered pairs (i, j) such that arr[i] and arr[j] concatenates to X Sort strings on the basis of their numeric part Number of ways to divide a N elements equally into group of at least 2 Find Permutation of N numbers in range [1, N] such that K numbers have value same as their index Arrays in Java Write a program to reverse an array or string Maximum and minimum of an array using minimum number of comparisons Top 50 Array Coding Problems for Interviews Largest Sum Contiguous Subarray
[ { "code": null, "e": 28, "s": 0, "text": "\n04 Jan, 2022" }, { "code": null, "e": 178, "s": 28, "text": "Given an integer array arr[] of size N, the task is to find all distinct pairs having minimum absolute difference and print them in ascending order. " }, { "code": null, "e": 188, "s": 178, "text": "Examples:" }, { "code": null, "e": 310, "s": 188, "text": "Input: arr[] = {4, 2, 1, 3}Output: {1, 2}, {2, 3}, {3, 4}Explanation: The minimum absolute difference between pairs is 1." }, { "code": null, "e": 451, "s": 310, "text": "Input: arr[] = {1, 3, 8, 10, 15}Output: {1, 3}, {8, 10}Explanation: The minimum absolute difference between the pairs {1, 3}, {8, 10} is 2. " }, { "code": null, "e": 600, "s": 451, "text": "Approach: The idea is to consider the absolute difference of the adjacent elements of the sorted array. Follow the steps below to solve the problem:" }, { "code": null, "e": 628, "s": 600, "text": "Sort the given array arr[]." }, { "code": null, "e": 744, "s": 628, "text": "Compare all adjacent pairs in the sorted array and find the minimum absolute difference between all adjacent pairs." }, { "code": null, "e": 843, "s": 744, "text": "Finally, print all the adjacent pairs having differences equal to the minimum absolute difference." }, { "code": null, "e": 890, "s": 843, "text": "Below is the implementation of the above code:" }, { "code": null, "e": 894, "s": 890, "text": "C++" }, { "code": null, "e": 899, "s": 894, "text": "Java" }, { "code": null, "e": 907, "s": 899, "text": "Python3" }, { "code": null, "e": 910, "s": 907, "text": "C#" }, { "code": null, "e": 921, "s": 910, "text": "Javascript" }, { "code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to return all// pairs having minimal absolute differencevector<vector<int> > minAbsDiffPairs(vector<int>& arr){ vector<vector<int> > ans; int n = arr.size(); // Sort the array sort(arr.begin(), arr.end()); // Stores the minimal absolute difference int minDiff = INT_MAX; for (int i = 0; i < n - 1; i++) minDiff = min(minDiff, abs(arr[i] - arr[i + 1])); for (int i = 0; i < n - 1; i++) { vector<int> pair; if (abs(arr[i] - arr[i + 1]) == minDiff) { pair.push_back(min(arr[i], arr[i + 1])); pair.push_back(max(arr[i], arr[i + 1])); ans.push_back(pair); } } return ans;} // Driver Codeint main(){ vector<int> arr = { 4, 2, 1, 3 }; int N = (sizeof arr) / (sizeof arr[0]); vector<vector<int> > pairs = minAbsDiffPairs(arr); // Print all pairs for (auto v : pairs) cout << v[0] << \" \" << v[1] << endl; return 0;}", "e": 1946, "s": 921, "text": null }, { "code": "// Java program for the above approachimport java.util.ArrayList;import java.util.Collections; class GFG{ // Function to return all // pairs having minimal absolute difference static ArrayList<ArrayList<Integer>> minAbsDiffPairs(ArrayList<Integer> arr) { ArrayList<ArrayList<Integer>> ans = new ArrayList<ArrayList<Integer>>(); int n = arr.size(); // Sort the array Collections.sort(arr); // Stores the minimal absolute difference int minDiff = Integer.MAX_VALUE; for (int i = 0; i < n - 1; i++) minDiff = Math.min(minDiff, Math.abs(arr.get(i) - arr.get(i + 1))); for (int i = 0; i < n - 1; i++) { ArrayList<Integer> pair = new ArrayList<Integer>(); if (Math.abs(arr.get(i) - arr.get(i + 1)) == minDiff) { pair.add(Math.min(arr.get(i), arr.get(i + 1))); pair.add(Math.max(arr.get(i), arr.get(i + 1))); ans.add(pair); } } return ans; } // Driver Code public static void main(String args[]) { ArrayList<Integer> arr = new ArrayList<Integer>(); arr.add(4); arr.add(2); arr.add(1); arr.add(3); ArrayList<ArrayList<Integer>> pairs = minAbsDiffPairs(arr); // Print all pairs // System.out.println(pairs); for (ArrayList<Integer> v : pairs) { for (int w : v) System.out.print(w + \" \"); System.out.println(\"\"); } }} // This code is contributed by saurabh_jaiswal.", "e": 3501, "s": 1946, "text": null }, { "code": "# Python3 program for the above approachimport math as Math # Function to return all pairs having# minimal absolute differencedef minAbsDiffPairs(arr): ans = [] n = len(arr) # Sort the array arr.sort() # Stores the minimal absolute difference minDiff = 10 ** 9 for i in range(n - 1): minDiff = min(minDiff, Math.fabs(arr[i] - arr[i + 1])) for i in range(n - 1): pair = [] if (Math.fabs(arr[i] - arr[i + 1]) == minDiff): pair.append(min(arr[i], arr[i + 1])) pair.append(max(arr[i], arr[i + 1])) ans.append(pair) return ans # Driver Codearr = [ 4, 2, 1, 3 ]N = len(arr) pairs = minAbsDiffPairs(arr) # Print all pairsfor v in pairs: print(f\"{v[0]} {v[1]}\") # This code is contributed by gfgking", "e": 4335, "s": 3501, "text": null }, { "code": "// C# program for the above approachusing System;using System.Collections.Generic; class GFG{ // Function to return all // pairs having minimal Absolute difference static List<List<int>> minAbsDiffPairs(List<int> arr) { List<List<int>> ans = new List<List<int>>(); int n = arr.Count; // Sort the array arr.Sort(); // Stores the minimal Absolute difference int minDiff = int.MaxValue; for (int i = 0; i < n - 1; i++) minDiff = Math.Min(minDiff, Math.Abs(arr[i] - arr[i + 1])); for (int i = 0; i < n - 1; i++) { List<int> pair = new List<int>(); if (Math.Abs(arr[i] - arr[i + 1]) == minDiff) { pair.Add(Math.Min(arr[i], arr[i + 1])); pair.Add(Math.Max(arr[i], arr[i + 1])); ans.Add(pair); } } return ans; } // Driver Code public static void Main() { List<int> arr = new List<int>(); arr.Add(4); arr.Add(2); arr.Add(1); arr.Add(3); List<List<int>> pairs = minAbsDiffPairs(arr); // Print all pairs // System.out.println(pairs); foreach (List<int> v in pairs) { foreach (int w in v) Console.Write(w + \" \"); Console.WriteLine(\"\"); } }} // This code is contributed by saurabh_jaiswal.", "e": 5552, "s": 4335, "text": null }, { "code": "<script> // JavaScript code for the above approach // Function to return all // pairs having minimal absolute difference function minAbsDiffPairs(arr) { let ans = []; let n = arr.length; // Sort the array arr.sort(function (a, b) { return a - b }) // Stores the minimal absolute difference let minDiff = Number.MAX_VALUE; for (let i = 0; i < n - 1; i++) minDiff = Math.min(minDiff, Math.abs(arr[i] - arr[i + 1])); for (let i = 0; i < n - 1; i++) { let pair = []; if (Math.abs(arr[i] - arr[i + 1]) == minDiff) { pair.push(Math.min(arr[i], arr[i + 1])); pair.push(Math.max(arr[i], arr[i + 1])); ans.push(pair); } } return ans; } // Driver Code let arr = [4, 2, 1, 3]; let N = arr.length; let pairs = minAbsDiffPairs(arr); // Print all pairs for (let v of pairs) document.write(v[0] + \" \" + v[1] + '<br>') // This code is contributed by Potta Lokesh </script>", "e": 6567, "s": 5552, "text": null }, { "code": null, "e": 6579, "s": 6567, "text": "1 2\n2 3\n3 4" }, { "code": null, "e": 6626, "s": 6579, "text": "Time Complexity: O(NlogN)Auxiliary Space: O(N)" }, { "code": null, "e": 6642, "s": 6628, "text": "lokeshpotta20" }, { "code": null, "e": 6650, "s": 6642, "text": "gfgking" }, { "code": null, "e": 6667, "s": 6650, "text": "_saurabh_jaiswal" }, { "code": null, "e": 6682, "s": 6667, "text": "Algo-Geek 2021" }, { "code": null, "e": 6692, "s": 6682, "text": "Algo Geek" }, { "code": null, "e": 6699, "s": 6692, "text": "Arrays" }, { "code": null, "e": 6712, "s": 6699, "text": "Mathematical" }, { "code": null, "e": 6720, "s": 6712, "text": "Sorting" }, { "code": null, "e": 6727, "s": 6720, "text": "Arrays" }, { "code": null, "e": 6740, "s": 6727, "text": "Mathematical" }, { "code": null, "e": 6748, "s": 6740, "text": "Sorting" }, { "code": null, "e": 6846, "s": 6748, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6916, "s": 6846, "text": "Generate all Binary Strings of length N with equal count of 0s and 1s" }, { "code": null, "e": 6992, "s": 6916, "text": "Count of ordered pairs (i, j) such that arr[i] and arr[j] concatenates to X" }, { "code": null, "e": 7040, "s": 6992, "text": "Sort strings on the basis of their numeric part" }, { "code": null, "e": 7111, "s": 7040, "text": "Number of ways to divide a N elements equally into group of at least 2" }, { "code": null, "e": 7208, "s": 7111, "text": "Find Permutation of N numbers in range [1, N] such that K numbers have value same as their index" }, { "code": null, "e": 7223, "s": 7208, "text": "Arrays in Java" }, { "code": null, "e": 7269, "s": 7223, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 7337, "s": 7269, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 7381, "s": 7337, "text": "Top 50 Array Coding Problems for Interviews" } ]
Difference between Docker Image and Container
12 Jul, 2022 1. Docker Image: The concept of Images and Container is like class and object in which object is an instance of class and class is the blueprint of the object. Images are different in Virtual Machines and Docker, in virtual machines images, are just snapshots of running virtual machines at different points of time but Docker images are a little bit different from them, and the most important and major difference is that Docker images are immutable that is they can not be changed. In the real world, it happens a lot that software works on one computer but it does not works on others due to different environments, this issue is completely solved by docker images and using this, the application will work same on everyone’s PC. Every developer on a team will have exact same development instance. Each testing instance is exactly the same as the development instance. Your production instance is exactly the same as the testing instance. Also, Developers around World can share their Docker Images on a Platform called Docker HUB. 2. Docker Container: They are actually Docker Virtual Machines but are commonly called Docker Containers. If a Docker image is a map of the house, then Docker Container is actual build house or in other words, we can call it an instance of an image. As per the official website, containers are runnable instance of an image. You can create, start, stop, move, or delete a container using Docker API or CLI. You can connect a container to one or more networks, attach storage to it, or even create a new image based on its current state. An application runs using a cluster of containers which are self isolated from one another and also from host machine where they are running example if a backend application is running on a docker container at port 8000 and you tried to access it from host machine, you will not be able to access as containers are self-isolated and in that case you have to explicitly expose your application at a certain port and connect your machine port to that port. Example: docker run --publish 8000:8080 --detach --name alias_name application_name:1.0 Here application running at port 8080 in container is connected to port 8000 at the host machine. Now it can access application using URL localhost:8000 Difference between Docker Image and Docker Container: khushb99 Difference Between 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": "\n12 Jul, 2022" }, { "code": null, "e": 1066, "s": 28, "text": "1. Docker Image: The concept of Images and Container is like class and object in which object is an instance of class and class is the blueprint of the object. Images are different in Virtual Machines and Docker, in virtual machines images, are just snapshots of running virtual machines at different points of time but Docker images are a little bit different from them, and the most important and major difference is that Docker images are immutable that is they can not be changed. In the real world, it happens a lot that software works on one computer but it does not works on others due to different environments, this issue is completely solved by docker images and using this, the application will work same on everyone’s PC. Every developer on a team will have exact same development instance. Each testing instance is exactly the same as the development instance. Your production instance is exactly the same as the testing instance. Also, Developers around World can share their Docker Images on a Platform called Docker HUB. " }, { "code": null, "e": 2058, "s": 1066, "text": "2. Docker Container: They are actually Docker Virtual Machines but are commonly called Docker Containers. If a Docker image is a map of the house, then Docker Container is actual build house or in other words, we can call it an instance of an image. As per the official website, containers are runnable instance of an image. You can create, start, stop, move, or delete a container using Docker API or CLI. You can connect a container to one or more networks, attach storage to it, or even create a new image based on its current state. An application runs using a cluster of containers which are self isolated from one another and also from host machine where they are running example if a backend application is running on a docker container at port 8000 and you tried to access it from host machine, you will not be able to access as containers are self-isolated and in that case you have to explicitly expose your application at a certain port and connect your machine port to that port." }, { "code": null, "e": 2067, "s": 2058, "text": "Example:" }, { "code": null, "e": 2147, "s": 2067, "text": "docker run --publish 8000:8080 --detach --name alias_name application_name:1.0 " }, { "code": null, "e": 2300, "s": 2147, "text": "Here application running at port 8080 in container is connected to port 8000 at the host machine. Now it can access application using URL localhost:8000" }, { "code": null, "e": 2354, "s": 2300, "text": "Difference between Docker Image and Docker Container:" }, { "code": null, "e": 2363, "s": 2354, "text": "khushb99" }, { "code": null, "e": 2382, "s": 2363, "text": "Difference Between" }, { "code": null, "e": 2399, "s": 2382, "text": "Web Technologies" } ]
Python | Tkinter ttk.Checkbutton and comparison with simple Checkbutton
27 Mar, 2019 Tkinter is a GUI (Graphical User Interface) module which comes along with the Python itself. This module is widely used to create GUI applications. tkinter.ttk is used to create the GUI applications with the effects of modern graphics which cannot be achieved using only tkinter. Checkbutton is used to select multiple options. Checkbuttons can be created using following snippet. chkbtn = ttk.Checkbutton(master, option=value, ...) Code #1: # importing tkinter.ttkfrom tkinter import *from tkinter.ttk import * # creating rootroot = Tk() # label textLabel(root, text ='Select Programming language of your choice').place(x = 20, y = 0) # check buttonsjava = Checkbutton(root, text ='Java', takefocus = 0).place(x = 40, y = 30) cpp = Checkbutton(root, text ='C++', takefocus = 0).place(x = 40, y = 50) python = Checkbutton(root, text ='Python', takefocus = 0).place(x = 40, y = 70) c = Checkbutton(root, text ='C', takefocus = 0).place(x = 40, y = 90) root.mainloop() Output: Code #2: Difference between simple Checkbutton and ttk.Checkbutton # importing tkinter and ttkfrom tkinter import * from tkinter import ttk # rootroot = Tk() # This will depict the features of Simple CheckbuttonLabel(root, text ='Simple Checkbutton').place(x = 10, y = 10)chkbtn1 = Checkbutton(root, text ='Checkbutton1', takefocus = 0).place(x = 10, y = 40)chkbtn2 = Checkbutton(root, text ='Checkbutton2', takefocus = 0).place(x = 10, y = 60) # This will depict the features of ttk.CheckbuttonLabel(root, text ='ttk.Checkbutton').place(x = 140, y = 10)chkbtn1 = ttk.Checkbutton(root, text ='Checkbutton1', takefocus = 0).place(x = 140, y = 40)chkbtn2 = ttk.Checkbutton(root, text ='Checkbutton2', takefocus = 0).place(x = 140, y = 60) root.mainloop() Output: Notice the difference in the appearance of both the Checkbuttons which is all due to the modern graphics. In the above Code when mouse is being hovered over the ttk.Checkbutton you may see a blue color effect (effect may change from os from os). When we hover mouse over Simple Checkbutton you may not experience any such kind of effects. Python-tkinter Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n27 Mar, 2019" }, { "code": null, "e": 356, "s": 28, "text": "Tkinter is a GUI (Graphical User Interface) module which comes along with the Python itself. This module is widely used to create GUI applications. tkinter.ttk is used to create the GUI applications with the effects of modern graphics which cannot be achieved using only tkinter. Checkbutton is used to select multiple options." }, { "code": null, "e": 409, "s": 356, "text": "Checkbuttons can be created using following snippet." }, { "code": null, "e": 461, "s": 409, "text": "chkbtn = ttk.Checkbutton(master, option=value, ...)" }, { "code": null, "e": 470, "s": 461, "text": "Code #1:" }, { "code": "# importing tkinter.ttkfrom tkinter import *from tkinter.ttk import * # creating rootroot = Tk() # label textLabel(root, text ='Select Programming language of your choice').place(x = 20, y = 0) # check buttonsjava = Checkbutton(root, text ='Java', takefocus = 0).place(x = 40, y = 30) cpp = Checkbutton(root, text ='C++', takefocus = 0).place(x = 40, y = 50) python = Checkbutton(root, text ='Python', takefocus = 0).place(x = 40, y = 70) c = Checkbutton(root, text ='C', takefocus = 0).place(x = 40, y = 90) root.mainloop()", "e": 1073, "s": 470, "text": null }, { "code": null, "e": 1081, "s": 1073, "text": "Output:" }, { "code": null, "e": 1148, "s": 1081, "text": "Code #2: Difference between simple Checkbutton and ttk.Checkbutton" }, { "code": "# importing tkinter and ttkfrom tkinter import * from tkinter import ttk # rootroot = Tk() # This will depict the features of Simple CheckbuttonLabel(root, text ='Simple Checkbutton').place(x = 10, y = 10)chkbtn1 = Checkbutton(root, text ='Checkbutton1', takefocus = 0).place(x = 10, y = 40)chkbtn2 = Checkbutton(root, text ='Checkbutton2', takefocus = 0).place(x = 10, y = 60) # This will depict the features of ttk.CheckbuttonLabel(root, text ='ttk.Checkbutton').place(x = 140, y = 10)chkbtn1 = ttk.Checkbutton(root, text ='Checkbutton1', takefocus = 0).place(x = 140, y = 40)chkbtn2 = ttk.Checkbutton(root, text ='Checkbutton2', takefocus = 0).place(x = 140, y = 60) root.mainloop()", "e": 1895, "s": 1148, "text": null }, { "code": null, "e": 1903, "s": 1895, "text": "Output:" }, { "code": null, "e": 2242, "s": 1903, "text": "Notice the difference in the appearance of both the Checkbuttons which is all due to the modern graphics. In the above Code when mouse is being hovered over the ttk.Checkbutton you may see a blue color effect (effect may change from os from os). When we hover mouse over Simple Checkbutton you may not experience any such kind of effects." }, { "code": null, "e": 2257, "s": 2242, "text": "Python-tkinter" }, { "code": null, "e": 2264, "s": 2257, "text": "Python" } ]
SQL Query to Update All Rows in a Table
10 Oct, 2021 The Update statement is a SQL keyword to update data in the database. We can update all the rows in the database or some values with the help of conditions. The update is a SQL keyword and it falls under Data Manipulation Language(DML), as the name suggests it is used to manipulate the data. There are many DML keywords that fall under this: UPDATE INSERT DELETE SELECT SQL is a case insensitive language i.e SELECT * FROM PRODUCTS is the same as select * from products. But we write keywords in capital letters and tables, column names in small letters as a convention. Step 1: CREATE DATABASE Syntax: CREATE DATABASE database_name; Step 2: TO CREATE TABLE(PRODUCTS) Query: CREATE TABLE products(product_id int primary key, product_name varchar(45), product_cost float); Step 3: TO INSERT VALUES IN TABLE Query: INSERT INTO products VALUES (1001,'Colgate Toothpaste', 2.25), (1002, 'Sensodyne Toothpaste', 2.30), (1003, 'Listrine Mouthwash', 1.75), (1004, 'T-Shirt', 1.75), (1005, 'Pants', 2.35); Step 4: Now let’s see the data inside the table we created. Query: SELECT * FROM products; Output: Step 5: TO UPDATE ALL DATA Syntax: UPDATE table_name SET column_name1 = new_value1, column_name2 = new_value2 ---- ; Here table_name is the name of the table, column_name is the column whose value you want to update, new_value is the updated value. Let’s look at an example. Now our task is to update the product_cost to 4, for all product_id(s), so let’s see how it is done. Query: UPDATE products SET product_cost = 4; Output: As you can see product_cost for all product_id(s) is changed to 4. Syntax: UPDATE table_name SET column_name1 = new_value1, column_name2 = new_value2 ---- WHERE condition; Here table_name is the name of the table, column_name is the column whose value you want to update, new_value is the updated value, WHERE is used to filter for specific data. Let’s look at an example. Now our task is to update the product_cost to 4, for product_id 1001, so let’s see how it is done. Query: UPDATE products SET product_cost = 4 WHERE product_id = 1001; Output: As you can see product_cost for product_id 1001 is changed to 4. Picked SQL-Query SQL-Server SQL SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. CTE in SQL SQL Trigger | Student Database How to Update Multiple Columns in Single Update Statement in SQL? SQL Interview Questions SQL | Views Difference between DELETE, DROP and TRUNCATE Window functions in SQL SQL | GROUP BY MySQL | Group_CONCAT() Function Difference between DELETE and TRUNCATE
[ { "code": null, "e": 52, "s": 24, "text": "\n10 Oct, 2021" }, { "code": null, "e": 397, "s": 52, "text": "The Update statement is a SQL keyword to update data in the database. We can update all the rows in the database or some values with the help of conditions. The update is a SQL keyword and it falls under Data Manipulation Language(DML), as the name suggests it is used to manipulate the data. There are many DML keywords that fall under this:" }, { "code": null, "e": 404, "s": 397, "text": "UPDATE" }, { "code": null, "e": 411, "s": 404, "text": "INSERT" }, { "code": null, "e": 418, "s": 411, "text": "DELETE" }, { "code": null, "e": 425, "s": 418, "text": "SELECT" }, { "code": null, "e": 626, "s": 425, "text": "SQL is a case insensitive language i.e SELECT * FROM PRODUCTS is the same as select * from products. But we write keywords in capital letters and tables, column names in small letters as a convention." }, { "code": null, "e": 650, "s": 626, "text": "Step 1: CREATE DATABASE" }, { "code": null, "e": 658, "s": 650, "text": "Syntax:" }, { "code": null, "e": 689, "s": 658, "text": "CREATE DATABASE database_name;" }, { "code": null, "e": 723, "s": 689, "text": "Step 2: TO CREATE TABLE(PRODUCTS)" }, { "code": null, "e": 730, "s": 723, "text": "Query:" }, { "code": null, "e": 829, "s": 730, "text": "CREATE TABLE products(product_id int \nprimary key, product_name varchar(45),\n product_cost float);" }, { "code": null, "e": 863, "s": 829, "text": "Step 3: TO INSERT VALUES IN TABLE" }, { "code": null, "e": 871, "s": 863, "text": "Query: " }, { "code": null, "e": 1057, "s": 871, "text": "INSERT INTO products VALUES\n(1001,'Colgate Toothpaste', 2.25),\n(1002, 'Sensodyne Toothpaste', 2.30),\n(1003, 'Listrine Mouthwash', 1.75), \n(1004, 'T-Shirt', 1.75),\n(1005, 'Pants', 2.35);" }, { "code": null, "e": 1117, "s": 1057, "text": "Step 4: Now let’s see the data inside the table we created." }, { "code": null, "e": 1124, "s": 1117, "text": "Query:" }, { "code": null, "e": 1148, "s": 1124, "text": "SELECT * FROM products;" }, { "code": null, "e": 1156, "s": 1148, "text": "Output:" }, { "code": null, "e": 1183, "s": 1156, "text": "Step 5: TO UPDATE ALL DATA" }, { "code": null, "e": 1193, "s": 1183, "text": "Syntax: " }, { "code": null, "e": 1277, "s": 1193, "text": "UPDATE table_name SET column_name1 = new_value1, \ncolumn_name2 = new_value2 ---- ;" }, { "code": null, "e": 1436, "s": 1277, "text": "Here table_name is the name of the table, column_name is the column whose value you want to update, new_value is the updated value. Let’s look at an example. " }, { "code": null, "e": 1538, "s": 1436, "text": "Now our task is to update the product_cost to 4, for all product_id(s), so let’s see how it is done." }, { "code": null, "e": 1545, "s": 1538, "text": "Query:" }, { "code": null, "e": 1583, "s": 1545, "text": "UPDATE products SET product_cost = 4;" }, { "code": null, "e": 1591, "s": 1583, "text": "Output:" }, { "code": null, "e": 1659, "s": 1591, "text": "As you can see product_cost for all product_id(s) is changed to 4." }, { "code": null, "e": 1667, "s": 1659, "text": "Syntax:" }, { "code": null, "e": 1766, "s": 1667, "text": "UPDATE table_name SET column_name1 = new_value1, \ncolumn_name2 = new_value2 ---- WHERE condition;" }, { "code": null, "e": 1941, "s": 1766, "text": "Here table_name is the name of the table, column_name is the column whose value you want to update, new_value is the updated value, WHERE is used to filter for specific data." }, { "code": null, "e": 1969, "s": 1941, "text": "Let’s look at an example. " }, { "code": null, "e": 2069, "s": 1969, "text": "Now our task is to update the product_cost to 4, for product_id 1001, so let’s see how it is done." }, { "code": null, "e": 2076, "s": 2069, "text": "Query:" }, { "code": null, "e": 2139, "s": 2076, "text": "UPDATE products SET product_cost \n= 4 WHERE product_id = 1001;" }, { "code": null, "e": 2147, "s": 2139, "text": "Output:" }, { "code": null, "e": 2212, "s": 2147, "text": "As you can see product_cost for product_id 1001 is changed to 4." }, { "code": null, "e": 2219, "s": 2212, "text": "Picked" }, { "code": null, "e": 2229, "s": 2219, "text": "SQL-Query" }, { "code": null, "e": 2240, "s": 2229, "text": "SQL-Server" }, { "code": null, "e": 2244, "s": 2240, "text": "SQL" }, { "code": null, "e": 2248, "s": 2244, "text": "SQL" }, { "code": null, "e": 2346, "s": 2248, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2357, "s": 2346, "text": "CTE in SQL" }, { "code": null, "e": 2388, "s": 2357, "text": "SQL Trigger | Student Database" }, { "code": null, "e": 2454, "s": 2388, "text": "How to Update Multiple Columns in Single Update Statement in SQL?" }, { "code": null, "e": 2478, "s": 2454, "text": "SQL Interview Questions" }, { "code": null, "e": 2490, "s": 2478, "text": "SQL | Views" }, { "code": null, "e": 2535, "s": 2490, "text": "Difference between DELETE, DROP and TRUNCATE" }, { "code": null, "e": 2559, "s": 2535, "text": "Window functions in SQL" }, { "code": null, "e": 2574, "s": 2559, "text": "SQL | GROUP BY" }, { "code": null, "e": 2606, "s": 2574, "text": "MySQL | Group_CONCAT() Function" } ]
Shortest cycle in an undirected unweighted graph
18 Mar, 2022 Given an undirected unweighted graph. The task is to find the length of the shortest cycle in the given graph. If no cycle exists print -1. Examples: Input: Output: 4 Cycle 6 -> 1 -> 5 -> 0 -> 6 Input: Output: 3 Cycle 6 -> 1 -> 2 -> 6 Prerequisites: Dijkstra Approach: For every vertex, we check if it is possible to get the shortest cycle involving this vertex. For every vertex first, push current vertex into the queue and then it’s neighbours and if the vertex which is already visited comes again then the cycle is present. Apply the above process for every vertex and get the length of the shortest cycle. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ implementation of the approach#include <bits/stdc++.h>using namespace std;#define N 100200 vector<int> gr[N]; // Function to add edgevoid Add_edge(int x, int y){ gr[x].push_back(y); gr[y].push_back(x);} // Function to find the length of// the shortest cycle in the graphint shortest_cycle(int n){ // To store length of the shortest cycle int ans = INT_MAX; // For all vertices for (int i = 0; i < n; i++) { // Make distance maximum vector<int> dist(n, (int)(1e9)); // Take a imaginary parent vector<int> par(n, -1); // Distance of source to source is 0 dist[i] = 0; queue<int> q; // Push the source element q.push(i); // Continue until queue is not empty while (!q.empty()) { // Take the first element int x = q.front(); q.pop(); // Traverse for all it's childs for (int child : gr[x]) { // If it is not visited yet if (dist[child] == (int)(1e9)) { // Increase distance by 1 dist[child] = 1 + dist[x]; // Change parent par[child] = x; // Push into the queue q.push(child); } // If it is already visited else if (par[x] != child and par[child] != x) ans = min(ans, dist[x] + dist[child] + 1); } } } // If graph contains no cycle if (ans == INT_MAX) return -1; // If graph contains cycle else return ans;} // Driver codeint main(){ // Number of vertices int n = 7; // Add edges Add_edge(0, 6); Add_edge(0, 5); Add_edge(5, 1); Add_edge(1, 6); Add_edge(2, 6); Add_edge(2, 3); Add_edge(3, 4); Add_edge(4, 1); // Function call cout << shortest_cycle(n); return 0;} // Java implementation of the approachimport java.util.*; class GFG{ static final int N = 100200; @SuppressWarnings("unchecked") static Vector<Integer>[] gr = new Vector[N]; // Function to add edge static void Add_edge(int x, int y) { gr[x].add(y); gr[y].add(x); } // Function to find the length of // the shortest cycle in the graph static int shortest_cycle(int n) { // To store length of the shortest cycle int ans = Integer.MAX_VALUE; // For all vertices for (int i = 0; i < n; i++) { // Make distance maximum int[] dist = new int[n]; Arrays.fill(dist, (int) 1e9); // Take a imaginary parent int[] par = new int[n]; Arrays.fill(par, -1); // Distance of source to source is 0 dist[i] = 0; Queue<Integer> q = new LinkedList<>(); // Push the source element q.add(i); // Continue until queue is not empty while (!q.isEmpty()) { // Take the first element int x = q.poll(); // Traverse for all it's childs for (int child : gr[x]) { // If it is not visited yet if (dist[child] == (int) (1e9)) { // Increase distance by 1 dist[child] = 1 + dist[x]; // Change parent par[child] = x; // Push into the queue q.add(child); } else if (par[x] != child && par[child] != x) ans = Math.min(ans, dist[x] + dist[child] + 1); } } } // If graph contains no cycle if (ans == Integer.MAX_VALUE) return -1; // If graph contains cycle else return ans; } // Driver Code public static void main(String[] args) { for (int i = 0; i < N; i++) gr[i] = new Vector<>(); // Number of vertices int n = 7; // Add edges Add_edge(0, 6); Add_edge(0, 5); Add_edge(5, 1); Add_edge(1, 6); Add_edge(2, 6); Add_edge(2, 3); Add_edge(3, 4); Add_edge(4, 1); // Function call System.out.println(shortest_cycle(n)); }} // This code is contributed by// sanjeev2552 # Python3 implementation of the approachfrom sys import maxsize as INT_MAXfrom collections import deque N = 100200 gr = [0] * Nfor i in range(N): gr[i] = [] # Function to add edgedef add_edge(x: int, y: int) -> None: global gr gr[x].append(y) gr[y].append(x) # Function to find the length of# the shortest cycle in the graphdef shortest_cycle(n: int) -> int: # To store length of the shortest cycle ans = INT_MAX # For all vertices for i in range(n): # Make distance maximum dist = [int(1e9)] * n # Take a imaginary parent par = [-1] * n # Distance of source to source is 0 dist[i] = 0 q = deque() # Push the source element q.append(i) # Continue until queue is not empty while q: # Take the first element x = q[0] q.popleft() # Traverse for all it's childs for child in gr[x]: # If it is not visited yet if dist[child] == int(1e9): # Increase distance by 1 dist[child] = 1 + dist[x] # Change parent par[child] = x # Push into the queue q.append(child) # If it is already visited elif par[x] != child and par[child] != x: ans = min(ans, dist[x] + dist[child] + 1) # If graph contains no cycle if ans == INT_MAX: return -1 # If graph contains cycle else: return ans # Driver Codeif __name__ == "__main__": # Number of vertices n = 7 # Add edges add_edge(0, 6) add_edge(0, 5) add_edge(5, 1) add_edge(1, 6) add_edge(2, 6) add_edge(2, 3) add_edge(3, 4) add_edge(4, 1) # Function call print(shortest_cycle(n)) # This code is contributed by# sanjeev2552 // C# implementation of the approachusing System;using System.Collections.Generic; class GFG{ static readonly int N = 100200; static List<int>[] gr = new List<int>[N]; // Function to add edge static void Add_edge(int x, int y) { gr[x].Add(y); gr[y].Add(x); } // Function to find the length of // the shortest cycle in the graph static int shortest_cycle(int n) { // To store length of the shortest cycle int ans = int.MaxValue; // For all vertices for (int i = 0; i < n; i++) { // Make distance maximum int[] dist = new int[n]; fill(dist, (int) 1e9); // Take a imaginary parent int[] par = new int[n]; fill(par, -1); // Distance of source to source is 0 dist[i] = 0; List<int> q = new List<int>(); // Push the source element q.Add(i); // Continue until queue is not empty while (q.Count!=0) { // Take the first element int x = q[0]; q.RemoveAt(0); // Traverse for all it's childs foreach (int child in gr[x]) { // If it is not visited yet if (dist[child] == (int) (1e9)) { // Increase distance by 1 dist[child] = 1 + dist[x]; // Change parent par[child] = x; // Push into the queue q.Add(child); } else if (par[x] != child && par[child] != x) ans = Math.Min(ans, dist[x] + dist[child] + 1); } } } // If graph contains no cycle if (ans == int.MaxValue) return -1; // If graph contains cycle else return ans; } static int[] fill(int []arr, int val) { for(int i = 0;i<arr.GetLength(0);i++) arr[i] = val; return arr; } // Driver Code public static void Main(String[] args) { for (int i = 0; i < N; i++) gr[i] = new List<int>(); // Number of vertices int n = 7; // Add edges Add_edge(0, 6); Add_edge(0, 5); Add_edge(5, 1); Add_edge(1, 6); Add_edge(2, 6); Add_edge(2, 3); Add_edge(3, 4); Add_edge(4, 1); // Function call Console.WriteLine(shortest_cycle(n)); }} // This code is contributed by 29AjayKumar <script> // JavaScript implementation of the approachvar N = 100200;var gr = Array.from(Array(N),()=>Array());// Function to add edgefunction Add_edge(x, y){ gr[x].push(y); gr[y].push(x);}// Function to find the length of// the shortest cycle in the graphfunction shortest_cycle(n){ // To store length of the shortest cycle var ans = 1000000000; // For all vertices for(var i = 0; i < n; i++) { // Make distance maximum var dist = Array(n).fill(1000000000); // Take a imaginary parent var par = Array(n).fill(-1); // Distance of source to source is 0 dist[i] = 0; var q = []; // Push the source element q.push(i); // Continue until queue is not empty while (q.length!=0) { // Take the first element var x = q[0]; q.shift(); // Traverse for all it's childs for(var child of gr[x]) { // If it is not visited yet if (dist[child] == 1000000000) { // Increase distance by 1 dist[child] = 1 + dist[x]; // Change parent par[child] = x; // Push into the queue q.push(child); } else if (par[x] != child && par[child] != x) ans = Math.min(ans, dist[x] + dist[child] + 1); } } } // If graph contains no cycle if (ans == 1000000000) return -1; // If graph contains cycle else return ans;}function fill(arr, val){ for(var i = 0;i<arr.length;i++) arr[i] = val; return arr;} // Driver Code// Number of verticesvar n = 7;// push edgesAdd_edge(0, 6);Add_edge(0, 5);Add_edge(5, 1);Add_edge(1, 6);Add_edge(2, 6);Add_edge(2, 3);Add_edge(3, 4);Add_edge(4, 1);// Function calldocument.write(shortest_cycle(n)); </script> 4 Time Complexity: O( |V| * (|V|+|E|)) for a graph G=(V, E) Memory Complexity: O(V^2) for a graph G=(V, E) sanjeev2552 29AjayKumar ssaksham noob2000 abusaleh Dijkstra graph-cycle Advanced Data Structure Graph Graph Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n18 Mar, 2022" }, { "code": null, "e": 192, "s": 52, "text": "Given an undirected unweighted graph. The task is to find the length of the shortest cycle in the given graph. If no cycle exists print -1." }, { "code": null, "e": 204, "s": 192, "text": "Examples: " }, { "code": null, "e": 212, "s": 204, "text": "Input: " }, { "code": null, "e": 250, "s": 212, "text": "Output: 4 Cycle 6 -> 1 -> 5 -> 0 -> 6" }, { "code": null, "e": 258, "s": 250, "text": "Input: " }, { "code": null, "e": 292, "s": 258, "text": "Output: 3 Cycle 6 -> 1 -> 2 -> 6 " }, { "code": null, "e": 317, "s": 292, "text": "Prerequisites: Dijkstra " }, { "code": null, "e": 670, "s": 317, "text": "Approach: For every vertex, we check if it is possible to get the shortest cycle involving this vertex. For every vertex first, push current vertex into the queue and then it’s neighbours and if the vertex which is already visited comes again then the cycle is present. Apply the above process for every vertex and get the length of the shortest cycle." }, { "code": null, "e": 722, "s": 670, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 726, "s": 722, "text": "C++" }, { "code": null, "e": 731, "s": 726, "text": "Java" }, { "code": null, "e": 739, "s": 731, "text": "Python3" }, { "code": null, "e": 742, "s": 739, "text": "C#" }, { "code": null, "e": 753, "s": 742, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std;#define N 100200 vector<int> gr[N]; // Function to add edgevoid Add_edge(int x, int y){ gr[x].push_back(y); gr[y].push_back(x);} // Function to find the length of// the shortest cycle in the graphint shortest_cycle(int n){ // To store length of the shortest cycle int ans = INT_MAX; // For all vertices for (int i = 0; i < n; i++) { // Make distance maximum vector<int> dist(n, (int)(1e9)); // Take a imaginary parent vector<int> par(n, -1); // Distance of source to source is 0 dist[i] = 0; queue<int> q; // Push the source element q.push(i); // Continue until queue is not empty while (!q.empty()) { // Take the first element int x = q.front(); q.pop(); // Traverse for all it's childs for (int child : gr[x]) { // If it is not visited yet if (dist[child] == (int)(1e9)) { // Increase distance by 1 dist[child] = 1 + dist[x]; // Change parent par[child] = x; // Push into the queue q.push(child); } // If it is already visited else if (par[x] != child and par[child] != x) ans = min(ans, dist[x] + dist[child] + 1); } } } // If graph contains no cycle if (ans == INT_MAX) return -1; // If graph contains cycle else return ans;} // Driver codeint main(){ // Number of vertices int n = 7; // Add edges Add_edge(0, 6); Add_edge(0, 5); Add_edge(5, 1); Add_edge(1, 6); Add_edge(2, 6); Add_edge(2, 3); Add_edge(3, 4); Add_edge(4, 1); // Function call cout << shortest_cycle(n); return 0;}", "e": 2684, "s": 753, "text": null }, { "code": "// Java implementation of the approachimport java.util.*; class GFG{ static final int N = 100200; @SuppressWarnings(\"unchecked\") static Vector<Integer>[] gr = new Vector[N]; // Function to add edge static void Add_edge(int x, int y) { gr[x].add(y); gr[y].add(x); } // Function to find the length of // the shortest cycle in the graph static int shortest_cycle(int n) { // To store length of the shortest cycle int ans = Integer.MAX_VALUE; // For all vertices for (int i = 0; i < n; i++) { // Make distance maximum int[] dist = new int[n]; Arrays.fill(dist, (int) 1e9); // Take a imaginary parent int[] par = new int[n]; Arrays.fill(par, -1); // Distance of source to source is 0 dist[i] = 0; Queue<Integer> q = new LinkedList<>(); // Push the source element q.add(i); // Continue until queue is not empty while (!q.isEmpty()) { // Take the first element int x = q.poll(); // Traverse for all it's childs for (int child : gr[x]) { // If it is not visited yet if (dist[child] == (int) (1e9)) { // Increase distance by 1 dist[child] = 1 + dist[x]; // Change parent par[child] = x; // Push into the queue q.add(child); } else if (par[x] != child && par[child] != x) ans = Math.min(ans, dist[x] + dist[child] + 1); } } } // If graph contains no cycle if (ans == Integer.MAX_VALUE) return -1; // If graph contains cycle else return ans; } // Driver Code public static void main(String[] args) { for (int i = 0; i < N; i++) gr[i] = new Vector<>(); // Number of vertices int n = 7; // Add edges Add_edge(0, 6); Add_edge(0, 5); Add_edge(5, 1); Add_edge(1, 6); Add_edge(2, 6); Add_edge(2, 3); Add_edge(3, 4); Add_edge(4, 1); // Function call System.out.println(shortest_cycle(n)); }} // This code is contributed by// sanjeev2552", "e": 5180, "s": 2684, "text": null }, { "code": "# Python3 implementation of the approachfrom sys import maxsize as INT_MAXfrom collections import deque N = 100200 gr = [0] * Nfor i in range(N): gr[i] = [] # Function to add edgedef add_edge(x: int, y: int) -> None: global gr gr[x].append(y) gr[y].append(x) # Function to find the length of# the shortest cycle in the graphdef shortest_cycle(n: int) -> int: # To store length of the shortest cycle ans = INT_MAX # For all vertices for i in range(n): # Make distance maximum dist = [int(1e9)] * n # Take a imaginary parent par = [-1] * n # Distance of source to source is 0 dist[i] = 0 q = deque() # Push the source element q.append(i) # Continue until queue is not empty while q: # Take the first element x = q[0] q.popleft() # Traverse for all it's childs for child in gr[x]: # If it is not visited yet if dist[child] == int(1e9): # Increase distance by 1 dist[child] = 1 + dist[x] # Change parent par[child] = x # Push into the queue q.append(child) # If it is already visited elif par[x] != child and par[child] != x: ans = min(ans, dist[x] + dist[child] + 1) # If graph contains no cycle if ans == INT_MAX: return -1 # If graph contains cycle else: return ans # Driver Codeif __name__ == \"__main__\": # Number of vertices n = 7 # Add edges add_edge(0, 6) add_edge(0, 5) add_edge(5, 1) add_edge(1, 6) add_edge(2, 6) add_edge(2, 3) add_edge(3, 4) add_edge(4, 1) # Function call print(shortest_cycle(n)) # This code is contributed by# sanjeev2552", "e": 7095, "s": 5180, "text": null }, { "code": "// C# implementation of the approachusing System;using System.Collections.Generic; class GFG{ static readonly int N = 100200; static List<int>[] gr = new List<int>[N]; // Function to add edge static void Add_edge(int x, int y) { gr[x].Add(y); gr[y].Add(x); } // Function to find the length of // the shortest cycle in the graph static int shortest_cycle(int n) { // To store length of the shortest cycle int ans = int.MaxValue; // For all vertices for (int i = 0; i < n; i++) { // Make distance maximum int[] dist = new int[n]; fill(dist, (int) 1e9); // Take a imaginary parent int[] par = new int[n]; fill(par, -1); // Distance of source to source is 0 dist[i] = 0; List<int> q = new List<int>(); // Push the source element q.Add(i); // Continue until queue is not empty while (q.Count!=0) { // Take the first element int x = q[0]; q.RemoveAt(0); // Traverse for all it's childs foreach (int child in gr[x]) { // If it is not visited yet if (dist[child] == (int) (1e9)) { // Increase distance by 1 dist[child] = 1 + dist[x]; // Change parent par[child] = x; // Push into the queue q.Add(child); } else if (par[x] != child && par[child] != x) ans = Math.Min(ans, dist[x] + dist[child] + 1); } } } // If graph contains no cycle if (ans == int.MaxValue) return -1; // If graph contains cycle else return ans; } static int[] fill(int []arr, int val) { for(int i = 0;i<arr.GetLength(0);i++) arr[i] = val; return arr; } // Driver Code public static void Main(String[] args) { for (int i = 0; i < N; i++) gr[i] = new List<int>(); // Number of vertices int n = 7; // Add edges Add_edge(0, 6); Add_edge(0, 5); Add_edge(5, 1); Add_edge(1, 6); Add_edge(2, 6); Add_edge(2, 3); Add_edge(3, 4); Add_edge(4, 1); // Function call Console.WriteLine(shortest_cycle(n)); }} // This code is contributed by 29AjayKumar", "e": 9739, "s": 7095, "text": null }, { "code": "<script> // JavaScript implementation of the approachvar N = 100200;var gr = Array.from(Array(N),()=>Array());// Function to add edgefunction Add_edge(x, y){ gr[x].push(y); gr[y].push(x);}// Function to find the length of// the shortest cycle in the graphfunction shortest_cycle(n){ // To store length of the shortest cycle var ans = 1000000000; // For all vertices for(var i = 0; i < n; i++) { // Make distance maximum var dist = Array(n).fill(1000000000); // Take a imaginary parent var par = Array(n).fill(-1); // Distance of source to source is 0 dist[i] = 0; var q = []; // Push the source element q.push(i); // Continue until queue is not empty while (q.length!=0) { // Take the first element var x = q[0]; q.shift(); // Traverse for all it's childs for(var child of gr[x]) { // If it is not visited yet if (dist[child] == 1000000000) { // Increase distance by 1 dist[child] = 1 + dist[x]; // Change parent par[child] = x; // Push into the queue q.push(child); } else if (par[x] != child && par[child] != x) ans = Math.min(ans, dist[x] + dist[child] + 1); } } } // If graph contains no cycle if (ans == 1000000000) return -1; // If graph contains cycle else return ans;}function fill(arr, val){ for(var i = 0;i<arr.length;i++) arr[i] = val; return arr;} // Driver Code// Number of verticesvar n = 7;// push edgesAdd_edge(0, 6);Add_edge(0, 5);Add_edge(5, 1);Add_edge(1, 6);Add_edge(2, 6);Add_edge(2, 3);Add_edge(3, 4);Add_edge(4, 1);// Function calldocument.write(shortest_cycle(n)); </script>", "e": 11686, "s": 9739, "text": null }, { "code": null, "e": 11688, "s": 11686, "text": "4" }, { "code": null, "e": 11749, "s": 11690, "text": "Time Complexity: O( |V| * (|V|+|E|)) for a graph G=(V, E) " }, { "code": null, "e": 11797, "s": 11749, "text": "Memory Complexity: O(V^2) for a graph G=(V, E) " }, { "code": null, "e": 11809, "s": 11797, "text": "sanjeev2552" }, { "code": null, "e": 11821, "s": 11809, "text": "29AjayKumar" }, { "code": null, "e": 11830, "s": 11821, "text": "ssaksham" }, { "code": null, "e": 11839, "s": 11830, "text": "noob2000" }, { "code": null, "e": 11848, "s": 11839, "text": "abusaleh" }, { "code": null, "e": 11857, "s": 11848, "text": "Dijkstra" }, { "code": null, "e": 11869, "s": 11857, "text": "graph-cycle" }, { "code": null, "e": 11893, "s": 11869, "text": "Advanced Data Structure" }, { "code": null, "e": 11899, "s": 11893, "text": "Graph" }, { "code": null, "e": 11905, "s": 11899, "text": "Graph" } ]
Length of smallest substring of a given string which contains another string as subsequence | Set 2
04 Feb, 2022 Given two strings A and B, the task is to find the smallest substring of A having B as a subsequence. Examples: Input: A = “abcdefababaef”, B = “abf”Output: 5Explanation:Smallest substring of A having B as subsequence is abcdef.Therefore, the required length is 5. Input: A = “abcdefababaef”, B = “aef”Output: 3 Approach: Follow the steps below to solve the problem: Store all the indices of the characters of A which are also present in B in a Map CharacterIndex. Traverse over all the characters of string B. Check if the first character of string B is present in the string A or not:If found to be true, then initialize two variables firstVar and lastVar with the index of the first occurrence of B[0] in the string A.After updating the values, remove that character from the Map CharacterIndex.Otherwise, no further substring is possible. If found to be true, then initialize two variables firstVar and lastVar with the index of the first occurrence of B[0] in the string A.After updating the values, remove that character from the Map CharacterIndex.Otherwise, no further substring is possible. If found to be true, then initialize two variables firstVar and lastVar with the index of the first occurrence of B[0] in the string A. After updating the values, remove that character from the Map CharacterIndex. Otherwise, no further substring is possible. For the remaining characters of B, check if the character is present in the string A or not. If found to be true, traverse through all the occurrences of that character in the string A and if the index of that character in the string A exceeds lastVar, then update the lastVar with that index. Otherwise, no further substring is possible. If B is completely traversed, update answer with the difference between firstVar and the lastVar. Print the final minimized answer. Below is the implementation of the above approach: C++ Java Python3 // C++ program to implement// the above approach#include <bits/stdc++.h>using namespace std; // Function to find the length of// smallest substring of a having// string b as a subsequenceint minLength(string a, string b){ // Stores the characters present // in string b map<char, int> Char; for (int i = 0; i < b.length(); i++) { Char[b[i]]++; } // Find index of characters of a // that are also present in string b map<char, vector<int> > CharacterIndex; for (int i = 0; i < a.length(); i++) { char x = a[i]; // If character is present in string b if (Char.find(x) != Char.end()) { // Store the index of character CharacterIndex[x].push_back(i); } } int len = INT_MAX; // Flag is used to check if // substring is possible int flag; while (true) { // Assume that substring is // possible flag = 1; // Stores first and last // indices of the substring // respectively int firstVar, lastVar; for (int i = 0; i < b.length(); i++) { // For first character of string b if (i == 0) { // If the first character of // b is not present in a if (CharacterIndex.find(b[i]) == CharacterIndex.end()) { flag = 0; break; } // If the first character of b // is present in a else { int x = *( CharacterIndex[b[i]].begin()); // Remove the index from map CharacterIndex[b[i]].erase( CharacterIndex[b[i]].begin()); // Update indices of // the substring firstVar = x; lastVar = x; } } // For the remaining characters of b else { int elementFound = 0; for (auto e : CharacterIndex[b[i]]) { if (e > lastVar) { // If index possible for // current character elementFound = 1; lastVar = e; break; } } if (elementFound == 0) { // If no index is possible flag = 0; break; } } } if (flag == 0) { // If no more substring // is possible break; } // Update the minimum length // of substring len = min(len, abs(lastVar - firstVar) + 1); } // Return the result return len;} // Driver Codeint main(){ // Given two string string a = "abcdefababaef"; string b = "abf"; int len = minLength(a, b); if (len != INT_MAX) { cout << len << endl; } else { cout << "Impossible" << endl; }} // Java program to implement// the above approachimport java.util.ArrayList;import java.util.HashMap; class GFG{ // Function to find the length of// smallest substring of a having// string b as a subsequencestatic int minLength(String a, String b){ // Stores the characters present // in string b HashMap<Character, Integer> Char = new HashMap<>(); for(int i = 0; i < b.length(); i++) { Char.put(b.charAt(i), Char.getOrDefault(b.charAt(i), 0) + 1); } // Find index of characters of a // that are also present in string b HashMap<Character, ArrayList<Integer>> CharacterIndex = new HashMap<>(); for(int i = 0; i < a.length(); i++) { char x = a.charAt(i); // If character is present in string b if (Char.containsKey(x)) { if (CharacterIndex.get(x) == null) { CharacterIndex.put( x, new ArrayList<Integer>()); } // Store the index of character CharacterIndex.get(x).add(i); } } int len = Integer.MAX_VALUE; // Flag is used to check if // substring is possible int flag; while (true) { // Assume that substring is // possible flag = 1; // Stores first and last // indices of the substring // respectively int firstVar = 0, lastVar = 0; for(int i = 0; i < b.length(); i++) { // For first character of string b if (i == 0) { // If the first character of // b is not present in a if (CharacterIndex.containsKey(i)) { flag = 0; break; } // If the first character of b // is present in a else { int x = CharacterIndex.get(b.charAt(i)).get(0); // Remove the index from map CharacterIndex.get(b.charAt(i)).remove( CharacterIndex.get(b.charAt(i)).get(0)); // Update indices of // the substring firstVar = x; lastVar = x; } } // For the remaining characters of b else { int elementFound = 0; for(var e : CharacterIndex.get(b.charAt(i))) { if (e > lastVar) { // If index possible for // current character elementFound = 1; lastVar = e; break; } } if (elementFound == 0) { // If no index is possible flag = 0; break; } } } if (flag == 0) { // If no more substring // is possible break; } // Update the minimum length // of substring len = Math.min( len, Math.abs(lastVar - firstVar) + 1); } // Return the result return len;} // Driver codepublic static void main(String[] args){ // Given two string String a = "abcdefababaef"; String b = "abf"; int len = minLength(a, b); if (len != Integer.MAX_VALUE) { System.out.println(len); } else { System.out.println("Impossible"); }}} // This code is contributed by sk944795 # Python3 program to implement# the above approachimport sys # Function to find the length of# smallest substring of a having# string b as a subsequencedef minLength(a, b): # Stores the characters present # in string b Char = {} for i in range(len(b)): Char[b[i]] = Char.get(b[i], 0) + 1 # Find index of characters of a # that are also present in string b CharacterIndex = {} for i in range(len(a)): x = a[i] # If character is present in string b if (x in Char): # Store the index of character CharacterIndex[x] = CharacterIndex.get(x, []) CharacterIndex[x].append(i) l = sys.maxsize # Flag is used to check if # substring is possible while(True): # Assume that substring is # possible flag = 1 firstVar = 0 lastVar = 0 # Stores first and last # indices of the substring # respectively for i in range(len(b)): # For first character of string b if (i == 0): # If the first character of # b is not present in a if (b[i] not in CharacterIndex): flag = 0 break # If the first character of b # is present in a else: x = CharacterIndex[b[i]][0] # Remove the index from map CharacterIndex[b[i]].remove( CharacterIndex[b[i]][0]) # Update indices of # the substring firstVar = x lastVar = x # For the remaining characters of b else: elementFound = 0 for e in CharacterIndex[b[i]]: if (e > lastVar): # If index possible for # current character elementFound = 1 lastVar = e break if (elementFound == 0): # If no index is possible flag = 0 break if (flag == 0): # If no more substring # is possible break # Update the minimum length # of substring l = min(l, abs(lastVar - firstVar) + 1) # Return the result return l # Driver Codeif __name__ == '__main__': # Given two string a = "abcdefababaef" b = "abf" l = minLength(a, b) if (l != sys.maxsize): print(l) else: print("Impossible") # This code is contributed by SURENDRA_GANGWAR 5 Time Complexity: O(N2)Auxiliary Space: O(N) SURENDRA_GANGWAR sk944795 cpp-map frequency-counting sliding-window subsequence substring Hash Searching Strings sliding-window Searching Hash Strings Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. What is Hashing | A Complete Tutorial Longest Consecutive Subsequence Counting frequencies of array elements Hashing | Set 2 (Separate Chaining) Sorting a Map by value in C++ STL Binary Search Maximum and minimum of an array using minimum number of comparisons Linear Search K'th Smallest/Largest Element in Unsorted Array | Set 1 Search an element in a sorted and rotated array
[ { "code": null, "e": 54, "s": 26, "text": "\n04 Feb, 2022" }, { "code": null, "e": 156, "s": 54, "text": "Given two strings A and B, the task is to find the smallest substring of A having B as a subsequence." }, { "code": null, "e": 166, "s": 156, "text": "Examples:" }, { "code": null, "e": 319, "s": 166, "text": "Input: A = “abcdefababaef”, B = “abf”Output: 5Explanation:Smallest substring of A having B as subsequence is abcdef.Therefore, the required length is 5." }, { "code": null, "e": 366, "s": 319, "text": "Input: A = “abcdefababaef”, B = “aef”Output: 3" }, { "code": null, "e": 421, "s": 366, "text": "Approach: Follow the steps below to solve the problem:" }, { "code": null, "e": 519, "s": 421, "text": "Store all the indices of the characters of A which are also present in B in a Map CharacterIndex." }, { "code": null, "e": 565, "s": 519, "text": "Traverse over all the characters of string B." }, { "code": null, "e": 897, "s": 565, "text": "Check if the first character of string B is present in the string A or not:If found to be true, then initialize two variables firstVar and lastVar with the index of the first occurrence of B[0] in the string A.After updating the values, remove that character from the Map CharacterIndex.Otherwise, no further substring is possible." }, { "code": null, "e": 1154, "s": 897, "text": "If found to be true, then initialize two variables firstVar and lastVar with the index of the first occurrence of B[0] in the string A.After updating the values, remove that character from the Map CharacterIndex.Otherwise, no further substring is possible." }, { "code": null, "e": 1290, "s": 1154, "text": "If found to be true, then initialize two variables firstVar and lastVar with the index of the first occurrence of B[0] in the string A." }, { "code": null, "e": 1368, "s": 1290, "text": "After updating the values, remove that character from the Map CharacterIndex." }, { "code": null, "e": 1413, "s": 1368, "text": "Otherwise, no further substring is possible." }, { "code": null, "e": 1752, "s": 1413, "text": "For the remaining characters of B, check if the character is present in the string A or not. If found to be true, traverse through all the occurrences of that character in the string A and if the index of that character in the string A exceeds lastVar, then update the lastVar with that index. Otherwise, no further substring is possible." }, { "code": null, "e": 1850, "s": 1752, "text": "If B is completely traversed, update answer with the difference between firstVar and the lastVar." }, { "code": null, "e": 1884, "s": 1850, "text": "Print the final minimized answer." }, { "code": null, "e": 1935, "s": 1884, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 1939, "s": 1935, "text": "C++" }, { "code": null, "e": 1944, "s": 1939, "text": "Java" }, { "code": null, "e": 1952, "s": 1944, "text": "Python3" }, { "code": "// C++ program to implement// the above approach#include <bits/stdc++.h>using namespace std; // Function to find the length of// smallest substring of a having// string b as a subsequenceint minLength(string a, string b){ // Stores the characters present // in string b map<char, int> Char; for (int i = 0; i < b.length(); i++) { Char[b[i]]++; } // Find index of characters of a // that are also present in string b map<char, vector<int> > CharacterIndex; for (int i = 0; i < a.length(); i++) { char x = a[i]; // If character is present in string b if (Char.find(x) != Char.end()) { // Store the index of character CharacterIndex[x].push_back(i); } } int len = INT_MAX; // Flag is used to check if // substring is possible int flag; while (true) { // Assume that substring is // possible flag = 1; // Stores first and last // indices of the substring // respectively int firstVar, lastVar; for (int i = 0; i < b.length(); i++) { // For first character of string b if (i == 0) { // If the first character of // b is not present in a if (CharacterIndex.find(b[i]) == CharacterIndex.end()) { flag = 0; break; } // If the first character of b // is present in a else { int x = *( CharacterIndex[b[i]].begin()); // Remove the index from map CharacterIndex[b[i]].erase( CharacterIndex[b[i]].begin()); // Update indices of // the substring firstVar = x; lastVar = x; } } // For the remaining characters of b else { int elementFound = 0; for (auto e : CharacterIndex[b[i]]) { if (e > lastVar) { // If index possible for // current character elementFound = 1; lastVar = e; break; } } if (elementFound == 0) { // If no index is possible flag = 0; break; } } } if (flag == 0) { // If no more substring // is possible break; } // Update the minimum length // of substring len = min(len, abs(lastVar - firstVar) + 1); } // Return the result return len;} // Driver Codeint main(){ // Given two string string a = \"abcdefababaef\"; string b = \"abf\"; int len = minLength(a, b); if (len != INT_MAX) { cout << len << endl; } else { cout << \"Impossible\" << endl; }}", "e": 5069, "s": 1952, "text": null }, { "code": "// Java program to implement// the above approachimport java.util.ArrayList;import java.util.HashMap; class GFG{ // Function to find the length of// smallest substring of a having// string b as a subsequencestatic int minLength(String a, String b){ // Stores the characters present // in string b HashMap<Character, Integer> Char = new HashMap<>(); for(int i = 0; i < b.length(); i++) { Char.put(b.charAt(i), Char.getOrDefault(b.charAt(i), 0) + 1); } // Find index of characters of a // that are also present in string b HashMap<Character, ArrayList<Integer>> CharacterIndex = new HashMap<>(); for(int i = 0; i < a.length(); i++) { char x = a.charAt(i); // If character is present in string b if (Char.containsKey(x)) { if (CharacterIndex.get(x) == null) { CharacterIndex.put( x, new ArrayList<Integer>()); } // Store the index of character CharacterIndex.get(x).add(i); } } int len = Integer.MAX_VALUE; // Flag is used to check if // substring is possible int flag; while (true) { // Assume that substring is // possible flag = 1; // Stores first and last // indices of the substring // respectively int firstVar = 0, lastVar = 0; for(int i = 0; i < b.length(); i++) { // For first character of string b if (i == 0) { // If the first character of // b is not present in a if (CharacterIndex.containsKey(i)) { flag = 0; break; } // If the first character of b // is present in a else { int x = CharacterIndex.get(b.charAt(i)).get(0); // Remove the index from map CharacterIndex.get(b.charAt(i)).remove( CharacterIndex.get(b.charAt(i)).get(0)); // Update indices of // the substring firstVar = x; lastVar = x; } } // For the remaining characters of b else { int elementFound = 0; for(var e : CharacterIndex.get(b.charAt(i))) { if (e > lastVar) { // If index possible for // current character elementFound = 1; lastVar = e; break; } } if (elementFound == 0) { // If no index is possible flag = 0; break; } } } if (flag == 0) { // If no more substring // is possible break; } // Update the minimum length // of substring len = Math.min( len, Math.abs(lastVar - firstVar) + 1); } // Return the result return len;} // Driver codepublic static void main(String[] args){ // Given two string String a = \"abcdefababaef\"; String b = \"abf\"; int len = minLength(a, b); if (len != Integer.MAX_VALUE) { System.out.println(len); } else { System.out.println(\"Impossible\"); }}} // This code is contributed by sk944795", "e": 8813, "s": 5069, "text": null }, { "code": "# Python3 program to implement# the above approachimport sys # Function to find the length of# smallest substring of a having# string b as a subsequencedef minLength(a, b): # Stores the characters present # in string b Char = {} for i in range(len(b)): Char[b[i]] = Char.get(b[i], 0) + 1 # Find index of characters of a # that are also present in string b CharacterIndex = {} for i in range(len(a)): x = a[i] # If character is present in string b if (x in Char): # Store the index of character CharacterIndex[x] = CharacterIndex.get(x, []) CharacterIndex[x].append(i) l = sys.maxsize # Flag is used to check if # substring is possible while(True): # Assume that substring is # possible flag = 1 firstVar = 0 lastVar = 0 # Stores first and last # indices of the substring # respectively for i in range(len(b)): # For first character of string b if (i == 0): # If the first character of # b is not present in a if (b[i] not in CharacterIndex): flag = 0 break # If the first character of b # is present in a else: x = CharacterIndex[b[i]][0] # Remove the index from map CharacterIndex[b[i]].remove( CharacterIndex[b[i]][0]) # Update indices of # the substring firstVar = x lastVar = x # For the remaining characters of b else: elementFound = 0 for e in CharacterIndex[b[i]]: if (e > lastVar): # If index possible for # current character elementFound = 1 lastVar = e break if (elementFound == 0): # If no index is possible flag = 0 break if (flag == 0): # If no more substring # is possible break # Update the minimum length # of substring l = min(l, abs(lastVar - firstVar) + 1) # Return the result return l # Driver Codeif __name__ == '__main__': # Given two string a = \"abcdefababaef\" b = \"abf\" l = minLength(a, b) if (l != sys.maxsize): print(l) else: print(\"Impossible\") # This code is contributed by SURENDRA_GANGWAR", "e": 11668, "s": 8813, "text": null }, { "code": null, "e": 11670, "s": 11668, "text": "5" }, { "code": null, "e": 11716, "s": 11672, "text": "Time Complexity: O(N2)Auxiliary Space: O(N)" }, { "code": null, "e": 11735, "s": 11718, "text": "SURENDRA_GANGWAR" }, { "code": null, "e": 11744, "s": 11735, "text": "sk944795" }, { "code": null, "e": 11752, "s": 11744, "text": "cpp-map" }, { "code": null, "e": 11771, "s": 11752, "text": "frequency-counting" }, { "code": null, "e": 11786, "s": 11771, "text": "sliding-window" }, { "code": null, "e": 11798, "s": 11786, "text": "subsequence" }, { "code": null, "e": 11808, "s": 11798, "text": "substring" }, { "code": null, "e": 11813, "s": 11808, "text": "Hash" }, { "code": null, "e": 11823, "s": 11813, "text": "Searching" }, { "code": null, "e": 11831, "s": 11823, "text": "Strings" }, { "code": null, "e": 11846, "s": 11831, "text": "sliding-window" }, { "code": null, "e": 11856, "s": 11846, "text": "Searching" }, { "code": null, "e": 11861, "s": 11856, "text": "Hash" }, { "code": null, "e": 11869, "s": 11861, "text": "Strings" }, { "code": null, "e": 11967, "s": 11869, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 12005, "s": 11967, "text": "What is Hashing | A Complete Tutorial" }, { "code": null, "e": 12037, "s": 12005, "text": "Longest Consecutive Subsequence" }, { "code": null, "e": 12076, "s": 12037, "text": "Counting frequencies of array elements" }, { "code": null, "e": 12112, "s": 12076, "text": "Hashing | Set 2 (Separate Chaining)" }, { "code": null, "e": 12146, "s": 12112, "text": "Sorting a Map by value in C++ STL" }, { "code": null, "e": 12160, "s": 12146, "text": "Binary Search" }, { "code": null, "e": 12228, "s": 12160, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 12242, "s": 12228, "text": "Linear Search" }, { "code": null, "e": 12298, "s": 12242, "text": "K'th Smallest/Largest Element in Unsorted Array | Set 1" } ]
Static Keyword in C++
When static keyword is used, variable or data members or functions can not be modified again. It is allocated for the lifetime of program. Static functions can be called directly by using class name. Static variables are initialized only once. Compiler persist the variable till the end of the program. Static variable can be defined inside or outside the function. They are local to the block. The default value of static variable is zero. The static variables are alive till the execution of the program. Here is the syntax of static keyword in C++ language, static datatype variable_name = value; // Static variable static return_type function_name { // Static functions ... } Here, datatype − The datatype of variable like int, char, float etc. variable_name − This is the name of variable given by user. value − Any value to initialize the variable. By default, it is zero. return_type − The datatype of function to return the value. function_name − Any name to the function. Here is an example of static variable in C++ language, Live Demo #include <bits/stdc++.h> using namespace std; class Base { public : static int val; static int func(int a) { cout << "\nStatic member function called"; cout << "\nThe value of a : " << a; } }; int Base::val=28; int main() { Base b; Base::func(8); cout << "\nThe static variable value : " << b.val; return 0; } Static member function called The value of a : 8 The static variable value : 28 In the above program, a static variable is declared and a static function is defined in the class Base as shown below − public : static int val; static int func(int a) { cout << "\nStatic member function called"; cout << "\nThe value of a : " << a; } After the class and before main(), the static variable is initialized as follows − int Base::val=28; In the function main(), object of Base class is created and static variable is called. The static function is also called without using object of Base class as follows − Base b; Base::func(8); cout << "\nThe static variable value : " << b.val;
[ { "code": null, "e": 1387, "s": 1187, "text": "When static keyword is used, variable or data members or functions can not be modified again. It is allocated for the lifetime of program. Static functions can be called directly by using class name." }, { "code": null, "e": 1694, "s": 1387, "text": "Static variables are initialized only once. Compiler persist the variable till the end of the program. Static variable can be defined inside or outside the function. They are local to the block. The default value of static variable is zero. The static variables are alive till the execution of the program." }, { "code": null, "e": 1748, "s": 1694, "text": "Here is the syntax of static keyword in C++ language," }, { "code": null, "e": 1888, "s": 1748, "text": "static datatype variable_name = value; // Static variable\nstatic return_type function_name { // Static functions\n ...\n}\n" }, { "code": null, "e": 1894, "s": 1888, "text": "Here," }, { "code": null, "e": 1957, "s": 1894, "text": "datatype − The datatype of variable like int, char, float etc." }, { "code": null, "e": 2017, "s": 1957, "text": "variable_name − This is the name of variable given by user." }, { "code": null, "e": 2087, "s": 2017, "text": "value − Any value to initialize the variable. By default, it is zero." }, { "code": null, "e": 2147, "s": 2087, "text": "return_type − The datatype of function to return the value." }, { "code": null, "e": 2189, "s": 2147, "text": "function_name − Any name to the function." }, { "code": null, "e": 2244, "s": 2189, "text": "Here is an example of static variable in C++ language," }, { "code": null, "e": 2255, "s": 2244, "text": " Live Demo" }, { "code": null, "e": 2598, "s": 2255, "text": "#include <bits/stdc++.h>\nusing namespace std;\nclass Base {\n public : static int val;\n static int func(int a) {\n cout << \"\\nStatic member function called\";\n cout << \"\\nThe value of a : \" << a;\n }\n};\nint Base::val=28;\nint main() {\n Base b;\n Base::func(8);\n cout << \"\\nThe static variable value : \" << b.val;\n return 0;\n}" }, { "code": null, "e": 2679, "s": 2598, "text": "Static member function called\nThe value of a : 8\nThe static variable value : 28\n" }, { "code": null, "e": 2799, "s": 2679, "text": "In the above program, a static variable is declared and a static function is defined in the class Base as shown below −" }, { "code": null, "e": 2936, "s": 2799, "text": "public : static int val;\nstatic int func(int a) {\n cout << \"\\nStatic member function called\";\n cout << \"\\nThe value of a : \" << a;\n}" }, { "code": null, "e": 3019, "s": 2936, "text": "After the class and before main(), the static variable is initialized as follows −" }, { "code": null, "e": 3038, "s": 3019, "text": "int Base::val=28;\n" }, { "code": null, "e": 3208, "s": 3038, "text": "In the function main(), object of Base class is created and static variable is called. The static function is also called without using object of Base class as follows −" }, { "code": null, "e": 3283, "s": 3208, "text": "Base b;\nBase::func(8);\ncout << \"\\nThe static variable value : \" << b.val;\n" } ]
Find a pair with maximum product in array of Integers
28 Jun, 2022 Given an array with both +ive and -ive integers, return a pair with highest product. Examples : Input: arr[] = {1, 4, 3, 6, 7, 0} Output: {6,7} Input: arr[] = {-1, -3, -4, 2, 0, -5} Output: {-4,-5} A Simple Solution is to consider every pair and keep track of the maximum product. Below is the implementation of this simple solution. C++ Java Python3 C# PHP Javascript // A simple C++ program to find max product pair in// an array of integers#include<bits/stdc++.h>using namespace std; // Function to find maximum product pair in arr[0..n-1]void maxProduct(int arr[], int n){ if (n < 2) { cout << "No pairs exists\n"; return; } // Initialize max product pair int a = arr[0], b = arr[1]; // Traverse through every possible pair // and keep track of max product for (int i=0; i<n; i++) for (int j=i+1; j<n; j++) if (arr[i]*arr[j] > a*b) a = arr[i], b = arr[j]; cout << "Max product pair is {" << a << ", " << b << "}";} // Driver program to testint main(){ int arr[] = {1, 4, 3, 6, 7, 0}; int n = sizeof(arr)/sizeof(arr[0]); maxProduct(arr, n); return 0;} // JAVA Code to Find a pair with maximum// product in array of Integersimport java.util.*; class GFG { // Function to find maximum product pair // in arr[0..n-1] static void maxProduct(int arr[], int n) { if (n < 2) { System.out.println("No pairs exists"); return; } // Initialize max product pair int a = arr[0], b = arr[1]; // Traverse through every possible pair // and keep track of max product for (int i = 0; i < n; i++) for (int j = i + 1; j < n; j++) if (arr[i] * arr[j] > a * b){ a = arr[i]; b = arr[j]; } System.out.println("Max product pair is {" + a + ", " + b + "}"); } /* Driver program to test above function */ public static void main(String[] args) { int arr[] = {1, 4, 3, 6, 7, 0}; int n = arr.length; maxProduct(arr, n); }} // This code is contributed by Arnav Kr. Mandal. # A simple Python3 program to find max# product pair in an array of integers # Function to find maximum# product pair in arr[0..n-1]def maxProduct(arr, n): if (n < 2): print("No pairs exists") return # Initialize max product pair a = arr[0]; b = arr[1] # Traverse through every possible pair # and keep track of max product for i in range(0, n): for j in range(i + 1, n): if (arr[i] * arr[j] > a * b): a = arr[i]; b = arr[j] print("Max product pair is {", a, ",", b, "}", sep = "") # Driver Codearr = [1, 4, 3, 6, 7, 0]n = len(arr)maxProduct(arr, n) # This code is contributed by Smitha Dinesh Semwal. // C# Code to Find a pair with maximum// product in array of Integersusing System; class GFG{ // Function to find maximum // product pair in arr[0..n-1] static void maxProduct(int []arr, int n) { if (n < 2) { Console.Write("No pairs exists"); return; } // Initialize max product pair int a = arr[0], b = arr[1]; // Traverse through every possible pair // and keep track of max product for (int i = 0; i < n; i++) for (int j = i + 1; j < n; j++) if (arr[i] * arr[j] > a * b) { a = arr[i]; b = arr[j]; } Console.Write("Max product pair is {" + a + ", " + b + "}"); } // Driver Code public static void Main() { int []arr = {1, 4, 3, 6, 7, 0}; int n = arr.Length; maxProduct(arr, n); }} // This code is contributed by nitin mittal. <?php// A simple PHP program to// find max product pair in// an array of integers // Function to find maximum// product pair in arr[0..n-1]function maxProduct( $arr, $n){ if ($n < 2) { echo "No pairs exists\n"; return; } // Initialize max product pair $a = $arr[0]; $b = $arr[1]; // Traverse through every possible pair // and keep track of max product for ($i = 0; $i < $n; $i++) for ($j = $i + 1; $j < $n; $j++) { if ($arr[$i] * $arr[$j] > $a * $b) { $a = $arr[$i]; $b = $arr[$j]; } } echo "Max product pair is {" , $a , ", "; echo $b , "}";} // Driver Code $arr = array(1, 4, 3, 6, 7, 0); $n = count($arr); maxProduct($arr, $n); // This code is contributed by anuj_67.?> <script> // A simple Javascript program to find max product pair in// an array of integers // Function to find maximum product pair in arr[0..n-1]function maxProduct(arr, n){ if (n < 2) { document.write("No pairs exists" + "<br>"); return; } // Initialize max product pair let a = arr[0], b = arr[1]; // Traverse through every possible pair // and keep track of max product for (let i=0; i<n; i++) for (let j=i+1; j<n; j++) if (arr[i]*arr[j] > a*b) a = arr[i], b = arr[j]; document.write("Max product pair is {" + a + ", " + b + "}");} // Driver program to test let arr = [1, 4, 3, 6, 7, 0]; let n = arr.length; maxProduct(arr, n); // This code is contributed by Mayank Tyagi </script> Max product pair is {6, 7} Time Complexity : O(n2) Better Approach: A Better Solution is to use sorting. Below are detailed steps. Sort input array in increasing order. If all elements are positive, then return the product of the last two numbers. Else return a maximum of products of the first two and last two numbers. Sort input array in increasing order. If all elements are positive, then return the product of the last two numbers. Else return a maximum of products of the first two and last two numbers. Thanks to Rahul Jain for suggesting this method. C++14 Java Python3 C# Javascript // C++ code to find a pair with maximum// product in array of Integers#include<bits/stdc++.h>using namespace std; void maxProduct(vector<int>arr, int n){ // Sort the array sort(arr.begin(), arr.end()); int num1, num2; // Calculate product of two smallest numbers int sum1 = arr[0] * arr[1]; // Calculate product of two largest numbers int sum2 = arr[n - 1] * arr[n - 2]; // Print the pairs whose product is greater if (sum1 > sum2) { num1 = arr[0]; num2 = arr[1]; } else { num1 = arr[n - 2]; num2 = arr[n - 1]; } cout << ("Max product pair = ") << num1 << "," << num2;} // Driver Codeint main(){ vector<int>arr = { 1, 4, 3, 6, 7, 0 }; int n = arr.size(); maxProduct(arr, n);} // This code is contributed by Stream_Cipher // JAVA Code to Find a pair with maximum// product in array of Integersimport java.util.*; public class GFG { static void maxProduct(int arr[], int n) { // Sort the array Arrays.sort(arr); int num1, num2; // Calculate product of two smallest numbers int sum1 = arr[0] * arr[1]; // Calculate product of two largest numbers int sum2 = arr[n - 1] * arr[n - 2]; // print the pairs whose product is greater if (sum1 > sum2) { num1 = arr[0]; num2 = arr[1]; } else { num1 = arr[n - 2]; num2 = arr[n - 1]; } System.out.println("Max product pair = " + "{" + num1 + "," + num2 + "}"); } // Driver Code public static void main(String[] args) { int arr[] = { 1, 4, 3, 6, 7, 0 }; int n = arr.length; maxProduct(arr, n); }}// Contributed by Navtika Kumar # Python code to find a pair with maximum# product in array of Integersdef maxProduct(arr, n): # Sort the array arr.sort() num1 = num2 = 0 # Calculate product of two smallest numbers sum1 = arr[0] * arr[1] # Calculate product of two largest numbers sum2 = arr[n - 1] * arr[n - 2] # Print the pairs whose product is greater if (sum1 > sum2): num1 = arr[0] num2 = arr[1] else: num1 = arr[n - 2] num2 = arr[n - 1] print("Max product pair = {", num1, ",", num2, "}", sep="") # Driver Codearr = [1, 4, 3, 6, 7, 0]n = len(arr) maxProduct(arr, n) # This code is contributed by subhammahato348. // C# code to Find a pair with maximum// product in array of Integersusing System; class GFG{ static void maxProduct(int []arr, int n){ // Sort the array Array.Sort(arr); int num1, num2; // Calculate product of two // smallest numbers int sum1 = arr[0] * arr[1]; // Calculate product of two // largest numbers int sum2 = arr[n - 1] * arr[n - 2]; // Print the pairs whose // product is greater if (sum1 > sum2) { num1 = arr[0]; num2 = arr[1]; } else { num1 = arr[n - 2]; num2 = arr[n - 1]; } Console.Write("Max product pair = " + "{" + num1 + "," + num2 + "}");} // Driver Codepublic static void Main(String[] args){ int []arr = { 1, 4, 3, 6, 7, 0 }; int n = arr.Length; maxProduct(arr, n);}} // This code is contributed by shivanisinghss2110 <script> // Javascript code to Find a pair with maximum// product in array of Integersfunction maxProduct(arr, n){ // Sort the array arr.sort(function(a, b){return a - b}); let num1, num2; // Calculate product of two smallest numbers let sum1 = arr[0] * arr[1]; // Calculate product of two largest numbers let sum2 = arr[n - 1] * arr[n - 2]; // print the pairs whose product is greater if (sum1 > sum2) { num1 = arr[0]; num2 = arr[1]; } else { num1 = arr[n - 2]; num2 = arr[n - 1]; } document.write("Max product pair = " + "{" + num1 + "," + num2 + "}");} // Driver Codelet arr = [ 1, 4, 3, 6, 7, 0 ];let n = arr.length; maxProduct(arr, n); // This code is contributed by avanitrachhadiya2155 </script> Max product pair = 6,7 Time Complexity: O(nlog n)Auxiliary Space: O(1) Efficient Approach: An Efficient Solution can solve the above problem in a single traversal of the input array. The idea is to traverse the input array and keep track of the following four values. Maximum positive value Second maximum positive value Maximum negative value i.e., a negative value with maximum absolute value Second maximum negative value. Maximum positive value Second maximum positive value Maximum negative value i.e., a negative value with maximum absolute value Second maximum negative value. At the end of the loop, compare the products of the first two and last two and print the maximum of two products. Below is the implementation of this idea. C++ Java Python3 C# PHP Javascript // A O(n) C++ program to find maximum product pair in an array#include<bits/stdc++.h>using namespace std; // Function to find maximum product pair in arr[0..n-1]void maxProduct(int arr[], int n){ if (n < 2) { cout << "No pairs exists\n"; return; } if (n == 2) { cout << arr[0] << " " << arr[1] << endl; return; } // Initialize maximum and second maximum int posa = INT_MIN, posb = INT_MIN; // Initialize minimum and second minimum int nega = INT_MIN, negb = INT_MIN; // Traverse given array for (int i = 0; i < n; i++) { // Update maximum and second maximum if needed if (arr[i] > posa) { posb = posa; posa = arr[i]; } else if (arr[i] > posb) posb = arr[i]; // Update minimum and second minimum if needed if (arr[i] < 0 && abs(arr[i]) > abs(nega)) { negb = nega; nega = arr[i]; } else if(arr[i] < 0 && abs(arr[i]) > abs(negb)) negb = arr[i]; } if (nega*negb > posa*posb) cout << "Max product pair is {" << nega << ", " << negb << "}"; else cout << "Max product pair is {" << posa << ", " << posb << "}";} // Driver program to test above functionint main(){ int arr[] = {1, 4, 3, 6, 7, 0}; int n = sizeof(arr)/sizeof(arr[0]); maxProduct(arr, n); return 0;} // JAVA Code to Find a pair with maximum// product in array of Integersimport java.util.*; class GFG { // Function to find maximum product pair // in arr[0..n-1] static void maxProduct(int arr[], int n) { if (n < 2) { System.out.println("No pairs exists"); return; } if (n == 2) { System.out.println(arr[0] + " " + arr[1]); return; } // Initialize maximum and second maximum int posa = Integer.MIN_VALUE, posb = Integer.MIN_VALUE; // Initialize minimum and second minimum int nega = Integer.MIN_VALUE, negb = Integer.MIN_VALUE; // Traverse given array for (int i = 0; i < n; i++) { // Update maximum and second maximum // if needed if (arr[i] > posa) { posb = posa; posa = arr[i]; } else if (arr[i] > posb) posb = arr[i]; // Update minimum and second minimum // if needed if (arr[i] < 0 && Math.abs(arr[i]) > Math.abs(nega)) { negb = nega; nega = arr[i]; } else if(arr[i] < 0 && Math.abs(arr[i]) > Math.abs(negb)) negb = arr[i]; } if (nega * negb > posa * posb) System.out.println("Max product pair is {" + nega + ", " + negb + "}"); else System.out.println("Max product pair is {" + posa + ", " + posb + "}"); } /* Driver program to test above function */ public static void main(String[] args) { int arr[] = {1, 4, 3, 6, 7, 0}; int n = arr.length; maxProduct(arr, n); }} // This code is contributed by Arnav Kr. Mandal. # A O(n) Python 3 program to find# maximum product pair in an array # Function to find maximum product# pair in arr[0..n-1]def maxProduct(arr, n): if (n < 2): print("No pairs exists") return if (n == 2): print(arr[0] ," " , arr[1]) return # Initialize maximum and # second maximum posa = 0 posb = 0 # Initialize minimum and # second minimum nega = 0 negb = 0 # Traverse given array for i in range(n): # Update maximum and second # maximum if needed if (arr[i] > posa): posb = posa posa = arr[i] elif (arr[i] > posb): posb = arr[i] # Update minimum and second # minimum if needed if (arr[i] < 0 and abs(arr[i]) > abs(nega)): negb = nega nega = arr[i] elif(arr[i] < 0 and abs(arr[i]) > abs(negb)): negb = arr[i] if (nega * negb > posa * posb): print("Max product pair is {" , nega ,", ", negb , "}") else: print( "Max product pair is {" , posa ,", " ,posb , "}") # Driver Codeif __name__ =="__main__": arr = [1, 4, 3, 6, 7, 0] n = len(arr) maxProduct(arr, n) # This code is contributed# by ChitraNayal // C# Code to Find a pair with maximum// product in array of Integersusing System;class GFG { // Function to find maximum // product pair in arr[0..n-1] static void maxProduct(int []arr, int n) { if (n < 2) { Console.WriteLine("No pairs exists"); return; } if (n == 2) { Console.WriteLine(arr[0] + " " + arr[1]); return; } // Initialize maximum and // second maximum int posa = int.MinValue; int posb = int.MaxValue; // Initialize minimum and // second minimum int nega = int.MinValue; int negb = int.MaxValue; // Traverse given array for (int i = 0; i < n; i++) { // Update maximum and // second maximum // if needed if (arr[i] > posa) { posb = posa; posa = arr[i]; } else if (arr[i] > posb) posb = arr[i]; // Update minimum and // second minimum if // needed if (arr[i] < 0 && Math.Abs(arr[i]) > Math.Abs(nega)) { negb = nega; nega = arr[i]; } else if(arr[i] < 0 && Math.Abs(arr[i]) > Math.Abs(negb)) negb = arr[i]; } if (nega * negb > posa * posb) Console.WriteLine("Max product pair is {" + nega + ", " + negb + "}"); else Console.WriteLine("Max product pair is {" + posa + ", " + posb + "}"); } // Driver Code public static void Main() { int []arr = {1, 4, 3, 6, 7, 0}; int n = arr.Length; maxProduct(arr, n); }} // This code is contributed by anuj_67. <?php// A O(n) PHP program to find maximum// product pair in an array // Function to find maximum product// pair in arr[0..n-1]function maxProduct(&$arr, $n){ if ($n < 2) { echo("No pairs exists\n"); return; } if ($n == 2) { echo ($arr[0]); echo (" "); echo($arr[1]); echo("\n"); return; } // Initialize maximum and // second maximum $posa = 0; $posb = 0; // Initialize minimum and // second minimum $nega = 0; $negb = 0; // Traverse given array for ($i = 0; $i < $n; $i++) { // Update maximum and second // maximum if needed if ($arr[$i] > $posa) { $posb = $posa; $posa = $arr[$i]; } else if ($arr[$i] > $posb) $posb = $arr[$i]; // Update minimum and second // minimum if needed if ($arr[$i] < 0 && abs($arr[$i]) > abs($nega)) { $negb = $nega; $nega = $arr[$i]; } else if($arr[$i] < 0 && abs($arr[$i]) > abs($negb)) $negb = $arr[$i]; } if ($nega * $negb > $posa * $posb) { echo("Max product pair is {"); echo $nega; echo(", "); echo ($negb); echo ("}"); } else { echo("Max product pair is {"); echo $posa; echo(", "); echo ($posb); echo ("}"); }} // Driver Code$arr = array(1, 4, 3, 6, 7, 0);$n = sizeof($arr);maxProduct($arr, $n); // This code is contributed// by Shivi_Aggarwal?> <script>// JAVAscript Code to Find a pair with maximum// product in array of Integers // Function to find maximum product pair // in arr[0..n-1] function maxProduct(arr,n) { if (n < 2) { document.write("No pairs exists"); return; } if (n == 2) { document.write(arr[0] + " " + arr[1]); return; } // Initialize maximum and second maximum let posa = Number.MIN_VALUE, posb = Number.MIN_VALUE; // Initialize minimum and second minimum let nega = Number.MIN_VALUE, negb = Number.MIN_VALUE; // Traverse given array for (let i = 0; i < n; i++) { // Update maximum and second maximum // if needed if (arr[i] > posa) { posb = posa; posa = arr[i]; } else if (arr[i] > posb) posb = arr[i]; // Update minimum and second minimum // if needed if (arr[i] < 0 && Math.abs(arr[i]) > Math.abs(nega)) { negb = nega; nega = arr[i]; } else if(arr[i] < 0 && Math.abs(arr[i]) > Math.abs(negb)) negb = arr[i]; } if (nega * negb > posa * posb) document.write("Max product pair is {" + nega + ", " + negb + "}"); else document.write("Max product pair is {" + posa + ", " + posb + "}"); } /* Driver program to test above function */ let arr=[1, 4, 3, 6, 7, 0]; let n = arr.length; maxProduct(arr, n); // This code is contributed by rag2127</script> Max product pair is {7, 6} Time complexity: O(n) Auxiliary Space: O(1) Find a pair with maximum product in array of Integers | GeeksforGeeks - YouTubeGeeksforGeeks529K subscribersFind a pair with maximum product in array of Integers | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 4:01•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=PrJdyDMP8VU" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> nitin mittal vt_m ukasp Shivi_Aggarwal kumarnavtika shivanisinghss2110 Stream_Cipher subhammahato348 mayanktyagi1709 avanitrachhadiya2155 rag2127 simranarora5sos hardikkoriintern Accolite Amazon Arrays Mathematical Searching Sorting Accolite Amazon Arrays Searching Mathematical Sorting Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Maximum and minimum of an array using minimum number of comparisons Top 50 Array Coding Problems for Interviews Multidimensional Arrays in Java Stack Data Structure (Introduction and Program) Linear Search Program for Fibonacci numbers 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": 52, "s": 24, "text": "\n28 Jun, 2022" }, { "code": null, "e": 137, "s": 52, "text": "Given an array with both +ive and -ive integers, return a pair with highest product." }, { "code": null, "e": 150, "s": 137, "text": "Examples : " }, { "code": null, "e": 258, "s": 150, "text": "Input: arr[] = {1, 4, 3, 6, 7, 0} \nOutput: {6,7} \n\nInput: arr[] = {-1, -3, -4, 2, 0, -5} \nOutput: {-4,-5}" }, { "code": null, "e": 395, "s": 258, "text": "A Simple Solution is to consider every pair and keep track of the maximum product. Below is the implementation of this simple solution. " }, { "code": null, "e": 399, "s": 395, "text": "C++" }, { "code": null, "e": 404, "s": 399, "text": "Java" }, { "code": null, "e": 412, "s": 404, "text": "Python3" }, { "code": null, "e": 415, "s": 412, "text": "C#" }, { "code": null, "e": 419, "s": 415, "text": "PHP" }, { "code": null, "e": 430, "s": 419, "text": "Javascript" }, { "code": "// A simple C++ program to find max product pair in// an array of integers#include<bits/stdc++.h>using namespace std; // Function to find maximum product pair in arr[0..n-1]void maxProduct(int arr[], int n){ if (n < 2) { cout << \"No pairs exists\\n\"; return; } // Initialize max product pair int a = arr[0], b = arr[1]; // Traverse through every possible pair // and keep track of max product for (int i=0; i<n; i++) for (int j=i+1; j<n; j++) if (arr[i]*arr[j] > a*b) a = arr[i], b = arr[j]; cout << \"Max product pair is {\" << a << \", \" << b << \"}\";} // Driver program to testint main(){ int arr[] = {1, 4, 3, 6, 7, 0}; int n = sizeof(arr)/sizeof(arr[0]); maxProduct(arr, n); return 0;}", "e": 1204, "s": 430, "text": null }, { "code": "// JAVA Code to Find a pair with maximum// product in array of Integersimport java.util.*; class GFG { // Function to find maximum product pair // in arr[0..n-1] static void maxProduct(int arr[], int n) { if (n < 2) { System.out.println(\"No pairs exists\"); return; } // Initialize max product pair int a = arr[0], b = arr[1]; // Traverse through every possible pair // and keep track of max product for (int i = 0; i < n; i++) for (int j = i + 1; j < n; j++) if (arr[i] * arr[j] > a * b){ a = arr[i]; b = arr[j]; } System.out.println(\"Max product pair is {\" + a + \", \" + b + \"}\"); } /* Driver program to test above function */ public static void main(String[] args) { int arr[] = {1, 4, 3, 6, 7, 0}; int n = arr.length; maxProduct(arr, n); }} // This code is contributed by Arnav Kr. Mandal.", "e": 2267, "s": 1204, "text": null }, { "code": "# A simple Python3 program to find max# product pair in an array of integers # Function to find maximum# product pair in arr[0..n-1]def maxProduct(arr, n): if (n < 2): print(\"No pairs exists\") return # Initialize max product pair a = arr[0]; b = arr[1] # Traverse through every possible pair # and keep track of max product for i in range(0, n): for j in range(i + 1, n): if (arr[i] * arr[j] > a * b): a = arr[i]; b = arr[j] print(\"Max product pair is {\", a, \",\", b, \"}\", sep = \"\") # Driver Codearr = [1, 4, 3, 6, 7, 0]n = len(arr)maxProduct(arr, n) # This code is contributed by Smitha Dinesh Semwal.", "e": 2999, "s": 2267, "text": null }, { "code": "// C# Code to Find a pair with maximum// product in array of Integersusing System; class GFG{ // Function to find maximum // product pair in arr[0..n-1] static void maxProduct(int []arr, int n) { if (n < 2) { Console.Write(\"No pairs exists\"); return; } // Initialize max product pair int a = arr[0], b = arr[1]; // Traverse through every possible pair // and keep track of max product for (int i = 0; i < n; i++) for (int j = i + 1; j < n; j++) if (arr[i] * arr[j] > a * b) { a = arr[i]; b = arr[j]; } Console.Write(\"Max product pair is {\" + a + \", \" + b + \"}\"); } // Driver Code public static void Main() { int []arr = {1, 4, 3, 6, 7, 0}; int n = arr.Length; maxProduct(arr, n); }} // This code is contributed by nitin mittal.", "e": 3981, "s": 2999, "text": null }, { "code": "<?php// A simple PHP program to// find max product pair in// an array of integers // Function to find maximum// product pair in arr[0..n-1]function maxProduct( $arr, $n){ if ($n < 2) { echo \"No pairs exists\\n\"; return; } // Initialize max product pair $a = $arr[0]; $b = $arr[1]; // Traverse through every possible pair // and keep track of max product for ($i = 0; $i < $n; $i++) for ($j = $i + 1; $j < $n; $j++) { if ($arr[$i] * $arr[$j] > $a * $b) { $a = $arr[$i]; $b = $arr[$j]; } } echo \"Max product pair is {\" , $a , \", \"; echo $b , \"}\";} // Driver Code $arr = array(1, 4, 3, 6, 7, 0); $n = count($arr); maxProduct($arr, $n); // This code is contributed by anuj_67.?>", "e": 4770, "s": 3981, "text": null }, { "code": "<script> // A simple Javascript program to find max product pair in// an array of integers // Function to find maximum product pair in arr[0..n-1]function maxProduct(arr, n){ if (n < 2) { document.write(\"No pairs exists\" + \"<br>\"); return; } // Initialize max product pair let a = arr[0], b = arr[1]; // Traverse through every possible pair // and keep track of max product for (let i=0; i<n; i++) for (let j=i+1; j<n; j++) if (arr[i]*arr[j] > a*b) a = arr[i], b = arr[j]; document.write(\"Max product pair is {\" + a + \", \" + b + \"}\");} // Driver program to test let arr = [1, 4, 3, 6, 7, 0]; let n = arr.length; maxProduct(arr, n); // This code is contributed by Mayank Tyagi </script>", "e": 5538, "s": 4770, "text": null }, { "code": null, "e": 5565, "s": 5538, "text": "Max product pair is {6, 7}" }, { "code": null, "e": 5589, "s": 5565, "text": "Time Complexity : O(n2)" }, { "code": null, "e": 5606, "s": 5589, "text": "Better Approach:" }, { "code": null, "e": 5670, "s": 5606, "text": "A Better Solution is to use sorting. Below are detailed steps. " }, { "code": null, "e": 5861, "s": 5670, "text": "Sort input array in increasing order. If all elements are positive, then return the product of the last two numbers. Else return a maximum of products of the first two and last two numbers. " }, { "code": null, "e": 5900, "s": 5861, "text": "Sort input array in increasing order. " }, { "code": null, "e": 5980, "s": 5900, "text": "If all elements are positive, then return the product of the last two numbers. " }, { "code": null, "e": 6054, "s": 5980, "text": "Else return a maximum of products of the first two and last two numbers. " }, { "code": null, "e": 6103, "s": 6054, "text": "Thanks to Rahul Jain for suggesting this method." }, { "code": null, "e": 6109, "s": 6103, "text": "C++14" }, { "code": null, "e": 6114, "s": 6109, "text": "Java" }, { "code": null, "e": 6122, "s": 6114, "text": "Python3" }, { "code": null, "e": 6125, "s": 6122, "text": "C#" }, { "code": null, "e": 6136, "s": 6125, "text": "Javascript" }, { "code": "// C++ code to find a pair with maximum// product in array of Integers#include<bits/stdc++.h>using namespace std; void maxProduct(vector<int>arr, int n){ // Sort the array sort(arr.begin(), arr.end()); int num1, num2; // Calculate product of two smallest numbers int sum1 = arr[0] * arr[1]; // Calculate product of two largest numbers int sum2 = arr[n - 1] * arr[n - 2]; // Print the pairs whose product is greater if (sum1 > sum2) { num1 = arr[0]; num2 = arr[1]; } else { num1 = arr[n - 2]; num2 = arr[n - 1]; } cout << (\"Max product pair = \") << num1 << \",\" << num2;} // Driver Codeint main(){ vector<int>arr = { 1, 4, 3, 6, 7, 0 }; int n = arr.size(); maxProduct(arr, n);} // This code is contributed by Stream_Cipher", "e": 6970, "s": 6136, "text": null }, { "code": "// JAVA Code to Find a pair with maximum// product in array of Integersimport java.util.*; public class GFG { static void maxProduct(int arr[], int n) { // Sort the array Arrays.sort(arr); int num1, num2; // Calculate product of two smallest numbers int sum1 = arr[0] * arr[1]; // Calculate product of two largest numbers int sum2 = arr[n - 1] * arr[n - 2]; // print the pairs whose product is greater if (sum1 > sum2) { num1 = arr[0]; num2 = arr[1]; } else { num1 = arr[n - 2]; num2 = arr[n - 1]; } System.out.println(\"Max product pair = \" + \"{\" + num1 + \",\" + num2 + \"}\"); } // Driver Code public static void main(String[] args) { int arr[] = { 1, 4, 3, 6, 7, 0 }; int n = arr.length; maxProduct(arr, n); }}// Contributed by Navtika Kumar", "e": 7946, "s": 6970, "text": null }, { "code": "# Python code to find a pair with maximum# product in array of Integersdef maxProduct(arr, n): # Sort the array arr.sort() num1 = num2 = 0 # Calculate product of two smallest numbers sum1 = arr[0] * arr[1] # Calculate product of two largest numbers sum2 = arr[n - 1] * arr[n - 2] # Print the pairs whose product is greater if (sum1 > sum2): num1 = arr[0] num2 = arr[1] else: num1 = arr[n - 2] num2 = arr[n - 1] print(\"Max product pair = {\", num1, \",\", num2, \"}\", sep=\"\") # Driver Codearr = [1, 4, 3, 6, 7, 0]n = len(arr) maxProduct(arr, n) # This code is contributed by subhammahato348.", "e": 8598, "s": 7946, "text": null }, { "code": "// C# code to Find a pair with maximum// product in array of Integersusing System; class GFG{ static void maxProduct(int []arr, int n){ // Sort the array Array.Sort(arr); int num1, num2; // Calculate product of two // smallest numbers int sum1 = arr[0] * arr[1]; // Calculate product of two // largest numbers int sum2 = arr[n - 1] * arr[n - 2]; // Print the pairs whose // product is greater if (sum1 > sum2) { num1 = arr[0]; num2 = arr[1]; } else { num1 = arr[n - 2]; num2 = arr[n - 1]; } Console.Write(\"Max product pair = \" + \"{\" + num1 + \",\" + num2 + \"}\");} // Driver Codepublic static void Main(String[] args){ int []arr = { 1, 4, 3, 6, 7, 0 }; int n = arr.Length; maxProduct(arr, n);}} // This code is contributed by shivanisinghss2110", "e": 9465, "s": 8598, "text": null }, { "code": "<script> // Javascript code to Find a pair with maximum// product in array of Integersfunction maxProduct(arr, n){ // Sort the array arr.sort(function(a, b){return a - b}); let num1, num2; // Calculate product of two smallest numbers let sum1 = arr[0] * arr[1]; // Calculate product of two largest numbers let sum2 = arr[n - 1] * arr[n - 2]; // print the pairs whose product is greater if (sum1 > sum2) { num1 = arr[0]; num2 = arr[1]; } else { num1 = arr[n - 2]; num2 = arr[n - 1]; } document.write(\"Max product pair = \" + \"{\" + num1 + \",\" + num2 + \"}\");} // Driver Codelet arr = [ 1, 4, 3, 6, 7, 0 ];let n = arr.length; maxProduct(arr, n); // This code is contributed by avanitrachhadiya2155 </script>", "e": 10283, "s": 9465, "text": null }, { "code": null, "e": 10306, "s": 10283, "text": "Max product pair = 6,7" }, { "code": null, "e": 10355, "s": 10306, "text": " Time Complexity: O(nlog n)Auxiliary Space: O(1)" }, { "code": null, "e": 10376, "s": 10355, "text": "Efficient Approach: " }, { "code": null, "e": 10554, "s": 10376, "text": "An Efficient Solution can solve the above problem in a single traversal of the input array. The idea is to traverse the input array and keep track of the following four values. " }, { "code": null, "e": 10713, "s": 10554, "text": "Maximum positive value Second maximum positive value Maximum negative value i.e., a negative value with maximum absolute value Second maximum negative value. " }, { "code": null, "e": 10737, "s": 10713, "text": "Maximum positive value " }, { "code": null, "e": 10768, "s": 10737, "text": "Second maximum positive value " }, { "code": null, "e": 10843, "s": 10768, "text": "Maximum negative value i.e., a negative value with maximum absolute value " }, { "code": null, "e": 10875, "s": 10843, "text": "Second maximum negative value. " }, { "code": null, "e": 11032, "s": 10875, "text": "At the end of the loop, compare the products of the first two and last two and print the maximum of two products. Below is the implementation of this idea. " }, { "code": null, "e": 11036, "s": 11032, "text": "C++" }, { "code": null, "e": 11041, "s": 11036, "text": "Java" }, { "code": null, "e": 11049, "s": 11041, "text": "Python3" }, { "code": null, "e": 11052, "s": 11049, "text": "C#" }, { "code": null, "e": 11056, "s": 11052, "text": "PHP" }, { "code": null, "e": 11067, "s": 11056, "text": "Javascript" }, { "code": "// A O(n) C++ program to find maximum product pair in an array#include<bits/stdc++.h>using namespace std; // Function to find maximum product pair in arr[0..n-1]void maxProduct(int arr[], int n){ if (n < 2) { cout << \"No pairs exists\\n\"; return; } if (n == 2) { cout << arr[0] << \" \" << arr[1] << endl; return; } // Initialize maximum and second maximum int posa = INT_MIN, posb = INT_MIN; // Initialize minimum and second minimum int nega = INT_MIN, negb = INT_MIN; // Traverse given array for (int i = 0; i < n; i++) { // Update maximum and second maximum if needed if (arr[i] > posa) { posb = posa; posa = arr[i]; } else if (arr[i] > posb) posb = arr[i]; // Update minimum and second minimum if needed if (arr[i] < 0 && abs(arr[i]) > abs(nega)) { negb = nega; nega = arr[i]; } else if(arr[i] < 0 && abs(arr[i]) > abs(negb)) negb = arr[i]; } if (nega*negb > posa*posb) cout << \"Max product pair is {\" << nega << \", \" << negb << \"}\"; else cout << \"Max product pair is {\" << posa << \", \" << posb << \"}\";} // Driver program to test above functionint main(){ int arr[] = {1, 4, 3, 6, 7, 0}; int n = sizeof(arr)/sizeof(arr[0]); maxProduct(arr, n); return 0;}", "e": 12491, "s": 11067, "text": null }, { "code": "// JAVA Code to Find a pair with maximum// product in array of Integersimport java.util.*; class GFG { // Function to find maximum product pair // in arr[0..n-1] static void maxProduct(int arr[], int n) { if (n < 2) { System.out.println(\"No pairs exists\"); return; } if (n == 2) { System.out.println(arr[0] + \" \" + arr[1]); return; } // Initialize maximum and second maximum int posa = Integer.MIN_VALUE, posb = Integer.MIN_VALUE; // Initialize minimum and second minimum int nega = Integer.MIN_VALUE, negb = Integer.MIN_VALUE; // Traverse given array for (int i = 0; i < n; i++) { // Update maximum and second maximum // if needed if (arr[i] > posa) { posb = posa; posa = arr[i]; } else if (arr[i] > posb) posb = arr[i]; // Update minimum and second minimum // if needed if (arr[i] < 0 && Math.abs(arr[i]) > Math.abs(nega)) { negb = nega; nega = arr[i]; } else if(arr[i] < 0 && Math.abs(arr[i]) > Math.abs(negb)) negb = arr[i]; } if (nega * negb > posa * posb) System.out.println(\"Max product pair is {\" + nega + \", \" + negb + \"}\"); else System.out.println(\"Max product pair is {\" + posa + \", \" + posb + \"}\"); } /* Driver program to test above function */ public static void main(String[] args) { int arr[] = {1, 4, 3, 6, 7, 0}; int n = arr.length; maxProduct(arr, n); }} // This code is contributed by Arnav Kr. Mandal. ", "e": 14439, "s": 12491, "text": null }, { "code": "# A O(n) Python 3 program to find# maximum product pair in an array # Function to find maximum product# pair in arr[0..n-1]def maxProduct(arr, n): if (n < 2): print(\"No pairs exists\") return if (n == 2): print(arr[0] ,\" \" , arr[1]) return # Initialize maximum and # second maximum posa = 0 posb = 0 # Initialize minimum and # second minimum nega = 0 negb = 0 # Traverse given array for i in range(n): # Update maximum and second # maximum if needed if (arr[i] > posa): posb = posa posa = arr[i] elif (arr[i] > posb): posb = arr[i] # Update minimum and second # minimum if needed if (arr[i] < 0 and abs(arr[i]) > abs(nega)): negb = nega nega = arr[i] elif(arr[i] < 0 and abs(arr[i]) > abs(negb)): negb = arr[i] if (nega * negb > posa * posb): print(\"Max product pair is {\" , nega ,\", \", negb , \"}\") else: print( \"Max product pair is {\" , posa ,\", \" ,posb , \"}\") # Driver Codeif __name__ ==\"__main__\": arr = [1, 4, 3, 6, 7, 0] n = len(arr) maxProduct(arr, n) # This code is contributed# by ChitraNayal", "e": 15715, "s": 14439, "text": null }, { "code": "// C# Code to Find a pair with maximum// product in array of Integersusing System;class GFG { // Function to find maximum // product pair in arr[0..n-1] static void maxProduct(int []arr, int n) { if (n < 2) { Console.WriteLine(\"No pairs exists\"); return; } if (n == 2) { Console.WriteLine(arr[0] + \" \" + arr[1]); return; } // Initialize maximum and // second maximum int posa = int.MinValue; int posb = int.MaxValue; // Initialize minimum and // second minimum int nega = int.MinValue; int negb = int.MaxValue; // Traverse given array for (int i = 0; i < n; i++) { // Update maximum and // second maximum // if needed if (arr[i] > posa) { posb = posa; posa = arr[i]; } else if (arr[i] > posb) posb = arr[i]; // Update minimum and // second minimum if // needed if (arr[i] < 0 && Math.Abs(arr[i]) > Math.Abs(nega)) { negb = nega; nega = arr[i]; } else if(arr[i] < 0 && Math.Abs(arr[i]) > Math.Abs(negb)) negb = arr[i]; } if (nega * negb > posa * posb) Console.WriteLine(\"Max product pair is {\" + nega + \", \" + negb + \"}\"); else Console.WriteLine(\"Max product pair is {\" + posa + \", \" + posb + \"}\"); } // Driver Code public static void Main() { int []arr = {1, 4, 3, 6, 7, 0}; int n = arr.Length; maxProduct(arr, n); }} // This code is contributed by anuj_67.", "e": 17637, "s": 15715, "text": null }, { "code": "<?php// A O(n) PHP program to find maximum// product pair in an array // Function to find maximum product// pair in arr[0..n-1]function maxProduct(&$arr, $n){ if ($n < 2) { echo(\"No pairs exists\\n\"); return; } if ($n == 2) { echo ($arr[0]); echo (\" \"); echo($arr[1]); echo(\"\\n\"); return; } // Initialize maximum and // second maximum $posa = 0; $posb = 0; // Initialize minimum and // second minimum $nega = 0; $negb = 0; // Traverse given array for ($i = 0; $i < $n; $i++) { // Update maximum and second // maximum if needed if ($arr[$i] > $posa) { $posb = $posa; $posa = $arr[$i]; } else if ($arr[$i] > $posb) $posb = $arr[$i]; // Update minimum and second // minimum if needed if ($arr[$i] < 0 && abs($arr[$i]) > abs($nega)) { $negb = $nega; $nega = $arr[$i]; } else if($arr[$i] < 0 && abs($arr[$i]) > abs($negb)) $negb = $arr[$i]; } if ($nega * $negb > $posa * $posb) { echo(\"Max product pair is {\"); echo $nega; echo(\", \"); echo ($negb); echo (\"}\"); } else { echo(\"Max product pair is {\"); echo $posa; echo(\", \"); echo ($posb); echo (\"}\"); }} // Driver Code$arr = array(1, 4, 3, 6, 7, 0);$n = sizeof($arr);maxProduct($arr, $n); // This code is contributed// by Shivi_Aggarwal?>", "e": 19189, "s": 17637, "text": null }, { "code": "<script>// JAVAscript Code to Find a pair with maximum// product in array of Integers // Function to find maximum product pair // in arr[0..n-1] function maxProduct(arr,n) { if (n < 2) { document.write(\"No pairs exists\"); return; } if (n == 2) { document.write(arr[0] + \" \" + arr[1]); return; } // Initialize maximum and second maximum let posa = Number.MIN_VALUE, posb = Number.MIN_VALUE; // Initialize minimum and second minimum let nega = Number.MIN_VALUE, negb = Number.MIN_VALUE; // Traverse given array for (let i = 0; i < n; i++) { // Update maximum and second maximum // if needed if (arr[i] > posa) { posb = posa; posa = arr[i]; } else if (arr[i] > posb) posb = arr[i]; // Update minimum and second minimum // if needed if (arr[i] < 0 && Math.abs(arr[i]) > Math.abs(nega)) { negb = nega; nega = arr[i]; } else if(arr[i] < 0 && Math.abs(arr[i]) > Math.abs(negb)) negb = arr[i]; } if (nega * negb > posa * posb) document.write(\"Max product pair is {\" + nega + \", \" + negb + \"}\"); else document.write(\"Max product pair is {\" + posa + \", \" + posb + \"}\"); } /* Driver program to test above function */ let arr=[1, 4, 3, 6, 7, 0]; let n = arr.length; maxProduct(arr, n); // This code is contributed by rag2127</script>", "e": 21015, "s": 19189, "text": null }, { "code": null, "e": 21042, "s": 21015, "text": "Max product pair is {7, 6}" }, { "code": null, "e": 21086, "s": 21042, "text": "Time complexity: O(n) Auxiliary Space: O(1)" }, { "code": null, "e": 22010, "s": 21086, "text": "Find a pair with maximum product in array of Integers | GeeksforGeeks - YouTubeGeeksforGeeks529K subscribersFind a pair with maximum product in array of Integers | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 4:01•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=PrJdyDMP8VU\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>" }, { "code": null, "e": 22023, "s": 22010, "text": "nitin mittal" }, { "code": null, "e": 22028, "s": 22023, "text": "vt_m" }, { "code": null, "e": 22034, "s": 22028, "text": "ukasp" }, { "code": null, "e": 22049, "s": 22034, "text": "Shivi_Aggarwal" }, { "code": null, "e": 22062, "s": 22049, "text": "kumarnavtika" }, { "code": null, "e": 22081, "s": 22062, "text": "shivanisinghss2110" }, { "code": null, "e": 22095, "s": 22081, "text": "Stream_Cipher" }, { "code": null, "e": 22111, "s": 22095, "text": "subhammahato348" }, { "code": null, "e": 22127, "s": 22111, "text": "mayanktyagi1709" }, { "code": null, "e": 22148, "s": 22127, "text": "avanitrachhadiya2155" }, { "code": null, "e": 22156, "s": 22148, "text": "rag2127" }, { "code": null, "e": 22172, "s": 22156, "text": "simranarora5sos" }, { "code": null, "e": 22189, "s": 22172, "text": "hardikkoriintern" }, { "code": null, "e": 22198, "s": 22189, "text": "Accolite" }, { "code": null, "e": 22205, "s": 22198, "text": "Amazon" }, { "code": null, "e": 22212, "s": 22205, "text": "Arrays" }, { "code": null, "e": 22225, "s": 22212, "text": "Mathematical" }, { "code": null, "e": 22235, "s": 22225, "text": "Searching" }, { "code": null, "e": 22243, "s": 22235, "text": "Sorting" }, { "code": null, "e": 22252, "s": 22243, "text": "Accolite" }, { "code": null, "e": 22259, "s": 22252, "text": "Amazon" }, { "code": null, "e": 22266, "s": 22259, "text": "Arrays" }, { "code": null, "e": 22276, "s": 22266, "text": "Searching" }, { "code": null, "e": 22289, "s": 22276, "text": "Mathematical" }, { "code": null, "e": 22297, "s": 22289, "text": "Sorting" }, { "code": null, "e": 22395, "s": 22297, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 22463, "s": 22395, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 22507, "s": 22463, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 22539, "s": 22507, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 22587, "s": 22539, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 22601, "s": 22587, "text": "Linear Search" }, { "code": null, "e": 22631, "s": 22601, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 22674, "s": 22631, "text": "Set in C++ Standard Template Library (STL)" }, { "code": null, "e": 22734, "s": 22674, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 22749, "s": 22734, "text": "C++ Data Types" } ]
Minimum number of characters required to be added to a String such that all lowercase alphabets occurs as a subsequence in increasing order
09 Sep, 2021 Given a string S consisting of N characters, the task is to find the minimum number of characters that must be added to S such that all lowercase alphabets occur as a subsequence in increasing order in S. Examples: Input: S = “axyabzaxd”Output: 22Explanation:The characters from b to w (bcdefghijklmnopqrstuvw) whose count is 22, is missing in the given string S.So, to make all the lower case english characters as a subsequence in it we have to add all these 22 characters. Therefore, the minimum characters to be added is 22. Input: S = “abcdefghixyabzjklmnoaxpqrstd”Output: 6 Naive Approach: The simplest approach to solve the given problem is to generate all possible subsequences of the given string S and check in which subsequence appending the minimum number of characters in the string gives the subsequence of all lowercase alphabets in increasing order. After checking for all the subsequences, print the minimum number of characters appended. Time Complexity: O(2N)Auxiliary Space: O(1) Efficient Approach: The above approach can also be optimized by the following observation: Since all the lowercase characters must be present after appending characters i.e., string S must contain string T as “abcdefghijklmnopqrstuvwxyz” as a subsequence. The minimum number of characters that must be appended in any order is to first find the Longest Common Subsequence(say L) of string S and string T as this gives the maximum number of characters in increasing order that we don’t need to add And then print the value of (26 – L) as the resultant minimum characters required. From the above observations, find the value of LCS of the string S and T and print the value of (26 – LCS) as the result. Below is the implementation of the above approach: C++ Java Python C# Javascript // C++ program for the above approach#include "bits/stdc++.h"using namespace std; // Function to find the LCS// of strings S and string Tint LCS(string& S, int N, string& T, int M, vector<vector<int> >& dp){ // Base Case if (N == 0 or M == 0) return 0; // Already Calculated State if (dp[N][M] != -1) return dp[N][M]; // If the characters are the same if (S[N - 1] == T[M - 1]) { return dp[N][M] = 1 + LCS(S, N - 1, T, M - 1, dp); } // Otherwise return dp[N][M] = max(LCS(S, N - 1, T, M, dp), LCS(S, N, T, M - 1, dp));} // Function to find the minimum number of// characters that needs to be appended// in the string to get all lowercase// alphabets as a subsequencesint minimumCharacter(string& S){ // String containing all the characters string T = "abcdefghijklmnopqrstuvwxyz"; int N = S.length(), M = T.length(); // Stores the result of overlapping // subproblems vector<vector<int> > dp(N + 1, vector<int>(M + 1, -1)); // Return the minimum characters // required return (26 - LCS(S, N, T, M, dp));} // Driver Codeint main(){ string S = "abcdadc"; cout << minimumCharacter(S); return 0;} // Java program for the above approachimport java.io.*; class GFG{ // Function to find the LCS // of strings S and string T static int LCS(String S, int N, String T, int M, int dp[][]) { // Base Case if (N == 0 || M == 0) return 0; // Already Calculated State if (dp[N][M] != 0) return dp[N][M]; // If the characters are the same if (S.charAt(N - 1)== T.charAt(M - 1)) { return dp[N][M] = 1 + LCS(S, N - 1, T, M - 1, dp); } // Otherwise return dp[N][M] = Math.max( LCS(S, N - 1, T, M, dp), LCS(S, N, T, M - 1, dp)); } // Function to find the minimum number of // characters that needs to be appended // in the string to get all lowercase // alphabets as a subsequences static int minimumCharacter(String S) { // String containing all the characters String T = "abcdefghijklmnopqrstuvwxyz"; int N = S.length(), M = T.length(); // Stores the result of overlapping // subproblems int dp[][]= new int[N+1][M+1]; // Return the minimum characters // required return (26 - LCS(S, N, T, M, dp)); } // Driver Code public static void main (String[] args) { String S = "abcdadc"; System.out.println(minimumCharacter(S)); }} // This code is contributed by Potta Lokesh # Python3 program for the above approachimport numpy as np # Function to find the LCS# of strings S and string Tdef LCS(S, N, T, M, dp) : # Base Case if (N == 0 or M == 0) : return 0; # Already Calculated State if (dp[N][M] != 0) : return dp[N][M]; # If the characters are the same if (S[N - 1] == T[M - 1]) : dp[N][M] = 1 + LCS(S, N - 1, T, M - 1, dp); return dp[N][M] # Otherwise dp[N][M] = max( LCS(S, N - 1, T, M, dp), LCS(S, N, T, M - 1, dp)); return dp[N][M] # Function to find the minimum number of# characters that needs to be appended# in the string to get all lowercase# alphabets as a subsequencesdef minimumCharacter(S) : # String containing all the characters T = "abcdefghijklmnopqrstuvwxyz"; N = len(S); M = len(T); # Stores the result of overlapping # subproblems dp = np.zeros((N + 1, M + 1)); # Return the minimum characters # required return (26 - LCS(S, N, T, M, dp)); # Driver Codeif __name__ == "__main__" : S = "abcdadc"; print(minimumCharacter(S)); # This code is contributed by AnkThon // C# program for the above approach using System; public class GFG{ // Function to find the LCS // of strings S and string T static int LCS(String S, int N, String T, int M, int [,]dp) { // Base Case if (N == 0 || M == 0) return 0; // Already Calculated State if (dp[N,M] != 0) return dp[N,M]; // If the characters are the same if (S[N - 1]== T[M - 1]) { return dp[N,M] = 1 + LCS(S, N - 1, T, M - 1, dp); } // Otherwise return dp[N,M] = Math.Max( LCS(S, N - 1, T, M, dp), LCS(S, N, T, M - 1, dp)); } // Function to find the minimum number of // characters that needs to be appended // in the string to get all lowercase // alphabets as a subsequences static int minimumchar(String S) { // String containing all the characters String T = "abcdefghijklmnopqrstuvwxyz"; int N = S.Length, M = T.Length; // Stores the result of overlapping // subproblems int [,]dp= new int[N+1,M+1]; // Return the minimum characters // required return (26 - LCS(S, N, T, M, dp)); } // Driver Code public static void Main(String[] args) { String S = "abcdadc"; Console.WriteLine(minimumchar(S)); }} // This code is contributed by 29AjayKumar <script>// javascript program for the above approach // Function to find the LCS // of strings S and string T function LCS(S , N, T, M , dp) { // Base Case if (N == 0 || M == 0) return 0; // Already Calculated State if (dp[N][M] != 0) return dp[N][M]; // If the characters are the same if (S.charAt(N - 1)== T.charAt(M - 1)) { return dp[N][M] = 1 + LCS(S, N - 1, T, M - 1, dp); } // Otherwise return dp[N][M] = Math.max( LCS(S, N - 1, T, M, dp), LCS(S, N, T, M - 1, dp)); } // Function to find the minimum number of // characters that needs to be appended // in the string to get all lowercase // alphabets as a subsequences function minimumCharacter(S) { // String containing all the characters var T = "abcdefghijklmnopqrstuvwxyz"; var N = S.length, M = T.length; // Stores the result of overlapping // subproblems var dp= Array(N+1).fill(0).map(x => Array(M+1).fill(0)); // Return the minimum characters // required return (26 - LCS(S, N, T, M, dp)); } // Driver Code var S = "abcdadc"; document.write(minimumCharacter(S)); // This code is contributed by 29AjayKumar</script> 22 Time Complexity: O(26*N)Auxiliary Space: O(1) lokeshpotta20 29AjayKumar ankthon subsequence Strings Strings Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Top 50 String Coding Problems for Interviews What is Data Structure: Types, Classifications and Applications Print all the duplicates in the input string Print all subsequences of a string A Program to check if strings are rotations of each other or not String class in Java | Set 1 Find if a string is interleaved of two other strings | DP-33 Check if an URL is valid or not using Regular Expression Remove first and last character of a string in Java Find the smallest window in a string containing all characters of another string
[ { "code": null, "e": 52, "s": 24, "text": "\n09 Sep, 2021" }, { "code": null, "e": 257, "s": 52, "text": "Given a string S consisting of N characters, the task is to find the minimum number of characters that must be added to S such that all lowercase alphabets occur as a subsequence in increasing order in S." }, { "code": null, "e": 267, "s": 257, "text": "Examples:" }, { "code": null, "e": 581, "s": 267, "text": "Input: S = “axyabzaxd”Output: 22Explanation:The characters from b to w (bcdefghijklmnopqrstuvw) whose count is 22, is missing in the given string S.So, to make all the lower case english characters as a subsequence in it we have to add all these 22 characters. Therefore, the minimum characters to be added is 22." }, { "code": null, "e": 632, "s": 581, "text": "Input: S = “abcdefghixyabzjklmnoaxpqrstd”Output: 6" }, { "code": null, "e": 1052, "s": 632, "text": "Naive Approach: The simplest approach to solve the given problem is to generate all possible subsequences of the given string S and check in which subsequence appending the minimum number of characters in the string gives the subsequence of all lowercase alphabets in increasing order. After checking for all the subsequences, print the minimum number of characters appended. Time Complexity: O(2N)Auxiliary Space: O(1)" }, { "code": null, "e": 1143, "s": 1052, "text": "Efficient Approach: The above approach can also be optimized by the following observation:" }, { "code": null, "e": 1308, "s": 1143, "text": "Since all the lowercase characters must be present after appending characters i.e., string S must contain string T as “abcdefghijklmnopqrstuvwxyz” as a subsequence." }, { "code": null, "e": 1549, "s": 1308, "text": "The minimum number of characters that must be appended in any order is to first find the Longest Common Subsequence(say L) of string S and string T as this gives the maximum number of characters in increasing order that we don’t need to add" }, { "code": null, "e": 1632, "s": 1549, "text": "And then print the value of (26 – L) as the resultant minimum characters required." }, { "code": null, "e": 1754, "s": 1632, "text": "From the above observations, find the value of LCS of the string S and T and print the value of (26 – LCS) as the result." }, { "code": null, "e": 1805, "s": 1754, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 1809, "s": 1805, "text": "C++" }, { "code": null, "e": 1814, "s": 1809, "text": "Java" }, { "code": null, "e": 1821, "s": 1814, "text": "Python" }, { "code": null, "e": 1824, "s": 1821, "text": "C#" }, { "code": null, "e": 1835, "s": 1824, "text": "Javascript" }, { "code": "// C++ program for the above approach#include \"bits/stdc++.h\"using namespace std; // Function to find the LCS// of strings S and string Tint LCS(string& S, int N, string& T, int M, vector<vector<int> >& dp){ // Base Case if (N == 0 or M == 0) return 0; // Already Calculated State if (dp[N][M] != -1) return dp[N][M]; // If the characters are the same if (S[N - 1] == T[M - 1]) { return dp[N][M] = 1 + LCS(S, N - 1, T, M - 1, dp); } // Otherwise return dp[N][M] = max(LCS(S, N - 1, T, M, dp), LCS(S, N, T, M - 1, dp));} // Function to find the minimum number of// characters that needs to be appended// in the string to get all lowercase// alphabets as a subsequencesint minimumCharacter(string& S){ // String containing all the characters string T = \"abcdefghijklmnopqrstuvwxyz\"; int N = S.length(), M = T.length(); // Stores the result of overlapping // subproblems vector<vector<int> > dp(N + 1, vector<int>(M + 1, -1)); // Return the minimum characters // required return (26 - LCS(S, N, T, M, dp));} // Driver Codeint main(){ string S = \"abcdadc\"; cout << minimumCharacter(S); return 0;}", "e": 3054, "s": 1835, "text": null }, { "code": "// Java program for the above approachimport java.io.*; class GFG{ // Function to find the LCS // of strings S and string T static int LCS(String S, int N, String T, int M, int dp[][]) { // Base Case if (N == 0 || M == 0) return 0; // Already Calculated State if (dp[N][M] != 0) return dp[N][M]; // If the characters are the same if (S.charAt(N - 1)== T.charAt(M - 1)) { return dp[N][M] = 1 + LCS(S, N - 1, T, M - 1, dp); } // Otherwise return dp[N][M] = Math.max( LCS(S, N - 1, T, M, dp), LCS(S, N, T, M - 1, dp)); } // Function to find the minimum number of // characters that needs to be appended // in the string to get all lowercase // alphabets as a subsequences static int minimumCharacter(String S) { // String containing all the characters String T = \"abcdefghijklmnopqrstuvwxyz\"; int N = S.length(), M = T.length(); // Stores the result of overlapping // subproblems int dp[][]= new int[N+1][M+1]; // Return the minimum characters // required return (26 - LCS(S, N, T, M, dp)); } // Driver Code public static void main (String[] args) { String S = \"abcdadc\"; System.out.println(minimumCharacter(S)); }} // This code is contributed by Potta Lokesh", "e": 4369, "s": 3054, "text": null }, { "code": "# Python3 program for the above approachimport numpy as np # Function to find the LCS# of strings S and string Tdef LCS(S, N, T, M, dp) : # Base Case if (N == 0 or M == 0) : return 0; # Already Calculated State if (dp[N][M] != 0) : return dp[N][M]; # If the characters are the same if (S[N - 1] == T[M - 1]) : dp[N][M] = 1 + LCS(S, N - 1, T, M - 1, dp); return dp[N][M] # Otherwise dp[N][M] = max( LCS(S, N - 1, T, M, dp), LCS(S, N, T, M - 1, dp)); return dp[N][M] # Function to find the minimum number of# characters that needs to be appended# in the string to get all lowercase# alphabets as a subsequencesdef minimumCharacter(S) : # String containing all the characters T = \"abcdefghijklmnopqrstuvwxyz\"; N = len(S); M = len(T); # Stores the result of overlapping # subproblems dp = np.zeros((N + 1, M + 1)); # Return the minimum characters # required return (26 - LCS(S, N, T, M, dp)); # Driver Codeif __name__ == \"__main__\" : S = \"abcdadc\"; print(minimumCharacter(S)); # This code is contributed by AnkThon", "e": 5492, "s": 4369, "text": null }, { "code": "// C# program for the above approach using System; public class GFG{ // Function to find the LCS // of strings S and string T static int LCS(String S, int N, String T, int M, int [,]dp) { // Base Case if (N == 0 || M == 0) return 0; // Already Calculated State if (dp[N,M] != 0) return dp[N,M]; // If the characters are the same if (S[N - 1]== T[M - 1]) { return dp[N,M] = 1 + LCS(S, N - 1, T, M - 1, dp); } // Otherwise return dp[N,M] = Math.Max( LCS(S, N - 1, T, M, dp), LCS(S, N, T, M - 1, dp)); } // Function to find the minimum number of // characters that needs to be appended // in the string to get all lowercase // alphabets as a subsequences static int minimumchar(String S) { // String containing all the characters String T = \"abcdefghijklmnopqrstuvwxyz\"; int N = S.Length, M = T.Length; // Stores the result of overlapping // subproblems int [,]dp= new int[N+1,M+1]; // Return the minimum characters // required return (26 - LCS(S, N, T, M, dp)); } // Driver Code public static void Main(String[] args) { String S = \"abcdadc\"; Console.WriteLine(minimumchar(S)); }} // This code is contributed by 29AjayKumar", "e": 6774, "s": 5492, "text": null }, { "code": "<script>// javascript program for the above approach // Function to find the LCS // of strings S and string T function LCS(S , N, T, M , dp) { // Base Case if (N == 0 || M == 0) return 0; // Already Calculated State if (dp[N][M] != 0) return dp[N][M]; // If the characters are the same if (S.charAt(N - 1)== T.charAt(M - 1)) { return dp[N][M] = 1 + LCS(S, N - 1, T, M - 1, dp); } // Otherwise return dp[N][M] = Math.max( LCS(S, N - 1, T, M, dp), LCS(S, N, T, M - 1, dp)); } // Function to find the minimum number of // characters that needs to be appended // in the string to get all lowercase // alphabets as a subsequences function minimumCharacter(S) { // String containing all the characters var T = \"abcdefghijklmnopqrstuvwxyz\"; var N = S.length, M = T.length; // Stores the result of overlapping // subproblems var dp= Array(N+1).fill(0).map(x => Array(M+1).fill(0)); // Return the minimum characters // required return (26 - LCS(S, N, T, M, dp)); } // Driver Code var S = \"abcdadc\"; document.write(minimumCharacter(S)); // This code is contributed by 29AjayKumar</script>", "e": 8004, "s": 6774, "text": null }, { "code": null, "e": 8007, "s": 8004, "text": "22" }, { "code": null, "e": 8055, "s": 8009, "text": "Time Complexity: O(26*N)Auxiliary Space: O(1)" }, { "code": null, "e": 8069, "s": 8055, "text": "lokeshpotta20" }, { "code": null, "e": 8081, "s": 8069, "text": "29AjayKumar" }, { "code": null, "e": 8089, "s": 8081, "text": "ankthon" }, { "code": null, "e": 8101, "s": 8089, "text": "subsequence" }, { "code": null, "e": 8109, "s": 8101, "text": "Strings" }, { "code": null, "e": 8117, "s": 8109, "text": "Strings" }, { "code": null, "e": 8215, "s": 8117, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 8260, "s": 8215, "text": "Top 50 String Coding Problems for Interviews" }, { "code": null, "e": 8324, "s": 8260, "text": "What is Data Structure: Types, Classifications and Applications" }, { "code": null, "e": 8369, "s": 8324, "text": "Print all the duplicates in the input string" }, { "code": null, "e": 8404, "s": 8369, "text": "Print all subsequences of a string" }, { "code": null, "e": 8469, "s": 8404, "text": "A Program to check if strings are rotations of each other or not" }, { "code": null, "e": 8498, "s": 8469, "text": "String class in Java | Set 1" }, { "code": null, "e": 8559, "s": 8498, "text": "Find if a string is interleaved of two other strings | DP-33" }, { "code": null, "e": 8616, "s": 8559, "text": "Check if an URL is valid or not using Regular Expression" }, { "code": null, "e": 8668, "s": 8616, "text": "Remove first and last character of a string in Java" } ]
How to Get TreeMap Key or Value using Index in Java?
23 Jul, 2021 The TreeMap in Java is used to implement the Map interface and NavigableMap along with the AbstractMap Class. The TreeMap is sorted according to the natural ordering of its keys. The TreeMap class is a Red-Black tree implementation of the Map interface and thus does not expose any methods using which we can access the TreeMap keys or values using their indices. There are three simple ways to get key or TreeMap value using index in Java, which is the following : Using an ArrayUsing a ListUsing iteration Using an Array Using a List Using iteration Method 1: Using an Array We can get a TreeMap key or TreeMap value using an index in Java by using an Array. The process is divided into three steps: Use the entrySet() method of the TreeMap class to get a Set view of all the entries stored in the TreeMap object.Convert the entry set to an array using the toArray() method.And get TreeMap key or TreeMap value using index with the help of getKey() and getValue() method Use the entrySet() method of the TreeMap class to get a Set view of all the entries stored in the TreeMap object. Convert the entry set to an array using the toArray() method. And get TreeMap key or TreeMap value using index with the help of getKey() and getValue() method Syntax: Set<Map.Entry<Integer, String>> entrySet = treeMap.entrySet(); Map.Entry<Integer, String>[] entryArray = entrySet.toArray(new Map.Entry[entrySet.size()]); Example: Java // Java Program to get TreeMap key or TreeMap value// using index // Importing all classes of// java.util packageimport java.util.*; // Classpublic class GFG { // MAin driver method public static void main(String[] args) { // Creating a New TreeMap TreeMap<Integer, String> treeMap = new TreeMap<Integer, String>(); // Add elements to TreeMap // Custom inputs treeMap.put(1, "Welcome"); treeMap.put(2, "geeks"); treeMap.put(3, "on"); treeMap.put(4, "geeksforgeeks"); // Get entry set of the TreeMap using entrySet // method Set<Map.Entry<Integer, String> > entrySet = treeMap.entrySet(); // Convert entrySet to Array using toArray method Map.Entry<Integer, String>[] entryArray = entrySet.toArray( new Map.Entry[entrySet.size()]); // For loop for iteration and printing for (int i = 0; i < 4; i++) { // Get Key using index and print System.out.println("Key at " + i + ":" + entryArray[i].getKey()); // Get value using index and print System.out.println("Value at " + i + ":" + entryArray[i].getValue()); } }} Output: 1 Welcome 2 geeks 3 on 4 geeksforgeeks Method 2: Using a List We can get TreeMap key or TreeMap value using index in Java by using a List instead of Array. The process is divided into three steps: Using entrySet() method of the TreeMap class to get a set view of all the entries stored in the TreeMap object.Now, converting the entry set to an array using the toArray() method.Finally, getting TreeMap key or TreeMap value using index with the help of get(), getKey() and getValue() methods. Using entrySet() method of the TreeMap class to get a set view of all the entries stored in the TreeMap object. Now, converting the entry set to an array using the toArray() method. Finally, getting TreeMap key or TreeMap value using index with the help of get(), getKey() and getValue() methods. Syntax: Set<Map.Entry<Integer, String>> entrySet = treeMap.entrySet(); List<Map.Entry<Integer, String>> entryList = new ArrayList<Map.Entry<Integer, String>>(entrySet); Example: Java // Java Program to get TreeMap key or TreeMap value// using index // Importing all classes of// java.util packageimport java.util.*; // Classpublic class GFG { // Main driver method public static void main(String[] args) { // Creating a TreeMap TreeMap<Integer, String> treeMap = new TreeMap<>(); // Add elements to TreeMap // Custom inputs treeMap.put(1, "Welcome"); treeMap.put(2, "geeks"); treeMap.put(3, "on"); treeMap.put(4, "geeksforgeeks"); // Get entry set of the TreeMap // using entrySet method Set<Map.Entry<Integer, String> > entrySet = treeMap.entrySet(); // Converting entrySet to ArrayList List<Map.Entry<Integer, String> > entryList = new ArrayList<>(entrySet); // For each loop for iteration for (int i = 0; i < 4; i++) { // Print Key and Values using index // Get Key using index System.out.println("Key at " + i + ":" + entryList.get(i).getKey()); // Get value using index System.out.println( "Value at " + i + ":" + entryList.get(i).getValue()); } }} Key at 0:1 Value at 0:Welcome Key at 1:2 Value at 1:geeks Key at 2:3 Value at 2:on Key at 3:4 Value at 3:geeksforgeeks Method 3: Using iteration We can get TreeMap key or TreeMap value using index in Java by using an iteration. The process is divided into two steps: Using the entrySet() method of the TreeMap class to get a Set view of all the entries stored in the TreeMap object.Iterating on entrySet to get TreeMap key or TreeMap value using index with the help of getKey() and getValue() methods. Using the entrySet() method of the TreeMap class to get a Set view of all the entries stored in the TreeMap object. Iterating on entrySet to get TreeMap key or TreeMap value using index with the help of getKey() and getValue() methods. Syntax: Set<Map.Entry<Integer, String>> entrySet = treeMap.entrySet(); Example: Java // Java Program to get TreeMap key or TreeMap value using// index // Importing all classes of// java.util packageimport java.util.*; // Classpublic class GFG { // MAin driver method public static void main(String[] args) { // Creating a TreeMp TreeMap<Integer, String> treeMap = new TreeMap<>(); // Add elements to TreeMap // Custom inputs treeMap.put(1, "Welcome"); treeMap.put(2, "geeks"); treeMap.put(3, "on"); treeMap.put(4, "geeksforgeeks"); // Get entry set of the TreeMap // using entrySet method Set<Map.Entry<Integer, String> > entrySet = treeMap.entrySet(); int index = 0; // For-each loop for iteration for (Map.Entry<Integer, String> currentEntry : entrySet) { // Print Key and Values using index // Get Key using index System.out.println("Key at " + index + ":" + currentEntry.getKey()); // Get value using index System.out.println("Value at " + index + ":" + currentEntry.getValue()); index++; } }} Key at 0:1 Value at 0:Welcome Key at 1:2 Value at 1:geeks Key at 2:3 Value at 2:on Key at 3:4 Value at 3:geeksforgeeks rajeev0719singh java-TreeMap Picked Java Java Programs Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. List Interface in Java with Examples Different ways of Reading a text file in Java Constructors in Java Strings in Java HashMap containsKey() Method in Java Java Programming Examples Convert Double to Integer in Java Implementing a Linked List in Java using Class Traverse Through a HashMap in Java Extends vs Implements in Java
[ { "code": null, "e": 28, "s": 0, "text": "\n23 Jul, 2021" }, { "code": null, "e": 392, "s": 28, "text": "The TreeMap in Java is used to implement the Map interface and NavigableMap along with the AbstractMap Class. The TreeMap is sorted according to the natural ordering of its keys. The TreeMap class is a Red-Black tree implementation of the Map interface and thus does not expose any methods using which we can access the TreeMap keys or values using their indices." }, { "code": null, "e": 495, "s": 392, "text": " There are three simple ways to get key or TreeMap value using index in Java, which is the following :" }, { "code": null, "e": 537, "s": 495, "text": "Using an ArrayUsing a ListUsing iteration" }, { "code": null, "e": 552, "s": 537, "text": "Using an Array" }, { "code": null, "e": 565, "s": 552, "text": "Using a List" }, { "code": null, "e": 581, "s": 565, "text": "Using iteration" }, { "code": null, "e": 606, "s": 581, "text": "Method 1: Using an Array" }, { "code": null, "e": 731, "s": 606, "text": "We can get a TreeMap key or TreeMap value using an index in Java by using an Array. The process is divided into three steps:" }, { "code": null, "e": 1002, "s": 731, "text": "Use the entrySet() method of the TreeMap class to get a Set view of all the entries stored in the TreeMap object.Convert the entry set to an array using the toArray() method.And get TreeMap key or TreeMap value using index with the help of getKey() and getValue() method" }, { "code": null, "e": 1116, "s": 1002, "text": "Use the entrySet() method of the TreeMap class to get a Set view of all the entries stored in the TreeMap object." }, { "code": null, "e": 1178, "s": 1116, "text": "Convert the entry set to an array using the toArray() method." }, { "code": null, "e": 1275, "s": 1178, "text": "And get TreeMap key or TreeMap value using index with the help of getKey() and getValue() method" }, { "code": null, "e": 1283, "s": 1275, "text": "Syntax:" }, { "code": null, "e": 1346, "s": 1283, "text": "Set<Map.Entry<Integer, String>> entrySet = treeMap.entrySet();" }, { "code": null, "e": 1438, "s": 1346, "text": "Map.Entry<Integer, String>[] entryArray = entrySet.toArray(new Map.Entry[entrySet.size()]);" }, { "code": null, "e": 1447, "s": 1438, "text": "Example:" }, { "code": null, "e": 1452, "s": 1447, "text": "Java" }, { "code": "// Java Program to get TreeMap key or TreeMap value// using index // Importing all classes of// java.util packageimport java.util.*; // Classpublic class GFG { // MAin driver method public static void main(String[] args) { // Creating a New TreeMap TreeMap<Integer, String> treeMap = new TreeMap<Integer, String>(); // Add elements to TreeMap // Custom inputs treeMap.put(1, \"Welcome\"); treeMap.put(2, \"geeks\"); treeMap.put(3, \"on\"); treeMap.put(4, \"geeksforgeeks\"); // Get entry set of the TreeMap using entrySet // method Set<Map.Entry<Integer, String> > entrySet = treeMap.entrySet(); // Convert entrySet to Array using toArray method Map.Entry<Integer, String>[] entryArray = entrySet.toArray( new Map.Entry[entrySet.size()]); // For loop for iteration and printing for (int i = 0; i < 4; i++) { // Get Key using index and print System.out.println(\"Key at \" + i + \":\" + entryArray[i].getKey()); // Get value using index and print System.out.println(\"Value at \" + i + \":\" + entryArray[i].getValue()); } }}", "e": 2761, "s": 1452, "text": null }, { "code": null, "e": 2769, "s": 2761, "text": "Output:" }, { "code": null, "e": 2808, "s": 2769, "text": "1\nWelcome\n2\ngeeks\n3\non\n4\ngeeksforgeeks" }, { "code": null, "e": 2833, "s": 2810, "text": "Method 2: Using a List" }, { "code": null, "e": 2968, "s": 2833, "text": "We can get TreeMap key or TreeMap value using index in Java by using a List instead of Array. The process is divided into three steps:" }, { "code": null, "e": 3263, "s": 2968, "text": "Using entrySet() method of the TreeMap class to get a set view of all the entries stored in the TreeMap object.Now, converting the entry set to an array using the toArray() method.Finally, getting TreeMap key or TreeMap value using index with the help of get(), getKey() and getValue() methods." }, { "code": null, "e": 3375, "s": 3263, "text": "Using entrySet() method of the TreeMap class to get a set view of all the entries stored in the TreeMap object." }, { "code": null, "e": 3445, "s": 3375, "text": "Now, converting the entry set to an array using the toArray() method." }, { "code": null, "e": 3560, "s": 3445, "text": "Finally, getting TreeMap key or TreeMap value using index with the help of get(), getKey() and getValue() methods." }, { "code": null, "e": 3571, "s": 3562, "text": "Syntax: " }, { "code": null, "e": 3634, "s": 3571, "text": "Set<Map.Entry<Integer, String>> entrySet = treeMap.entrySet();" }, { "code": null, "e": 3732, "s": 3634, "text": "List<Map.Entry<Integer, String>> entryList = new ArrayList<Map.Entry<Integer, String>>(entrySet);" }, { "code": null, "e": 3741, "s": 3732, "text": "Example:" }, { "code": null, "e": 3746, "s": 3741, "text": "Java" }, { "code": "// Java Program to get TreeMap key or TreeMap value// using index // Importing all classes of// java.util packageimport java.util.*; // Classpublic class GFG { // Main driver method public static void main(String[] args) { // Creating a TreeMap TreeMap<Integer, String> treeMap = new TreeMap<>(); // Add elements to TreeMap // Custom inputs treeMap.put(1, \"Welcome\"); treeMap.put(2, \"geeks\"); treeMap.put(3, \"on\"); treeMap.put(4, \"geeksforgeeks\"); // Get entry set of the TreeMap // using entrySet method Set<Map.Entry<Integer, String> > entrySet = treeMap.entrySet(); // Converting entrySet to ArrayList List<Map.Entry<Integer, String> > entryList = new ArrayList<>(entrySet); // For each loop for iteration for (int i = 0; i < 4; i++) { // Print Key and Values using index // Get Key using index System.out.println(\"Key at \" + i + \":\" + entryList.get(i).getKey()); // Get value using index System.out.println( \"Value at \" + i + \":\" + entryList.get(i).getValue()); } }}", "e": 4987, "s": 3746, "text": null }, { "code": null, "e": 5109, "s": 4990, "text": "Key at 0:1\nValue at 0:Welcome\nKey at 1:2\nValue at 1:geeks\nKey at 2:3\nValue at 2:on\nKey at 3:4\nValue at 3:geeksforgeeks" }, { "code": null, "e": 5136, "s": 5109, "text": " Method 3: Using iteration" }, { "code": null, "e": 5259, "s": 5136, "text": "We can get TreeMap key or TreeMap value using index in Java by using an iteration. The process is divided into two steps: " }, { "code": null, "e": 5494, "s": 5259, "text": "Using the entrySet() method of the TreeMap class to get a Set view of all the entries stored in the TreeMap object.Iterating on entrySet to get TreeMap key or TreeMap value using index with the help of getKey() and getValue() methods." }, { "code": null, "e": 5610, "s": 5494, "text": "Using the entrySet() method of the TreeMap class to get a Set view of all the entries stored in the TreeMap object." }, { "code": null, "e": 5730, "s": 5610, "text": "Iterating on entrySet to get TreeMap key or TreeMap value using index with the help of getKey() and getValue() methods." }, { "code": null, "e": 5742, "s": 5732, "text": "Syntax: " }, { "code": null, "e": 5805, "s": 5742, "text": "Set<Map.Entry<Integer, String>> entrySet = treeMap.entrySet();" }, { "code": null, "e": 5814, "s": 5805, "text": "Example:" }, { "code": null, "e": 5819, "s": 5814, "text": "Java" }, { "code": "// Java Program to get TreeMap key or TreeMap value using// index // Importing all classes of// java.util packageimport java.util.*; // Classpublic class GFG { // MAin driver method public static void main(String[] args) { // Creating a TreeMp TreeMap<Integer, String> treeMap = new TreeMap<>(); // Add elements to TreeMap // Custom inputs treeMap.put(1, \"Welcome\"); treeMap.put(2, \"geeks\"); treeMap.put(3, \"on\"); treeMap.put(4, \"geeksforgeeks\"); // Get entry set of the TreeMap // using entrySet method Set<Map.Entry<Integer, String> > entrySet = treeMap.entrySet(); int index = 0; // For-each loop for iteration for (Map.Entry<Integer, String> currentEntry : entrySet) { // Print Key and Values using index // Get Key using index System.out.println(\"Key at \" + index + \":\" + currentEntry.getKey()); // Get value using index System.out.println(\"Value at \" + index + \":\" + currentEntry.getValue()); index++; } }}", "e": 7006, "s": 5819, "text": null }, { "code": null, "e": 7125, "s": 7006, "text": "Key at 0:1\nValue at 0:Welcome\nKey at 1:2\nValue at 1:geeks\nKey at 2:3\nValue at 2:on\nKey at 3:4\nValue at 3:geeksforgeeks" }, { "code": null, "e": 7143, "s": 7127, "text": "rajeev0719singh" }, { "code": null, "e": 7156, "s": 7143, "text": "java-TreeMap" }, { "code": null, "e": 7163, "s": 7156, "text": "Picked" }, { "code": null, "e": 7168, "s": 7163, "text": "Java" }, { "code": null, "e": 7182, "s": 7168, "text": "Java Programs" }, { "code": null, "e": 7187, "s": 7182, "text": "Java" }, { "code": null, "e": 7285, "s": 7187, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 7322, "s": 7285, "text": "List Interface in Java with Examples" }, { "code": null, "e": 7368, "s": 7322, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 7389, "s": 7368, "text": "Constructors in Java" }, { "code": null, "e": 7405, "s": 7389, "text": "Strings in Java" }, { "code": null, "e": 7442, "s": 7405, "text": "HashMap containsKey() Method in Java" }, { "code": null, "e": 7468, "s": 7442, "text": "Java Programming Examples" }, { "code": null, "e": 7502, "s": 7468, "text": "Convert Double to Integer in Java" }, { "code": null, "e": 7549, "s": 7502, "text": "Implementing a Linked List in Java using Class" }, { "code": null, "e": 7584, "s": 7549, "text": "Traverse Through a HashMap in Java" } ]
Java program to calculate the percentage
Percent means percent (hundreds), i.e., a ratio of the parts out of 100. The symbol of a percent is %. We generally count the percentage of marks obtained, return on investment etc. The percentage can go beyond 100% also. For Example, assuming that we have total and a part. So we say what part is what percent of total and should be calculated as − percentage = ( part / total ) × 100 1. Collect values for part and total 2. Apply formula { percentage = ( part / total ) × 100 } 3. Display percentage import java.util.Scanner; public class Percentage { public static void main(String args[]){ float percentage; float total_marks; float scored; Scanner sc = new Scanner(System.in); System.out.println("Enter your marks ::"); scored = sc.nextFloat(); System.out.println("Enter total marks ::"); total_marks = sc.nextFloat(); percentage = (float)((scored / total_marks) * 100); System.out.println("Percentage ::"+ percentage); } } Enter your marks :: 500 Enter total marks :: 600 Percentage ::83.33333
[ { "code": null, "e": 1409, "s": 1187, "text": "Percent means percent (hundreds), i.e., a ratio of the parts out of 100. The symbol of a percent is %. We generally count the percentage of marks obtained, return on investment etc. The percentage can go beyond 100% also." }, { "code": null, "e": 1537, "s": 1409, "text": "For Example, assuming that we have total and a part. So we say what part is what percent of total and should be calculated as −" }, { "code": null, "e": 1573, "s": 1537, "text": "percentage = ( part / total ) × 100" }, { "code": null, "e": 1689, "s": 1573, "text": "1. Collect values for part and total\n2. Apply formula { percentage = ( part / total ) × 100 }\n3. Display percentage" }, { "code": null, "e": 2184, "s": 1689, "text": "import java.util.Scanner;\npublic class Percentage {\n public static void main(String args[]){\n float percentage;\n float total_marks;\n float scored;\n Scanner sc = new Scanner(System.in);\n System.out.println(\"Enter your marks ::\");\n scored = sc.nextFloat();\n\n System.out.println(\"Enter total marks ::\");\n total_marks = sc.nextFloat();\n\n percentage = (float)((scored / total_marks) * 100);\n System.out.println(\"Percentage ::\"+ percentage);\n }\n}" }, { "code": null, "e": 2255, "s": 2184, "text": "Enter your marks ::\n500\nEnter total marks ::\n600\nPercentage ::83.33333" } ]
Check if two strings can be made equal by swapping one character among each other
23 May, 2022 Given two strings A and B of length N, the task is to check whether the two strings can be made equal by swapping any character of A with any other character of B only once.Examples: Input: A = “SEEKSFORGEEKS”, B = “GEEKSFORGEEKG” Output: Yes “SEEKSFORGEEKS” and “GEEKSFORGEEKG” can be swapped to make both the strings equal.Input: A = “GEEKSFORGEEKS”, B = “THESUPERBSITE” Output: No Approach: First omit the elements which are the same and have the same index in both the strings. Then if the new strings are of length two and both the elements in each string are the same then only the swap is possible.Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function that returns true if the string// can be made equal after one swapbool canBeEqual(string a, string b, int n){ // A and B are new a and b // after we omit the same elements vector<char> A, B; // Take only the characters which are // different in both the strings // for every pair of indices for (int i = 0; i < n; i++) { // If the current characters differ if (a[i]!= b[i]) { A.push_back(a[i]); B.push_back(b[i]); } } // The strings were already equal if (A.size() == B.size() and B.size() == 0) return true; // If the lengths of the // strings are two if (A.size() == B.size() and B.size() == 2) { // If swapping these characters // can make the strings equal if (A[0] == A[1] and B[0] == B[1]) return true; } return false;} // Driver codeint main(){ string A = "SEEKSFORGEEKS"; string B = "GEEKSFORGEEKG"; if (canBeEqual(A, B, A.size())) printf("Yes"); else printf("No");} // This code is contributed by Mohit Kumar // Java implementation of the approachimport java.util.*;class GFG{ // Function that returns true if the string// can be made equal after one swapstatic boolean canBeEqual(char []a, char []b, int n){ // A and B are new a and b // after we omit the same elements Vector<Character> A = new Vector<>(); Vector<Character> B = new Vector<>(); // Take only the characters which are // different in both the strings // for every pair of indices for (int i = 0; i < n; i++) { // If the current characters differ if (a[i] != b[i]) { A.add(a[i]); B.add(b[i]); } } // The strings were already equal if (A.size() == B.size() && B.size() == 0) return true; // If the lengths of the // strings are two if (A.size() == B.size() && B.size() == 2) { // If swapping these characters // can make the strings equal if (A.get(0) == A.get(1) && B.get(0) == B.get(1)) return true; } return false;} // Driver codepublic static void main(String[] args){ char []A = "SEEKSFORGEEKS".toCharArray(); char []B = "GEEKSFORGEEKG".toCharArray(); if (canBeEqual(A, B, A.length)) System.out.printf("Yes"); else System.out.printf("No");}} // This code is contributed by Rajput-Ji # Python3 implementation of the approach # Function that returns true if the string# can be made equal after one swapdef canBeEqual(a, b, n): # A and B are new a and b # after we omit the same elements A =[] B =[] # Take only the characters which are # different in both the strings # for every pair of indices for i in range(n): # If the current characters differ if a[i]!= b[i]: A.append(a[i]) B.append(b[i]) # The strings were already equal if len(A)== len(B)== 0: return True # If the lengths of the # strings are two if len(A)== len(B)== 2: # If swapping these characters # can make the strings equal if A[0]== A[1] and B[0]== B[1]: return True return False # Driver codeA = 'SEEKSFORGEEKS'B = 'GEEKSFORGEEKG' if (canBeEqual(A, B, len(A))): print("Yes")else: print("No") // C# implementation of the above approachusing System;using System.Collections.Generic; class GFG{ // Function that returns true if the string// can be made equal after one swapstatic Boolean canBeEqual(char []a, char []b, int n){ // A and B are new a and b // after we omit the same elements List<char> A = new List<char>(); List<char> B = new List<char>(); // Take only the characters which are // different in both the strings // for every pair of indices for (int i = 0; i < n; i++) { // If the current characters differ if (a[i] != b[i]) { A.Add(a[i]); B.Add(b[i]); } } // The strings were already equal if (A.Count == B.Count && B.Count == 0) return true; // If the lengths of the // strings are two if (A.Count == B.Count && B.Count == 2) { // If swapping these characters // can make the strings equal if (A[0] == A[1] && B[0] == B[1]) return true; } return false;} // Driver codepublic static void Main(String[] args){ char []A = "SEEKSFORGEEKS".ToCharArray(); char []B = "GEEKSFORGEEKG".ToCharArray(); if (canBeEqual(A, B, A.Length)) Console.WriteLine("Yes"); else Console.WriteLine("No");}} // This code is contributed by PrinciRaj1992 <script>// Javascript implementation of the approach // Function that returns true if the string// can be made equal after one swapfunction canBeEqual(a,b,n){ // A and B are new a and b // after we omit the same elements let A = []; let B = []; // Take only the characters which are // different in both the strings // for every pair of indices for (let i = 0; i < n; i++) { // If the current characters differ if (a[i] != b[i]) { A.push(a[i]); B.push(b[i]); } } // The strings were already equal if (A.length == B.length && B.length == 0) return true; // If the lengths of the // strings are two if (A.length == B.length && B.length == 2) { // If swapping these characters // can make the strings equal if (A[0] == A[1] && B[0] == B[1]) return true; } return false;}// Driver codelet A = "SEEKSFORGEEKS".split("");let B = "GEEKSFORGEEKG".split(""); if (canBeEqual(A, B, A.length)) document.write("Yes");else document.write("No"); // This code is contributed by unknown2108</script> Yes Time Complexity: O(N), where N is the size of the given strings. Auxiliary Space: O(N), where N is the size of the given strings. mohit kumar 29 Rajput-Ji princiraj1992 unknown2108 samim2000 Constructive Algorithms Strings Strings Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Different Methods to Reverse a String in C++ Python program to check if a string is palindrome or not Check for Balanced Brackets in an expression (well-formedness) using Stack KMP Algorithm for Pattern Searching Longest Palindromic Substring | Set 1 Length of the longest substring without repeating characters Top 50 String Coding Problems for Interviews Check whether two strings are anagram of each other Convert string to char array in C++ Reverse words in a given string
[ { "code": null, "e": 52, "s": 24, "text": "\n23 May, 2022" }, { "code": null, "e": 237, "s": 52, "text": "Given two strings A and B of length N, the task is to check whether the two strings can be made equal by swapping any character of A with any other character of B only once.Examples: " }, { "code": null, "e": 440, "s": 237, "text": "Input: A = “SEEKSFORGEEKS”, B = “GEEKSFORGEEKG” Output: Yes “SEEKSFORGEEKS” and “GEEKSFORGEEKG” can be swapped to make both the strings equal.Input: A = “GEEKSFORGEEKS”, B = “THESUPERBSITE” Output: No " }, { "code": null, "e": 716, "s": 442, "text": "Approach: First omit the elements which are the same and have the same index in both the strings. Then if the new strings are of length two and both the elements in each string are the same then only the swap is possible.Below is the implementation of the above approach: " }, { "code": null, "e": 720, "s": 716, "text": "C++" }, { "code": null, "e": 725, "s": 720, "text": "Java" }, { "code": null, "e": 733, "s": 725, "text": "Python3" }, { "code": null, "e": 736, "s": 733, "text": "C#" }, { "code": null, "e": 747, "s": 736, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function that returns true if the string// can be made equal after one swapbool canBeEqual(string a, string b, int n){ // A and B are new a and b // after we omit the same elements vector<char> A, B; // Take only the characters which are // different in both the strings // for every pair of indices for (int i = 0; i < n; i++) { // If the current characters differ if (a[i]!= b[i]) { A.push_back(a[i]); B.push_back(b[i]); } } // The strings were already equal if (A.size() == B.size() and B.size() == 0) return true; // If the lengths of the // strings are two if (A.size() == B.size() and B.size() == 2) { // If swapping these characters // can make the strings equal if (A[0] == A[1] and B[0] == B[1]) return true; } return false;} // Driver codeint main(){ string A = \"SEEKSFORGEEKS\"; string B = \"GEEKSFORGEEKG\"; if (canBeEqual(A, B, A.size())) printf(\"Yes\"); else printf(\"No\");} // This code is contributed by Mohit Kumar", "e": 1953, "s": 747, "text": null }, { "code": "// Java implementation of the approachimport java.util.*;class GFG{ // Function that returns true if the string// can be made equal after one swapstatic boolean canBeEqual(char []a, char []b, int n){ // A and B are new a and b // after we omit the same elements Vector<Character> A = new Vector<>(); Vector<Character> B = new Vector<>(); // Take only the characters which are // different in both the strings // for every pair of indices for (int i = 0; i < n; i++) { // If the current characters differ if (a[i] != b[i]) { A.add(a[i]); B.add(b[i]); } } // The strings were already equal if (A.size() == B.size() && B.size() == 0) return true; // If the lengths of the // strings are two if (A.size() == B.size() && B.size() == 2) { // If swapping these characters // can make the strings equal if (A.get(0) == A.get(1) && B.get(0) == B.get(1)) return true; } return false;} // Driver codepublic static void main(String[] args){ char []A = \"SEEKSFORGEEKS\".toCharArray(); char []B = \"GEEKSFORGEEKG\".toCharArray(); if (canBeEqual(A, B, A.length)) System.out.printf(\"Yes\"); else System.out.printf(\"No\");}} // This code is contributed by Rajput-Ji", "e": 3334, "s": 1953, "text": null }, { "code": "# Python3 implementation of the approach # Function that returns true if the string# can be made equal after one swapdef canBeEqual(a, b, n): # A and B are new a and b # after we omit the same elements A =[] B =[] # Take only the characters which are # different in both the strings # for every pair of indices for i in range(n): # If the current characters differ if a[i]!= b[i]: A.append(a[i]) B.append(b[i]) # The strings were already equal if len(A)== len(B)== 0: return True # If the lengths of the # strings are two if len(A)== len(B)== 2: # If swapping these characters # can make the strings equal if A[0]== A[1] and B[0]== B[1]: return True return False # Driver codeA = 'SEEKSFORGEEKS'B = 'GEEKSFORGEEKG' if (canBeEqual(A, B, len(A))): print(\"Yes\")else: print(\"No\")", "e": 4271, "s": 3334, "text": null }, { "code": "// C# implementation of the above approachusing System;using System.Collections.Generic; class GFG{ // Function that returns true if the string// can be made equal after one swapstatic Boolean canBeEqual(char []a, char []b, int n){ // A and B are new a and b // after we omit the same elements List<char> A = new List<char>(); List<char> B = new List<char>(); // Take only the characters which are // different in both the strings // for every pair of indices for (int i = 0; i < n; i++) { // If the current characters differ if (a[i] != b[i]) { A.Add(a[i]); B.Add(b[i]); } } // The strings were already equal if (A.Count == B.Count && B.Count == 0) return true; // If the lengths of the // strings are two if (A.Count == B.Count && B.Count == 2) { // If swapping these characters // can make the strings equal if (A[0] == A[1] && B[0] == B[1]) return true; } return false;} // Driver codepublic static void Main(String[] args){ char []A = \"SEEKSFORGEEKS\".ToCharArray(); char []B = \"GEEKSFORGEEKG\".ToCharArray(); if (canBeEqual(A, B, A.Length)) Console.WriteLine(\"Yes\"); else Console.WriteLine(\"No\");}} // This code is contributed by PrinciRaj1992", "e": 5656, "s": 4271, "text": null }, { "code": "<script>// Javascript implementation of the approach // Function that returns true if the string// can be made equal after one swapfunction canBeEqual(a,b,n){ // A and B are new a and b // after we omit the same elements let A = []; let B = []; // Take only the characters which are // different in both the strings // for every pair of indices for (let i = 0; i < n; i++) { // If the current characters differ if (a[i] != b[i]) { A.push(a[i]); B.push(b[i]); } } // The strings were already equal if (A.length == B.length && B.length == 0) return true; // If the lengths of the // strings are two if (A.length == B.length && B.length == 2) { // If swapping these characters // can make the strings equal if (A[0] == A[1] && B[0] == B[1]) return true; } return false;}// Driver codelet A = \"SEEKSFORGEEKS\".split(\"\");let B = \"GEEKSFORGEEKG\".split(\"\"); if (canBeEqual(A, B, A.length)) document.write(\"Yes\");else document.write(\"No\"); // This code is contributed by unknown2108</script>", "e": 6834, "s": 5656, "text": null }, { "code": null, "e": 6838, "s": 6834, "text": "Yes" }, { "code": null, "e": 6905, "s": 6840, "text": "Time Complexity: O(N), where N is the size of the given strings." }, { "code": null, "e": 6970, "s": 6905, "text": "Auxiliary Space: O(N), where N is the size of the given strings." }, { "code": null, "e": 6985, "s": 6970, "text": "mohit kumar 29" }, { "code": null, "e": 6995, "s": 6985, "text": "Rajput-Ji" }, { "code": null, "e": 7009, "s": 6995, "text": "princiraj1992" }, { "code": null, "e": 7021, "s": 7009, "text": "unknown2108" }, { "code": null, "e": 7031, "s": 7021, "text": "samim2000" }, { "code": null, "e": 7055, "s": 7031, "text": "Constructive Algorithms" }, { "code": null, "e": 7063, "s": 7055, "text": "Strings" }, { "code": null, "e": 7071, "s": 7063, "text": "Strings" }, { "code": null, "e": 7169, "s": 7071, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 7214, "s": 7169, "text": "Different Methods to Reverse a String in C++" }, { "code": null, "e": 7271, "s": 7214, "text": "Python program to check if a string is palindrome or not" }, { "code": null, "e": 7346, "s": 7271, "text": "Check for Balanced Brackets in an expression (well-formedness) using Stack" }, { "code": null, "e": 7382, "s": 7346, "text": "KMP Algorithm for Pattern Searching" }, { "code": null, "e": 7420, "s": 7382, "text": "Longest Palindromic Substring | Set 1" }, { "code": null, "e": 7481, "s": 7420, "text": "Length of the longest substring without repeating characters" }, { "code": null, "e": 7526, "s": 7481, "text": "Top 50 String Coding Problems for Interviews" }, { "code": null, "e": 7578, "s": 7526, "text": "Check whether two strings are anagram of each other" }, { "code": null, "e": 7614, "s": 7578, "text": "Convert string to char array in C++" } ]
Sum of GCD of all possible sequences
24 Mar, 2022 Given two numbers N and K. A sequence A1, A2, ....AN of length N can be created by placing numbers from 1 to K at each position, making a total of KN sequences. The task is to find the sum of GCD of all the sequences formed.Note: The answer can be very large, so take modulo of 109 + 7. Examples: Input: N = 3, K = 2 Output: 9 Explanation: The gcd of all the subsequences are: gcd(1, 1, 1) = 1 gcd(1, 1, 2) = 1 gcd(1, 2, 1) = 1 gcd(1, 2, 2) = 1 gcd(2, 1, 1) = 1 gcd(2, 1, 2) = 1 gcd(2, 2, 1) = 1 gcd(2, 2, 2) = 2 The sum of GCD is 1 + 1 + 1 + 1 + 1 + 1 + 1 + 2 = 9. Input: N = 3, K = 200 Output: 10813692 Naive Approach: The idea is to generate all the possible subsequences of length N recursively. The summation of GCD of all the sequences formed is the required result. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ implementation of the above approach#include <bits/stdc++.h>using namespace std; const int MOD = (int)1e9 + 7; // A recursive function that generates all// the sequence and find GCDint calculate(int pos, int g, int n, int k){ // If we reach the sequence of length N // g is the GCD of the sequence if (pos == n) { return g; } // Initialise answer to 0 int answer = 0; // Placing all possible values at this // position and recursively find the // GCD of the sequence for (int i = 1; i <= k; i++) { // Take GCD of GCD calculated uptill // now i.e. g with current element answer = (answer % MOD + calculate(pos + 1, __gcd(g, i), n, k) % MOD); // Take modulo to avoid overflow answer %= MOD; } // Return the final answer return answer;} // Function that finds the sum of GCD// of all the subsequence of N lengthint sumofGCD(int n, int k){ // Recursive function that generates // the sequence and return the GCD return calculate(0, 0, n, k);} // Driver Codeint main(){ int N = 3, K = 2; // Function Call cout << sumofGCD(N, K); return 0;} // Java implementation of the above approachclass GFG{ static int MOD = (int)1e9 + 7; // A recursive function that generates all// the sequence and find GCDstatic int calculate(int pos, int g, int n, int k){ // If we reach the sequence of length N // g is the GCD of the sequence if (pos == n) { return g; } // Initialise answer to 0 int answer = 0; // Placing all possible values at this // position and recursively find the // GCD of the sequence for (int i = 1; i <= k; i++) { // Take GCD of GCD calculated uptill // now i.e. g with current element answer = (answer % MOD + calculate(pos + 1, __gcd(g, i), n, k) % MOD); // Take modulo to astatic void overflow answer %= MOD; } // Return the final answer return answer;} // Function that finds the sum of GCD// of all the subsequence of N lengthstatic int sumofGCD(int n, int k){ // Recursive function that generates // the sequence and return the GCD return calculate(0, 0, n, k);} static int __gcd(int a, int b) { return b == 0? a:__gcd(b, a % b); }// Driver Codepublic static void main(String[] args){ int N = 3, K = 2; // Function Call System.out.print(sumofGCD(N, K));}} // This code is contributed by Rajput-Ji # Python3 implementation of the# above approachMOD = 1e9 + 7 def gcd(a, b): if (b == 0): return a else: return gcd(b, a % b) # A recursive function that generates all# the sequence and find GCDdef calculate(pos, g, n, k): # If we reach the sequence of length N # g is the GCD of the sequence if (pos == n): return g # Initialise answer to 0 answer = 0 # Placing all possible values at this # position and recursively find the # GCD of the sequence for i in range(1, k + 1): # Take GCD of GCD calculated uptill # now i.e. g with current element answer = (answer % MOD + calculate(pos + 1, gcd(g, i), n, k) % MOD) # Take modulo to avoid overflow answer %= MOD # Return the final answer return answer # Function that finds the sum of GCD# of all the subsequence of N lengthdef sumofGCD(n, k): # Recursive function that generates # the sequence and return the GCD return calculate(0, 0, n, k) # Driver code if __name__=="__main__": N = 3 K = 2 # Function Call print(sumofGCD(N, K)) # This code is contributed by rutvik_56 // C# implementation of the above approachusing System; public class GFG{ static int MOD = (int)1e9 + 7; // A recursive function that generates all// the sequence and find GCDstatic int calculate(int pos, int g, int n, int k){ // If we reach the sequence of length N // g is the GCD of the sequence if (pos == n) { return g; } // Initialise answer to 0 int answer = 0; // Placing all possible values at this // position and recursively find the // GCD of the sequence for (int i = 1; i <= k; i++) { // Take GCD of GCD calculated uptill // now i.e. g with current element answer = (answer % MOD + calculate(pos + 1, __gcd(g, i), n, k) % MOD); // Take modulo to astatic void overflow answer %= MOD; } // Return the readonly answer return answer;} // Function that finds the sum of GCD// of all the subsequence of N lengthstatic int sumofGCD(int n, int k){ // Recursive function that generates // the sequence and return the GCD return calculate(0, 0, n, k);} static int __gcd(int a, int b){ return b == 0 ? a : __gcd(b, a % b); } // Driver codepublic static void Main(String[] args){ int N = 3, K = 2; // Function call Console.Write(sumofGCD(N, K));}} // This code is contributed by 29AjayKumar <script> // Javascript implementation of the above approach var MOD = 1000000007; // A recursive function that generates all// the sequence and find GCDfunction calculate(pos, g, n, k){ // If we reach the sequence of length N // g is the GCD of the sequence if (pos == n) { return g; } // Initialise answer to 0 var answer = 0; // Placing all possible values at this // position and recursively find the // GCD of the sequence for (var i = 1; i <= k; i++) { // Take GCD of GCD calculated uptill // now i.e. g with current element answer = (answer % MOD + calculate(pos + 1, __gcd(g, i), n, k) % MOD); // Take modulo to avoid overflow answer %= MOD; } // Return the final answer return answer;} function __gcd(a, b) { return b == 0? a:__gcd(b, a % b); } // Function that finds the sum of GCD// of all the subsequence of N lengthfunction sumofGCD(n, k){ // Recursive function that generates // the sequence and return the GCD return calculate(0, 0, n, k);} // Driver Codevar N = 3, K = 2;// Function Calldocument.write( sumofGCD(N, K)); </script> 9 Time Complexity: O(NK) Auxiliary Space: O(k * log N) Efficient Approach: Since the numbers of the sequence can be from 1 to K, the gcd value of the sequence will be in the range 1 to K. Let count[i] represent the number of sequences with gcd = i. For i = 1, we have no constraints on which elements can belong to the sequence, so at each of the N places, we have K possibilities to place elements making the total sequences be KN. But the resulting sequences may have higher GCD, So subtract the over counted values: count[1] = KN - count[2] - count[3] - count[4] - .... count[K] Similarly, for i = 2, since every number must be a multiple of 2, we have K/2 possibilities at each place, making the total be (K/2)N. And Subtract all the over counted values by subtracting the sequence count with the GCD of all multiples of 2. count[2] = (K/2)N - count[4] - count[6] - count[8] - ... all multiples of 2 Similarly, follow the above steps for each gcd value to K. The summation of each GCD value(say g) with count[g] is the sum of GCD of all the sequences formed. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ implementation of the above approach#include <bits/stdc++.h>using namespace std;const int MOD = (int)1e9 + 7; // Function to find a^b in log(b)int fastexpo(int a, int b){ int res = 1; a %= MOD; while (b) { if (b & 1) res = (res * a) % MOD; a *= a; a %= MOD; b >>= 1; } return res;} // Function that finds the sum of GCD// of all the subsequence of N lengthint sumofGCD(int n, int k){ // To stores the number of sequences // with gcd i int count[k + 1] = { 0 }; // Find contribution of each gcd // to happen for (int g = k; g >= 1; g--) { // To count multiples int count_multiples = k / g; // possible sequences with // overcounting int temp; temp = fastexpo(count_multiples, n); // to avoid overflow temp %= MOD; // Find extra element which will // not form gcd = i int extra = 0; // Find overcounting for (int j = g * 2; j <= k; j += g) { extra = (extra + count[j]); extra %= MOD; } // Remove the overcounting count[g] = (temp - extra + MOD); count[g] %= MOD; } // To store the final answer int sum = 0; int add; for (int i = 1; i <= k; ++i) { add = (count[i] % MOD * i % MOD); add %= MOD; sum += add; sum %= MOD; } // Return Final answer return sum;} // Driver Codeint main(){ int N = 3, K = 2; // Function call cout << sumofGCD(N, K); return 0;} // Java implementation of the above approachclass GFG{static int MOD = (int)1e9 + 7; // Function to find a^b in log(b)static int fastexpo(int a, int b){ int res = 1; a %= MOD; while (b > 0) { if (b % 2 == 1) res = (res * a) % MOD; a *= a; a %= MOD; b >>= 1; } return res;} // Function that finds the sum of GCD// of all the subsequence of N lengthstatic int sumofGCD(int n, int k){ // To stores the number of sequences // with gcd i int []count = new int[k + 1]; // Find contribution of each gcd // to happen for (int g = k; g >= 1; g--) { // To count multiples int count_multiples = k / g; // possible sequences with // overcounting int temp; temp = fastexpo(count_multiples, n); // to astatic void overflow temp %= MOD; // Find extra element which will // not form gcd = i int extra = 0; // Find overcounting for (int j = g * 2; j <= k; j += g) { extra = (extra + count[j]); extra %= MOD; } // Remove the overcounting count[g] = (temp - extra + MOD); count[g] %= MOD; } // To store the final answer int sum = 0; int add; for (int i = 1; i <= k; ++i) { add = (count[i] % MOD * i % MOD); add %= MOD; sum += add; sum %= MOD; } // Return Final answer return sum;} // Driver Codepublic static void main(String[] args){ int N = 3, K = 2; // Function call System.out.print(sumofGCD(N, K));}} // This code is contributed by PrinciRaj1992 # Python3 implementation of the above approachMOD = (int)(1e9 + 7) # Function to find a^b in log(b)def fastexpo(a, b) : res = 1 a = a % MOD while (b > 0) : if ((b & 1) != 0) : res = (res * a) % MOD a = a * a a = a % MOD b = b >> 1 return res # Function that finds the sum of GCD# of all the subsequence of N lengthdef sumofGCD(n, k) : # To stores the number of sequences # with gcd i count = [0] * (k + 1) # Find contribution of each gcd # to happen for g in range(k, 0, -1) : # To count multiples count_multiples = k // g # possible sequences with # overcounting temp = fastexpo(count_multiples, n) # to avoid overflow temp = temp % MOD # Find extra element which will # not form gcd = i extra = 0 # Find overcounting for j in range(g * 2, k + 1, g) : extra = extra + count[j] extra = extra % MOD # Remove the overcounting count[g] = temp - extra + MOD count[g] = count[g] % MOD # To store the final answer Sum = 0 for i in range(1, k + 1) : add = count[i] % MOD * i % MOD add = add % MOD Sum = Sum + add Sum = Sum % MOD # Return Final answer return Sum # Driver codeN, K = 3, 2 # Function callprint(sumofGCD(N, K)) # This code is contributed by divyeshrabadiya07. // C# implementation of the above approachusing System; class GFG{static int MOD = (int)1e9 + 7; // Function to find a^b in log(b)static int fastexpo(int a, int b){ int res = 1; a %= MOD; while (b > 0) { if (b % 2 == 1) res = (res * a) % MOD; a *= a; a %= MOD; b >>= 1; } return res;} // Function that finds the sum of GCD// of all the subsequence of N lengthstatic int sumofGCD(int n, int k){ // To stores the number of sequences // with gcd i int []count = new int[k + 1]; // Find contribution of each gcd // to happen for (int g = k; g >= 1; g--) { // To count multiples int count_multiples = k / g; // possible sequences with // overcounting int temp; temp = fastexpo(count_multiples, n); // to astatic void overflow temp %= MOD; // Find extra element which will // not form gcd = i int extra = 0; // Find overcounting for (int j = g * 2; j <= k; j += g) { extra = (extra + count[j]); extra %= MOD; } // Remove the overcounting count[g] = (temp - extra + MOD); count[g] %= MOD; } // To store the readonly answer int sum = 0; int add; for (int i = 1; i <= k; ++i) { add = (count[i] % MOD * i % MOD); add %= MOD; sum += add; sum %= MOD; } // Return Final answer return sum;} // Driver Codepublic static void Main(String[] args){ int N = 3, K = 2; // Function call Console.Write(sumofGCD(N, K));}} // This code is contributed by Princi Singh <script> // JavaScript implementation of the above approachvar MOD = 1000000007; // Function to find a^b in log(b)function fastexpo(a, b){ var res = 1; a %= MOD; while (b) { if (b & 1) res = (res * a) % MOD; a *= a; a %= MOD; b >>= 1; } return res;} // Function that finds the sum of GCD// of all the subsequence of N lengthfunction sumofGCD( n, k){ // To stores the number of sequences // with gcd i var count = Array(k+1).fill(0); // Find contribution of each gcd // to happen for (var g = k; g >= 1; g--) { // To count multiples var count_multiples = k / g; // possible sequences with // overcounting var temp; temp = fastexpo(count_multiples, n); // to avoid overflow temp %= MOD; // Find extra element which will // not form gcd = i var extra = 0; // Find overcounting for (var j = g * 2; j <= k; j += g) { extra = (extra + count[j]); extra %= MOD; } // Remove the overcounting count[g] = (temp - extra + MOD); count[g] %= MOD; } // To store the final answer var sum = 0; var add; for (var i = 1; i <= k; ++i) { add = (count[i] % MOD * i % MOD); add %= MOD; sum += add; sum %= MOD; } // Return Final answer return sum;} // Driver Code var N = 3, K = 2; // Function calldocument.write( sumofGCD(N, K)); </script> 9 Time Complexity: O( K*log(N) + K*log(log(K)) )Auxiliary Space: O(K) princiraj1992 princi singh Rajput-Ji 29AjayKumar rutvik_56 khushboogoyal499 divyeshrabadiya07 itsok rrrtnx sagartomar9927 pankajsharmagfg rishavmahato348 simmytarika5 GCD-LCM Algorithms Combinatorial Competitive Programming Dynamic Programming Mathematical Dynamic Programming Mathematical Combinatorial Algorithms Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. What is Hashing | A Complete Tutorial Find if there is a path between two vertices in an undirected graph How to Start Learning DSA? Complete Roadmap To Learn DSA From Scratch Types of Complexity Classes | P, NP, CoNP, NP hard and NP complete Write a program to print all permutations of a given string Permutation and Combination in Python Factorial of a large number itertools.combinations() module in Python to print all possible combinations Count of subsets with sum equal to X
[ { "code": null, "e": 54, "s": 26, "text": "\n24 Mar, 2022" }, { "code": null, "e": 342, "s": 54, "text": "Given two numbers N and K. A sequence A1, A2, ....AN of length N can be created by placing numbers from 1 to K at each position, making a total of KN sequences. The task is to find the sum of GCD of all the sequences formed.Note: The answer can be very large, so take modulo of 109 + 7. " }, { "code": null, "e": 353, "s": 342, "text": "Examples: " }, { "code": null, "e": 622, "s": 353, "text": "Input: N = 3, K = 2 Output: 9 Explanation: The gcd of all the subsequences are: gcd(1, 1, 1) = 1 gcd(1, 1, 2) = 1 gcd(1, 2, 1) = 1 gcd(1, 2, 2) = 1 gcd(2, 1, 1) = 1 gcd(2, 1, 2) = 1 gcd(2, 2, 1) = 1 gcd(2, 2, 2) = 2 The sum of GCD is 1 + 1 + 1 + 1 + 1 + 1 + 1 + 2 = 9." }, { "code": null, "e": 661, "s": 622, "text": "Input: N = 3, K = 200 Output: 10813692" }, { "code": null, "e": 829, "s": 661, "text": "Naive Approach: The idea is to generate all the possible subsequences of length N recursively. The summation of GCD of all the sequences formed is the required result." }, { "code": null, "e": 880, "s": 829, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 884, "s": 880, "text": "C++" }, { "code": null, "e": 889, "s": 884, "text": "Java" }, { "code": null, "e": 897, "s": 889, "text": "Python3" }, { "code": null, "e": 900, "s": 897, "text": "C#" }, { "code": null, "e": 911, "s": 900, "text": "Javascript" }, { "code": "// C++ implementation of the above approach#include <bits/stdc++.h>using namespace std; const int MOD = (int)1e9 + 7; // A recursive function that generates all// the sequence and find GCDint calculate(int pos, int g, int n, int k){ // If we reach the sequence of length N // g is the GCD of the sequence if (pos == n) { return g; } // Initialise answer to 0 int answer = 0; // Placing all possible values at this // position and recursively find the // GCD of the sequence for (int i = 1; i <= k; i++) { // Take GCD of GCD calculated uptill // now i.e. g with current element answer = (answer % MOD + calculate(pos + 1, __gcd(g, i), n, k) % MOD); // Take modulo to avoid overflow answer %= MOD; } // Return the final answer return answer;} // Function that finds the sum of GCD// of all the subsequence of N lengthint sumofGCD(int n, int k){ // Recursive function that generates // the sequence and return the GCD return calculate(0, 0, n, k);} // Driver Codeint main(){ int N = 3, K = 2; // Function Call cout << sumofGCD(N, K); return 0;}", "e": 2080, "s": 911, "text": null }, { "code": "// Java implementation of the above approachclass GFG{ static int MOD = (int)1e9 + 7; // A recursive function that generates all// the sequence and find GCDstatic int calculate(int pos, int g, int n, int k){ // If we reach the sequence of length N // g is the GCD of the sequence if (pos == n) { return g; } // Initialise answer to 0 int answer = 0; // Placing all possible values at this // position and recursively find the // GCD of the sequence for (int i = 1; i <= k; i++) { // Take GCD of GCD calculated uptill // now i.e. g with current element answer = (answer % MOD + calculate(pos + 1, __gcd(g, i), n, k) % MOD); // Take modulo to astatic void overflow answer %= MOD; } // Return the final answer return answer;} // Function that finds the sum of GCD// of all the subsequence of N lengthstatic int sumofGCD(int n, int k){ // Recursive function that generates // the sequence and return the GCD return calculate(0, 0, n, k);} static int __gcd(int a, int b) { return b == 0? a:__gcd(b, a % b); }// Driver Codepublic static void main(String[] args){ int N = 3, K = 2; // Function Call System.out.print(sumofGCD(N, K));}} // This code is contributed by Rajput-Ji", "e": 3391, "s": 2080, "text": null }, { "code": "# Python3 implementation of the# above approachMOD = 1e9 + 7 def gcd(a, b): if (b == 0): return a else: return gcd(b, a % b) # A recursive function that generates all# the sequence and find GCDdef calculate(pos, g, n, k): # If we reach the sequence of length N # g is the GCD of the sequence if (pos == n): return g # Initialise answer to 0 answer = 0 # Placing all possible values at this # position and recursively find the # GCD of the sequence for i in range(1, k + 1): # Take GCD of GCD calculated uptill # now i.e. g with current element answer = (answer % MOD + calculate(pos + 1, gcd(g, i), n, k) % MOD) # Take modulo to avoid overflow answer %= MOD # Return the final answer return answer # Function that finds the sum of GCD# of all the subsequence of N lengthdef sumofGCD(n, k): # Recursive function that generates # the sequence and return the GCD return calculate(0, 0, n, k) # Driver code if __name__==\"__main__\": N = 3 K = 2 # Function Call print(sumofGCD(N, K)) # This code is contributed by rutvik_56", "e": 4601, "s": 3391, "text": null }, { "code": "// C# implementation of the above approachusing System; public class GFG{ static int MOD = (int)1e9 + 7; // A recursive function that generates all// the sequence and find GCDstatic int calculate(int pos, int g, int n, int k){ // If we reach the sequence of length N // g is the GCD of the sequence if (pos == n) { return g; } // Initialise answer to 0 int answer = 0; // Placing all possible values at this // position and recursively find the // GCD of the sequence for (int i = 1; i <= k; i++) { // Take GCD of GCD calculated uptill // now i.e. g with current element answer = (answer % MOD + calculate(pos + 1, __gcd(g, i), n, k) % MOD); // Take modulo to astatic void overflow answer %= MOD; } // Return the readonly answer return answer;} // Function that finds the sum of GCD// of all the subsequence of N lengthstatic int sumofGCD(int n, int k){ // Recursive function that generates // the sequence and return the GCD return calculate(0, 0, n, k);} static int __gcd(int a, int b){ return b == 0 ? a : __gcd(b, a % b); } // Driver codepublic static void Main(String[] args){ int N = 3, K = 2; // Function call Console.Write(sumofGCD(N, K));}} // This code is contributed by 29AjayKumar", "e": 5928, "s": 4601, "text": null }, { "code": "<script> // Javascript implementation of the above approach var MOD = 1000000007; // A recursive function that generates all// the sequence and find GCDfunction calculate(pos, g, n, k){ // If we reach the sequence of length N // g is the GCD of the sequence if (pos == n) { return g; } // Initialise answer to 0 var answer = 0; // Placing all possible values at this // position and recursively find the // GCD of the sequence for (var i = 1; i <= k; i++) { // Take GCD of GCD calculated uptill // now i.e. g with current element answer = (answer % MOD + calculate(pos + 1, __gcd(g, i), n, k) % MOD); // Take modulo to avoid overflow answer %= MOD; } // Return the final answer return answer;} function __gcd(a, b) { return b == 0? a:__gcd(b, a % b); } // Function that finds the sum of GCD// of all the subsequence of N lengthfunction sumofGCD(n, k){ // Recursive function that generates // the sequence and return the GCD return calculate(0, 0, n, k);} // Driver Codevar N = 3, K = 2;// Function Calldocument.write( sumofGCD(N, K)); </script>", "e": 7096, "s": 5928, "text": null }, { "code": null, "e": 7098, "s": 7096, "text": "9" }, { "code": null, "e": 7123, "s": 7100, "text": "Time Complexity: O(NK)" }, { "code": null, "e": 7153, "s": 7123, "text": "Auxiliary Space: O(k * log N)" }, { "code": null, "e": 7174, "s": 7153, "text": "Efficient Approach: " }, { "code": null, "e": 7287, "s": 7174, "text": "Since the numbers of the sequence can be from 1 to K, the gcd value of the sequence will be in the range 1 to K." }, { "code": null, "e": 7618, "s": 7287, "text": "Let count[i] represent the number of sequences with gcd = i. For i = 1, we have no constraints on which elements can belong to the sequence, so at each of the N places, we have K possibilities to place elements making the total sequences be KN. But the resulting sequences may have higher GCD, So subtract the over counted values:" }, { "code": null, "e": 7681, "s": 7618, "text": "count[1] = KN - count[2] - count[3] - count[4] - .... count[K]" }, { "code": null, "e": 7927, "s": 7681, "text": "Similarly, for i = 2, since every number must be a multiple of 2, we have K/2 possibilities at each place, making the total be (K/2)N. And Subtract all the over counted values by subtracting the sequence count with the GCD of all multiples of 2." }, { "code": null, "e": 8003, "s": 7927, "text": "count[2] = (K/2)N - count[4] - count[6] - count[8] - ... all multiples of 2" }, { "code": null, "e": 8062, "s": 8003, "text": "Similarly, follow the above steps for each gcd value to K." }, { "code": null, "e": 8162, "s": 8062, "text": "The summation of each GCD value(say g) with count[g] is the sum of GCD of all the sequences formed." }, { "code": null, "e": 8213, "s": 8162, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 8217, "s": 8213, "text": "C++" }, { "code": null, "e": 8222, "s": 8217, "text": "Java" }, { "code": null, "e": 8230, "s": 8222, "text": "Python3" }, { "code": null, "e": 8233, "s": 8230, "text": "C#" }, { "code": null, "e": 8244, "s": 8233, "text": "Javascript" }, { "code": "// C++ implementation of the above approach#include <bits/stdc++.h>using namespace std;const int MOD = (int)1e9 + 7; // Function to find a^b in log(b)int fastexpo(int a, int b){ int res = 1; a %= MOD; while (b) { if (b & 1) res = (res * a) % MOD; a *= a; a %= MOD; b >>= 1; } return res;} // Function that finds the sum of GCD// of all the subsequence of N lengthint sumofGCD(int n, int k){ // To stores the number of sequences // with gcd i int count[k + 1] = { 0 }; // Find contribution of each gcd // to happen for (int g = k; g >= 1; g--) { // To count multiples int count_multiples = k / g; // possible sequences with // overcounting int temp; temp = fastexpo(count_multiples, n); // to avoid overflow temp %= MOD; // Find extra element which will // not form gcd = i int extra = 0; // Find overcounting for (int j = g * 2; j <= k; j += g) { extra = (extra + count[j]); extra %= MOD; } // Remove the overcounting count[g] = (temp - extra + MOD); count[g] %= MOD; } // To store the final answer int sum = 0; int add; for (int i = 1; i <= k; ++i) { add = (count[i] % MOD * i % MOD); add %= MOD; sum += add; sum %= MOD; } // Return Final answer return sum;} // Driver Codeint main(){ int N = 3, K = 2; // Function call cout << sumofGCD(N, K); return 0;}", "e": 9794, "s": 8244, "text": null }, { "code": "// Java implementation of the above approachclass GFG{static int MOD = (int)1e9 + 7; // Function to find a^b in log(b)static int fastexpo(int a, int b){ int res = 1; a %= MOD; while (b > 0) { if (b % 2 == 1) res = (res * a) % MOD; a *= a; a %= MOD; b >>= 1; } return res;} // Function that finds the sum of GCD// of all the subsequence of N lengthstatic int sumofGCD(int n, int k){ // To stores the number of sequences // with gcd i int []count = new int[k + 1]; // Find contribution of each gcd // to happen for (int g = k; g >= 1; g--) { // To count multiples int count_multiples = k / g; // possible sequences with // overcounting int temp; temp = fastexpo(count_multiples, n); // to astatic void overflow temp %= MOD; // Find extra element which will // not form gcd = i int extra = 0; // Find overcounting for (int j = g * 2; j <= k; j += g) { extra = (extra + count[j]); extra %= MOD; } // Remove the overcounting count[g] = (temp - extra + MOD); count[g] %= MOD; } // To store the final answer int sum = 0; int add; for (int i = 1; i <= k; ++i) { add = (count[i] % MOD * i % MOD); add %= MOD; sum += add; sum %= MOD; } // Return Final answer return sum;} // Driver Codepublic static void main(String[] args){ int N = 3, K = 2; // Function call System.out.print(sumofGCD(N, K));}} // This code is contributed by PrinciRaj1992", "e": 11437, "s": 9794, "text": null }, { "code": "# Python3 implementation of the above approachMOD = (int)(1e9 + 7) # Function to find a^b in log(b)def fastexpo(a, b) : res = 1 a = a % MOD while (b > 0) : if ((b & 1) != 0) : res = (res * a) % MOD a = a * a a = a % MOD b = b >> 1 return res # Function that finds the sum of GCD# of all the subsequence of N lengthdef sumofGCD(n, k) : # To stores the number of sequences # with gcd i count = [0] * (k + 1) # Find contribution of each gcd # to happen for g in range(k, 0, -1) : # To count multiples count_multiples = k // g # possible sequences with # overcounting temp = fastexpo(count_multiples, n) # to avoid overflow temp = temp % MOD # Find extra element which will # not form gcd = i extra = 0 # Find overcounting for j in range(g * 2, k + 1, g) : extra = extra + count[j] extra = extra % MOD # Remove the overcounting count[g] = temp - extra + MOD count[g] = count[g] % MOD # To store the final answer Sum = 0 for i in range(1, k + 1) : add = count[i] % MOD * i % MOD add = add % MOD Sum = Sum + add Sum = Sum % MOD # Return Final answer return Sum # Driver codeN, K = 3, 2 # Function callprint(sumofGCD(N, K)) # This code is contributed by divyeshrabadiya07.", "e": 12858, "s": 11437, "text": null }, { "code": "// C# implementation of the above approachusing System; class GFG{static int MOD = (int)1e9 + 7; // Function to find a^b in log(b)static int fastexpo(int a, int b){ int res = 1; a %= MOD; while (b > 0) { if (b % 2 == 1) res = (res * a) % MOD; a *= a; a %= MOD; b >>= 1; } return res;} // Function that finds the sum of GCD// of all the subsequence of N lengthstatic int sumofGCD(int n, int k){ // To stores the number of sequences // with gcd i int []count = new int[k + 1]; // Find contribution of each gcd // to happen for (int g = k; g >= 1; g--) { // To count multiples int count_multiples = k / g; // possible sequences with // overcounting int temp; temp = fastexpo(count_multiples, n); // to astatic void overflow temp %= MOD; // Find extra element which will // not form gcd = i int extra = 0; // Find overcounting for (int j = g * 2; j <= k; j += g) { extra = (extra + count[j]); extra %= MOD; } // Remove the overcounting count[g] = (temp - extra + MOD); count[g] %= MOD; } // To store the readonly answer int sum = 0; int add; for (int i = 1; i <= k; ++i) { add = (count[i] % MOD * i % MOD); add %= MOD; sum += add; sum %= MOD; } // Return Final answer return sum;} // Driver Codepublic static void Main(String[] args){ int N = 3, K = 2; // Function call Console.Write(sumofGCD(N, K));}} // This code is contributed by Princi Singh", "e": 14532, "s": 12858, "text": null }, { "code": "<script> // JavaScript implementation of the above approachvar MOD = 1000000007; // Function to find a^b in log(b)function fastexpo(a, b){ var res = 1; a %= MOD; while (b) { if (b & 1) res = (res * a) % MOD; a *= a; a %= MOD; b >>= 1; } return res;} // Function that finds the sum of GCD// of all the subsequence of N lengthfunction sumofGCD( n, k){ // To stores the number of sequences // with gcd i var count = Array(k+1).fill(0); // Find contribution of each gcd // to happen for (var g = k; g >= 1; g--) { // To count multiples var count_multiples = k / g; // possible sequences with // overcounting var temp; temp = fastexpo(count_multiples, n); // to avoid overflow temp %= MOD; // Find extra element which will // not form gcd = i var extra = 0; // Find overcounting for (var j = g * 2; j <= k; j += g) { extra = (extra + count[j]); extra %= MOD; } // Remove the overcounting count[g] = (temp - extra + MOD); count[g] %= MOD; } // To store the final answer var sum = 0; var add; for (var i = 1; i <= k; ++i) { add = (count[i] % MOD * i % MOD); add %= MOD; sum += add; sum %= MOD; } // Return Final answer return sum;} // Driver Code var N = 3, K = 2; // Function calldocument.write( sumofGCD(N, K)); </script>", "e": 16032, "s": 14532, "text": null }, { "code": null, "e": 16034, "s": 16032, "text": "9" }, { "code": null, "e": 16104, "s": 16036, "text": "Time Complexity: O( K*log(N) + K*log(log(K)) )Auxiliary Space: O(K)" }, { "code": null, "e": 16118, "s": 16104, "text": "princiraj1992" }, { "code": null, "e": 16131, "s": 16118, "text": "princi singh" }, { "code": null, "e": 16141, "s": 16131, "text": "Rajput-Ji" }, { "code": null, "e": 16153, "s": 16141, "text": "29AjayKumar" }, { "code": null, "e": 16163, "s": 16153, "text": "rutvik_56" }, { "code": null, "e": 16180, "s": 16163, "text": "khushboogoyal499" }, { "code": null, "e": 16198, "s": 16180, "text": "divyeshrabadiya07" }, { "code": null, "e": 16204, "s": 16198, "text": "itsok" }, { "code": null, "e": 16211, "s": 16204, "text": "rrrtnx" }, { "code": null, "e": 16226, "s": 16211, "text": "sagartomar9927" }, { "code": null, "e": 16242, "s": 16226, "text": "pankajsharmagfg" }, { "code": null, "e": 16258, "s": 16242, "text": "rishavmahato348" }, { "code": null, "e": 16271, "s": 16258, "text": "simmytarika5" }, { "code": null, "e": 16279, "s": 16271, "text": "GCD-LCM" }, { "code": null, "e": 16290, "s": 16279, "text": "Algorithms" }, { "code": null, "e": 16304, "s": 16290, "text": "Combinatorial" }, { "code": null, "e": 16328, "s": 16304, "text": "Competitive Programming" }, { "code": null, "e": 16348, "s": 16328, "text": "Dynamic Programming" }, { "code": null, "e": 16361, "s": 16348, "text": "Mathematical" }, { "code": null, "e": 16381, "s": 16361, "text": "Dynamic Programming" }, { "code": null, "e": 16394, "s": 16381, "text": "Mathematical" }, { "code": null, "e": 16408, "s": 16394, "text": "Combinatorial" }, { "code": null, "e": 16419, "s": 16408, "text": "Algorithms" }, { "code": null, "e": 16517, "s": 16419, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 16555, "s": 16517, "text": "What is Hashing | A Complete Tutorial" }, { "code": null, "e": 16623, "s": 16555, "text": "Find if there is a path between two vertices in an undirected graph" }, { "code": null, "e": 16650, "s": 16623, "text": "How to Start Learning DSA?" }, { "code": null, "e": 16693, "s": 16650, "text": "Complete Roadmap To Learn DSA From Scratch" }, { "code": null, "e": 16760, "s": 16693, "text": "Types of Complexity Classes | P, NP, CoNP, NP hard and NP complete" }, { "code": null, "e": 16820, "s": 16760, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 16858, "s": 16820, "text": "Permutation and Combination in Python" }, { "code": null, "e": 16886, "s": 16858, "text": "Factorial of a large number" }, { "code": null, "e": 16963, "s": 16886, "text": "itertools.combinations() module in Python to print all possible combinations" } ]
How to Extract YouTube Comments Using Youtube API - Python - GeeksforGeeks
26 Dec, 2020 Prerequisite: YouTube API Google provides a large set of API’s for the developer to choose from. Each and every service provided by Google has an associated API. Being on of them, YouTube Data API is very simple to use provides features like – Search for videos Handle videos like retrieve information about a video, insert a video, delete a video etc. Handle Subscriptions like lists all the subscriptions, insert or delete a subscription etc. In this article, we will discuss How to Extract YouTube Comments and reply using Google YouTube API in Python. Understand step by step implementation:- Retrieve YouTube Video ResultsHere we will use commentThreads, list, execute method, it will give the list of comment and repliesInside list method, pass snippet and replies in part property and in videoId property pass video id of video URL Here we will use commentThreads, list, execute method, it will give the list of comment and replies Inside list method, pass snippet and replies in part property and in videoId property pass video id of video URL Python3 # creating youtube resource objectyoutube = build('youtube','v3', developerKey="Enter API Key") # retrieve youtube video resultsvideo_response=youtube.commentThreads().list( part='snippet,replies', videoId="Enter Video ID").execute() Iterate through each Video Response and fetch comments and repliesThe data comes in dictionary format, each comment data has reply count number, if reply count number is zero means no reply on that commentif count is greater than zero then we are iterating each reply and get text.nextPageToken contain the next data, here we are checking if nextPageToken has no value it means value is None, loop end, else loop will continue. The data comes in dictionary format, each comment data has reply count number, if reply count number is zero means no reply on that comment if count is greater than zero then we are iterating each reply and get text. nextPageToken contain the next data, here we are checking if nextPageToken has no value it means value is None, loop end, else loop will continue. Below is the full implementation: Python3 from googleapiclient.discovery import build api_key = 'API KEY' def video_comments(video_id): # empty list for storing reply replies = [] # creating youtube resource object youtube = build('youtube', 'v3', developerKey=api_key) # retrieve youtube video results video_response=youtube.commentThreads().list( part='snippet,replies', videoId=video_id ).execute() # iterate video response while video_response: # extracting required info # from each result object for item in video_response['items']: # Extracting comments comment = item['snippet']['topLevelComment']['snippet']['textDisplay'] # counting number of reply of comment replycount = item['snippet']['totalReplyCount'] # if reply is there if replycount>0: # iterate through all reply for reply in item['replies']['comments']: # Extract reply reply = reply['snippet']['textDisplay'] # Store reply is list replies.append(reply) # print comment with list of reply print(comment, replies, end = '\n\n') # empty reply list replies = [] # Again repeat if 'nextPageToken' in video_response: video_response = youtube.commentThreads().list( part = 'snippet,replies', videoId = video_id ).execute() else: break # Enter video idvideo_id = "Enter Video ID" # Call functionvideo_comments(video_id) Output: Let’s verify the results: 3 Comments and 2 Replies Picked python-utility Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? How to drop one or multiple columns in Pandas Dataframe Python Classes and Objects Python | os.path.join() method Python | Pandas dataframe.groupby() Create a directory in Python Defaultdict in Python Python | Get unique values from a list
[ { "code": null, "e": 25647, "s": 25619, "text": "\n26 Dec, 2020" }, { "code": null, "e": 25673, "s": 25647, "text": "Prerequisite: YouTube API" }, { "code": null, "e": 25891, "s": 25673, "text": "Google provides a large set of API’s for the developer to choose from. Each and every service provided by Google has an associated API. Being on of them, YouTube Data API is very simple to use provides features like –" }, { "code": null, "e": 25909, "s": 25891, "text": "Search for videos" }, { "code": null, "e": 26000, "s": 25909, "text": "Handle videos like retrieve information about a video, insert a video, delete a video etc." }, { "code": null, "e": 26092, "s": 26000, "text": "Handle Subscriptions like lists all the subscriptions, insert or delete a subscription etc." }, { "code": null, "e": 26203, "s": 26092, "text": "In this article, we will discuss How to Extract YouTube Comments and reply using Google YouTube API in Python." }, { "code": null, "e": 26244, "s": 26203, "text": "Understand step by step implementation:-" }, { "code": null, "e": 26486, "s": 26244, "text": "Retrieve YouTube Video ResultsHere we will use commentThreads, list, execute method, it will give the list of comment and repliesInside list method, pass snippet and replies in part property and in videoId property pass video id of video URL" }, { "code": null, "e": 26586, "s": 26486, "text": "Here we will use commentThreads, list, execute method, it will give the list of comment and replies" }, { "code": null, "e": 26699, "s": 26586, "text": "Inside list method, pass snippet and replies in part property and in videoId property pass video id of video URL" }, { "code": null, "e": 26707, "s": 26699, "text": "Python3" }, { "code": "# creating youtube resource objectyoutube = build('youtube','v3', developerKey=\"Enter API Key\") # retrieve youtube video resultsvideo_response=youtube.commentThreads().list( part='snippet,replies', videoId=\"Enter Video ID\").execute()", "e": 26959, "s": 26707, "text": null }, { "code": null, "e": 27387, "s": 26959, "text": "Iterate through each Video Response and fetch comments and repliesThe data comes in dictionary format, each comment data has reply count number, if reply count number is zero means no reply on that commentif count is greater than zero then we are iterating each reply and get text.nextPageToken contain the next data, here we are checking if nextPageToken has no value it means value is None, loop end, else loop will continue." }, { "code": null, "e": 27527, "s": 27387, "text": "The data comes in dictionary format, each comment data has reply count number, if reply count number is zero means no reply on that comment" }, { "code": null, "e": 27604, "s": 27527, "text": "if count is greater than zero then we are iterating each reply and get text." }, { "code": null, "e": 27751, "s": 27604, "text": "nextPageToken contain the next data, here we are checking if nextPageToken has no value it means value is None, loop end, else loop will continue." }, { "code": null, "e": 27785, "s": 27751, "text": "Below is the full implementation:" }, { "code": null, "e": 27793, "s": 27785, "text": "Python3" }, { "code": "from googleapiclient.discovery import build api_key = 'API KEY' def video_comments(video_id): # empty list for storing reply replies = [] # creating youtube resource object youtube = build('youtube', 'v3', developerKey=api_key) # retrieve youtube video results video_response=youtube.commentThreads().list( part='snippet,replies', videoId=video_id ).execute() # iterate video response while video_response: # extracting required info # from each result object for item in video_response['items']: # Extracting comments comment = item['snippet']['topLevelComment']['snippet']['textDisplay'] # counting number of reply of comment replycount = item['snippet']['totalReplyCount'] # if reply is there if replycount>0: # iterate through all reply for reply in item['replies']['comments']: # Extract reply reply = reply['snippet']['textDisplay'] # Store reply is list replies.append(reply) # print comment with list of reply print(comment, replies, end = '\\n\\n') # empty reply list replies = [] # Again repeat if 'nextPageToken' in video_response: video_response = youtube.commentThreads().list( part = 'snippet,replies', videoId = video_id ).execute() else: break # Enter video idvideo_id = \"Enter Video ID\" # Call functionvideo_comments(video_id)", "e": 29531, "s": 27793, "text": null }, { "code": null, "e": 29539, "s": 29531, "text": "Output:" }, { "code": null, "e": 29565, "s": 29539, "text": "Let’s verify the results:" }, { "code": null, "e": 29590, "s": 29565, "text": "3 Comments and 2 Replies" }, { "code": null, "e": 29597, "s": 29590, "text": "Picked" }, { "code": null, "e": 29612, "s": 29597, "text": "python-utility" }, { "code": null, "e": 29619, "s": 29612, "text": "Python" }, { "code": null, "e": 29717, "s": 29619, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29749, "s": 29717, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 29791, "s": 29749, "text": "Check if element exists in list in Python" }, { "code": null, "e": 29833, "s": 29791, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 29889, "s": 29833, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 29916, "s": 29889, "text": "Python Classes and Objects" }, { "code": null, "e": 29947, "s": 29916, "text": "Python | os.path.join() method" }, { "code": null, "e": 29983, "s": 29947, "text": "Python | Pandas dataframe.groupby()" }, { "code": null, "e": 30012, "s": 29983, "text": "Create a directory in Python" }, { "code": null, "e": 30034, "s": 30012, "text": "Defaultdict in Python" } ]
Queries to update array elements in a range [L, R] to satisfy given conditions - GeeksforGeeks
02 Dec, 2021 Given an array arr[] consisting of N 0s and an array Q[][] with each row of the form (L, R)., the task for each query is to update all the array elements in the range [L, R] such that arr[i] = i – L + 1. Examples: Input: arr[] = { 0, 0, 0, 0 }, Q[][] = { { 1, 2 }, { 0, 1 } } Output: 1 3 2 0 Explanation: Query1: Updating arr[1] = 1 – 1 + 1, arr[2] = 2 – 1 + 1 modifies arr[] to { 0, 1, 2, 0 } Query2: Updating arr[0] = 0 – 0 + 1, arr[1] = 1 – 0 + 1 modifies arr[] to { 1, 3, 2, 0 } Therefore, the required output is 1 3 2 0. Input: arr[] = { 0, 0, 0, 0 }, Q[][] = { { 1, 3 }, { 0, 1 } }Output: 1 3 2 3 Naive Approach:The simplest approach to solve the problem is to traverse the array Q[][] and for each query, traverse all the array elements in the given range and update arr[i] += i – L + 1. Finally, print the array elements. Time Complexity: O(N * Q)Auxiliary Space: O(1) Efficient Approach: The above approach can be optimized using the concept of Difference Array. Follow the steps below to solve the problem: Initialize two arrays arr1[] and arr2[] and initialize all elements as 0. Traverse the query array, Q[][]. For each query of type (L, R) update arr1[L] += 1, arr1[R + 1] -= 1 and arr2[R + 1] -= R – L + 1. Traverse the array, arr1[] and store the prefix sum of arr1[], i.e. arr1[i] += arr1[i -1]. Traverse the array, arr2[] and update arr2[i] += arr2[i – 1] + arr1[i]. Finally, print the array, arr2[]. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program to implement// the above approach#include <bits/stdc++.h>using namespace std; // Function to print the arrayvoid printArray(int arr[], int N){ for (int i = 0; i < N; i++) { cout << arr[i] << " "; }} // Function to perform the query in range [L, R]// such that arr[i] += i - L + 1void modifyArray(int arr[], int N, int Q[][2], int cntQuery){ // Initialize array int arr1[N + 1] = { 0 }; int arr2[N + 1] = { 0 }; // Traverse the query array for (int i = 0; i < cntQuery; i++) { // Stores range in 1-based index int L = Q[i][0] + 1, R = Q[i][1] + 1; // Update arr1[L] arr1[L]++; // Update arr1[R + 1] arr1[R + 1]--; // Update arr2[R + 1] arr2[R + 1] -= R - L + 1; } // Calculate prefix sum for (int i = 1; i <= N; i++) arr1[i] += arr1[i - 1]; // Traverse the array, arr2[] for (int i = 1; i <= N; i++) arr2[i] += arr2[i - 1] + arr1[i]; // Copy arr2[] into arr[] for (int i = 1; i <= N; i++) arr[i - 1] = arr2[i]; printArray(arr, N);} // Driver Codeint main(){ // Given array int arr[] = { 0, 0, 0, 0 }; // Size of the array int N = sizeof(arr) / sizeof(arr[0]); int Q[][2] = { { 1, 3 }, { 0, 1 } }; // Stores count of query int cntQuery = sizeof(Q) / sizeof(Q[0]); // Function Call modifyArray(arr, N, Q, cntQuery); return 0;} // Java program to implement// the above approachclass GFG{ // Function to print the array static void printArray(int arr[], int N) { for (int i = 0; i < N; i++) { System.out.print(arr[i] + " "); } } // Function to perform the query in range [L, R] // such that arr[i] += i - L + 1 static void modifyArray(int arr[], int N, int Q[][], int cntQuery) { // Initialize array int arr1[] = new int[N + 2]; int arr2[] = new int[N + 2]; // Traverse the query array for (int i = 0; i < cntQuery; i++) { // Stores range in 1-based index int L = Q[i][0] + 1, R = Q[i][1] + 1; // Update arr1[L] arr1[L]++; // Update arr1[R + 1] arr1[R + 1]--; // Update arr2[R + 1] arr2[R + 1] -= R - L + 1; } // Calculate prefix sum for (int i = 1; i <= N; i++) arr1[i] += arr1[i - 1]; // Traverse the array, arr2[] for (int i = 1; i <= N; i++) arr2[i] += arr2[i - 1] + arr1[i]; // Copy arr2[] into arr[] for (int i = 1; i <= N; i++) arr[i - 1] = arr2[i]; printArray(arr, N); } // Driver Code public static void main (String[] args) { // Given array int arr[] = { 0, 0, 0, 0 }; // Size of the array int N = arr.length; int Q[][] = { { 1, 3 }, { 0, 1 } }; // Stores count of query int cntQuery = Q.length; // Function Call modifyArray(arr, N, Q, cntQuery); }} // This code is contributed by AnkThon # Python3 program to implement# the above approach # Function to print arraydef printArray(arr, N): print(*arr) # Function to perform the query in range [L, R]# such that arr[i] += i - L + 1def modifyArray(arr, N, Q, cntQuery): # Initialize array arr1 = [0 for i in range(N + 2)] arr2 = [0 for i in range(N + 2)] # Traverse the query array for i in range(cntQuery): # Stores range in 1-based index L = Q[i][0] + 1 R = Q[i][1] + 1 # print(L,R) # Update arr1[L] arr1[L] += 1 # Update arr1[R + 1] arr1[R + 1] -= 1 # Update arr2[R + 1] arr2[R + 1] -= R - L + 1 # Calculate prefix sum for i in range(1, N + 1): arr1[i] += arr1[i - 1] # Traverse the array, arr2[] for i in range(1, N + 1): arr2[i] += arr2[i - 1] + arr1[i] # Copy arr2[] into arr[] for i in range(1, N + 1): arr[i - 1] = arr2[i] printArray(arr, N) # Driver Codeif __name__ == '__main__': # Given array arr = [0, 0, 0, 0] # Size of the array N = len(arr) Q = [[ 1, 3 ], [ 0, 1 ]] # Stores count of query cntQuery = len(Q) # Function Call modifyArray(arr, N, Q, cntQuery) # This code is contributed by mohit kumar 29. // C# program to implement// the above approachusing System;class GFG{ // Function to print the array static void printArray(int []arr, int N) { for (int i = 0; i < N; i++) { Console.Write(arr[i] + " "); } } // Function to perform the query in range [L, R] // such that arr[i] += i - L + 1 static void modifyArray(int []arr, int N, int[,] Q, int cntQuery) { // Initialize array int []arr1 = new int[N + 2]; int []arr2 = new int[N + 2]; // Traverse the query array for (int i = 0; i < cntQuery; i++) { // Stores range in 1-based index int L = Q[i,0] + 1, R = Q[i,1] + 1; // Update arr1[L] arr1[L]++; // Update arr1[R + 1] arr1[R + 1]--; // Update arr2[R + 1] arr2[R + 1] -= R - L + 1; } // Calculate prefix sum for (int i = 1; i <= N; i++) arr1[i] += arr1[i - 1]; // Traverse the array, arr2[] for (int i = 1; i <= N; i++) arr2[i] += arr2[i - 1] + arr1[i]; // Copy arr2[] into arr[] for (int i = 1; i <= N; i++) arr[i - 1] = arr2[i]; printArray(arr, N); } // Driver Code public static void Main() { // Given array int []arr = { 0, 0, 0, 0 }; // Size of the array int N = arr.Length; int [,]Q = { { 1, 3 }, { 0, 1 } }; // Stores count of query int cntQuery = 2; // Function Call modifyArray(arr, N, Q, cntQuery); }} // This code is contributed by bgangwar59. <script> // Javascript program to implement// the above approach // Function to print the arrayfunction printArray(arr, N){ for(let i = 0; i < N; i++) { document.write(arr[i] + " "); }} // Function to perform the query in// range [L, R] such that// arr[i] += i - L + 1function modifyArray(arr, N, Q, cntQuery){ // Initialize array let arr1 = new Array(N + 2).fill(0); let arr2 = new Array(N + 2).fill(0); // Traverse the query array for(let i = 0; i < cntQuery; i++) { // Stores range in 1-based index let L = Q[i][0] + 1, R = Q[i][1] + 1; // Update arr1[L] arr1[L]++; // Update arr1[R + 1] arr1[R + 1]--; // Update arr2[R + 1] arr2[R + 1] -= R - L + 1; } // Calculate prefix sum for(let i = 1; i <= N; i++) arr1[i] += arr1[i - 1]; // Traverse the array, arr2[] for(let i = 1; i <= N; i++) arr2[i] += arr2[i - 1] + arr1[i]; // Copy arr2[] into arr[] for(let i = 1; i <= N; i++) arr[i - 1] = arr2[i]; prletArray(arr, N);} // Driver Code // Given arraylet arr = [ 0, 0, 0, 0 ]; // Size of the arraylet N = arr.length; let Q = [ [ 1, 3 ], [ 0, 1 ] ]; // Stores count of querylet cntQuery = Q.length; // Function CallmodifyArray(arr, N, Q, cntQuery); // This code is contributed by avijitmondal1998 </script> 1 3 2 3 Time Complexity: O(N+Q)Auxiliary Space: O(N) mohit kumar 29 ankthon bgangwar59 avijitmondal1998 sumitgumber28 gulshankumarar231 khushboogoyal499 ankita_saini arorakashish0911 array-range-queries array-rearrange Arrays Mathematical Arrays Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Maximum and minimum of an array using minimum number of comparisons Top 50 Array Coding Problems for Interviews Stack Data Structure (Introduction and Program) Introduction to Arrays Multidimensional Arrays in Java Program for Fibonacci numbers Write a program to print all permutations of a given string C++ Data Types Set in C++ Standard Template Library (STL) Coin Change | DP-7
[ { "code": null, "e": 26587, "s": 26559, "text": "\n02 Dec, 2021" }, { "code": null, "e": 26791, "s": 26587, "text": "Given an array arr[] consisting of N 0s and an array Q[][] with each row of the form (L, R)., the task for each query is to update all the array elements in the range [L, R] such that arr[i] = i – L + 1." }, { "code": null, "e": 26801, "s": 26791, "text": "Examples:" }, { "code": null, "e": 27113, "s": 26801, "text": "Input: arr[] = { 0, 0, 0, 0 }, Q[][] = { { 1, 2 }, { 0, 1 } } Output: 1 3 2 0 Explanation: Query1: Updating arr[1] = 1 – 1 + 1, arr[2] = 2 – 1 + 1 modifies arr[] to { 0, 1, 2, 0 } Query2: Updating arr[0] = 0 – 0 + 1, arr[1] = 1 – 0 + 1 modifies arr[] to { 1, 3, 2, 0 } Therefore, the required output is 1 3 2 0." }, { "code": null, "e": 27190, "s": 27113, "text": "Input: arr[] = { 0, 0, 0, 0 }, Q[][] = { { 1, 3 }, { 0, 1 } }Output: 1 3 2 3" }, { "code": null, "e": 27418, "s": 27190, "text": "Naive Approach:The simplest approach to solve the problem is to traverse the array Q[][] and for each query, traverse all the array elements in the given range and update arr[i] += i – L + 1. Finally, print the array elements. " }, { "code": null, "e": 27465, "s": 27418, "text": "Time Complexity: O(N * Q)Auxiliary Space: O(1)" }, { "code": null, "e": 27605, "s": 27465, "text": "Efficient Approach: The above approach can be optimized using the concept of Difference Array. Follow the steps below to solve the problem:" }, { "code": null, "e": 27679, "s": 27605, "text": "Initialize two arrays arr1[] and arr2[] and initialize all elements as 0." }, { "code": null, "e": 27810, "s": 27679, "text": "Traverse the query array, Q[][]. For each query of type (L, R) update arr1[L] += 1, arr1[R + 1] -= 1 and arr2[R + 1] -= R – L + 1." }, { "code": null, "e": 27901, "s": 27810, "text": "Traverse the array, arr1[] and store the prefix sum of arr1[], i.e. arr1[i] += arr1[i -1]." }, { "code": null, "e": 27973, "s": 27901, "text": "Traverse the array, arr2[] and update arr2[i] += arr2[i – 1] + arr1[i]." }, { "code": null, "e": 28007, "s": 27973, "text": "Finally, print the array, arr2[]." }, { "code": null, "e": 28058, "s": 28007, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 28062, "s": 28058, "text": "C++" }, { "code": null, "e": 28067, "s": 28062, "text": "Java" }, { "code": null, "e": 28075, "s": 28067, "text": "Python3" }, { "code": null, "e": 28078, "s": 28075, "text": "C#" }, { "code": null, "e": 28089, "s": 28078, "text": "Javascript" }, { "code": "// C++ program to implement// the above approach#include <bits/stdc++.h>using namespace std; // Function to print the arrayvoid printArray(int arr[], int N){ for (int i = 0; i < N; i++) { cout << arr[i] << \" \"; }} // Function to perform the query in range [L, R]// such that arr[i] += i - L + 1void modifyArray(int arr[], int N, int Q[][2], int cntQuery){ // Initialize array int arr1[N + 1] = { 0 }; int arr2[N + 1] = { 0 }; // Traverse the query array for (int i = 0; i < cntQuery; i++) { // Stores range in 1-based index int L = Q[i][0] + 1, R = Q[i][1] + 1; // Update arr1[L] arr1[L]++; // Update arr1[R + 1] arr1[R + 1]--; // Update arr2[R + 1] arr2[R + 1] -= R - L + 1; } // Calculate prefix sum for (int i = 1; i <= N; i++) arr1[i] += arr1[i - 1]; // Traverse the array, arr2[] for (int i = 1; i <= N; i++) arr2[i] += arr2[i - 1] + arr1[i]; // Copy arr2[] into arr[] for (int i = 1; i <= N; i++) arr[i - 1] = arr2[i]; printArray(arr, N);} // Driver Codeint main(){ // Given array int arr[] = { 0, 0, 0, 0 }; // Size of the array int N = sizeof(arr) / sizeof(arr[0]); int Q[][2] = { { 1, 3 }, { 0, 1 } }; // Stores count of query int cntQuery = sizeof(Q) / sizeof(Q[0]); // Function Call modifyArray(arr, N, Q, cntQuery); return 0;}", "e": 29525, "s": 28089, "text": null }, { "code": "// Java program to implement// the above approachclass GFG{ // Function to print the array static void printArray(int arr[], int N) { for (int i = 0; i < N; i++) { System.out.print(arr[i] + \" \"); } } // Function to perform the query in range [L, R] // such that arr[i] += i - L + 1 static void modifyArray(int arr[], int N, int Q[][], int cntQuery) { // Initialize array int arr1[] = new int[N + 2]; int arr2[] = new int[N + 2]; // Traverse the query array for (int i = 0; i < cntQuery; i++) { // Stores range in 1-based index int L = Q[i][0] + 1, R = Q[i][1] + 1; // Update arr1[L] arr1[L]++; // Update arr1[R + 1] arr1[R + 1]--; // Update arr2[R + 1] arr2[R + 1] -= R - L + 1; } // Calculate prefix sum for (int i = 1; i <= N; i++) arr1[i] += arr1[i - 1]; // Traverse the array, arr2[] for (int i = 1; i <= N; i++) arr2[i] += arr2[i - 1] + arr1[i]; // Copy arr2[] into arr[] for (int i = 1; i <= N; i++) arr[i - 1] = arr2[i]; printArray(arr, N); } // Driver Code public static void main (String[] args) { // Given array int arr[] = { 0, 0, 0, 0 }; // Size of the array int N = arr.length; int Q[][] = { { 1, 3 }, { 0, 1 } }; // Stores count of query int cntQuery = Q.length; // Function Call modifyArray(arr, N, Q, cntQuery); }} // This code is contributed by AnkThon", "e": 31252, "s": 29525, "text": null }, { "code": "# Python3 program to implement# the above approach # Function to print arraydef printArray(arr, N): print(*arr) # Function to perform the query in range [L, R]# such that arr[i] += i - L + 1def modifyArray(arr, N, Q, cntQuery): # Initialize array arr1 = [0 for i in range(N + 2)] arr2 = [0 for i in range(N + 2)] # Traverse the query array for i in range(cntQuery): # Stores range in 1-based index L = Q[i][0] + 1 R = Q[i][1] + 1 # print(L,R) # Update arr1[L] arr1[L] += 1 # Update arr1[R + 1] arr1[R + 1] -= 1 # Update arr2[R + 1] arr2[R + 1] -= R - L + 1 # Calculate prefix sum for i in range(1, N + 1): arr1[i] += arr1[i - 1] # Traverse the array, arr2[] for i in range(1, N + 1): arr2[i] += arr2[i - 1] + arr1[i] # Copy arr2[] into arr[] for i in range(1, N + 1): arr[i - 1] = arr2[i] printArray(arr, N) # Driver Codeif __name__ == '__main__': # Given array arr = [0, 0, 0, 0] # Size of the array N = len(arr) Q = [[ 1, 3 ], [ 0, 1 ]] # Stores count of query cntQuery = len(Q) # Function Call modifyArray(arr, N, Q, cntQuery) # This code is contributed by mohit kumar 29.", "e": 32502, "s": 31252, "text": null }, { "code": "// C# program to implement// the above approachusing System;class GFG{ // Function to print the array static void printArray(int []arr, int N) { for (int i = 0; i < N; i++) { Console.Write(arr[i] + \" \"); } } // Function to perform the query in range [L, R] // such that arr[i] += i - L + 1 static void modifyArray(int []arr, int N, int[,] Q, int cntQuery) { // Initialize array int []arr1 = new int[N + 2]; int []arr2 = new int[N + 2]; // Traverse the query array for (int i = 0; i < cntQuery; i++) { // Stores range in 1-based index int L = Q[i,0] + 1, R = Q[i,1] + 1; // Update arr1[L] arr1[L]++; // Update arr1[R + 1] arr1[R + 1]--; // Update arr2[R + 1] arr2[R + 1] -= R - L + 1; } // Calculate prefix sum for (int i = 1; i <= N; i++) arr1[i] += arr1[i - 1]; // Traverse the array, arr2[] for (int i = 1; i <= N; i++) arr2[i] += arr2[i - 1] + arr1[i]; // Copy arr2[] into arr[] for (int i = 1; i <= N; i++) arr[i - 1] = arr2[i]; printArray(arr, N); } // Driver Code public static void Main() { // Given array int []arr = { 0, 0, 0, 0 }; // Size of the array int N = arr.Length; int [,]Q = { { 1, 3 }, { 0, 1 } }; // Stores count of query int cntQuery = 2; // Function Call modifyArray(arr, N, Q, cntQuery); }} // This code is contributed by bgangwar59.", "e": 34216, "s": 32502, "text": null }, { "code": "<script> // Javascript program to implement// the above approach // Function to print the arrayfunction printArray(arr, N){ for(let i = 0; i < N; i++) { document.write(arr[i] + \" \"); }} // Function to perform the query in// range [L, R] such that// arr[i] += i - L + 1function modifyArray(arr, N, Q, cntQuery){ // Initialize array let arr1 = new Array(N + 2).fill(0); let arr2 = new Array(N + 2).fill(0); // Traverse the query array for(let i = 0; i < cntQuery; i++) { // Stores range in 1-based index let L = Q[i][0] + 1, R = Q[i][1] + 1; // Update arr1[L] arr1[L]++; // Update arr1[R + 1] arr1[R + 1]--; // Update arr2[R + 1] arr2[R + 1] -= R - L + 1; } // Calculate prefix sum for(let i = 1; i <= N; i++) arr1[i] += arr1[i - 1]; // Traverse the array, arr2[] for(let i = 1; i <= N; i++) arr2[i] += arr2[i - 1] + arr1[i]; // Copy arr2[] into arr[] for(let i = 1; i <= N; i++) arr[i - 1] = arr2[i]; prletArray(arr, N);} // Driver Code // Given arraylet arr = [ 0, 0, 0, 0 ]; // Size of the arraylet N = arr.length; let Q = [ [ 1, 3 ], [ 0, 1 ] ]; // Stores count of querylet cntQuery = Q.length; // Function CallmodifyArray(arr, N, Q, cntQuery); // This code is contributed by avijitmondal1998 </script>", "e": 35621, "s": 34216, "text": null }, { "code": null, "e": 35629, "s": 35621, "text": "1 3 2 3" }, { "code": null, "e": 35676, "s": 35631, "text": "Time Complexity: O(N+Q)Auxiliary Space: O(N)" }, { "code": null, "e": 35691, "s": 35676, "text": "mohit kumar 29" }, { "code": null, "e": 35699, "s": 35691, "text": "ankthon" }, { "code": null, "e": 35710, "s": 35699, "text": "bgangwar59" }, { "code": null, "e": 35727, "s": 35710, "text": "avijitmondal1998" }, { "code": null, "e": 35741, "s": 35727, "text": "sumitgumber28" }, { "code": null, "e": 35759, "s": 35741, "text": "gulshankumarar231" }, { "code": null, "e": 35776, "s": 35759, "text": "khushboogoyal499" }, { "code": null, "e": 35789, "s": 35776, "text": "ankita_saini" }, { "code": null, "e": 35806, "s": 35789, "text": "arorakashish0911" }, { "code": null, "e": 35826, "s": 35806, "text": "array-range-queries" }, { "code": null, "e": 35842, "s": 35826, "text": "array-rearrange" }, { "code": null, "e": 35849, "s": 35842, "text": "Arrays" }, { "code": null, "e": 35862, "s": 35849, "text": "Mathematical" }, { "code": null, "e": 35869, "s": 35862, "text": "Arrays" }, { "code": null, "e": 35882, "s": 35869, "text": "Mathematical" }, { "code": null, "e": 35980, "s": 35882, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 36048, "s": 35980, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 36092, "s": 36048, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 36140, "s": 36092, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 36163, "s": 36140, "text": "Introduction to Arrays" }, { "code": null, "e": 36195, "s": 36163, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 36225, "s": 36195, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 36285, "s": 36225, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 36300, "s": 36285, "text": "C++ Data Types" }, { "code": null, "e": 36343, "s": 36300, "text": "Set in C++ Standard Template Library (STL)" } ]
BabelJS - CLI
Babel comes with a built-in command line interface, which can be used to compile the code. Create a directory wherein you would be working. Here, we have created directory called babelproject. Let us make use of nodejs to create the project details. We have used npm init to create the project as shown below − Here is the project structure that we created. Now to work with Babel we need to instal Babel cli, Babel preset, Babel core as shown below − Execute the following command to install babel-cli − npm install --save-dev babel-cli Execute the following command to install babel-preset − npm install --save-dev babel-preset-env Execute the following command to install babel-core − npm install --save-dev babel-core After installation, here are the details available in package.json − We have installed babel plugins local to the project. This is done so that we can use babel differently on our projects based on the project requirements and also different versions of babeljs. Package.json gives the version details of babeljs used. In order to make use of babel in our project, we need to specify the same in package.json as follows − Babel is mainly used to compile JavaScript code, which will have backward compatibility. Now, we will write our code in ES6 -> ES5 or ES7 -> ES5 also ES7->ES6, etc. To provide instructions to Babel on the same, while executing, we need to create a file called .babelrc in the root folder. It contains a json object with details of the presets as shown below − We will create the JavaScript file index.js and compile it to es2015 using Babel. Before that, we need to install the es2015 preset as follows − In index.js, we have created a function using the arrow function which is a new feature added in es6. Using Babel, we will compile the code to es5. To execute to es2015, following command is used − npx babel index.js It displays the index.js code in es5 as shown above. We can store the output in the file by executing the command as shown below − npx babel index.js --out-file index_es5.js Here is the file that we created, index_es5.js − Print Add Notes Bookmark this page
[ { "code": null, "e": 2186, "s": 2095, "text": "Babel comes with a built-in command line interface, which can be used to compile the code." }, { "code": null, "e": 2345, "s": 2186, "text": "Create a directory wherein you would be working. Here, we have created directory called babelproject. Let us make use of nodejs to create the project details." }, { "code": null, "e": 2406, "s": 2345, "text": "We have used npm init to create the project as shown below −" }, { "code": null, "e": 2453, "s": 2406, "text": "Here is the project structure that we created." }, { "code": null, "e": 2547, "s": 2453, "text": "Now to work with Babel we need to instal Babel cli, Babel preset, Babel core as shown below −" }, { "code": null, "e": 2600, "s": 2547, "text": "Execute the following command to install babel-cli −" }, { "code": null, "e": 2634, "s": 2600, "text": "npm install --save-dev babel-cli\n" }, { "code": null, "e": 2690, "s": 2634, "text": "Execute the following command to install babel-preset −" }, { "code": null, "e": 2731, "s": 2690, "text": "npm install --save-dev babel-preset-env\n" }, { "code": null, "e": 2785, "s": 2731, "text": "Execute the following command to install babel-core −" }, { "code": null, "e": 2820, "s": 2785, "text": "npm install --save-dev babel-core\n" }, { "code": null, "e": 2889, "s": 2820, "text": "After installation, here are the details available in package.json −" }, { "code": null, "e": 3139, "s": 2889, "text": "We have installed babel plugins local to the project. This is done so that we can use babel differently on our projects based on the project requirements and also different versions of babeljs. Package.json gives the version details of babeljs used." }, { "code": null, "e": 3242, "s": 3139, "text": "In order to make use of babel in our project, we need to specify the same in package.json as follows −" }, { "code": null, "e": 3407, "s": 3242, "text": "Babel is mainly used to compile JavaScript code, which will have backward compatibility. Now, we will write our code in ES6 -> ES5 or ES7 -> ES5 also ES7->ES6, etc." }, { "code": null, "e": 3602, "s": 3407, "text": "To provide instructions to Babel on the same, while executing, we need to create a file called .babelrc in the root folder. It contains a json object with details of the presets as shown below −" }, { "code": null, "e": 3747, "s": 3602, "text": "We will create the JavaScript file index.js and compile it to es2015 using Babel. Before that, we need to install the es2015 preset as follows −" }, { "code": null, "e": 3895, "s": 3747, "text": "In index.js, we have created a function using the arrow function which is a new feature added in es6. Using Babel, we will compile the code to es5." }, { "code": null, "e": 3945, "s": 3895, "text": "To execute to es2015, following command is used −" }, { "code": null, "e": 3965, "s": 3945, "text": "npx babel index.js\n" }, { "code": null, "e": 4018, "s": 3965, "text": "It displays the index.js code in es5 as shown above." }, { "code": null, "e": 4096, "s": 4018, "text": "We can store the output in the file by executing the command as shown below −" }, { "code": null, "e": 4140, "s": 4096, "text": "npx babel index.js --out-file index_es5.js\n" }, { "code": null, "e": 4189, "s": 4140, "text": "Here is the file that we created, index_es5.js −" }, { "code": null, "e": 4196, "s": 4189, "text": " Print" }, { "code": null, "e": 4207, "s": 4196, "text": " Add Notes" } ]
Python OR Operator - GeeksforGeeks
19 Oct, 2021 Python OR Operator takes at least two boolean expressions and returns True if any one of the expressions is True. If all the expressions are False then it returns False. Python OR operator returns True in any one of the boolean expressions passed is True. Python3 bool1 = 2>3bool2 = 2<3 print('bool1:', bool1)print('bool2:', bool2) # or operatorOR = bool1 or bool2print("OR operator:", OR) bool1: False bool2: True OR operator: True We can use the OR operator in the if statement. We can use it in the case where we want to execute the if block if any one of the conditions becomes if True. Python3 # or operator with ifdef fun(a): if a >= 5 or a <= 15: print('a lies between 5 and 15') else: print('a is either less than 5 or greater than 15') # driver codefun(10)fun(20)fun(5) a lies between 5 and 15 a lies between 5 and 15 a lies between 5 and 15 In the above output, we can see that the code for the if statement is executed always. This is because for every value of a, one of the boolean expressions will always be True and the else block will never get executed. The Python Or operator always evaluates the expression until it finds a True and as soon it Found a True then the rest of the expression is not checked. Consider the below example for better understanding. Python3 # short circuit in Python or operatordef true(): print("Inside True") return True def false(): print("Inside False") return False case1 = true() or false()print("Case 1")print(case1)print() case2 = true() or true()print("Case 2")print(case2)print() case3 = false() or false()print("Case 3")print(case3)print() case4 = false() or true()print("Case 4")print(case4) Inside True Case 1 True Inside True Case 2 True Inside False Inside False Case 3 False Inside False Inside True Case 4 True From the above example, we can see that the short circuit or lazy evaluation is followed. In case1 and case2, the second expression is not evaluated because the first expression returns True, whereas, in case3 and case4 the second expression is evaluated as the first expression does not returns True. Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? How to drop one or multiple columns in Pandas Dataframe Python Classes and Objects Python | os.path.join() method Python | Pandas dataframe.groupby() Create a directory in Python Defaultdict in Python Python | Get unique values from a list
[ { "code": null, "e": 25647, "s": 25619, "text": "\n19 Oct, 2021" }, { "code": null, "e": 25817, "s": 25647, "text": "Python OR Operator takes at least two boolean expressions and returns True if any one of the expressions is True. If all the expressions are False then it returns False." }, { "code": null, "e": 25903, "s": 25817, "text": "Python OR operator returns True in any one of the boolean expressions passed is True." }, { "code": null, "e": 25911, "s": 25903, "text": "Python3" }, { "code": "bool1 = 2>3bool2 = 2<3 print('bool1:', bool1)print('bool2:', bool2) # or operatorOR = bool1 or bool2print(\"OR operator:\", OR)", "e": 26039, "s": 25911, "text": null }, { "code": null, "e": 26082, "s": 26039, "text": "bool1: False\nbool2: True\nOR operator: True" }, { "code": null, "e": 26240, "s": 26082, "text": "We can use the OR operator in the if statement. We can use it in the case where we want to execute the if block if any one of the conditions becomes if True." }, { "code": null, "e": 26248, "s": 26240, "text": "Python3" }, { "code": "# or operator with ifdef fun(a): if a >= 5 or a <= 15: print('a lies between 5 and 15') else: print('a is either less than 5 or greater than 15') # driver codefun(10)fun(20)fun(5)", "e": 26451, "s": 26248, "text": null }, { "code": null, "e": 26523, "s": 26451, "text": "a lies between 5 and 15\na lies between 5 and 15\na lies between 5 and 15" }, { "code": null, "e": 26743, "s": 26523, "text": "In the above output, we can see that the code for the if statement is executed always. This is because for every value of a, one of the boolean expressions will always be True and the else block will never get executed." }, { "code": null, "e": 26949, "s": 26743, "text": "The Python Or operator always evaluates the expression until it finds a True and as soon it Found a True then the rest of the expression is not checked. Consider the below example for better understanding." }, { "code": null, "e": 26957, "s": 26949, "text": "Python3" }, { "code": "# short circuit in Python or operatordef true(): print(\"Inside True\") return True def false(): print(\"Inside False\") return False case1 = true() or false()print(\"Case 1\")print(case1)print() case2 = true() or true()print(\"Case 2\")print(case2)print() case3 = false() or false()print(\"Case 3\")print(case3)print() case4 = false() or true()print(\"Case 4\")print(case4)", "e": 27337, "s": 26957, "text": null }, { "code": null, "e": 27464, "s": 27337, "text": "Inside True\nCase 1\nTrue\n\nInside True\nCase 2\nTrue\n\nInside False\nInside False\nCase 3\nFalse\n\nInside False\nInside True\nCase 4\nTrue" }, { "code": null, "e": 27766, "s": 27464, "text": "From the above example, we can see that the short circuit or lazy evaluation is followed. In case1 and case2, the second expression is not evaluated because the first expression returns True, whereas, in case3 and case4 the second expression is evaluated as the first expression does not returns True." }, { "code": null, "e": 27773, "s": 27766, "text": "Python" }, { "code": null, "e": 27871, "s": 27773, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27903, "s": 27871, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27945, "s": 27903, "text": "Check if element exists in list in Python" }, { "code": null, "e": 27987, "s": 27945, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 28043, "s": 27987, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 28070, "s": 28043, "text": "Python Classes and Objects" }, { "code": null, "e": 28101, "s": 28070, "text": "Python | os.path.join() method" }, { "code": null, "e": 28137, "s": 28101, "text": "Python | Pandas dataframe.groupby()" }, { "code": null, "e": 28166, "s": 28137, "text": "Create a directory in Python" }, { "code": null, "e": 28188, "s": 28166, "text": "Defaultdict in Python" } ]
How to combine LaTeX and R for report generation | Towards Data Science
If you have to create a report, LaTeX is definitely the choice to make, everything looks better in LaTeX! Chances are that you used it to write your thesis or some assays, back in your academia years. Indeed, environments like texstudio or the more recent Overleaf are great for single projects. But now in your day job, can they really scale it up and make LaTeX still useful? What you need is a method that generates reports automatically (maybe, just there at the end of your pipeline), that changes its content dynamically in relation to the findings of your code, that is visually pleasing (for your boss), and that can be fast enough to mass-produce results. If that is the case, my favourite solution is the R package “knitr” that allows us to create LaTeX documents directly from R code. Combining the flexibility of a programming language and the LaTeX aesthetics. In this article, I want to give you a basic tutorial and some tips on how to do it successfully. I understand that not many know both R and LaTeX, I will try to keep it simple, but both coding systems and their combination cannot be explained in one single article, I hope that, if you have clicked on this article and read it until now, you have some basic knowledge on the two. Without further ado, let’s create a LaTeX report with R. Two are the steps needed to create a R/tex report, a ‘starter’ R script to create the final pdf, and the .Rnw file where all our code will be stored. Let’s see them: The ‘starter’ script has to do two basic functions: Load and pass the Rnw file to the knit command of the knitr package. This process is called weaving. This will execute the R code and produce a series of files among which there’s a .tex file that we would normally use in texstudio.Execute twice the .tex file in order to create the final PDF report Load and pass the Rnw file to the knit command of the knitr package. This process is called weaving. This will execute the R code and produce a series of files among which there’s a .tex file that we would normally use in texstudio. Execute twice the .tex file in order to create the final PDF report To make the overall process easier, I would recommend creating an independent file called starter.R with the code above and run it when needed, with the following command: R CMD BATCH starter.R Alternatively, you can copy/paste the three lines of code on the command line or anywhere else you might need. Don’t forget to install knitr in R. install.packages('knitr') The .Rnw (or Sweave) file is in essence a .tex file in which it is possible to insert blocks of R code. The structure of the file follows the normal structure of a LaTeX work starting with the declaration of the document class but at any point in the code you can add R blocks of code. Those are defined between two elements: a <<...>> in which the setting of the R code blocks are passed and a @, that defines its end. Let’s see an example: So far this is a common code that you could find in any .tex file and it produce the pages in Fig 1. It produce an front page, table of content and the first chapter: Let’s continue and see the first R block that create a plot with R and import the figure in LaTeX: In between the less-than and the greater-than signs we can pass the parameters for the execution of our R blocks; the most important elements to pass are: Name: This is simply the name of the block, each block has to have a unique name. An identify name will help you greatly in the debugging phase echo: this TRUE or FALSE value will indicate if the code will be shown or not in the final pdf document. results can take value ‘asis’ or ‘hide’ and it will show or to hide the results (output) of the block Other parameters are the Boolean “include” that determine if the block has to be run, and “warning” and “message” both determine if the debugging messages have to be shown in the pdf final version. Let’s see a practical example in which we will load the Iris database and create a plot within the R block of code: In the code above we define a block of code called CreatePlot , in which we ask to show the underline R code in the pdf but the resulting plot is hidden and iit will be loaded using \includegraphics{}. In Fig 2 we can see the result of the code above.A title, the block of R code shown as requested with echo and the latex code used to load the figure. I have manually add the plot in Fig 2 to show the result of the R code, otherwise it will be in a different pdf page. Let’s see another case using a table as example: With this block of code, we create a table using the iris database and both the code and the table are immediately shown as you can see below in Fig 3. We can see that the above block created a table with the Iris database in it (not entirely reported) and the R code that produced it. For my personal experience the .Rnw file is a very powerful tool, however, I recommend keeping the R code at a minimum, and use the blocks only to import plots and csv/table produced elsewhere. If you prefer to compute and generate content directly in the Rnw it will start to be messy soon. I hope this article will give a concrete help in the creation of your first report using LaTeX and R. The full and extended code is present in this GitHub repository: The above script will produce the following pdf (click on the image within the link). For more information on knitr: source one and two. I hope you found this article helpful
[ { "code": null, "e": 278, "s": 172, "text": "If you have to create a report, LaTeX is definitely the choice to make, everything looks better in LaTeX!" }, { "code": null, "e": 550, "s": 278, "text": "Chances are that you used it to write your thesis or some assays, back in your academia years. Indeed, environments like texstudio or the more recent Overleaf are great for single projects. But now in your day job, can they really scale it up and make LaTeX still useful?" }, { "code": null, "e": 837, "s": 550, "text": "What you need is a method that generates reports automatically (maybe, just there at the end of your pipeline), that changes its content dynamically in relation to the findings of your code, that is visually pleasing (for your boss), and that can be fast enough to mass-produce results." }, { "code": null, "e": 1046, "s": 837, "text": "If that is the case, my favourite solution is the R package “knitr” that allows us to create LaTeX documents directly from R code. Combining the flexibility of a programming language and the LaTeX aesthetics." }, { "code": null, "e": 1426, "s": 1046, "text": "In this article, I want to give you a basic tutorial and some tips on how to do it successfully. I understand that not many know both R and LaTeX, I will try to keep it simple, but both coding systems and their combination cannot be explained in one single article, I hope that, if you have clicked on this article and read it until now, you have some basic knowledge on the two." }, { "code": null, "e": 1483, "s": 1426, "text": "Without further ado, let’s create a LaTeX report with R." }, { "code": null, "e": 1649, "s": 1483, "text": "Two are the steps needed to create a R/tex report, a ‘starter’ R script to create the final pdf, and the .Rnw file where all our code will be stored. Let’s see them:" }, { "code": null, "e": 1701, "s": 1649, "text": "The ‘starter’ script has to do two basic functions:" }, { "code": null, "e": 2001, "s": 1701, "text": "Load and pass the Rnw file to the knit command of the knitr package. This process is called weaving. This will execute the R code and produce a series of files among which there’s a .tex file that we would normally use in texstudio.Execute twice the .tex file in order to create the final PDF report" }, { "code": null, "e": 2234, "s": 2001, "text": "Load and pass the Rnw file to the knit command of the knitr package. This process is called weaving. This will execute the R code and produce a series of files among which there’s a .tex file that we would normally use in texstudio." }, { "code": null, "e": 2302, "s": 2234, "text": "Execute twice the .tex file in order to create the final PDF report" }, { "code": null, "e": 2474, "s": 2302, "text": "To make the overall process easier, I would recommend creating an independent file called starter.R with the code above and run it when needed, with the following command:" }, { "code": null, "e": 2496, "s": 2474, "text": "R CMD BATCH starter.R" }, { "code": null, "e": 2607, "s": 2496, "text": "Alternatively, you can copy/paste the three lines of code on the command line or anywhere else you might need." }, { "code": null, "e": 2643, "s": 2607, "text": "Don’t forget to install knitr in R." }, { "code": null, "e": 2669, "s": 2643, "text": "install.packages('knitr')" }, { "code": null, "e": 2773, "s": 2669, "text": "The .Rnw (or Sweave) file is in essence a .tex file in which it is possible to insert blocks of R code." }, { "code": null, "e": 2955, "s": 2773, "text": "The structure of the file follows the normal structure of a LaTeX work starting with the declaration of the document class but at any point in the code you can add R blocks of code." }, { "code": null, "e": 3089, "s": 2955, "text": "Those are defined between two elements: a <<...>> in which the setting of the R code blocks are passed and a @, that defines its end." }, { "code": null, "e": 3111, "s": 3089, "text": "Let’s see an example:" }, { "code": null, "e": 3278, "s": 3111, "text": "So far this is a common code that you could find in any .tex file and it produce the pages in Fig 1. It produce an front page, table of content and the first chapter:" }, { "code": null, "e": 3377, "s": 3278, "text": "Let’s continue and see the first R block that create a plot with R and import the figure in LaTeX:" }, { "code": null, "e": 3532, "s": 3377, "text": "In between the less-than and the greater-than signs we can pass the parameters for the execution of our R blocks; the most important elements to pass are:" }, { "code": null, "e": 3676, "s": 3532, "text": "Name: This is simply the name of the block, each block has to have a unique name. An identify name will help you greatly in the debugging phase" }, { "code": null, "e": 3781, "s": 3676, "text": "echo: this TRUE or FALSE value will indicate if the code will be shown or not in the final pdf document." }, { "code": null, "e": 3883, "s": 3781, "text": "results can take value ‘asis’ or ‘hide’ and it will show or to hide the results (output) of the block" }, { "code": null, "e": 4081, "s": 3883, "text": "Other parameters are the Boolean “include” that determine if the block has to be run, and “warning” and “message” both determine if the debugging messages have to be shown in the pdf final version." }, { "code": null, "e": 4197, "s": 4081, "text": "Let’s see a practical example in which we will load the Iris database and create a plot within the R block of code:" }, { "code": null, "e": 4399, "s": 4197, "text": "In the code above we define a block of code called CreatePlot , in which we ask to show the underline R code in the pdf but the resulting plot is hidden and iit will be loaded using \\includegraphics{}." }, { "code": null, "e": 4550, "s": 4399, "text": "In Fig 2 we can see the result of the code above.A title, the block of R code shown as requested with echo and the latex code used to load the figure." }, { "code": null, "e": 4668, "s": 4550, "text": "I have manually add the plot in Fig 2 to show the result of the R code, otherwise it will be in a different pdf page." }, { "code": null, "e": 4717, "s": 4668, "text": "Let’s see another case using a table as example:" }, { "code": null, "e": 4869, "s": 4717, "text": "With this block of code, we create a table using the iris database and both the code and the table are immediately shown as you can see below in Fig 3." }, { "code": null, "e": 5003, "s": 4869, "text": "We can see that the above block created a table with the Iris database in it (not entirely reported) and the R code that produced it." }, { "code": null, "e": 5295, "s": 5003, "text": "For my personal experience the .Rnw file is a very powerful tool, however, I recommend keeping the R code at a minimum, and use the blocks only to import plots and csv/table produced elsewhere. If you prefer to compute and generate content directly in the Rnw it will start to be messy soon." }, { "code": null, "e": 5397, "s": 5295, "text": "I hope this article will give a concrete help in the creation of your first report using LaTeX and R." }, { "code": null, "e": 5462, "s": 5397, "text": "The full and extended code is present in this GitHub repository:" }, { "code": null, "e": 5548, "s": 5462, "text": "The above script will produce the following pdf (click on the image within the link)." }, { "code": null, "e": 5599, "s": 5548, "text": "For more information on knitr: source one and two." } ]
Program to calculate Root Mean Square
01 Apr, 2021 Given an array of N numbers. The task is to calculate the Root Mean Square(RMS) of the given numbers. Examples: Input: arr[] = {1, 2, 3, 4, 5} Output: 3.31662 Input: arr[] = {10, 4, 6, 8} Output: 7.34847 Approach: The Root Mean Square value of N numbers x1,x2,x3,.....xn can be given as, RMS method first calculates the square of each number and then calculate the mean and finally calculate the square root of the mean.Below is the program to find RMS of N numbers: C++ Java Python3 C# PHP Javascript // CPP program to calculate Root Mean Square#include <bits/stdc++.h>using namespace std; // Function that Calculate Root Mean Squarefloat rmsValue(int arr[], int n){ int square = 0; float mean = 0.0, root = 0.0; // Calculate square. for (int i = 0; i < n; i++) { square += pow(arr[i], 2); } // Calculate Mean. mean = (square / (float)(n)); // Calculate Root. root = sqrt(mean); return root;} // Driver codeint main(){ int arr[] = { 10, 4, 6, 8 }; int n = sizeof(arr) / sizeof(arr[0]); cout << rmsValue(arr, n); return 0;} // Java program to calculate// Root Mean Square class GFG{ // Function that Calculate Root// Mean Squarestatic float rmsValue(int arr[], int n){ int square = 0; float mean = 0; float root = 0; // Calculate square. for(int i = 0; i < n; i++) { square += Math.pow(arr[i], 2); } // Calculate Mean. mean = (square / (float) (n)); // Calculate Root. root = (float)Math.sqrt(mean); return root;} // Driver Codepublic static void main(String args[]){ int arr[] = { 10, 4, 6, 8}; int n = arr.length; System.out.println(rmsValue(arr, n));}} // This code is contributed by ANKITRAI1 #Python3 program to calculate Root Mean Square import math#Function that Calculate Root Mean Squaredef rmsValue(arr, n): square = 0 mean = 0.0 root = 0.0 #Calculate square for i in range(0,n): square += (arr[i]**2) #Calculate Mean mean = (square / (float)(n)) #Calculate Root root = math.sqrt(mean) return root #Driver codeif __name__=='__main__': arr = [10, 4, 6, 8] n = len(arr) print(rmsValue(arr, n)) #This code is contributed by Shashank_Sharma // C# program to calculate// Root Mean Squareusing System;class GFG{ // Function that Calculate// Root Mean Squarestatic float rmsValue(int[] arr, int n){ int square = 0; float mean = 0; float root = 0; // Calculate square. for(int i = 0; i < n; i++) { square += (int)Math.Pow(arr[i], 2); } // Calculate Mean. mean = (square / (float) (n)); // Calculate Root. root = (float)Math.Sqrt(mean); return root;} // Driver Codepublic static void Main(){ int[] arr = {10, 4, 6, 8}; int n = arr.Length; Console.Write(rmsValue(arr, n));}} // This code is contributed// by ChitraNayal <?php// PHP program to calculate Root// Mean Square // Function that Calculate Root// Mean Squarefunction rmsValue($arr, $n){ $square = 0; $mean = 0.0; $root = 0.0; // Calculate square. for ($i = 0; $i < $n; $i++) { $square += pow($arr[$i], 2); } // Calculate Mean. $mean = ($square / (float)($n)); // Calculate Root. $root = sqrt($mean); return $root;} // Driver code$arr = array( 10, 4, 6, 8 );$n = sizeof($arr); echo rmsValue($arr, $n); // This code is contributed// by jit_t?> <script> // javascript program to calculate// Root Mean Square // Function that Calculate Root // Mean Square function rmsValue(arr , n) { var square = 0; var mean = 0; var root = 0; // Calculate square. for (i = 0; i < n; i++) { square += Math.pow(arr[i], 2); } // Calculate Mean. mean = (square / (n)); // Calculate Root. root = Math.sqrt(mean); return root; } // Driver Code var arr = [ 10, 4, 6, 8 ]; var n = arr.length; document.write(rmsValue(arr, n).toFixed(5)); // This code contributed by aashish1995 </script> 7.34847 Shashank_Sharma ankthon ukasp jit_t aashish1995 Mathematical School Programming Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n01 Apr, 2021" }, { "code": null, "e": 167, "s": 53, "text": "Given an array of N numbers. The task is to calculate the Root Mean Square(RMS) of the given numbers. Examples: " }, { "code": null, "e": 260, "s": 167, "text": "Input: arr[] = {1, 2, 3, 4, 5}\nOutput: 3.31662\n\nInput: arr[] = {10, 4, 6, 8}\nOutput: 7.34847" }, { "code": null, "e": 348, "s": 262, "text": "Approach: The Root Mean Square value of N numbers x1,x2,x3,.....xn can be given as, " }, { "code": null, "e": 529, "s": 348, "text": "RMS method first calculates the square of each number and then calculate the mean and finally calculate the square root of the mean.Below is the program to find RMS of N numbers: " }, { "code": null, "e": 533, "s": 529, "text": "C++" }, { "code": null, "e": 538, "s": 533, "text": "Java" }, { "code": null, "e": 546, "s": 538, "text": "Python3" }, { "code": null, "e": 549, "s": 546, "text": "C#" }, { "code": null, "e": 553, "s": 549, "text": "PHP" }, { "code": null, "e": 564, "s": 553, "text": "Javascript" }, { "code": "// CPP program to calculate Root Mean Square#include <bits/stdc++.h>using namespace std; // Function that Calculate Root Mean Squarefloat rmsValue(int arr[], int n){ int square = 0; float mean = 0.0, root = 0.0; // Calculate square. for (int i = 0; i < n; i++) { square += pow(arr[i], 2); } // Calculate Mean. mean = (square / (float)(n)); // Calculate Root. root = sqrt(mean); return root;} // Driver codeint main(){ int arr[] = { 10, 4, 6, 8 }; int n = sizeof(arr) / sizeof(arr[0]); cout << rmsValue(arr, n); return 0;}", "e": 1141, "s": 564, "text": null }, { "code": "// Java program to calculate// Root Mean Square class GFG{ // Function that Calculate Root// Mean Squarestatic float rmsValue(int arr[], int n){ int square = 0; float mean = 0; float root = 0; // Calculate square. for(int i = 0; i < n; i++) { square += Math.pow(arr[i], 2); } // Calculate Mean. mean = (square / (float) (n)); // Calculate Root. root = (float)Math.sqrt(mean); return root;} // Driver Codepublic static void main(String args[]){ int arr[] = { 10, 4, 6, 8}; int n = arr.length; System.out.println(rmsValue(arr, n));}} // This code is contributed by ANKITRAI1", "e": 1785, "s": 1141, "text": null }, { "code": "#Python3 program to calculate Root Mean Square import math#Function that Calculate Root Mean Squaredef rmsValue(arr, n): square = 0 mean = 0.0 root = 0.0 #Calculate square for i in range(0,n): square += (arr[i]**2) #Calculate Mean mean = (square / (float)(n)) #Calculate Root root = math.sqrt(mean) return root #Driver codeif __name__=='__main__': arr = [10, 4, 6, 8] n = len(arr) print(rmsValue(arr, n)) #This code is contributed by Shashank_Sharma", "e": 2301, "s": 1785, "text": null }, { "code": "// C# program to calculate// Root Mean Squareusing System;class GFG{ // Function that Calculate// Root Mean Squarestatic float rmsValue(int[] arr, int n){ int square = 0; float mean = 0; float root = 0; // Calculate square. for(int i = 0; i < n; i++) { square += (int)Math.Pow(arr[i], 2); } // Calculate Mean. mean = (square / (float) (n)); // Calculate Root. root = (float)Math.Sqrt(mean); return root;} // Driver Codepublic static void Main(){ int[] arr = {10, 4, 6, 8}; int n = arr.Length; Console.Write(rmsValue(arr, n));}} // This code is contributed// by ChitraNayal", "e": 2944, "s": 2301, "text": null }, { "code": "<?php// PHP program to calculate Root// Mean Square // Function that Calculate Root// Mean Squarefunction rmsValue($arr, $n){ $square = 0; $mean = 0.0; $root = 0.0; // Calculate square. for ($i = 0; $i < $n; $i++) { $square += pow($arr[$i], 2); } // Calculate Mean. $mean = ($square / (float)($n)); // Calculate Root. $root = sqrt($mean); return $root;} // Driver code$arr = array( 10, 4, 6, 8 );$n = sizeof($arr); echo rmsValue($arr, $n); // This code is contributed// by jit_t?>", "e": 3472, "s": 2944, "text": null }, { "code": "<script> // javascript program to calculate// Root Mean Square // Function that Calculate Root // Mean Square function rmsValue(arr , n) { var square = 0; var mean = 0; var root = 0; // Calculate square. for (i = 0; i < n; i++) { square += Math.pow(arr[i], 2); } // Calculate Mean. mean = (square / (n)); // Calculate Root. root = Math.sqrt(mean); return root; } // Driver Code var arr = [ 10, 4, 6, 8 ]; var n = arr.length; document.write(rmsValue(arr, n).toFixed(5)); // This code contributed by aashish1995 </script>", "e": 4131, "s": 3472, "text": null }, { "code": null, "e": 4139, "s": 4131, "text": "7.34847" }, { "code": null, "e": 4157, "s": 4141, "text": "Shashank_Sharma" }, { "code": null, "e": 4165, "s": 4157, "text": "ankthon" }, { "code": null, "e": 4171, "s": 4165, "text": "ukasp" }, { "code": null, "e": 4177, "s": 4171, "text": "jit_t" }, { "code": null, "e": 4189, "s": 4177, "text": "aashish1995" }, { "code": null, "e": 4202, "s": 4189, "text": "Mathematical" }, { "code": null, "e": 4221, "s": 4202, "text": "School Programming" }, { "code": null, "e": 4234, "s": 4221, "text": "Mathematical" } ]
How to run JavaScript from PHP?
31 Jul, 2021 JavaScript is the client side scripting language and PHP is the server side scripting language. JavaScript is used as client side to check and verify client details and PHP is server side used to interact with database. In PHP, HTML is used as a string in the code. In order to render it to the browser, we produce JavaScript code as a string in the PHP code. Example 1: Write JavaScript code within PHP code <?php echo '<script type="text/JavaScript"> prompt("GeeksForGeeks"); </script>';?> Output: Example 2: Write JavaScript code outside of PHP code (in same PHP file) <?php // some php stuff?><script type="text/javascript"> alert('GeeksforGeeks!');</script> Output: Example 3: JavaScript Function – DOM Manipulation (in same PHP file) <?php echo "<div id='demo'></div>";?><script type="text/JavaScript"> // Function is called, return // value will end up in xvar x = myFunction(11, 10); document.getElementById("demo").innerHTML = x; // Function returns the product of a and bfunction myFunction(a, b) { return a * b; }</script> Output: 110 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. PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples. Picked Technical Scripter 2018 PHP PHP Programs Technical Scripter Web Technologies PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n31 Jul, 2021" }, { "code": null, "e": 414, "s": 54, "text": "JavaScript is the client side scripting language and PHP is the server side scripting language. JavaScript is used as client side to check and verify client details and PHP is server side used to interact with database. In PHP, HTML is used as a string in the code. In order to render it to the browser, we produce JavaScript code as a string in the PHP code." }, { "code": null, "e": 463, "s": 414, "text": "Example 1: Write JavaScript code within PHP code" }, { "code": "<?php echo '<script type=\"text/JavaScript\"> prompt(\"GeeksForGeeks\"); </script>';?>", "e": 555, "s": 463, "text": null }, { "code": null, "e": 563, "s": 555, "text": "Output:" }, { "code": null, "e": 635, "s": 563, "text": "Example 2: Write JavaScript code outside of PHP code (in same PHP file)" }, { "code": "<?php // some php stuff?><script type=\"text/javascript\"> alert('GeeksforGeeks!');</script>", "e": 732, "s": 635, "text": null }, { "code": null, "e": 740, "s": 732, "text": "Output:" }, { "code": null, "e": 809, "s": 740, "text": "Example 3: JavaScript Function – DOM Manipulation (in same PHP file)" }, { "code": "<?php echo \"<div id='demo'></div>\";?><script type=\"text/JavaScript\"> // Function is called, return // value will end up in xvar x = myFunction(11, 10); document.getElementById(\"demo\").innerHTML = x; // Function returns the product of a and bfunction myFunction(a, b) { return a * b; }</script>", "e": 1125, "s": 809, "text": null }, { "code": null, "e": 1133, "s": 1125, "text": "Output:" }, { "code": null, "e": 1137, "s": 1133, "text": "110" }, { "code": null, "e": 1356, "s": 1137, "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": 1525, "s": 1356, "text": "PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples." }, { "code": null, "e": 1532, "s": 1525, "text": "Picked" }, { "code": null, "e": 1556, "s": 1532, "text": "Technical Scripter 2018" }, { "code": null, "e": 1560, "s": 1556, "text": "PHP" }, { "code": null, "e": 1573, "s": 1560, "text": "PHP Programs" }, { "code": null, "e": 1592, "s": 1573, "text": "Technical Scripter" }, { "code": null, "e": 1609, "s": 1592, "text": "Web Technologies" }, { "code": null, "e": 1613, "s": 1609, "text": "PHP" } ]
m-WAY Search Trees | Set-1 ( Searching )
23 Jun, 2022 The m-way search trees are multi-way trees which are generalised versions of binary trees where each node contains multiple elements. In an m-Way tree of order m, each node contains a maximum of m – 1 elements and m children.The goal of m-Way search tree of height h calls for O(h) no. of accesses for an insert/delete/retrieval operation. Hence, it ensures that the height h is close to log_m(n + 1).The number of elements in an m-Way search tree of height h ranges from a minimum of h to a maximum of .An m-Way search tree of n elements ranges from a minimum height of log_m(n+1) to a maximum of nAn example of a 5-Way search tree is shown in the figure below. Observe how each node has at most 5 child nodes & therefore has at most 4 keys contained in it. The structure of a node of an m-Way tree is given below: C++ Java Python3 C# struct node { int count; int value[MAX + 1]; struct node* child[MAX + 1];}; public class Node { int count; int[] value = new int[MAX + 1]; Node[] child = new Node[MAX + 1];} // This code is contributed by tapeshdua420. class node: def __init__(self): self.count = -1 self.value = [-1]*(MAX + 1) self.child = [None]*(MAX + 1) class node { public int count; public int[] value = new int[MAX + 1]; public node[] child = new node[MAX + 1];} // This code is contributed by Tapesh (tapeshdua420) Here, count represents the number of children that a particular node has The values of a node stored in the array value The addresses of child nodes are stored in the child array The MAX macro signifies the maximum number of values that a particular node can contain Searching in an m-Way search tree: Searching for a key in an m-Way search tree is similar to that of binary search tree To search for 77 in the 5-Way search tree, shown in the figure, we begin at the root & as 77> 76> 44> 18, move to the fourth sub-tree In the root node of the fourth sub-tree, 77< 80 & therefore we move to the first sub-tree of the node. Since 77 is available in the only node of this sub-tree, we claim 77 was successfully searched C++ Java Python3 C# // Searches value in the nodestruct node* search(int val, struct node* root, int* pos){ // if root is Null then return if (root == NULL) return NULL; else { // if node is found if (searchnode(val, root, pos)) return root; // if not then search in child nodes else return search(val, root->child[*pos], pos); }} // Searches the nodeint searchnode(int val, struct node* n, int* pos){ // if val is less than node->value[1] if (val < n->value[1]) { *pos = 0; return 0; } // if the val is greater else { *pos = n->count; // check in the child array // for correct position while ((val < n->value[*pos]) && *pos > 1) (*pos)--; if (val == n->value[*pos]) return 1; else return 0; }} // Searches value in the nodepublic Node search(int val, Node root, int pos) { // if root is Null then return if (root == null) return null; else { // if node is found if (searchnode(val, root, pos)) return root; // if not then search in child nodes else return search(val, root.child[pos], pos); }} // Searches the nodepublic boolean searchnode(int val, Node n, int pos) { // if val is less than node.value[1] if (val < n.value[1]) { pos = 0; return false; } // if the val is greater else { pos = n.count; // check in the child array // for correct position while ((val < n.value[pos]) && pos > 1) pos--; if (val == n.value[pos]) return true; else return false; }} // This code is contributed by Tapesh(tapeshdua420) # Searches value in the nodedef search(val, root, pos): # if root is None then return if (root == None): return None else : # if node is found if (searchnode(val, root, pos)): return root # if not then search in child nodes else: return search(val, root.child[pos], pos) # Searches the nodedef searchnode(val, n, pos): # if val is less than node.value[1] if (val < n.value[1]): pos = 0 return 0 # if the val is greater else : pos = n.count # check in the child array # for correct position while ((val < n.value[pos]) and pos > 1): pos-=1 if (val == n.value[pos]): return 1 else: return 0 // Searches value in the nodepublic Node search(int val, Node root, int pos){ // if root is Null then return if (root == null) return null; else { // if node is found if (searchnode(val, root, pos)) return root; // if not then search in child nodes else return search(val, root.child[pos], pos); }} // Searches the nodepublic bool searchnode(int val, Node n, int pos){ // if val is less than node.value[1] if (val < n.value[1]) { pos = 0; return false; } // if the val is greater else { pos = n.count; // check in the child array // for correct position while ((val < n.value[pos]) && pos > 1) pos--; if (val == n.value[pos]) return true; else return false; }} // This code is contributed by Tapesh (tapeshdua420) search(): The function search() receives three parameters The first parameter is the value to be searched, second is the address of the node from where the search is to be performed and third is the address of a variable that is used to store the position of the value once found Initially a condition is checked whether the address of the node being searched is NULL If it is, then simply a NULL value is returned Otherwise, a function searchnode() is called which actually searches the given value If the search is successful the address of the node in which the value is found is returned If the search is unsuccessful then a recursive call is made to the search() function for the child of the current node searchnode(): The function searchnode() receives three parameters The first parameter is the value that is to be searched The second parameter is the address of the node in which the search is to be performed and third is a pointer pos that holds the address of a variable in which the position of the value that once found is stored This function returns a value 0 if the search is unsuccessful and 1 if it is successful In this function initially it is checked whether the value that is to be searched is less than the very first value of the node If it is then it indicates that the value is not present in the current node. Hence, a value 0 is assigned in the variable that is pointed to by pos and 0 is returned, as the search is unsuccessful amartyaghoshgfg tapeshdua420 Data Structures Searching Tree Data Structures Searching Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n23 Jun, 2022" }, { "code": null, "e": 813, "s": 52, "text": "The m-way search trees are multi-way trees which are generalised versions of binary trees where each node contains multiple elements. In an m-Way tree of order m, each node contains a maximum of m – 1 elements and m children.The goal of m-Way search tree of height h calls for O(h) no. of accesses for an insert/delete/retrieval operation. Hence, it ensures that the height h is close to log_m(n + 1).The number of elements in an m-Way search tree of height h ranges from a minimum of h to a maximum of .An m-Way search tree of n elements ranges from a minimum height of log_m(n+1) to a maximum of nAn example of a 5-Way search tree is shown in the figure below. Observe how each node has at most 5 child nodes & therefore has at most 4 keys contained in it. " }, { "code": null, "e": 872, "s": 813, "text": "The structure of a node of an m-Way tree is given below: " }, { "code": null, "e": 876, "s": 872, "text": "C++" }, { "code": null, "e": 881, "s": 876, "text": "Java" }, { "code": null, "e": 889, "s": 881, "text": "Python3" }, { "code": null, "e": 892, "s": 889, "text": "C#" }, { "code": "struct node { int count; int value[MAX + 1]; struct node* child[MAX + 1];};", "e": 977, "s": 892, "text": null }, { "code": "public class Node { int count; int[] value = new int[MAX + 1]; Node[] child = new Node[MAX + 1];} // This code is contributed by tapeshdua420.", "e": 1129, "s": 977, "text": null }, { "code": "class node: def __init__(self): self.count = -1 self.value = [-1]*(MAX + 1) self.child = [None]*(MAX + 1)", "e": 1259, "s": 1129, "text": null }, { "code": "class node { public int count; public int[] value = new int[MAX + 1]; public node[] child = new node[MAX + 1];} // This code is contributed by Tapesh (tapeshdua420)", "e": 1433, "s": 1259, "text": null }, { "code": null, "e": 1506, "s": 1433, "text": "Here, count represents the number of children that a particular node has" }, { "code": null, "e": 1553, "s": 1506, "text": "The values of a node stored in the array value" }, { "code": null, "e": 1612, "s": 1553, "text": "The addresses of child nodes are stored in the child array" }, { "code": null, "e": 1700, "s": 1612, "text": "The MAX macro signifies the maximum number of values that a particular node can contain" }, { "code": null, "e": 1737, "s": 1700, "text": "Searching in an m-Way search tree: " }, { "code": null, "e": 1822, "s": 1737, "text": "Searching for a key in an m-Way search tree is similar to that of binary search tree" }, { "code": null, "e": 1956, "s": 1822, "text": "To search for 77 in the 5-Way search tree, shown in the figure, we begin at the root & as 77> 76> 44> 18, move to the fourth sub-tree" }, { "code": null, "e": 2154, "s": 1956, "text": "In the root node of the fourth sub-tree, 77< 80 & therefore we move to the first sub-tree of the node. Since 77 is available in the only node of this sub-tree, we claim 77 was successfully searched" }, { "code": null, "e": 2162, "s": 2158, "text": "C++" }, { "code": null, "e": 2167, "s": 2162, "text": "Java" }, { "code": null, "e": 2175, "s": 2167, "text": "Python3" }, { "code": null, "e": 2178, "s": 2175, "text": "C#" }, { "code": "// Searches value in the nodestruct node* search(int val, struct node* root, int* pos){ // if root is Null then return if (root == NULL) return NULL; else { // if node is found if (searchnode(val, root, pos)) return root; // if not then search in child nodes else return search(val, root->child[*pos], pos); }} // Searches the nodeint searchnode(int val, struct node* n, int* pos){ // if val is less than node->value[1] if (val < n->value[1]) { *pos = 0; return 0; } // if the val is greater else { *pos = n->count; // check in the child array // for correct position while ((val < n->value[*pos]) && *pos > 1) (*pos)--; if (val == n->value[*pos]) return 1; else return 0; }}", "e": 3165, "s": 2178, "text": null }, { "code": "// Searches value in the nodepublic Node search(int val, Node root, int pos) { // if root is Null then return if (root == null) return null; else { // if node is found if (searchnode(val, root, pos)) return root; // if not then search in child nodes else return search(val, root.child[pos], pos); }} // Searches the nodepublic boolean searchnode(int val, Node n, int pos) { // if val is less than node.value[1] if (val < n.value[1]) { pos = 0; return false; } // if the val is greater else { pos = n.count; // check in the child array // for correct position while ((val < n.value[pos]) && pos > 1) pos--; if (val == n.value[pos]) return true; else return false; }} // This code is contributed by Tapesh(tapeshdua420)", "e": 4095, "s": 3165, "text": null }, { "code": "# Searches value in the nodedef search(val, root, pos): # if root is None then return if (root == None): return None else : # if node is found if (searchnode(val, root, pos)): return root # if not then search in child nodes else: return search(val, root.child[pos], pos) # Searches the nodedef searchnode(val, n, pos): # if val is less than node.value[1] if (val < n.value[1]): pos = 0 return 0 # if the val is greater else : pos = n.count # check in the child array # for correct position while ((val < n.value[pos]) and pos > 1): pos-=1 if (val == n.value[pos]): return 1 else: return 0 ", "e": 4870, "s": 4095, "text": null }, { "code": "// Searches value in the nodepublic Node search(int val, Node root, int pos){ // if root is Null then return if (root == null) return null; else { // if node is found if (searchnode(val, root, pos)) return root; // if not then search in child nodes else return search(val, root.child[pos], pos); }} // Searches the nodepublic bool searchnode(int val, Node n, int pos){ // if val is less than node.value[1] if (val < n.value[1]) { pos = 0; return false; } // if the val is greater else { pos = n.count; // check in the child array // for correct position while ((val < n.value[pos]) && pos > 1) pos--; if (val == n.value[pos]) return true; else return false; }} // This code is contributed by Tapesh (tapeshdua420)", "e": 5764, "s": 4870, "text": null }, { "code": null, "e": 5776, "s": 5764, "text": "search(): " }, { "code": null, "e": 5824, "s": 5776, "text": "The function search() receives three parameters" }, { "code": null, "e": 6046, "s": 5824, "text": "The first parameter is the value to be searched, second is the address of the node from where the search is to be performed and third is the address of a variable that is used to store the position of the value once found" }, { "code": null, "e": 6134, "s": 6046, "text": "Initially a condition is checked whether the address of the node being searched is NULL" }, { "code": null, "e": 6181, "s": 6134, "text": "If it is, then simply a NULL value is returned" }, { "code": null, "e": 6266, "s": 6181, "text": "Otherwise, a function searchnode() is called which actually searches the given value" }, { "code": null, "e": 6358, "s": 6266, "text": "If the search is successful the address of the node in which the value is found is returned" }, { "code": null, "e": 6477, "s": 6358, "text": "If the search is unsuccessful then a recursive call is made to the search() function for the child of the current node" }, { "code": null, "e": 6493, "s": 6477, "text": "searchnode(): " }, { "code": null, "e": 6545, "s": 6493, "text": "The function searchnode() receives three parameters" }, { "code": null, "e": 6601, "s": 6545, "text": "The first parameter is the value that is to be searched" }, { "code": null, "e": 6813, "s": 6601, "text": "The second parameter is the address of the node in which the search is to be performed and third is a pointer pos that holds the address of a variable in which the position of the value that once found is stored" }, { "code": null, "e": 6901, "s": 6813, "text": "This function returns a value 0 if the search is unsuccessful and 1 if it is successful" }, { "code": null, "e": 7029, "s": 6901, "text": "In this function initially it is checked whether the value that is to be searched is less than the very first value of the node" }, { "code": null, "e": 7227, "s": 7029, "text": "If it is then it indicates that the value is not present in the current node. Hence, a value 0 is assigned in the variable that is pointed to by pos and 0 is returned, as the search is unsuccessful" }, { "code": null, "e": 7245, "s": 7229, "text": "amartyaghoshgfg" }, { "code": null, "e": 7258, "s": 7245, "text": "tapeshdua420" }, { "code": null, "e": 7274, "s": 7258, "text": "Data Structures" }, { "code": null, "e": 7284, "s": 7274, "text": "Searching" }, { "code": null, "e": 7289, "s": 7284, "text": "Tree" }, { "code": null, "e": 7305, "s": 7289, "text": "Data Structures" }, { "code": null, "e": 7315, "s": 7305, "text": "Searching" }, { "code": null, "e": 7320, "s": 7315, "text": "Tree" } ]
Handling large numbers in C++?
In C++, we can use large numbers by using the boost library. This C++ boost library is widely used library. This is used for different sections. It has large domain of applications. For example, using boost, we can use large number like 264 in C++. Here we will see some examples of boost library. We can use big integer datatype. We can use different datatypes like int128_t, int256_t, int1024_t etc. By using this we can get precision up to 1024 easily. At first we are multiplying two huge number using boost library. #include<iostream> #include <boost/multiprecision/cpp_int.hpp> using namespace boost::multiprecision; using namespace std; int128_t large_product(long long n1, long long n2) { int128_t ans = (int128_t) n1 * n2; return ans; } int main() { long long num1 = 98745636214564698; long long num2 = 7459874565236544789; cout << "Product of "<< num1 << " * "<< num2 << " = " << large_product(num1,num2); } Product of 98745636214564698 * 7459874565236544789 = 736630060025131838840151335215258722 Another kind of datatype is that Arbitrary Precision Datatype. So we can use any precision using cpp_int datatype. It automatically assigns precision at runtime. #include<iostream> #include <boost/multiprecision/cpp_int.hpp> using namespace boost::multiprecision; using namespace std; cpp_int large_fact(int num) { cpp_int fact = 1; for (int i=num; i>1; --i) fact *= i; return fact; } int main() { cout << "Factorial of 50: " << large_fact(50) << endl; } Factorial of 50: 30414093201713378043612608166064768844377641568960512000000000000
[ { "code": null, "e": 1311, "s": 1062, "text": "In C++, we can use large numbers by using the boost library. This C++ boost library is widely used library. This is used for different sections. It has large domain of applications. For example, using boost, we can use large number like 264 in C++." }, { "code": null, "e": 1518, "s": 1311, "text": "Here we will see some examples of boost library. We can use big integer datatype. We can use different datatypes like int128_t, int256_t, int1024_t etc. By using this we can get precision up to 1024 easily." }, { "code": null, "e": 1583, "s": 1518, "text": "At first we are multiplying two huge number using boost library." }, { "code": null, "e": 1998, "s": 1583, "text": "#include<iostream>\n#include <boost/multiprecision/cpp_int.hpp>\nusing namespace boost::multiprecision;\nusing namespace std;\nint128_t large_product(long long n1, long long n2) {\n int128_t ans = (int128_t) n1 * n2;\n return ans;\n}\nint main() {\n long long num1 = 98745636214564698;\n long long num2 = 7459874565236544789;\n cout << \"Product of \"<< num1 << \" * \"<< num2 << \" = \" <<\n large_product(num1,num2);\n}" }, { "code": null, "e": 2088, "s": 1998, "text": "Product of 98745636214564698 * 7459874565236544789 =\n736630060025131838840151335215258722" }, { "code": null, "e": 2250, "s": 2088, "text": "Another kind of datatype is that Arbitrary Precision Datatype. So we can use any precision using cpp_int datatype. It automatically assigns precision at runtime." }, { "code": null, "e": 2561, "s": 2250, "text": "#include<iostream>\n#include <boost/multiprecision/cpp_int.hpp>\nusing namespace boost::multiprecision;\nusing namespace std;\ncpp_int large_fact(int num) {\n cpp_int fact = 1;\n for (int i=num; i>1; --i)\n fact *= i;\n return fact;\n}\nint main() {\n cout << \"Factorial of 50: \" << large_fact(50) << endl;\n}" }, { "code": null, "e": 2644, "s": 2561, "text": "Factorial of 50:\n30414093201713378043612608166064768844377641568960512000000000000" } ]
ggplot2 - Multi Panel Plots
Multi panel plots mean plot creation of multiple graphs together in a single plot. We will use par() function to put multiple graphs in a single plot by passing graphical parameters mfrow and mfcol. Here we will use “AirQuality” dataset to implement multi panel plots. Let us understand the dataset first to have a look on creation of multi panel plots. This dataset includes Contains the responses of a gas multi-sensor device deployed on the field in an Italian city. Hourly responses averages are recorded along with gas concentrations references from a certified analyzer. Understand the par() function to create a dimension of required multi panel plots. > par(mfrow=c(1,2)) > # set the plotting area into a 1*2 array This creates a blank plot with dimension of 1*2. Now create the bar plot and pie chart of the mentioned dataset using following command. This same phenomenon can be achieved with the graphical parameter mfcol. The only difference between the two is that, mfrow fills in the subplot region row wise while mfcol fills it column wise. > Temperature <- airquality$Temp > Ozone <- airquality$Ozone > par(mfrow=c(2,2)) > hist(Temperature) > boxplot(Temperature, horizontal=TRUE) > hist(Ozone) > boxplot(Ozone, horizontal=TRUE) The boxplots and barplots are created in single window basically creating a multi panel plots. Same plot with a change of dimensions in par function would look as follows − par(mfcol = c(2, 2)) Print Add Notes Bookmark this page
[ { "code": null, "e": 2221, "s": 2022, "text": "Multi panel plots mean plot creation of multiple graphs together in a single plot. We will use par() function to put multiple graphs in a single plot by passing graphical parameters mfrow and mfcol." }, { "code": null, "e": 2599, "s": 2221, "text": "Here we will use “AirQuality” dataset to implement multi panel plots. Let us understand the dataset first to have a look on creation of multi panel plots. This dataset includes Contains the responses of a gas multi-sensor device deployed on the field in an Italian city. Hourly responses averages are recorded along with gas concentrations references from a certified analyzer." }, { "code": null, "e": 2682, "s": 2599, "text": "Understand the par() function to create a dimension of required multi panel plots." }, { "code": null, "e": 2746, "s": 2682, "text": "> par(mfrow=c(1,2))\n> # set the plotting area into a 1*2 array\n" }, { "code": null, "e": 2795, "s": 2746, "text": "This creates a blank plot with dimension of 1*2." }, { "code": null, "e": 2956, "s": 2795, "text": "Now create the bar plot and pie chart of the mentioned dataset using following command. This same phenomenon can be achieved with the graphical parameter mfcol." }, { "code": null, "e": 3078, "s": 2956, "text": "The only difference between the two is that, mfrow fills in the subplot region row wise while mfcol fills it column wise." }, { "code": null, "e": 3268, "s": 3078, "text": "> Temperature <- airquality$Temp\n> Ozone <- airquality$Ozone\n> par(mfrow=c(2,2))\n> hist(Temperature)\n> boxplot(Temperature, horizontal=TRUE)\n> hist(Ozone)\n> boxplot(Ozone, horizontal=TRUE)\n" }, { "code": null, "e": 3363, "s": 3268, "text": "The boxplots and barplots are created in single window basically creating a multi panel plots." }, { "code": null, "e": 3441, "s": 3363, "text": "Same plot with a change of dimensions in par function would look as follows −" }, { "code": null, "e": 3463, "s": 3441, "text": "par(mfcol = c(2, 2))\n" }, { "code": null, "e": 3470, "s": 3463, "text": " Print" }, { "code": null, "e": 3481, "s": 3470, "text": " Add Notes" } ]
Count number of triangles possible for the given sides range - GeeksforGeeks
07 Apr, 2021 Given four integers A, B, C, and D, the task is to find the number of distinct sets (X, Y, and Z) where X, Y and Z denotes the length of sides forming a valid triangle. A ≤ X ≤ B, B ≤ Y ≤ C, and C ≤ Z ≤ D.Examples: Input: A = 2, B = 3, C = 4, D = 5 Output: 7 Explanation: Possible Length of Side of Triangles are – {(2, 3, 4), (2, 4, 4), (2, 4, 5), (3, 3, 4), (3, 3, 5), (3, 4, 4) and (3, 4, 5)}Input: A = 1, B = 1, C = 2, D = 2 Output: 1 Explanation: Only possible length of sides we can choose triangle is (1, 2, 2) Naive Approach: The key observation in the problem is that, If X, Y and Z are the valid sides of a triangle and X ≤ Y ≤ Z, then sufficient conditions for these sides to form a valid triangle will be X+Y > Z.Finally, the count of the possible Z value for the given X and Y can be computed as – If X+Y is greater than D, for this case Z can be chosen from [C, D], Total possible values of Z will be (D-C+1).If X+Y is less than D and greater than C, then Z can be chosen from [C, X+Y-1].If X+Y is less than or equal to C, then we cannot choose Z as these sides will not form a valid triangle. If X+Y is greater than D, for this case Z can be chosen from [C, D], Total possible values of Z will be (D-C+1). If X+Y is less than D and greater than C, then Z can be chosen from [C, X+Y-1]. If X+Y is less than or equal to C, then we cannot choose Z as these sides will not form a valid triangle. Time Complexity: Efficient Approach: The idea is to iterate for all the possible values of A and then compute the number of possible Y and Z values possible for the given X using mathematical computations.For a given X, the value of X+Y will be in the range of . If we compute the number of possible value greater than D, then the total number of possible values of Y and Z will be – // Number of possible values of Y and Z // If num_greater is the number of possible // Y values which is greater than D Similarly, Let R and L is the upper bound and Lower Bound of the values of X+Y in the range of C and D. Then, total combinations for Y and Z will be – Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ implementation to count the// number of possible triangles// for the given sides ranges #include <bits/stdc++.h>using namespace std; // Function to count the number of// possible triangles for the given// sides rangesint count_triangles(int a, int b, int c, int d){ int ans = 0; // Iterate for every possible of x for (int x = a; x <= b; ++x) { // Range of y is [b, c] // From this range First // we will find the number // of x + y greater than d int num_greater_than_d = max(d, c + x) - max(d, b + x - 1); // For x+y greater than d // we can choose all z from [c, d] // Total permutation will be ans += num_greater_than_d * (d - c + 1); // Now we will find the number // of x+y in between the [c, d] int r = min(max(c, c + x), d) - c; int l = min(max(c, b + x - 1), d) - c; // [l, r] will be the range // from total [c, d] x+y belongs // For any r such that r = x+y // We can choose z, in the range // [c, d] only less than r, // Thus total permutation be int x1 = (r * (r + 1)) / 2; int x2 = (l * (l + 1)) / 2; ans += x1 - x2; } return ans;} // Driver Codeint main(){ int a = 2, b = 3, c = 4, d = 5; cout << count_triangles(a, b, c, d) << endl; return 0;} // Java implementation to count the// number of possible triangles// for the given sides rangesimport java.util.Scanner;import java.util.Arrays; class GFG{ // Function to count the number of// possible triangles for the given// sides rangespublic static int count_triangles(int a, int b, int c, int d){ int ans = 0; // Iterate for every possible of x for(int x = a; x <= b; ++x) { // Range of y is [b, c] // From this range First // we will find the number // of x + y greater than d int num_greater_than_d = Math.max(d, c + x) - Math.max(d, b + x - 1); // For x+y greater than d // we can choose all z from [c, d] // Total permutation will be ans += num_greater_than_d * (d - c + 1); // Now we will find the number // of x+y in between the [c, d] int r = Math.min(Math.max(c, c + x), d) - c; int l = Math.min(Math.max(c, b + x - 1), d) - c; // [l, r] will be the range // from total [c, d] x+y belongs // For any r such that r = x+y // We can choose z, in the range // [c, d] only less than r, // Thus total permutation be int x1 = (r * (r + 1)) / 2; int x2 = (l * (l + 1)) / 2; ans += x1 - x2; } return ans;} // Driver Codepublic static void main(String args[]){ int a = 2, b = 3, c = 4, d = 5; System.out.println(count_triangles(a, b, c, d));}} // This code is contributed by SoumikMondal # Python3 implementation to count # the number of possible triangles# for the given sides ranges # Function to count the number of# possible triangles for the given# sides rangesdef count_triangles(a, b, c, d): ans = 0 # Iterate for every possible of x for x in range(a, b + 1): # Range of y is [b, c] # From this range First # we will find the number # of x + y greater than d num_greater_than_d = (max(d, c + x) - max(d, b + x - 1)) # For x+y greater than d we # can choose all z from [c, d] # Total permutation will be ans = (ans + num_greater_than_d * (d - c + 1)) # Now we will find the number # of x+y in between the [c, d] r = min(max(c, c + x), d) - c; l = min(max(c, b + x - 1), d) - c; # [l, r] will be the range # from total [c, d] x+y belongs # For any r such that r = x+y # We can choose z, in the range # [c, d] only less than r, # Thus total permutation be x1 = int((r * (r + 1)) / 2) x2 = int((l * (l + 1)) / 2) ans = ans + (x1 - x2) return ans # Driver Codea = 2b = 3c = 4d = 5 print (count_triangles(a, b, c, d), end = '\n') # This code is contributed by PratikBasu // C# implementation to count the// number of possible triangles// for the given sides rangesusing System; class GFG{ // Function to count the number of// possible triangles for the given// sides rangespublic static int count_triangles(int a, int b, int c, int d){ int ans = 0; // Iterate for every possible of x for(int x = a; x <= b; ++x) { // Range of y is [b, c] // From this range First // we will find the number // of x + y greater than d int num_greater_than_d = Math.Max(d, c + x) - Math.Max(d, b + x - 1); // For x+y greater than d // we can choose all z from [c, d] // Total permutation will be ans += num_greater_than_d * (d - c + 1); // Now we will find the number // of x+y in between the [c, d] int r = Math.Min(Math.Max(c, c + x), d) - c; int l = Math.Min(Math.Max(c, b + x - 1), d) - c; // [l, r] will be the range // from total [c, d] x+y belongs // For any r such that r = x+y // We can choose z, in the range // [c, d] only less than r, // Thus total permutation be int x1 = (r * (r + 1)) / 2; int x2 = (l * (l + 1)) / 2; ans += x1 - x2; } return ans;} // Driver Codepublic static void Main(String []args){ int a = 2, b = 3, c = 4, d = 5; Console.WriteLine(count_triangles(a, b, c, d));}} // This code is contributed by gauravrajput1 <script> // JavaScript implementation to count the// number of possible triangles// for the given sides ranges // Function to count the number of// possible triangles for the given// sides rangesfunction count_triangles(a , b, c , d){ var ans = 0; // Iterate for every possible of x for(x = a; x <= b; ++x) { // Range of y is [b, c] // From this range First // we will find the number // of x + y greater than d var num_greater_than_d = Math.max(d, c + x) - Math.max(d, b + x - 1); // For x+y greater than d // we can choose all z from [c, d] // Total permutation will be ans += num_greater_than_d * (d - c + 1); // Now we will find the number // of x+y in between the [c, d] var r = Math.min(Math.max(c, c + x), d) - c; var l = Math.min(Math.max(c, b + x - 1), d) - c; // [l, r] will be the range // from total [c, d] x+y belongs // For any r such that r = x+y // We can choose z, in the range // [c, d] only less than r, // Thus total permutation be var x1 = (r * (r + 1)) / 2; var x2 = (l * (l + 1)) / 2; ans += x1 - x2; } return ans;} // Driver Code var a = 2, b = 3, c = 4, d = 5; document.write(count_triangles(a, b, c, d)); // This code contributed by shikhasingrajput </script> 7 PratikBasu SoumikMondal GauravRajput1 shikhasingrajput triangle Combinatorial Competitive Programming Geometric Greedy Mathematical Greedy Mathematical Combinatorial Geometric Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Largest number by rearranging digits of a given positive or negative number Johnson and Trotter algorithm Ways to sum to N using Natural Numbers up to K with repetitions allowed Combinations with repetitions Given number of matches played, find number of teams in tournament Practice for cracking any coding interview Competitive Programming - A Complete Guide Arrow operator -> in C/C++ with Examples Bits manipulation (Important tactics) Pairs with same Manhattan and Euclidean distance
[ { "code": null, "e": 25061, "s": 25033, "text": "\n07 Apr, 2021" }, { "code": null, "e": 25278, "s": 25061, "text": "Given four integers A, B, C, and D, the task is to find the number of distinct sets (X, Y, and Z) where X, Y and Z denotes the length of sides forming a valid triangle. A ≤ X ≤ B, B ≤ Y ≤ C, and C ≤ Z ≤ D.Examples: " }, { "code": null, "e": 25583, "s": 25278, "text": "Input: A = 2, B = 3, C = 4, D = 5 Output: 7 Explanation: Possible Length of Side of Triangles are – {(2, 3, 4), (2, 4, 4), (2, 4, 5), (3, 3, 4), (3, 3, 5), (3, 4, 4) and (3, 4, 5)}Input: A = 1, B = 1, C = 2, D = 2 Output: 1 Explanation: Only possible length of sides we can choose triangle is (1, 2, 2) " }, { "code": null, "e": 25878, "s": 25583, "text": "Naive Approach: The key observation in the problem is that, If X, Y and Z are the valid sides of a triangle and X ≤ Y ≤ Z, then sufficient conditions for these sides to form a valid triangle will be X+Y > Z.Finally, the count of the possible Z value for the given X and Y can be computed as – " }, { "code": null, "e": 26175, "s": 25878, "text": "If X+Y is greater than D, for this case Z can be chosen from [C, D], Total possible values of Z will be (D-C+1).If X+Y is less than D and greater than C, then Z can be chosen from [C, X+Y-1].If X+Y is less than or equal to C, then we cannot choose Z as these sides will not form a valid triangle." }, { "code": null, "e": 26288, "s": 26175, "text": "If X+Y is greater than D, for this case Z can be chosen from [C, D], Total possible values of Z will be (D-C+1)." }, { "code": null, "e": 26368, "s": 26288, "text": "If X+Y is less than D and greater than C, then Z can be chosen from [C, X+Y-1]." }, { "code": null, "e": 26474, "s": 26368, "text": "If X+Y is less than or equal to C, then we cannot choose Z as these sides will not form a valid triangle." }, { "code": null, "e": 26492, "s": 26474, "text": "Time Complexity: " }, { "code": null, "e": 26861, "s": 26492, "text": "Efficient Approach: The idea is to iterate for all the possible values of A and then compute the number of possible Y and Z values possible for the given X using mathematical computations.For a given X, the value of X+Y will be in the range of . If we compute the number of possible value greater than D, then the total number of possible values of Y and Z will be – " }, { "code": null, "e": 26982, "s": 26861, "text": "// Number of possible values of Y and Z\n// If num_greater is the number of possible\n// Y values which is greater than D\n" }, { "code": null, "e": 27135, "s": 26982, "text": "Similarly, Let R and L is the upper bound and Lower Bound of the values of X+Y in the range of C and D. Then, total combinations for Y and Z will be – " }, { "code": null, "e": 27187, "s": 27135, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 27191, "s": 27187, "text": "C++" }, { "code": null, "e": 27196, "s": 27191, "text": "Java" }, { "code": null, "e": 27204, "s": 27196, "text": "Python3" }, { "code": null, "e": 27207, "s": 27204, "text": "C#" }, { "code": null, "e": 27218, "s": 27207, "text": "Javascript" }, { "code": "// C++ implementation to count the// number of possible triangles// for the given sides ranges #include <bits/stdc++.h>using namespace std; // Function to count the number of// possible triangles for the given// sides rangesint count_triangles(int a, int b, int c, int d){ int ans = 0; // Iterate for every possible of x for (int x = a; x <= b; ++x) { // Range of y is [b, c] // From this range First // we will find the number // of x + y greater than d int num_greater_than_d = max(d, c + x) - max(d, b + x - 1); // For x+y greater than d // we can choose all z from [c, d] // Total permutation will be ans += num_greater_than_d * (d - c + 1); // Now we will find the number // of x+y in between the [c, d] int r = min(max(c, c + x), d) - c; int l = min(max(c, b + x - 1), d) - c; // [l, r] will be the range // from total [c, d] x+y belongs // For any r such that r = x+y // We can choose z, in the range // [c, d] only less than r, // Thus total permutation be int x1 = (r * (r + 1)) / 2; int x2 = (l * (l + 1)) / 2; ans += x1 - x2; } return ans;} // Driver Codeint main(){ int a = 2, b = 3, c = 4, d = 5; cout << count_triangles(a, b, c, d) << endl; return 0;}", "e": 28599, "s": 27218, "text": null }, { "code": "// Java implementation to count the// number of possible triangles// for the given sides rangesimport java.util.Scanner;import java.util.Arrays; class GFG{ // Function to count the number of// possible triangles for the given// sides rangespublic static int count_triangles(int a, int b, int c, int d){ int ans = 0; // Iterate for every possible of x for(int x = a; x <= b; ++x) { // Range of y is [b, c] // From this range First // we will find the number // of x + y greater than d int num_greater_than_d = Math.max(d, c + x) - Math.max(d, b + x - 1); // For x+y greater than d // we can choose all z from [c, d] // Total permutation will be ans += num_greater_than_d * (d - c + 1); // Now we will find the number // of x+y in between the [c, d] int r = Math.min(Math.max(c, c + x), d) - c; int l = Math.min(Math.max(c, b + x - 1), d) - c; // [l, r] will be the range // from total [c, d] x+y belongs // For any r such that r = x+y // We can choose z, in the range // [c, d] only less than r, // Thus total permutation be int x1 = (r * (r + 1)) / 2; int x2 = (l * (l + 1)) / 2; ans += x1 - x2; } return ans;} // Driver Codepublic static void main(String args[]){ int a = 2, b = 3, c = 4, d = 5; System.out.println(count_triangles(a, b, c, d));}} // This code is contributed by SoumikMondal", "e": 30141, "s": 28599, "text": null }, { "code": "# Python3 implementation to count # the number of possible triangles# for the given sides ranges # Function to count the number of# possible triangles for the given# sides rangesdef count_triangles(a, b, c, d): ans = 0 # Iterate for every possible of x for x in range(a, b + 1): # Range of y is [b, c] # From this range First # we will find the number # of x + y greater than d num_greater_than_d = (max(d, c + x) - max(d, b + x - 1)) # For x+y greater than d we # can choose all z from [c, d] # Total permutation will be ans = (ans + num_greater_than_d * (d - c + 1)) # Now we will find the number # of x+y in between the [c, d] r = min(max(c, c + x), d) - c; l = min(max(c, b + x - 1), d) - c; # [l, r] will be the range # from total [c, d] x+y belongs # For any r such that r = x+y # We can choose z, in the range # [c, d] only less than r, # Thus total permutation be x1 = int((r * (r + 1)) / 2) x2 = int((l * (l + 1)) / 2) ans = ans + (x1 - x2) return ans # Driver Codea = 2b = 3c = 4d = 5 print (count_triangles(a, b, c, d), end = '\\n') # This code is contributed by PratikBasu ", "e": 31460, "s": 30141, "text": null }, { "code": "// C# implementation to count the// number of possible triangles// for the given sides rangesusing System; class GFG{ // Function to count the number of// possible triangles for the given// sides rangespublic static int count_triangles(int a, int b, int c, int d){ int ans = 0; // Iterate for every possible of x for(int x = a; x <= b; ++x) { // Range of y is [b, c] // From this range First // we will find the number // of x + y greater than d int num_greater_than_d = Math.Max(d, c + x) - Math.Max(d, b + x - 1); // For x+y greater than d // we can choose all z from [c, d] // Total permutation will be ans += num_greater_than_d * (d - c + 1); // Now we will find the number // of x+y in between the [c, d] int r = Math.Min(Math.Max(c, c + x), d) - c; int l = Math.Min(Math.Max(c, b + x - 1), d) - c; // [l, r] will be the range // from total [c, d] x+y belongs // For any r such that r = x+y // We can choose z, in the range // [c, d] only less than r, // Thus total permutation be int x1 = (r * (r + 1)) / 2; int x2 = (l * (l + 1)) / 2; ans += x1 - x2; } return ans;} // Driver Codepublic static void Main(String []args){ int a = 2, b = 3, c = 4, d = 5; Console.WriteLine(count_triangles(a, b, c, d));}} // This code is contributed by gauravrajput1", "e": 32964, "s": 31460, "text": null }, { "code": "<script> // JavaScript implementation to count the// number of possible triangles// for the given sides ranges // Function to count the number of// possible triangles for the given// sides rangesfunction count_triangles(a , b, c , d){ var ans = 0; // Iterate for every possible of x for(x = a; x <= b; ++x) { // Range of y is [b, c] // From this range First // we will find the number // of x + y greater than d var num_greater_than_d = Math.max(d, c + x) - Math.max(d, b + x - 1); // For x+y greater than d // we can choose all z from [c, d] // Total permutation will be ans += num_greater_than_d * (d - c + 1); // Now we will find the number // of x+y in between the [c, d] var r = Math.min(Math.max(c, c + x), d) - c; var l = Math.min(Math.max(c, b + x - 1), d) - c; // [l, r] will be the range // from total [c, d] x+y belongs // For any r such that r = x+y // We can choose z, in the range // [c, d] only less than r, // Thus total permutation be var x1 = (r * (r + 1)) / 2; var x2 = (l * (l + 1)) / 2; ans += x1 - x2; } return ans;} // Driver Code var a = 2, b = 3, c = 4, d = 5; document.write(count_triangles(a, b, c, d)); // This code contributed by shikhasingrajput </script>", "e": 34360, "s": 32964, "text": null }, { "code": null, "e": 34362, "s": 34360, "text": "7" }, { "code": null, "e": 34375, "s": 34364, "text": "PratikBasu" }, { "code": null, "e": 34388, "s": 34375, "text": "SoumikMondal" }, { "code": null, "e": 34402, "s": 34388, "text": "GauravRajput1" }, { "code": null, "e": 34419, "s": 34402, "text": "shikhasingrajput" }, { "code": null, "e": 34428, "s": 34419, "text": "triangle" }, { "code": null, "e": 34442, "s": 34428, "text": "Combinatorial" }, { "code": null, "e": 34466, "s": 34442, "text": "Competitive Programming" }, { "code": null, "e": 34476, "s": 34466, "text": "Geometric" }, { "code": null, "e": 34483, "s": 34476, "text": "Greedy" }, { "code": null, "e": 34496, "s": 34483, "text": "Mathematical" }, { "code": null, "e": 34503, "s": 34496, "text": "Greedy" }, { "code": null, "e": 34516, "s": 34503, "text": "Mathematical" }, { "code": null, "e": 34530, "s": 34516, "text": "Combinatorial" }, { "code": null, "e": 34540, "s": 34530, "text": "Geometric" }, { "code": null, "e": 34638, "s": 34540, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34647, "s": 34638, "text": "Comments" }, { "code": null, "e": 34660, "s": 34647, "text": "Old Comments" }, { "code": null, "e": 34736, "s": 34660, "text": "Largest number by rearranging digits of a given positive or negative number" }, { "code": null, "e": 34766, "s": 34736, "text": "Johnson and Trotter algorithm" }, { "code": null, "e": 34838, "s": 34766, "text": "Ways to sum to N using Natural Numbers up to K with repetitions allowed" }, { "code": null, "e": 34868, "s": 34838, "text": "Combinations with repetitions" }, { "code": null, "e": 34935, "s": 34868, "text": "Given number of matches played, find number of teams in tournament" }, { "code": null, "e": 34978, "s": 34935, "text": "Practice for cracking any coding interview" }, { "code": null, "e": 35021, "s": 34978, "text": "Competitive Programming - A Complete Guide" }, { "code": null, "e": 35062, "s": 35021, "text": "Arrow operator -> in C/C++ with Examples" }, { "code": null, "e": 35100, "s": 35062, "text": "Bits manipulation (Important tactics)" } ]
Tree Traversals (Inorder, Preorder and Postorder) - GeeksforGeeks
30 Nov, 2021 Unlike linear data structures (Array, Linked List, Queues, Stacks, etc) which have only one logical way to traverse them, trees can be traversed in different ways. Following are the generally used ways for traversing trees. Depth First Traversals: (a) Inorder (Left, Root, Right) : 4 2 5 1 3 (b) Preorder (Root, Left, Right) : 1 2 4 5 3 (c) Postorder (Left, Right, Root) : 4 5 2 3 1Breadth-First or Level Order Traversal: 1 2 3 4 5 Please see this post for Breadth-First Traversal. Inorder Traversal (Practice): Algorithm Inorder(tree) 1. Traverse the left subtree, i.e., call Inorder(left-subtree) 2. Visit the root. 3. Traverse the right subtree, i.e., call Inorder(right-subtree) Uses of Inorder In the case of binary search trees (BST), Inorder traversal gives nodes in non-decreasing order. To get nodes of BST in non-increasing order, a variation of Inorder traversal where Inorder traversal s reversed can be used. Example: In order traversal for the above-given figure is 4 2 5 1 3. Preorder Traversal (Practice): Algorithm Preorder(tree) 1. Visit the root. 2. Traverse the left subtree, i.e., call Preorder(left-subtree) 3. Traverse the right subtree, i.e., call Preorder(right-subtree) Uses of Preorder Preorder traversal is used to create a copy of the tree. Preorder traversal is also used to get prefix expression on an expression tree. Please see http://en.wikipedia.org/wiki/Polish_notation know why prefix expressions are useful. Example: Preorder traversal for the above-given figure is 1 2 4 5 3. Postorder Traversal (Practice): Algorithm Postorder(tree) 1. Traverse the left subtree, i.e., call Postorder(left-subtree) 2. Traverse the right subtree, i.e., call Postorder(right-subtree) 3. Visit the root. Uses of Postorder Postorder traversal is used to delete the tree. Please see the question for the deletion of a tree for details. Postorder traversal is also useful to get the postfix expression of an expression tree. Please see http://en.wikipedia.org/wiki/Reverse_Polish_notation for the usage of postfix expression. Example: Postorder traversal for the above-given figure is 4 5 2 3 1. C++ C Python Java C# Javascript // C++ program for different tree traversals #include <iostream> using namespace std; /* A binary tree node has data, pointer to left child and a pointer to right child */ struct Node { int data; struct Node *left, *right; }; //Utility function to create a new tree node Node* newNode(int data) { Node* temp = new Node; temp->data = data; temp->left = temp->right = NULL; return temp; } /* Given a binary tree, print its nodes according to the "bottom-up" postorder traversal. */ void printPostorder(struct Node* node) { if (node == NULL) return; // first recur on left subtree printPostorder(node->left); // then recur on right subtree printPostorder(node->right); // now deal with the node cout << node->data << " "; } /* Given a binary tree, print its nodes in inorder*/ void printInorder(struct Node* node) { if (node == NULL) return; /* first recur on left child */ printInorder(node->left); /* then print the data of node */ cout << node->data << " "; /* now recur on right child */ printInorder(node->right); } /* Given a binary tree, print its nodes in preorder*/ void printPreorder(struct Node* node) { if (node == NULL) return; /* first print data of node */ cout << node->data << " "; /* then recur on left subtree */ printPreorder(node->left); /* now recur on right subtree */ printPreorder(node->right); } /* Driver program to test above functions*/ int main() { struct Node* root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); cout << "\nPreorder traversal of binary tree is \n"; printPreorder(root); cout << "\nInorder traversal of binary tree is \n"; printInorder(root); cout << "\nPostorder traversal of binary tree is \n"; printPostorder(root); return 0; } // C program for different tree traversals #include <stdio.h> #include <stdlib.h> /* A binary tree node has data, pointer to left child and a pointer to right child */ struct node { int data; struct node* left; struct node* right; }; /* Helper function that allocates a new node with the given data and NULL left and right pointers. */ struct node* newNode(int data) { struct node* node = (struct node*)malloc(sizeof(struct node)); node->data = data; node->left = NULL; node->right = NULL; return (node); } /* Given a binary tree, print its nodes according to the "bottom-up" postorder traversal. */ void printPostorder(struct node* node) { if (node == NULL) return; // first recur on left subtree printPostorder(node->left); // then recur on right subtree printPostorder(node->right); // now deal with the node printf("%d ", node->data); } /* Given a binary tree, print its nodes in inorder*/ void printInorder(struct node* node) { if (node == NULL) return; /* first recur on left child */ printInorder(node->left); /* then print the data of node */ printf("%d ", node->data); /* now recur on right child */ printInorder(node->right); } /* Given a binary tree, print its nodes in preorder*/ void printPreorder(struct node* node) { if (node == NULL) return; /* first print data of node */ printf("%d ", node->data); /* then recur on left subtree */ printPreorder(node->left); /* now recur on right subtree */ printPreorder(node->right); } /* Driver program to test above functions*/ int main() { struct node* root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); printf("\nPreorder traversal of binary tree is \n"); printPreorder(root); printf("\nInorder traversal of binary tree is \n"); printInorder(root); printf("\nPostorder traversal of binary tree is \n"); printPostorder(root); getchar(); return 0; } # Python program to for tree traversals # A class that represents an individual node in a # Binary Tree class Node: def __init__(self, key): self.left = None self.right = None self.val = key # A function to do inorder tree traversal def printInorder(root): if root: # First recur on left child printInorder(root.left) # then print the data of node print(root.val), # now recur on right child printInorder(root.right) # A function to do postorder tree traversal def printPostorder(root): if root: # First recur on left child printPostorder(root.left) # the recur on right child printPostorder(root.right) # now print the data of node print(root.val), # A function to do preorder tree traversal def printPreorder(root): if root: # First print the data of node print(root.val), # Then recur on left child printPreorder(root.left) # Finally recur on right child printPreorder(root.right) # Driver code root = Node(1) root.left = Node(2) root.right = Node(3) root.left.left = Node(4) root.left.right = Node(5) print "Preorder traversal of binary tree is" printPreorder(root) print "\nInorder traversal of binary tree is" printInorder(root) print "\nPostorder traversal of binary tree is" printPostorder(root) // Java program for different tree traversals /* Class containing left and right child of current node and key value*/ class Node { int key; Node left, right; public Node(int item) { key = item; left = right = null; } } class BinaryTree { // Root of Binary Tree Node root; BinaryTree() { root = null; } /* Given a binary tree, print its nodes according to the "bottom-up" postorder traversal. */ void printPostorder(Node node) { if (node == null) return; // first recur on left subtree printPostorder(node.left); // then recur on right subtree printPostorder(node.right); // now deal with the node System.out.print(node.key + " "); } /* Given a binary tree, print its nodes in inorder*/ void printInorder(Node node) { if (node == null) return; /* first recur on left child */ printInorder(node.left); /* then print the data of node */ System.out.print(node.key + " "); /* now recur on right child */ printInorder(node.right); } /* Given a binary tree, print its nodes in preorder*/ void printPreorder(Node node) { if (node == null) return; /* first print data of node */ System.out.print(node.key + " "); /* then recur on left subtree */ printPreorder(node.left); /* now recur on right subtree */ printPreorder(node.right); } // Wrappers over above recursive functions void printPostorder() { printPostorder(root); } void printInorder() { printInorder(root); } void printPreorder() { printPreorder(root); } // Driver method public static void main(String[] args) { BinaryTree tree = new BinaryTree(); tree.root = new Node(1); tree.root.left = new Node(2); tree.root.right = new Node(3); tree.root.left.left = new Node(4); tree.root.left.right = new Node(5); System.out.println( "Preorder traversal of binary tree is "); tree.printPreorder(); System.out.println( "\nInorder traversal of binary tree is "); tree.printInorder(); System.out.println( "\nPostorder traversal of binary tree is "); tree.printPostorder(); } } // C# program for different // tree traversals using System; /* Class containing left and right child of current node and key value*/ class Node { public int key; public Node left, right; public Node(int item) { key = item; left = right = null; } } class BinaryTree { // Root of Binary Tree Node root; BinaryTree() { root = null; } /* Given a binary tree, print its nodes according to the "bottom-up" postorder traversal. */ void printPostorder(Node node) { if (node == null) return; // first recur on left subtree printPostorder(node.left); // then recur on right subtree printPostorder(node.right); // now deal with the node Console.Write(node.key + " "); } /* Given a binary tree, print its nodes in inorder*/ void printInorder(Node node) { if (node == null) return; /* first recur on left child */ printInorder(node.left); /* then print the data of node */ Console.Write(node.key + " "); /* now recur on right child */ printInorder(node.right); } /* Given a binary tree, print its nodes in preorder*/ void printPreorder(Node node) { if (node == null) return; /* first print data of node */ Console.Write(node.key + " "); /* then recur on left subtree */ printPreorder(node.left); /* now recur on right subtree */ printPreorder(node.right); } // Wrappers over above recursive functions void printPostorder() { printPostorder(root); } void printInorder() { printInorder(root); } void printPreorder() { printPreorder(root); } // Driver Code static public void Main(String[] args) { BinaryTree tree = new BinaryTree(); tree.root = new Node(1); tree.root.left = new Node(2); tree.root.right = new Node(3); tree.root.left.left = new Node(4); tree.root.left.right = new Node(5); Console.WriteLine("Preorder traversal " + "of binary tree is "); tree.printPreorder(); Console.WriteLine("\nInorder traversal " + "of binary tree is "); tree.printInorder(); Console.WriteLine("\nPostorder traversal " + "of binary tree is "); tree.printPostorder(); } } // This code is contributed by Arnab Kundu <script> // javascript program for different tree traversals /* Class containing left and right child of current node and key value*/ class Node { constructor(val) { this.key = val; this.left = null; this.right = null; } } // Root of Binary Tree var root = null; /* * Given a binary tree, print its nodes according to the "bottom-up" postorder * traversal. */ function printPostorder(node) { if (node == null) return; // first recur on left subtree printPostorder(node.left); // then recur on right subtree printPostorder(node.right); // now deal with the node document.write(node.key + " "); } /* Given a binary tree, print its nodes in inorder */ function printInorder(node) { if (node == null) return; /* first recur on left child */ printInorder(node.left); /* then print the data of node */ document.write(node.key + " "); /* now recur on right child */ printInorder(node.right); } /* Given a binary tree, print its nodes in preorder */ function printPreorder(node) { if (node == null) return; /* first print data of node */ document.write(node.key + " "); /* then recur on left subtree */ printPreorder(node.left); /* now recur on right subtree */ printPreorder(node.right); } // Driver method root = new Node(1); root.left = new Node(2); root.right = new Node(3); root.left.left = new Node(4); root.left.right = new Node(5); document.write("Preorder traversal of binary tree is <br/>"); printPreorder(root); document.write("<br/>Inorder traversal of binary tree is <br/>"); printInorder(root); document.write("<br/>Postorder traversal of binary tree is <br/>"); printPostorder(root); // This code is contributed by aashish1995 </script> Output: Preorder traversal of binary tree is 1 2 4 5 3 Inorder traversal of binary tree is 4 2 5 1 3 Postorder traversal of binary tree is 4 5 2 3 1 One more example: Time Complexity: O(n) Let us see different corner cases. Complexity function T(n) — for all problems where tree traversal is involved — can be defined as:T(n) = T(k) + T(n – k – 1) + cWhere k is the number of nodes on one side of the root and n-k-1 on the other side.Let’s do an analysis of boundary conditionsCase 1: Skewed tree (One of the subtrees is empty and another subtree is non-empty )k is 0 in this case. T(n) = T(0) + T(n-1) + c T(n) = 2T(0) + T(n-2) + 2c T(n) = 3T(0) + T(n-3) + 3c T(n) = 4T(0) + T(n-4) + 4c................................................ ................................................. T(n) = (n-1)T(0) + T(1) + (n-1)c T(n) = nT(0) + (n)cValue of T(0) will be some constant say d. (traversing an empty tree will take some constants time)T(n) = n(c+d) T(n) = Θ(n) (Theta of n)Case 2: Both left and right subtrees have an equal number of nodes.T(n) = 2T(|_n/2_|) + cThis recursive function is in the standard form (T(n) = aT(n/b) + (-)(n) ) for master method http://en.wikipedia.org/wiki/Master_theorem. If we solve it by master method we get (-)(n) Auxiliary Space: If we don’t consider the size of the stack for function calls then O(1) otherwise O(h) where h is the height of the tree. The height of the skewed tree is n (no. of elements) so the worst space complexity is O(n) and height is (Log n) for the balanced tree so the best space complexity is O(Log n). YouTubeGeeksforGeeks500K subscribersTree Traversals | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 8:55•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=IpyCqRmaKW4" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> danielbritten andrew1234 sapcastic ac2147020 aashish1995 khushboogoyal499 gabaa406 pujasingg43 pranjaypoddar Inorder Traversal PostOrder Traversal Preorder Traversal Snapdeal tree-traversal Trees Articles Tree Snapdeal Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments SQL | Join (Inner, Left, Right and Full Joins) find command in Linux with examples Analysis of Algorithms | Set 1 (Asymptotic Analysis) Mutex vs Semaphore Time Complexity and Space Complexity Level Order Binary Tree Traversal AVL Tree | Set 1 (Insertion) Decision Tree Write a Program to Find the Maximum Depth or Height of a Tree Complexity of different operations in Binary tree, Binary Search Tree and AVL tree
[ { "code": null, "e": 29781, "s": 29750, "text": " \n30 Nov, 2021\n" }, { "code": null, "e": 30005, "s": 29781, "text": "Unlike linear data structures (Array, Linked List, Queues, Stacks, etc) which have only one logical way to traverse them, trees can be traversed in different ways. Following are the generally used ways for traversing trees." }, { "code": null, "e": 30263, "s": 30005, "text": "Depth First Traversals: (a) Inorder (Left, Root, Right) : 4 2 5 1 3 (b) Preorder (Root, Left, Right) : 1 2 4 5 3 (c) Postorder (Left, Right, Root) : 4 5 2 3 1Breadth-First or Level Order Traversal: 1 2 3 4 5 Please see this post for Breadth-First Traversal." }, { "code": null, "e": 30294, "s": 30263, "text": "Inorder Traversal (Practice): " }, { "code": null, "e": 30474, "s": 30294, "text": "Algorithm Inorder(tree)\n 1. Traverse the left subtree, i.e., call Inorder(left-subtree)\n 2. Visit the root.\n 3. Traverse the right subtree, i.e., call Inorder(right-subtree)" }, { "code": null, "e": 30782, "s": 30474, "text": "Uses of Inorder In the case of binary search trees (BST), Inorder traversal gives nodes in non-decreasing order. To get nodes of BST in non-increasing order, a variation of Inorder traversal where Inorder traversal s reversed can be used. Example: In order traversal for the above-given figure is 4 2 5 1 3." }, { "code": null, "e": 30814, "s": 30782, "text": "Preorder Traversal (Practice): " }, { "code": null, "e": 30998, "s": 30814, "text": "Algorithm Preorder(tree)\n 1. Visit the root.\n 2. Traverse the left subtree, i.e., call Preorder(left-subtree)\n 3. Traverse the right subtree, i.e., call Preorder(right-subtree) " }, { "code": null, "e": 31317, "s": 30998, "text": "Uses of Preorder Preorder traversal is used to create a copy of the tree. Preorder traversal is also used to get prefix expression on an expression tree. Please see http://en.wikipedia.org/wiki/Polish_notation know why prefix expressions are useful. Example: Preorder traversal for the above-given figure is 1 2 4 5 3." }, { "code": null, "e": 31350, "s": 31317, "text": "Postorder Traversal (Practice): " }, { "code": null, "e": 31536, "s": 31350, "text": "Algorithm Postorder(tree)\n 1. Traverse the left subtree, i.e., call Postorder(left-subtree)\n 2. Traverse the right subtree, i.e., call Postorder(right-subtree)\n 3. Visit the root." }, { "code": null, "e": 31855, "s": 31536, "text": "Uses of Postorder Postorder traversal is used to delete the tree. Please see the question for the deletion of a tree for details. Postorder traversal is also useful to get the postfix expression of an expression tree. Please see http://en.wikipedia.org/wiki/Reverse_Polish_notation for the usage of postfix expression." }, { "code": null, "e": 31925, "s": 31855, "text": "Example: Postorder traversal for the above-given figure is 4 5 2 3 1." }, { "code": null, "e": 31929, "s": 31925, "text": "C++" }, { "code": null, "e": 31931, "s": 31929, "text": "C" }, { "code": null, "e": 31938, "s": 31931, "text": "Python" }, { "code": null, "e": 31943, "s": 31938, "text": "Java" }, { "code": null, "e": 31946, "s": 31943, "text": "C#" }, { "code": null, "e": 31957, "s": 31946, "text": "Javascript" }, { "code": "\n\n\n\n\n\n\n// C++ program for different tree traversals\n#include <iostream>\nusing namespace std;\n \n/* A binary tree node has data, pointer to left child\nand a pointer to right child */\nstruct Node {\n int data;\n struct Node *left, *right;\n};\n \n//Utility function to create a new tree node\nNode* newNode(int data)\n{\n Node* temp = new Node;\n temp->data = data;\n temp->left = temp->right = NULL;\n return temp;\n}\n \n/* Given a binary tree, print its nodes according to the\n\"bottom-up\" postorder traversal. */\nvoid printPostorder(struct Node* node)\n{\n if (node == NULL)\n return;\n \n // first recur on left subtree\n printPostorder(node->left);\n \n // then recur on right subtree\n printPostorder(node->right);\n \n // now deal with the node\n cout << node->data << \" \";\n}\n \n/* Given a binary tree, print its nodes in inorder*/\nvoid printInorder(struct Node* node)\n{\n if (node == NULL)\n return;\n \n /* first recur on left child */\n printInorder(node->left);\n \n /* then print the data of node */\n cout << node->data << \" \";\n \n /* now recur on right child */\n printInorder(node->right);\n}\n \n/* Given a binary tree, print its nodes in preorder*/\nvoid printPreorder(struct Node* node)\n{\n if (node == NULL)\n return;\n \n /* first print data of node */\n cout << node->data << \" \";\n \n /* then recur on left subtree */\n printPreorder(node->left);\n \n /* now recur on right subtree */\n printPreorder(node->right);\n}\n \n/* Driver program to test above functions*/\nint main()\n{\n struct Node* root = newNode(1);\n root->left = newNode(2);\n root->right = newNode(3);\n root->left->left = newNode(4);\n root->left->right = newNode(5);\n \n cout << \"\\nPreorder traversal of binary tree is \\n\";\n printPreorder(root);\n \n cout << \"\\nInorder traversal of binary tree is \\n\";\n printInorder(root);\n \n cout << \"\\nPostorder traversal of binary tree is \\n\";\n printPostorder(root);\n \n return 0;\n}\n\n\n\n\n\n", "e": 33954, "s": 31967, "text": null }, { "code": "\n\n\n\n\n\n\n// C program for different tree traversals\n#include <stdio.h>\n#include <stdlib.h>\n \n/* A binary tree node has data, pointer to left child\n and a pointer to right child */\nstruct node {\n int data;\n struct node* left;\n struct node* right;\n};\n \n/* Helper function that allocates a new node with the\n given data and NULL left and right pointers. */\nstruct node* newNode(int data)\n{\n struct node* node\n = (struct node*)malloc(sizeof(struct node));\n node->data = data;\n node->left = NULL;\n node->right = NULL;\n \n return (node);\n}\n \n/* Given a binary tree, print its nodes according to the\n \"bottom-up\" postorder traversal. */\nvoid printPostorder(struct node* node)\n{\n if (node == NULL)\n return;\n \n // first recur on left subtree\n printPostorder(node->left);\n \n // then recur on right subtree\n printPostorder(node->right);\n \n // now deal with the node\n printf(\"%d \", node->data);\n}\n \n/* Given a binary tree, print its nodes in inorder*/\nvoid printInorder(struct node* node)\n{\n if (node == NULL)\n return;\n \n /* first recur on left child */\n printInorder(node->left);\n \n /* then print the data of node */\n printf(\"%d \", node->data);\n \n /* now recur on right child */\n printInorder(node->right);\n}\n \n/* Given a binary tree, print its nodes in preorder*/\nvoid printPreorder(struct node* node)\n{\n if (node == NULL)\n return;\n \n /* first print data of node */\n printf(\"%d \", node->data);\n \n /* then recur on left subtree */\n printPreorder(node->left);\n \n /* now recur on right subtree */\n printPreorder(node->right);\n}\n \n/* Driver program to test above functions*/\nint main()\n{\n struct node* root = newNode(1);\n root->left = newNode(2);\n root->right = newNode(3);\n root->left->left = newNode(4);\n root->left->right = newNode(5);\n \n printf(\"\\nPreorder traversal of binary tree is \\n\");\n printPreorder(root);\n \n printf(\"\\nInorder traversal of binary tree is \\n\");\n printInorder(root);\n \n printf(\"\\nPostorder traversal of binary tree is \\n\");\n printPostorder(root);\n \n getchar();\n return 0;\n}\n\n\n\n\n\n", "e": 36112, "s": 33964, "text": null }, { "code": "\n\n\n\n\n\n\n# Python program to for tree traversals\n \n# A class that represents an individual node in a\n# Binary Tree\n \n \nclass Node:\n def __init__(self, key):\n self.left = None\n self.right = None\n self.val = key\n \n \n# A function to do inorder tree traversal\ndef printInorder(root):\n \n if root:\n \n # First recur on left child\n printInorder(root.left)\n \n # then print the data of node\n print(root.val),\n \n # now recur on right child\n printInorder(root.right)\n \n \n# A function to do postorder tree traversal\ndef printPostorder(root):\n \n if root:\n \n # First recur on left child\n printPostorder(root.left)\n \n # the recur on right child\n printPostorder(root.right)\n \n # now print the data of node\n print(root.val),\n \n \n# A function to do preorder tree traversal\ndef printPreorder(root):\n \n if root:\n \n # First print the data of node\n print(root.val),\n \n # Then recur on left child\n printPreorder(root.left)\n \n # Finally recur on right child\n printPreorder(root.right)\n \n \n# Driver code\nroot = Node(1)\nroot.left = Node(2)\nroot.right = Node(3)\nroot.left.left = Node(4)\nroot.left.right = Node(5)\nprint \"Preorder traversal of binary tree is\"\nprintPreorder(root)\n \nprint \"\\nInorder traversal of binary tree is\"\nprintInorder(root)\n \nprint \"\\nPostorder traversal of binary tree is\"\nprintPostorder(root)\n\n\n\n\n\n", "e": 37573, "s": 36122, "text": null }, { "code": "\n\n\n\n\n\n\n// Java program for different tree traversals\n \n/* Class containing left and right child of current\n node and key value*/\nclass Node {\n int key;\n Node left, right;\n \n public Node(int item)\n {\n key = item;\n left = right = null;\n }\n}\n \nclass BinaryTree {\n // Root of Binary Tree\n Node root;\n \n BinaryTree() { root = null; }\n \n /* Given a binary tree, print its nodes according to the\n \"bottom-up\" postorder traversal. */\n void printPostorder(Node node)\n {\n if (node == null)\n return;\n \n // first recur on left subtree\n printPostorder(node.left);\n \n // then recur on right subtree\n printPostorder(node.right);\n \n // now deal with the node\n System.out.print(node.key + \" \");\n }\n \n /* Given a binary tree, print its nodes in inorder*/\n void printInorder(Node node)\n {\n if (node == null)\n return;\n \n /* first recur on left child */\n printInorder(node.left);\n \n /* then print the data of node */\n System.out.print(node.key + \" \");\n \n /* now recur on right child */\n printInorder(node.right);\n }\n \n /* Given a binary tree, print its nodes in preorder*/\n void printPreorder(Node node)\n {\n if (node == null)\n return;\n \n /* first print data of node */\n System.out.print(node.key + \" \");\n \n /* then recur on left subtree */\n printPreorder(node.left);\n \n /* now recur on right subtree */\n printPreorder(node.right);\n }\n \n // Wrappers over above recursive functions\n void printPostorder() { printPostorder(root); }\n void printInorder() { printInorder(root); }\n void printPreorder() { printPreorder(root); }\n \n // Driver method\n public static void main(String[] args)\n {\n BinaryTree tree = new BinaryTree();\n tree.root = new Node(1);\n tree.root.left = new Node(2);\n tree.root.right = new Node(3);\n tree.root.left.left = new Node(4);\n tree.root.left.right = new Node(5);\n \n System.out.println(\n \"Preorder traversal of binary tree is \");\n tree.printPreorder();\n \n System.out.println(\n \"\\nInorder traversal of binary tree is \");\n tree.printInorder();\n \n System.out.println(\n \"\\nPostorder traversal of binary tree is \");\n tree.printPostorder();\n }\n}\n\n\n\n\n\n", "e": 40029, "s": 37583, "text": null }, { "code": "\n\n\n\n\n\n\n// C# program for different\n// tree traversals\nusing System;\n \n/* Class containing left and\nright child of current\nnode and key value*/\nclass Node {\n public int key;\n public Node left, right;\n \n public Node(int item)\n {\n key = item;\n left = right = null;\n }\n}\n \nclass BinaryTree {\n // Root of Binary Tree\n Node root;\n \n BinaryTree() { root = null; }\n \n /* Given a binary tree, print\n its nodes according to the\n \"bottom-up\" postorder traversal. */\n void printPostorder(Node node)\n {\n if (node == null)\n return;\n \n // first recur on left subtree\n printPostorder(node.left);\n \n // then recur on right subtree\n printPostorder(node.right);\n \n // now deal with the node\n Console.Write(node.key + \" \");\n }\n \n /* Given a binary tree, print\n its nodes in inorder*/\n void printInorder(Node node)\n {\n if (node == null)\n return;\n \n /* first recur on left child */\n printInorder(node.left);\n \n /* then print the data of node */\n Console.Write(node.key + \" \");\n \n /* now recur on right child */\n printInorder(node.right);\n }\n \n /* Given a binary tree, print\n its nodes in preorder*/\n void printPreorder(Node node)\n {\n if (node == null)\n return;\n \n /* first print data of node */\n Console.Write(node.key + \" \");\n \n /* then recur on left subtree */\n printPreorder(node.left);\n \n /* now recur on right subtree */\n printPreorder(node.right);\n }\n \n // Wrappers over above recursive functions\n void printPostorder() { printPostorder(root); }\n void printInorder() { printInorder(root); }\n void printPreorder() { printPreorder(root); }\n \n // Driver Code\n static public void Main(String[] args)\n {\n BinaryTree tree = new BinaryTree();\n tree.root = new Node(1);\n tree.root.left = new Node(2);\n tree.root.right = new Node(3);\n tree.root.left.left = new Node(4);\n tree.root.left.right = new Node(5);\n \n Console.WriteLine(\"Preorder traversal \"\n + \"of binary tree is \");\n tree.printPreorder();\n \n Console.WriteLine(\"\\nInorder traversal \"\n + \"of binary tree is \");\n tree.printInorder();\n \n Console.WriteLine(\"\\nPostorder traversal \"\n + \"of binary tree is \");\n tree.printPostorder();\n }\n}\n \n// This code is contributed by Arnab Kundu\n\n\n\n\n\n", "e": 42618, "s": 40039, "text": null }, { "code": "\n\n\n\n\n\n\n<script>\n// javascript program for different tree traversals\n \n/* Class containing left and right child of current\n node and key value*/\nclass Node {\n constructor(val) {\n this.key = val;\n this.left = null;\n this.right = null;\n }\n}\n \n // Root of Binary Tree\n var root = null;\n \n \n /*\n * Given a binary tree, print its nodes according to the \"bottom-up\" postorder\n * traversal.\n */\n function printPostorder(node) {\n if (node == null)\n return;\n \n // first recur on left subtree\n printPostorder(node.left);\n \n // then recur on right subtree\n printPostorder(node.right);\n \n // now deal with the node\n document.write(node.key + \" \");\n }\n \n /* Given a binary tree, print its nodes in inorder */\n function printInorder(node) {\n if (node == null)\n return;\n \n /* first recur on left child */\n printInorder(node.left);\n \n /* then print the data of node */\n document.write(node.key + \" \");\n \n /* now recur on right child */\n printInorder(node.right);\n }\n \n /* Given a binary tree, print its nodes in preorder */\n function printPreorder(node) {\n if (node == null)\n return;\n \n /* first print data of node */\n document.write(node.key + \" \");\n \n /* then recur on left subtree */\n printPreorder(node.left);\n \n /* now recur on right subtree */\n printPreorder(node.right);\n \n }\n \n \n \n // Driver method\n \n \n root = new Node(1);\n root.left = new Node(2);\n root.right = new Node(3);\n root.left.left = new Node(4);\n root.left.right = new Node(5);\n \n document.write(\"Preorder traversal of binary tree is <br/>\");\n printPreorder(root);\n \n document.write(\"<br/>Inorder traversal of binary tree is <br/>\");\n printInorder(root);\n \n document.write(\"<br/>Postorder traversal of binary tree is <br/>\");\n printPostorder(root);\n \n// This code is contributed by aashish1995\n</script>\n\n\n\n\n\n", "e": 44744, "s": 42628, "text": null }, { "code": null, "e": 44753, "s": 44744, "text": "Output: " }, { "code": null, "e": 44896, "s": 44753, "text": "Preorder traversal of binary tree is\n1 2 4 5 3 \nInorder traversal of binary tree is\n4 2 5 1 3 \nPostorder traversal of binary tree is\n4 5 2 3 1" }, { "code": null, "e": 44915, "s": 44896, "text": "One more example: " }, { "code": null, "e": 45996, "s": 44915, "text": "Time Complexity: O(n) Let us see different corner cases. Complexity function T(n) — for all problems where tree traversal is involved — can be defined as:T(n) = T(k) + T(n – k – 1) + cWhere k is the number of nodes on one side of the root and n-k-1 on the other side.Let’s do an analysis of boundary conditionsCase 1: Skewed tree (One of the subtrees is empty and another subtree is non-empty )k is 0 in this case. T(n) = T(0) + T(n-1) + c T(n) = 2T(0) + T(n-2) + 2c T(n) = 3T(0) + T(n-3) + 3c T(n) = 4T(0) + T(n-4) + 4c................................................ ................................................. T(n) = (n-1)T(0) + T(1) + (n-1)c T(n) = nT(0) + (n)cValue of T(0) will be some constant say d. (traversing an empty tree will take some constants time)T(n) = n(c+d) T(n) = Θ(n) (Theta of n)Case 2: Both left and right subtrees have an equal number of nodes.T(n) = 2T(|_n/2_|) + cThis recursive function is in the standard form (T(n) = aT(n/b) + (-)(n) ) for master method http://en.wikipedia.org/wiki/Master_theorem. If we solve it by master method we get (-)(n)" }, { "code": null, "e": 46136, "s": 45996, "text": "Auxiliary Space: If we don’t consider the size of the stack for function calls then O(1) otherwise O(h) where h is the height of the tree. " }, { "code": null, "e": 46313, "s": 46136, "text": "The height of the skewed tree is n (no. of elements) so the worst space complexity is O(n) and height is (Log n) for the balanced tree so the best space complexity is O(Log n)." }, { "code": null, "e": 47127, "s": 46313, "text": "YouTubeGeeksforGeeks500K subscribersTree Traversals | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 8:55•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=IpyCqRmaKW4\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>" }, { "code": null, "e": 47141, "s": 47127, "text": "danielbritten" }, { "code": null, "e": 47152, "s": 47141, "text": "andrew1234" }, { "code": null, "e": 47162, "s": 47152, "text": "sapcastic" }, { "code": null, "e": 47172, "s": 47162, "text": "ac2147020" }, { "code": null, "e": 47184, "s": 47172, "text": "aashish1995" }, { "code": null, "e": 47201, "s": 47184, "text": "khushboogoyal499" }, { "code": null, "e": 47210, "s": 47201, "text": "gabaa406" }, { "code": null, "e": 47222, "s": 47210, "text": "pujasingg43" }, { "code": null, "e": 47236, "s": 47222, "text": "pranjaypoddar" }, { "code": null, "e": 47256, "s": 47236, "text": "\nInorder Traversal\n" }, { "code": null, "e": 47278, "s": 47256, "text": "\nPostOrder Traversal\n" }, { "code": null, "e": 47299, "s": 47278, "text": "\nPreorder Traversal\n" }, { "code": null, "e": 47310, "s": 47299, "text": "\nSnapdeal\n" }, { "code": null, "e": 47327, "s": 47310, "text": "\ntree-traversal\n" }, { "code": null, "e": 47335, "s": 47327, "text": "\nTrees\n" }, { "code": null, "e": 47346, "s": 47335, "text": "\nArticles\n" }, { "code": null, "e": 47353, "s": 47346, "text": "\nTree\n" }, { "code": null, "e": 47362, "s": 47353, "text": "Snapdeal" }, { "code": null, "e": 47367, "s": 47362, "text": "Tree" }, { "code": null, "e": 47572, "s": 47367, "text": "Writing code in comment? \n Please use ide.geeksforgeeks.org, \n generate link and share the link here.\n " }, { "code": null, "e": 47581, "s": 47572, "text": "Comments" }, { "code": null, "e": 47594, "s": 47581, "text": "Old Comments" }, { "code": null, "e": 47641, "s": 47594, "text": "SQL | Join (Inner, Left, Right and Full Joins)" }, { "code": null, "e": 47677, "s": 47641, "text": "find command in Linux with examples" }, { "code": null, "e": 47730, "s": 47677, "text": "Analysis of Algorithms | Set 1 (Asymptotic Analysis)" }, { "code": null, "e": 47749, "s": 47730, "text": "Mutex vs Semaphore" }, { "code": null, "e": 47786, "s": 47749, "text": "Time Complexity and Space Complexity" }, { "code": null, "e": 47820, "s": 47786, "text": "Level Order Binary Tree Traversal" }, { "code": null, "e": 47849, "s": 47820, "text": "AVL Tree | Set 1 (Insertion)" }, { "code": null, "e": 47863, "s": 47849, "text": "Decision Tree" }, { "code": null, "e": 47925, "s": 47863, "text": "Write a Program to Find the Maximum Depth or Height of a Tree" } ]
Unsupervised Sentiment Analysis. How to extract sentiment from the data... | by Rafał Wójcik | Towards Data Science
Note: full code available in github repo: github.com One of the common applications of NLP methods is sentiment analysis, where you try to extract from the data information about the emotions of the writer. Mainly, at least at the beginning, you would try to distinguish between positive and negative sentiment, eventually also neutral, or even retrieve score associated with a given opinion based only on text. There are two main approaches you could take, to teach an algorithm to distinguish between positive and negative emotions in writing — a supervised, and an unsupervised one. The first one would inquire from you to collect labeled data, and teach an algorithm (e.g. LSTM network) in a supervised manner how each word in a sequence (actually all words appearing one after another, if we talk about RNNs) corresponds to the outcome of overall sentence being negative or positive. This approach requires manually labeled data, which is often time consuming, and not always possible. Secondly, for not well exploited languages in terms of NLP, such as Polish language, there are not so many pretrained models to work with, so it’s not possible to use libraries which have already pretrained models for estimating sentiment scores for each word in a sentence. The latter approach would be an unsupervised one, and this one is an object of interest in this article. The main idea behind unsupervised learning is that you don’t give any previous assumptions and definitions to the model about the outcome of variables you feed into it — you simply insert the data (of course preprocessed before), and want the model to learn the structure of the data itself. It is extremely useful in cases when you don’t have labeled data, or you are not sure about the structure of the data, and you want to learn more about the nature of process you are analyzing, without making any previous assumptions about its outcome. Before we hop into the main part of this article, there is one more thing that could be important to mention. One of the most important ideas in recent breakthroughs both in NLP and computer vision was efficient usage of transfer learning. In the field of NLP most of transfer learning happens in a way, that some model (let it be MLP in case of Word2Vec, or transformer like BERT) is at first trained in unsupervised manner (actually fake supervised) on the data, and then fine tuned on specific task, or just used in another model to produce better quality features. Usually, it is given a fake supervised task, such as predicting word based on words that surround it, or predict surrounding words based on a given word (see: word2vec), or predict next word/sentence based on previous words/sentences (transformer models). Such training shouldn’t be thought of as directly supervised, as there is no human factor, that tells an algorithm what answer is the correct one (except human writing the sentence itself). I mention this because Word2Vec algorithm can be taught as an example of transfer learning. With that being said, we arrive at the subject of this article, which is unsupervised sentiment analysis. To make things harder, and because I’m from Poland, I’ve chosen to analyse Polish Sentiment Dataset, though this approach should also work with any language, as I didn’t make any assumptions specific to Polish language, nor use pretrained models. The dataset was collected and analyzed in a supervised approach by Szymon Płotka in this article: ermlab.com There are different approaches to this problem, which I will mention at the bottom of this article, that could probably work better, but I find it quite exciting that mine actually worked, as it’s one of these ideas that just bump into your head, and turn out to actually work without a lot of effort being put into them (which might also be worrying). The main idea behind this approach is that negative and positive words usually are surrounded by similar words. This means that if we would have movie reviews dataset, word ‘boring’ would be surrounded by the same words as word ‘tedious’, and usually such words would have somewhere close to the words such as ‘didn’t’ (like), which would also make word didn’t be similar to them. On the other hand, it would be unlikely to have happened, that word ‘tedious’ had more similar surrounding to word ‘exciting’, than to word ‘boring’. With such assumption, words could form clusters (based on similarity of their surrounding) of negative words that have similar surroundings, positive words that have similar surroundings, and some neutral words that end up between them (such as ‘movie’). It might seem not quite convincing at the beginning, and I might not be perfect explainer, but it actually turns out to be true. The perfect tool for such problem (of having words that are similar to their surrounding) is the one and only word2vec! If you haven’t heard of it before, here is a article about word2vec algorithm by Chris McCornick: medium.com And perfect tutorial by Pierre Megret, which I used in this article to train my own word embeddings: www.kaggle.com The first, the only, and the most important step in every Data Science/Machine Learning project is data preparation. Without good data quality, it is always possible to end up with a biased model, that is either not performing well according to some metric we choose(e.g. F-score on test set) or, which is harder to diagnose at the beginning, has been taught biased relations, that actually doesn’t reflect it’s availability to e.g. distinguish positive and negative emotions, but just allowed it to perform well on given data set. The cell below presents one of basic text preparation steps that I’ve chosen to use, but I didn’t include all of them, as everything is included in my repository, and I don’t want to make the article less readable. Frankly speaking, I didn’t spend a lot of time on it, and there is still plenty of space to do your own preparations, especially if you would try to implement it for languages like English, that have libraries for text normalization. For Polish language it could be really important to use tools like Morfologik, to stem the words to their basic structure, as we have a lot of different word suffixes that change the word for the model, but actually mean exactly the same thing (e.g. ‘beznadziejny’ and ‘beznadziejna’ both mean hopeless but the first one refers to a man, and the other to a woman). All the steps that I’ve chosen to include: dropping rows with missing (NaN) values, dropping duplicated rows, removing rows with rate equal to 0, as it contained some error, probably from the data gathering phase, replacing polish letters with use of unidecode package, replacing all non-alphanumeric signs, punctuation signs, and duplicated white spaces with a single white space retaining all rows with sentences with a length of at least 2 words. Another idea could be to implement spell checker, in order to prevent training too many embeddings of words, that actually mean exactly the same thing. Here is great article about spell checker that uses Word2Vec and Levenstein distance, to detect semantically most similar words: link.medium.com After cleaning the words, there were several other steps taken to prepare the data for word2vec model, all of which are included in my github repo. Main steps included most frequent bigrams of words detection and replacement with gensim’s Phrases module. All these steps and most of the hyperparameters in Word2Vec model I used were based on the Word2Vec tutorial from kaggle that I linked before. In this exercise, I used gensim’s implementation of word2vec algorithm with CBOW architecture. I trained 300 dimensional embeddings with lookup window equal to 4, negative sampling was set to 20 words, sub-sampling to 1e-5, and learning rate decayed from 0.03 to 0.0007. w2v_model = Word2Vec(min_count=3, window=4, size=300, sample=1e-5, alpha=0.03, min_alpha=0.0007, negative=20, workers=multiprocessing.cpu_count()-1) K-means clustering is a basic technique for data clustering, and it seemed most suitable for a given problem, as it takes as an input number of necessary clusters, and outputs coordinates of calculated clusters centroids (central points of discovered clusters). It is an iterative algorithm, in which in first step n random data points are chosen as coordinates of clusters centroids (where n is the number of seeked clusters), and next in every step all points are assigned to their closest centroid, based on euclidean distance. Next, new coordinates of every centroid are calculated, as mean of coordinates of all data points assigned to each centroid, and iterations are repeated till reaching minimal value of squared sum of distances between points assigned to centroids, and their centroid coordinates (which just simply means that coordinates of clusters stop to change), or number of iterations reach given limit. In the given problem I used sklearn’s implementation of K-means algorithm with 50 repeated starting points, to presumably prevent the algorithm from choosing wrong starting centroid coordinates, that would lead the algorithm to converge to not optimal clusters, and 1000 iterations of reassigning points to clusters. After running it on estimated word vectors, I got 2 centroids, with coordinates that can be retrieved with method: model.cluster_centers_ Next, to check which cluster is relatively positive, and which negative, with use of gensim’s most_similar method I checked what word vectors are most similar in terms of cosine similarity to coordinates of first cluster: word_vectors.similar_by_vector(model.cluster_centers_[0], topn=10, restrict_vocab=None) which outputs: [('pelen_profesjonalim', 0.9740794897079468), ('superszybko_supersprawnie', 0.97325599193573), ('bardzon', 0.9731361865997314), ('duzu_wybor', 0.971358060836792), ('ladne_garnki', 0.9698898196220398), ('najlpszym_porzadku', 0.9690271615982056), ('wieloma_promocjami', 0.9684171676635742), ('cudowna_wspolpraca', 0.9679782390594482), ('pelen_profesjonaliz', 0.9675517678260803), ('przyzwoicie_cenowo', 0.9674378633499146)] As you can see (if you know Polish, which I encourage you to learn if you want to have some superpowers to show off with) 10 closest words to cluster no. 0 in terms of cosine distance are the ones with positive sentiment. Some words classified to cluster 0 are even contextually positive, e.g. collocation ‘miod_malina’, which consists of words that literally mean ‘honey’ and ‘raspberry’, means that something is amazing and perfect, and it got sentiment score (inverse of distance from cluster it was assigned to, see the code in repository for details) of +1.363374. The negative cluster is harder to describe, as not all most similar words that end up closest to it’s centroid are directly negative, but when you check if words like 'hopeless’, ‘poor' or ‘broken’ are assigned to it, you get quite good results, as all of them end up where they should have. temp[temp.words.isin(['beznadziejna', 'slaba', 'zepsuty'])] gives: {'zepsuty': -1.2202580315412217, 'slaba': -1.0219668995616882, 'beznadziejna': -1.0847829796850548} It might seem tricky, that I use cosine distance to determine the sentiment of each cluster, and then euclidean distance to assign each word to a cluster, but there is no motivation behind it, I just used available methods from both libraries, and it worked. Next step, partially mentioned in the previous chapter, was to assign each word sentiment score — negative or positive value (-1 or 1) based on the cluster to which they belong. To weigh this score I multiplied it by how close they were to their cluster (to weigh how potentially positive/negative they are). As the score that K-means algorithm outputs is distance from both clusters, to properly weigh them I multiplied them by the inverse of closeness score (divided sentiment score by closeness score). With these steps being complete, there was full dictionary created (in form of pandas DataFrame), where each word had it’s own weighted sentiment score. To assess how accurate these weighted sentiment coefficients were, I randomly sampled dataframe with obtained coefficients. As you can see, for most of you probably with help of google translate, words in the table below mostly end up in the correct cluster, though I must admit that many words didn’t look so promising. Probably, the best option to correct it would be to normalize data properly or to create 3rd, neutral cluster for words that shouldn’t have any sentiment at all assigned to them, but in order to not make this project too big, I didn’t improve them, and it still worked pretty well, as you will see later. Next step was to calculate tfidf score of each word in each sentence with sklearn’s TfidfVectorizer. This step was conducted to consider how unique every word was for every sentence, and increase positive/negative signal associated with words that are highly specific for given sentence in comparison to whole corpus. Finally, all words in every sentence were on one hand replaced with their tfidf scores, and on the other with their corresponding weighted sentiment scores. Gists above and below present functions for replacing words in sentences with their associated tfidf/sentiment scores, to obtain 2 vectors for each sentence The dot product of such 2 sentence vectors indicated whether overall sentiment was positive or negative (if the dot product was positive, the sentiment was positive, and in opposite case negative). Chosen metric for evaluating model’s performance was precision, recall, and F-score, mainly because classes in dataset were highly imbalanced, but in fact, the dataset was so highly imbalanced, that I should have probably come up with a metric that would punish this imbalance even more. It turned out, that model achieved 0.99 precision, which shows that it was really good at discriminating negative sentiment observations (it almost didn’t mistake negative observations with positive ones). One could argue that it’s quite obvious that it should have, as it had very few negative observations, and they probably differed the most from others, and it’s partially true, but if you consider that the model also achieved almost 80% recall (which means that 80% of all positive observations in the dataset were correctly classified as positive), it might show, that it also learned quite a lot, and didn’t just split the data in half, with negative observations ending up in the correct cluster. If you compare these results with ones achieved by Szymon Płotka in his article, precision of unsupervised model is actually higher than his supervised model, and accuracy and recall are ~17.5 p.p. lower, though it’s hard to compare, as we used different test sets (mine consisted of full dataset, and his from 20% of original data). ╔════════════════ Confusion Matrix ══════════════╗╔═══════════╦════════════════════╦═══════════════╗║ ║ 0 ║ 1 ║╠═══════════╬════════════════════╬═══════════════╣║ 0 ║ 9523 ║ 306 ║╠═══════════╬════════════════════╬═══════════════╣║ 1 ║ 127125 ║ 508277 ║╚═══════════╩════════════════════╩═══════════════╝╔═══════════╦════════════════════╗║ Scores ║ ║╠═══════════╬════════════════════╣║ accuracy ║ 0.802503 ║║ precision ║ 0.999398 ║║ recall ║ 0.799930 ║║ F1 ║ 0.888608 ║╚═══════════╩════════════════════╝ To sum up, unsupervised approach achieved quite good results (in my opinion), as without the use of any pretrained models, and actually no previous information what is positive or negative in given text, it achieved quite high metrics, significantly higher than predicted at random. Frankly speaking, I’m quite interested in hearing from you how it worked for your datasets! This article was written mainly to present an idea about unsupervised language processing, not to create the best possible solution based on it, so there is plenty of space to improve it. Improvements that come into my mind, other than ones I already mentioned before, include: K-Means clustering based on cosine, not euclidean distances Include third, neutral cluster, or assign some words that end up somewhere between positive and negative clusters sentiment score equal to zero Hyperparameter tuning of Word2Vec algorithm, based on e.g. F1-score achieved on dataset (though it would require splitting the dataset into train and test datasets, as the training would become supervised) Not considering bi-grams of words Here we arrive at the end of this short article — I really hope you enjoyed it and look forward to hearing from you about any improvements that you came up with. I also hope that it was somehow informative to you, and thank you for reading it! All the best, and may the high F1-score be with you!
[ { "code": null, "e": 214, "s": 172, "text": "Note: full code available in github repo:" }, { "code": null, "e": 225, "s": 214, "text": "github.com" }, { "code": null, "e": 584, "s": 225, "text": "One of the common applications of NLP methods is sentiment analysis, where you try to extract from the data information about the emotions of the writer. Mainly, at least at the beginning, you would try to distinguish between positive and negative sentiment, eventually also neutral, or even retrieve score associated with a given opinion based only on text." }, { "code": null, "e": 758, "s": 584, "text": "There are two main approaches you could take, to teach an algorithm to distinguish between positive and negative emotions in writing — a supervised, and an unsupervised one." }, { "code": null, "e": 1438, "s": 758, "text": "The first one would inquire from you to collect labeled data, and teach an algorithm (e.g. LSTM network) in a supervised manner how each word in a sequence (actually all words appearing one after another, if we talk about RNNs) corresponds to the outcome of overall sentence being negative or positive. This approach requires manually labeled data, which is often time consuming, and not always possible. Secondly, for not well exploited languages in terms of NLP, such as Polish language, there are not so many pretrained models to work with, so it’s not possible to use libraries which have already pretrained models for estimating sentiment scores for each word in a sentence." }, { "code": null, "e": 2087, "s": 1438, "text": "The latter approach would be an unsupervised one, and this one is an object of interest in this article. The main idea behind unsupervised learning is that you don’t give any previous assumptions and definitions to the model about the outcome of variables you feed into it — you simply insert the data (of course preprocessed before), and want the model to learn the structure of the data itself. It is extremely useful in cases when you don’t have labeled data, or you are not sure about the structure of the data, and you want to learn more about the nature of process you are analyzing, without making any previous assumptions about its outcome." }, { "code": null, "e": 3194, "s": 2087, "text": "Before we hop into the main part of this article, there is one more thing that could be important to mention. One of the most important ideas in recent breakthroughs both in NLP and computer vision was efficient usage of transfer learning. In the field of NLP most of transfer learning happens in a way, that some model (let it be MLP in case of Word2Vec, or transformer like BERT) is at first trained in unsupervised manner (actually fake supervised) on the data, and then fine tuned on specific task, or just used in another model to produce better quality features. Usually, it is given a fake supervised task, such as predicting word based on words that surround it, or predict surrounding words based on a given word (see: word2vec), or predict next word/sentence based on previous words/sentences (transformer models). Such training shouldn’t be thought of as directly supervised, as there is no human factor, that tells an algorithm what answer is the correct one (except human writing the sentence itself). I mention this because Word2Vec algorithm can be taught as an example of transfer learning." }, { "code": null, "e": 3645, "s": 3194, "text": "With that being said, we arrive at the subject of this article, which is unsupervised sentiment analysis. To make things harder, and because I’m from Poland, I’ve chosen to analyse Polish Sentiment Dataset, though this approach should also work with any language, as I didn’t make any assumptions specific to Polish language, nor use pretrained models. The dataset was collected and analyzed in a supervised approach by Szymon Płotka in this article:" }, { "code": null, "e": 3656, "s": 3645, "text": "ermlab.com" }, { "code": null, "e": 4009, "s": 3656, "text": "There are different approaches to this problem, which I will mention at the bottom of this article, that could probably work better, but I find it quite exciting that mine actually worked, as it’s one of these ideas that just bump into your head, and turn out to actually work without a lot of effort being put into them (which might also be worrying)." }, { "code": null, "e": 4924, "s": 4009, "text": "The main idea behind this approach is that negative and positive words usually are surrounded by similar words. This means that if we would have movie reviews dataset, word ‘boring’ would be surrounded by the same words as word ‘tedious’, and usually such words would have somewhere close to the words such as ‘didn’t’ (like), which would also make word didn’t be similar to them. On the other hand, it would be unlikely to have happened, that word ‘tedious’ had more similar surrounding to word ‘exciting’, than to word ‘boring’. With such assumption, words could form clusters (based on similarity of their surrounding) of negative words that have similar surroundings, positive words that have similar surroundings, and some neutral words that end up between them (such as ‘movie’). It might seem not quite convincing at the beginning, and I might not be perfect explainer, but it actually turns out to be true." }, { "code": null, "e": 5142, "s": 4924, "text": "The perfect tool for such problem (of having words that are similar to their surrounding) is the one and only word2vec! If you haven’t heard of it before, here is a article about word2vec algorithm by Chris McCornick:" }, { "code": null, "e": 5153, "s": 5142, "text": "medium.com" }, { "code": null, "e": 5254, "s": 5153, "text": "And perfect tutorial by Pierre Megret, which I used in this article to train my own word embeddings:" }, { "code": null, "e": 5269, "s": 5254, "text": "www.kaggle.com" }, { "code": null, "e": 5801, "s": 5269, "text": "The first, the only, and the most important step in every Data Science/Machine Learning project is data preparation. Without good data quality, it is always possible to end up with a biased model, that is either not performing well according to some metric we choose(e.g. F-score on test set) or, which is harder to diagnose at the beginning, has been taught biased relations, that actually doesn’t reflect it’s availability to e.g. distinguish positive and negative emotions, but just allowed it to perform well on given data set." }, { "code": null, "e": 6615, "s": 5801, "text": "The cell below presents one of basic text preparation steps that I’ve chosen to use, but I didn’t include all of them, as everything is included in my repository, and I don’t want to make the article less readable. Frankly speaking, I didn’t spend a lot of time on it, and there is still plenty of space to do your own preparations, especially if you would try to implement it for languages like English, that have libraries for text normalization. For Polish language it could be really important to use tools like Morfologik, to stem the words to their basic structure, as we have a lot of different word suffixes that change the word for the model, but actually mean exactly the same thing (e.g. ‘beznadziejny’ and ‘beznadziejna’ both mean hopeless but the first one refers to a man, and the other to a woman)." }, { "code": null, "e": 6658, "s": 6615, "text": "All the steps that I’ve chosen to include:" }, { "code": null, "e": 6699, "s": 6658, "text": "dropping rows with missing (NaN) values," }, { "code": null, "e": 6725, "s": 6699, "text": "dropping duplicated rows," }, { "code": null, "e": 6829, "s": 6725, "text": "removing rows with rate equal to 0, as it contained some error, probably from the data gathering phase," }, { "code": null, "e": 6885, "s": 6829, "text": "replacing polish letters with use of unidecode package," }, { "code": null, "e": 6996, "s": 6885, "text": "replacing all non-alphanumeric signs, punctuation signs, and duplicated white spaces with a single white space" }, { "code": null, "e": 7065, "s": 6996, "text": "retaining all rows with sentences with a length of at least 2 words." }, { "code": null, "e": 7346, "s": 7065, "text": "Another idea could be to implement spell checker, in order to prevent training too many embeddings of words, that actually mean exactly the same thing. Here is great article about spell checker that uses Word2Vec and Levenstein distance, to detect semantically most similar words:" }, { "code": null, "e": 7362, "s": 7346, "text": "link.medium.com" }, { "code": null, "e": 7760, "s": 7362, "text": "After cleaning the words, there were several other steps taken to prepare the data for word2vec model, all of which are included in my github repo. Main steps included most frequent bigrams of words detection and replacement with gensim’s Phrases module. All these steps and most of the hyperparameters in Word2Vec model I used were based on the Word2Vec tutorial from kaggle that I linked before." }, { "code": null, "e": 8031, "s": 7760, "text": "In this exercise, I used gensim’s implementation of word2vec algorithm with CBOW architecture. I trained 300 dimensional embeddings with lookup window equal to 4, negative sampling was set to 20 words, sub-sampling to 1e-5, and learning rate decayed from 0.03 to 0.0007." }, { "code": null, "e": 8323, "s": 8031, "text": "w2v_model = Word2Vec(min_count=3, window=4, size=300, sample=1e-5, alpha=0.03, min_alpha=0.0007, negative=20, workers=multiprocessing.cpu_count()-1)" }, { "code": null, "e": 9246, "s": 8323, "text": "K-means clustering is a basic technique for data clustering, and it seemed most suitable for a given problem, as it takes as an input number of necessary clusters, and outputs coordinates of calculated clusters centroids (central points of discovered clusters). It is an iterative algorithm, in which in first step n random data points are chosen as coordinates of clusters centroids (where n is the number of seeked clusters), and next in every step all points are assigned to their closest centroid, based on euclidean distance. Next, new coordinates of every centroid are calculated, as mean of coordinates of all data points assigned to each centroid, and iterations are repeated till reaching minimal value of squared sum of distances between points assigned to centroids, and their centroid coordinates (which just simply means that coordinates of clusters stop to change), or number of iterations reach given limit." }, { "code": null, "e": 9563, "s": 9246, "text": "In the given problem I used sklearn’s implementation of K-means algorithm with 50 repeated starting points, to presumably prevent the algorithm from choosing wrong starting centroid coordinates, that would lead the algorithm to converge to not optimal clusters, and 1000 iterations of reassigning points to clusters." }, { "code": null, "e": 9678, "s": 9563, "text": "After running it on estimated word vectors, I got 2 centroids, with coordinates that can be retrieved with method:" }, { "code": null, "e": 9701, "s": 9678, "text": "model.cluster_centers_" }, { "code": null, "e": 9923, "s": 9701, "text": "Next, to check which cluster is relatively positive, and which negative, with use of gensim’s most_similar method I checked what word vectors are most similar in terms of cosine similarity to coordinates of first cluster:" }, { "code": null, "e": 10011, "s": 9923, "text": "word_vectors.similar_by_vector(model.cluster_centers_[0], topn=10, restrict_vocab=None)" }, { "code": null, "e": 10026, "s": 10011, "text": "which outputs:" }, { "code": null, "e": 10448, "s": 10026, "text": "[('pelen_profesjonalim', 0.9740794897079468), ('superszybko_supersprawnie', 0.97325599193573), ('bardzon', 0.9731361865997314), ('duzu_wybor', 0.971358060836792), ('ladne_garnki', 0.9698898196220398), ('najlpszym_porzadku', 0.9690271615982056), ('wieloma_promocjami', 0.9684171676635742), ('cudowna_wspolpraca', 0.9679782390594482), ('pelen_profesjonaliz', 0.9675517678260803), ('przyzwoicie_cenowo', 0.9674378633499146)]" }, { "code": null, "e": 11018, "s": 10448, "text": "As you can see (if you know Polish, which I encourage you to learn if you want to have some superpowers to show off with) 10 closest words to cluster no. 0 in terms of cosine distance are the ones with positive sentiment. Some words classified to cluster 0 are even contextually positive, e.g. collocation ‘miod_malina’, which consists of words that literally mean ‘honey’ and ‘raspberry’, means that something is amazing and perfect, and it got sentiment score (inverse of distance from cluster it was assigned to, see the code in repository for details) of +1.363374." }, { "code": null, "e": 11310, "s": 11018, "text": "The negative cluster is harder to describe, as not all most similar words that end up closest to it’s centroid are directly negative, but when you check if words like 'hopeless’, ‘poor' or ‘broken’ are assigned to it, you get quite good results, as all of them end up where they should have." }, { "code": null, "e": 11370, "s": 11310, "text": "temp[temp.words.isin(['beznadziejna', 'slaba', 'zepsuty'])]" }, { "code": null, "e": 11377, "s": 11370, "text": "gives:" }, { "code": null, "e": 11477, "s": 11377, "text": "{'zepsuty': -1.2202580315412217, 'slaba': -1.0219668995616882, 'beznadziejna': -1.0847829796850548}" }, { "code": null, "e": 11736, "s": 11477, "text": "It might seem tricky, that I use cosine distance to determine the sentiment of each cluster, and then euclidean distance to assign each word to a cluster, but there is no motivation behind it, I just used available methods from both libraries, and it worked." }, { "code": null, "e": 12242, "s": 11736, "text": "Next step, partially mentioned in the previous chapter, was to assign each word sentiment score — negative or positive value (-1 or 1) based on the cluster to which they belong. To weigh this score I multiplied it by how close they were to their cluster (to weigh how potentially positive/negative they are). As the score that K-means algorithm outputs is distance from both clusters, to properly weigh them I multiplied them by the inverse of closeness score (divided sentiment score by closeness score)." }, { "code": null, "e": 13021, "s": 12242, "text": "With these steps being complete, there was full dictionary created (in form of pandas DataFrame), where each word had it’s own weighted sentiment score. To assess how accurate these weighted sentiment coefficients were, I randomly sampled dataframe with obtained coefficients. As you can see, for most of you probably with help of google translate, words in the table below mostly end up in the correct cluster, though I must admit that many words didn’t look so promising. Probably, the best option to correct it would be to normalize data properly or to create 3rd, neutral cluster for words that shouldn’t have any sentiment at all assigned to them, but in order to not make this project too big, I didn’t improve them, and it still worked pretty well, as you will see later." }, { "code": null, "e": 13339, "s": 13021, "text": "Next step was to calculate tfidf score of each word in each sentence with sklearn’s TfidfVectorizer. This step was conducted to consider how unique every word was for every sentence, and increase positive/negative signal associated with words that are highly specific for given sentence in comparison to whole corpus." }, { "code": null, "e": 13496, "s": 13339, "text": "Finally, all words in every sentence were on one hand replaced with their tfidf scores, and on the other with their corresponding weighted sentiment scores." }, { "code": null, "e": 13653, "s": 13496, "text": "Gists above and below present functions for replacing words in sentences with their associated tfidf/sentiment scores, to obtain 2 vectors for each sentence" }, { "code": null, "e": 13851, "s": 13653, "text": "The dot product of such 2 sentence vectors indicated whether overall sentiment was positive or negative (if the dot product was positive, the sentiment was positive, and in opposite case negative)." }, { "code": null, "e": 15179, "s": 13851, "text": "Chosen metric for evaluating model’s performance was precision, recall, and F-score, mainly because classes in dataset were highly imbalanced, but in fact, the dataset was so highly imbalanced, that I should have probably come up with a metric that would punish this imbalance even more. It turned out, that model achieved 0.99 precision, which shows that it was really good at discriminating negative sentiment observations (it almost didn’t mistake negative observations with positive ones). One could argue that it’s quite obvious that it should have, as it had very few negative observations, and they probably differed the most from others, and it’s partially true, but if you consider that the model also achieved almost 80% recall (which means that 80% of all positive observations in the dataset were correctly classified as positive), it might show, that it also learned quite a lot, and didn’t just split the data in half, with negative observations ending up in the correct cluster. If you compare these results with ones achieved by Szymon Płotka in his article, precision of unsupervised model is actually higher than his supervised model, and accuracy and recall are ~17.5 p.p. lower, though it’s hard to compare, as we used different test sets (mine consisted of full dataset, and his from 20% of original data)." }, { "code": null, "e": 15852, "s": 15179, "text": "╔════════════════ Confusion Matrix ══════════════╗╔═══════════╦════════════════════╦═══════════════╗║ ║ 0 ║ 1 ║╠═══════════╬════════════════════╬═══════════════╣║ 0 ║ 9523 ║ 306 ║╠═══════════╬════════════════════╬═══════════════╣║ 1 ║ 127125 ║ 508277 ║╚═══════════╩════════════════════╩═══════════════╝╔═══════════╦════════════════════╗║ Scores ║ ║╠═══════════╬════════════════════╣║ accuracy ║ 0.802503 ║║ precision ║ 0.999398 ║║ recall ║ 0.799930 ║║ F1 ║ 0.888608 ║╚═══════════╩════════════════════╝" }, { "code": null, "e": 16227, "s": 15852, "text": "To sum up, unsupervised approach achieved quite good results (in my opinion), as without the use of any pretrained models, and actually no previous information what is positive or negative in given text, it achieved quite high metrics, significantly higher than predicted at random. Frankly speaking, I’m quite interested in hearing from you how it worked for your datasets!" }, { "code": null, "e": 16505, "s": 16227, "text": "This article was written mainly to present an idea about unsupervised language processing, not to create the best possible solution based on it, so there is plenty of space to improve it. Improvements that come into my mind, other than ones I already mentioned before, include:" }, { "code": null, "e": 16565, "s": 16505, "text": "K-Means clustering based on cosine, not euclidean distances" }, { "code": null, "e": 16709, "s": 16565, "text": "Include third, neutral cluster, or assign some words that end up somewhere between positive and negative clusters sentiment score equal to zero" }, { "code": null, "e": 16915, "s": 16709, "text": "Hyperparameter tuning of Word2Vec algorithm, based on e.g. F1-score achieved on dataset (though it would require splitting the dataset into train and test datasets, as the training would become supervised)" }, { "code": null, "e": 16949, "s": 16915, "text": "Not considering bi-grams of words" }, { "code": null, "e": 17193, "s": 16949, "text": "Here we arrive at the end of this short article — I really hope you enjoyed it and look forward to hearing from you about any improvements that you came up with. I also hope that it was somehow informative to you, and thank you for reading it!" } ]
Python 3 - Number randrange() Method
The randrange() method returns a randomly selected element from range(start, stop, step). Following is the syntax for the randrange() method randrange ([start,] stop [,step]) Note − This function is not accessible directly, so we need to import the random module and then we need to call this function using the random static object. start − Start point of the range. This would be included in the range. Default is 0 start − Start point of the range. This would be included in the range. Default is 0 stop − Stop point of the range. This would be included in the range. Default is 1 stop − Stop point of the range. This would be included in the range. Default is 1 step − Step point of the range. This would be excluded from the range. step − Step point of the range. This would be excluded from the range. This method returns a random item from the given range. The following example shows the usage of the randrange() method. #!/usr/bin/python3 import random # randomly select an odd number between 1-100 print ("randrange(1,100, 2) : ", random.randrange(1, 100, 2)) # randomly select a number between 0-99 print ("randrange(100) : ", random.randrange(100)) When we run the above program, it produces the following result − randrange(1,100, 2) : 83 randrange(100) : 93 187 Lectures 17.5 hours Malhar Lathkar 55 Lectures 8 hours Arnab Chakraborty 136 Lectures 11 hours In28Minutes Official 75 Lectures 13 hours Eduonix Learning Solutions 70 Lectures 8.5 hours Lets Kode It 63 Lectures 6 hours Abhilash Nelson Print Add Notes Bookmark this page
[ { "code": null, "e": 2430, "s": 2340, "text": "The randrange() method returns a randomly selected element from range(start, stop, step)." }, { "code": null, "e": 2481, "s": 2430, "text": "Following is the syntax for the randrange() method" }, { "code": null, "e": 2516, "s": 2481, "text": "randrange ([start,] stop [,step])\n" }, { "code": null, "e": 2675, "s": 2516, "text": "Note − This function is not accessible directly, so we need to import the random module and then we need to call this function using the random static object." }, { "code": null, "e": 2759, "s": 2675, "text": "start − Start point of the range. This would be included in the range. Default is 0" }, { "code": null, "e": 2843, "s": 2759, "text": "start − Start point of the range. This would be included in the range. Default is 0" }, { "code": null, "e": 2925, "s": 2843, "text": "stop − Stop point of the range. This would be included in the range. Default is 1" }, { "code": null, "e": 3007, "s": 2925, "text": "stop − Stop point of the range. This would be included in the range. Default is 1" }, { "code": null, "e": 3078, "s": 3007, "text": "step − Step point of the range. This would be excluded from the range." }, { "code": null, "e": 3149, "s": 3078, "text": "step − Step point of the range. This would be excluded from the range." }, { "code": null, "e": 3205, "s": 3149, "text": "This method returns a random item from the given range." }, { "code": null, "e": 3270, "s": 3205, "text": "The following example shows the usage of the randrange() method." }, { "code": null, "e": 3506, "s": 3270, "text": "#!/usr/bin/python3\nimport random\n\n# randomly select an odd number between 1-100 \nprint (\"randrange(1,100, 2) : \", random.randrange(1, 100, 2))\n\n# randomly select a number between 0-99 \nprint (\"randrange(100) : \", random.randrange(100))" }, { "code": null, "e": 3572, "s": 3506, "text": "When we run the above program, it produces the following result −" }, { "code": null, "e": 3620, "s": 3572, "text": "randrange(1,100, 2) : 83\nrandrange(100) : 93\n" }, { "code": null, "e": 3657, "s": 3620, "text": "\n 187 Lectures \n 17.5 hours \n" }, { "code": null, "e": 3673, "s": 3657, "text": " Malhar Lathkar" }, { "code": null, "e": 3706, "s": 3673, "text": "\n 55 Lectures \n 8 hours \n" }, { "code": null, "e": 3725, "s": 3706, "text": " Arnab Chakraborty" }, { "code": null, "e": 3760, "s": 3725, "text": "\n 136 Lectures \n 11 hours \n" }, { "code": null, "e": 3782, "s": 3760, "text": " In28Minutes Official" }, { "code": null, "e": 3816, "s": 3782, "text": "\n 75 Lectures \n 13 hours \n" }, { "code": null, "e": 3844, "s": 3816, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 3879, "s": 3844, "text": "\n 70 Lectures \n 8.5 hours \n" }, { "code": null, "e": 3893, "s": 3879, "text": " Lets Kode It" }, { "code": null, "e": 3926, "s": 3893, "text": "\n 63 Lectures \n 6 hours \n" }, { "code": null, "e": 3943, "s": 3926, "text": " Abhilash Nelson" }, { "code": null, "e": 3950, "s": 3943, "text": " Print" }, { "code": null, "e": 3961, "s": 3950, "text": " Add Notes" } ]
Find pairs of Positive and Negative values present in given array
27 Jun, 2022 Given an array of distinct integers, print all the pairs having positive value and negative value of a number that exists in the array. The pairs can be printed in any order. Examples: Input: arr[] = { 1, -3, 2, 3, 6, -1 }Output: -1 1 -3 3 Input: arr[] = { 4, 8, 9, -4, 1, -1, -8, -9 }Output: -4 4 -8 8 -9 9 -1 1 Method 1 (Simple : O(n2)) The idea is to use two nested loop. For each element arr[i], find negative of arr[i] from index i + 1 to n – 1 and store it in another array. For output, print negative positive value of the stored element. Below is the implementation of this approach: C++ Java Python 3 C# Javascript // Simple CPP program to find pairs of positive// and negative values present in an array.#include <bits/stdc++.h>using namespace std; // Print pair with negative and positive valuevoid printPairs(int arr[], int n){ vector<int> v; // For each element of array. for (int i = 0; i < n; i++) // Try to find the negative value of // arr[i] from i + 1 to n for (int j = i + 1; j < n; j++) // If absolute values are equal print pair. if (abs(arr[i]) == abs(arr[j])) v.push_back(abs(arr[i])); // If size of vector is 0, therefore there is no // element with positive negative value, print "0" if (v.size() == 0) return; // Print the pair with negative positive value. for (int i = 0; i < v.size(); i++) cout << -v[i] << " " << v[i] << " ";} // Driven Programint main(){ int arr[] = { 4, 8, 9, -4, 1, -1, -8, -9 }; int n = sizeof(arr) / sizeof(arr[0]); printPairs(arr, n); return 0;} // Java program to find pairs of positive// and negative values present in an array.import java.lang.*;import java.util.*; class GFG { // Print pair with negative and positive value public static void printPairs(int arr[], int n) { Vector<Integer> v = new Vector<Integer>(); // For each element of array. for (int i = 0; i < n; i++) // Try to find the negative value of // arr[i] from i + 1 to n for (int j = i + 1; j < n; j++) // If absolute values are equal // print pair. if (Math.abs(arr[i]) == Math.abs(arr[j])) v.add(Math.abs(arr[i])); // If size of vector is 0, therefore there // is no element with positive negative // value, print "0" if (v.size() == 0) return; // Print the pair with negative positive // value. for (int i = 0; i < v.size(); i++) System.out.print(-v.get(i) + " " + v.get(i) + " "); } // Driven Program public static void main(String[] args) { int arr[] = { 4, 8, 9, -4, 1, -1, -8, -9 }; int n = arr.length; printPairs(arr, n); }} // This code is contributed by Prasad Kshirsagar. # Simple Python 3 program to find# pairs of positive and negative# values present in an array. # Print pair with negative and# positive value def printPairs(arr, n): v = [] # For each element of array. for i in range(n): # Try to find the negative value # of arr[i] from i + 1 to n for j in range(i + 1, n): # If absolute values are # equal print pair. if (abs(arr[i]) == abs(arr[j])): v.append(abs(arr[i])) # If size of vector is 0, therefore # there is no element with positive # negative value, print "0" if (len(v) == 0): return # Print the pair with negative # positive value. for i in range(len(v)): print(-v[i], "", v[i], end=" ") # Driver Codeif __name__ == "__main__": arr = [4, 8, 9, -4, 1, -1, -8, -9] n = len(arr) printPairs(arr, n) # This code is contributed# by ChitraNayal // C# program to find pairs of positive// and negative values present in an array.using System;using System.Collections.Generic; class GFG { // Print pair with negative and positive value public static void printPairs(int[] arr, int n) { List<int> v = new List<int>(); // For each element of array. for (int i = 0; i < n; i++) // Try to find the negative value of // arr[i] from i + 1 to n for (int j = i + 1; j < n; j++) // If absolute values are equal // print pair. if (Math.Abs(arr[i]) == Math.Abs(arr[j])) v.Add(Math.Abs(arr[i])); // If size of vector is 0, therefore there // is no element with positive negative // value, print "0" if (v.Count == 0) return; // Print the pair with negative positive // value. for (int i = 0; i < v.Count; i++) Console.Write(-v[i] + " " + v[i] + " "); } // Driver code public static void Main(String[] args) { int[] arr = { 4, 8, 9, -4, 1, -1, -8, -9 }; int n = arr.Length; printPairs(arr, n); }} // This code has been contributed by 29AjayKumar <script>// Javascript program to find pairs of positive// and negative values present in an array. // Print pair with negative and positive value function printPairs(arr,n) { let v = []; // For each element of array. for (let i = 0; i < n; i++) // Try to find the negative value of // arr[i] from i + 1 to n for (let j = i + 1; j < n; j++) // If absolute values are equal // print pair. if (Math.abs(arr[i]) == Math.abs(arr[j])) v.push(Math.abs(arr[i])); // If size of vector is 0, therefore there // is no element with positive negative // value, print "0" if (v.length == 0) return; // Print the pair with negative positive // value. for (let i = 0; i < v.length; i++) document.write(-v[i] + " " + v[i] + " "); } // Driven Program let arr=[4, 8, 9, -4, 1, -1, -8, -9]; let n = arr.length; printPairs(arr, n); // This code is contributed by rag2127</script> -4 4 -8 8 -9 9 -1 1 Time Complexity: O(n*n)Auxiliary Space : O(n) Method 2 (Hashing) The idea is to use hashing. Traverse the given array, increase the count at absolute value of hash table. If count becomes 2, store its absolute value in another vector. If the size of the vector is 0, print “0”, else for each term in vector print first its negative value and the positive value. Below is the implementation of this approach: C++ Java Python3 C# Javascript // Efficient CPP program to find pairs of// positive and negative values present in// an array.#include <bits/stdc++.h>using namespace std;// Print pair with negative and positive valuevoid printPairs(int arr[], int n){ vector<int> v; unordered_map<int, bool> cnt; // For each element of array. for (int i = 0; i < n; i++) { // If element has not encounter early, // mark it on cnt array. if (cnt[abs(arr[i])] == 0) cnt[abs(arr[i])] = 1; // If seen before, push it in vector ( // given that elements are distinct) else { v.push_back(abs(arr[i])); cnt[abs(arr[i])] = 0; } } if (v.size() == 0) return; for (int i = 0; i < v.size(); i++) cout << "-" << v[i] << " " << v[i] << " ";} // Driven Programint main(){ int arr[] = { 4, 8, 9, -4, 1, -1, -8, -9 }; int n = sizeof(arr) / sizeof(arr[0]); printPairs(arr, n); return 0;} // Efficient Java program to find pairs of// positive and negative values present in// an array.import java.util.*;class GFG { // Print pair with negative // and positive value static void printPairs(int arr[], int n) { ArrayList<Integer> v = new ArrayList<Integer>(); HashMap<Integer, Integer> cnt = new HashMap<Integer, Integer>(); // For each element of array. for (int i = 0; i < n; i++) { // If element has encounter early, // then increment its count if (cnt.containsKey(Math.abs(arr[i]))) cnt.put(Math.abs(arr[i]), cnt.get(Math.abs(arr[i])) + 1); // If element has not seen before, // then initialize its count to 1 else { cnt.put(Math.abs(arr[i]), 1); } if (cnt.get(Math.abs(arr[i])) == 2) { v.add(Math.abs(arr[i])); } } if (v.size() == 0) return; for (int i = 0; i < v.size(); i++) System.out.print("-" + v.get(i) + " " + v.get(i) + " "); } // Driver Code public static void main(String[] args) { int arr[] = { 4, 8, 9, -4, 1, -1, -8, -9 }; int n = arr.length; printPairs(arr, n); }}// This code is contributed by Prerna Saini # Efficient Python3 program to find pairs of# positive and negative values present in# an array.# Print pair with negative and# positive value def printPairs(arr, n): s = set()ret = [] # For each element of array.for i in arr:if abs(i) in s:ret.append(abs(i))else:s.add(abs(i)) ret.sort() for i in range(0, len(ret)):print(-ret[i], "", ret[i], end=" ")# Driver Codeif __name__ == "__main__": arr = [4, 8, 9, -4, 1, -1, -8, -9]n = len(arr) printPairs(arr, n)# This code is contributed by RohitOberoi // Efficient C# program to find pairs of// positive and negative values present in// an array.using System;using System.Collections.Generic;class GFG { // Print pair with negative and positive value static void printPairs(int[] arr, int n) { List<int> v = new List<int>(); Dictionary<int, bool> cnt = new Dictionary<int, bool>(); // For each element of array. for (int i = 0; i < n; i++) { // If element has not encounter early, // mark it on cnt array. int absVal = Math.Abs(arr[i]); if (!cnt.ContainsKey(absVal)) { cnt[absVal] = true; } else if (cnt[absVal] == false) { cnt[absVal] = true; } else { v.Add(Math.Abs(arr[i])); cnt[absVal] = false; } } if (v.Count == 0) return; v.Sort(); for (int i = 0; i < v.Count; i++) Console.Write(-v[i] + " " + v[i] + " "); } // Driver code static void Main() { int[] arr = { 4, 8, 9, -4, 1, -1, -8, -9 }; int n = arr.Length; printPairs(arr, n); }}// This code is contributed by divyeshrabadiya07 <script>// Efficient JavaScript program to find pairs of// positive and negative values present in// an array.// Print pair with negative and positive valuefunction printPairs(arr,n){let v = new Array();let cnt = new Map();// For each element of array.for (let i = 0; i < n; i++) {// If element has not encounter early,// mark it on cnt array.if (cnt.has(Math.abs(arr[i])) == false)cnt.set(Math.abs(arr[i]) , 1);// If seen before, push it in vector (// given that elements are distinct)else {v.push(Math.abs(arr[i]));cnt.delete(Math.abs(arr[i]));}}if (v.length == 0)return;v.sort((a,b)=>a-b)for (let i = 0; i < v.length; i++)document.write(-v[i] + " " + v[i] + " ");}// Driven Programlet arr = [ 4, 8, 9, -4, 1, -1, -8, -9 ];let n = arr.length;printPairs(arr, n);// This code is contributed by shinjanpatra.</script> -4 4 -1 1 -8 8 -9 9 Time Complexity: O(n)Auxiliary Space: O(n) Method 3 (Using set) : The idea is to use a set. Find the negative of the number in the set. If it exits then print both the numbers and if it does not exits then add it on to the set. Below is the implementation of this approach: C++ Java Python3 Javascript // Efficient CPP program to find pairs of// positive and negative values present in// an array.#include <bits/stdc++.h>using namespace std;// Print pair with negative and positive valuevoid printPairs(int arr[], int n){ unordered_set<int> hs; vector<int> ans; for (int i = 0; i < n; i++) { if (hs.find((arr[i]) * -1) != hs.end()) { if (arr[i] < 0) { cout << arr[i] << " "; cout << (arr[i] * -1) << " "; } else { cout << (arr[i] * -1) << " "; cout << arr[i] << " "; } } hs.insert(arr[i]); } return;}// Driven Programint main(){ int arr[] = { 4, 8, 9, -4, 1, -1, -8, -9 }; int n = sizeof(arr) / sizeof(arr[0]); printPairs(arr, n); return 0;} // Efficient CPP program to find pairs of// positive and negative values present in// an array.import java.util.*; public class GFG { // Print pair with negative and positive value public static void printPairs(int[] arr, int n) { HashSet<Integer> hs = new HashSet<Integer>(); ArrayList<Integer> ans = new ArrayList<Integer>(); for (int i = 0; i < n; i++) { if (hs.contains((arr[i]) * -1)) { if (arr[i] < 0) { System.out.print(arr[i]); System.out.print(" "); System.out.print((arr[i] * -1)); System.out.print(" "); } else { System.out.print((arr[i] * -1)); System.out.print(" "); System.out.print(arr[i]); System.out.print(" "); } } hs.add(arr[i]); } return; } // Driven Program public static void main(String[] args) { int[] arr = { 4, 8, 9, -4, 1, -1, -8, -9 }; int n = arr.length; printPairs(arr, n); }} // This code is contributed by Aarti_Rathi # Print pair with negative and positive valuedef printPairs(arr,n): hs = set() ans = [] for i in range(n): if (arr[i] * -1) in hs: if (arr[i] < 0): print(arr[i],end = " ") print((arr[i] * -1),end = " ") else: print((arr[i] * -1),end = " ") print(arr[i],end = " ") hs.add(arr[i]) return # Driven Programarr = [ 4, 8, 9, -4, 1, -1, -8, -9 ]n = len(arr)printPairs(arr, n) # This code is contributed by shinjanpatra. <script>// Efficient JavaScript program to find pairs of// positive and negative values present in// an array.// Print pair with negative and positive valuefunction printPairs(arr, n){let hs = new Set();let ans = new Array();for(let i = 0 ; i < n ; i++ ){if( hs.has((arr[i])*-1) == true){if(arr[i] < 0){document.write(arr[i]," ");document.write((arr[i]*-1)," ");}else{document.write((arr[i]*-1)," ");document.write(arr[i]," ");}}hs.add(arr[i]) ;} return ;}// Driver Programlet arr = [ 4, 8, 9, -4, 1, -1, -8, -9 ];let n = arr.length;printPairs(arr, n);// This code is contributed by shinjanpatra.</script> -4 4 -1 1 -8 8 -9 9 Time Complexity: O(n)Auxiliary Space : O(n) This article is contributed by Anuj Chauhan. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. 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. Prasad_Kshirsagar prerna saini ukasp 29AjayKumar RohitOberoi divyeshrabadiya07 akhtarnasim1990 rag2127 akshaysingh98088 prasanna1995 shinjanpatra RishabhPrabhu anandkumarshivam2266 codewithmini Arrays Hash Arrays Hash 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 Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum) What is Hashing | A Complete Tutorial Internal Working of HashMap in Java Hashing | Set 1 (Introduction) Count pairs with given sum
[ { "code": null, "e": 52, "s": 24, "text": "\n27 Jun, 2022" }, { "code": null, "e": 228, "s": 52, "text": "Given an array of distinct integers, print all the pairs having positive value and negative value of a number that exists in the array. The pairs can be printed in any order." }, { "code": null, "e": 240, "s": 228, "text": "Examples: " }, { "code": null, "e": 296, "s": 240, "text": "Input: arr[] = { 1, -3, 2, 3, 6, -1 }Output: -1 1 -3 3" }, { "code": null, "e": 371, "s": 296, "text": "Input: arr[] = { 4, 8, 9, -4, 1, -1, -8, -9 }Output: -4 4 -8 8 -9 9 -1 1 " }, { "code": null, "e": 604, "s": 371, "text": "Method 1 (Simple : O(n2)) The idea is to use two nested loop. For each element arr[i], find negative of arr[i] from index i + 1 to n – 1 and store it in another array. For output, print negative positive value of the stored element." }, { "code": null, "e": 652, "s": 604, "text": "Below is the implementation of this approach: " }, { "code": null, "e": 656, "s": 652, "text": "C++" }, { "code": null, "e": 661, "s": 656, "text": "Java" }, { "code": null, "e": 670, "s": 661, "text": "Python 3" }, { "code": null, "e": 673, "s": 670, "text": "C#" }, { "code": null, "e": 684, "s": 673, "text": "Javascript" }, { "code": "// Simple CPP program to find pairs of positive// and negative values present in an array.#include <bits/stdc++.h>using namespace std; // Print pair with negative and positive valuevoid printPairs(int arr[], int n){ vector<int> v; // For each element of array. for (int i = 0; i < n; i++) // Try to find the negative value of // arr[i] from i + 1 to n for (int j = i + 1; j < n; j++) // If absolute values are equal print pair. if (abs(arr[i]) == abs(arr[j])) v.push_back(abs(arr[i])); // If size of vector is 0, therefore there is no // element with positive negative value, print \"0\" if (v.size() == 0) return; // Print the pair with negative positive value. for (int i = 0; i < v.size(); i++) cout << -v[i] << \" \" << v[i] << \" \";} // Driven Programint main(){ int arr[] = { 4, 8, 9, -4, 1, -1, -8, -9 }; int n = sizeof(arr) / sizeof(arr[0]); printPairs(arr, n); return 0;}", "e": 1673, "s": 684, "text": null }, { "code": "// Java program to find pairs of positive// and negative values present in an array.import java.lang.*;import java.util.*; class GFG { // Print pair with negative and positive value public static void printPairs(int arr[], int n) { Vector<Integer> v = new Vector<Integer>(); // For each element of array. for (int i = 0; i < n; i++) // Try to find the negative value of // arr[i] from i + 1 to n for (int j = i + 1; j < n; j++) // If absolute values are equal // print pair. if (Math.abs(arr[i]) == Math.abs(arr[j])) v.add(Math.abs(arr[i])); // If size of vector is 0, therefore there // is no element with positive negative // value, print \"0\" if (v.size() == 0) return; // Print the pair with negative positive // value. for (int i = 0; i < v.size(); i++) System.out.print(-v.get(i) + \" \" + v.get(i) + \" \"); } // Driven Program public static void main(String[] args) { int arr[] = { 4, 8, 9, -4, 1, -1, -8, -9 }; int n = arr.length; printPairs(arr, n); }} // This code is contributed by Prasad Kshirsagar.", "e": 2949, "s": 1673, "text": null }, { "code": "# Simple Python 3 program to find# pairs of positive and negative# values present in an array. # Print pair with negative and# positive value def printPairs(arr, n): v = [] # For each element of array. for i in range(n): # Try to find the negative value # of arr[i] from i + 1 to n for j in range(i + 1, n): # If absolute values are # equal print pair. if (abs(arr[i]) == abs(arr[j])): v.append(abs(arr[i])) # If size of vector is 0, therefore # there is no element with positive # negative value, print \"0\" if (len(v) == 0): return # Print the pair with negative # positive value. for i in range(len(v)): print(-v[i], \"\", v[i], end=\" \") # Driver Codeif __name__ == \"__main__\": arr = [4, 8, 9, -4, 1, -1, -8, -9] n = len(arr) printPairs(arr, n) # This code is contributed# by ChitraNayal", "e": 3866, "s": 2949, "text": null }, { "code": "// C# program to find pairs of positive// and negative values present in an array.using System;using System.Collections.Generic; class GFG { // Print pair with negative and positive value public static void printPairs(int[] arr, int n) { List<int> v = new List<int>(); // For each element of array. for (int i = 0; i < n; i++) // Try to find the negative value of // arr[i] from i + 1 to n for (int j = i + 1; j < n; j++) // If absolute values are equal // print pair. if (Math.Abs(arr[i]) == Math.Abs(arr[j])) v.Add(Math.Abs(arr[i])); // If size of vector is 0, therefore there // is no element with positive negative // value, print \"0\" if (v.Count == 0) return; // Print the pair with negative positive // value. for (int i = 0; i < v.Count; i++) Console.Write(-v[i] + \" \" + v[i] + \" \"); } // Driver code public static void Main(String[] args) { int[] arr = { 4, 8, 9, -4, 1, -1, -8, -9 }; int n = arr.Length; printPairs(arr, n); }} // This code has been contributed by 29AjayKumar", "e": 5092, "s": 3866, "text": null }, { "code": "<script>// Javascript program to find pairs of positive// and negative values present in an array. // Print pair with negative and positive value function printPairs(arr,n) { let v = []; // For each element of array. for (let i = 0; i < n; i++) // Try to find the negative value of // arr[i] from i + 1 to n for (let j = i + 1; j < n; j++) // If absolute values are equal // print pair. if (Math.abs(arr[i]) == Math.abs(arr[j])) v.push(Math.abs(arr[i])); // If size of vector is 0, therefore there // is no element with positive negative // value, print \"0\" if (v.length == 0) return; // Print the pair with negative positive // value. for (let i = 0; i < v.length; i++) document.write(-v[i] + \" \" + v[i] + \" \"); } // Driven Program let arr=[4, 8, 9, -4, 1, -1, -8, -9]; let n = arr.length; printPairs(arr, n); // This code is contributed by rag2127</script>", "e": 6272, "s": 5092, "text": null }, { "code": null, "e": 6293, "s": 6272, "text": "-4 4 -8 8 -9 9 -1 1 " }, { "code": null, "e": 6339, "s": 6293, "text": "Time Complexity: O(n*n)Auxiliary Space : O(n)" }, { "code": null, "e": 6655, "s": 6339, "text": "Method 2 (Hashing) The idea is to use hashing. Traverse the given array, increase the count at absolute value of hash table. If count becomes 2, store its absolute value in another vector. If the size of the vector is 0, print “0”, else for each term in vector print first its negative value and the positive value." }, { "code": null, "e": 6701, "s": 6655, "text": "Below is the implementation of this approach:" }, { "code": null, "e": 6705, "s": 6701, "text": "C++" }, { "code": null, "e": 6710, "s": 6705, "text": "Java" }, { "code": null, "e": 6718, "s": 6710, "text": "Python3" }, { "code": null, "e": 6721, "s": 6718, "text": "C#" }, { "code": null, "e": 6732, "s": 6721, "text": "Javascript" }, { "code": "// Efficient CPP program to find pairs of// positive and negative values present in// an array.#include <bits/stdc++.h>using namespace std;// Print pair with negative and positive valuevoid printPairs(int arr[], int n){ vector<int> v; unordered_map<int, bool> cnt; // For each element of array. for (int i = 0; i < n; i++) { // If element has not encounter early, // mark it on cnt array. if (cnt[abs(arr[i])] == 0) cnt[abs(arr[i])] = 1; // If seen before, push it in vector ( // given that elements are distinct) else { v.push_back(abs(arr[i])); cnt[abs(arr[i])] = 0; } } if (v.size() == 0) return; for (int i = 0; i < v.size(); i++) cout << \"-\" << v[i] << \" \" << v[i] << \" \";} // Driven Programint main(){ int arr[] = { 4, 8, 9, -4, 1, -1, -8, -9 }; int n = sizeof(arr) / sizeof(arr[0]); printPairs(arr, n); return 0;}", "e": 7689, "s": 6732, "text": null }, { "code": "// Efficient Java program to find pairs of// positive and negative values present in// an array.import java.util.*;class GFG { // Print pair with negative // and positive value static void printPairs(int arr[], int n) { ArrayList<Integer> v = new ArrayList<Integer>(); HashMap<Integer, Integer> cnt = new HashMap<Integer, Integer>(); // For each element of array. for (int i = 0; i < n; i++) { // If element has encounter early, // then increment its count if (cnt.containsKey(Math.abs(arr[i]))) cnt.put(Math.abs(arr[i]), cnt.get(Math.abs(arr[i])) + 1); // If element has not seen before, // then initialize its count to 1 else { cnt.put(Math.abs(arr[i]), 1); } if (cnt.get(Math.abs(arr[i])) == 2) { v.add(Math.abs(arr[i])); } } if (v.size() == 0) return; for (int i = 0; i < v.size(); i++) System.out.print(\"-\" + v.get(i) + \" \" + v.get(i) + \" \"); } // Driver Code public static void main(String[] args) { int arr[] = { 4, 8, 9, -4, 1, -1, -8, -9 }; int n = arr.length; printPairs(arr, n); }}// This code is contributed by Prerna Saini", "e": 9051, "s": 7689, "text": null }, { "code": "# Efficient Python3 program to find pairs of# positive and negative values present in# an array.# Print pair with negative and# positive value def printPairs(arr, n): s = set()ret = [] # For each element of array.for i in arr:if abs(i) in s:ret.append(abs(i))else:s.add(abs(i)) ret.sort() for i in range(0, len(ret)):print(-ret[i], \"\", ret[i], end=\" \")# Driver Codeif __name__ == \"__main__\": arr = [4, 8, 9, -4, 1, -1, -8, -9]n = len(arr) printPairs(arr, n)# This code is contributed by RohitOberoi", "e": 9552, "s": 9051, "text": null }, { "code": "// Efficient C# program to find pairs of// positive and negative values present in// an array.using System;using System.Collections.Generic;class GFG { // Print pair with negative and positive value static void printPairs(int[] arr, int n) { List<int> v = new List<int>(); Dictionary<int, bool> cnt = new Dictionary<int, bool>(); // For each element of array. for (int i = 0; i < n; i++) { // If element has not encounter early, // mark it on cnt array. int absVal = Math.Abs(arr[i]); if (!cnt.ContainsKey(absVal)) { cnt[absVal] = true; } else if (cnt[absVal] == false) { cnt[absVal] = true; } else { v.Add(Math.Abs(arr[i])); cnt[absVal] = false; } } if (v.Count == 0) return; v.Sort(); for (int i = 0; i < v.Count; i++) Console.Write(-v[i] + \" \" + v[i] + \" \"); } // Driver code static void Main() { int[] arr = { 4, 8, 9, -4, 1, -1, -8, -9 }; int n = arr.Length; printPairs(arr, n); }}// This code is contributed by divyeshrabadiya07", "e": 10785, "s": 9552, "text": null }, { "code": "<script>// Efficient JavaScript program to find pairs of// positive and negative values present in// an array.// Print pair with negative and positive valuefunction printPairs(arr,n){let v = new Array();let cnt = new Map();// For each element of array.for (let i = 0; i < n; i++) {// If element has not encounter early,// mark it on cnt array.if (cnt.has(Math.abs(arr[i])) == false)cnt.set(Math.abs(arr[i]) , 1);// If seen before, push it in vector (// given that elements are distinct)else {v.push(Math.abs(arr[i]));cnt.delete(Math.abs(arr[i]));}}if (v.length == 0)return;v.sort((a,b)=>a-b)for (let i = 0; i < v.length; i++)document.write(-v[i] + \" \" + v[i] + \" \");}// Driven Programlet arr = [ 4, 8, 9, -4, 1, -1, -8, -9 ];let n = arr.length;printPairs(arr, n);// This code is contributed by shinjanpatra.</script>", "e": 11602, "s": 10785, "text": null }, { "code": null, "e": 11623, "s": 11602, "text": "-4 4 -1 1 -8 8 -9 9 " }, { "code": null, "e": 11666, "s": 11623, "text": "Time Complexity: O(n)Auxiliary Space: O(n)" }, { "code": null, "e": 11851, "s": 11666, "text": "Method 3 (Using set) : The idea is to use a set. Find the negative of the number in the set. If it exits then print both the numbers and if it does not exits then add it on to the set." }, { "code": null, "e": 11897, "s": 11851, "text": "Below is the implementation of this approach:" }, { "code": null, "e": 11901, "s": 11897, "text": "C++" }, { "code": null, "e": 11906, "s": 11901, "text": "Java" }, { "code": null, "e": 11914, "s": 11906, "text": "Python3" }, { "code": null, "e": 11925, "s": 11914, "text": "Javascript" }, { "code": "// Efficient CPP program to find pairs of// positive and negative values present in// an array.#include <bits/stdc++.h>using namespace std;// Print pair with negative and positive valuevoid printPairs(int arr[], int n){ unordered_set<int> hs; vector<int> ans; for (int i = 0; i < n; i++) { if (hs.find((arr[i]) * -1) != hs.end()) { if (arr[i] < 0) { cout << arr[i] << \" \"; cout << (arr[i] * -1) << \" \"; } else { cout << (arr[i] * -1) << \" \"; cout << arr[i] << \" \"; } } hs.insert(arr[i]); } return;}// Driven Programint main(){ int arr[] = { 4, 8, 9, -4, 1, -1, -8, -9 }; int n = sizeof(arr) / sizeof(arr[0]); printPairs(arr, n); return 0;}", "e": 12718, "s": 11925, "text": null }, { "code": "// Efficient CPP program to find pairs of// positive and negative values present in// an array.import java.util.*; public class GFG { // Print pair with negative and positive value public static void printPairs(int[] arr, int n) { HashSet<Integer> hs = new HashSet<Integer>(); ArrayList<Integer> ans = new ArrayList<Integer>(); for (int i = 0; i < n; i++) { if (hs.contains((arr[i]) * -1)) { if (arr[i] < 0) { System.out.print(arr[i]); System.out.print(\" \"); System.out.print((arr[i] * -1)); System.out.print(\" \"); } else { System.out.print((arr[i] * -1)); System.out.print(\" \"); System.out.print(arr[i]); System.out.print(\" \"); } } hs.add(arr[i]); } return; } // Driven Program public static void main(String[] args) { int[] arr = { 4, 8, 9, -4, 1, -1, -8, -9 }; int n = arr.length; printPairs(arr, n); }} // This code is contributed by Aarti_Rathi", "e": 13894, "s": 12718, "text": null }, { "code": "# Print pair with negative and positive valuedef printPairs(arr,n): hs = set() ans = [] for i in range(n): if (arr[i] * -1) in hs: if (arr[i] < 0): print(arr[i],end = \" \") print((arr[i] * -1),end = \" \") else: print((arr[i] * -1),end = \" \") print(arr[i],end = \" \") hs.add(arr[i]) return # Driven Programarr = [ 4, 8, 9, -4, 1, -1, -8, -9 ]n = len(arr)printPairs(arr, n) # This code is contributed by shinjanpatra.", "e": 14420, "s": 13894, "text": null }, { "code": "<script>// Efficient JavaScript program to find pairs of// positive and negative values present in// an array.// Print pair with negative and positive valuefunction printPairs(arr, n){let hs = new Set();let ans = new Array();for(let i = 0 ; i < n ; i++ ){if( hs.has((arr[i])*-1) == true){if(arr[i] < 0){document.write(arr[i],\" \");document.write((arr[i]*-1),\" \");}else{document.write((arr[i]*-1),\" \");document.write(arr[i],\" \");}}hs.add(arr[i]) ;} return ;}// Driver Programlet arr = [ 4, 8, 9, -4, 1, -1, -8, -9 ];let n = arr.length;printPairs(arr, n);// This code is contributed by shinjanpatra.</script>", "e": 15026, "s": 14420, "text": null }, { "code": null, "e": 15047, "s": 15026, "text": "-4 4 -1 1 -8 8 -9 9 " }, { "code": null, "e": 15091, "s": 15047, "text": "Time Complexity: O(n)Auxiliary Space : O(n)" }, { "code": null, "e": 15512, "s": 15091, "text": "This article is contributed by Anuj Chauhan. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. 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": 15530, "s": 15512, "text": "Prasad_Kshirsagar" }, { "code": null, "e": 15543, "s": 15530, "text": "prerna saini" }, { "code": null, "e": 15549, "s": 15543, "text": "ukasp" }, { "code": null, "e": 15561, "s": 15549, "text": "29AjayKumar" }, { "code": null, "e": 15573, "s": 15561, "text": "RohitOberoi" }, { "code": null, "e": 15591, "s": 15573, "text": "divyeshrabadiya07" }, { "code": null, "e": 15607, "s": 15591, "text": "akhtarnasim1990" }, { "code": null, "e": 15615, "s": 15607, "text": "rag2127" }, { "code": null, "e": 15632, "s": 15615, "text": "akshaysingh98088" }, { "code": null, "e": 15645, "s": 15632, "text": "prasanna1995" }, { "code": null, "e": 15658, "s": 15645, "text": "shinjanpatra" }, { "code": null, "e": 15672, "s": 15658, "text": "RishabhPrabhu" }, { "code": null, "e": 15693, "s": 15672, "text": "anandkumarshivam2266" }, { "code": null, "e": 15706, "s": 15693, "text": "codewithmini" }, { "code": null, "e": 15713, "s": 15706, "text": "Arrays" }, { "code": null, "e": 15718, "s": 15713, "text": "Hash" }, { "code": null, "e": 15725, "s": 15718, "text": "Arrays" }, { "code": null, "e": 15730, "s": 15725, "text": "Hash" }, { "code": null, "e": 15828, "s": 15730, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 15896, "s": 15828, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 15940, "s": 15896, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 15972, "s": 15940, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 16020, "s": 15972, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 16034, "s": 16020, "text": "Linear Search" }, { "code": null, "e": 16119, "s": 16034, "text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)" }, { "code": null, "e": 16157, "s": 16119, "text": "What is Hashing | A Complete Tutorial" }, { "code": null, "e": 16193, "s": 16157, "text": "Internal Working of HashMap in Java" }, { "code": null, "e": 16224, "s": 16193, "text": "Hashing | Set 1 (Introduction)" } ]
Replace values from dataframe column using R
07 Apr, 2021 In this article, we will discuss how to replace values from a DataFrame column in R Programming Language. Whenever we deal with some data, it is necessary that we draw accurate conclusions from it. Now imagine what if, there are some missing values(this happens when some observation is missing in a column of a data-frame or contains a character value instead of a numerical value) in our data or let’s say there are some negative values in the dataset, which might lead to false accuracy, also it affects the analysis result. So, to avoid these, we can replace such values, using the following methods. Example 1. Replacing NA values in a data frame with Zeroes(0’s) So first, we create a table with the column names: Name, ID, CPI and add respective values to the respective columns R Name <- c("Amy", "Celine", "Lily", "Irene", "Rosy", "Tom", "Kite")ID <- c(123, NA, 134, NA, 166, 129, 178)CPI <- c(8.5, 8.3, 7.8, NA, 6.9, 9.1, 5.6) details <- data.frame(Name, ID, CPI)View(details) Output: Replace value from NA values to 0: R details[is.na(details)] <- 0 # views the newly modified tableView(details) Output: Example 2. Replacing NA values in a data frame with the mean values We create the table with the following columns and values, same as explained before. R RollNo <- c(24,23,NA,18)ID <- c(123, 156, 134, 148)CPI <- c(8.5,8.3,7.8,NA) secR1 <- data.frame(RollNo,ID,CPI)View(secR1) Output: Table Now replacing the NA value with the mean value: R ex <- secR1ex # replacing the NA value with the mean valueex$RollNo[is.na(ex$RollNo)]<-mean(ex$RollNo, na.rm = T)round(ex, digits = 0) Output: The Output –> NA in Roll no. replaced with the mean Example 3. Replacing the negative values with 0s(zeroes): First, we create a table, as we did before. R RollNo <- c(24,23,16,-18)ID <- c(123,156,-134,148)CPI <- c(8.5,8.3,7.8,8.9)marks <- c(-54,70,-20,9) secR1 <- data.frame(RollNo,ID,CPI,marks)View(secR1) Output: Now change the negative values to 0: R secR1[secR1 < 0] <- 0 view(secR1) Output: Example 4. Using replace( ) method: The replace() function, replaces the values in x with indices given in the list by those given in values. If necessary, the values in values are recycled. Syntax: replace(x, list, values) Arguments: x: vector list: an index vector values: replacement values Example: R # creates a tableRollNo <- c(24,23,NA,18)ID <- c(123, 156, 134, 148)CPI <- c(8.5,8.3,7.8,NA)secR1 <- data.frame(RollNo,ID,CPI) View(secR1) # 2nd element of the list, hence 2, replacement value is 45secR1<- replace(RollNo, 2, 45) View(secR1) Output: Final Output Picked R DataFrame-Programs R-DataFrame R Language R Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Group by function in R using Dplyr How to Split Column Into Multiple Columns in R DataFrame? How to filter R DataFrame by values in a column? Change Color of Bars in Barchart using ggplot2 in R How to Change Axis Scales in R Plots? How to Split Column Into Multiple Columns in R DataFrame? How to filter R DataFrame by values in a column? Replace Specific Characters in String in R Convert Matrix to Dataframe in R Extract specific column from a DataFrame using column name in R
[ { "code": null, "e": 28, "s": 0, "text": "\n07 Apr, 2021" }, { "code": null, "e": 134, "s": 28, "text": "In this article, we will discuss how to replace values from a DataFrame column in R Programming Language." }, { "code": null, "e": 634, "s": 134, "text": "Whenever we deal with some data, it is necessary that we draw accurate conclusions from it. Now imagine what if, there are some missing values(this happens when some observation is missing in a column of a data-frame or contains a character value instead of a numerical value) in our data or let’s say there are some negative values in the dataset, which might lead to false accuracy, also it affects the analysis result. So, to avoid these, we can replace such values, using the following methods. " }, { "code": null, "e": 698, "s": 634, "text": "Example 1. Replacing NA values in a data frame with Zeroes(0’s)" }, { "code": null, "e": 815, "s": 698, "text": "So first, we create a table with the column names: Name, ID, CPI and add respective values to the respective columns" }, { "code": null, "e": 817, "s": 815, "text": "R" }, { "code": "Name <- c(\"Amy\", \"Celine\", \"Lily\", \"Irene\", \"Rosy\", \"Tom\", \"Kite\")ID <- c(123, NA, 134, NA, 166, 129, 178)CPI <- c(8.5, 8.3, 7.8, NA, 6.9, 9.1, 5.6) details <- data.frame(Name, ID, CPI)View(details)", "e": 1026, "s": 817, "text": null }, { "code": null, "e": 1034, "s": 1026, "text": "Output:" }, { "code": null, "e": 1069, "s": 1034, "text": "Replace value from NA values to 0:" }, { "code": null, "e": 1071, "s": 1069, "text": "R" }, { "code": "details[is.na(details)] <- 0 # views the newly modified tableView(details)", "e": 1147, "s": 1071, "text": null }, { "code": null, "e": 1155, "s": 1147, "text": "Output:" }, { "code": null, "e": 1223, "s": 1155, "text": "Example 2. Replacing NA values in a data frame with the mean values" }, { "code": null, "e": 1308, "s": 1223, "text": "We create the table with the following columns and values, same as explained before." }, { "code": null, "e": 1310, "s": 1308, "text": "R" }, { "code": "RollNo <- c(24,23,NA,18)ID <- c(123, 156, 134, 148)CPI <- c(8.5,8.3,7.8,NA) secR1 <- data.frame(RollNo,ID,CPI)View(secR1)", "e": 1433, "s": 1310, "text": null }, { "code": null, "e": 1441, "s": 1433, "text": "Output:" }, { "code": null, "e": 1447, "s": 1441, "text": "Table" }, { "code": null, "e": 1495, "s": 1447, "text": "Now replacing the NA value with the mean value:" }, { "code": null, "e": 1497, "s": 1495, "text": "R" }, { "code": "ex <- secR1ex # replacing the NA value with the mean valueex$RollNo[is.na(ex$RollNo)]<-mean(ex$RollNo, na.rm = T)round(ex, digits = 0)", "e": 1633, "s": 1497, "text": null }, { "code": null, "e": 1641, "s": 1633, "text": "Output:" }, { "code": null, "e": 1693, "s": 1641, "text": "The Output –> NA in Roll no. replaced with the mean" }, { "code": null, "e": 1751, "s": 1693, "text": "Example 3. Replacing the negative values with 0s(zeroes):" }, { "code": null, "e": 1795, "s": 1751, "text": "First, we create a table, as we did before." }, { "code": null, "e": 1797, "s": 1795, "text": "R" }, { "code": "RollNo <- c(24,23,16,-18)ID <- c(123,156,-134,148)CPI <- c(8.5,8.3,7.8,8.9)marks <- c(-54,70,-20,9) secR1 <- data.frame(RollNo,ID,CPI,marks)View(secR1)", "e": 1950, "s": 1797, "text": null }, { "code": null, "e": 1958, "s": 1950, "text": "Output:" }, { "code": null, "e": 1995, "s": 1958, "text": "Now change the negative values to 0:" }, { "code": null, "e": 1997, "s": 1995, "text": "R" }, { "code": "secR1[secR1 < 0] <- 0 view(secR1)", "e": 2035, "s": 1997, "text": null }, { "code": null, "e": 2043, "s": 2035, "text": "Output:" }, { "code": null, "e": 2079, "s": 2043, "text": "Example 4. Using replace( ) method:" }, { "code": null, "e": 2234, "s": 2079, "text": "The replace() function, replaces the values in x with indices given in the list by those given in values. If necessary, the values in values are recycled." }, { "code": null, "e": 2267, "s": 2234, "text": "Syntax: replace(x, list, values)" }, { "code": null, "e": 2278, "s": 2267, "text": "Arguments:" }, { "code": null, "e": 2288, "s": 2278, "text": "x: vector" }, { "code": null, "e": 2310, "s": 2288, "text": "list: an index vector" }, { "code": null, "e": 2337, "s": 2310, "text": "values: replacement values" }, { "code": null, "e": 2346, "s": 2337, "text": "Example:" }, { "code": null, "e": 2348, "s": 2346, "text": "R" }, { "code": "# creates a tableRollNo <- c(24,23,NA,18)ID <- c(123, 156, 134, 148)CPI <- c(8.5,8.3,7.8,NA)secR1 <- data.frame(RollNo,ID,CPI) View(secR1) # 2nd element of the list, hence 2, replacement value is 45secR1<- replace(RollNo, 2, 45) View(secR1)", "e": 2598, "s": 2348, "text": null }, { "code": null, "e": 2606, "s": 2598, "text": "Output:" }, { "code": null, "e": 2619, "s": 2606, "text": "Final Output" }, { "code": null, "e": 2626, "s": 2619, "text": "Picked" }, { "code": null, "e": 2647, "s": 2626, "text": "R DataFrame-Programs" }, { "code": null, "e": 2659, "s": 2647, "text": "R-DataFrame" }, { "code": null, "e": 2670, "s": 2659, "text": "R Language" }, { "code": null, "e": 2681, "s": 2670, "text": "R Programs" }, { "code": null, "e": 2779, "s": 2681, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2814, "s": 2779, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 2872, "s": 2814, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 2921, "s": 2872, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 2973, "s": 2921, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 3011, "s": 2973, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 3069, "s": 3011, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 3118, "s": 3069, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 3161, "s": 3118, "text": "Replace Specific Characters in String in R" }, { "code": null, "e": 3194, "s": 3161, "text": "Convert Matrix to Dataframe in R" } ]
HTML5 - WebSockets
WebSockets is a next-generation bidirectional communication technology for web applications which operates over a single socket and is exposed via a JavaScript interface in HTML 5 compliant browsers. Once you get a Web Socket connection with the web server, you can send data from browser to server by calling a send() method, and receive data from server to browser by an onmessage event handler. Following is the API which creates a new WebSocket object. var Socket = new WebSocket(url, [protocal] ); Here first argument, url, specifies the URL to which to connect. The second attribute, protocol is optional, and if present, specifies a sub-protocol that the server must support for the connection to be successful. Following are the attribute of WebSocket object. Assuming we created Socket object as mentioned above − Socket.readyState The readonly attribute readyState represents the state of the connection. It can have the following values − A value of 0 indicates that the connection has not yet been established. A value of 0 indicates that the connection has not yet been established. A value of 1 indicates that the connection is established and communication is possible. A value of 1 indicates that the connection is established and communication is possible. A value of 2 indicates that the connection is going through the closing handshake. A value of 2 indicates that the connection is going through the closing handshake. A value of 3 indicates that the connection has been closed or could not be opened. A value of 3 indicates that the connection has been closed or could not be opened. Socket.bufferedAmount The readonly attribute bufferedAmount represents the number of bytes of UTF-8 text that have been queued using send() method. Following are the events associated with WebSocket object. Assuming we created Socket object as mentioned above − Following are the methods associated with WebSocket object. Assuming we created Socket object as mentioned above − Socket.send() The send(data) method transmits data using the connection. Socket.close() The close() method would be used to terminate any existing connection. A WebSocket is a standard bidirectional TCP socket between the client and the server. The socket starts out as a HTTP connection and then "Upgrades" to a TCP socket after a HTTP handshake. After the handshake, either side can send data. At the time of writing this tutorial, there are only few web browsers supporting WebSocket() interface. You can try following example with latest version of Chrome, Mozilla, Opera and Safari. <!DOCTYPE HTML> <html> <head> <script type = "text/javascript"> function WebSocketTest() { if ("WebSocket" in window) { alert("WebSocket is supported by your Browser!"); // Let us open a web socket var ws = new WebSocket("ws://localhost:9998/echo"); ws.onopen = function() { // Web Socket is connected, send data using send() ws.send("Message to send"); alert("Message is sent..."); }; ws.onmessage = function (evt) { var received_msg = evt.data; alert("Message is received..."); }; ws.onclose = function() { // websocket is closed. alert("Connection is closed..."); }; } else { // The browser doesn't support WebSocket alert("WebSocket NOT supported by your Browser!"); } } </script> </head> <body> <div id = "sse"> <a href = "javascript:WebSocketTest()">Run WebSocket</a> </div> </body> </html> Before you test above client program, you need a server which supports WebSocket. Download mod_pywebsocket-x.x.x.tar.gz from pywebsocket which aims to provide a Web Socket extension for Apache HTTP Server and install it following these steps. Unzip and untar the downloaded file. Unzip and untar the downloaded file. Go inside pywebsocket-x.x.x/src/ directory. Go inside pywebsocket-x.x.x/src/ directory. $python setup.py build $python setup.py build $sudo python setup.py install $sudo python setup.py install Then read document by − $pydoc mod_pywebsocket Then read document by − $pydoc mod_pywebsocket This will install it into your python environment. Go to the pywebsocket-x.x.x/src/mod_pywebsocket folder and run the following command − $sudo python standalone.py -p 9998 -w ../example/ This will start the server listening at port 9998 and use the handlers directory specified by the -w option where our echo_wsh.py resides. Now using Chrome browser open the html file your created in the beginning. If your browser supports WebSocket(), then you would get alert indicating that your browser supports WebSocket and finally when you click on "Run WebSocket" you would get Goodbye message sent by the server script.
[ { "code": null, "e": 2942, "s": 2742, "text": "WebSockets is a next-generation bidirectional communication technology for web applications which operates over a single socket and is exposed via a JavaScript interface in HTML 5 compliant browsers." }, { "code": null, "e": 3140, "s": 2942, "text": "Once you get a Web Socket connection with the web server, you can send data from browser to server by calling a send() method, and receive data from server to browser by an onmessage event handler." }, { "code": null, "e": 3199, "s": 3140, "text": "Following is the API which creates a new WebSocket object." }, { "code": null, "e": 3246, "s": 3199, "text": "var Socket = new WebSocket(url, [protocal] );\n" }, { "code": null, "e": 3462, "s": 3246, "text": "Here first argument, url, specifies the URL to which to connect. The second attribute, protocol is optional, and if present, specifies a sub-protocol that the server must support for the connection to be successful." }, { "code": null, "e": 3566, "s": 3462, "text": "Following are the attribute of WebSocket object. Assuming we created Socket object as mentioned above −" }, { "code": null, "e": 3584, "s": 3566, "text": "Socket.readyState" }, { "code": null, "e": 3693, "s": 3584, "text": "The readonly attribute readyState represents the state of the connection. It can have the following values −" }, { "code": null, "e": 3766, "s": 3693, "text": "A value of 0 indicates that the connection has not yet been established." }, { "code": null, "e": 3839, "s": 3766, "text": "A value of 0 indicates that the connection has not yet been established." }, { "code": null, "e": 3928, "s": 3839, "text": "A value of 1 indicates that the connection is established and communication is possible." }, { "code": null, "e": 4017, "s": 3928, "text": "A value of 1 indicates that the connection is established and communication is possible." }, { "code": null, "e": 4100, "s": 4017, "text": "A value of 2 indicates that the connection is going through the closing handshake." }, { "code": null, "e": 4183, "s": 4100, "text": "A value of 2 indicates that the connection is going through the closing handshake." }, { "code": null, "e": 4266, "s": 4183, "text": "A value of 3 indicates that the connection has been closed or could not be opened." }, { "code": null, "e": 4349, "s": 4266, "text": "A value of 3 indicates that the connection has been closed or could not be opened." }, { "code": null, "e": 4371, "s": 4349, "text": "Socket.bufferedAmount" }, { "code": null, "e": 4497, "s": 4371, "text": "The readonly attribute bufferedAmount represents the number of bytes of UTF-8 text that have been queued using send() method." }, { "code": null, "e": 4611, "s": 4497, "text": "Following are the events associated with WebSocket object. Assuming we created Socket object as mentioned above −" }, { "code": null, "e": 4726, "s": 4611, "text": "Following are the methods associated with WebSocket object. Assuming we created Socket object as mentioned above −" }, { "code": null, "e": 4740, "s": 4726, "text": "Socket.send()" }, { "code": null, "e": 4799, "s": 4740, "text": "The send(data) method transmits data using the connection." }, { "code": null, "e": 4814, "s": 4799, "text": "Socket.close()" }, { "code": null, "e": 4885, "s": 4814, "text": "The close() method would be used to terminate any existing connection." }, { "code": null, "e": 5122, "s": 4885, "text": "A WebSocket is a standard bidirectional TCP socket between the client and the server. The socket starts out as a HTTP connection and then \"Upgrades\" to a TCP socket after a HTTP handshake. After the handshake, either side can send data." }, { "code": null, "e": 5314, "s": 5122, "text": "At the time of writing this tutorial, there are only few web browsers supporting WebSocket() interface. You can try following example with latest version of Chrome, Mozilla, Opera and Safari." }, { "code": null, "e": 6623, "s": 5314, "text": "<!DOCTYPE HTML>\n\n<html>\n <head>\n \n <script type = \"text/javascript\">\n function WebSocketTest() {\n \n if (\"WebSocket\" in window) {\n alert(\"WebSocket is supported by your Browser!\");\n \n // Let us open a web socket\n var ws = new WebSocket(\"ws://localhost:9998/echo\");\n\t\t\t\t\n ws.onopen = function() {\n \n // Web Socket is connected, send data using send()\n ws.send(\"Message to send\");\n alert(\"Message is sent...\");\n };\n\t\t\t\t\n ws.onmessage = function (evt) { \n var received_msg = evt.data;\n alert(\"Message is received...\");\n };\n\t\t\t\t\n ws.onclose = function() { \n \n // websocket is closed.\n alert(\"Connection is closed...\"); \n };\n } else {\n \n // The browser doesn't support WebSocket\n alert(\"WebSocket NOT supported by your Browser!\");\n }\n }\n </script>\n\t\t\n </head>\n \n <body>\n <div id = \"sse\">\n <a href = \"javascript:WebSocketTest()\">Run WebSocket</a>\n </div>\n \n </body>\n</html>" }, { "code": null, "e": 6866, "s": 6623, "text": "Before you test above client program, you need a server which supports WebSocket. Download mod_pywebsocket-x.x.x.tar.gz from pywebsocket which aims to provide a Web Socket extension for Apache HTTP Server and install it following these steps." }, { "code": null, "e": 6903, "s": 6866, "text": "Unzip and untar the downloaded file." }, { "code": null, "e": 6940, "s": 6903, "text": "Unzip and untar the downloaded file." }, { "code": null, "e": 6984, "s": 6940, "text": "Go inside pywebsocket-x.x.x/src/ directory." }, { "code": null, "e": 7028, "s": 6984, "text": "Go inside pywebsocket-x.x.x/src/ directory." }, { "code": null, "e": 7051, "s": 7028, "text": "$python setup.py build" }, { "code": null, "e": 7074, "s": 7051, "text": "$python setup.py build" }, { "code": null, "e": 7104, "s": 7074, "text": "$sudo python setup.py install" }, { "code": null, "e": 7134, "s": 7104, "text": "$sudo python setup.py install" }, { "code": null, "e": 7183, "s": 7134, "text": "Then read document by −\n\n$pydoc mod_pywebsocket\n" }, { "code": null, "e": 7207, "s": 7183, "text": "Then read document by −" }, { "code": null, "e": 7230, "s": 7207, "text": "$pydoc mod_pywebsocket" }, { "code": null, "e": 7281, "s": 7230, "text": "This will install it into your python environment." }, { "code": null, "e": 7368, "s": 7281, "text": "Go to the pywebsocket-x.x.x/src/mod_pywebsocket folder and run the following command −" }, { "code": null, "e": 7419, "s": 7368, "text": "$sudo python standalone.py -p 9998 -w ../example/\n" }, { "code": null, "e": 7558, "s": 7419, "text": "This will start the server listening at port 9998 and use the handlers directory specified by the -w option where our echo_wsh.py resides." } ]
How to Display HTML in Textview along with Images in Android?
19 Oct, 2021 There are some situations when one needs to display rich formatted text in the app, like for a blog app or an app like Quora but Android’s inbuilt function doesn’t allow to display inline images by default, moreover they show the ugly blue line to the left of anything inside blockquote tag. Here is the simple solution to show HTML in TextView along with images in Android. Note that we are going to implement this project using Kotlin language in Android. Below is a demo screenshot of the app. Basic knowledge of the Coroutines library. Basic knowledge of Picasso library. To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Kotlin as the programming language. Add some colors in the colors.xml file. The Colors here are for the blockquote Styling. You are free to choose different colors. <?xml version="1.0" encoding="utf-8"?><resources> <color name="colorPrimary">#0F9D58</color> <color name="colorPrimaryDark">#0F9D58</color> <color name="colorAccent">#03DAC5</color> <color name="Grey">#878585</color></resources> Go to build.gradle(Module:app) file and add the following dependency. // Picasso library to downloading images implementation 'com.squareup.picasso:picasso:2.71828' // Coroutines dependency to put the downloading process in background thread implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.3.9' In the following activity_main.xml file we have added the following widgets: EditText where the user will input the HTML text, Button to trigger an event to display HTML text, ScrollView for smooth scrolling, TextView to display the HTML after processing the input. activity_main.xml <?xml version="1.0" encoding="utf-8"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:padding="16dp" tools:context=".MainActivity"> <!-- Edittext to take input for this sample app, for real app you will not need this --> <EditText android:id="@+id/editor" android:layout_width="0dp" android:layout_height="40dp" app:layout_constraintEnd_toStartOf="@+id/display_html" app:layout_constraintHorizontal_bias="0.0" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" /> <!-- Button to trigger an event to display html/Rich text--> <Button android:id="@+id/display_html" android:layout_width="100dp" android:layout_height="50dp" android:text="Display Html" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintTop_toTopOf="parent" /> <!-- Scroll View for smooth scrolling --> <ScrollView android:layout_width="0dp" android:layout_height="0dp" android:layout_marginTop="16dp" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/editor"> <!-- Text View in which you will display the html after processing the input--> <TextView android:id="@+id/html_viewer" android:layout_width="match_parent" android:layout_height="match_parent"> </TextView> </ScrollView> </androidx.constraintlayout.widget.ConstraintLayout> Output UI: Create a class that will download images contained in the img tag. Below is the complete ImageGetter.kt file. Understand the complete code by referring to the corresponding comments inside the code. ImageGetter.kt import android.content.res.Resourcesimport android.graphics.Bitmapimport android.graphics.Canvasimport android.graphics.drawable.BitmapDrawableimport android.graphics.drawable.Drawableimport android.text.Htmlimport android.widget.TextViewimport com.squareup.picasso.Picassoimport kotlinx.coroutines.Dispatchersimport kotlinx.coroutines.GlobalScopeimport kotlinx.coroutines.launchimport kotlinx.coroutines.withContext // Class to download Images which extends [Html.ImageGetter]class ImageGetter( private val res: Resources, private val htmlTextView: TextView) : Html.ImageGetter { // Function needs to overridden when extending [Html.ImageGetter] , // which will download the image override fun getDrawable(url: String): Drawable { val holder = BitmapDrawablePlaceHolder(res, null) // Coroutine Scope to download image in Background GlobalScope.launch(Dispatchers.IO) { runCatching { // downloading image in bitmap format using [Picasso] Library val bitmap = Picasso.get().load(url).get() val drawable = BitmapDrawable(res, bitmap) // To make sure Images don't go out of screen , Setting width less // than screen width, You can change image size if you want val width = getScreenWidth() - 150 // Images may stretch out if you will only resize width, // hence resize height to according to aspect ratio val aspectRatio: Float = (drawable.intrinsicWidth.toFloat()) / (drawable.intrinsicHeight.toFloat()) val height = width / aspectRatio drawable.setBounds(10, 20, width, height.toInt()) holder.setDrawable(drawable) holder.setBounds(10, 20, width, height.toInt()) withContext(Dispatchers.Main) { htmlTextView.text = htmlTextView.text } } } return holder } // Actually Putting images internal class BitmapDrawablePlaceHolder(res: Resources, bitmap: Bitmap?) : BitmapDrawable(res, bitmap) { private var drawable: Drawable? = null override fun draw(canvas: Canvas) { drawable?.run { draw(canvas) } } fun setDrawable(drawable: Drawable) { this.drawable = drawable } } // Function to get screenWidth used above fun getScreenWidth() = Resources.getSystem().displayMetrics.widthPixels} Note: One can change the height and the width of the image according to your will in the getDrawable() function. Create a click-Listener for the button inside the onCreate() method. MainActivity.kt class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // Click Listener to listener button click events. // display_html is button id from activity_main.xml // You don't need to get reference to it because kotlin // provides synthetic import and // We are gonna use for the same for rest of Views display_html.setOnClickListener { if (editor.text.isNotEmpty()) { displayHtml(editor.text.toString()) } } }} Create a function displayHtml() which you just called inside click listener. Note: Kotlin has Synthetic import ,so there was no need of storing reference to views in a variable and we are going to do the same for all other views. Kotlin private fun displayHtml(html: String) { // Creating object of ImageGetter class you just created val imageGetter = ImageGetter(resources, html_viewer) // Using Html framework to parse html val styledText=HtmlCompat.fromHtml(html, HtmlCompat.FROM_HTML_MODE_LEGACY, imageGetter,null) // to enable image/link clicking html_viewer.movementMethod = LinkMovementMethod.getInstance() // setting the text after formatting html and downloading and setting images html_viewer.text = styledText } So now the Image work is done, now it should load the images. Below is the complete code for the MainActivity.kt file. Kotlin import android.os.Bundleimport android.text.method.LinkMovementMethodimport androidx.appcompat.app.AppCompatActivityimport androidx.core.text.HtmlCompatimport kotlinx.android.synthetic.main.activity_main.* class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // Click Listener to listener button click events. // display_html is button id from activity_main.xml // You don't need to get reference to it // because kotlin provides synthetic import and // We are gonna use for the same for rest of Views display_html.setOnClickListener { if (editor.text.isNotEmpty()) { displayHtml(editor.text.toString()) } } } private fun displayHtml(html: String) { // Creating object of ImageGetter class you just created val imageGetter = ImageGetter(resources, html_viewer) // Using Html framework to parse html val styledText = HtmlCompat.fromHtml(html, HtmlCompat.FROM_HTML_MODE_LEGACY, imageGetter,null) // to enable image/link clicking html_viewer.movementMethod = LinkMovementMethod.getInstance() // setting the text after formatting html and downloading and setting images html_viewer.text = styledText }} Let’s see how it’s working now. Use HTML of another webpage. Here we have used the following webpage of the GFG article. Get the HTML string file from here. Note: Remember that input the HTML text inside the EditText and then click on the “DISPLAY HTML” Button The images are now loading but you can see, for the blockquote part, there is the plain ugly blue line. We are now gonna fix that. Create a Kotlin Class named QuoteSpanClass and add this following code to this file. QuoteSpanClass.kt import android.graphics.Canvasimport android.graphics.Paintimport android.text.Layoutimport android.text.style.LeadingMarginSpanimport android.text.style.LineBackgroundSpan class QuoteSpanClass( private val backgroundColor: Int, private val stripeColor: Int, private val stripeWidth: Float, private val gap: Float) : LeadingMarginSpan, LineBackgroundSpan { // Margin for the block quote tag override fun getLeadingMargin(first: Boolean): Int { return (stripeWidth + gap).toInt() } // this function draws the margin. override fun drawLeadingMargin( c: Canvas, p: Paint, x: Int, dir: Int, top: Int, baseline: Int, bottom: Int, text: CharSequence, start: Int, end: Int, first: Boolean, layout: Layout ) { val style = p.style val paintColor = p.color p.style = Paint.Style.FILL p.color = stripeColor // Creating margin according to color and stripewidth it recieves // Press CTRL+Q on function name to read more c.drawRect(x.toFloat(), top.toFloat(), x + dir * stripeWidth, bottom.toFloat(), p) p.style = style p.color = paintColor } override fun drawBackground( c: Canvas, p: Paint, left: Int, right: Int, top: Int, baseline: Int, bottom: Int, text: CharSequence, start: Int, end: Int, lnum: Int ) { val paintColor = p.color p.color = backgroundColor // It draws the background on which blockquote text is written c.drawRect(left.toFloat(), top.toFloat(), right.toFloat(), bottom.toFloat(), p) p.color = paintColor }} Since the QuoteSpanClass is created, it’s time to use this class in MainActivity.kt, but before you need to create a function to parse blockquote tags and draw the margin and background using the QuoteSpanClass. MainActivity.kt private fun replaceQuoteSpans(spannable: Spannable) { val quoteSpans: Array<QuoteSpan> = spannable.getSpans(0, spannable.length - 1, QuoteSpan::class.java) for (quoteSpan in quoteSpans) { val start: Int = spannable.getSpanStart(quoteSpan) val end: Int = spannable.getSpanEnd(quoteSpan) val flags: Int = spannable.getSpanFlags(quoteSpan) spannable.removeSpan(quoteSpan) spannable.setSpan( QuoteSpanClass( // background color ContextCompat.getColor(this, R.color.colorPrimary), // strip color ContextCompat.getColor(this, R.color.colorAccent), // strip width 10F, 50F ), start, end, flags ) } } And finally, call this function from displayHtml() function before setting the text for html_viewer. Below is the complete code for the MainActivity.kt file. Kotlin import android.os.Bundleimport android.text.Spannableimport android.text.method.LinkMovementMethodimport android.text.style.QuoteSpanimport androidx.appcompat.app.AppCompatActivityimport androidx.core.content.ContextCompatimport androidx.core.text.HtmlCompatimport kotlinx.android.synthetic.main.activity_main.* class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // Click Listener to listener button click events. // display_html is button id from activity_main.xml // You don't need to get reference to it // because kotlin provides synthetic import and // We are gonna use for the same for rest of Views display_html.setOnClickListener { if (editor.text.isNotEmpty()) { displayHtml(editor.text.toString()) } } } private fun displayHtml(html: String) { // Creating object of ImageGetter class you just created val imageGetter = ImageGetter(resources, html_viewer) // Using Html framework to parse html val styledText = HtmlCompat.fromHtml(html, HtmlCompat.FROM_HTML_MODE_LEGACY, imageGetter,null) replaceQuoteSpans(styledText as Spannable) // setting the text after formatting html and downloading and setting images html_viewer.text = styledText // to enable image/link clicking html_viewer.movementMethod = LinkMovementMethod.getInstance() } private fun replaceQuoteSpans(spannable: Spannable) { val quoteSpans: Array<QuoteSpan> = spannable.getSpans(0, spannable.length - 1, QuoteSpan::class.java) for (quoteSpan in quoteSpans) { val start: Int = spannable.getSpanStart(quoteSpan) val end: Int = spannable.getSpanEnd(quoteSpan) val flags: Int = spannable.getSpanFlags(quoteSpan) spannable.removeSpan(quoteSpan) spannable.setSpan( QuoteSpanClass( // background color ContextCompat.getColor(this, R.color.colorPrimary), // strip color ContextCompat.getColor(this, R.color.colorAccent), // strip width 10F, 50F ), start, end, flags ) } }} Now let’s see the changes in the output screen. Note: One can change strip Color, background color, strip width of your choice in replaceQuoteSpans function, and beautify it. But there is still one problem. What if you click an image? Nothing happens as of now. You need to add a few more lines to handle that. Kotlin // Function to parse image tags and enable click eventsfun ImageClick(html: Spannable) { for (span in html.getSpans(0, html.length, ImageSpan::class.java)) { val flags = html.getSpanFlags(span) val start = html.getSpanStart(span) val end = html.getSpanEnd(span) html.setSpan(object : URLSpan(span.source) { override fun onClick(v: View) { Log.d(TAG, "onClick: url is ${span.source}") } }, start, end, flags)} And then call this function from displayHtml() Function before setting the text for html_viewer. Below is the complete code for the MainActivity.kt file. Kotlin import android.os.Bundleimport android.text.Spannableimport android.text.method.LinkMovementMethodimport android.text.style.ImageSpanimport android.text.style.QuoteSpanimport android.text.style.URLSpanimport android.util.Logimport android.view.Viewimport androidx.appcompat.app.AppCompatActivityimport androidx.core.content.ContextCompatimport androidx.core.text.HtmlCompatimport kotlinx.android.synthetic.main.activity_main.* private const val TAG="MainActivity" class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // Click Listener to listener button click events. // display_html is button id from activity_main.xml // You don't need to get reference to it // because kotlin provides synthetic import and // We are gonna use for the same for rest of Views display_html.setOnClickListener { if (editor.text.isNotEmpty()) { displayHtml(editor.text.toString()) } } } private fun displayHtml(html: String) { // Creating object of ImageGetter class you just created val imageGetter = ImageGetter(resources, html_viewer) // Using Html framework to parse html val styledText = HtmlCompat.fromHtml(html, HtmlCompat.FROM_HTML_MODE_LEGACY, imageGetter, null) replaceQuoteSpans(styledText as Spannable) ImageClick(styledText as Spannable) // setting the text after formatting html and downloading and setting images html_viewer.text = styledText // to enable image/link clicking html_viewer.movementMethod = LinkMovementMethod.getInstance() } private fun replaceQuoteSpans(spannable: Spannable) { val quoteSpans: Array<QuoteSpan> = spannable.getSpans(0, spannable.length - 1, QuoteSpan::class.java) for (quoteSpan in quoteSpans) { val start: Int = spannable.getSpanStart(quoteSpan) val end: Int = spannable.getSpanEnd(quoteSpan) val flags: Int = spannable.getSpanFlags(quoteSpan) spannable.removeSpan(quoteSpan) spannable.setSpan( QuoteSpanClass( // background color ContextCompat.getColor(this, R.color.colorPrimary), // strip color ContextCompat.getColor(this, R.color.colorAccent), // strip width 10F, 50F ), start, end, flags ) } } // Function to parse image tags and enable click events fun ImageClick(html: Spannable) { for (span in html.getSpans(0, html.length, ImageSpan::class.java)) { val flags = html.getSpanFlags(span) val start = html.getSpanStart(span) val end = html.getSpanEnd(span) html.setSpan(object : URLSpan(span.source) { override fun onClick(v: View) { Log.d(TAG, "onClick: url is ${span.source}") } }, start, end, flags) } }} Now if you click on any Image and check Logcat you will see the URL of the image is being logged. From there you can trigger some function with that URL. Resource: Get the complete project file here. anikaseth98 anikakapoor abhishek0719kadiyan ruhelaa48 kashishsoda android Android Kotlin Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n19 Oct, 2021" }, { "code": null, "e": 549, "s": 52, "text": "There are some situations when one needs to display rich formatted text in the app, like for a blog app or an app like Quora but Android’s inbuilt function doesn’t allow to display inline images by default, moreover they show the ugly blue line to the left of anything inside blockquote tag. Here is the simple solution to show HTML in TextView along with images in Android. Note that we are going to implement this project using Kotlin language in Android. Below is a demo screenshot of the app." }, { "code": null, "e": 592, "s": 549, "text": "Basic knowledge of the Coroutines library." }, { "code": null, "e": 628, "s": 592, "text": "Basic knowledge of Picasso library." }, { "code": null, "e": 792, "s": 628, "text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Kotlin as the programming language." }, { "code": null, "e": 921, "s": 792, "text": "Add some colors in the colors.xml file. The Colors here are for the blockquote Styling. You are free to choose different colors." }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><resources> <color name=\"colorPrimary\">#0F9D58</color> <color name=\"colorPrimaryDark\">#0F9D58</color> <color name=\"colorAccent\">#03DAC5</color> <color name=\"Grey\">#878585</color></resources>", "e": 1162, "s": 921, "text": null }, { "code": null, "e": 1232, "s": 1162, "text": "Go to build.gradle(Module:app) file and add the following dependency." }, { "code": null, "e": 1482, "s": 1232, "text": "\n// Picasso library to downloading images \nimplementation 'com.squareup.picasso:picasso:2.71828'\n// Coroutines dependency to put the downloading \nprocess in background thread implementation \n'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.3.9'\n\n" }, { "code": null, "e": 1559, "s": 1482, "text": "In the following activity_main.xml file we have added the following widgets:" }, { "code": null, "e": 1609, "s": 1559, "text": "EditText where the user will input the HTML text," }, { "code": null, "e": 1658, "s": 1609, "text": "Button to trigger an event to display HTML text," }, { "code": null, "e": 1691, "s": 1658, "text": "ScrollView for smooth scrolling," }, { "code": null, "e": 1748, "s": 1691, "text": "TextView to display the HTML after processing the input." }, { "code": null, "e": 1766, "s": 1748, "text": "activity_main.xml" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:padding=\"16dp\" tools:context=\".MainActivity\"> <!-- Edittext to take input for this sample app, for real app you will not need this --> <EditText android:id=\"@+id/editor\" android:layout_width=\"0dp\" android:layout_height=\"40dp\" app:layout_constraintEnd_toStartOf=\"@+id/display_html\" app:layout_constraintHorizontal_bias=\"0.0\" app:layout_constraintStart_toStartOf=\"parent\" app:layout_constraintTop_toTopOf=\"parent\" /> <!-- Button to trigger an event to display html/Rich text--> <Button android:id=\"@+id/display_html\" android:layout_width=\"100dp\" android:layout_height=\"50dp\" android:text=\"Display Html\" app:layout_constraintEnd_toEndOf=\"parent\" app:layout_constraintTop_toTopOf=\"parent\" /> <!-- Scroll View for smooth scrolling --> <ScrollView android:layout_width=\"0dp\" android:layout_height=\"0dp\" android:layout_marginTop=\"16dp\" app:layout_constraintBottom_toBottomOf=\"parent\" app:layout_constraintEnd_toEndOf=\"parent\" app:layout_constraintStart_toStartOf=\"parent\" app:layout_constraintTop_toBottomOf=\"@+id/editor\"> <!-- Text View in which you will display the html after processing the input--> <TextView android:id=\"@+id/html_viewer\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\"> </TextView> </ScrollView> </androidx.constraintlayout.widget.ConstraintLayout>", "e": 3662, "s": 1766, "text": null }, { "code": null, "e": 3673, "s": 3662, "text": "Output UI:" }, { "code": null, "e": 3873, "s": 3673, "text": "Create a class that will download images contained in the img tag. Below is the complete ImageGetter.kt file. Understand the complete code by referring to the corresponding comments inside the code. " }, { "code": null, "e": 3888, "s": 3873, "text": "ImageGetter.kt" }, { "code": "import android.content.res.Resourcesimport android.graphics.Bitmapimport android.graphics.Canvasimport android.graphics.drawable.BitmapDrawableimport android.graphics.drawable.Drawableimport android.text.Htmlimport android.widget.TextViewimport com.squareup.picasso.Picassoimport kotlinx.coroutines.Dispatchersimport kotlinx.coroutines.GlobalScopeimport kotlinx.coroutines.launchimport kotlinx.coroutines.withContext // Class to download Images which extends [Html.ImageGetter]class ImageGetter( private val res: Resources, private val htmlTextView: TextView) : Html.ImageGetter { // Function needs to overridden when extending [Html.ImageGetter] , // which will download the image override fun getDrawable(url: String): Drawable { val holder = BitmapDrawablePlaceHolder(res, null) // Coroutine Scope to download image in Background GlobalScope.launch(Dispatchers.IO) { runCatching { // downloading image in bitmap format using [Picasso] Library val bitmap = Picasso.get().load(url).get() val drawable = BitmapDrawable(res, bitmap) // To make sure Images don't go out of screen , Setting width less // than screen width, You can change image size if you want val width = getScreenWidth() - 150 // Images may stretch out if you will only resize width, // hence resize height to according to aspect ratio val aspectRatio: Float = (drawable.intrinsicWidth.toFloat()) / (drawable.intrinsicHeight.toFloat()) val height = width / aspectRatio drawable.setBounds(10, 20, width, height.toInt()) holder.setDrawable(drawable) holder.setBounds(10, 20, width, height.toInt()) withContext(Dispatchers.Main) { htmlTextView.text = htmlTextView.text } } } return holder } // Actually Putting images internal class BitmapDrawablePlaceHolder(res: Resources, bitmap: Bitmap?) : BitmapDrawable(res, bitmap) { private var drawable: Drawable? = null override fun draw(canvas: Canvas) { drawable?.run { draw(canvas) } } fun setDrawable(drawable: Drawable) { this.drawable = drawable } } // Function to get screenWidth used above fun getScreenWidth() = Resources.getSystem().displayMetrics.widthPixels}", "e": 6409, "s": 3888, "text": null }, { "code": null, "e": 6522, "s": 6409, "text": "Note: One can change the height and the width of the image according to your will in the getDrawable() function." }, { "code": null, "e": 6591, "s": 6522, "text": "Create a click-Listener for the button inside the onCreate() method." }, { "code": null, "e": 6607, "s": 6591, "text": "MainActivity.kt" }, { "code": "class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // Click Listener to listener button click events. // display_html is button id from activity_main.xml // You don't need to get reference to it because kotlin // provides synthetic import and // We are gonna use for the same for rest of Views display_html.setOnClickListener { if (editor.text.isNotEmpty()) { displayHtml(editor.text.toString()) } } }}", "e": 7240, "s": 6607, "text": null }, { "code": null, "e": 7317, "s": 7240, "text": "Create a function displayHtml() which you just called inside click listener." }, { "code": null, "e": 7470, "s": 7317, "text": "Note: Kotlin has Synthetic import ,so there was no need of storing reference to views in a variable and we are going to do the same for all other views." }, { "code": null, "e": 7477, "s": 7470, "text": "Kotlin" }, { "code": "private fun displayHtml(html: String) { // Creating object of ImageGetter class you just created val imageGetter = ImageGetter(resources, html_viewer) // Using Html framework to parse html val styledText=HtmlCompat.fromHtml(html, HtmlCompat.FROM_HTML_MODE_LEGACY, imageGetter,null) // to enable image/link clicking html_viewer.movementMethod = LinkMovementMethod.getInstance() // setting the text after formatting html and downloading and setting images html_viewer.text = styledText }", "e": 8113, "s": 7477, "text": null }, { "code": null, "e": 8232, "s": 8113, "text": "So now the Image work is done, now it should load the images. Below is the complete code for the MainActivity.kt file." }, { "code": null, "e": 8239, "s": 8232, "text": "Kotlin" }, { "code": "import android.os.Bundleimport android.text.method.LinkMovementMethodimport androidx.appcompat.app.AppCompatActivityimport androidx.core.text.HtmlCompatimport kotlinx.android.synthetic.main.activity_main.* class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // Click Listener to listener button click events. // display_html is button id from activity_main.xml // You don't need to get reference to it // because kotlin provides synthetic import and // We are gonna use for the same for rest of Views display_html.setOnClickListener { if (editor.text.isNotEmpty()) { displayHtml(editor.text.toString()) } } } private fun displayHtml(html: String) { // Creating object of ImageGetter class you just created val imageGetter = ImageGetter(resources, html_viewer) // Using Html framework to parse html val styledText = HtmlCompat.fromHtml(html, HtmlCompat.FROM_HTML_MODE_LEGACY, imageGetter,null) // to enable image/link clicking html_viewer.movementMethod = LinkMovementMethod.getInstance() // setting the text after formatting html and downloading and setting images html_viewer.text = styledText }}", "e": 9648, "s": 8239, "text": null }, { "code": null, "e": 9805, "s": 9648, "text": "Let’s see how it’s working now. Use HTML of another webpage. Here we have used the following webpage of the GFG article. Get the HTML string file from here." }, { "code": null, "e": 9909, "s": 9805, "text": "Note: Remember that input the HTML text inside the EditText and then click on the “DISPLAY HTML” Button" }, { "code": null, "e": 10041, "s": 9909, "text": "The images are now loading but you can see, for the blockquote part, there is the plain ugly blue line. We are now gonna fix that. " }, { "code": null, "e": 10126, "s": 10041, "text": "Create a Kotlin Class named QuoteSpanClass and add this following code to this file." }, { "code": null, "e": 10144, "s": 10126, "text": "QuoteSpanClass.kt" }, { "code": "import android.graphics.Canvasimport android.graphics.Paintimport android.text.Layoutimport android.text.style.LeadingMarginSpanimport android.text.style.LineBackgroundSpan class QuoteSpanClass( private val backgroundColor: Int, private val stripeColor: Int, private val stripeWidth: Float, private val gap: Float) : LeadingMarginSpan, LineBackgroundSpan { // Margin for the block quote tag override fun getLeadingMargin(first: Boolean): Int { return (stripeWidth + gap).toInt() } // this function draws the margin. override fun drawLeadingMargin( c: Canvas, p: Paint, x: Int, dir: Int, top: Int, baseline: Int, bottom: Int, text: CharSequence, start: Int, end: Int, first: Boolean, layout: Layout ) { val style = p.style val paintColor = p.color p.style = Paint.Style.FILL p.color = stripeColor // Creating margin according to color and stripewidth it recieves // Press CTRL+Q on function name to read more c.drawRect(x.toFloat(), top.toFloat(), x + dir * stripeWidth, bottom.toFloat(), p) p.style = style p.color = paintColor } override fun drawBackground( c: Canvas, p: Paint, left: Int, right: Int, top: Int, baseline: Int, bottom: Int, text: CharSequence, start: Int, end: Int, lnum: Int ) { val paintColor = p.color p.color = backgroundColor // It draws the background on which blockquote text is written c.drawRect(left.toFloat(), top.toFloat(), right.toFloat(), bottom.toFloat(), p) p.color = paintColor }}", "e": 11884, "s": 10144, "text": null }, { "code": null, "e": 12096, "s": 11884, "text": "Since the QuoteSpanClass is created, it’s time to use this class in MainActivity.kt, but before you need to create a function to parse blockquote tags and draw the margin and background using the QuoteSpanClass." }, { "code": null, "e": 12112, "s": 12096, "text": "MainActivity.kt" }, { "code": "private fun replaceQuoteSpans(spannable: Spannable) { val quoteSpans: Array<QuoteSpan> = spannable.getSpans(0, spannable.length - 1, QuoteSpan::class.java) for (quoteSpan in quoteSpans) { val start: Int = spannable.getSpanStart(quoteSpan) val end: Int = spannable.getSpanEnd(quoteSpan) val flags: Int = spannable.getSpanFlags(quoteSpan) spannable.removeSpan(quoteSpan) spannable.setSpan( QuoteSpanClass( // background color ContextCompat.getColor(this, R.color.colorPrimary), // strip color ContextCompat.getColor(this, R.color.colorAccent), // strip width 10F, 50F ), start, end, flags ) } }", "e": 12917, "s": 12112, "text": null }, { "code": null, "e": 13075, "s": 12917, "text": "And finally, call this function from displayHtml() function before setting the text for html_viewer. Below is the complete code for the MainActivity.kt file." }, { "code": null, "e": 13082, "s": 13075, "text": "Kotlin" }, { "code": "import android.os.Bundleimport android.text.Spannableimport android.text.method.LinkMovementMethodimport android.text.style.QuoteSpanimport androidx.appcompat.app.AppCompatActivityimport androidx.core.content.ContextCompatimport androidx.core.text.HtmlCompatimport kotlinx.android.synthetic.main.activity_main.* class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // Click Listener to listener button click events. // display_html is button id from activity_main.xml // You don't need to get reference to it // because kotlin provides synthetic import and // We are gonna use for the same for rest of Views display_html.setOnClickListener { if (editor.text.isNotEmpty()) { displayHtml(editor.text.toString()) } } } private fun displayHtml(html: String) { // Creating object of ImageGetter class you just created val imageGetter = ImageGetter(resources, html_viewer) // Using Html framework to parse html val styledText = HtmlCompat.fromHtml(html, HtmlCompat.FROM_HTML_MODE_LEGACY, imageGetter,null) replaceQuoteSpans(styledText as Spannable) // setting the text after formatting html and downloading and setting images html_viewer.text = styledText // to enable image/link clicking html_viewer.movementMethod = LinkMovementMethod.getInstance() } private fun replaceQuoteSpans(spannable: Spannable) { val quoteSpans: Array<QuoteSpan> = spannable.getSpans(0, spannable.length - 1, QuoteSpan::class.java) for (quoteSpan in quoteSpans) { val start: Int = spannable.getSpanStart(quoteSpan) val end: Int = spannable.getSpanEnd(quoteSpan) val flags: Int = spannable.getSpanFlags(quoteSpan) spannable.removeSpan(quoteSpan) spannable.setSpan( QuoteSpanClass( // background color ContextCompat.getColor(this, R.color.colorPrimary), // strip color ContextCompat.getColor(this, R.color.colorAccent), // strip width 10F, 50F ), start, end, flags ) } }}", "e": 15519, "s": 13082, "text": null }, { "code": null, "e": 15567, "s": 15519, "text": "Now let’s see the changes in the output screen." }, { "code": null, "e": 15694, "s": 15567, "text": "Note: One can change strip Color, background color, strip width of your choice in replaceQuoteSpans function, and beautify it." }, { "code": null, "e": 15830, "s": 15694, "text": "But there is still one problem. What if you click an image? Nothing happens as of now. You need to add a few more lines to handle that." }, { "code": null, "e": 15837, "s": 15830, "text": "Kotlin" }, { "code": "// Function to parse image tags and enable click eventsfun ImageClick(html: Spannable) { for (span in html.getSpans(0, html.length, ImageSpan::class.java)) { val flags = html.getSpanFlags(span) val start = html.getSpanStart(span) val end = html.getSpanEnd(span) html.setSpan(object : URLSpan(span.source) { override fun onClick(v: View) { Log.d(TAG, \"onClick: url is ${span.source}\") } }, start, end, flags)}", "e": 16295, "s": 15837, "text": null }, { "code": null, "e": 16450, "s": 16295, "text": "And then call this function from displayHtml() Function before setting the text for html_viewer. Below is the complete code for the MainActivity.kt file. " }, { "code": null, "e": 16457, "s": 16450, "text": "Kotlin" }, { "code": "import android.os.Bundleimport android.text.Spannableimport android.text.method.LinkMovementMethodimport android.text.style.ImageSpanimport android.text.style.QuoteSpanimport android.text.style.URLSpanimport android.util.Logimport android.view.Viewimport androidx.appcompat.app.AppCompatActivityimport androidx.core.content.ContextCompatimport androidx.core.text.HtmlCompatimport kotlinx.android.synthetic.main.activity_main.* private const val TAG=\"MainActivity\" class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // Click Listener to listener button click events. // display_html is button id from activity_main.xml // You don't need to get reference to it // because kotlin provides synthetic import and // We are gonna use for the same for rest of Views display_html.setOnClickListener { if (editor.text.isNotEmpty()) { displayHtml(editor.text.toString()) } } } private fun displayHtml(html: String) { // Creating object of ImageGetter class you just created val imageGetter = ImageGetter(resources, html_viewer) // Using Html framework to parse html val styledText = HtmlCompat.fromHtml(html, HtmlCompat.FROM_HTML_MODE_LEGACY, imageGetter, null) replaceQuoteSpans(styledText as Spannable) ImageClick(styledText as Spannable) // setting the text after formatting html and downloading and setting images html_viewer.text = styledText // to enable image/link clicking html_viewer.movementMethod = LinkMovementMethod.getInstance() } private fun replaceQuoteSpans(spannable: Spannable) { val quoteSpans: Array<QuoteSpan> = spannable.getSpans(0, spannable.length - 1, QuoteSpan::class.java) for (quoteSpan in quoteSpans) { val start: Int = spannable.getSpanStart(quoteSpan) val end: Int = spannable.getSpanEnd(quoteSpan) val flags: Int = spannable.getSpanFlags(quoteSpan) spannable.removeSpan(quoteSpan) spannable.setSpan( QuoteSpanClass( // background color ContextCompat.getColor(this, R.color.colorPrimary), // strip color ContextCompat.getColor(this, R.color.colorAccent), // strip width 10F, 50F ), start, end, flags ) } } // Function to parse image tags and enable click events fun ImageClick(html: Spannable) { for (span in html.getSpans(0, html.length, ImageSpan::class.java)) { val flags = html.getSpanFlags(span) val start = html.getSpanStart(span) val end = html.getSpanEnd(span) html.setSpan(object : URLSpan(span.source) { override fun onClick(v: View) { Log.d(TAG, \"onClick: url is ${span.source}\") } }, start, end, flags) } }}", "e": 19623, "s": 16457, "text": null }, { "code": null, "e": 19777, "s": 19623, "text": "Now if you click on any Image and check Logcat you will see the URL of the image is being logged. From there you can trigger some function with that URL." }, { "code": null, "e": 19823, "s": 19777, "text": "Resource: Get the complete project file here." }, { "code": null, "e": 19835, "s": 19823, "text": "anikaseth98" }, { "code": null, "e": 19847, "s": 19835, "text": "anikakapoor" }, { "code": null, "e": 19867, "s": 19847, "text": "abhishek0719kadiyan" }, { "code": null, "e": 19877, "s": 19867, "text": "ruhelaa48" }, { "code": null, "e": 19889, "s": 19877, "text": "kashishsoda" }, { "code": null, "e": 19897, "s": 19889, "text": "android" }, { "code": null, "e": 19905, "s": 19897, "text": "Android" }, { "code": null, "e": 19912, "s": 19905, "text": "Kotlin" }, { "code": null, "e": 19920, "s": 19912, "text": "Android" } ]
Sum of all elements between k1’th and k2’th smallest elements
06 Jul, 2022 Given an array of integers and two numbers k1 and k2. Find the sum of all elements between given two k1’th and k2’th smallest elements of the array. It may be assumed that (1 <= k1 < k2 <= n) and all elements of array are distinct. Examples : Input : arr[] = {20, 8, 22, 4, 12, 10, 14}, k1 = 3, k2 = 6 Output : 26 3rd smallest element is 10. 6th smallest element is 20. Sum of all element between k1 & k2 is 12 + 14 = 26 Input : arr[] = {10, 2, 50, 12, 48, 13}, k1 = 2, k2 = 6 Output : 73 Method 1 (Sorting): First sort the given array using a O(n log n) sorting algorithm like Merge Sort, Heap Sort, etc and return the sum of all element between index k1 and k2 in the sorted array. Implementation: C++ Java Python3 C# PHP Javascript // C++ program to find sum of all element between// to K1'th and k2'th smallest elements in array#include <bits/stdc++.h> using namespace std; // Returns sum between two kth smallest elements of the arrayint sumBetweenTwoKth(int arr[], int n, int k1, int k2){ // Sort the given array sort(arr, arr + n); /* Below code is equivalent to int result = 0; for (int i=k1; i<k2-1; i++) result += arr[i]; */ return accumulate(arr + k1, arr + k2 - 1, 0);} // Driver programint main(){ int arr[] = { 20, 8, 22, 4, 12, 10, 14 }; int k1 = 3, k2 = 6; int n = sizeof(arr) / sizeof(arr[0]); cout << sumBetweenTwoKth(arr, n, k1, k2); return 0;} // Java program to find sum of all element// between to K1'th and k2'th smallest// elements in arrayimport java.util.Arrays; class GFG { // Returns sum between two kth smallest // element of array static int sumBetweenTwoKth(int arr[], int k1, int k2) { // Sort the given array Arrays.sort(arr); // Below code is equivalent to int result = 0; for (int i = k1; i < k2 - 1; i++) result += arr[i]; return result; } // Driver code public static void main(String[] args) { int arr[] = { 20, 8, 22, 4, 12, 10, 14 }; int k1 = 3, k2 = 6; int n = arr.length; System.out.print(sumBetweenTwoKth(arr, k1, k2)); }} // This code is contributed by Anant Agarwal. # Python program to find sum of# all element between to K1'th and# k2'th smallest elements in array # Returns sum between two kth# smallest element of arraydef sumBetweenTwoKth(arr, n, k1, k2): # Sort the given array arr.sort() result = 0 for i in range(k1, k2-1): result += arr[i] return result # Driver codearr = [ 20, 8, 22, 4, 12, 10, 14 ]k1 = 3; k2 = 6n = len(arr)print(sumBetweenTwoKth(arr, n, k1, k2)) # This code is contributed by Anant Agarwal. // C# program to find sum of all element// between to K1'th and k2'th smallest// elements in arrayusing System; class GFG { // Returns sum between two kth smallest // element of array static int sumBetweenTwoKth(int[] arr, int n, int k1, int k2) { // Sort the given array Array.Sort(arr); // Below code is equivalent to int result = 0; for (int i = k1; i < k2 - 1; i++) result += arr[i]; return result; } // Driver code public static void Main() { int[] arr = { 20, 8, 22, 4, 12, 10, 14 }; int k1 = 3, k2 = 6; int n = arr.Length; Console.Write(sumBetweenTwoKth(arr, n, k1, k2)); }} // This code is contributed by nitin mittal. <?php// PHP program to find sum of all element between// to K1'th and k2'th smallest elements in array // Returns sum between two kth smallest elements of the arrayfunction sumBetweenTwoKth($arr, $n, $k1, $k2){ // Sort the given array sort($arr); // Below code is equivalent to $result = 0; for ($i = $k1; $i < $k2 - 1; $i++) $result += $arr[$i]; return $result;} // Driver program $arr = array( 20, 8, 22, 4, 12, 10, 14 ); $k1 = 3; $k2 = 6; $n = count($arr);; echo sumBetweenTwoKth($arr, $n, $k1, $k2); // This code is contributed by mits?> <script> // Javascript program to find sum of all element// between to K1'th and k2'th smallest// elements in array // Returns sum between two kth smallest// element of arrayfunction sumBetweenTwoKth(arr, k1 , k2){ // Sort the given array arr.sort(function(a, b){return a - b}); // Below code is equivalent to var result = 0; for(var i = k1; i < k2 - 1; i++) result += arr[i]; return result;} // Driver codevar arr = [ 20, 8, 22, 4, 12, 10, 14 ];var k1 = 3, k2 = 6;var n = arr.length; document.write(sumBetweenTwoKth(arr, k1, k2)); // This code is contributed by shikhasingrajput </script> 26 Time Complexity: O(n log n) Method 2 (Using Min Heap): We can optimize the above solution be using a min heap. Create a min heap of all array elements. (This step takes O(n) time) Do extract minimum k1 times (This step takes O(K1 Log n) time) Do extract minimum k2 – k1 – 1 time and sum all extracted elements. (This step takes O ((K2 – k1) * Log n) time) Create a min heap of all array elements. (This step takes O(n) time) Do extract minimum k1 times (This step takes O(K1 Log n) time) Do extract minimum k2 – k1 – 1 time and sum all extracted elements. (This step takes O ((K2 – k1) * Log n) time) Time Complexity Analysis: By doing a simple analysis, we can observe that time complexity of step3 [ Determining step for overall time complexity ] can reach to O(nlogn) also. Take a look at the following description:Time Complexity of step3 is: O((k2-k1)*log(n)) . In worst case, (k2-k1) would be almost O(n) [ Assume situation when k1=0 and k2=len(arr)-1 ]When O(k2-k1) =O(n) then overall complexity will be O(n* Log n ) .but in most of the cases...it will be lesser than O(n Log n) that is equal to sorting approach described above. Time Complexity of step3 is: O((k2-k1)*log(n)) . In worst case, (k2-k1) would be almost O(n) [ Assume situation when k1=0 and k2=len(arr)-1 ] When O(k2-k1) =O(n) then overall complexity will be O(n* Log n ) . but in most of the cases...it will be lesser than O(n Log n) that is equal to sorting approach described above. Implementation: C++ Java Python3 C# Javascript // C++ implementation of above approach#include <bits/stdc++.h>using namespace std; int n = 7; void minheapify(int a[], int index){ int small = index; int l = 2 * index + 1; int r = 2 * index + 2; if (l < n && a[l] < a[small]) small = l; if (r < n && a[r] < a[small]) small = r; if (small != index) { swap(a[small], a[index]); minheapify(a, small); }} int main(){ int i = 0; int k1 = 3; int k2 = 6; int a[] = { 20, 8, 22, 4, 12, 10, 14 }; int ans = 0; for (i = (n / 2) - 1; i >= 0; i--) { minheapify(a, i); } // decreasing value by 1 because we want min heapifying k times and it starts // from 0 so we have to decrease it 1 time k1--; k2--; // Step 1: Do extract minimum k1 times (This step takes O(K1 Log n) time) for (i = 0; i <= k1; i++) { // cout<<a[0]<<endl; a[0] = a[n - 1]; n--; minheapify(a, 0); } /*Step 2: Do extract minimum k2 – k1 – 1 times and sum all extracted elements. (This step takes O ((K2 – k1) * Log n) time)*/ for (i = k1 + 1; i < k2; i++) { // cout<<a[0]<<endl; ans += a[0]; a[0] = a[n - 1]; n--; minheapify(a, 0); } cout << ans; return 0;} // Java implementation of above approachclass GFG{ static int n = 7; static void minheapify(int []a, int index){ int small = index; int l = 2 * index + 1; int r = 2 * index + 2; if (l < n && a[l] < a[small]) small = l; if (r < n && a[r] < a[small]) small = r; if (small != index) { int t = a[small]; a[small] = a[index]; a[index] = t; minheapify(a, small); }} // Driver codepublic static void main (String[] args){ int i = 0; int k1 = 3; int k2 = 6; int []a = { 20, 8, 22, 4, 12, 10, 14 }; int ans = 0; for (i = (n / 2) - 1; i >= 0; i--) { minheapify(a, i); } // decreasing value by 1 because we want // min heapifying k times and it starts // from 0 so we have to decrease it 1 time k1--; k2--; // Step 1: Do extract minimum k1 times // (This step takes O(K1 Log n) time) for (i = 0; i <= k1; i++) { a[0] = a[n - 1]; n--; minheapify(a, 0); } for (i = k1 + 1; i < k2; i++) { // cout<<a[0]<<endl; ans += a[0]; a[0] = a[n - 1]; n--; minheapify(a, 0); } System.out.println(ans);}} // This code is contributed by mits # Python 3 implementation of above approachn = 7 def minheapify(a, index): small = index l = 2 * index + 1 r = 2 * index + 2 if (l < n and a[l] < a[small]): small = l if (r < n and a[r] < a[small]): small = r if (small != index): (a[small], a[index]) = (a[index], a[small]) minheapify(a, small) # Driver Codei = 0k1 = 3k2 = 6 a = [ 20, 8, 22, 4, 12, 10, 14 ]ans = 0 for i in range((n //2) - 1, -1, -1): minheapify(a, i) # decreasing value by 1 because we want# min heapifying k times and it starts# from 0 so we have to decrease it 1 timek1 -= 1k2 -= 1 # Step 1: Do extract minimum k1 times# (This step takes O(K1 Log n) time)for i in range(0, k1 + 1): a[0] = a[n - 1] n -= 1 minheapify(a, 0) # Step 2: Do extract minimum k2 – k1 – 1 times and# sum all extracted elements.# (This step takes O ((K2 – k1) * Log n) time)*/for i in range(k1 + 1, k2) : ans += a[0] a[0] = a[n - 1] n -= 1 minheapify(a, 0) print (ans) # This code is contributed# by Atul_kumar_Shrivastava // C# implementation of above approachusing System; class GFG{ static int n = 7; static void minheapify(int []a, int index){ int small = index; int l = 2 * index + 1; int r = 2 * index + 2; if (l < n && a[l] < a[small]) small = l; if (r < n && a[r] < a[small]) small = r; if (small != index) { int t = a[small]; a[small] = a[index]; a[index] = t; minheapify(a, small); }} // Driver codestatic void Main(){ int i = 0; int k1 = 3; int k2 = 6; int []a = { 20, 8, 22, 4, 12, 10, 14 }; int ans = 0; for (i = (n / 2) - 1; i >= 0; i--) { minheapify(a, i); } // decreasing value by 1 because we want // min heapifying k times and it starts // from 0 so we have to decrease it 1 time k1--; k2--; // Step 1: Do extract minimum k1 times // (This step takes O(K1 Log n) time) for (i = 0; i <= k1; i++) { // cout<<a[0]<<endl; a[0] = a[n - 1]; n--; minheapify(a, 0); } /*Step 2: Do extract minimum k2 – k1 – 1 times and sum all extracted elements. (This step takes O ((K2 – k1) * Log n) time)*/ for (i = k1 + 1; i < k2; i++) { // cout<<a[0]<<endl; ans += a[0]; a[0] = a[n - 1]; n--; minheapify(a, 0); } Console.Write(ans);}} // This code is contributed by mits <script> // Javascript implementation of above approachlet n = 7; function minheapify(a, index){ let small = index; let l = 2 * index + 1; let r = 2 * index + 2; if (l < n && a[l] < a[small]) small = l; if (r < n && a[r] < a[small]) small = r; if (small != index) { let t = a[small]; a[small] = a[index]; a[index] = t; minheapify(a, small); }} // Driver codelet i = 0;let k1 = 3;let k2 = 6; let a = [ 20, 8, 22, 4, 12, 10, 14 ]; let ans = 0; for(i = parseInt(n / 2, 10) - 1; i >= 0; i--){ minheapify(a, i);} // decreasing value by 1 because we want// min heapifying k times and it starts// from 0 so we have to decrease it 1 timek1--;k2--; // Step 1: Do extract minimum k1 times// (This step takes O(K1 Log n) time)for(i = 0; i <= k1; i++){ a[0] = a[n - 1]; n--; minheapify(a, 0);} for(i = k1 + 1; i < k2; i++){ // cout<<a[0]<<endl; ans += a[0]; a[0] = a[n - 1]; n--; minheapify(a, 0);} document.write(ans); // This code is contributed by vaibhavrabadiya117 </script> 26 Overall time complexity of this method is O(n + k2 Log n) which is better than sorting based method. References : https://www.geeksforgeeks.org/heap-sort This article is contributed by Nishant_Singh (Pintu). If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. nitin mittal AbhishekVats3 md1844 Mithun Kumar Atul_kumar_Shrivastava shikhasingrajput vaibhavrabadiya117 rajatkumargla19 khushboogoyal499 hardikkoriintern STL Arrays Heap Sorting Arrays Sorting Heap STL 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 Linear Search Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum) HeapSort K'th Smallest/Largest Element in Unsorted Array | Set 1 Binary Heap Introduction to Data Structures Huffman Coding | Greedy Algo-3
[ { "code": null, "e": 52, "s": 24, "text": "\n06 Jul, 2022" }, { "code": null, "e": 284, "s": 52, "text": "Given an array of integers and two numbers k1 and k2. Find the sum of all elements between given two k1’th and k2’th smallest elements of the array. It may be assumed that (1 <= k1 < k2 <= n) and all elements of array are distinct." }, { "code": null, "e": 296, "s": 284, "text": "Examples : " }, { "code": null, "e": 587, "s": 296, "text": "Input : arr[] = {20, 8, 22, 4, 12, 10, 14}, k1 = 3, k2 = 6 \nOutput : 26 \n 3rd smallest element is 10. 6th smallest element \n is 20. Sum of all element between k1 & k2 is\n 12 + 14 = 26\n\nInput : arr[] = {10, 2, 50, 12, 48, 13}, k1 = 2, k2 = 6 \nOutput : 73 " }, { "code": null, "e": 782, "s": 587, "text": "Method 1 (Sorting): First sort the given array using a O(n log n) sorting algorithm like Merge Sort, Heap Sort, etc and return the sum of all element between index k1 and k2 in the sorted array." }, { "code": null, "e": 798, "s": 782, "text": "Implementation:" }, { "code": null, "e": 802, "s": 798, "text": "C++" }, { "code": null, "e": 807, "s": 802, "text": "Java" }, { "code": null, "e": 815, "s": 807, "text": "Python3" }, { "code": null, "e": 818, "s": 815, "text": "C#" }, { "code": null, "e": 822, "s": 818, "text": "PHP" }, { "code": null, "e": 833, "s": 822, "text": "Javascript" }, { "code": "// C++ program to find sum of all element between// to K1'th and k2'th smallest elements in array#include <bits/stdc++.h> using namespace std; // Returns sum between two kth smallest elements of the arrayint sumBetweenTwoKth(int arr[], int n, int k1, int k2){ // Sort the given array sort(arr, arr + n); /* Below code is equivalent to int result = 0; for (int i=k1; i<k2-1; i++) result += arr[i]; */ return accumulate(arr + k1, arr + k2 - 1, 0);} // Driver programint main(){ int arr[] = { 20, 8, 22, 4, 12, 10, 14 }; int k1 = 3, k2 = 6; int n = sizeof(arr) / sizeof(arr[0]); cout << sumBetweenTwoKth(arr, n, k1, k2); return 0;}", "e": 1503, "s": 833, "text": null }, { "code": "// Java program to find sum of all element// between to K1'th and k2'th smallest// elements in arrayimport java.util.Arrays; class GFG { // Returns sum between two kth smallest // element of array static int sumBetweenTwoKth(int arr[], int k1, int k2) { // Sort the given array Arrays.sort(arr); // Below code is equivalent to int result = 0; for (int i = k1; i < k2 - 1; i++) result += arr[i]; return result; } // Driver code public static void main(String[] args) { int arr[] = { 20, 8, 22, 4, 12, 10, 14 }; int k1 = 3, k2 = 6; int n = arr.length; System.out.print(sumBetweenTwoKth(arr, k1, k2)); }} // This code is contributed by Anant Agarwal.", "e": 2338, "s": 1503, "text": null }, { "code": "# Python program to find sum of# all element between to K1'th and# k2'th smallest elements in array # Returns sum between two kth# smallest element of arraydef sumBetweenTwoKth(arr, n, k1, k2): # Sort the given array arr.sort() result = 0 for i in range(k1, k2-1): result += arr[i] return result # Driver codearr = [ 20, 8, 22, 4, 12, 10, 14 ]k1 = 3; k2 = 6n = len(arr)print(sumBetweenTwoKth(arr, n, k1, k2)) # This code is contributed by Anant Agarwal.", "e": 2817, "s": 2338, "text": null }, { "code": "// C# program to find sum of all element// between to K1'th and k2'th smallest// elements in arrayusing System; class GFG { // Returns sum between two kth smallest // element of array static int sumBetweenTwoKth(int[] arr, int n, int k1, int k2) { // Sort the given array Array.Sort(arr); // Below code is equivalent to int result = 0; for (int i = k1; i < k2 - 1; i++) result += arr[i]; return result; } // Driver code public static void Main() { int[] arr = { 20, 8, 22, 4, 12, 10, 14 }; int k1 = 3, k2 = 6; int n = arr.Length; Console.Write(sumBetweenTwoKth(arr, n, k1, k2)); }} // This code is contributed by nitin mittal.", "e": 3589, "s": 2817, "text": null }, { "code": "<?php// PHP program to find sum of all element between// to K1'th and k2'th smallest elements in array // Returns sum between two kth smallest elements of the arrayfunction sumBetweenTwoKth($arr, $n, $k1, $k2){ // Sort the given array sort($arr); // Below code is equivalent to $result = 0; for ($i = $k1; $i < $k2 - 1; $i++) $result += $arr[$i]; return $result;} // Driver program $arr = array( 20, 8, 22, 4, 12, 10, 14 ); $k1 = 3; $k2 = 6; $n = count($arr);; echo sumBetweenTwoKth($arr, $n, $k1, $k2); // This code is contributed by mits?>", "e": 4197, "s": 3589, "text": null }, { "code": "<script> // Javascript program to find sum of all element// between to K1'th and k2'th smallest// elements in array // Returns sum between two kth smallest// element of arrayfunction sumBetweenTwoKth(arr, k1 , k2){ // Sort the given array arr.sort(function(a, b){return a - b}); // Below code is equivalent to var result = 0; for(var i = k1; i < k2 - 1; i++) result += arr[i]; return result;} // Driver codevar arr = [ 20, 8, 22, 4, 12, 10, 14 ];var k1 = 3, k2 = 6;var n = arr.length; document.write(sumBetweenTwoKth(arr, k1, k2)); // This code is contributed by shikhasingrajput </script>", "e": 4851, "s": 4197, "text": null }, { "code": null, "e": 4854, "s": 4851, "text": "26" }, { "code": null, "e": 4883, "s": 4854, "text": "Time Complexity: O(n log n) " }, { "code": null, "e": 4910, "s": 4883, "text": "Method 2 (Using Min Heap):" }, { "code": null, "e": 4967, "s": 4910, "text": "We can optimize the above solution be using a min heap. " }, { "code": null, "e": 5212, "s": 4967, "text": "Create a min heap of all array elements. (This step takes O(n) time) Do extract minimum k1 times (This step takes O(K1 Log n) time) Do extract minimum k2 – k1 – 1 time and sum all extracted elements. (This step takes O ((K2 – k1) * Log n) time)" }, { "code": null, "e": 5282, "s": 5212, "text": "Create a min heap of all array elements. (This step takes O(n) time) " }, { "code": null, "e": 5346, "s": 5282, "text": "Do extract minimum k1 times (This step takes O(K1 Log n) time) " }, { "code": null, "e": 5459, "s": 5346, "text": "Do extract minimum k2 – k1 – 1 time and sum all extracted elements. (This step takes O ((K2 – k1) * Log n) time)" }, { "code": null, "e": 5486, "s": 5459, "text": "Time Complexity Analysis: " }, { "code": null, "e": 5637, "s": 5486, "text": "By doing a simple analysis, we can observe that time complexity of step3 [ Determining step for overall time complexity ] can reach to O(nlogn) also. " }, { "code": null, "e": 5999, "s": 5637, "text": "Take a look at the following description:Time Complexity of step3 is: O((k2-k1)*log(n)) . In worst case, (k2-k1) would be almost O(n) [ Assume situation when k1=0 and k2=len(arr)-1 ]When O(k2-k1) =O(n) then overall complexity will be O(n* Log n ) .but in most of the cases...it will be lesser than O(n Log n) that is equal to sorting approach described above." }, { "code": null, "e": 6050, "s": 5999, "text": "Time Complexity of step3 is: O((k2-k1)*log(n)) . " }, { "code": null, "e": 6144, "s": 6050, "text": "In worst case, (k2-k1) would be almost O(n) [ Assume situation when k1=0 and k2=len(arr)-1 ]" }, { "code": null, "e": 6211, "s": 6144, "text": "When O(k2-k1) =O(n) then overall complexity will be O(n* Log n ) ." }, { "code": null, "e": 6323, "s": 6211, "text": "but in most of the cases...it will be lesser than O(n Log n) that is equal to sorting approach described above." }, { "code": null, "e": 6339, "s": 6323, "text": "Implementation:" }, { "code": null, "e": 6343, "s": 6339, "text": "C++" }, { "code": null, "e": 6348, "s": 6343, "text": "Java" }, { "code": null, "e": 6356, "s": 6348, "text": "Python3" }, { "code": null, "e": 6359, "s": 6356, "text": "C#" }, { "code": null, "e": 6370, "s": 6359, "text": "Javascript" }, { "code": "// C++ implementation of above approach#include <bits/stdc++.h>using namespace std; int n = 7; void minheapify(int a[], int index){ int small = index; int l = 2 * index + 1; int r = 2 * index + 2; if (l < n && a[l] < a[small]) small = l; if (r < n && a[r] < a[small]) small = r; if (small != index) { swap(a[small], a[index]); minheapify(a, small); }} int main(){ int i = 0; int k1 = 3; int k2 = 6; int a[] = { 20, 8, 22, 4, 12, 10, 14 }; int ans = 0; for (i = (n / 2) - 1; i >= 0; i--) { minheapify(a, i); } // decreasing value by 1 because we want min heapifying k times and it starts // from 0 so we have to decrease it 1 time k1--; k2--; // Step 1: Do extract minimum k1 times (This step takes O(K1 Log n) time) for (i = 0; i <= k1; i++) { // cout<<a[0]<<endl; a[0] = a[n - 1]; n--; minheapify(a, 0); } /*Step 2: Do extract minimum k2 – k1 – 1 times and sum all extracted elements. (This step takes O ((K2 – k1) * Log n) time)*/ for (i = k1 + 1; i < k2; i++) { // cout<<a[0]<<endl; ans += a[0]; a[0] = a[n - 1]; n--; minheapify(a, 0); } cout << ans; return 0;}", "e": 7625, "s": 6370, "text": null }, { "code": "// Java implementation of above approachclass GFG{ static int n = 7; static void minheapify(int []a, int index){ int small = index; int l = 2 * index + 1; int r = 2 * index + 2; if (l < n && a[l] < a[small]) small = l; if (r < n && a[r] < a[small]) small = r; if (small != index) { int t = a[small]; a[small] = a[index]; a[index] = t; minheapify(a, small); }} // Driver codepublic static void main (String[] args){ int i = 0; int k1 = 3; int k2 = 6; int []a = { 20, 8, 22, 4, 12, 10, 14 }; int ans = 0; for (i = (n / 2) - 1; i >= 0; i--) { minheapify(a, i); } // decreasing value by 1 because we want // min heapifying k times and it starts // from 0 so we have to decrease it 1 time k1--; k2--; // Step 1: Do extract minimum k1 times // (This step takes O(K1 Log n) time) for (i = 0; i <= k1; i++) { a[0] = a[n - 1]; n--; minheapify(a, 0); } for (i = k1 + 1; i < k2; i++) { // cout<<a[0]<<endl; ans += a[0]; a[0] = a[n - 1]; n--; minheapify(a, 0); } System.out.println(ans);}} // This code is contributed by mits", "e": 8849, "s": 7625, "text": null }, { "code": "# Python 3 implementation of above approachn = 7 def minheapify(a, index): small = index l = 2 * index + 1 r = 2 * index + 2 if (l < n and a[l] < a[small]): small = l if (r < n and a[r] < a[small]): small = r if (small != index): (a[small], a[index]) = (a[index], a[small]) minheapify(a, small) # Driver Codei = 0k1 = 3k2 = 6 a = [ 20, 8, 22, 4, 12, 10, 14 ]ans = 0 for i in range((n //2) - 1, -1, -1): minheapify(a, i) # decreasing value by 1 because we want# min heapifying k times and it starts# from 0 so we have to decrease it 1 timek1 -= 1k2 -= 1 # Step 1: Do extract minimum k1 times# (This step takes O(K1 Log n) time)for i in range(0, k1 + 1): a[0] = a[n - 1] n -= 1 minheapify(a, 0) # Step 2: Do extract minimum k2 – k1 – 1 times and# sum all extracted elements.# (This step takes O ((K2 – k1) * Log n) time)*/for i in range(k1 + 1, k2) : ans += a[0] a[0] = a[n - 1] n -= 1 minheapify(a, 0) print (ans) # This code is contributed# by Atul_kumar_Shrivastava", "e": 9893, "s": 8849, "text": null }, { "code": "// C# implementation of above approachusing System; class GFG{ static int n = 7; static void minheapify(int []a, int index){ int small = index; int l = 2 * index + 1; int r = 2 * index + 2; if (l < n && a[l] < a[small]) small = l; if (r < n && a[r] < a[small]) small = r; if (small != index) { int t = a[small]; a[small] = a[index]; a[index] = t; minheapify(a, small); }} // Driver codestatic void Main(){ int i = 0; int k1 = 3; int k2 = 6; int []a = { 20, 8, 22, 4, 12, 10, 14 }; int ans = 0; for (i = (n / 2) - 1; i >= 0; i--) { minheapify(a, i); } // decreasing value by 1 because we want // min heapifying k times and it starts // from 0 so we have to decrease it 1 time k1--; k2--; // Step 1: Do extract minimum k1 times // (This step takes O(K1 Log n) time) for (i = 0; i <= k1; i++) { // cout<<a[0]<<endl; a[0] = a[n - 1]; n--; minheapify(a, 0); } /*Step 2: Do extract minimum k2 – k1 – 1 times and sum all extracted elements. (This step takes O ((K2 – k1) * Log n) time)*/ for (i = k1 + 1; i < k2; i++) { // cout<<a[0]<<endl; ans += a[0]; a[0] = a[n - 1]; n--; minheapify(a, 0); } Console.Write(ans);}} // This code is contributed by mits", "e": 11266, "s": 9893, "text": null }, { "code": "<script> // Javascript implementation of above approachlet n = 7; function minheapify(a, index){ let small = index; let l = 2 * index + 1; let r = 2 * index + 2; if (l < n && a[l] < a[small]) small = l; if (r < n && a[r] < a[small]) small = r; if (small != index) { let t = a[small]; a[small] = a[index]; a[index] = t; minheapify(a, small); }} // Driver codelet i = 0;let k1 = 3;let k2 = 6; let a = [ 20, 8, 22, 4, 12, 10, 14 ]; let ans = 0; for(i = parseInt(n / 2, 10) - 1; i >= 0; i--){ minheapify(a, i);} // decreasing value by 1 because we want// min heapifying k times and it starts// from 0 so we have to decrease it 1 timek1--;k2--; // Step 1: Do extract minimum k1 times// (This step takes O(K1 Log n) time)for(i = 0; i <= k1; i++){ a[0] = a[n - 1]; n--; minheapify(a, 0);} for(i = k1 + 1; i < k2; i++){ // cout<<a[0]<<endl; ans += a[0]; a[0] = a[n - 1]; n--; minheapify(a, 0);} document.write(ans); // This code is contributed by vaibhavrabadiya117 </script>", "e": 12335, "s": 11266, "text": null }, { "code": null, "e": 12338, "s": 12335, "text": "26" }, { "code": null, "e": 12439, "s": 12338, "text": "Overall time complexity of this method is O(n + k2 Log n) which is better than sorting based method." }, { "code": null, "e": 12493, "s": 12439, "text": "References : https://www.geeksforgeeks.org/heap-sort " }, { "code": null, "e": 12799, "s": 12493, "text": "This article is contributed by Nishant_Singh (Pintu). If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. " }, { "code": null, "e": 12812, "s": 12799, "text": "nitin mittal" }, { "code": null, "e": 12826, "s": 12812, "text": "AbhishekVats3" }, { "code": null, "e": 12833, "s": 12826, "text": "md1844" }, { "code": null, "e": 12846, "s": 12833, "text": "Mithun Kumar" }, { "code": null, "e": 12869, "s": 12846, "text": "Atul_kumar_Shrivastava" }, { "code": null, "e": 12886, "s": 12869, "text": "shikhasingrajput" }, { "code": null, "e": 12905, "s": 12886, "text": "vaibhavrabadiya117" }, { "code": null, "e": 12921, "s": 12905, "text": "rajatkumargla19" }, { "code": null, "e": 12938, "s": 12921, "text": "khushboogoyal499" }, { "code": null, "e": 12955, "s": 12938, "text": "hardikkoriintern" }, { "code": null, "e": 12959, "s": 12955, "text": "STL" }, { "code": null, "e": 12966, "s": 12959, "text": "Arrays" }, { "code": null, "e": 12971, "s": 12966, "text": "Heap" }, { "code": null, "e": 12979, "s": 12971, "text": "Sorting" }, { "code": null, "e": 12986, "s": 12979, "text": "Arrays" }, { "code": null, "e": 12994, "s": 12986, "text": "Sorting" }, { "code": null, "e": 12999, "s": 12994, "text": "Heap" }, { "code": null, "e": 13003, "s": 12999, "text": "STL" }, { "code": null, "e": 13101, "s": 13003, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 13169, "s": 13101, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 13213, "s": 13169, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 13245, "s": 13213, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 13259, "s": 13245, "text": "Linear Search" }, { "code": null, "e": 13344, "s": 13259, "text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)" }, { "code": null, "e": 13353, "s": 13344, "text": "HeapSort" }, { "code": null, "e": 13409, "s": 13353, "text": "K'th Smallest/Largest Element in Unsorted Array | Set 1" }, { "code": null, "e": 13421, "s": 13409, "text": "Binary Heap" }, { "code": null, "e": 13453, "s": 13421, "text": "Introduction to Data Structures" } ]
Ruby | Array sample() function
06 Dec, 2019 Array#sample() : sample() is a Array class method which returns a random element or n random elements from the array. Syntax: Array.sample() Parameter: Array Return: a random element or n random elements from the array. Example #1 : # Ruby code for sample() method # declaring arraya = [18, 22, 33, nil, 5, 6] # declaring arrayb = [1, 4, 1, 1, 88, 9] # declaring arrayc = [18, 22, 50, 6] # sample method exampleputs "sample() method form : #{a.sample(2)}\n\n" puts "sample() method form : #{b.sample(1)}\n\n" puts "sample() method form : #{c.sample(3)}\n\n" Output : sample() method form : [6, nil] sample() method form : [4] sample() method form : [18, 22, 6] Example #2 : # Ruby code for sample() method # declaring arraya = ["abc", "nil", "dog"] # declaring arrayc = ["cat", nil] # declaring arrayb = ["cow", nil, "dog"] # sample method exampleputs "sample() method form : #{a.sample(2)}\n\n" puts "sample() method form : #{b.sample(1)}\n\n" puts "sample() method form : #{c.sample(3)}\n\n" Output : sample() method form : ["dog", "abc"] sample() method form : ["dog"] sample() method form : ["cat", nil] Ruby Array-class Ruby-Methods Ruby Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Make a Custom Array of Hashes in Ruby? Ruby | Array count() operation Ruby | Array slice() function Ruby | push() function Include v/s Extend in Ruby Global Variable in Ruby Ruby | Array select() function Ruby | Enumerator each_with_index function Ruby | Case Statement Ruby | unless Statement and unless Modifier
[ { "code": null, "e": 28, "s": 0, "text": "\n06 Dec, 2019" }, { "code": null, "e": 146, "s": 28, "text": "Array#sample() : sample() is a Array class method which returns a random element or n random elements from the array." }, { "code": null, "e": 169, "s": 146, "text": "Syntax: Array.sample()" }, { "code": null, "e": 186, "s": 169, "text": "Parameter: Array" }, { "code": null, "e": 248, "s": 186, "text": "Return: a random element or n random elements from the array." }, { "code": null, "e": 261, "s": 248, "text": "Example #1 :" }, { "code": "# Ruby code for sample() method # declaring arraya = [18, 22, 33, nil, 5, 6] # declaring arrayb = [1, 4, 1, 1, 88, 9] # declaring arrayc = [18, 22, 50, 6] # sample method exampleputs \"sample() method form : #{a.sample(2)}\\n\\n\" puts \"sample() method form : #{b.sample(1)}\\n\\n\" puts \"sample() method form : #{c.sample(3)}\\n\\n\"", "e": 592, "s": 261, "text": null }, { "code": null, "e": 601, "s": 592, "text": "Output :" }, { "code": null, "e": 699, "s": 601, "text": "sample() method form : [6, nil]\n\nsample() method form : [4]\n\nsample() method form : [18, 22, 6]\n\n" }, { "code": null, "e": 712, "s": 699, "text": "Example #2 :" }, { "code": "# Ruby code for sample() method # declaring arraya = [\"abc\", \"nil\", \"dog\"] # declaring arrayc = [\"cat\", nil] # declaring arrayb = [\"cow\", nil, \"dog\"] # sample method exampleputs \"sample() method form : #{a.sample(2)}\\n\\n\" puts \"sample() method form : #{b.sample(1)}\\n\\n\" puts \"sample() method form : #{c.sample(3)}\\n\\n\"", "e": 1038, "s": 712, "text": null }, { "code": null, "e": 1047, "s": 1038, "text": "Output :" }, { "code": null, "e": 1156, "s": 1047, "text": "sample() method form : [\"dog\", \"abc\"]\n\nsample() method form : [\"dog\"]\n\nsample() method form : [\"cat\", nil]\n\n" }, { "code": null, "e": 1173, "s": 1156, "text": "Ruby Array-class" }, { "code": null, "e": 1186, "s": 1173, "text": "Ruby-Methods" }, { "code": null, "e": 1191, "s": 1186, "text": "Ruby" }, { "code": null, "e": 1289, "s": 1191, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1335, "s": 1289, "text": "How to Make a Custom Array of Hashes in Ruby?" }, { "code": null, "e": 1366, "s": 1335, "text": "Ruby | Array count() operation" }, { "code": null, "e": 1396, "s": 1366, "text": "Ruby | Array slice() function" }, { "code": null, "e": 1419, "s": 1396, "text": "Ruby | push() function" }, { "code": null, "e": 1446, "s": 1419, "text": "Include v/s Extend in Ruby" }, { "code": null, "e": 1470, "s": 1446, "text": "Global Variable in Ruby" }, { "code": null, "e": 1501, "s": 1470, "text": "Ruby | Array select() function" }, { "code": null, "e": 1544, "s": 1501, "text": "Ruby | Enumerator each_with_index function" }, { "code": null, "e": 1566, "s": 1544, "text": "Ruby | Case Statement" } ]
How to Extract Data from PDF file in Android?
15 Jan, 2021 PDF is a portable document format that is used to represent data such as images, tables, and many more. Nowadays the use of PDF is increased rapidly in different fields. Many apps have switched overusing PDF files to represent data. So some of the apps have a requirement to extract the data from the PDF file and to display that data inside our app. In this article, we will create an application to extract the data from the PDF file and display it in our app. In this article, we will be building a simple application in which we will be extracting the data from the PDF on a button click and display the extracted data in our Text View. Step 1: Create a New Project To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language. Step 2: Add dependency to the build.gradle(Module:app) Chapters descriptions off, selected captions settings, opens captions settings dialog captions off, selected English This is a modal window. Beginning of dialog window. Escape will cancel and close the window. End of dialog window. Navigate to the Gradle Scripts > build.gradle(Module:app) and add the below dependency in the dependencies section. implementation ‘com.itextpdf:itextg:5.5.10’ After adding the dependency click on the sync now option and sync your project. After adding dependency let’s move towards adding a PDF file inside your app. Step 3: Adding PDF file in your app As we are extracting data from PDF files, so we will be adding PDF files inside our app. For adding PDF files to your app we have to create the raw folder first. Please refer to Resource Raw Folder in Android Studio to create a raw folder in android. After creating a new raw directory copy and paste your PDF file inside that “raw” folder. After adding that PDF file in your app, now we will move towards implementation in the XML part. Step 4: Working with the activity_main.xml file Go to the activity_main.xml file and refer to the following code. Below is the code for the activity_main.xml file. XML <?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".MainActivity"> <ScrollView android:layout_width="match_parent" android:layout_height="match_parent"> <!--text view for displaying our extracted text--> <TextView android:id="@+id/idPDFTV" android:layout_width="match_parent" android:layout_height="match_parent" /> </ScrollView> <!--button for starting extraction process--> <Button android:id="@+id/idBtnExtract" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:layout_centerHorizontal="true" android:layout_marginBottom="20dp" android:text="Extract Text from PDF" android:textAllCaps="false" /> </RelativeLayout> After adding XML code now we will move towards our Java part. Step 5: Working with the MainActivity.java file Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail. Java import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.TextView; import androidx.appcompat.app.AppCompatActivity; import com.itextpdf.text.pdf.PdfReader;import com.itextpdf.text.pdf.parser.PdfTextExtractor; public class MainActivity extends AppCompatActivity { // creating variables for // button and text view. private Button extractPDFBtn; private TextView extractedTV; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // initializing variables for button and text view. extractedTV = findViewById(R.id.idPDFTV); extractPDFBtn = findViewById(R.id.idBtnExtract); // adding on click listener for button extractPDFBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // calling method to extract // data from PDF file. extractPDF(); } }); } private void extractPDF() { try { // creating a string for // storing our extracted text. String extractedText = ""; // creating a variable for pdf reader // and passing our PDF file in it. PdfReader reader = new PdfReader("res/raw/amiya_rout.pdf"); // below line is for getting number // of pages of PDF file. int n = reader.getNumberOfPages(); // running a for loop to get the data from PDF // we are storing that data inside our string. for (int i = 0; i < n; i++) { extractedText = extractedText + PdfTextExtractor.getTextFromPage(reader, i + 1).trim() + "\n"; // to extract the PDF content from the different pages } // after extracting all the data we are // setting that string value to our text view. extractedTV.setText(extractedText); // below line is used for closing reader. reader.close(); } catch (Exception e) { // for handling error while extracting the text file. extractedTV.setText("Error found is : \n" + e); } }} After adding this code now run your app and see the output of the code. After you run the app click on Extract Data from PDF button and you will get to see that text is extracted from the PDF file. android Technical Scripter 2020 Android Java Technical Scripter Java Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n15 Jan, 2021" }, { "code": null, "e": 516, "s": 52, "text": "PDF is a portable document format that is used to represent data such as images, tables, and many more. Nowadays the use of PDF is increased rapidly in different fields. Many apps have switched overusing PDF files to represent data. So some of the apps have a requirement to extract the data from the PDF file and to display that data inside our app. In this article, we will create an application to extract the data from the PDF file and display it in our app. " }, { "code": null, "e": 694, "s": 516, "text": "In this article, we will be building a simple application in which we will be extracting the data from the PDF on a button click and display the extracted data in our Text View." }, { "code": null, "e": 723, "s": 694, "text": "Step 1: Create a New Project" }, { "code": null, "e": 885, "s": 723, "text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language." }, { "code": null, "e": 940, "s": 885, "text": "Step 2: Add dependency to the build.gradle(Module:app)" }, { "code": null, "e": 949, "s": 940, "text": "Chapters" }, { "code": null, "e": 976, "s": 949, "text": "descriptions off, selected" }, { "code": null, "e": 1026, "s": 976, "text": "captions settings, opens captions settings dialog" }, { "code": null, "e": 1049, "s": 1026, "text": "captions off, selected" }, { "code": null, "e": 1057, "s": 1049, "text": "English" }, { "code": null, "e": 1081, "s": 1057, "text": "This is a modal window." }, { "code": null, "e": 1150, "s": 1081, "text": "Beginning of dialog window. Escape will cancel and close the window." }, { "code": null, "e": 1172, "s": 1150, "text": "End of dialog window." }, { "code": null, "e": 1288, "s": 1172, "text": "Navigate to the Gradle Scripts > build.gradle(Module:app) and add the below dependency in the dependencies section." }, { "code": null, "e": 1332, "s": 1288, "text": "implementation ‘com.itextpdf:itextg:5.5.10’" }, { "code": null, "e": 1491, "s": 1332, "text": "After adding the dependency click on the sync now option and sync your project. After adding dependency let’s move towards adding a PDF file inside your app. " }, { "code": null, "e": 1527, "s": 1491, "text": "Step 3: Adding PDF file in your app" }, { "code": null, "e": 1969, "s": 1527, "text": "As we are extracting data from PDF files, so we will be adding PDF files inside our app. For adding PDF files to your app we have to create the raw folder first. Please refer to Resource Raw Folder in Android Studio to create a raw folder in android. After creating a new raw directory copy and paste your PDF file inside that “raw” folder. After adding that PDF file in your app, now we will move towards implementation in the XML part. " }, { "code": null, "e": 2017, "s": 1969, "text": "Step 4: Working with the activity_main.xml file" }, { "code": null, "e": 2133, "s": 2017, "text": "Go to the activity_main.xml file and refer to the following code. Below is the code for the activity_main.xml file." }, { "code": null, "e": 2137, "s": 2133, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:orientation=\"vertical\" tools:context=\".MainActivity\"> <ScrollView android:layout_width=\"match_parent\" android:layout_height=\"match_parent\"> <!--text view for displaying our extracted text--> <TextView android:id=\"@+id/idPDFTV\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" /> </ScrollView> <!--button for starting extraction process--> <Button android:id=\"@+id/idBtnExtract\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_alignParentBottom=\"true\" android:layout_centerHorizontal=\"true\" android:layout_marginBottom=\"20dp\" android:text=\"Extract Text from PDF\" android:textAllCaps=\"false\" /> </RelativeLayout>", "e": 3222, "s": 2137, "text": null }, { "code": null, "e": 3285, "s": 3222, "text": "After adding XML code now we will move towards our Java part. " }, { "code": null, "e": 3333, "s": 3285, "text": "Step 5: Working with the MainActivity.java file" }, { "code": null, "e": 3523, "s": 3333, "text": "Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail." }, { "code": null, "e": 3528, "s": 3523, "text": "Java" }, { "code": "import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.TextView; import androidx.appcompat.app.AppCompatActivity; import com.itextpdf.text.pdf.PdfReader;import com.itextpdf.text.pdf.parser.PdfTextExtractor; public class MainActivity extends AppCompatActivity { // creating variables for // button and text view. private Button extractPDFBtn; private TextView extractedTV; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // initializing variables for button and text view. extractedTV = findViewById(R.id.idPDFTV); extractPDFBtn = findViewById(R.id.idBtnExtract); // adding on click listener for button extractPDFBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // calling method to extract // data from PDF file. extractPDF(); } }); } private void extractPDF() { try { // creating a string for // storing our extracted text. String extractedText = \"\"; // creating a variable for pdf reader // and passing our PDF file in it. PdfReader reader = new PdfReader(\"res/raw/amiya_rout.pdf\"); // below line is for getting number // of pages of PDF file. int n = reader.getNumberOfPages(); // running a for loop to get the data from PDF // we are storing that data inside our string. for (int i = 0; i < n; i++) { extractedText = extractedText + PdfTextExtractor.getTextFromPage(reader, i + 1).trim() + \"\\n\"; // to extract the PDF content from the different pages } // after extracting all the data we are // setting that string value to our text view. extractedTV.setText(extractedText); // below line is used for closing reader. reader.close(); } catch (Exception e) { // for handling error while extracting the text file. extractedTV.setText(\"Error found is : \\n\" + e); } }}", "e": 5919, "s": 3528, "text": null }, { "code": null, "e": 5992, "s": 5919, "text": "After adding this code now run your app and see the output of the code. " }, { "code": null, "e": 6119, "s": 5992, "text": "After you run the app click on Extract Data from PDF button and you will get to see that text is extracted from the PDF file. " }, { "code": null, "e": 6127, "s": 6119, "text": "android" }, { "code": null, "e": 6151, "s": 6127, "text": "Technical Scripter 2020" }, { "code": null, "e": 6159, "s": 6151, "text": "Android" }, { "code": null, "e": 6164, "s": 6159, "text": "Java" }, { "code": null, "e": 6183, "s": 6164, "text": "Technical Scripter" }, { "code": null, "e": 6188, "s": 6183, "text": "Java" }, { "code": null, "e": 6196, "s": 6188, "text": "Android" } ]
Python – Convert List of lists to list of Sets
25 Feb, 2021 Given a list containing lists, the task is to write a Python Program to convert it to a list containing sets. Examples: Input : [[1, 2, 1], [1, 2, 3], [2, 2, 2, 2], [0]] Output : [{1, 2}, {1, 2, 3}, {2}, {0}] Input : [[4, 4], [5, 5, 5], [1, 2, 3]] Output : [{4}, {5}, {1, 2, 3}] Method 1: Using list comprehension This can easily be achieved using list comprehension. We just iterate through each list converting the lists to the sets. Python3 # python3 program to convert list# of lists to a list of sets # initializing listtest_list = [[1, 2, 1], [1, 2, 3], [2, 2, 2, 2], [0]] # printing original listprint("The original list of lists : " + str(test_list)) # using list comprehension# convert list of lists to list of setsres = [set(ele) for ele in test_list] # print resultprint("The converted list of sets : " + str(res)) Output: he original list of lists : [[1, 2, 1], [1, 2, 3], [2, 2, 2, 2], [0]] The converted list of sets : [{1, 2}, {1, 2, 3}, {2}, {0}] Method 2 : Using map() + set We can use the combination of map function and set operator to perform this particular task. The map function binds each list and converts it into the set. Python3 # Python3 code to demonstrate# convert list of lists to list of sets# using map() + set # initializing listtest_list = [[1, 2, 1], [1, 2, 3], [2, 2, 2, 2], [0]] # printing original listprint("The original list of lists : " + str(test_list)) # using map() + setres = list(map(set, test_list)) # print resultprint("The converted list of sets : " + str(res)) Output: The original list of lists : [[1, 2, 1], [1, 2, 3], [2, 2, 2, 2], [0]] The converted list of sets : [{1, 2}, {1, 2, 3}, {2}, {0}] Python list-programs Python set-programs Technical Scripter 2020 Python Python Programs Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON How to drop one or multiple columns in Pandas Dataframe Defaultdict in Python Python | Get dictionary keys as a list Python | Convert a list to dictionary Python Program for Fibonacci numbers Python | Convert string dictionary to dictionary
[ { "code": null, "e": 28, "s": 0, "text": "\n25 Feb, 2021" }, { "code": null, "e": 138, "s": 28, "text": "Given a list containing lists, the task is to write a Python Program to convert it to a list containing sets." }, { "code": null, "e": 148, "s": 138, "text": "Examples:" }, { "code": null, "e": 308, "s": 148, "text": "Input : [[1, 2, 1], [1, 2, 3], [2, 2, 2, 2], [0]]\nOutput : [{1, 2}, {1, 2, 3}, {2}, {0}]\n\nInput : [[4, 4], [5, 5, 5], [1, 2, 3]]\nOutput : [{4}, {5}, {1, 2, 3}]" }, { "code": null, "e": 343, "s": 308, "text": "Method 1: Using list comprehension" }, { "code": null, "e": 465, "s": 343, "text": "This can easily be achieved using list comprehension. We just iterate through each list converting the lists to the sets." }, { "code": null, "e": 473, "s": 465, "text": "Python3" }, { "code": "# python3 program to convert list# of lists to a list of sets # initializing listtest_list = [[1, 2, 1], [1, 2, 3], [2, 2, 2, 2], [0]] # printing original listprint(\"The original list of lists : \" + str(test_list)) # using list comprehension# convert list of lists to list of setsres = [set(ele) for ele in test_list] # print resultprint(\"The converted list of sets : \" + str(res))", "e": 861, "s": 473, "text": null }, { "code": null, "e": 869, "s": 861, "text": "Output:" }, { "code": null, "e": 998, "s": 869, "text": "he original list of lists : [[1, 2, 1], [1, 2, 3], [2, 2, 2, 2], [0]]\nThe converted list of sets : [{1, 2}, {1, 2, 3}, {2}, {0}]" }, { "code": null, "e": 1027, "s": 998, "text": "Method 2 : Using map() + set" }, { "code": null, "e": 1183, "s": 1027, "text": "We can use the combination of map function and set operator to perform this particular task. The map function binds each list and converts it into the set." }, { "code": null, "e": 1191, "s": 1183, "text": "Python3" }, { "code": "# Python3 code to demonstrate# convert list of lists to list of sets# using map() + set # initializing listtest_list = [[1, 2, 1], [1, 2, 3], [2, 2, 2, 2], [0]] # printing original listprint(\"The original list of lists : \" + str(test_list)) # using map() + setres = list(map(set, test_list)) # print resultprint(\"The converted list of sets : \" + str(res))", "e": 1551, "s": 1191, "text": null }, { "code": null, "e": 1559, "s": 1551, "text": "Output:" }, { "code": null, "e": 1689, "s": 1559, "text": "The original list of lists : [[1, 2, 1], [1, 2, 3], [2, 2, 2, 2], [0]]\nThe converted list of sets : [{1, 2}, {1, 2, 3}, {2}, {0}]" }, { "code": null, "e": 1710, "s": 1689, "text": "Python list-programs" }, { "code": null, "e": 1730, "s": 1710, "text": "Python set-programs" }, { "code": null, "e": 1754, "s": 1730, "text": "Technical Scripter 2020" }, { "code": null, "e": 1761, "s": 1754, "text": "Python" }, { "code": null, "e": 1777, "s": 1761, "text": "Python Programs" }, { "code": null, "e": 1796, "s": 1777, "text": "Technical Scripter" }, { "code": null, "e": 1894, "s": 1796, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1926, "s": 1894, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 1953, "s": 1926, "text": "Python Classes and Objects" }, { "code": null, "e": 1974, "s": 1953, "text": "Python OOPs Concepts" }, { "code": null, "e": 1997, "s": 1974, "text": "Introduction To PYTHON" }, { "code": null, "e": 2053, "s": 1997, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 2075, "s": 2053, "text": "Defaultdict in Python" }, { "code": null, "e": 2114, "s": 2075, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 2152, "s": 2114, "text": "Python | Convert a list to dictionary" }, { "code": null, "e": 2189, "s": 2152, "text": "Python Program for Fibonacci numbers" } ]
Entity Framework - Seed Database
In Entity Framework, Seed was introduced in EF 4.1 and works with database initializers. The general idea of a Seed Method is to initialize data into a database that is being created by Code First or evolved by Migrations. This data is often test data, but may also be reference data such as lists of known Students, Courses, etc. When the data is initialized, it does the following − Checks whether or not the target database already exists. If it does, then the current Code First model is compared with the model stored in metadata in the database. The database is dropped if the current model does not match the model in the database. The database is created if it was dropped or didn’t exist in the first place. If the database was created, then the initializer Seed method is called. The Seed method takes the database context object as an input parameter, and the code in the method uses that object to add new entities to the database. To seed data into your database, you need to override the Seed method. Let’s take a look at the following example in which some of the default data are initiated into the database in an internal class. private class UniDBInitializer<T> : DropCreateDatabaseAlways<MyContext> { protected override void Seed(MyContext context) { IList<Student> students = new List<Student>(); students.Add(new Student() { FirstMidName = "Andrew", LastName = "Peters", EnrollmentDate = DateTime.Parse(DateTime.Today.ToString()) }); students.Add(new Student() { FirstMidName = "Brice", LastName = "Lambson", EnrollmentDate = DateTime.Parse(DateTime.Today.ToString()) }); students.Add(new Student() { FirstMidName = "Rowan", LastName = "Miller", EnrollmentDate = DateTime.Parse(DateTime.Today.ToString()) }); foreach (Student student in students) context.Students.Add(student); base.Seed(context); } } In the above code, student table is initialized. You need to set this DB initializer class in context class as shown in the following code. public MyContext() : base("name=MyContextDB") { Database.SetInitializer<MyContext>(new UniDBInitializer<MyContext>()); } Following is the complete class implementation of MyContext class, which also contains the DB initializer class. public class MyContext : DbContext { public MyContext() : base("name=MyContextDB") { Database.SetInitializer<MyContext>(new UniDBInitializer<MyContext>()); } public virtual DbSet<Course> Courses { get; set; } public virtual DbSet<Enrollment> Enrollments { get; set; } public virtual DbSet<Student> Students { get; set; } private class UniDBInitializer<T> : DropCreateDatabaseAlways<MyContext> { protected override void Seed(MyContext context) { IList<Student> students = new List<Student>(); students.Add(new Student() { FirstMidName = "Andrew", LastName = "Peters", EnrollmentDate = DateTime.Parse(DateTime.Today.ToString()) }); students.Add(new Student() { FirstMidName = "Brice", LastName = "Lambson", EnrollmentDate = DateTime.Parse(DateTime.Today.ToString()) }); students.Add(new Student() { FirstMidName = "Rowan", LastName = "Miller", EnrollmentDate = DateTime.Parse(DateTime.Today.ToString()) }); foreach (Student student in students) context.Students.Add(student); base.Seed(context); } } } When the above example is compiled and executed, you can see the data in a database as shown in the following image. We recommend that you execute the above example in a step-by-step manner for better understanding.
[ { "code": null, "e": 3551, "s": 3166, "text": "In Entity Framework, Seed was introduced in EF 4.1 and works with database initializers. The general idea of a Seed Method is to initialize data into a database that is being created by Code First or evolved by Migrations. This data is often test data, but may also be reference data such as lists of known Students, Courses, etc. When the data is initialized, it does the following −" }, { "code": null, "e": 3609, "s": 3551, "text": "Checks whether or not the target database already exists." }, { "code": null, "e": 3718, "s": 3609, "text": "If it does, then the current Code First model is compared with the model stored in metadata in the database." }, { "code": null, "e": 3805, "s": 3718, "text": "The database is dropped if the current model does not match the model in the database." }, { "code": null, "e": 3883, "s": 3805, "text": "The database is created if it was dropped or didn’t exist in the first place." }, { "code": null, "e": 3956, "s": 3883, "text": "If the database was created, then the initializer Seed method is called." }, { "code": null, "e": 4312, "s": 3956, "text": "The Seed method takes the database context object as an input parameter, and the code in the method uses that object to add new entities to the database. To seed data into your database, you need to override the Seed method. Let’s take a look at the following example in which some of the default data are initiated into the database in an internal class." }, { "code": null, "e": 5148, "s": 4312, "text": "private class UniDBInitializer<T> : DropCreateDatabaseAlways<MyContext> {\n\n protected override void Seed(MyContext context) {\n\n IList<Student> students = new List<Student>();\n\n students.Add(new Student() {\n FirstMidName = \"Andrew\", \n LastName = \"Peters\", \n EnrollmentDate = DateTime.Parse(DateTime.Today.ToString())\n });\n\n students.Add(new Student() {\n FirstMidName = \"Brice\", \n LastName = \"Lambson\", \n EnrollmentDate = DateTime.Parse(DateTime.Today.ToString())\n });\n\n students.Add(new Student() {\n FirstMidName = \"Rowan\", \n LastName = \"Miller\", \n EnrollmentDate = DateTime.Parse(DateTime.Today.ToString())\n });\n\n foreach (Student student in students)\n context.Students.Add(student);\n base.Seed(context);\n }\n}" }, { "code": null, "e": 5288, "s": 5148, "text": "In the above code, student table is initialized. You need to set this DB initializer class in context class as shown in the following code." }, { "code": null, "e": 5412, "s": 5288, "text": "public MyContext() : base(\"name=MyContextDB\") {\n Database.SetInitializer<MyContext>(new UniDBInitializer<MyContext>());\n}" }, { "code": null, "e": 5525, "s": 5412, "text": "Following is the complete class implementation of MyContext class, which also contains the DB initializer class." }, { "code": null, "e": 6783, "s": 5525, "text": "public class MyContext : DbContext {\n\n public MyContext() : base(\"name=MyContextDB\") {\n Database.SetInitializer<MyContext>(new UniDBInitializer<MyContext>());\n }\n\n public virtual DbSet<Course> Courses { get; set; }\n public virtual DbSet<Enrollment> Enrollments { get; set; }\n public virtual DbSet<Student> Students { get; set; }\n\t\n private class UniDBInitializer<T> : DropCreateDatabaseAlways<MyContext> {\n\n protected override void Seed(MyContext context) {\n\n IList<Student> students = new List<Student>();\n\t\t\t\n students.Add(new Student() {\n FirstMidName = \"Andrew\", \n LastName = \"Peters\", \n EnrollmentDate = DateTime.Parse(DateTime.Today.ToString()) \n });\n\n students.Add(new Student() {\n FirstMidName = \"Brice\", \n LastName = \"Lambson\", \n EnrollmentDate = DateTime.Parse(DateTime.Today.ToString())\n });\n\n students.Add(new Student() {\n FirstMidName = \"Rowan\", \n LastName = \"Miller\", \n EnrollmentDate = DateTime.Parse(DateTime.Today.ToString())\n });\n\n foreach (Student student in students)\n context.Students.Add(student);\n base.Seed(context);\n }\n } \n}" }, { "code": null, "e": 6900, "s": 6783, "text": "When the above example is compiled and executed, you can see the data in a database as shown in the following image." } ]
LongSummaryStatistics getCount() method in Java with Examples
27 Jun, 2019 The getCount() method of LongSummaryStatistics class in Java is used to get the count of records in this LongSummaryStatistics. Syntax: public long getCount() Parameter: This method do not accept any value as parameter. Return Value: This method returns the count of the records in this LongSummaryStatistics. Program: // Java program to demonstrate// the above method import java.util.*; public class LongSummaryStatisticsDemo { public static void main(String[] args) { LongSummaryStatistics longSummaryStatistics = new LongSummaryStatistics(); List<Integer> list = Arrays.asList(10, 20, 30, 40, 50); Iterator<Integer> iterator = list.listIterator(); while (iterator.hasNext()) { // Add the integers to the LongSummaryStatistics object longSummaryStatistics.accept(iterator.next()); } System.out.println("The count of values is " + longSummaryStatistics.getCount()); }} The count of values is 5 Reference: https://docs.oracle.com/javase/10/docs/api/java/util/LongSummaryStatistics.html#getCount() Java - util package Java-Functions Java-LongSummaryStatistics Java 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 Functional Interfaces in Java Java Programming Examples Strings in Java Differences between JDK, JRE and JVM Abstraction in Java
[ { "code": null, "e": 28, "s": 0, "text": "\n27 Jun, 2019" }, { "code": null, "e": 156, "s": 28, "text": "The getCount() method of LongSummaryStatistics class in Java is used to get the count of records in this LongSummaryStatistics." }, { "code": null, "e": 164, "s": 156, "text": "Syntax:" }, { "code": null, "e": 188, "s": 164, "text": "public long getCount()\n" }, { "code": null, "e": 249, "s": 188, "text": "Parameter: This method do not accept any value as parameter." }, { "code": null, "e": 339, "s": 249, "text": "Return Value: This method returns the count of the records in this LongSummaryStatistics." }, { "code": null, "e": 348, "s": 339, "text": "Program:" }, { "code": "// Java program to demonstrate// the above method import java.util.*; public class LongSummaryStatisticsDemo { public static void main(String[] args) { LongSummaryStatistics longSummaryStatistics = new LongSummaryStatistics(); List<Integer> list = Arrays.asList(10, 20, 30, 40, 50); Iterator<Integer> iterator = list.listIterator(); while (iterator.hasNext()) { // Add the integers to the LongSummaryStatistics object longSummaryStatistics.accept(iterator.next()); } System.out.println(\"The count of values is \" + longSummaryStatistics.getCount()); }}", "e": 1033, "s": 348, "text": null }, { "code": null, "e": 1059, "s": 1033, "text": "The count of values is 5\n" }, { "code": null, "e": 1161, "s": 1059, "text": "Reference: https://docs.oracle.com/javase/10/docs/api/java/util/LongSummaryStatistics.html#getCount()" }, { "code": null, "e": 1181, "s": 1161, "text": "Java - util package" }, { "code": null, "e": 1196, "s": 1181, "text": "Java-Functions" }, { "code": null, "e": 1223, "s": 1196, "text": "Java-LongSummaryStatistics" }, { "code": null, "e": 1228, "s": 1223, "text": "Java" }, { "code": null, "e": 1233, "s": 1228, "text": "Java" }, { "code": null, "e": 1331, "s": 1233, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1346, "s": 1331, "text": "Stream In Java" }, { "code": null, "e": 1367, "s": 1346, "text": "Introduction to Java" }, { "code": null, "e": 1388, "s": 1367, "text": "Constructors in Java" }, { "code": null, "e": 1407, "s": 1388, "text": "Exceptions in Java" }, { "code": null, "e": 1424, "s": 1407, "text": "Generics in Java" }, { "code": null, "e": 1454, "s": 1424, "text": "Functional Interfaces in Java" }, { "code": null, "e": 1480, "s": 1454, "text": "Java Programming Examples" }, { "code": null, "e": 1496, "s": 1480, "text": "Strings in Java" }, { "code": null, "e": 1533, "s": 1496, "text": "Differences between JDK, JRE and JVM" } ]
How to read multiple Excel files in R
18 Jul, 2021 In this article, we will discuss how to merge multiple Excel files in the R programming language. dplyr: The dplyr package in R is a structure of data manipulation that provides a uniform set of verbs, helping to resolve the most frequent data manipulation hurdles. plyr: The “plyr” package in R is used to work with data, including its enhancements and manipulations. readxl: This package is used to work with excel files in R readr: This package is used to read files in R list.files() function produces a character vector of the names of files or directories in the named directory. Syntax: list.files(path = “.”, pattern = NULL, all.files = FALSE,full.names = FALSE, recursive = FALSE, ignore.case = FALSE, include.dirs = FALSE, no.. = FALSE) lapply() function returns a list of the same length as X, each element of which is the result of applying FUN to the corresponding element of X. Syntax: lapply(X, FUN, ...) bind_rows() function is an efficient implementation of the common pattern of do.call(rbind, dfs) or do.call(cbind, dfs) for binding many data frames into one. Syntax: bind_rows(..., .id = NULL) Files in use: gfg_data1.xlsx gfg_data2.xlsx gfg_data3.xlsx Example: Merging Excel using R R library("dplyr") library("plyr") library("readr") library("readxl") gfg_data <- list.files(path = "Location/to/folder", pattern = "*.xlsx", full.names = TRUE) %>% lapply(read_excel) %>% bind_rows gfg_data Output: Picked R-Excel R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Filter data by multiple conditions in R using Dplyr How to Replace specific values in column in R DataFrame ? Change Color of Bars in Barchart using ggplot2 in R How to Split Column Into Multiple Columns in R DataFrame? Loops in R (for, while, repeat) Group by function in R using Dplyr How to change Row Names of DataFrame in R ? Printing Output of an R Program How to Change Axis Scales in R Plots? R - if statement
[ { "code": null, "e": 28, "s": 0, "text": "\n18 Jul, 2021" }, { "code": null, "e": 126, "s": 28, "text": "In this article, we will discuss how to merge multiple Excel files in the R programming language." }, { "code": null, "e": 294, "s": 126, "text": "dplyr: The dplyr package in R is a structure of data manipulation that provides a uniform set of verbs, helping to resolve the most frequent data manipulation hurdles." }, { "code": null, "e": 398, "s": 294, "text": "plyr: The “plyr” package in R is used to work with data, including its enhancements and manipulations. " }, { "code": null, "e": 457, "s": 398, "text": "readxl: This package is used to work with excel files in R" }, { "code": null, "e": 504, "s": 457, "text": "readr: This package is used to read files in R" }, { "code": null, "e": 615, "s": 504, "text": "list.files() function produces a character vector of the names of files or directories in the named directory." }, { "code": null, "e": 776, "s": 615, "text": "Syntax: list.files(path = “.”, pattern = NULL, all.files = FALSE,full.names = FALSE, recursive = FALSE, ignore.case = FALSE, include.dirs = FALSE, no.. = FALSE)" }, { "code": null, "e": 921, "s": 776, "text": "lapply() function returns a list of the same length as X, each element of which is the result of applying FUN to the corresponding element of X." }, { "code": null, "e": 949, "s": 921, "text": "Syntax: lapply(X, FUN, ...)" }, { "code": null, "e": 1108, "s": 949, "text": "bind_rows() function is an efficient implementation of the common pattern of do.call(rbind, dfs) or do.call(cbind, dfs) for binding many data frames into one." }, { "code": null, "e": 1143, "s": 1108, "text": "Syntax: bind_rows(..., .id = NULL)" }, { "code": null, "e": 1157, "s": 1143, "text": "Files in use:" }, { "code": null, "e": 1172, "s": 1157, "text": "gfg_data1.xlsx" }, { "code": null, "e": 1187, "s": 1172, "text": "gfg_data2.xlsx" }, { "code": null, "e": 1202, "s": 1187, "text": "gfg_data3.xlsx" }, { "code": null, "e": 1233, "s": 1202, "text": "Example: Merging Excel using R" }, { "code": null, "e": 1235, "s": 1233, "text": "R" }, { "code": "library(\"dplyr\") library(\"plyr\") library(\"readr\") library(\"readxl\") gfg_data <- list.files(path = \"Location/to/folder\", pattern = \"*.xlsx\", full.names = TRUE) %>% lapply(read_excel) %>% bind_rows gfg_data ", "e": 1743, "s": 1235, "text": null }, { "code": null, "e": 1751, "s": 1743, "text": "Output:" }, { "code": null, "e": 1758, "s": 1751, "text": "Picked" }, { "code": null, "e": 1766, "s": 1758, "text": "R-Excel" }, { "code": null, "e": 1777, "s": 1766, "text": "R Language" }, { "code": null, "e": 1875, "s": 1777, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1927, "s": 1875, "text": "Filter data by multiple conditions in R using Dplyr" }, { "code": null, "e": 1985, "s": 1927, "text": "How to Replace specific values in column in R DataFrame ?" }, { "code": null, "e": 2037, "s": 1985, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 2095, "s": 2037, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 2127, "s": 2095, "text": "Loops in R (for, while, repeat)" }, { "code": null, "e": 2162, "s": 2127, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 2206, "s": 2162, "text": "How to change Row Names of DataFrame in R ?" }, { "code": null, "e": 2238, "s": 2206, "text": "Printing Output of an R Program" }, { "code": null, "e": 2276, "s": 2238, "text": "How to Change Axis Scales in R Plots?" } ]