title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
---|---|---|
C# Program that Demonstrates Exception Handling For Invalid TypeCasting in UnBoxing - GeeksforGeeks | 01 Nov, 2021
Exception handling is used to handle the errors in the program. Or we can say that an exception is an event that occurs during the execution of a program that is unexpected by the program code. The actions to be performed in case of the occurrence of an exception are not known to the program. In this situation, we can create an exception object and call the exception handler code. This exception handler saves the program from the crash and this process is known as exception handling. Exception handling is necessary because it handles an unwanted event so that the program code still makes sense to the user. We can achieve this by using try and catch block
try: This block identifies a block of code for which any errors are there. If there is any error then it will send to catch block. It can contain one or more catch block and this block is created using try keyword. catch: This block is used to handle the error raised in the try block. The catch keyword is used for catch block. For the catch block, there should be definitely a try block.finally: This block is used to run the specified set of statements, whether an exception is thrown or not thrown. It is an optional block and created by using the finally keyword.
try: This block identifies a block of code for which any errors are there. If there is any error then it will send to catch block. It can contain one or more catch block and this block is created using try keyword.
catch: This block is used to handle the error raised in the try block. The catch keyword is used for catch block. For the catch block, there should be definitely a try block.
finally: This block is used to run the specified set of statements, whether an exception is thrown or not thrown. It is an optional block and created by using the finally keyword.
Syntax:
try{
// Statements
}
catch{
// Handle the exception
}
finally{
// Finally block
}
Typecasting can be defined as the process of converting the variable from one data type to another. If the data types are compatible, then C# does Automatic Type Conversion. If not comparable, then they need to be converted explicitly which is known as Explicit Type conversion.
Syntax:
(datatype)variable/object;
Here, the data type is the type of data that we type case, For example, we can convert Integer type to Short type.
Here in this article, we have to handle the Typecasting integer to short data type and we are going to handle that exception.
Example:
Input : 50
Output : Specified cast is not valid.
Approach:
Declare an integer variable named “number”.Convert that variable to the object(This is known as Unboxing).Convert the integer variable into short data type in try block.Handle the exception in catch block.
Declare an integer variable named “number”.
Convert that variable to the object(This is known as Unboxing).
Convert the integer variable into short data type in try block.
Handle the exception in catch block.
Example:
C#
// C# program to illustrate how to exception handling // for invalid TypeCasting in unBoxingusing System;class GFG{ static void Main(){ // Declare a number int number = 50; // Set this number to the object object object1 = number; try { // Type cast this object to short int x = (short)object1; System.Console.WriteLine("Unboxing the object"); } // Handle exception catch (System.InvalidCastException e) { // Display the error message System.Console.WriteLine(e.Message); }}}
Output:
Specified cast is not valid.
CSharp-Exception-Handling
CSharp-programs
Picked
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Destructors in C#
Extension Method in C#
HashSet in C# with Examples
Top 50 C# Interview Questions & Answers
C# | How to insert an element in an Array?
Partial Classes in C#
C# | Inheritance
C# | List Class
Difference between Hashtable and Dictionary in C#
Lambda Expressions in C# | [
{
"code": null,
"e": 24302,
"s": 24274,
"text": "\n01 Nov, 2021"
},
{
"code": null,
"e": 24965,
"s": 24302,
"text": "Exception handling is used to handle the errors in the program. Or we can say that an exception is an event that occurs during the execution of a program that is unexpected by the program code. The actions to be performed in case of the occurrence of an exception are not known to the program. In this situation, we can create an exception object and call the exception handler code. This exception handler saves the program from the crash and this process is known as exception handling. Exception handling is necessary because it handles an unwanted event so that the program code still makes sense to the user. We can achieve this by using try and catch block"
},
{
"code": null,
"e": 25534,
"s": 24965,
"text": "try: This block identifies a block of code for which any errors are there. If there is any error then it will send to catch block. It can contain one or more catch block and this block is created using try keyword. catch: This block is used to handle the error raised in the try block. The catch keyword is used for catch block. For the catch block, there should be definitely a try block.finally: This block is used to run the specified set of statements, whether an exception is thrown or not thrown. It is an optional block and created by using the finally keyword."
},
{
"code": null,
"e": 25750,
"s": 25534,
"text": "try: This block identifies a block of code for which any errors are there. If there is any error then it will send to catch block. It can contain one or more catch block and this block is created using try keyword. "
},
{
"code": null,
"e": 25925,
"s": 25750,
"text": "catch: This block is used to handle the error raised in the try block. The catch keyword is used for catch block. For the catch block, there should be definitely a try block."
},
{
"code": null,
"e": 26105,
"s": 25925,
"text": "finally: This block is used to run the specified set of statements, whether an exception is thrown or not thrown. It is an optional block and created by using the finally keyword."
},
{
"code": null,
"e": 26113,
"s": 26105,
"text": "Syntax:"
},
{
"code": null,
"e": 26118,
"s": 26113,
"text": "try{"
},
{
"code": null,
"e": 26138,
"s": 26118,
"text": " // Statements"
},
{
"code": null,
"e": 26140,
"s": 26138,
"text": "}"
},
{
"code": null,
"e": 26147,
"s": 26140,
"text": "catch{"
},
{
"code": null,
"e": 26176,
"s": 26147,
"text": " // Handle the exception"
},
{
"code": null,
"e": 26178,
"s": 26176,
"text": "}"
},
{
"code": null,
"e": 26187,
"s": 26178,
"text": "finally{"
},
{
"code": null,
"e": 26208,
"s": 26187,
"text": " // Finally block"
},
{
"code": null,
"e": 26210,
"s": 26208,
"text": "}"
},
{
"code": null,
"e": 26489,
"s": 26210,
"text": "Typecasting can be defined as the process of converting the variable from one data type to another. If the data types are compatible, then C# does Automatic Type Conversion. If not comparable, then they need to be converted explicitly which is known as Explicit Type conversion."
},
{
"code": null,
"e": 26497,
"s": 26489,
"text": "Syntax:"
},
{
"code": null,
"e": 26524,
"s": 26497,
"text": "(datatype)variable/object;"
},
{
"code": null,
"e": 26640,
"s": 26524,
"text": "Here, the data type is the type of data that we type case, For example, we can convert Integer type to Short type. "
},
{
"code": null,
"e": 26766,
"s": 26640,
"text": "Here in this article, we have to handle the Typecasting integer to short data type and we are going to handle that exception."
},
{
"code": null,
"e": 26775,
"s": 26766,
"text": "Example:"
},
{
"code": null,
"e": 26825,
"s": 26775,
"text": "Input : 50\nOutput : Specified cast is not valid."
},
{
"code": null,
"e": 26835,
"s": 26825,
"text": "Approach:"
},
{
"code": null,
"e": 27041,
"s": 26835,
"text": "Declare an integer variable named “number”.Convert that variable to the object(This is known as Unboxing).Convert the integer variable into short data type in try block.Handle the exception in catch block."
},
{
"code": null,
"e": 27085,
"s": 27041,
"text": "Declare an integer variable named “number”."
},
{
"code": null,
"e": 27149,
"s": 27085,
"text": "Convert that variable to the object(This is known as Unboxing)."
},
{
"code": null,
"e": 27213,
"s": 27149,
"text": "Convert the integer variable into short data type in try block."
},
{
"code": null,
"e": 27250,
"s": 27213,
"text": "Handle the exception in catch block."
},
{
"code": null,
"e": 27259,
"s": 27250,
"text": "Example:"
},
{
"code": null,
"e": 27262,
"s": 27259,
"text": "C#"
},
{
"code": "// C# program to illustrate how to exception handling // for invalid TypeCasting in unBoxingusing System;class GFG{ static void Main(){ // Declare a number int number = 50; // Set this number to the object object object1 = number; try { // Type cast this object to short int x = (short)object1; System.Console.WriteLine(\"Unboxing the object\"); } // Handle exception catch (System.InvalidCastException e) { // Display the error message System.Console.WriteLine(e.Message); }}}",
"e": 27851,
"s": 27262,
"text": null
},
{
"code": null,
"e": 27859,
"s": 27851,
"text": "Output:"
},
{
"code": null,
"e": 27888,
"s": 27859,
"text": "Specified cast is not valid."
},
{
"code": null,
"e": 27914,
"s": 27888,
"text": "CSharp-Exception-Handling"
},
{
"code": null,
"e": 27930,
"s": 27914,
"text": "CSharp-programs"
},
{
"code": null,
"e": 27937,
"s": 27930,
"text": "Picked"
},
{
"code": null,
"e": 27940,
"s": 27937,
"text": "C#"
},
{
"code": null,
"e": 28038,
"s": 27940,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28056,
"s": 28038,
"text": "Destructors in C#"
},
{
"code": null,
"e": 28079,
"s": 28056,
"text": "Extension Method in C#"
},
{
"code": null,
"e": 28107,
"s": 28079,
"text": "HashSet in C# with Examples"
},
{
"code": null,
"e": 28147,
"s": 28107,
"text": "Top 50 C# Interview Questions & Answers"
},
{
"code": null,
"e": 28190,
"s": 28147,
"text": "C# | How to insert an element in an Array?"
},
{
"code": null,
"e": 28212,
"s": 28190,
"text": "Partial Classes in C#"
},
{
"code": null,
"e": 28229,
"s": 28212,
"text": "C# | Inheritance"
},
{
"code": null,
"e": 28245,
"s": 28229,
"text": "C# | List Class"
},
{
"code": null,
"e": 28295,
"s": 28245,
"text": "Difference between Hashtable and Dictionary in C#"
}
] |
Python - HTTP Authentication | Authentication is the process of determining if the request has come from a valid user who has the required privileges to use the system. In the world of computer networking this is a very vital requirement as many systems keep interacting with each other and proper mechanism needs to ensure that only valid interactions happen between these programs.
The python module names requests has in-built feature to call various APIs provided by the serving web apps along with the user credentials. These credentials have to be embedded in the calling program. If the APIs verify it successfully then a valid login happens.
We install the required python module named requests for running the authentication program.
pip install requests
Below we see a simple authentication mechanism involving only the username and the password. A successful response indicates valid login.
import requests
r = requests.get('https://api.github.com/user', auth=('user', 'pass'))
print r
When we run the above program, we get the following output −
We can also run a program to use twitter's api and make a successful login by using the following code. We use the OAuth1 method available in the requests module to process the parameters required by Twitter API. As we can see the requests module is capable of handling more complex authentication mechanism involving keys and tokens rather than just the username and password mechanism.
import requests
from requests_oauthlib import OAuth1
url = 'https://api.twitter.com/1.1/account/verify_credentials.json'
auth = OAuth1('YOUR_APP_KEY', 'YOUR_APP_SECRET',
'USER_OAUTH_TOKEN', 'USER_OAUTH_TOKEN_SECRET')
requests.get(url, auth=auth)
When we run the above program, we get the following output −
{
"errors": [
{
"code": 215,
"message": "Bad Authentication data."
}
]
}
But using the proper values for OAuth1 parameters you get a successful response.
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": 2679,
"s": 2326,
"text": "Authentication is the process of determining if the request has come from a valid user who has the required privileges to use the system. In the world of computer networking this is a very vital requirement as many systems keep interacting with each other and proper mechanism needs to ensure that only valid interactions happen between these programs."
},
{
"code": null,
"e": 2945,
"s": 2679,
"text": "The python module names requests has in-built feature to call various APIs provided by the serving web apps along with the user credentials. These credentials have to be embedded in the calling program. If the APIs verify it successfully then a valid login happens."
},
{
"code": null,
"e": 3038,
"s": 2945,
"text": "We install the required python module named requests for running the authentication program."
},
{
"code": null,
"e": 3059,
"s": 3038,
"text": "pip install requests"
},
{
"code": null,
"e": 3197,
"s": 3059,
"text": "Below we see a simple authentication mechanism involving only the username and the password. A successful response indicates valid login."
},
{
"code": null,
"e": 3293,
"s": 3197,
"text": "import requests \nr = requests.get('https://api.github.com/user', auth=('user', 'pass'))\nprint r"
},
{
"code": null,
"e": 3354,
"s": 3293,
"text": "When we run the above program, we get the following output −"
},
{
"code": null,
"e": 3744,
"s": 3356,
"text": "We can also run a program to use twitter's api and make a successful login by using the following code. We use the OAuth1 method available in the requests module to process the parameters required by Twitter API. As we can see the requests module is capable of handling more complex authentication mechanism involving keys and tokens rather than just the username and password mechanism."
},
{
"code": null,
"e": 4006,
"s": 3744,
"text": "import requests\nfrom requests_oauthlib import OAuth1\n\nurl = 'https://api.twitter.com/1.1/account/verify_credentials.json'\nauth = OAuth1('YOUR_APP_KEY', 'YOUR_APP_SECRET',\n 'USER_OAUTH_TOKEN', 'USER_OAUTH_TOKEN_SECRET')\n\nrequests.get(url, auth=auth)"
},
{
"code": null,
"e": 4067,
"s": 4006,
"text": "When we run the above program, we get the following output −"
},
{
"code": null,
"e": 4166,
"s": 4067,
"text": "{\n \"errors\": [\n {\n \"code\": 215,\n \"message\": \"Bad Authentication data.\"\n }\n ]\n}\n\n"
},
{
"code": null,
"e": 4247,
"s": 4166,
"text": "But using the proper values for OAuth1 parameters you get a successful response."
},
{
"code": null,
"e": 4284,
"s": 4247,
"text": "\n 187 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 4300,
"s": 4284,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 4333,
"s": 4300,
"text": "\n 55 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 4352,
"s": 4333,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 4387,
"s": 4352,
"text": "\n 136 Lectures \n 11 hours \n"
},
{
"code": null,
"e": 4409,
"s": 4387,
"text": " In28Minutes Official"
},
{
"code": null,
"e": 4443,
"s": 4409,
"text": "\n 75 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 4471,
"s": 4443,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 4506,
"s": 4471,
"text": "\n 70 Lectures \n 8.5 hours \n"
},
{
"code": null,
"e": 4520,
"s": 4506,
"text": " Lets Kode It"
},
{
"code": null,
"e": 4553,
"s": 4520,
"text": "\n 63 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 4570,
"s": 4553,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 4577,
"s": 4570,
"text": " Print"
},
{
"code": null,
"e": 4588,
"s": 4577,
"text": " Add Notes"
}
] |
Converting the Slides of a PPT into Images using Java - GeeksforGeeks | 15 Jul, 2021
To convert PowerPoint slides to images, multiple packages are required like, java.awt because It contains all the classes for creating user interfaces and for painting graphics and images, java.io because It provides a set of input streams and a set of output streams used to read and write data to files or other input and output sources, Apache POI because It is used to create, modify, and display Microsoft Office files using Java programs.
Download Apache POI
Download the zip file from the official site.Extract the external jar files from the zip file.Add the external jar files. For that select Java Build Path -> Configure Build Path -> Libraries -> Class -> Add External Jars...Select the jar file from the required folderClick Apply and close.
Download the zip file from the official site.
Extract the external jar files from the zip file.
Add the external jar files. For that select Java Build Path -> Configure Build Path -> Libraries -> Class -> Add External Jars...
Select the jar file from the required folder
Click Apply and close.
Imports from java.awt
java.awt.Color: This class has the colors needed to change the appearance of objects in the interface.java.awt.Dimension It contains the height and width of a component.java.awt.Graphics2D It provides provides control over geometry, coordinate transformations, color management, and text layout.java.awt.geom.Rectangle2D It describes a rectangle defined by a location (x,y) and dimension (w x h) .java.awt.image.BufferedImage It is used to handle and manipulate the image data.
java.awt.Color: This class has the colors needed to change the appearance of objects in the interface.
java.awt.Dimension It contains the height and width of a component.
java.awt.Graphics2D It provides provides control over geometry, coordinate transformations, color management, and text layout.
java.awt.geom.Rectangle2D It describes a rectangle defined by a location (x,y) and dimension (w x h) .
java.awt.image.BufferedImage It is used to handle and manipulate the image data.
Imports from java.io
java.io.File: It contains several methods for working with the path name, deleting and renaming files,etc.java.io.FileInputStream: It is used to read data from a file.java.io.FileOutputStream: It is used for writing data to a File.java.io.IOException: It is an exception which is used in the code to throw a failure in Input and Output operations
java.io.File: It contains several methods for working with the path name, deleting and renaming files,etc.
java.io.FileInputStream: It is used to read data from a file.
java.io.FileOutputStream: It is used for writing data to a File.
java.io.IOException: It is an exception which is used in the code to throw a failure in Input and Output operations
Imports from Apache POI
org.apache.poi.xslf.usermodel.XMLSlideShow: It is used to create objects to read or write a slideshow.org.apache.poi.xslf.usermodel.XSLFSlide: It is used to create and manage a slide in a presentation.
org.apache.poi.xslf.usermodel.XMLSlideShow: It is used to create objects to read or write a slideshow.
org.apache.poi.xslf.usermodel.XSLFSlide: It is used to create and manage a slide in a presentation.
Implementation:
Java
// Converting the slides of a PPT into Images using Javaimport java.util.List; import java.awt.Color;import java.awt.Dimension;import java.awt.Graphics2D;import java.awt.geom.Rectangle2D;import java.awt.image.BufferedImage; import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException; import org.apache.poi.xslf.usermodel.XMLSlideShow;import org.apache.poi.xslf.usermodel.XSLFSlide; public class PPTToImages { public static void main(String args[]) throws IOException { // create an empty presentation File file = new File("slides.pptx"); XMLSlideShow ppt = new XMLSlideShow(new FileInputStream(file)); // get the dimension and size of the slide Dimension pgsize = ppt.getPageSize(); List<XSLFSlide> slide = ppt.getSlides(); BufferedImage img = null; System.out.println(slide.size()); for (int i = 0; i < slide.size(); i++) { img = new BufferedImage( pgsize.width, pgsize.height, BufferedImage.TYPE_INT_RGB); Graphics2D graphics = img.createGraphics(); // clear area graphics.setPaint(Color.white); graphics.fill(new Rectangle2D.Float( 0, 0, pgsize.width, pgsize.height)); // draw the images slide.get(i).draw(graphics); FileOutputStream out = new FileOutputStream( "ppt_image" + i + ".png"); javax.imageio.ImageIO.write(img, "png", out); ppt.write(out); out.close(); System.out.println(i); } System.out.println("Image successfully created"); }}
Before the execution of the program:
After Execution of the program:
anikakapoor
Picked
Technical Scripter 2020
Java
Java Programs
Technical Scripter
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Functional Interfaces in Java
Stream In Java
Constructors in Java
Different ways of Reading a text file in Java
Exceptions in Java
Convert a String to Character array in Java
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
How to Iterate HashMap in Java? | [
{
"code": null,
"e": 23581,
"s": 23553,
"text": "\n15 Jul, 2021"
},
{
"code": null,
"e": 24026,
"s": 23581,
"text": "To convert PowerPoint slides to images, multiple packages are required like, java.awt because It contains all the classes for creating user interfaces and for painting graphics and images, java.io because It provides a set of input streams and a set of output streams used to read and write data to files or other input and output sources, Apache POI because It is used to create, modify, and display Microsoft Office files using Java programs."
},
{
"code": null,
"e": 24047,
"s": 24026,
"text": "Download Apache POI "
},
{
"code": null,
"e": 24337,
"s": 24047,
"text": "Download the zip file from the official site.Extract the external jar files from the zip file.Add the external jar files. For that select Java Build Path -> Configure Build Path -> Libraries -> Class -> Add External Jars...Select the jar file from the required folderClick Apply and close."
},
{
"code": null,
"e": 24383,
"s": 24337,
"text": "Download the zip file from the official site."
},
{
"code": null,
"e": 24433,
"s": 24383,
"text": "Extract the external jar files from the zip file."
},
{
"code": null,
"e": 24563,
"s": 24433,
"text": "Add the external jar files. For that select Java Build Path -> Configure Build Path -> Libraries -> Class -> Add External Jars..."
},
{
"code": null,
"e": 24608,
"s": 24563,
"text": "Select the jar file from the required folder"
},
{
"code": null,
"e": 24631,
"s": 24608,
"text": "Click Apply and close."
},
{
"code": null,
"e": 24653,
"s": 24631,
"text": "Imports from java.awt"
},
{
"code": null,
"e": 25131,
"s": 24653,
"text": "java.awt.Color: This class has the colors needed to change the appearance of objects in the interface.java.awt.Dimension It contains the height and width of a component.java.awt.Graphics2D It provides provides control over geometry, coordinate transformations, color management, and text layout.java.awt.geom.Rectangle2D It describes a rectangle defined by a location (x,y) and dimension (w x h) .java.awt.image.BufferedImage It is used to handle and manipulate the image data."
},
{
"code": null,
"e": 25234,
"s": 25131,
"text": "java.awt.Color: This class has the colors needed to change the appearance of objects in the interface."
},
{
"code": null,
"e": 25302,
"s": 25234,
"text": "java.awt.Dimension It contains the height and width of a component."
},
{
"code": null,
"e": 25429,
"s": 25302,
"text": "java.awt.Graphics2D It provides provides control over geometry, coordinate transformations, color management, and text layout."
},
{
"code": null,
"e": 25532,
"s": 25429,
"text": "java.awt.geom.Rectangle2D It describes a rectangle defined by a location (x,y) and dimension (w x h) ."
},
{
"code": null,
"e": 25613,
"s": 25532,
"text": "java.awt.image.BufferedImage It is used to handle and manipulate the image data."
},
{
"code": null,
"e": 25635,
"s": 25613,
"text": "Imports from java.io "
},
{
"code": null,
"e": 25982,
"s": 25635,
"text": "java.io.File: It contains several methods for working with the path name, deleting and renaming files,etc.java.io.FileInputStream: It is used to read data from a file.java.io.FileOutputStream: It is used for writing data to a File.java.io.IOException: It is an exception which is used in the code to throw a failure in Input and Output operations"
},
{
"code": null,
"e": 26089,
"s": 25982,
"text": "java.io.File: It contains several methods for working with the path name, deleting and renaming files,etc."
},
{
"code": null,
"e": 26151,
"s": 26089,
"text": "java.io.FileInputStream: It is used to read data from a file."
},
{
"code": null,
"e": 26216,
"s": 26151,
"text": "java.io.FileOutputStream: It is used for writing data to a File."
},
{
"code": null,
"e": 26332,
"s": 26216,
"text": "java.io.IOException: It is an exception which is used in the code to throw a failure in Input and Output operations"
},
{
"code": null,
"e": 26357,
"s": 26332,
"text": "Imports from Apache POI "
},
{
"code": null,
"e": 26559,
"s": 26357,
"text": "org.apache.poi.xslf.usermodel.XMLSlideShow: It is used to create objects to read or write a slideshow.org.apache.poi.xslf.usermodel.XSLFSlide: It is used to create and manage a slide in a presentation."
},
{
"code": null,
"e": 26662,
"s": 26559,
"text": "org.apache.poi.xslf.usermodel.XMLSlideShow: It is used to create objects to read or write a slideshow."
},
{
"code": null,
"e": 26762,
"s": 26662,
"text": "org.apache.poi.xslf.usermodel.XSLFSlide: It is used to create and manage a slide in a presentation."
},
{
"code": null,
"e": 26778,
"s": 26762,
"text": "Implementation:"
},
{
"code": null,
"e": 26783,
"s": 26778,
"text": "Java"
},
{
"code": "// Converting the slides of a PPT into Images using Javaimport java.util.List; import java.awt.Color;import java.awt.Dimension;import java.awt.Graphics2D;import java.awt.geom.Rectangle2D;import java.awt.image.BufferedImage; import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException; import org.apache.poi.xslf.usermodel.XMLSlideShow;import org.apache.poi.xslf.usermodel.XSLFSlide; public class PPTToImages { public static void main(String args[]) throws IOException { // create an empty presentation File file = new File(\"slides.pptx\"); XMLSlideShow ppt = new XMLSlideShow(new FileInputStream(file)); // get the dimension and size of the slide Dimension pgsize = ppt.getPageSize(); List<XSLFSlide> slide = ppt.getSlides(); BufferedImage img = null; System.out.println(slide.size()); for (int i = 0; i < slide.size(); i++) { img = new BufferedImage( pgsize.width, pgsize.height, BufferedImage.TYPE_INT_RGB); Graphics2D graphics = img.createGraphics(); // clear area graphics.setPaint(Color.white); graphics.fill(new Rectangle2D.Float( 0, 0, pgsize.width, pgsize.height)); // draw the images slide.get(i).draw(graphics); FileOutputStream out = new FileOutputStream( \"ppt_image\" + i + \".png\"); javax.imageio.ImageIO.write(img, \"png\", out); ppt.write(out); out.close(); System.out.println(i); } System.out.println(\"Image successfully created\"); }}",
"e": 28482,
"s": 26783,
"text": null
},
{
"code": null,
"e": 28519,
"s": 28482,
"text": "Before the execution of the program:"
},
{
"code": null,
"e": 28551,
"s": 28519,
"text": "After Execution of the program:"
},
{
"code": null,
"e": 28567,
"s": 28555,
"text": "anikakapoor"
},
{
"code": null,
"e": 28574,
"s": 28567,
"text": "Picked"
},
{
"code": null,
"e": 28598,
"s": 28574,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 28603,
"s": 28598,
"text": "Java"
},
{
"code": null,
"e": 28617,
"s": 28603,
"text": "Java Programs"
},
{
"code": null,
"e": 28636,
"s": 28617,
"text": "Technical Scripter"
},
{
"code": null,
"e": 28641,
"s": 28636,
"text": "Java"
},
{
"code": null,
"e": 28739,
"s": 28641,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28748,
"s": 28739,
"text": "Comments"
},
{
"code": null,
"e": 28761,
"s": 28748,
"text": "Old Comments"
},
{
"code": null,
"e": 28791,
"s": 28761,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 28806,
"s": 28791,
"text": "Stream In Java"
},
{
"code": null,
"e": 28827,
"s": 28806,
"text": "Constructors in Java"
},
{
"code": null,
"e": 28873,
"s": 28827,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 28892,
"s": 28873,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 28936,
"s": 28892,
"text": "Convert a String to Character array in Java"
},
{
"code": null,
"e": 28962,
"s": 28936,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 28996,
"s": 28962,
"text": "Convert Double to Integer in Java"
},
{
"code": null,
"e": 29043,
"s": 28996,
"text": "Implementing a Linked List in Java using Class"
}
] |
Spring Boot JPA - Unit Test Repository | To test a Repository, we need the following annotation and classes −
@ExtendWith(SpringExtension.class) − Mark the class to run as test case using SpringExtension class.
@ExtendWith(SpringExtension.class) − Mark the class to run as test case using SpringExtension class.
@SpringBootTest(classes = SprintBootH2Application.class) − Configure the Spring Boot application.
@SpringBootTest(classes = SprintBootH2Application.class) − Configure the Spring Boot application.
@Transactional − To mark repository to do CRUD Operation capable.
@Transactional − To mark repository to do CRUD Operation capable.
@Autowired private EmployeeRepository employeeRepository − EmployeeRepository object to be tested.
@Autowired private EmployeeRepository employeeRepository − EmployeeRepository object to be tested.
Following is the complete code of EmployeeRepositoryTest.
package com.tutorialspoint.repository;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.ArrayList;
import java.util.List;
import javax.transaction.Transactional;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import com.tutorialspoint.entity.Employee;
import com.tutorialspoint.sprintbooth2.SprintBootH2Application;
@ExtendWith(SpringExtension.class)
@Transactional
@SpringBootTest(classes = SprintBootH2Application.class)
public class EmployeeRepositoryTest {
@Autowired
private EmployeeRepository employeeRepository;
@Test
public void testFindById() {
Employee employee = getEmployee();
employeeRepository.save(employee);
Employee result = employeeRepository.findById(employee.getId()).get();
assertEquals(employee.getId(), result.getId());
}
@Test
public void testFindAll() {
Employee employee = getEmployee();
employeeRepository.save(employee);
List<Employee> result = new ArrayList<>();
employeeRepository.findAll().forEach(e -> result.add(e));
assertEquals(result.size(), 1);
}
@Test
public void testSave() {
Employee employee = getEmployee();
employeeRepository.save(employee);
Employee found = employeeRepository.findById(employee.getId()).get();
assertEquals(employee.getId(), found.getId());
}
@Test
public void testDeleteById() {
Employee employee = getEmployee();
employeeRepository.save(employee);
employeeRepository.deleteById(employee.getId());
List<Employee> result = new ArrayList<>();
employeeRepository.findAll().forEach(e -> result.add(e));
assertEquals(result.size(), 0);
}
private Employee getEmployee() {
Employee employee = new Employee();
employee.setId(1);
employee.setName("Mahesh");
employee.setAge(30);
employee.setEmail("[email protected]");
return employee;
}
}
Right Click on the file in eclipse and select Run a JUnit Test and verify the result.
102 Lectures
8 hours
Karthikeya T
39 Lectures
5 hours
Chaand Sheikh
73 Lectures
5.5 hours
Senol Atac
62 Lectures
4.5 hours
Senol Atac
67 Lectures
4.5 hours
Senol Atac
69 Lectures
5 hours
Senol Atac
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2047,
"s": 1978,
"text": "To test a Repository, we need the following annotation and classes −"
},
{
"code": null,
"e": 2148,
"s": 2047,
"text": "@ExtendWith(SpringExtension.class) − Mark the class to run as test case using SpringExtension class."
},
{
"code": null,
"e": 2249,
"s": 2148,
"text": "@ExtendWith(SpringExtension.class) − Mark the class to run as test case using SpringExtension class."
},
{
"code": null,
"e": 2347,
"s": 2249,
"text": "@SpringBootTest(classes = SprintBootH2Application.class) − Configure the Spring Boot application."
},
{
"code": null,
"e": 2445,
"s": 2347,
"text": "@SpringBootTest(classes = SprintBootH2Application.class) − Configure the Spring Boot application."
},
{
"code": null,
"e": 2511,
"s": 2445,
"text": "@Transactional − To mark repository to do CRUD Operation capable."
},
{
"code": null,
"e": 2577,
"s": 2511,
"text": "@Transactional − To mark repository to do CRUD Operation capable."
},
{
"code": null,
"e": 2676,
"s": 2577,
"text": "@Autowired private EmployeeRepository employeeRepository − EmployeeRepository object to be tested."
},
{
"code": null,
"e": 2775,
"s": 2676,
"text": "@Autowired private EmployeeRepository employeeRepository − EmployeeRepository object to be tested."
},
{
"code": null,
"e": 2833,
"s": 2775,
"text": "Following is the complete code of EmployeeRepositoryTest."
},
{
"code": null,
"e": 5012,
"s": 2833,
"text": "package com.tutorialspoint.repository;\n\nimport static org.junit.jupiter.api.Assertions.assertEquals;\nimport java.util.ArrayList;\nimport java.util.List;\nimport javax.transaction.Transactional;\nimport org.junit.jupiter.api.Test;\nimport org.junit.jupiter.api.extension.ExtendWith;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.boot.test.context.SpringBootTest;\nimport org.springframework.test.context.junit.jupiter.SpringExtension;\nimport com.tutorialspoint.entity.Employee;\nimport com.tutorialspoint.sprintbooth2.SprintBootH2Application;\n\n@ExtendWith(SpringExtension.class)\n@Transactional\n@SpringBootTest(classes = SprintBootH2Application.class)\npublic class EmployeeRepositoryTest {\n @Autowired\n private EmployeeRepository employeeRepository;\n\n @Test\n public void testFindById() {\n Employee employee = getEmployee();\t \n employeeRepository.save(employee);\n Employee result = employeeRepository.findById(employee.getId()).get();\n assertEquals(employee.getId(), result.getId());\t \n }\n @Test\n public void testFindAll() {\n Employee employee = getEmployee();\n employeeRepository.save(employee);\n List<Employee> result = new ArrayList<>();\n employeeRepository.findAll().forEach(e -> result.add(e));\n assertEquals(result.size(), 1);\t \n }\n @Test\n public void testSave() {\n Employee employee = getEmployee();\n employeeRepository.save(employee);\n Employee found = employeeRepository.findById(employee.getId()).get();\n assertEquals(employee.getId(), found.getId());\t \n }\n @Test\n public void testDeleteById() {\n Employee employee = getEmployee();\n employeeRepository.save(employee);\n employeeRepository.deleteById(employee.getId());\n List<Employee> result = new ArrayList<>();\n employeeRepository.findAll().forEach(e -> result.add(e));\n assertEquals(result.size(), 0);\n }\n private Employee getEmployee() {\n Employee employee = new Employee();\n employee.setId(1);\n employee.setName(\"Mahesh\");\n employee.setAge(30);\n employee.setEmail(\"[email protected]\");\n return employee;\n }\n}"
},
{
"code": null,
"e": 5098,
"s": 5012,
"text": "Right Click on the file in eclipse and select Run a JUnit Test and verify the result."
},
{
"code": null,
"e": 5132,
"s": 5098,
"text": "\n 102 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 5146,
"s": 5132,
"text": " Karthikeya T"
},
{
"code": null,
"e": 5179,
"s": 5146,
"text": "\n 39 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 5194,
"s": 5179,
"text": " Chaand Sheikh"
},
{
"code": null,
"e": 5229,
"s": 5194,
"text": "\n 73 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 5241,
"s": 5229,
"text": " Senol Atac"
},
{
"code": null,
"e": 5276,
"s": 5241,
"text": "\n 62 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 5288,
"s": 5276,
"text": " Senol Atac"
},
{
"code": null,
"e": 5323,
"s": 5288,
"text": "\n 67 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 5335,
"s": 5323,
"text": " Senol Atac"
},
{
"code": null,
"e": 5368,
"s": 5335,
"text": "\n 69 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 5380,
"s": 5368,
"text": " Senol Atac"
},
{
"code": null,
"e": 5387,
"s": 5380,
"text": " Print"
},
{
"code": null,
"e": 5398,
"s": 5387,
"text": " Add Notes"
}
] |
How to extract numbers from cell array in MATLAB? - GeeksforGeeks | 23 Jul, 2021
In this article, we are going to discuss the extraction of numbers from the cell array with the help of regexp(), str2double(), cat(), and isletter() functions.
A cell array is nothing but a data type having indexed data containers called cells, where each cell contains any type of data. It mainly contains either a list of texts, combinations of text and numbers, or numeric arrays of different sizes.
Example:
Matlab
% MATLAB code for put data in the cell arrayA = {2, 4, 'gfg'}B = {1, 'GFG', {5; 10; 15}}
Output:
The regexp() function is used for matching the regular expression. It is case-sensitive.
Syntax:
startIndex = regexp(str, expression)
[startIndex, endIndex] = regexp(str, expression)
out = regexp(str, expression, outkey)
startIndex = regexp(str, expression) is used to return the starting index of each substring of str that matches the character patterns specified by the regular expression. If there are no matches, startIndex is an empty array.
[startIndex,endIndex] = regexp(str,expression) is used to return the starting and ending indices of all matches.
regexp(str, expression, outkey) is used to return the output specified by the outkey. For example, if outkey is ‘match’, then this function returns the substrings that match the expression rather than their starting indices.
Example:
Matlab
% MATLAB code for regexp with strjoin()% Initializing a cell arrayA = {'gfg'; 'gfg1.23GFG'; '5gfg10'};b=regexp(A,'\d+(\.)?(\d+)?','match')out=strjoin([b{:}],'')
Output:
The str2double() function is used for the conversion of strings to double-precision values.
Syntax:
str2double(string)
Here, str2double(string) is used to convert the text in the specified string to double-precision values.
Example:
Matlab
% MATLAB code for regexp() demonstration% Initializing a cell arrayA = {'gfg'; 'gfg1.23GFG'; '5gfg10'}; % Calling the regexp() function over the% above cell array to extract number partB = regexp(A,'\d+(\.)?(\d+)?','match'); % Calling the str2double() function to % convert the text to double-precision valuesout = str2double([B{:}])
Output:
out =
1.2300 5.0000 10.0000
The cat() function is used to concatenate the specified arrays.
Syntax:
cat(dim, A, B)
cat(dim, A1, A2 ,..., An)
cat(dim, A, B) is used to concatenate “B” to the end of “A” along with the dimension “dim” when A and B have compatible sizes, i.e. the lengths of the dimensions match except for the operating dimension dim.
cat(dim, A1, A2, ..., An) is used to concatenate “A1, A2, ..., An” along with the dimension dim.
Matlab
% MATLAB code for extract numbers from% cell using regexp with strcat()% Initializing a cell arrayA = {'gfg'; 'gfg1.23GFG'; '5gfg10'};A1 = regexp(A,'[\d*\.]*\d*','match')A2 = [A1{:}]out = str2double(strcat(A2{:}))
Output:
The isletter() function is used to find the array of elements that are letters of the alphabet.
Syntax:
isletter(‘string’)
Here, isletter(‘string’) is used to return an array the same size as the specified “string” that contains logical true i.e. 1 when the elements of “string” are letters of the alphabet, and logical false i.e. 0 when they are not.
Example
Matlab
% MATLAB code for isletter() demonstration% Initializing a cell arrayA = {'gfg'; 'gfg1.23GFG'; '5gfg'}; % Calling the cat() function to% concatenate the data of the above% cell array into a single string% one after anotherS = cat(2, A{:}); % Calling the isletter() function% to filter the numeric value S(isletter(S)) = []
Output:
S = 1.235
MATLAB Array-Programs
MATLAB-programs
MATLAB
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Remove Noise from Digital Image in Frequency Domain Using MATLAB?
MRI Image Segmentation in MATLAB
How to Solve Histogram Equalization Numerical Problem in MATLAB?
How to Normalize a Histogram in MATLAB?
Laplace Transform in MATLAB
Laplacian of Gaussian Filter in MATLAB
Adaptive Histogram Equalization in Image Processing Using MATLAB
Forward and Inverse Fourier Transform of an Image in MATLAB
Boundary Extraction of image using MATLAB
How to Remove Salt and Pepper Noise from Image Using MATLAB? | [
{
"code": null,
"e": 24255,
"s": 24227,
"text": "\n23 Jul, 2021"
},
{
"code": null,
"e": 24416,
"s": 24255,
"text": "In this article, we are going to discuss the extraction of numbers from the cell array with the help of regexp(), str2double(), cat(), and isletter() functions."
},
{
"code": null,
"e": 24660,
"s": 24416,
"text": "A cell array is nothing but a data type having indexed data containers called cells, where each cell contains any type of data. It mainly contains either a list of texts, combinations of text and numbers, or numeric arrays of different sizes. "
},
{
"code": null,
"e": 24669,
"s": 24660,
"text": "Example:"
},
{
"code": null,
"e": 24676,
"s": 24669,
"text": "Matlab"
},
{
"code": "% MATLAB code for put data in the cell arrayA = {2, 4, 'gfg'}B = {1, 'GFG', {5; 10; 15}}",
"e": 24765,
"s": 24676,
"text": null
},
{
"code": null,
"e": 24773,
"s": 24765,
"text": "Output:"
},
{
"code": null,
"e": 24862,
"s": 24773,
"text": "The regexp() function is used for matching the regular expression. It is case-sensitive."
},
{
"code": null,
"e": 24870,
"s": 24862,
"text": "Syntax:"
},
{
"code": null,
"e": 24907,
"s": 24870,
"text": "startIndex = regexp(str, expression)"
},
{
"code": null,
"e": 24956,
"s": 24907,
"text": "[startIndex, endIndex] = regexp(str, expression)"
},
{
"code": null,
"e": 24994,
"s": 24956,
"text": "out = regexp(str, expression, outkey)"
},
{
"code": null,
"e": 25221,
"s": 24994,
"text": "startIndex = regexp(str, expression) is used to return the starting index of each substring of str that matches the character patterns specified by the regular expression. If there are no matches, startIndex is an empty array."
},
{
"code": null,
"e": 25334,
"s": 25221,
"text": "[startIndex,endIndex] = regexp(str,expression) is used to return the starting and ending indices of all matches."
},
{
"code": null,
"e": 25559,
"s": 25334,
"text": "regexp(str, expression, outkey) is used to return the output specified by the outkey. For example, if outkey is ‘match’, then this function returns the substrings that match the expression rather than their starting indices."
},
{
"code": null,
"e": 25568,
"s": 25559,
"text": "Example:"
},
{
"code": null,
"e": 25575,
"s": 25568,
"text": "Matlab"
},
{
"code": "% MATLAB code for regexp with strjoin()% Initializing a cell arrayA = {'gfg'; 'gfg1.23GFG'; '5gfg10'};b=regexp(A,'\\d+(\\.)?(\\d+)?','match')out=strjoin([b{:}],'')",
"e": 25736,
"s": 25575,
"text": null
},
{
"code": null,
"e": 25744,
"s": 25736,
"text": "Output:"
},
{
"code": null,
"e": 25836,
"s": 25744,
"text": "The str2double() function is used for the conversion of strings to double-precision values."
},
{
"code": null,
"e": 25844,
"s": 25836,
"text": "Syntax:"
},
{
"code": null,
"e": 25863,
"s": 25844,
"text": "str2double(string)"
},
{
"code": null,
"e": 25968,
"s": 25863,
"text": "Here, str2double(string) is used to convert the text in the specified string to double-precision values."
},
{
"code": null,
"e": 25977,
"s": 25968,
"text": "Example:"
},
{
"code": null,
"e": 25984,
"s": 25977,
"text": "Matlab"
},
{
"code": "% MATLAB code for regexp() demonstration% Initializing a cell arrayA = {'gfg'; 'gfg1.23GFG'; '5gfg10'}; % Calling the regexp() function over the% above cell array to extract number partB = regexp(A,'\\d+(\\.)?(\\d+)?','match'); % Calling the str2double() function to % convert the text to double-precision valuesout = str2double([B{:}])",
"e": 26320,
"s": 25984,
"text": null
},
{
"code": null,
"e": 26328,
"s": 26320,
"text": "Output:"
},
{
"code": null,
"e": 26364,
"s": 26328,
"text": "out =\n 1.2300 5.0000 10.0000"
},
{
"code": null,
"e": 26428,
"s": 26364,
"text": "The cat() function is used to concatenate the specified arrays."
},
{
"code": null,
"e": 26436,
"s": 26428,
"text": "Syntax:"
},
{
"code": null,
"e": 26451,
"s": 26436,
"text": "cat(dim, A, B)"
},
{
"code": null,
"e": 26477,
"s": 26451,
"text": "cat(dim, A1, A2 ,..., An)"
},
{
"code": null,
"e": 26685,
"s": 26477,
"text": "cat(dim, A, B) is used to concatenate “B” to the end of “A” along with the dimension “dim” when A and B have compatible sizes, i.e. the lengths of the dimensions match except for the operating dimension dim."
},
{
"code": null,
"e": 26782,
"s": 26685,
"text": "cat(dim, A1, A2, ..., An) is used to concatenate “A1, A2, ..., An” along with the dimension dim."
},
{
"code": null,
"e": 26789,
"s": 26782,
"text": "Matlab"
},
{
"code": "% MATLAB code for extract numbers from% cell using regexp with strcat()% Initializing a cell arrayA = {'gfg'; 'gfg1.23GFG'; '5gfg10'};A1 = regexp(A,'[\\d*\\.]*\\d*','match')A2 = [A1{:}]out = str2double(strcat(A2{:}))",
"e": 27003,
"s": 26789,
"text": null
},
{
"code": null,
"e": 27011,
"s": 27003,
"text": "Output:"
},
{
"code": null,
"e": 27107,
"s": 27011,
"text": "The isletter() function is used to find the array of elements that are letters of the alphabet."
},
{
"code": null,
"e": 27115,
"s": 27107,
"text": "Syntax:"
},
{
"code": null,
"e": 27134,
"s": 27115,
"text": "isletter(‘string’)"
},
{
"code": null,
"e": 27363,
"s": 27134,
"text": "Here, isletter(‘string’) is used to return an array the same size as the specified “string” that contains logical true i.e. 1 when the elements of “string” are letters of the alphabet, and logical false i.e. 0 when they are not."
},
{
"code": null,
"e": 27372,
"s": 27363,
"text": "Example "
},
{
"code": null,
"e": 27379,
"s": 27372,
"text": "Matlab"
},
{
"code": "% MATLAB code for isletter() demonstration% Initializing a cell arrayA = {'gfg'; 'gfg1.23GFG'; '5gfg'}; % Calling the cat() function to% concatenate the data of the above% cell array into a single string% one after anotherS = cat(2, A{:}); % Calling the isletter() function% to filter the numeric value S(isletter(S)) = []",
"e": 27704,
"s": 27379,
"text": null
},
{
"code": null,
"e": 27712,
"s": 27704,
"text": "Output:"
},
{
"code": null,
"e": 27722,
"s": 27712,
"text": "S = 1.235"
},
{
"code": null,
"e": 27744,
"s": 27722,
"text": "MATLAB Array-Programs"
},
{
"code": null,
"e": 27760,
"s": 27744,
"text": "MATLAB-programs"
},
{
"code": null,
"e": 27767,
"s": 27760,
"text": "MATLAB"
},
{
"code": null,
"e": 27865,
"s": 27767,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27874,
"s": 27865,
"text": "Comments"
},
{
"code": null,
"e": 27887,
"s": 27874,
"text": "Old Comments"
},
{
"code": null,
"e": 27960,
"s": 27887,
"text": "How to Remove Noise from Digital Image in Frequency Domain Using MATLAB?"
},
{
"code": null,
"e": 27993,
"s": 27960,
"text": "MRI Image Segmentation in MATLAB"
},
{
"code": null,
"e": 28058,
"s": 27993,
"text": "How to Solve Histogram Equalization Numerical Problem in MATLAB?"
},
{
"code": null,
"e": 28098,
"s": 28058,
"text": "How to Normalize a Histogram in MATLAB?"
},
{
"code": null,
"e": 28126,
"s": 28098,
"text": "Laplace Transform in MATLAB"
},
{
"code": null,
"e": 28165,
"s": 28126,
"text": "Laplacian of Gaussian Filter in MATLAB"
},
{
"code": null,
"e": 28230,
"s": 28165,
"text": "Adaptive Histogram Equalization in Image Processing Using MATLAB"
},
{
"code": null,
"e": 28290,
"s": 28230,
"text": "Forward and Inverse Fourier Transform of an Image in MATLAB"
},
{
"code": null,
"e": 28332,
"s": 28290,
"text": "Boundary Extraction of image using MATLAB"
}
] |
Impala - Shell | In the earlier chapters, we have seen the installation of Impala using cloudera
and its architecture.
Impala shell (command prompt)
Hue (User Interface)
ODBC and JDBC (Third party libraries)
This chapter explains how to start Impala Shell and the various options of the shell.
The commands of Impala shell are classified as general commands, query specific options, and table and database specific options, as explained below.
help
version
history
shell (or) !
connect
exit | quit
Set/unset
Profile
Explain
Alter
describe
drop
insert
select
show
use
Open the cloudera terminal, sign in as superuser, and type cloudera as password as shown below.
[cloudera@quickstart ~]$ su
Password: cloudera
[root@quickstart cloudera]#
Start Impala shell by typing the following command −
[root@quickstart cloudera] # impala-shell
Starting Impala Shell without Kerberos authentication
Connected to quickstart.cloudera:21000
Server version: impalad version 2.3.0-cdh5.5.0 RELEASE
(build 0c891d79aa38f297d244855a32f1e17280e2129b)
*********************************************************************
Welcome to the Impala shell. Copyright (c) 2015 Cloudera, Inc. All rights reserved.
(Impala Shell v2.3.0-cdh5.5.0 (0c891d7) built on Mon Nov 9 12:18:12 PST 2015)
Want to know what version of Impala you're connected to? Run the VERSION command to
find out!
*********************************************************************
[quickstart.cloudera:21000] >
The general purpose commands of Impala are explained below −
The help command of Impala shell gives you a list of the commands available in Impala −
[quickstart.cloudera:21000] > help;
Documented commands (type help <topic>):
========================================================
compute describe insert set unset with version
connect explain quit show values use
exit history profile select shell tip
Undocumented commands:
=========================================
alter create desc drop help load summary
The version command gives you the current version of Impala, as shown below.
[quickstart.cloudera:21000] > version;
Shell version: Impala Shell v2.3.0-cdh5.5.0 (0c891d7) built on Mon Nov 9
12:18:12 PST 2015
Server version: impalad version 2.3.0-cdh5.5.0 RELEASE (build
0c891d79aa38f297d244855a32f1e17280e2129b)
The history command of Impala displays the last 10 commands executed in the shell. Following is the example of the history command. Here we have executed 5 commands, namely, version, help, show, use, and history.
[quickstart.cloudera:21000] > history;
[1]:version;
[2]:help;
[3]:show databases;
[4]:use my_db;
[5]:history;
You can come out of the Impala shell using the quit or exit command, as shown below.
[quickstart.cloudera:21000] > exit;
Goodbye cloudera
The connect command is used to connect to a given instance of Impala. In case you do not specify any instance, then it connects to the default port 21000 as shown below.
[quickstart.cloudera:21000] > connect;
Connected to quickstart.cloudera:21000
Server version: impalad version 2.3.0-cdh5.5.0 RELEASE (build
0c891d79aa38f297d244855a32f1e17280e2129b)
The query specific commands of Impala accept a query. They are explained below −
The explain command returns the execution plan for the given query.
[quickstart.cloudera:21000] > explain select * from sample;
Query: explain select * from sample
+------------------------------------------------------------------------------------+
| Explain String |
+------------------------------------------------------------------------------------+
| Estimated Per-Host Requirements: Memory = 48.00MB VCores = 1 |
| WARNING: The following tables are missing relevant table and/or column statistics. |
| my_db.customers |
| 01:EXCHANGE [UNPARTITIONED] |
| 00:SCAN HDFS [my_db.customers] |
| partitions = 1/1 files = 6 size = 148B |
+------------------------------------------------------------------------------------+
Fetched 7 row(s) in 0.17s
The profile command displays the low-level information about the recent query. This command is used for diagnosis and performance tuning of a query. Following is the example of a profile command. In this scenario, the profile command returns the low-level information of explain query.
[quickstart.cloudera:21000] > profile;
Query Runtime Profile:
Query (id=164b1294a1049189:a67598a6699e3ab6):
Summary:
Session ID: e74927207cd752b5:65ca61e630ad3ad
Session Type: BEESWAX
Start Time: 2016-04-17 23:49:26.08148000 End Time: 2016-04-17 23:49:26.2404000
Query Type: EXPLAIN
Query State: FINISHED
Query Status: OK
Impala Version: impalad version 2.3.0-cdh5.5.0 RELEASE (build 0c891d77280e2129b)
User: cloudera
Connected User: cloudera
Delegated User:
Network Address:10.0.2.15:43870
Default Db: my_db
Sql Statement: explain select * from sample
Coordinator: quickstart.cloudera:22000
: 0ns
Query Timeline: 167.304ms
- Start execution: 41.292us (41.292us) - Planning finished: 56.42ms (56.386ms)
- Rows available: 58.247ms (1.819ms)
- First row fetched: 160.72ms (101.824ms)
- Unregister query: 166.325ms (6.253ms)
ImpalaServer:
- ClientFetchWaitTimer: 107.969ms
- RowMaterializationTimer: 0ns
The following table lists out the table and data specific options in Impala.
Alter
The alter command is used to change the structure and name of a table in Impala.
Describe
The describe command of Impala gives the metadata of a table. It contains the information like columns and their data types. The describe command has desc as a short cut.
Drop
The drop command is used to remove a construct from Impala, where a construct can be a table, a view, or a database function.
insert
The insert command of Impala is used to,
Append data (columns) into a table.
Override the data of an existing table.
Override the data of an existing table.
select
The select statement is used to perform a desired operation on a particular dataset. It specifies the dataset on which to complete some action. You can print or store (in a file) the result of the select statement.
show
The show statement of Impala is used to display the metastore of various constructs such as tables, databases, and tables.
use
The use statement of Impala is used to change the current context to the desired database.
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2388,
"s": 2285,
"text": "In the earlier chapters, we have seen the installation of Impala using cloudera \nand its architecture."
},
{
"code": null,
"e": 2418,
"s": 2388,
"text": "Impala shell (command prompt)"
},
{
"code": null,
"e": 2439,
"s": 2418,
"text": "Hue (User Interface)"
},
{
"code": null,
"e": 2477,
"s": 2439,
"text": "ODBC and JDBC (Third party libraries)"
},
{
"code": null,
"e": 2563,
"s": 2477,
"text": "This chapter explains how to start Impala Shell and the various options of the shell."
},
{
"code": null,
"e": 2713,
"s": 2563,
"text": "The commands of Impala shell are classified as general commands, query specific options, and table and database specific options, as explained below."
},
{
"code": null,
"e": 2718,
"s": 2713,
"text": "help"
},
{
"code": null,
"e": 2726,
"s": 2718,
"text": "version"
},
{
"code": null,
"e": 2734,
"s": 2726,
"text": "history"
},
{
"code": null,
"e": 2747,
"s": 2734,
"text": "shell (or) !"
},
{
"code": null,
"e": 2755,
"s": 2747,
"text": "connect"
},
{
"code": null,
"e": 2767,
"s": 2755,
"text": "exit | quit"
},
{
"code": null,
"e": 2777,
"s": 2767,
"text": "Set/unset"
},
{
"code": null,
"e": 2785,
"s": 2777,
"text": "Profile"
},
{
"code": null,
"e": 2793,
"s": 2785,
"text": "Explain"
},
{
"code": null,
"e": 2799,
"s": 2793,
"text": "Alter"
},
{
"code": null,
"e": 2808,
"s": 2799,
"text": "describe"
},
{
"code": null,
"e": 2813,
"s": 2808,
"text": "drop"
},
{
"code": null,
"e": 2820,
"s": 2813,
"text": "insert"
},
{
"code": null,
"e": 2827,
"s": 2820,
"text": "select"
},
{
"code": null,
"e": 2832,
"s": 2827,
"text": "show"
},
{
"code": null,
"e": 2836,
"s": 2832,
"text": "use"
},
{
"code": null,
"e": 2932,
"s": 2836,
"text": "Open the cloudera terminal, sign in as superuser, and type cloudera as password as shown below."
},
{
"code": null,
"e": 3008,
"s": 2932,
"text": "[cloudera@quickstart ~]$ su\nPassword: cloudera\n[root@quickstart cloudera]#\n"
},
{
"code": null,
"e": 3061,
"s": 3008,
"text": "Start Impala shell by typing the following command −"
},
{
"code": null,
"e": 3737,
"s": 3061,
"text": "[root@quickstart cloudera] # impala-shell \nStarting Impala Shell without Kerberos authentication \nConnected to quickstart.cloudera:21000 \nServer version: impalad version 2.3.0-cdh5.5.0 RELEASE \n(build 0c891d79aa38f297d244855a32f1e17280e2129b)\n********************************************************************* \n\nWelcome to the Impala shell. Copyright (c) 2015 Cloudera, Inc. All rights reserved.\n(Impala Shell v2.3.0-cdh5.5.0 (0c891d7) built on Mon Nov 9 12:18:12 PST 2015)\n\nWant to know what version of Impala you're connected to? Run the VERSION command to \nfind out! \n********************************************************************* \n[quickstart.cloudera:21000] >\n"
},
{
"code": null,
"e": 3799,
"s": 3737,
"text": "The general purpose commands of Impala are explained below −"
},
{
"code": null,
"e": 3887,
"s": 3799,
"text": "The help command of Impala shell gives you a list of the commands available in Impala −"
},
{
"code": null,
"e": 4283,
"s": 3887,
"text": "[quickstart.cloudera:21000] > help;\n \nDocumented commands (type help <topic>):\n========================================================\ncompute describe insert set unset with version\nconnect explain quit show values use\nexit history profile select shell tip \n \nUndocumented commands:\n========================================= \nalter create desc drop help load summary\n"
},
{
"code": null,
"e": 4360,
"s": 4283,
"text": "The version command gives you the current version of Impala, as shown below."
},
{
"code": null,
"e": 4598,
"s": 4360,
"text": "[quickstart.cloudera:21000] > version;\nShell version: Impala Shell v2.3.0-cdh5.5.0 (0c891d7) built on Mon Nov 9 \n12:18:12 PST 2015\n\nServer version: impalad version 2.3.0-cdh5.5.0 RELEASE (build \n0c891d79aa38f297d244855a32f1e17280e2129b)\n"
},
{
"code": null,
"e": 4811,
"s": 4598,
"text": "The history command of Impala displays the last 10 commands executed in the shell. Following is the example of the history command. Here we have executed 5 commands, namely, version, help, show, use, and history."
},
{
"code": null,
"e": 4922,
"s": 4811,
"text": "[quickstart.cloudera:21000] > history;\n[1]:version;\n[2]:help;\n[3]:show databases;\n[4]:use my_db;\n[5]:history;\n"
},
{
"code": null,
"e": 5007,
"s": 4922,
"text": "You can come out of the Impala shell using the quit or exit command, as shown below."
},
{
"code": null,
"e": 5062,
"s": 5007,
"text": "[quickstart.cloudera:21000] > exit; \nGoodbye cloudera\n"
},
{
"code": null,
"e": 5232,
"s": 5062,
"text": "The connect command is used to connect to a given instance of Impala. In case you do not specify any instance, then it connects to the default port 21000 as shown below."
},
{
"code": null,
"e": 5418,
"s": 5232,
"text": "[quickstart.cloudera:21000] > connect; \nConnected to quickstart.cloudera:21000 \nServer version: impalad version 2.3.0-cdh5.5.0 RELEASE (build \n0c891d79aa38f297d244855a32f1e17280e2129b)\n"
},
{
"code": null,
"e": 5499,
"s": 5418,
"text": "The query specific commands of Impala accept a query. They are explained below −"
},
{
"code": null,
"e": 5567,
"s": 5499,
"text": "The explain command returns the execution plan for the given query."
},
{
"code": null,
"e": 6569,
"s": 5567,
"text": "[quickstart.cloudera:21000] > explain select * from sample;\nQuery: explain select * from sample\n+------------------------------------------------------------------------------------+ \n| Explain String | \n+------------------------------------------------------------------------------------+ \n| Estimated Per-Host Requirements: Memory = 48.00MB VCores = 1 | \n| WARNING: The following tables are missing relevant table and/or column statistics. |\n| my_db.customers | \n| 01:EXCHANGE [UNPARTITIONED] | \n| 00:SCAN HDFS [my_db.customers] | \n| partitions = 1/1 files = 6 size = 148B | \n+------------------------------------------------------------------------------------+ \nFetched 7 row(s) in 0.17s\n"
},
{
"code": null,
"e": 6855,
"s": 6569,
"text": "The profile command displays the low-level information about the recent query. This command is used for diagnosis and performance tuning of a query. Following is the example of a profile command. In this scenario, the profile command returns the low-level information of explain query."
},
{
"code": null,
"e": 7941,
"s": 6855,
"text": "[quickstart.cloudera:21000] > profile;\n\nQuery Runtime Profile: \nQuery (id=164b1294a1049189:a67598a6699e3ab6): \n\n Summary: \n Session ID: e74927207cd752b5:65ca61e630ad3ad\n Session Type: BEESWAX \n Start Time: 2016-04-17 23:49:26.08148000 End Time: 2016-04-17 23:49:26.2404000 \n Query Type: EXPLAIN \n Query State: FINISHED \n Query Status: OK \n Impala Version: impalad version 2.3.0-cdh5.5.0 RELEASE (build 0c891d77280e2129b) \n User: cloudera \n Connected User: cloudera \n Delegated User: \n Network Address:10.0.2.15:43870 \n Default Db: my_db \n Sql Statement: explain select * from sample \n Coordinator: quickstart.cloudera:22000 \n : 0ns \n Query Timeline: 167.304ms \n - Start execution: 41.292us (41.292us) - Planning finished: 56.42ms (56.386ms) \n - Rows available: 58.247ms (1.819ms) \n - First row fetched: 160.72ms (101.824ms) \n - Unregister query: 166.325ms (6.253ms)\n \n ImpalaServer: \n - ClientFetchWaitTimer: 107.969ms \n - RowMaterializationTimer: 0ns"
},
{
"code": null,
"e": 8018,
"s": 7941,
"text": "The following table lists out the table and data specific options in Impala."
},
{
"code": null,
"e": 8024,
"s": 8018,
"text": "Alter"
},
{
"code": null,
"e": 8105,
"s": 8024,
"text": "The alter command is used to change the structure and name of a table in Impala."
},
{
"code": null,
"e": 8114,
"s": 8105,
"text": "Describe"
},
{
"code": null,
"e": 8285,
"s": 8114,
"text": "The describe command of Impala gives the metadata of a table. It contains the information like columns and their data types. The describe command has desc as a short cut."
},
{
"code": null,
"e": 8290,
"s": 8285,
"text": "Drop"
},
{
"code": null,
"e": 8416,
"s": 8290,
"text": "The drop command is used to remove a construct from Impala, where a construct can be a table, a view, or a database function."
},
{
"code": null,
"e": 8423,
"s": 8416,
"text": "insert"
},
{
"code": null,
"e": 8464,
"s": 8423,
"text": "The insert command of Impala is used to,"
},
{
"code": null,
"e": 8500,
"s": 8464,
"text": "Append data (columns) into a table."
},
{
"code": null,
"e": 8540,
"s": 8500,
"text": "Override the data of an existing table."
},
{
"code": null,
"e": 8580,
"s": 8540,
"text": "Override the data of an existing table."
},
{
"code": null,
"e": 8587,
"s": 8580,
"text": "select"
},
{
"code": null,
"e": 8802,
"s": 8587,
"text": "The select statement is used to perform a desired operation on a particular dataset. It specifies the dataset on which to complete some action. You can print or store (in a file) the result of the select statement."
},
{
"code": null,
"e": 8807,
"s": 8802,
"text": "show"
},
{
"code": null,
"e": 8930,
"s": 8807,
"text": "The show statement of Impala is used to display the metastore of various constructs such as tables, databases, and tables."
},
{
"code": null,
"e": 8934,
"s": 8930,
"text": "use"
},
{
"code": null,
"e": 9025,
"s": 8934,
"text": "The use statement of Impala is used to change the current context to the desired database."
},
{
"code": null,
"e": 9032,
"s": 9025,
"text": " Print"
},
{
"code": null,
"e": 9043,
"s": 9032,
"text": " Add Notes"
}
] |
Design a calendar using HTML and CSS - GeeksforGeeks | 27 Jan, 2021
In this article, we will create a calendar using HTML, and CSS. First, we have to know a little about HTML. If someone does not know HTML and CSS, they will not be able to make the calendar better. The main focus of this article is on HTML tags and the way we are going to use CSS.
Approach: First we will be using the table tag, which will be used to create the structure of the calendar. This will give us an idea of how the calendar is created using HTML. Later we will apply some CSS property to make the design of the calendar better.
Creating Structure: In this section, we will create first the structure of the calendar by using the <table> tag. So this will help us to get the structure of the calendar.
HTML
<!DOCTYPE html><html> <body> <!-- Here we are using attributes like cellspacing and cellpadding --> <!-- The purpose of the cellpadding is the space that a user want between the border of cell and its contents--> <!-- cellspacing is used to specify the space between the cell and its contents --> <h2 align="center" style="color: orange;"> January 2021 </h2> <br /> <table bgcolor="lightgrey" align="center" cellspacing="21" cellpadding="21"> <!-- The tr tag is used to enter rows in the table --> <!-- It is used to give the heading to the table. We can give the heading to the top and bottom of the table --> <caption align="top"> <!-- Here we have used the attribute that is style and we have colored the sentence to make it better depending on the web page--> </caption> <!-- Here th stands for the heading of the table that comes in the first row--> <!-- The text in this table header tag will appear as bold and is center aligned--> <thead> <tr> <!-- Here we have applied inline style to make it more attractive--> <th>Sun</th> <th>Mon</th> <th>Tue</th> <th>Wed</th> <th>Thu</th> <th>Fri</th> <th>sat</th> </tr> </thead> <tbody> <tr> <td></td> <td></td> <td></td> <td></td> <td></td> <td>1</td> <td>2</td> </tr> <tr></tr> <tr> <td>3</td> <td>4</td> <td>5</td> <td>6</td> <td>7</td> <td>8</td> <td>9</td> </tr> <tr> <td>10</td> <td>11</td> <td>12</td> <td>13</td> <td>14</td> <td>15</td> <td>16</td> </tr> <tr> <td>17</td> <td>18</td> <td>19</td> <td>20</td> <td>21</td> <td>22</td> <td>23</td> </tr> <tr> <td>24</td> <td>25</td> <td>26</td> <td>27</td> <td>28</td> <td>29</td> <td>30</td> </tr> <tr> <td>31</td> <td>1</td> <td>2</td> <td>3</td> <td>4</td> <td>5</td> <td>6</td> </tr> </tbody> </table></body> </html>
Output:
CSS Design and its attributes: We will use some CSS properties and attributes of the table tag to design the calendar. The attributes that we are going to use is the border and cellspacing and cellpadding. Here we have used an interesting property of CSS that is border-collapse. The purpose of the border-collapse is to make all the border to be collapsed into a single border. Here we have also used the inline style attribute to make the dates of February be little visible.
CSS code:
table {
border-collapse: collapse;
background: white;
color: black;
}
th, td {
font-weight: bold;
}
Attributes that we will use in the table tag:
<table bgcolor="lightgrey" align="center"
cellspacing="21" cellpadding="21">
Final code: This is the combination of all the above codes
HTML
<!DOCTYPE html><html> <head> <style> table { border-collapse: collapse; background: white; color: black; } th, td { font-weight: bold; } </style></head> <body> <!-- Here we are using attributes like cellspacing and cellpadding --> <!-- The purpose of the cellpadding is the space that a user want between the border of cell and its contents--> <!-- cellspacing is used to specify the space between the cell and its contents --> <h2 align="center" style="color: orange;"> January 2021 </h2> <br /> <table bgcolor="lightgrey" align="center" cellspacing="21" cellpadding="21"> <!-- The tr tag is used to enter rows in the table --> <!-- It is used to give the heading to the table. We can give the heading to the top and bottom of the table --> <caption align="top"> <!-- Here we have used the attribute that is style and we have colored the sentence to make it better depending on the web page--> </caption> <!-- Here th stands for the heading of the table that comes in the first row--> <!-- The text in this table header tag will appear as bold and is center aligned--> <thead> <tr> <!-- Here we have applied inline style to make it more attractive--> <th style="color: white; background: purple;"> Sun</th> <th style="color: white; background: purple;"> Mon</th> <th style="color: white; background: purple;"> Tue</th> <th style="color: white; background: purple;"> Wed</th> <th style="color: white; background: purple;"> Thu</th> <th style="color: white; background: purple;"> Fri</th> <th style="color: white; background: purple;"> Sat</th> </tr> </thead> <tbody> <tr> <td></td> <td></td> <td></td> <td></td> <td></td> <td>1</td> <td>2</td> </tr> <tr></tr> <tr> <td>3</td> <td>4</td> <td>5</td> <td>6</td> <td>7</td> <td>8</td> <td>9</td> </tr> <tr> <td>10</td> <td>11</td> <td>12</td> <td>13</td> <td>14</td> <td>15</td> <td>16</td> </tr> <tr> <td>17</td> <td>18</td> <td>19</td> <td>20</td> <td>21</td> <td>22</td> <td>23</td> </tr> <tr> <td>24</td> <td>25</td> <td>26</td> <td>27</td> <td>28</td> <td>29</td> <td>30</td> </tr> <tr> <td>31</td> <td>1</td> <td>2</td> <td>3</td> <td>4</td> <td>5</td> <td>6</td> </tr> </tbody> </table></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.
CSS-Misc
HTML-Misc
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
Form validation using jQuery
How to set space between the flexbox ?
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 ?
How to set input type date in dd-mm-yyyy format using HTML ?
Hide or show elements in HTML using display property
How to Insert Form Data into Database using PHP ?
REST API (Introduction) | [
{
"code": null,
"e": 25376,
"s": 25348,
"text": "\n27 Jan, 2021"
},
{
"code": null,
"e": 25658,
"s": 25376,
"text": "In this article, we will create a calendar using HTML, and CSS. First, we have to know a little about HTML. If someone does not know HTML and CSS, they will not be able to make the calendar better. The main focus of this article is on HTML tags and the way we are going to use CSS."
},
{
"code": null,
"e": 25916,
"s": 25658,
"text": "Approach: First we will be using the table tag, which will be used to create the structure of the calendar. This will give us an idea of how the calendar is created using HTML. Later we will apply some CSS property to make the design of the calendar better."
},
{
"code": null,
"e": 26089,
"s": 25916,
"text": "Creating Structure: In this section, we will create first the structure of the calendar by using the <table> tag. So this will help us to get the structure of the calendar."
},
{
"code": null,
"e": 26094,
"s": 26089,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <body> <!-- Here we are using attributes like cellspacing and cellpadding --> <!-- The purpose of the cellpadding is the space that a user want between the border of cell and its contents--> <!-- cellspacing is used to specify the space between the cell and its contents --> <h2 align=\"center\" style=\"color: orange;\"> January 2021 </h2> <br /> <table bgcolor=\"lightgrey\" align=\"center\" cellspacing=\"21\" cellpadding=\"21\"> <!-- The tr tag is used to enter rows in the table --> <!-- It is used to give the heading to the table. We can give the heading to the top and bottom of the table --> <caption align=\"top\"> <!-- Here we have used the attribute that is style and we have colored the sentence to make it better depending on the web page--> </caption> <!-- Here th stands for the heading of the table that comes in the first row--> <!-- The text in this table header tag will appear as bold and is center aligned--> <thead> <tr> <!-- Here we have applied inline style to make it more attractive--> <th>Sun</th> <th>Mon</th> <th>Tue</th> <th>Wed</th> <th>Thu</th> <th>Fri</th> <th>sat</th> </tr> </thead> <tbody> <tr> <td></td> <td></td> <td></td> <td></td> <td></td> <td>1</td> <td>2</td> </tr> <tr></tr> <tr> <td>3</td> <td>4</td> <td>5</td> <td>6</td> <td>7</td> <td>8</td> <td>9</td> </tr> <tr> <td>10</td> <td>11</td> <td>12</td> <td>13</td> <td>14</td> <td>15</td> <td>16</td> </tr> <tr> <td>17</td> <td>18</td> <td>19</td> <td>20</td> <td>21</td> <td>22</td> <td>23</td> </tr> <tr> <td>24</td> <td>25</td> <td>26</td> <td>27</td> <td>28</td> <td>29</td> <td>30</td> </tr> <tr> <td>31</td> <td>1</td> <td>2</td> <td>3</td> <td>4</td> <td>5</td> <td>6</td> </tr> </tbody> </table></body> </html>",
"e": 29051,
"s": 26094,
"text": null
},
{
"code": null,
"e": 29059,
"s": 29051,
"text": "Output:"
},
{
"code": null,
"e": 29538,
"s": 29059,
"text": "CSS Design and its attributes: We will use some CSS properties and attributes of the table tag to design the calendar. The attributes that we are going to use is the border and cellspacing and cellpadding. Here we have used an interesting property of CSS that is border-collapse. The purpose of the border-collapse is to make all the border to be collapsed into a single border. Here we have also used the inline style attribute to make the dates of February be little visible."
},
{
"code": null,
"e": 29548,
"s": 29538,
"text": "CSS code:"
},
{
"code": null,
"e": 29666,
"s": 29548,
"text": "table {\n border-collapse: collapse;\n background: white;\n color: black;\n}\nth, td { \n font-weight: bold;\n}\n"
},
{
"code": null,
"e": 29712,
"s": 29666,
"text": "Attributes that we will use in the table tag:"
},
{
"code": null,
"e": 29796,
"s": 29712,
"text": "<table bgcolor=\"lightgrey\" align=\"center\" \n cellspacing=\"21\" cellpadding=\"21\"> "
},
{
"code": null,
"e": 29855,
"s": 29796,
"text": "Final code: This is the combination of all the above codes"
},
{
"code": null,
"e": 29860,
"s": 29855,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <style> table { border-collapse: collapse; background: white; color: black; } th, td { font-weight: bold; } </style></head> <body> <!-- Here we are using attributes like cellspacing and cellpadding --> <!-- The purpose of the cellpadding is the space that a user want between the border of cell and its contents--> <!-- cellspacing is used to specify the space between the cell and its contents --> <h2 align=\"center\" style=\"color: orange;\"> January 2021 </h2> <br /> <table bgcolor=\"lightgrey\" align=\"center\" cellspacing=\"21\" cellpadding=\"21\"> <!-- The tr tag is used to enter rows in the table --> <!-- It is used to give the heading to the table. We can give the heading to the top and bottom of the table --> <caption align=\"top\"> <!-- Here we have used the attribute that is style and we have colored the sentence to make it better depending on the web page--> </caption> <!-- Here th stands for the heading of the table that comes in the first row--> <!-- The text in this table header tag will appear as bold and is center aligned--> <thead> <tr> <!-- Here we have applied inline style to make it more attractive--> <th style=\"color: white; background: purple;\"> Sun</th> <th style=\"color: white; background: purple;\"> Mon</th> <th style=\"color: white; background: purple;\"> Tue</th> <th style=\"color: white; background: purple;\"> Wed</th> <th style=\"color: white; background: purple;\"> Thu</th> <th style=\"color: white; background: purple;\"> Fri</th> <th style=\"color: white; background: purple;\"> Sat</th> </tr> </thead> <tbody> <tr> <td></td> <td></td> <td></td> <td></td> <td></td> <td>1</td> <td>2</td> </tr> <tr></tr> <tr> <td>3</td> <td>4</td> <td>5</td> <td>6</td> <td>7</td> <td>8</td> <td>9</td> </tr> <tr> <td>10</td> <td>11</td> <td>12</td> <td>13</td> <td>14</td> <td>15</td> <td>16</td> </tr> <tr> <td>17</td> <td>18</td> <td>19</td> <td>20</td> <td>21</td> <td>22</td> <td>23</td> </tr> <tr> <td>24</td> <td>25</td> <td>26</td> <td>27</td> <td>28</td> <td>29</td> <td>30</td> </tr> <tr> <td>31</td> <td>1</td> <td>2</td> <td>3</td> <td>4</td> <td>5</td> <td>6</td> </tr> </tbody> </table></body> </html>",
"e": 33458,
"s": 29860,
"text": null
},
{
"code": null,
"e": 33466,
"s": 33458,
"text": "Output:"
},
{
"code": null,
"e": 33603,
"s": 33466,
"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": 33612,
"s": 33603,
"text": "CSS-Misc"
},
{
"code": null,
"e": 33622,
"s": 33612,
"text": "HTML-Misc"
},
{
"code": null,
"e": 33626,
"s": 33622,
"text": "CSS"
},
{
"code": null,
"e": 33631,
"s": 33626,
"text": "HTML"
},
{
"code": null,
"e": 33648,
"s": 33631,
"text": "Web Technologies"
},
{
"code": null,
"e": 33653,
"s": 33648,
"text": "HTML"
},
{
"code": null,
"e": 33751,
"s": 33653,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 33788,
"s": 33751,
"text": "Design a web page using HTML and CSS"
},
{
"code": null,
"e": 33817,
"s": 33788,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 33856,
"s": 33817,
"text": "How to set space between the flexbox ?"
},
{
"code": null,
"e": 33898,
"s": 33856,
"text": "Search Bar using HTML, CSS and JavaScript"
},
{
"code": null,
"e": 33933,
"s": 33898,
"text": "How to style a checkbox using CSS?"
},
{
"code": null,
"e": 33993,
"s": 33933,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 34054,
"s": 33993,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
},
{
"code": null,
"e": 34107,
"s": 34054,
"text": "Hide or show elements in HTML using display property"
},
{
"code": null,
"e": 34157,
"s": 34107,
"text": "How to Insert Form Data into Database using PHP ?"
}
] |
Given n line segments, find if any two segments intersect - GeeksforGeeks | 01 Sep, 2021
We have discussed the problem to detect if two given line segments intersect or not. In this post, we extend the problem. Here we are given n line segments and we need to find out if any two line segments intersect or not. Naive Algorithm A naive solution to solve this problem is to check every pair of lines and check if the pair intersects or not. We can check two line segments in O(1) time. Therefore, this approach takes O(n2). Sweep Line Algorithm: We can solve this problem in O(nLogn) time using Sweep Line Algorithm. The algorithm first sorts the end points along the x axis from left to right, then it passes a vertical line through all points from left to right and checks for intersections. Following are detailed steps. 1) Let there be n given lines. There must be 2n end points to represent the n lines. Sort all points according to x coordinates. While sorting maintain a flag to indicate whether this point is left point of its line or right point. 2) Start from the leftmost point. Do following for every point .....a) If the current point is a left point of its line segment, check for intersection of its line segment with the segments just above and below it. And add its line to active line segments (line segments for which left end point is seen, but right end point is not seen yet). Note that we consider only those neighbors which are still active. ....b) If the current point is a right point, remove its line segment from active list and check whether its two active neighbors (points just above and below) intersect with each other. The step 2 is like passing a vertical line from all points starting from the leftmost point to the rightmost point. That is why this algorithm is called Sweep Line Algorithm. The Sweep Line technique is useful in many other geometric algorithms like calculating the 2D Voronoi diagram What data structures should be used for efficient implementation? In step 2, we need to store all active line segments. We need to do following operations efficiently: a) Insert a new line segment b) Delete a line segment c) Find predecessor and successor according to y coordinate values The obvious choice for above operations is Self-Balancing Binary Search Tree like AVL Tree, Red Black Tree. With a Self-Balancing BST, we can do all of the above operations in O(Logn) time. Also, in step 1, instead of sorting, we can use min heap data structure. Building a min heap takes O(n) time and every extract min operation takes O(Logn) time (See this). PseudoCode: The following pseudocode doesn’t use heap. It simply sort the array.
sweepLineIntersection(Points[0..2n-1]):
1. Sort Points[] from left to right (according to x coordinate)
2. Create an empty Self-Balancing BST T. It will contain
all active line Segments ordered by y coordinate.
// Process all 2n points
3. for i = 0 to 2n-1
// If this point is left end of its line
if (Points[i].isLeft)
T.insert(Points[i].line()) // Insert into the tree
// Check if this points intersects with its predecessor and successor
if ( doIntersect(Points[i].line(), T.pred(Points[i].line()) )
return true
if ( doIntersect(Points[i].line(), T.succ(Points[i].line()) )
return true
else // If it's a right end of its line
// Check if its predecessor and successor intersect with each other
if ( doIntersect(T.pred(Points[i].line(), T.succ(Points[i].line()))
return true
T.delete(Points[i].line()) // Delete from tree
4. return False
Example: Let us consider the following example taken from here. There are 5 line segments 1, 2, 3, 4 and 5. The dotted green lines show sweep lines.
Following are steps followed by the algorithm. All points from left to right are processed one by one. We maintain a self-balancing binary search tree.
Left end point of line segment 1 is processed: 1 is inserted into the Tree. The tree contains 1. No intersection.
Left end point of line segment 2 is processed: Intersection of 1 and 2 is checked. 2 is inserted into the Tree. Intersection of 1&2 Found (“Note that the above pseudocode returns at this point”). We can continue from here to report all intersection points. The tree contains 1, 2.
Left end point of line segment 3 is processed: Intersection of 3 with 1 is checked. No intersection. 3 is inserted into the Tree. The tree contains 2, 1, 3.
Right end point of line segment 1 is processed: 1 is deleted from the Tree. Intersection of 2 and 3 is checked. Intersection of 2 and 3 is reported. The tree contains 2, 3.
Left end point of line segment 4 is processed: Intersections of line 4 with lines 2 and 3 are checked. No intersection. 4 is inserted into the Tree. The tree contains 2, 4, 3.
Left end point of line segment 5 is processed: Intersection of 5 with 3 is checked. No intersection. 5 is inserted into the Tree. The tree contains 2, 4, 3, 5.
Right end point of line segment 5 is processed: 5 is deleted from the Tree. The tree contains 2, 4, 3.
Right end point of line segment 4 is processed: 4 is deleted from the Tree. The tree contains 2, 4, 3. Intersection of 2 with 3 is checked. Intersection of 2 with 3 is reported (Note that the intersection of 2 and 3 is reported again. We can add some logic to check for duplicates ). The tree contains 2, 3.
Right end point of line segment 2 and 3 are processed: Both are deleted from tree and tree becomes empty.
C++14
#include <bits/stdc++.h>using namespace std; // A point in 2D planestruct Point{ int x, y;}; // A line segment with left as Point// with smaller x value and right with// larger x value.struct Segment{ Point left, right;}; // An event for sweep line algorithm// An event has a point, the position// of point (whether left or right) and// index of point in the original input// array of segments.struct Event { int x, y; bool isLeft; int index; Event(int x, int y, bool l, int i) : x(x), y(y), isLeft(l), index(i) {} // This is for maintaining the order in set. bool operator<(const Event& e) const { if(y==e.y)return x<e.x; return y < e.y; }}; // Given three collinear points p, q, r, the function checks if// point q lies on line segment 'pr'bool onSegment(Point p, Point q, Point r){ if (q.x <= max(p.x, r.x) && q.x >= min(p.x, r.x) && q.y <= max(p.y, r.y) && q.y >= min(p.y, r.y)) return true; return false;} // To find orientation of ordered triplet (p, q, r).// The function returns following values// 0 --> p, q and r are collinear// 1 --> Clockwise// 2 --> Counterclockwiseint orientation(Point p, Point q, Point r){ // See https://www.geeksforgeeks.org/orientation-3-ordered-points/ // for details of below formula. int val = (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y); if (val == 0) return 0; // collinear return (val > 0)? 1: 2; // clock or counterclock wise} // The main function that returns true if line segment 'p1q1'// and 'p2q2' intersect.bool doIntersect(Segment s1, Segment s2){ Point p1 = s1.left, q1 = s1.right, p2 = s2.left, q2 = s2.right; // Find the four orientations needed for general and // special cases int o1 = orientation(p1, q1, p2); int o2 = orientation(p1, q1, q2); int o3 = orientation(p2, q2, p1); int o4 = orientation(p2, q2, q1); // General case if (o1 != o2 && o3 != o4) return true; // Special Cases // p1, q1 and p2 are collinear and p2 lies on segment p1q1 if (o1 == 0 && onSegment(p1, p2, q1)) return true; // p1, q1 and q2 are collinear and q2 lies on segment p1q1 if (o2 == 0 && onSegment(p1, q2, q1)) return true; // p2, q2 and p1 are collinear and p1 lies on segment p2q2 if (o3 == 0 && onSegment(p2, p1, q2)) return true; // p2, q2 and q1 are collinear and q1 lies on segment p2q2 if (o4 == 0 && onSegment(p2, q1, q2)) return true; return false; // Doesn't fall in any of the above cases} // Find predecessor of iterator in s. set<Event>::iterator pred(set<Event> &s, set<Event>::iterator it) { return it == s.begin() ? s.end() : --it;} // Find successor of iterator in s.set<Event>::iterator succ(set<Event> &s, set<Event>::iterator it) { return ++it;} // Returns true if any two lines intersect.int isIntersect(Segment arr[], int n){ unordered_map<string,int> mp; // to note the pair for which intersection is checked already // Pushing all points to a vector of events vector<Event> e; for (int i = 0; i < n; ++i) { e.push_back(Event(arr[i].left.x, arr[i].left.y, true, i)); e.push_back(Event(arr[i].right.x, arr[i].right.y, false, i)); } // Sorting all events according to x coordinate. sort(e.begin(), e.end(), [](Event &e1, Event &e2) {return e1.x < e2.x;}); // For storing active segments. set<Event> s; int ans=0; // Traversing through sorted points for (int i=0; i<2*n; i++) { Event curr = e[i]; int index = curr.index; // If current point is left of its segment if (curr.isLeft) { // Get above and below points auto next = s.lower_bound(curr); auto prev = pred(s, next); // Check if current point intersects with // any of its adjacent bool flag=false; if (next != s.end() && doIntersect(arr[next->index], arr[index])){ string s=to_string(next->index+1)+" "+to_string(index+1); if(mp.count(s)==0){mp[s]++;ans++;} //if not already checked we can increase count in map } if (prev != s.end() && doIntersect(arr[prev->index], arr[index])){ string s=to_string(prev->index+1)+" "+to_string(index+1); if(mp.count(s)==0){mp[s]++;ans++;} //if not already checked we can increase count in map } // if same line segment is there then decrease answer as it got increased twice if(prev != s.end() && next != s.end() && next->index==prev->index)ans--; // Insert current point (or event) s.insert(curr); } // If current point is right of its segment else { // Find the iterator auto it=s.find(Event(arr[index].left.x, arr[index].left.y, true, index)); // Find above and below points auto next = succ(s, it); auto prev = pred(s, it); // If above and below point intersect if (next != s.end() && prev != s.end()) { string s=to_string(next->index+1)+" "+to_string(prev->index+1); string s1=to_string(prev->index+1)+" "+to_string(next->index+1); if (mp.count(s)==0&&mp.count(s1)==0&&doIntersect(arr[prev->index], arr[next->index])) ans++; mp[s]++; } // Remove current segment s.erase(it); } } //print pair of lines having intersection for(auto &pr:mp){ cout<<pr.first<<"\n"; } return ans;} // Driver codeint main() { Segment arr[] = { {{1, 5}, {4, 5}}, {{2, 5}, {10, 1}},{{3, 2}, {10, 3}},{{6, 4}, {9, 4}},{{7, 1}, {8, 1}}}; int n = sizeof(arr)/sizeof(arr[0]); cout<<isIntersect(arr, n); return 0;}
Output:
0
Time Complexity: The first step is sorting which takes O(nLogn) time. The second step process 2n points and for processing every point, it takes O(Logn) time. Therefore, overall time complexity is O(nLogn) References: http://www.cs.uiuc.edu/~jeffe/teaching/373/notes/x06-sweepline.pdf http://courses.csail.mit.edu/6.006/spring11/lectures/lec24.pdf http://www.youtube.com/watch?v=dePDHVovJlE http://www.eecs.wsu.edu/~cook/aa/lectures/l25/node10.html Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Sahil_Chhabra
anjitkumariitbhu
sagar0719kumar
Geometric-Lines
Geometric
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)
Polygon Clipping | Sutherland–Hodgman Algorithm
Program To Check whether a Triangle is Equilateral, Isosceles or Scalene
Check if two given circles touch or intersect each other
Window to Viewport Transformation in Computer Graphics with Implementation
Sum of Manhattan distances between all pairs of points
Optimum location of point to minimize total distance | [
{
"code": null,
"e": 34516,
"s": 34488,
"text": "\n01 Sep, 2021"
},
{
"code": null,
"e": 37099,
"s": 34516,
"text": "We have discussed the problem to detect if two given line segments intersect or not. In this post, we extend the problem. Here we are given n line segments and we need to find out if any two line segments intersect or not. Naive Algorithm A naive solution to solve this problem is to check every pair of lines and check if the pair intersects or not. We can check two line segments in O(1) time. Therefore, this approach takes O(n2). Sweep Line Algorithm: We can solve this problem in O(nLogn) time using Sweep Line Algorithm. The algorithm first sorts the end points along the x axis from left to right, then it passes a vertical line through all points from left to right and checks for intersections. Following are detailed steps. 1) Let there be n given lines. There must be 2n end points to represent the n lines. Sort all points according to x coordinates. While sorting maintain a flag to indicate whether this point is left point of its line or right point. 2) Start from the leftmost point. Do following for every point .....a) If the current point is a left point of its line segment, check for intersection of its line segment with the segments just above and below it. And add its line to active line segments (line segments for which left end point is seen, but right end point is not seen yet). Note that we consider only those neighbors which are still active. ....b) If the current point is a right point, remove its line segment from active list and check whether its two active neighbors (points just above and below) intersect with each other. The step 2 is like passing a vertical line from all points starting from the leftmost point to the rightmost point. That is why this algorithm is called Sweep Line Algorithm. The Sweep Line technique is useful in many other geometric algorithms like calculating the 2D Voronoi diagram What data structures should be used for efficient implementation? In step 2, we need to store all active line segments. We need to do following operations efficiently: a) Insert a new line segment b) Delete a line segment c) Find predecessor and successor according to y coordinate values The obvious choice for above operations is Self-Balancing Binary Search Tree like AVL Tree, Red Black Tree. With a Self-Balancing BST, we can do all of the above operations in O(Logn) time. Also, in step 1, instead of sorting, we can use min heap data structure. Building a min heap takes O(n) time and every extract min operation takes O(Logn) time (See this). PseudoCode: The following pseudocode doesn’t use heap. It simply sort the array. "
},
{
"code": null,
"e": 38043,
"s": 37099,
"text": "sweepLineIntersection(Points[0..2n-1]):\n1. Sort Points[] from left to right (according to x coordinate)\n\n2. Create an empty Self-Balancing BST T. It will contain \n all active line Segments ordered by y coordinate.\n\n// Process all 2n points \n3. for i = 0 to 2n-1\n\n // If this point is left end of its line \n if (Points[i].isLeft) \n T.insert(Points[i].line()) // Insert into the tree\n\n // Check if this points intersects with its predecessor and successor\n if ( doIntersect(Points[i].line(), T.pred(Points[i].line()) )\n return true\n if ( doIntersect(Points[i].line(), T.succ(Points[i].line()) )\n return true\n\n else // If it's a right end of its line\n // Check if its predecessor and successor intersect with each other\n if ( doIntersect(T.pred(Points[i].line(), T.succ(Points[i].line()))\n return true\n T.delete(Points[i].line()) // Delete from tree\n\n4. return False"
},
{
"code": null,
"e": 38196,
"s": 38043,
"text": "Example: Let us consider the following example taken from here. There are 5 line segments 1, 2, 3, 4 and 5. The dotted green lines show sweep lines. "
},
{
"code": null,
"e": 38350,
"s": 38196,
"text": "Following are steps followed by the algorithm. All points from left to right are processed one by one. We maintain a self-balancing binary search tree. "
},
{
"code": null,
"e": 38467,
"s": 38350,
"text": "Left end point of line segment 1 is processed: 1 is inserted into the Tree. The tree contains 1. No intersection. "
},
{
"code": null,
"e": 38751,
"s": 38467,
"text": "Left end point of line segment 2 is processed: Intersection of 1 and 2 is checked. 2 is inserted into the Tree. Intersection of 1&2 Found (“Note that the above pseudocode returns at this point”). We can continue from here to report all intersection points. The tree contains 1, 2. "
},
{
"code": null,
"e": 38913,
"s": 38751,
"text": "Left end point of line segment 3 is processed: Intersection of 3 with 1 is checked. No intersection. 3 is inserted into the Tree. The tree contains 2, 1, 3. "
},
{
"code": null,
"e": 39091,
"s": 38913,
"text": "Right end point of line segment 1 is processed: 1 is deleted from the Tree. Intersection of 2 and 3 is checked. Intersection of 2 and 3 is reported. The tree contains 2, 3. "
},
{
"code": null,
"e": 39273,
"s": 39091,
"text": "Left end point of line segment 4 is processed: Intersections of line 4 with lines 2 and 3 are checked. No intersection. 4 is inserted into the Tree. The tree contains 2, 4, 3. "
},
{
"code": null,
"e": 39440,
"s": 39273,
"text": "Left end point of line segment 5 is processed: Intersection of 5 with 3 is checked. No intersection. 5 is inserted into the Tree. The tree contains 2, 4, 3, 5. "
},
{
"code": null,
"e": 39547,
"s": 39440,
"text": "Right end point of line segment 5 is processed: 5 is deleted from the Tree. The tree contains 2, 4, 3. "
},
{
"code": null,
"e": 39862,
"s": 39547,
"text": "Right end point of line segment 4 is processed: 4 is deleted from the Tree. The tree contains 2, 4, 3. Intersection of 2 with 3 is checked. Intersection of 2 with 3 is reported (Note that the intersection of 2 and 3 is reported again. We can add some logic to check for duplicates ). The tree contains 2, 3."
},
{
"code": null,
"e": 39972,
"s": 39862,
"text": "Right end point of line segment 2 and 3 are processed: Both are deleted from tree and tree becomes empty. "
},
{
"code": null,
"e": 39980,
"s": 39974,
"text": "C++14"
},
{
"code": "#include <bits/stdc++.h>using namespace std; // A point in 2D planestruct Point{ int x, y;}; // A line segment with left as Point// with smaller x value and right with// larger x value.struct Segment{ Point left, right;}; // An event for sweep line algorithm// An event has a point, the position// of point (whether left or right) and// index of point in the original input// array of segments.struct Event { int x, y; bool isLeft; int index; Event(int x, int y, bool l, int i) : x(x), y(y), isLeft(l), index(i) {} // This is for maintaining the order in set. bool operator<(const Event& e) const { if(y==e.y)return x<e.x; return y < e.y; }}; // Given three collinear points p, q, r, the function checks if// point q lies on line segment 'pr'bool onSegment(Point p, Point q, Point r){ if (q.x <= max(p.x, r.x) && q.x >= min(p.x, r.x) && q.y <= max(p.y, r.y) && q.y >= min(p.y, r.y)) return true; return false;} // To find orientation of ordered triplet (p, q, r).// The function returns following values// 0 --> p, q and r are collinear// 1 --> Clockwise// 2 --> Counterclockwiseint orientation(Point p, Point q, Point r){ // See https://www.geeksforgeeks.org/orientation-3-ordered-points/ // for details of below formula. int val = (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y); if (val == 0) return 0; // collinear return (val > 0)? 1: 2; // clock or counterclock wise} // The main function that returns true if line segment 'p1q1'// and 'p2q2' intersect.bool doIntersect(Segment s1, Segment s2){ Point p1 = s1.left, q1 = s1.right, p2 = s2.left, q2 = s2.right; // Find the four orientations needed for general and // special cases int o1 = orientation(p1, q1, p2); int o2 = orientation(p1, q1, q2); int o3 = orientation(p2, q2, p1); int o4 = orientation(p2, q2, q1); // General case if (o1 != o2 && o3 != o4) return true; // Special Cases // p1, q1 and p2 are collinear and p2 lies on segment p1q1 if (o1 == 0 && onSegment(p1, p2, q1)) return true; // p1, q1 and q2 are collinear and q2 lies on segment p1q1 if (o2 == 0 && onSegment(p1, q2, q1)) return true; // p2, q2 and p1 are collinear and p1 lies on segment p2q2 if (o3 == 0 && onSegment(p2, p1, q2)) return true; // p2, q2 and q1 are collinear and q1 lies on segment p2q2 if (o4 == 0 && onSegment(p2, q1, q2)) return true; return false; // Doesn't fall in any of the above cases} // Find predecessor of iterator in s. set<Event>::iterator pred(set<Event> &s, set<Event>::iterator it) { return it == s.begin() ? s.end() : --it;} // Find successor of iterator in s.set<Event>::iterator succ(set<Event> &s, set<Event>::iterator it) { return ++it;} // Returns true if any two lines intersect.int isIntersect(Segment arr[], int n){ unordered_map<string,int> mp; // to note the pair for which intersection is checked already // Pushing all points to a vector of events vector<Event> e; for (int i = 0; i < n; ++i) { e.push_back(Event(arr[i].left.x, arr[i].left.y, true, i)); e.push_back(Event(arr[i].right.x, arr[i].right.y, false, i)); } // Sorting all events according to x coordinate. sort(e.begin(), e.end(), [](Event &e1, Event &e2) {return e1.x < e2.x;}); // For storing active segments. set<Event> s; int ans=0; // Traversing through sorted points for (int i=0; i<2*n; i++) { Event curr = e[i]; int index = curr.index; // If current point is left of its segment if (curr.isLeft) { // Get above and below points auto next = s.lower_bound(curr); auto prev = pred(s, next); // Check if current point intersects with // any of its adjacent bool flag=false; if (next != s.end() && doIntersect(arr[next->index], arr[index])){ string s=to_string(next->index+1)+\" \"+to_string(index+1); if(mp.count(s)==0){mp[s]++;ans++;} //if not already checked we can increase count in map } if (prev != s.end() && doIntersect(arr[prev->index], arr[index])){ string s=to_string(prev->index+1)+\" \"+to_string(index+1); if(mp.count(s)==0){mp[s]++;ans++;} //if not already checked we can increase count in map } // if same line segment is there then decrease answer as it got increased twice if(prev != s.end() && next != s.end() && next->index==prev->index)ans--; // Insert current point (or event) s.insert(curr); } // If current point is right of its segment else { // Find the iterator auto it=s.find(Event(arr[index].left.x, arr[index].left.y, true, index)); // Find above and below points auto next = succ(s, it); auto prev = pred(s, it); // If above and below point intersect if (next != s.end() && prev != s.end()) { string s=to_string(next->index+1)+\" \"+to_string(prev->index+1); string s1=to_string(prev->index+1)+\" \"+to_string(next->index+1); if (mp.count(s)==0&&mp.count(s1)==0&&doIntersect(arr[prev->index], arr[next->index])) ans++; mp[s]++; } // Remove current segment s.erase(it); } } //print pair of lines having intersection for(auto &pr:mp){ cout<<pr.first<<\"\\n\"; } return ans;} // Driver codeint main() { Segment arr[] = { {{1, 5}, {4, 5}}, {{2, 5}, {10, 1}},{{3, 2}, {10, 3}},{{6, 4}, {9, 4}},{{7, 1}, {8, 1}}}; int n = sizeof(arr)/sizeof(arr[0]); cout<<isIntersect(arr, n); return 0;}",
"e": 45802,
"s": 39980,
"text": null
},
{
"code": null,
"e": 45813,
"s": 45802,
"text": " Output: "
},
{
"code": null,
"e": 45815,
"s": 45813,
"text": "0"
},
{
"code": null,
"e": 46392,
"s": 45817,
"text": "Time Complexity: The first step is sorting which takes O(nLogn) time. The second step process 2n points and for processing every point, it takes O(Logn) time. Therefore, overall time complexity is O(nLogn) References: http://www.cs.uiuc.edu/~jeffe/teaching/373/notes/x06-sweepline.pdf http://courses.csail.mit.edu/6.006/spring11/lectures/lec24.pdf http://www.youtube.com/watch?v=dePDHVovJlE http://www.eecs.wsu.edu/~cook/aa/lectures/l25/node10.html Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 46408,
"s": 46394,
"text": "Sahil_Chhabra"
},
{
"code": null,
"e": 46425,
"s": 46408,
"text": "anjitkumariitbhu"
},
{
"code": null,
"e": 46440,
"s": 46425,
"text": "sagar0719kumar"
},
{
"code": null,
"e": 46456,
"s": 46440,
"text": "Geometric-Lines"
},
{
"code": null,
"e": 46466,
"s": 46456,
"text": "Geometric"
},
{
"code": null,
"e": 46476,
"s": 46466,
"text": "Geometric"
},
{
"code": null,
"e": 46574,
"s": 46476,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 46623,
"s": 46574,
"text": "Program for distance between two points on earth"
},
{
"code": null,
"e": 46654,
"s": 46623,
"text": "Find if two rectangles overlap"
},
{
"code": null,
"e": 46712,
"s": 46654,
"text": "Check whether triangle is valid or not if sides are given"
},
{
"code": null,
"e": 46763,
"s": 46712,
"text": "Line Clipping | Set 1 (Cohen–Sutherland Algorithm)"
},
{
"code": null,
"e": 46811,
"s": 46763,
"text": "Polygon Clipping | Sutherland–Hodgman Algorithm"
},
{
"code": null,
"e": 46884,
"s": 46811,
"text": "Program To Check whether a Triangle is Equilateral, Isosceles or Scalene"
},
{
"code": null,
"e": 46941,
"s": 46884,
"text": "Check if two given circles touch or intersect each other"
},
{
"code": null,
"e": 47016,
"s": 46941,
"text": "Window to Viewport Transformation in Computer Graphics with Implementation"
},
{
"code": null,
"e": 47071,
"s": 47016,
"text": "Sum of Manhattan distances between all pairs of points"
}
] |
String split(String regex, int limit) Method | This method has two variants and splits this string around matches of the given regular expression.
Here is the syntax of this method −
public String[] split(String regex, int limit)
Here is the detail of parameters −
regex − the delimiting regular expression.
regex − the delimiting regular expression.
limit − the result threshold, which means how many strings to be returned.
limit − the result threshold, which means how many strings to be returned.
It returns the array of strings computed by splitting this string around matches of the given regular expression.
It returns the array of strings computed by splitting this string around matches of the given regular expression.
import java.io.*;
public class Test {
public static void main(String args[]) {
String Str = new String("Welcome-to-Tutorialspoint.com");
System.out.println("Return Value :" );
for (String retval: Str.split("-", 2)) {
System.out.println(retval);
}
System.out.println("");
System.out.println("Return Value :" );
for (String retval: Str.split("-", 3)) {
System.out.println(retval);
}
System.out.println("");
System.out.println("Return Value :" );
for (String retval: Str.split("-", 0)) {
System.out.println(retval);
}
System.out.println("");
}
}
This will produce the following result −
Return Value :
Welcome
to-Tutorialspoint.com
Return Value :
Welcome
to
Tutorialspoint.com
Return Value:
Welcome
to
Tutorialspoint.com
16 Lectures
2 hours
Malhar Lathkar
19 Lectures
5 hours
Malhar Lathkar
25 Lectures
2.5 hours
Anadi Sharma
126 Lectures
7 hours
Tushar Kale
119 Lectures
17.5 hours
Monica Mittal
76 Lectures
7 hours
Arnab Chakraborty
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2477,
"s": 2377,
"text": "This method has two variants and splits this string around matches of the given regular expression."
},
{
"code": null,
"e": 2513,
"s": 2477,
"text": "Here is the syntax of this method −"
},
{
"code": null,
"e": 2561,
"s": 2513,
"text": "public String[] split(String regex, int limit)\n"
},
{
"code": null,
"e": 2596,
"s": 2561,
"text": "Here is the detail of parameters −"
},
{
"code": null,
"e": 2639,
"s": 2596,
"text": "regex − the delimiting regular expression."
},
{
"code": null,
"e": 2682,
"s": 2639,
"text": "regex − the delimiting regular expression."
},
{
"code": null,
"e": 2757,
"s": 2682,
"text": "limit − the result threshold, which means how many strings to be returned."
},
{
"code": null,
"e": 2832,
"s": 2757,
"text": "limit − the result threshold, which means how many strings to be returned."
},
{
"code": null,
"e": 2946,
"s": 2832,
"text": "It returns the array of strings computed by splitting this string around matches of the given regular expression."
},
{
"code": null,
"e": 3060,
"s": 2946,
"text": "It returns the array of strings computed by splitting this string around matches of the given regular expression."
},
{
"code": null,
"e": 3736,
"s": 3060,
"text": "import java.io.*;\npublic class Test {\n\n public static void main(String args[]) {\n String Str = new String(\"Welcome-to-Tutorialspoint.com\");\n System.out.println(\"Return Value :\" );\n \n for (String retval: Str.split(\"-\", 2)) {\n System.out.println(retval);\n }\n System.out.println(\"\");\n System.out.println(\"Return Value :\" );\n \n for (String retval: Str.split(\"-\", 3)) {\n System.out.println(retval);\n }\n System.out.println(\"\");\n System.out.println(\"Return Value :\" );\n \n for (String retval: Str.split(\"-\", 0)) {\n System.out.println(retval);\n }\n System.out.println(\"\");\n }\n}"
},
{
"code": null,
"e": 3777,
"s": 3736,
"text": "This will produce the following result −"
},
{
"code": null,
"e": 3914,
"s": 3777,
"text": "Return Value :\nWelcome\nto-Tutorialspoint.com\n\nReturn Value :\nWelcome\nto\nTutorialspoint.com\n\nReturn Value:\nWelcome\nto\nTutorialspoint.com\n"
},
{
"code": null,
"e": 3947,
"s": 3914,
"text": "\n 16 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 3963,
"s": 3947,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 3996,
"s": 3963,
"text": "\n 19 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 4012,
"s": 3996,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 4047,
"s": 4012,
"text": "\n 25 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 4061,
"s": 4047,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 4095,
"s": 4061,
"text": "\n 126 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 4109,
"s": 4095,
"text": " Tushar Kale"
},
{
"code": null,
"e": 4146,
"s": 4109,
"text": "\n 119 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 4161,
"s": 4146,
"text": " Monica Mittal"
},
{
"code": null,
"e": 4194,
"s": 4161,
"text": "\n 76 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 4213,
"s": 4194,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 4220,
"s": 4213,
"text": " Print"
},
{
"code": null,
"e": 4231,
"s": 4220,
"text": " Add Notes"
}
] |
Achieving world-class results using the new fastai library | by Aayush Agrawal | Towards Data Science | I am currently doing a fast.ai Live MOOC called “Practical Deep learning for Coders” which will be publically available in January 2019 on fast.ai website. The following code is based on lesson 1 from that course. I will be using fastai V1 library which sits on top of Pytorch 1.0. The fastai library provides many useful functions that enable us to quickly and easily build neural networks and train our models. I am writing this blog as a part of experimenting the course example on a dataset which is different in structure and complexity and to show how easy it is to use fastai library.
In the below example you will see how ridiculously easy is to do transfer learning and achieve world-class results on PlantVintage Dataset. PlantVintage data have images of plant leaves which consist of 38 disease classes which are commonly found on crops and one background class from Stanford’s open dataset of background images — DAGS. I downloaded data from links given on this Github Repo. I am particularly interested in this example because at the time I am writing this blog I work for an organization which helps farmers grow their business by providing products and tech solutions for better farm management. Let’s get started!
PS: This blog is also released as a jupyter notebook on my GitHub profile.
It’s a standard practice to start the notebook with the following three lines; they ensure that any edits to libraries you make are reloaded here automatically, and also that any charts or images displayed are shown in this notebook.
%reload_ext autoreload%autoreload 2%matplotlib inline
Let’s import fastai library and define our batch_size parameter to 64. Usually, image databases are huge, so we need to feed these images into a GPU using batches, batch size 64 means that we will feed 64 images at once to update parameters of our deep learning model. If you are running out of memory because of smaller GPU RAM, you can reduce batch size to 32 or 16.
from fastai import *from fastai.vision import *bs =64
The first thing we do when we approach a problem is to take a look at the data. We always need to understand very well what the problem is and what the data looks like before we can figure out how to solve it. Taking a look at the data means understanding how the data directories are structured, what the labels are and what some sample images look like. Our data is already split in train and validation folder, and inside each subdirectory, our folder name represents the class name of all the images present within that subfolder. Fortunately, the fastai library has a handy function made exactly for this, ImageDataBunch.from_folder gets the label names from the folder name automatically. fastai library has awesome documentation to navigate through their library functions with live examples on how to use them. Once the data is loaded, we can also normalize the data by using .normalize to ImageNet parameters.
## Declaring path of datasetpath_img = Path('/home/jupyter/fastai_v3_experimentation/data/PlantVillage/')## Loading data data = ImageDataBunch.from_folder(path=path_img, train='train', valid='valid', ds_tfms=get_transforms(),size=224, bs=bs, check_ext=False)## Normalizing data based on Image net parametersdata.normalize(imagenet_stats)
To look at a random sample of images, we can use .show_batch() function ImageDataBunch class. As we can see below, we have some cases of diseases leaf on different crops plus some background noise images from DAGS dataset which will act as noise.
data.show_batch(rows=3, figsize=(10,8))
Let’s print all the data classes present in the database. In total, we have images in 39 classes as mentioned above in the motivation section.
print(data.classes)len(data.classes),data.c
Now we will start training our model. We will use a convolutional neural network backbone ResNet 50 and a fully connected head with a single hidden layer as a classifier. You can also read the ResNet paper if you want to understand all the architectural detail. To create the transfer learning model we will need to use function create_cnn from Learner class and feed a pre-trained model from models class.
## To create a ResNET 50 with pretrained weightslearn = create_cnn(data, models.resnet50, metrics=error_rate)
The ResNet50 model created by create_cnn function have initial layers frozen, and we are just going to learn weights of the last fully connected layers.
learn.fit_one_cycle(5)
As we can see above by just running five epochs with the default setting our accuracy for this fine-grained classification task is around ~99.64% on the validation dataset. Let’s save the model as we are going to fine tune it later. If you want to know how good this result is, it already beats the shallow learning(only training last layer) benchmark of 96.53% from this Github Page.
learn.save('plant_vintage_stage1')
FastAI library also provides functions to explore results faster and find if our model is learning what it is supposed to learn. We will first see which were the categories that the model most confused with one another. We will try to see if what the model predicted was reasonable or not using ClassificationInterpretation class.
interp = ClassificationInterpretation.from_learner(learn)interp.plot_top_losses(4, figsize=(20,25))
In this case, the model is getting confused in detecting Northern Leaf blight from Gray leaf spots on Corn plant and early/late blight in tomato leaves which visually looks pretty similar. This is an indicator that our classifier is working correctly. Furthermore, when we plot the confusion matrix, we can see that most of the things are classified correctly, and it’s almost a near perfect model.
interp.plot_confusion_matrix(figsize=(20,20), dpi=60)
So until now, we have only been training the last classification layers, but what if we want to optimize earlier layers too. In transfer learning, tweaking initial layers should be done with caution, and the learning rate should be kept pretty low. FastAI library provides a function to see what will be the ideal learning rate to train upon, so let’s plot it. The lr_find function runs the model for a subset of data at multiple learning rate to determine which learning rate would be best.
learn.lr_find()learn.recorder.plot()
It looks like we should keep our learning rate lower than 10e-4. We can use slice function to logarithmically distribute learning rate between 10e-6 to 10e-4 for different layers in the network. Keeping the lowest learning rate for the initial layers and increasing it for later layers. Let’s unfreeze all the layers so that we can train the entire model using unfreeze() function.
learn.unfreeze()learn.fit_one_cycle(2, max_lr=slice(1e-7,1e-5))
As we can see by training all the layers, we improved our accuracy to 99.7% which is comparable to 99.76% on the Github benchmark using Inception-v3 model.
Fast.ai is an excellent initiative by Jeremy Howard and his team, and I believe fastai library can genuinely achieve the motive of democratizing deep learning to everyone by making building deep learning models super simple.
I hope you enjoyed reading, and feel free to use my code to try it out for your purposes. Also, if there is any feedback on code or just the blog post, feel free to reach out on LinkedIn or email me at [email protected]. | [
{
"code": null,
"e": 764,
"s": 172,
"text": "I am currently doing a fast.ai Live MOOC called “Practical Deep learning for Coders” which will be publically available in January 2019 on fast.ai website. The following code is based on lesson 1 from that course. I will be using fastai V1 library which sits on top of Pytorch 1.0. The fastai library provides many useful functions that enable us to quickly and easily build neural networks and train our models. I am writing this blog as a part of experimenting the course example on a dataset which is different in structure and complexity and to show how easy it is to use fastai library."
},
{
"code": null,
"e": 1402,
"s": 764,
"text": "In the below example you will see how ridiculously easy is to do transfer learning and achieve world-class results on PlantVintage Dataset. PlantVintage data have images of plant leaves which consist of 38 disease classes which are commonly found on crops and one background class from Stanford’s open dataset of background images — DAGS. I downloaded data from links given on this Github Repo. I am particularly interested in this example because at the time I am writing this blog I work for an organization which helps farmers grow their business by providing products and tech solutions for better farm management. Let’s get started!"
},
{
"code": null,
"e": 1477,
"s": 1402,
"text": "PS: This blog is also released as a jupyter notebook on my GitHub profile."
},
{
"code": null,
"e": 1711,
"s": 1477,
"text": "It’s a standard practice to start the notebook with the following three lines; they ensure that any edits to libraries you make are reloaded here automatically, and also that any charts or images displayed are shown in this notebook."
},
{
"code": null,
"e": 1765,
"s": 1711,
"text": "%reload_ext autoreload%autoreload 2%matplotlib inline"
},
{
"code": null,
"e": 2134,
"s": 1765,
"text": "Let’s import fastai library and define our batch_size parameter to 64. Usually, image databases are huge, so we need to feed these images into a GPU using batches, batch size 64 means that we will feed 64 images at once to update parameters of our deep learning model. If you are running out of memory because of smaller GPU RAM, you can reduce batch size to 32 or 16."
},
{
"code": null,
"e": 2188,
"s": 2134,
"text": "from fastai import *from fastai.vision import *bs =64"
},
{
"code": null,
"e": 3107,
"s": 2188,
"text": "The first thing we do when we approach a problem is to take a look at the data. We always need to understand very well what the problem is and what the data looks like before we can figure out how to solve it. Taking a look at the data means understanding how the data directories are structured, what the labels are and what some sample images look like. Our data is already split in train and validation folder, and inside each subdirectory, our folder name represents the class name of all the images present within that subfolder. Fortunately, the fastai library has a handy function made exactly for this, ImageDataBunch.from_folder gets the label names from the folder name automatically. fastai library has awesome documentation to navigate through their library functions with live examples on how to use them. Once the data is loaded, we can also normalize the data by using .normalize to ImageNet parameters."
},
{
"code": null,
"e": 3445,
"s": 3107,
"text": "## Declaring path of datasetpath_img = Path('/home/jupyter/fastai_v3_experimentation/data/PlantVillage/')## Loading data data = ImageDataBunch.from_folder(path=path_img, train='train', valid='valid', ds_tfms=get_transforms(),size=224, bs=bs, check_ext=False)## Normalizing data based on Image net parametersdata.normalize(imagenet_stats)"
},
{
"code": null,
"e": 3692,
"s": 3445,
"text": "To look at a random sample of images, we can use .show_batch() function ImageDataBunch class. As we can see below, we have some cases of diseases leaf on different crops plus some background noise images from DAGS dataset which will act as noise."
},
{
"code": null,
"e": 3732,
"s": 3692,
"text": "data.show_batch(rows=3, figsize=(10,8))"
},
{
"code": null,
"e": 3875,
"s": 3732,
"text": "Let’s print all the data classes present in the database. In total, we have images in 39 classes as mentioned above in the motivation section."
},
{
"code": null,
"e": 3919,
"s": 3875,
"text": "print(data.classes)len(data.classes),data.c"
},
{
"code": null,
"e": 4326,
"s": 3919,
"text": "Now we will start training our model. We will use a convolutional neural network backbone ResNet 50 and a fully connected head with a single hidden layer as a classifier. You can also read the ResNet paper if you want to understand all the architectural detail. To create the transfer learning model we will need to use function create_cnn from Learner class and feed a pre-trained model from models class."
},
{
"code": null,
"e": 4436,
"s": 4326,
"text": "## To create a ResNET 50 with pretrained weightslearn = create_cnn(data, models.resnet50, metrics=error_rate)"
},
{
"code": null,
"e": 4589,
"s": 4436,
"text": "The ResNet50 model created by create_cnn function have initial layers frozen, and we are just going to learn weights of the last fully connected layers."
},
{
"code": null,
"e": 4612,
"s": 4589,
"text": "learn.fit_one_cycle(5)"
},
{
"code": null,
"e": 4997,
"s": 4612,
"text": "As we can see above by just running five epochs with the default setting our accuracy for this fine-grained classification task is around ~99.64% on the validation dataset. Let’s save the model as we are going to fine tune it later. If you want to know how good this result is, it already beats the shallow learning(only training last layer) benchmark of 96.53% from this Github Page."
},
{
"code": null,
"e": 5032,
"s": 4997,
"text": "learn.save('plant_vintage_stage1')"
},
{
"code": null,
"e": 5363,
"s": 5032,
"text": "FastAI library also provides functions to explore results faster and find if our model is learning what it is supposed to learn. We will first see which were the categories that the model most confused with one another. We will try to see if what the model predicted was reasonable or not using ClassificationInterpretation class."
},
{
"code": null,
"e": 5463,
"s": 5363,
"text": "interp = ClassificationInterpretation.from_learner(learn)interp.plot_top_losses(4, figsize=(20,25))"
},
{
"code": null,
"e": 5862,
"s": 5463,
"text": "In this case, the model is getting confused in detecting Northern Leaf blight from Gray leaf spots on Corn plant and early/late blight in tomato leaves which visually looks pretty similar. This is an indicator that our classifier is working correctly. Furthermore, when we plot the confusion matrix, we can see that most of the things are classified correctly, and it’s almost a near perfect model."
},
{
"code": null,
"e": 5916,
"s": 5862,
"text": "interp.plot_confusion_matrix(figsize=(20,20), dpi=60)"
},
{
"code": null,
"e": 6408,
"s": 5916,
"text": "So until now, we have only been training the last classification layers, but what if we want to optimize earlier layers too. In transfer learning, tweaking initial layers should be done with caution, and the learning rate should be kept pretty low. FastAI library provides a function to see what will be the ideal learning rate to train upon, so let’s plot it. The lr_find function runs the model for a subset of data at multiple learning rate to determine which learning rate would be best."
},
{
"code": null,
"e": 6445,
"s": 6408,
"text": "learn.lr_find()learn.recorder.plot()"
},
{
"code": null,
"e": 6827,
"s": 6445,
"text": "It looks like we should keep our learning rate lower than 10e-4. We can use slice function to logarithmically distribute learning rate between 10e-6 to 10e-4 for different layers in the network. Keeping the lowest learning rate for the initial layers and increasing it for later layers. Let’s unfreeze all the layers so that we can train the entire model using unfreeze() function."
},
{
"code": null,
"e": 6891,
"s": 6827,
"text": "learn.unfreeze()learn.fit_one_cycle(2, max_lr=slice(1e-7,1e-5))"
},
{
"code": null,
"e": 7047,
"s": 6891,
"text": "As we can see by training all the layers, we improved our accuracy to 99.7% which is comparable to 99.76% on the Github benchmark using Inception-v3 model."
},
{
"code": null,
"e": 7272,
"s": 7047,
"text": "Fast.ai is an excellent initiative by Jeremy Howard and his team, and I believe fastai library can genuinely achieve the motive of democratizing deep learning to everyone by making building deep learning models super simple."
}
] |
Convert JSON to another JSON format with recursion JavaScript | Suppose, we have the following JSON object −
const obj = {
"context": {
"device": {
"localeCountryCode": "AX",
"datetime": "3047-09-29T07:09:52.498Z"
},
"currentLocation": {
"country": "KM",
"lon": -78789486,
}
}
};
We are required to write a JavaScript recursive function that initially takes in one such array.The function should split the above object into a "label" - "children" format.
Therefore, the output for the above object should look like −
const output = {
"label": "context",
"children": [
{
"label": "device",
"children": [
{
"label": "localeCountryCode"
},
{
"label": "datetime"
}
]
},
{
"label": "currentLocation",
"children": [
{
"label": "country"
},
{
"label": "lon"
}
]
}
]
}
The code for this will be −
const obj = {
"context": {
"device": {
"localeCountryCode": "AX",
"datetime": "3047-09-29T07:09:52.498Z"
},
"currentLocation": {
"country": "KM",
"lon": -78789486,
}
}
};
const transformObject = (obj = {}) => {
if (obj && typeof obj === 'object') {
return Object.keys(obj).map((el) => {
let children = transformObject(obj[el]); return children ? {
label: el, children: children } : {
label: el
};
});
};
};
console.log(JSON.stringify(transformObject(obj), undefined, 4));
And the output in the console will be −
[
{
"label": "context",
"children": [
{
"label": "device",
"children": [
{
"label": "localeCountryCode"
},
{
"label": "datetime"
}
]
},
{
"label": "currentLocation",
"children": [
{
"label": "country"
},
{
"label": "lon"
}
]
}
]
}
] | [
{
"code": null,
"e": 1107,
"s": 1062,
"text": "Suppose, we have the following JSON object −"
},
{
"code": null,
"e": 1344,
"s": 1107,
"text": "const obj = {\n \"context\": {\n \"device\": {\n \"localeCountryCode\": \"AX\",\n \"datetime\": \"3047-09-29T07:09:52.498Z\"\n },\n \"currentLocation\": {\n \"country\": \"KM\",\n \"lon\": -78789486,\n }\n }\n};"
},
{
"code": null,
"e": 1519,
"s": 1344,
"text": "We are required to write a JavaScript recursive function that initially takes in one such array.The function should split the above object into a \"label\" - \"children\" format."
},
{
"code": null,
"e": 1581,
"s": 1519,
"text": "Therefore, the output for the above object should look like −"
},
{
"code": null,
"e": 2035,
"s": 1581,
"text": "const output = {\n \"label\": \"context\",\n \"children\": [\n {\n \"label\": \"device\",\n \"children\": [\n {\n \"label\": \"localeCountryCode\"\n },\n {\n \"label\": \"datetime\"\n }\n ]\n },\n {\n \"label\": \"currentLocation\",\n \"children\": [\n {\n \"label\": \"country\"\n },\n {\n \"label\": \"lon\"\n }\n ]\n }\n ]\n}"
},
{
"code": null,
"e": 2063,
"s": 2035,
"text": "The code for this will be −"
},
{
"code": null,
"e": 2662,
"s": 2063,
"text": "const obj = {\n \"context\": {\n \"device\": {\n \"localeCountryCode\": \"AX\",\n \"datetime\": \"3047-09-29T07:09:52.498Z\"\n },\n \"currentLocation\": {\n \"country\": \"KM\",\n \"lon\": -78789486,\n }\n }\n};\nconst transformObject = (obj = {}) => {\n if (obj && typeof obj === 'object') {\n return Object.keys(obj).map((el) => {\n let children = transformObject(obj[el]); return children ? {\n label: el, children: children } : {\n label: el\n };\n });\n };\n};\nconsole.log(JSON.stringify(transformObject(obj), undefined, 4));"
},
{
"code": null,
"e": 2702,
"s": 2662,
"text": "And the output in the console will be −"
},
{
"code": null,
"e": 3280,
"s": 2702,
"text": "[\n {\n \"label\": \"context\",\n \"children\": [\n {\n \"label\": \"device\",\n \"children\": [\n {\n \"label\": \"localeCountryCode\"\n },\n {\n \"label\": \"datetime\"\n }\n ]\n },\n {\n \"label\": \"currentLocation\",\n \"children\": [\n {\n \"label\": \"country\"\n },\n {\n \"label\": \"lon\"\n }\n ]\n }\n ]\n }\n]"
}
] |
Python Blockchain - Adding Blocks | Each miner will pick up the transactions from a previously created transaction pool. To track the number of messages already mined, we have to create a global variable −
last_transaction_index = 0
We will now have our first miner adding a block to the blockchain.
To add a new block, we first create an instance of the Block class.
block = Block()
We pick up the top 3 transactions from the queue −
for i in range(3):
temp_transaction = transactions[last_transaction_index]
# validate transaction
Before adding the transaction to the block the miner will verify the validity of the transaction. The transaction validity is verified by testing for equality the hash provided by the sender against the hash generated by the miner using sender’s public key. Also, the miner will verify that the sender has sufficient balance to pay for the current transaction.
For brevity, we have not included this functionality in the tutorial. After the transaction is validated, we add it to the verified_transactions list in the block instance.
block.verified_transactions.append (temp_transaction)
We increment the last transaction index so that the next miner will pick up subsequent transactions in the queue.
last_transaction_index += 1
We add exactly three transactions to the block. Once this is done, we will initialize the rest of the instance variables of the Block class. We first add the hash of the last block.
block.previous_block_hash = last_block_hash
Next, we mine the block with a difficulty level of 2.
block.Nonce = mine (block, 2)
Note that the first parameter to the mine function is a binary object. We now hash the entire block and create a digest on it.
digest = hash (block)
Finally, we add the created block to the blockchain and re-initialize the global variable last_block_hash for the use in next block.
The entire code for adding the block is shown below −
block = Block()
for i in range(3):
temp_transaction = transactions[last_transaction_index]
# validate transaction
# if valid
block.verified_transactions.append (temp_transaction)
last_transaction_index += 1
block.previous_block_hash = last_block_hash
block.Nonce = mine (block, 2)
digest = hash (block)
TPCoins.append (block)
last_block_hash = digest
We will now add two more blocks to our blockchain. The code for adding the next two blocks is given below −
# Miner 2 adds a block
block = Block()
for i in range(3):
temp_transaction = transactions[last_transaction_index]
# validate transaction
# if valid
block.verified_transactions.append (temp_transaction)
last_transaction_index += 1
block.previous_block_hash = last_block_hash
block.Nonce = mine (block, 2)digest = hash (block)
TPCoins.append (block)last_block_hash = digest
# Miner 3 adds a block
block = Block()
for i in range(3):
temp_transaction = transactions[last_transaction_index]
#display_transaction (temp_transaction)
# validate transaction
# if valid
block.verified_transactions.append (temp_transaction)
last_transaction_index += 1
block.previous_block_hash = last_block_hash
block.Nonce = mine (block, 2)
digest = hash (block)
TPCoins.append (block)
last_block_hash = digest
When you add these two blocks, you will also see the number of iterations it took to find the Nonce. At this point, our blockchain consists of totally 4 blocks including the genesis block.
You can verify the contents of the entire blockchain using the following statement −
dump_blockchain(TPCoins)
You would see the output similar to the one shown below −
Number of blocks in the chain: 4
block # 0
sender: Genesis
-----
recipient:
30819f300d06092a864886f70d010101050003818d0030818902818100ed272b52ccb539e2cd779
c6cc10ed1dfadf5d97c6ab6de90ed0372b2655626fb79f62d0e01081c163b0864cc68d426bbe943
8e8566303bb77414d4bfcaa3468ab7febac099294de10273a816f7047d4087b4bafa11f141544d4
8e2f10b842cab91faf33153900c7bf6c08c9e47a7df8aa7e60dc9e0798fb2ba3484bbdad2e44302
03010001
-----
value: 500.0
-----
time: 2019-01-14 16:18:02.042739
-----
--------------
=====================================
block # 1
sender:
30819f300d06092a864886f70d010101050003818d0030818902818100bb064c99c492144a9f463
480273aba93ac1db1f0da3cb9f3c1f9d058cf499fd8e54d244da0a8dd6ddd329ec86794b04d773e
b4841c9f935ea4d9ccc2821c7a1082d23b6c928d59863407f52fa05d8b47e5157f8fe56c2ce3279
c657f9c6a80500073b0be8093f748aef667c03e64f04f84d311c4d866c12d79d3fc3034563dfb02
03010001
-----
recipient:
30819f300d06092a864886f70d010101050003818d0030818902818100be93b516b28c6e674abe7
abdb11ce0fdf5bb728b75216b73f37a6432e4b402b3ad8139b8c0ba541a72c8add126b6e1a1308f
b98b727beb63c6060356bb177bb7d54b54dbe87aee7353d0a6baa9397704de625d1836d3f42c7ee
5683f6703259592cc24b09699376807f28fe0e00ff882974484d805f874260dfc2d1627473b9102
03010001
-----
value: 15.0
-----
time: 2019-01-14 16:18:01.859915
-----
--------------
sender:
30819f300d06092a864886f70d010101050003818d0030818902818100bb064c99c492144a9f463
480273aba93ac1db1f0da3cb9f3c1f9d058cf499fd8e54d244da0a8dd6ddd329ec86794b04d773e
b4841c9f935ea4d9ccc2821c7a1082d23b6c928d59863407f52fa05d8b47e5157f8fe56c2ce3279
c657f9c6a80500073b0be8093f748aef667c03e64f04f84d311c4d866c12d79d3fc3034563dfb02
03010001
-----
recipient:
30819f300d06092a864886f70d010101050003818d0030818902818100a070c82b34ae143cbe59b
3a2afde7186e9d5bc274955d8112d87a00256a35369acc4d0edfe65e8f9dc93fbd9ee74b9e7ea12
334da38c8c9900e6ced1c4ce93f86e06611e656521a1eab561892b7db0961b4f212d1fd5b5e49ae
09cf8c603a068f9b723aa8a651032ff6f24e5de00387e4d062375799742a359b8f22c5362e56502
03010001
-----
value: 6.0
-----
time: 2019-01-14 16:18:01.860966
-----
--------------
sender:
30819f300d06092a864886f70d010101050003818d0030818902818100be93b516b28c6e674abe7
abdb11ce0fdf5bb728b75216b73f37a6432e4b402b3ad8139b8c0ba541a72c8add126b6e1a1308f
b98b727beb63c6060356bb177bb7d54b54dbe87aee7353d0a6baa9397704de625d1836d3f42c7ee
5683f6703259592cc24b09699376807f28fe0e00ff882974484d805f874260dfc2d1627473b9102
03010001
-----
recipient:
30819f300d06092a864886f70d010101050003818d0030818902818100cba097c0854876f41338c
62598c658f545182cfa4acebce147aedf328181f9c4930f14498fd03c0af6b0cce25be99452a81d
f4fa30a53eddbb7bb7b203adf8764a0ccd9db6913a576d68d642d8fd47452590137869c25d9ff83
d68ebe6d616056a8425b85b52e69715b8b85ae807b84638d8f00e321b65e4c33acaf6469e18e302
03010001
-----
value: 2.0
-----
time: 2019-01-14 16:18:01.861958
-----
--------------
=====================================
block # 2
sender:
30819f300d06092a864886f70d010101050003818d0030818902818100a070c82b34ae143cbe59b
3a2afde7186e9d5bc274955d8112d87a00256a35369acc4d0edfe65e8f9dc93fbd9ee74b9e7ea12
334da38c8c9900e6ced1c4ce93f86e06611e656521a1eab561892b7db0961b4f212d1fd5b5e49ae
09cf8c603a068f9b723aa8a651032ff6f24e5de00387e4d062375799742a359b8f22c5362e56502
03010001
-----
recipient:
30819f300d06092a864886f70d010101050003818d0030818902818100be93b516b28c6e674abe7
abdb11ce0fdf5bb728b75216b73f37a6432e4b402b3ad8139b8c0ba541a72c8add126b6e1a1308f
b98b727beb63c6060356bb177bb7d54b54dbe87aee7353d0a6baa9397704de625d1836d3f42c7ee
5683f6703259592cc24b09699376807f28fe0e00ff882974484d805f874260dfc2d1627473b9102
03010001
-----
value: 4.0
-----
time: 2019-01-14 16:18:01.862946
-----
--------------
sender:
30819f300d06092a864886f70d010101050003818d0030818902818100cba097c0854876f41338c
62598c658f545182cfa4acebce147aedf328181f9c4930f14498fd03c0af6b0cce25be99452a81d
f4fa30a53eddbb7bb7b203adf8764a0ccd9db6913a576d68d642d8fd47452590137869c25d9ff83
d68ebe6d616056a8425b85b52e69715b8b85ae807b84638d8f00e321b65e4c33acaf6469e18e302
03010001
-----
recipient:
30819f300d06092a864886f70d010101050003818d0030818902818100a070c82b34ae143cbe59b
3a2afde7186e9d5bc274955d8112d87a00256a35369acc4d0edfe65e8f9dc93fbd9ee74b9e7ea12
334da38c8c9900e6ced1c4ce93f86e06611e656521a1eab561892b7db0961b4f212d1fd5b5e49ae
09cf8c603a068f9b723aa8a651032ff6f24e5de00387e4d062375799742a359b8f22c5362e56502
03010001
-----
value: 7.0
-----
time: 2019-01-14 16:18:01.863932
-----
--------------
sender:
30819f300d06092a864886f70d010101050003818d0030818902818100be93b516b28c6e674abe7
abdb11ce0fdf5bb728b75216b73f37a6432e4b402b3ad8139b8c0ba541a72c8add126b6e1a1308f
b98b727beb63c6060356bb177bb7d54b54dbe87aee7353d0a6baa9397704de625d1836d3f42c7ee
5683f6703259592cc24b09699376807f28fe0e00ff882974484d805f874260dfc2d1627473b9102
03010001
-----
recipient:
30819f300d06092a864886f70d010101050003818d0030818902818100a070c82b34ae143cbe59b
3a2afde7186e9d5bc274955d8112d87a00256a35369acc4d0edfe65e8f9dc93fbd9ee74b9e7ea12
334da38c8c9900e6ced1c4ce93f86e06611e656521a1eab561892b7db0961b4f212d1fd5b5e49ae
09cf8c603a068f9b723aa8a651032ff6f24e5de00387e4d062375799742a359b8f22c5362e56502
03010001
-----
value: 3.0
-----
time: 2019-01-14 16:18:01.865099
-----
--------------
=====================================
block # 3
sender:
30819f300d06092a864886f70d010101050003818d0030818902818100a070c82b34ae143cbe59b
3a2afde7186e9d5bc274955d8112d87a00256a35369acc4d0edfe65e8f9dc93fbd9ee74b9e7ea12
334da38c8c9900e6ced1c4ce93f86e06611e656521a1eab561892b7db0961b4f212d1fd5b5e49ae
09cf8c603a068f9b723aa8a651032ff6f24e5de00387e4d062375799742a359b8f22c5362e56502
03010001
-----
recipient:
30819f300d06092a864886f70d010101050003818d0030818902818100bb064c99c492144a9f463
480273aba93ac1db1f0da3cb9f3c1f9d058cf499fd8e54d244da0a8dd6ddd329ec86794b04d773e
b4841c9f935ea4d9ccc2821c7a1082d23b6c928d59863407f52fa05d8b47e5157f8fe56c2ce3279
c657f9c6a80500073b0be8093f748aef667c03e64f04f84d311c4d866c12d79d3fc3034563dfb02
03010001
-----
value: 8.0
-----
time: 2019-01-14 16:18:01.866219
-----
--------------
sender:
30819f300d06092a864886f70d010101050003818d0030818902818100a070c82b34ae143cbe59b
3a2afde7186e9d5bc274955d8112d87a00256a35369acc4d0edfe65e8f9dc93fbd9ee74b9e7ea12
334da38c8c9900e6ced1c4ce93f86e06611e656521a1eab561892b7db0961b4f212d1fd5b5e49ae
09cf8c603a068f9b723aa8a651032ff6f24e5de00387e4d062375799742a359b8f22c5362e56502
03010001
-----
recipient:
30819f300d06092a864886f70d010101050003818d0030818902818100be93b516b28c6e674abe7
abdb11ce0fdf5bb728b75216b73f37a6432e4b402b3ad8139b8c0ba541a72c8add126b6e1a1308f
b98b727beb63c6060356bb177bb7d54b54dbe87aee7353d0a6baa9397704de625d1836d3f42c7ee
5683f6703259592cc24b09699376807f28fe0e00ff882974484d805f874260dfc2d1627473b9102
03010001
-----
value: 1.0
-----
time: 2019-01-14 16:18:01.867223
-----
--------------
sender:
30819f300d06092a864886f70d010101050003818d0030818902818100cba097c0854876f41338c
62598c658f545182cfa4acebce147aedf328181f9c4930f14498fd03c0af6b0cce25be99452a81d
f4fa30a53eddbb7bb7b203adf8764a0ccd9db6913a576d68d642d8fd47452590137869c25d9ff83
d68ebe6d616056a8425b85b52e69715b8b85ae807b84638d8f00e321b65e4c33acaf6469e18e302
03010001
-----
recipient:
30819f300d06092a864886f70d010101050003818d0030818902818100bb064c99c492144a9f463
480273aba93ac1db1f0da3cb9f3c1f9d058cf499fd8e54d244da0a8dd6ddd329ec86794b04d773e
b4841c9f935ea4d9ccc2821c7a1082d23b6c928d59863407f52fa05d8b47e5157f8fe56c2ce3279
c657f9c6a80500073b0be8093f748aef667c03e64f04f84d311c4d866c12d79d3fc3034563dfb02
03010001
-----
value: 5.0
-----
time: 2019-01-14 16:18:01.868241
-----
--------------
=====================================
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": 2165,
"s": 1995,
"text": "Each miner will pick up the transactions from a previously created transaction pool. To track the number of messages already mined, we have to create a global variable −"
},
{
"code": null,
"e": 2193,
"s": 2165,
"text": "last_transaction_index = 0\n"
},
{
"code": null,
"e": 2260,
"s": 2193,
"text": "We will now have our first miner adding a block to the blockchain."
},
{
"code": null,
"e": 2328,
"s": 2260,
"text": "To add a new block, we first create an instance of the Block class."
},
{
"code": null,
"e": 2345,
"s": 2328,
"text": "block = Block()\n"
},
{
"code": null,
"e": 2396,
"s": 2345,
"text": "We pick up the top 3 transactions from the queue −"
},
{
"code": null,
"e": 2501,
"s": 2396,
"text": "for i in range(3):\n temp_transaction = transactions[last_transaction_index]\n # validate transaction\n"
},
{
"code": null,
"e": 2862,
"s": 2501,
"text": "Before adding the transaction to the block the miner will verify the validity of the transaction. The transaction validity is verified by testing for equality the hash provided by the sender against the hash generated by the miner using sender’s public key. Also, the miner will verify that the sender has sufficient balance to pay for the current transaction."
},
{
"code": null,
"e": 3035,
"s": 2862,
"text": "For brevity, we have not included this functionality in the tutorial. After the transaction is validated, we add it to the verified_transactions list in the block instance."
},
{
"code": null,
"e": 3090,
"s": 3035,
"text": "block.verified_transactions.append (temp_transaction)\n"
},
{
"code": null,
"e": 3204,
"s": 3090,
"text": "We increment the last transaction index so that the next miner will pick up subsequent transactions in the queue."
},
{
"code": null,
"e": 3233,
"s": 3204,
"text": "last_transaction_index += 1\n"
},
{
"code": null,
"e": 3415,
"s": 3233,
"text": "We add exactly three transactions to the block. Once this is done, we will initialize the rest of the instance variables of the Block class. We first add the hash of the last block."
},
{
"code": null,
"e": 3460,
"s": 3415,
"text": "block.previous_block_hash = last_block_hash\n"
},
{
"code": null,
"e": 3514,
"s": 3460,
"text": "Next, we mine the block with a difficulty level of 2."
},
{
"code": null,
"e": 3545,
"s": 3514,
"text": "block.Nonce = mine (block, 2)\n"
},
{
"code": null,
"e": 3672,
"s": 3545,
"text": "Note that the first parameter to the mine function is a binary object. We now hash the entire block and create a digest on it."
},
{
"code": null,
"e": 3695,
"s": 3672,
"text": "digest = hash (block)\n"
},
{
"code": null,
"e": 3828,
"s": 3695,
"text": "Finally, we add the created block to the blockchain and re-initialize the global variable last_block_hash for the use in next block."
},
{
"code": null,
"e": 3882,
"s": 3828,
"text": "The entire code for adding the block is shown below −"
},
{
"code": null,
"e": 4250,
"s": 3882,
"text": "block = Block()\nfor i in range(3):\n temp_transaction = transactions[last_transaction_index]\n # validate transaction\n # if valid\n block.verified_transactions.append (temp_transaction)\n last_transaction_index += 1\n\nblock.previous_block_hash = last_block_hash\nblock.Nonce = mine (block, 2)\ndigest = hash (block)\nTPCoins.append (block)\nlast_block_hash = digest\n"
},
{
"code": null,
"e": 4358,
"s": 4250,
"text": "We will now add two more blocks to our blockchain. The code for adding the next two blocks is given below −"
},
{
"code": null,
"e": 5181,
"s": 4358,
"text": "# Miner 2 adds a block\nblock = Block()\n\nfor i in range(3):\n temp_transaction = transactions[last_transaction_index]\n # validate transaction\n # if valid\n block.verified_transactions.append (temp_transaction)\n last_transaction_index += 1\nblock.previous_block_hash = last_block_hash\nblock.Nonce = mine (block, 2)digest = hash (block)\nTPCoins.append (block)last_block_hash = digest\n# Miner 3 adds a block\nblock = Block()\n\nfor i in range(3):\n temp_transaction = transactions[last_transaction_index]\n #display_transaction (temp_transaction)\n # validate transaction\n # if valid\n block.verified_transactions.append (temp_transaction)\n last_transaction_index += 1\n\nblock.previous_block_hash = last_block_hash\nblock.Nonce = mine (block, 2)\ndigest = hash (block)\n\nTPCoins.append (block)\nlast_block_hash = digest"
},
{
"code": null,
"e": 5370,
"s": 5181,
"text": "When you add these two blocks, you will also see the number of iterations it took to find the Nonce. At this point, our blockchain consists of totally 4 blocks including the genesis block."
},
{
"code": null,
"e": 5455,
"s": 5370,
"text": "You can verify the contents of the entire blockchain using the following statement −"
},
{
"code": null,
"e": 5481,
"s": 5455,
"text": "dump_blockchain(TPCoins)\n"
},
{
"code": null,
"e": 5539,
"s": 5481,
"text": "You would see the output similar to the one shown below −"
},
{
"code": null,
"e": 13048,
"s": 5539,
"text": "Number of blocks in the chain: 4\nblock # 0\nsender: Genesis\n-----\nrecipient:\n30819f300d06092a864886f70d010101050003818d0030818902818100ed272b52ccb539e2cd779\nc6cc10ed1dfadf5d97c6ab6de90ed0372b2655626fb79f62d0e01081c163b0864cc68d426bbe943\n8e8566303bb77414d4bfcaa3468ab7febac099294de10273a816f7047d4087b4bafa11f141544d4\n8e2f10b842cab91faf33153900c7bf6c08c9e47a7df8aa7e60dc9e0798fb2ba3484bbdad2e44302\n03010001\n-----\nvalue: 500.0\n-----\ntime: 2019-01-14 16:18:02.042739\n-----\n--------------\n=====================================\nblock # 1\nsender:\n30819f300d06092a864886f70d010101050003818d0030818902818100bb064c99c492144a9f463\n480273aba93ac1db1f0da3cb9f3c1f9d058cf499fd8e54d244da0a8dd6ddd329ec86794b04d773e\nb4841c9f935ea4d9ccc2821c7a1082d23b6c928d59863407f52fa05d8b47e5157f8fe56c2ce3279\nc657f9c6a80500073b0be8093f748aef667c03e64f04f84d311c4d866c12d79d3fc3034563dfb02\n03010001\n-----\nrecipient:\n30819f300d06092a864886f70d010101050003818d0030818902818100be93b516b28c6e674abe7\nabdb11ce0fdf5bb728b75216b73f37a6432e4b402b3ad8139b8c0ba541a72c8add126b6e1a1308f\nb98b727beb63c6060356bb177bb7d54b54dbe87aee7353d0a6baa9397704de625d1836d3f42c7ee\n5683f6703259592cc24b09699376807f28fe0e00ff882974484d805f874260dfc2d1627473b9102\n03010001\n-----\nvalue: 15.0\n-----\ntime: 2019-01-14 16:18:01.859915\n-----\n--------------\nsender:\n30819f300d06092a864886f70d010101050003818d0030818902818100bb064c99c492144a9f463\n480273aba93ac1db1f0da3cb9f3c1f9d058cf499fd8e54d244da0a8dd6ddd329ec86794b04d773e\nb4841c9f935ea4d9ccc2821c7a1082d23b6c928d59863407f52fa05d8b47e5157f8fe56c2ce3279\nc657f9c6a80500073b0be8093f748aef667c03e64f04f84d311c4d866c12d79d3fc3034563dfb02\n03010001\n-----\nrecipient:\n30819f300d06092a864886f70d010101050003818d0030818902818100a070c82b34ae143cbe59b\n3a2afde7186e9d5bc274955d8112d87a00256a35369acc4d0edfe65e8f9dc93fbd9ee74b9e7ea12\n334da38c8c9900e6ced1c4ce93f86e06611e656521a1eab561892b7db0961b4f212d1fd5b5e49ae\n09cf8c603a068f9b723aa8a651032ff6f24e5de00387e4d062375799742a359b8f22c5362e56502\n03010001\n-----\nvalue: 6.0\n-----\ntime: 2019-01-14 16:18:01.860966\n-----\n--------------\nsender:\n30819f300d06092a864886f70d010101050003818d0030818902818100be93b516b28c6e674abe7\nabdb11ce0fdf5bb728b75216b73f37a6432e4b402b3ad8139b8c0ba541a72c8add126b6e1a1308f\nb98b727beb63c6060356bb177bb7d54b54dbe87aee7353d0a6baa9397704de625d1836d3f42c7ee\n5683f6703259592cc24b09699376807f28fe0e00ff882974484d805f874260dfc2d1627473b9102\n03010001\n-----\nrecipient:\n30819f300d06092a864886f70d010101050003818d0030818902818100cba097c0854876f41338c\n62598c658f545182cfa4acebce147aedf328181f9c4930f14498fd03c0af6b0cce25be99452a81d\nf4fa30a53eddbb7bb7b203adf8764a0ccd9db6913a576d68d642d8fd47452590137869c25d9ff83\nd68ebe6d616056a8425b85b52e69715b8b85ae807b84638d8f00e321b65e4c33acaf6469e18e302\n03010001\n-----\nvalue: 2.0\n-----\ntime: 2019-01-14 16:18:01.861958\n-----\n--------------\n=====================================\nblock # 2\nsender:\n30819f300d06092a864886f70d010101050003818d0030818902818100a070c82b34ae143cbe59b\n3a2afde7186e9d5bc274955d8112d87a00256a35369acc4d0edfe65e8f9dc93fbd9ee74b9e7ea12\n334da38c8c9900e6ced1c4ce93f86e06611e656521a1eab561892b7db0961b4f212d1fd5b5e49ae\n09cf8c603a068f9b723aa8a651032ff6f24e5de00387e4d062375799742a359b8f22c5362e56502\n03010001\n-----\nrecipient:\n30819f300d06092a864886f70d010101050003818d0030818902818100be93b516b28c6e674abe7\nabdb11ce0fdf5bb728b75216b73f37a6432e4b402b3ad8139b8c0ba541a72c8add126b6e1a1308f\nb98b727beb63c6060356bb177bb7d54b54dbe87aee7353d0a6baa9397704de625d1836d3f42c7ee\n5683f6703259592cc24b09699376807f28fe0e00ff882974484d805f874260dfc2d1627473b9102\n03010001\n-----\nvalue: 4.0\n-----\ntime: 2019-01-14 16:18:01.862946\n-----\n--------------\nsender:\n30819f300d06092a864886f70d010101050003818d0030818902818100cba097c0854876f41338c\n62598c658f545182cfa4acebce147aedf328181f9c4930f14498fd03c0af6b0cce25be99452a81d\nf4fa30a53eddbb7bb7b203adf8764a0ccd9db6913a576d68d642d8fd47452590137869c25d9ff83\nd68ebe6d616056a8425b85b52e69715b8b85ae807b84638d8f00e321b65e4c33acaf6469e18e302\n03010001\n-----\nrecipient:\n30819f300d06092a864886f70d010101050003818d0030818902818100a070c82b34ae143cbe59b\n3a2afde7186e9d5bc274955d8112d87a00256a35369acc4d0edfe65e8f9dc93fbd9ee74b9e7ea12\n334da38c8c9900e6ced1c4ce93f86e06611e656521a1eab561892b7db0961b4f212d1fd5b5e49ae\n09cf8c603a068f9b723aa8a651032ff6f24e5de00387e4d062375799742a359b8f22c5362e56502\n03010001\n-----\nvalue: 7.0\n-----\ntime: 2019-01-14 16:18:01.863932\n-----\n--------------\nsender:\n30819f300d06092a864886f70d010101050003818d0030818902818100be93b516b28c6e674abe7\nabdb11ce0fdf5bb728b75216b73f37a6432e4b402b3ad8139b8c0ba541a72c8add126b6e1a1308f\nb98b727beb63c6060356bb177bb7d54b54dbe87aee7353d0a6baa9397704de625d1836d3f42c7ee\n5683f6703259592cc24b09699376807f28fe0e00ff882974484d805f874260dfc2d1627473b9102\n03010001\n-----\nrecipient:\n30819f300d06092a864886f70d010101050003818d0030818902818100a070c82b34ae143cbe59b\n3a2afde7186e9d5bc274955d8112d87a00256a35369acc4d0edfe65e8f9dc93fbd9ee74b9e7ea12\n334da38c8c9900e6ced1c4ce93f86e06611e656521a1eab561892b7db0961b4f212d1fd5b5e49ae\n09cf8c603a068f9b723aa8a651032ff6f24e5de00387e4d062375799742a359b8f22c5362e56502\n03010001\n-----\nvalue: 3.0\n-----\ntime: 2019-01-14 16:18:01.865099\n-----\n--------------\n=====================================\nblock # 3\nsender:\n30819f300d06092a864886f70d010101050003818d0030818902818100a070c82b34ae143cbe59b\n3a2afde7186e9d5bc274955d8112d87a00256a35369acc4d0edfe65e8f9dc93fbd9ee74b9e7ea12\n334da38c8c9900e6ced1c4ce93f86e06611e656521a1eab561892b7db0961b4f212d1fd5b5e49ae\n09cf8c603a068f9b723aa8a651032ff6f24e5de00387e4d062375799742a359b8f22c5362e56502\n03010001\n-----\nrecipient:\n30819f300d06092a864886f70d010101050003818d0030818902818100bb064c99c492144a9f463\n480273aba93ac1db1f0da3cb9f3c1f9d058cf499fd8e54d244da0a8dd6ddd329ec86794b04d773e\nb4841c9f935ea4d9ccc2821c7a1082d23b6c928d59863407f52fa05d8b47e5157f8fe56c2ce3279\nc657f9c6a80500073b0be8093f748aef667c03e64f04f84d311c4d866c12d79d3fc3034563dfb02\n03010001\n-----\nvalue: 8.0\n-----\ntime: 2019-01-14 16:18:01.866219\n-----\n--------------\nsender:\n30819f300d06092a864886f70d010101050003818d0030818902818100a070c82b34ae143cbe59b\n3a2afde7186e9d5bc274955d8112d87a00256a35369acc4d0edfe65e8f9dc93fbd9ee74b9e7ea12\n334da38c8c9900e6ced1c4ce93f86e06611e656521a1eab561892b7db0961b4f212d1fd5b5e49ae\n09cf8c603a068f9b723aa8a651032ff6f24e5de00387e4d062375799742a359b8f22c5362e56502\n03010001\n-----\nrecipient:\n30819f300d06092a864886f70d010101050003818d0030818902818100be93b516b28c6e674abe7\nabdb11ce0fdf5bb728b75216b73f37a6432e4b402b3ad8139b8c0ba541a72c8add126b6e1a1308f\nb98b727beb63c6060356bb177bb7d54b54dbe87aee7353d0a6baa9397704de625d1836d3f42c7ee\n5683f6703259592cc24b09699376807f28fe0e00ff882974484d805f874260dfc2d1627473b9102\n03010001\n-----\nvalue: 1.0\n-----\ntime: 2019-01-14 16:18:01.867223\n-----\n--------------\nsender:\n30819f300d06092a864886f70d010101050003818d0030818902818100cba097c0854876f41338c\n62598c658f545182cfa4acebce147aedf328181f9c4930f14498fd03c0af6b0cce25be99452a81d\nf4fa30a53eddbb7bb7b203adf8764a0ccd9db6913a576d68d642d8fd47452590137869c25d9ff83\nd68ebe6d616056a8425b85b52e69715b8b85ae807b84638d8f00e321b65e4c33acaf6469e18e302\n03010001\n-----\nrecipient: \n30819f300d06092a864886f70d010101050003818d0030818902818100bb064c99c492144a9f463\n480273aba93ac1db1f0da3cb9f3c1f9d058cf499fd8e54d244da0a8dd6ddd329ec86794b04d773e\nb4841c9f935ea4d9ccc2821c7a1082d23b6c928d59863407f52fa05d8b47e5157f8fe56c2ce3279\nc657f9c6a80500073b0be8093f748aef667c03e64f04f84d311c4d866c12d79d3fc3034563dfb02\n03010001\n-----\nvalue: 5.0\n-----\ntime: 2019-01-14 16:18:01.868241\n-----\n--------------\n=====================================\n"
},
{
"code": null,
"e": 13085,
"s": 13048,
"text": "\n 187 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 13101,
"s": 13085,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 13134,
"s": 13101,
"text": "\n 55 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 13153,
"s": 13134,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 13188,
"s": 13153,
"text": "\n 136 Lectures \n 11 hours \n"
},
{
"code": null,
"e": 13210,
"s": 13188,
"text": " In28Minutes Official"
},
{
"code": null,
"e": 13244,
"s": 13210,
"text": "\n 75 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 13272,
"s": 13244,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 13307,
"s": 13272,
"text": "\n 70 Lectures \n 8.5 hours \n"
},
{
"code": null,
"e": 13321,
"s": 13307,
"text": " Lets Kode It"
},
{
"code": null,
"e": 13354,
"s": 13321,
"text": "\n 63 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 13371,
"s": 13354,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 13378,
"s": 13371,
"text": " Print"
},
{
"code": null,
"e": 13389,
"s": 13378,
"text": " Add Notes"
}
] |
Machine Learning Basics: K-Nearest Neighbors Classification | by Gurucharan M K | Towards Data Science | In the previous stories, I had given an explanation of the program for implementation of various Regression models. Also, I had described the implementation of the Logistic Regression model. In this article, we shall see the algorithm of the K-Nearest Neighbors or KNN Classification along with a simple example.
The K-Nearest Neighbors or KNN Classification is a simple and easy to implement, supervised machine learning algorithm that is used mostly for classification problems.
Let us understand this algorithm with a very simple example. Suppose there are two classes represented by Rectangles and Triangles. If we want to add a new shape (Diamond) to any one of the classes, then we can implement the KNN Classification model.
In this model, we have to choose the number of nearest neighbors (N). Here, as we have chosen N=4, the new data point calculates the distance between each of the points and draws a circular region around its nearest 4 neighbors ( as N=4). In this problem as all the four nearest neighbors lie in the Class 1 (Rectangles), the new data point (Diamond) is also assigned as a Class 1 data point.
In this way, we can alter the parameter, N with various values and choose the most accurate value for the model by a trial and error basis, also avoiding over-fitting and high loss.
In this way, we can implement the KNN Classification algorithm. Let us now move to its implementation with a real world example in the next section.
To apply the KNN Classification model in practical use, I am using the same dataset used in building the Logistic Regression model. In this, we DMV Test dataset which has three columns. The first two columns consist of the two DMV written tests (DMV_Test_1 and DMV_Test_2) which are the independent variables and the last column consists of the dependent variable, Results which denote that the driver has got the license (1) or not (0).
In this, we have to build a KNN Classification model using this data to predict if a driver who has taken the two DMV written tests will get the license or not using those marks obtained in their written tests and classify the results.
As always, the first step will always include importing the libraries which are the NumPy, Pandas and the Matplotlib.
import numpy as npimport matplotlib.pyplot as pltimport pandas as pd
In this step, we shall get the dataset from my GitHub repository as “DMVWrittenTests.csv”. The variable X will store the two “DMV Tests ”and the variable Y will store the final output as “Results”. The dataset.head(5)is used to visualize the first 5 rows of the data.
dataset = pd.read_csv('https://raw.githubusercontent.com/mk-gurucharan/Classification/master/DMVWrittenTests.csv')X = dataset.iloc[:, [0, 1]].valuesy = dataset.iloc[:, 2].valuesdataset.head(5)>>DMV_Test_1 DMV_Test_2 Results34.623660 78.024693 030.286711 43.894998 035.847409 72.902198 060.182599 86.308552 179.032736 75.344376 1
In this step, we have to split the dataset into the Training set, on which the Logistic Regression model will be trained and the Test set, on which the trained model will be applied to classify the results. In this the test_size=0.25 denotes that 25% of the data will be kept as the Test set and the remaining 75% will be used for training as the Training set.
from sklearn.model_selection import train_test_splitX_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.25)
This is an additional step that is used to normalize the data within a particular range. It also aids in speeding up the calculations. As the data is widely varying, we use this function to limit the range of the data within a small limit ( -2,2). For example, the score 62.0730638 is normalized to -0.21231162 and the score 96.51142588 is normalized to 1.55187648. In this way, the scores of X_train and X_test are normalized to a smaller range.
from sklearn.preprocessing import StandardScalersc = StandardScaler()X_train = sc.fit_transform(X_train)X_test = sc.transform(X_test)
In this step, the class KNeighborsClassifier is imported and is assigned to the variable “classifier”. The classifier.fit() function is fitted with X_train and Y_train on which the model will be trained.
from sklearn.neighbors import KNeighborsClassifierclassifier = KNeighborsClassifier(n_neighbors = 5, metric = 'minkowski', p = 2)classifier.fit(X_train, y_train)
In this step, the classifier.predict() function is used to predict the values for the Test set and the values are stored to the variable y_pred.
y_pred = classifier.predict(X_test) y_pred
This is a step that is mostly used in classification techniques. In this, we see the Accuracy of the trained model and plot the confusion matrix.
The confusion matrix is a table that is used to show the number of correct and incorrect predictions on a classification problem when the real values of the Test Set are known. It is of the format
The True values are the number of correct predictions made.
from sklearn.metrics import confusion_matrixcm = confusion_matrix(y_test, y_pred)from sklearn.metrics import accuracy_score print ("Accuracy : ", accuracy_score(y_test, y_pred))cm>>Accuracy : 0.92>>array([[11, 1], [ 1, 12]])
From the above confusion matrix, we infer that, out of 25 test set data, 23 were correctly classified and 2 were incorrectly classified which is little better than the Logistic Regression model.
In this step, a Pandas DataFrame is created to compare the classified values of both the original Test set (y_test) and the predicted results (y_pred).
df = pd.DataFrame({'Real Values':y_test, 'Predicted Values':y_pred})df>> Real Values Predicted Values0 00 11 10 00 01 11 10 00 01 10 01 01 11 10 00 00 01 11 11 11 10 01 11 10 0
Though this visualization may not be of much use as it was with Regression, from this, we can see that the model is able to classify the test set values with a decent accuracy of 92% as calculated above.
In this last step, we visualize the results of the KNN Classification model on a graph that is plotted along with the two regions.
from matplotlib.colors import ListedColormapX_set, y_set = X_test, y_testX1, X2 = np.meshgrid(np.arange(start = X_set[:, 0].min() - 1, stop = X_set[:, 0].max() + 1, step = 0.01), np.arange(start = X_set[:, 1].min() - 1, stop = X_set[:, 1].max() + 1, step = 0.01))plt.contourf(X1, X2, classifier.predict(np.array([X1.ravel(), X2.ravel()]).T).reshape(X1.shape), alpha = 0.75, cmap = ListedColormap(('red', 'green')))plt.xlim(X1.min(), X1.max())plt.ylim(X2.min(), X2.max())for i, j in enumerate(np.unique(y_set)): plt.scatter(X_set[y_set == j, 0], X_set[y_set == j, 1], c = ListedColormap(('red', 'green'))(i), label = j)plt.title('KNN Classification')plt.xlabel('DMV_Test_1')plt.ylabel('DMV_Test_2')plt.legend()plt.show()
In this graph, the value 1 (i.e, Yes) is plotted in “Red” color and the value 0 (i.e, No) is plotted in “Green” color. The KNN Classification model separates the two regions. It is not linear as the Logistic Regression model. Thus, any data with the two data points (DMV_Test_1 and DMV_Test_2) given, can be plotted on the graph and depending upon which region if falls in, the result (Getting the Driver’s License) can be classified as Yes or No.
As calculated above, we can see that there are two values in the test set, one on each region that are wrongly classified.
Thus in this story, we have successfully been able to build a KNN Classification Model that is able to predict if a person is able to get the driving license from their written examinations and visualize the results.
I am also attaching the link to my GitHub repository where you can download this Google Colab notebook and the data files for your reference.
github.com
You can also find the explanation of the program for other Classification models below:
Logistic Regression
K-Nearest Neighbours (KNN) Classification
Support Vector Machine (SVM) Classification (Coming Soon)
Naive Bayes Classification (Coming Soon)
Random Forest Classification (Coming Soon)
We will come across the more complex models of Regression, Classification and Clustering in the upcoming articles. Till then, Happy Machine Learning! | [
{
"code": null,
"e": 485,
"s": 172,
"text": "In the previous stories, I had given an explanation of the program for implementation of various Regression models. Also, I had described the implementation of the Logistic Regression model. In this article, we shall see the algorithm of the K-Nearest Neighbors or KNN Classification along with a simple example."
},
{
"code": null,
"e": 653,
"s": 485,
"text": "The K-Nearest Neighbors or KNN Classification is a simple and easy to implement, supervised machine learning algorithm that is used mostly for classification problems."
},
{
"code": null,
"e": 904,
"s": 653,
"text": "Let us understand this algorithm with a very simple example. Suppose there are two classes represented by Rectangles and Triangles. If we want to add a new shape (Diamond) to any one of the classes, then we can implement the KNN Classification model."
},
{
"code": null,
"e": 1297,
"s": 904,
"text": "In this model, we have to choose the number of nearest neighbors (N). Here, as we have chosen N=4, the new data point calculates the distance between each of the points and draws a circular region around its nearest 4 neighbors ( as N=4). In this problem as all the four nearest neighbors lie in the Class 1 (Rectangles), the new data point (Diamond) is also assigned as a Class 1 data point."
},
{
"code": null,
"e": 1479,
"s": 1297,
"text": "In this way, we can alter the parameter, N with various values and choose the most accurate value for the model by a trial and error basis, also avoiding over-fitting and high loss."
},
{
"code": null,
"e": 1628,
"s": 1479,
"text": "In this way, we can implement the KNN Classification algorithm. Let us now move to its implementation with a real world example in the next section."
},
{
"code": null,
"e": 2066,
"s": 1628,
"text": "To apply the KNN Classification model in practical use, I am using the same dataset used in building the Logistic Regression model. In this, we DMV Test dataset which has three columns. The first two columns consist of the two DMV written tests (DMV_Test_1 and DMV_Test_2) which are the independent variables and the last column consists of the dependent variable, Results which denote that the driver has got the license (1) or not (0)."
},
{
"code": null,
"e": 2302,
"s": 2066,
"text": "In this, we have to build a KNN Classification model using this data to predict if a driver who has taken the two DMV written tests will get the license or not using those marks obtained in their written tests and classify the results."
},
{
"code": null,
"e": 2420,
"s": 2302,
"text": "As always, the first step will always include importing the libraries which are the NumPy, Pandas and the Matplotlib."
},
{
"code": null,
"e": 2489,
"s": 2420,
"text": "import numpy as npimport matplotlib.pyplot as pltimport pandas as pd"
},
{
"code": null,
"e": 2757,
"s": 2489,
"text": "In this step, we shall get the dataset from my GitHub repository as “DMVWrittenTests.csv”. The variable X will store the two “DMV Tests ”and the variable Y will store the final output as “Results”. The dataset.head(5)is used to visualize the first 5 rows of the data."
},
{
"code": null,
"e": 3120,
"s": 2757,
"text": "dataset = pd.read_csv('https://raw.githubusercontent.com/mk-gurucharan/Classification/master/DMVWrittenTests.csv')X = dataset.iloc[:, [0, 1]].valuesy = dataset.iloc[:, 2].valuesdataset.head(5)>>DMV_Test_1 DMV_Test_2 Results34.623660 78.024693 030.286711 43.894998 035.847409 72.902198 060.182599 86.308552 179.032736 75.344376 1"
},
{
"code": null,
"e": 3481,
"s": 3120,
"text": "In this step, we have to split the dataset into the Training set, on which the Logistic Regression model will be trained and the Test set, on which the trained model will be applied to classify the results. In this the test_size=0.25 denotes that 25% of the data will be kept as the Test set and the remaining 75% will be used for training as the Training set."
},
{
"code": null,
"e": 3609,
"s": 3481,
"text": "from sklearn.model_selection import train_test_splitX_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.25)"
},
{
"code": null,
"e": 4056,
"s": 3609,
"text": "This is an additional step that is used to normalize the data within a particular range. It also aids in speeding up the calculations. As the data is widely varying, we use this function to limit the range of the data within a small limit ( -2,2). For example, the score 62.0730638 is normalized to -0.21231162 and the score 96.51142588 is normalized to 1.55187648. In this way, the scores of X_train and X_test are normalized to a smaller range."
},
{
"code": null,
"e": 4190,
"s": 4056,
"text": "from sklearn.preprocessing import StandardScalersc = StandardScaler()X_train = sc.fit_transform(X_train)X_test = sc.transform(X_test)"
},
{
"code": null,
"e": 4394,
"s": 4190,
"text": "In this step, the class KNeighborsClassifier is imported and is assigned to the variable “classifier”. The classifier.fit() function is fitted with X_train and Y_train on which the model will be trained."
},
{
"code": null,
"e": 4556,
"s": 4394,
"text": "from sklearn.neighbors import KNeighborsClassifierclassifier = KNeighborsClassifier(n_neighbors = 5, metric = 'minkowski', p = 2)classifier.fit(X_train, y_train)"
},
{
"code": null,
"e": 4701,
"s": 4556,
"text": "In this step, the classifier.predict() function is used to predict the values for the Test set and the values are stored to the variable y_pred."
},
{
"code": null,
"e": 4744,
"s": 4701,
"text": "y_pred = classifier.predict(X_test) y_pred"
},
{
"code": null,
"e": 4890,
"s": 4744,
"text": "This is a step that is mostly used in classification techniques. In this, we see the Accuracy of the trained model and plot the confusion matrix."
},
{
"code": null,
"e": 5087,
"s": 4890,
"text": "The confusion matrix is a table that is used to show the number of correct and incorrect predictions on a classification problem when the real values of the Test Set are known. It is of the format"
},
{
"code": null,
"e": 5147,
"s": 5087,
"text": "The True values are the number of correct predictions made."
},
{
"code": null,
"e": 5380,
"s": 5147,
"text": "from sklearn.metrics import confusion_matrixcm = confusion_matrix(y_test, y_pred)from sklearn.metrics import accuracy_score print (\"Accuracy : \", accuracy_score(y_test, y_pred))cm>>Accuracy : 0.92>>array([[11, 1], [ 1, 12]])"
},
{
"code": null,
"e": 5575,
"s": 5380,
"text": "From the above confusion matrix, we infer that, out of 25 test set data, 23 were correctly classified and 2 were incorrectly classified which is little better than the Logistic Regression model."
},
{
"code": null,
"e": 5727,
"s": 5575,
"text": "In this step, a Pandas DataFrame is created to compare the classified values of both the original Test set (y_test) and the predicted results (y_pred)."
},
{
"code": null,
"e": 6206,
"s": 5727,
"text": "df = pd.DataFrame({'Real Values':y_test, 'Predicted Values':y_pred})df>> Real Values Predicted Values0 00 11 10 00 01 11 10 00 01 10 01 01 11 10 00 00 01 11 11 11 10 01 11 10 0"
},
{
"code": null,
"e": 6410,
"s": 6206,
"text": "Though this visualization may not be of much use as it was with Regression, from this, we can see that the model is able to classify the test set values with a decent accuracy of 92% as calculated above."
},
{
"code": null,
"e": 6541,
"s": 6410,
"text": "In this last step, we visualize the results of the KNN Classification model on a graph that is plotted along with the two regions."
},
{
"code": null,
"e": 7311,
"s": 6541,
"text": "from matplotlib.colors import ListedColormapX_set, y_set = X_test, y_testX1, X2 = np.meshgrid(np.arange(start = X_set[:, 0].min() - 1, stop = X_set[:, 0].max() + 1, step = 0.01), np.arange(start = X_set[:, 1].min() - 1, stop = X_set[:, 1].max() + 1, step = 0.01))plt.contourf(X1, X2, classifier.predict(np.array([X1.ravel(), X2.ravel()]).T).reshape(X1.shape), alpha = 0.75, cmap = ListedColormap(('red', 'green')))plt.xlim(X1.min(), X1.max())plt.ylim(X2.min(), X2.max())for i, j in enumerate(np.unique(y_set)): plt.scatter(X_set[y_set == j, 0], X_set[y_set == j, 1], c = ListedColormap(('red', 'green'))(i), label = j)plt.title('KNN Classification')plt.xlabel('DMV_Test_1')plt.ylabel('DMV_Test_2')plt.legend()plt.show()"
},
{
"code": null,
"e": 7759,
"s": 7311,
"text": "In this graph, the value 1 (i.e, Yes) is plotted in “Red” color and the value 0 (i.e, No) is plotted in “Green” color. The KNN Classification model separates the two regions. It is not linear as the Logistic Regression model. Thus, any data with the two data points (DMV_Test_1 and DMV_Test_2) given, can be plotted on the graph and depending upon which region if falls in, the result (Getting the Driver’s License) can be classified as Yes or No."
},
{
"code": null,
"e": 7882,
"s": 7759,
"text": "As calculated above, we can see that there are two values in the test set, one on each region that are wrongly classified."
},
{
"code": null,
"e": 8099,
"s": 7882,
"text": "Thus in this story, we have successfully been able to build a KNN Classification Model that is able to predict if a person is able to get the driving license from their written examinations and visualize the results."
},
{
"code": null,
"e": 8241,
"s": 8099,
"text": "I am also attaching the link to my GitHub repository where you can download this Google Colab notebook and the data files for your reference."
},
{
"code": null,
"e": 8252,
"s": 8241,
"text": "github.com"
},
{
"code": null,
"e": 8340,
"s": 8252,
"text": "You can also find the explanation of the program for other Classification models below:"
},
{
"code": null,
"e": 8360,
"s": 8340,
"text": "Logistic Regression"
},
{
"code": null,
"e": 8402,
"s": 8360,
"text": "K-Nearest Neighbours (KNN) Classification"
},
{
"code": null,
"e": 8460,
"s": 8402,
"text": "Support Vector Machine (SVM) Classification (Coming Soon)"
},
{
"code": null,
"e": 8501,
"s": 8460,
"text": "Naive Bayes Classification (Coming Soon)"
},
{
"code": null,
"e": 8544,
"s": 8501,
"text": "Random Forest Classification (Coming Soon)"
}
] |
What is the difference between getWindowHandle() and getWindowHandles() methods in Selenium WebDriver? | There are difference between getWindowHandle() and getWindowHandles() methods in Selenium webdriver. The getWindowHandles
and getWindowHandle methods can be used to handle child windows. The getWindowHandles method is used to store all the opened window handles in the Set data structure.
The getWindowHandle method is used to store the window handle of the browser window in focus. We have to add import java.util.Set and import java.util.List statements to accommodate Set data structure in our code.
By default, the driver object can only access the elements of the parent window. To switch its focus from the parent to the child window, we shall take the help of the switchTo().window method and pass the window handle id of the child
window as an argument to the method. Then to move from the child window to the parent window, we shall take the help of the switchTo().window method and pass the parent window handle id as an argument to the method.
Code Implementation.
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 java.util.Set;
public class CloseSpecificWindow {
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver",
"C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("https://secure.indeed.com/account/login");
//implicit wait
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
//window handle of parent window
String m = driver.getWindowHandle();
driver.findElement(By.id("login-google-button")).click();
// store window handles in Set
Set<String> w = driver.getWindowHandles();
// iterate window handles
for (String h: w)
{
// switching to each window
driver.switchTo().window(h);
String s= driver.getTitle();
// checking specific window title
if(s.equalsIgnoreCase("Sign in - Google Accounts"))
{
System.out.println("Window title to be closed: "+ driver.getTitle());
driver.close();
}
}
// switching parent window
driver.switchTo().window(m);
driver.quit();
}
} | [
{
"code": null,
"e": 1351,
"s": 1062,
"text": "There are difference between getWindowHandle() and getWindowHandles() methods in Selenium webdriver. The getWindowHandles\nand getWindowHandle methods can be used to handle child windows. The getWindowHandles method is used to store all the opened window handles in the Set data structure."
},
{
"code": null,
"e": 1565,
"s": 1351,
"text": "The getWindowHandle method is used to store the window handle of the browser window in focus. We have to add import java.util.Set and import java.util.List statements to accommodate Set data structure in our code."
},
{
"code": null,
"e": 2017,
"s": 1565,
"text": "By default, the driver object can only access the elements of the parent window. To switch its focus from the parent to the child window, we shall take the help of the switchTo().window method and pass the window handle id of the child\nwindow as an argument to the method. Then to move from the child window to the parent window, we shall take the help of the switchTo().window method and pass the parent window handle id as an argument to the method."
},
{
"code": null,
"e": 2038,
"s": 2017,
"text": "Code Implementation."
},
{
"code": null,
"e": 3423,
"s": 2038,
"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 java.util.Set;\npublic class CloseSpecificWindow {\n public static void main(String[] args) {\n System.setProperty(\"webdriver.chrome.driver\",\n \"C:\\\\Users\\\\ghs6kor\\\\Desktop\\\\Java\\\\chromedriver.exe\");\n WebDriver driver = new ChromeDriver();\n driver.get(\"https://secure.indeed.com/account/login\");\n\n //implicit wait\n driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);\n\n //window handle of parent window\n String m = driver.getWindowHandle();\n driver.findElement(By.id(\"login-google-button\")).click();\n\n // store window handles in Set\n Set<String> w = driver.getWindowHandles();\n\n // iterate window handles\n for (String h: w)\n {\n // switching to each window\n driver.switchTo().window(h);\n String s= driver.getTitle();\n\n // checking specific window title\n if(s.equalsIgnoreCase(\"Sign in - Google Accounts\"))\n {\n System.out.println(\"Window title to be closed: \"+ driver.getTitle());\n driver.close();\n }\n }\n\n // switching parent window\n driver.switchTo().window(m);\n driver.quit();\n }\n}"
}
] |
Solidity - Special Variables | Special variables are globally available variables and provides information about the blockchain. Following is the list of special variables −
blockhash(uint blockNumber) returns (bytes32)
Hash of the given block - only works for 256 most recent, excluding current, blocks.
block.coinbase (address payable)
Current block miner's address.
block.difficulty (uint)
current block difficulty.
block.gaslimit (uint)
Current block gaslimit.
block.number (uint)
Current block number.
block.timestamp
Current block timestamp as seconds since unix epoch.
gasleft() returns (uint256)
Remaining gas.
msg.data (bytes calldata)
Complete calldata.
msg.sender (address payable)
Sender of the message (current call).
msg.sig (bytes4)
First four bytes of the calldata (i.e. function identifier)
msg.value (uint)
Number of wei sent with the message.
now (uint)
Current block timestamp (alias for block.timestamp).
tx.gasprice (uint)
Gas price of the transaction.
tx.origin (address payable)
Sender of the transaction (full call chain).
Try the following code to see the use of msg, a special variable to get the sender address in Solidity.
pragma solidity ^0.5.0;
contract LedgerBalance {
mapping(address => uint) public balances;
function updateBalance(uint newBalance) public {
balances[msg.sender] = newBalance;
}
}
contract Updater {
function updateBalance() public returns (uint) {
LedgerBalance ledgerBalance = new LedgerBalance();
ledgerBalance.updateBalance(10);
return ledgerBalance.balances(address(this));
}
}
Run the above program using steps provided in Solidity First Application chapter.
First Click updateBalance Button to set the value as 10 then look into the logs which will show the decoded output as −
{
"0": "uint256: 10"
}
38 Lectures
4.5 hours
Abhilash Nelson
62 Lectures
8.5 hours
Frahaan Hussain
31 Lectures
3.5 hours
Swapnil Kole
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2698,
"s": 2555,
"text": "Special variables are globally available variables and provides information about the blockchain. Following is the list of special variables −"
},
{
"code": null,
"e": 2744,
"s": 2698,
"text": "blockhash(uint blockNumber) returns (bytes32)"
},
{
"code": null,
"e": 2829,
"s": 2744,
"text": "Hash of the given block - only works for 256 most recent, excluding current, blocks."
},
{
"code": null,
"e": 2862,
"s": 2829,
"text": "block.coinbase (address payable)"
},
{
"code": null,
"e": 2893,
"s": 2862,
"text": "Current block miner's address."
},
{
"code": null,
"e": 2917,
"s": 2893,
"text": "block.difficulty (uint)"
},
{
"code": null,
"e": 2943,
"s": 2917,
"text": "current block difficulty."
},
{
"code": null,
"e": 2965,
"s": 2943,
"text": "block.gaslimit (uint)"
},
{
"code": null,
"e": 2989,
"s": 2965,
"text": "Current block gaslimit."
},
{
"code": null,
"e": 3009,
"s": 2989,
"text": "block.number (uint)"
},
{
"code": null,
"e": 3031,
"s": 3009,
"text": "Current block number."
},
{
"code": null,
"e": 3047,
"s": 3031,
"text": "block.timestamp"
},
{
"code": null,
"e": 3100,
"s": 3047,
"text": "Current block timestamp as seconds since unix epoch."
},
{
"code": null,
"e": 3128,
"s": 3100,
"text": "gasleft() returns (uint256)"
},
{
"code": null,
"e": 3143,
"s": 3128,
"text": "Remaining gas."
},
{
"code": null,
"e": 3169,
"s": 3143,
"text": "msg.data (bytes calldata)"
},
{
"code": null,
"e": 3188,
"s": 3169,
"text": "Complete calldata."
},
{
"code": null,
"e": 3217,
"s": 3188,
"text": "msg.sender (address payable)"
},
{
"code": null,
"e": 3255,
"s": 3217,
"text": "Sender of the message (current call)."
},
{
"code": null,
"e": 3272,
"s": 3255,
"text": "msg.sig (bytes4)"
},
{
"code": null,
"e": 3332,
"s": 3272,
"text": "First four bytes of the calldata (i.e. function identifier)"
},
{
"code": null,
"e": 3349,
"s": 3332,
"text": "msg.value (uint)"
},
{
"code": null,
"e": 3386,
"s": 3349,
"text": "Number of wei sent with the message."
},
{
"code": null,
"e": 3397,
"s": 3386,
"text": "now (uint)"
},
{
"code": null,
"e": 3450,
"s": 3397,
"text": "Current block timestamp (alias for block.timestamp)."
},
{
"code": null,
"e": 3469,
"s": 3450,
"text": "tx.gasprice (uint)"
},
{
"code": null,
"e": 3499,
"s": 3469,
"text": "Gas price of the transaction."
},
{
"code": null,
"e": 3527,
"s": 3499,
"text": "tx.origin (address payable)"
},
{
"code": null,
"e": 3572,
"s": 3527,
"text": "Sender of the transaction (full call chain)."
},
{
"code": null,
"e": 3676,
"s": 3572,
"text": "Try the following code to see the use of msg, a special variable to get the sender address in Solidity."
},
{
"code": null,
"e": 4098,
"s": 3676,
"text": "pragma solidity ^0.5.0;\n\ncontract LedgerBalance {\n mapping(address => uint) public balances;\n\n function updateBalance(uint newBalance) public {\n balances[msg.sender] = newBalance;\n }\n}\ncontract Updater {\n function updateBalance() public returns (uint) {\n LedgerBalance ledgerBalance = new LedgerBalance();\n ledgerBalance.updateBalance(10);\n return ledgerBalance.balances(address(this));\n }\n}"
},
{
"code": null,
"e": 4180,
"s": 4098,
"text": "Run the above program using steps provided in Solidity First Application chapter."
},
{
"code": null,
"e": 4301,
"s": 4180,
"text": "First Click updateBalance Button to set the value as 10 then look into the logs which will show the decoded output as − "
},
{
"code": null,
"e": 4328,
"s": 4301,
"text": "{\n \"0\": \"uint256: 10\"\n}\n"
},
{
"code": null,
"e": 4363,
"s": 4328,
"text": "\n 38 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 4380,
"s": 4363,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 4415,
"s": 4380,
"text": "\n 62 Lectures \n 8.5 hours \n"
},
{
"code": null,
"e": 4432,
"s": 4415,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 4467,
"s": 4432,
"text": "\n 31 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 4481,
"s": 4467,
"text": " Swapnil Kole"
},
{
"code": null,
"e": 4488,
"s": 4481,
"text": " Print"
},
{
"code": null,
"e": 4499,
"s": 4488,
"text": " Add Notes"
}
] |
CSS Buttons - Social Buttons Usage | Social Buttons library is a set of CSS Buttons made in pure CSS and are based on Bootstrap and Font Awesome.
To load the bootstrap-social.css library, download the bootstrap-social.css from github and paste the following line in the <head> section of the webpage.
<head>
<link rel = "stylesheet" href = "bootstrap-social.css">
</head>
Create a button using html anchor tag and add styles btn, btn-block with social specifier btn-social.
<html>
<head>
<link rel = "stylesheet" href = "https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.3.0/css/font-awesome.min.css">
<link rel = "stylesheet" href = "http://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
<link rel = "stylesheet" href = "/css_buttons/bootstrap-social.css">
</head>
<body>
<a class = "btn btn-block btn-social btn-twitter">
<span class = "fa fa-twitter"></span>
Login with Twitter
</a>
</body>
</html>
It will produce the following output −
You can increase or decrease the size of an button by defining its size using CSS and using it along with the class name, as shown below. In the given example, we have changes four sizes.
<html>
<head>
<link rel = "stylesheet" href = "https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.3.0/css/font-awesome.min.css">
<link rel = "stylesheet" href = "http://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
<link rel = "stylesheet" href = "/css_buttons/bootstrap-social.css">
</head>
<body>
<a class = "btn btn-block btn-lg btn-social btn-twitter">
<span class = "fa fa-twitter"></span>
Login with Twitter
</a>
<a class = "btn btn-block btn-md btn-social btn-twitter">
<span class = "fa fa-twitter"></span>
Login with Twitter
</a>
<a class = "btn btn-block btn-sm btn-social btn-twitter">
<span class = "fa fa-twitter"></span>
Login with Twitter
</a>
<a class = "btn btn-block btn-xs btn-social btn-twitter">
<span class = "fa fa-twitter"></span>
Login with Twitter
</a>
</body>
</html>
It will produce the following output −
The following example shows how to choose icon only buttons.
<html>
<head>
<link rel = "stylesheet" href = "https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.3.0/css/font-awesome.min.css">
<link rel = "stylesheet" href = "http://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
<link rel = "stylesheet" href = "bootstrap-social.css">
</head>
<body>
<a class = "btn btn-social-icon btn-twitter">
<span class = "fa fa-twitter"></span>
</a>
</body>
</html>
It will produce the following output −
33 Lectures
2.5 hours
Anadi Sharma
26 Lectures
2.5 hours
Frahaan Hussain
44 Lectures
4.5 hours
DigiFisk (Programming Is Fun)
21 Lectures
2.5 hours
DigiFisk (Programming Is Fun)
51 Lectures
7.5 hours
DigiFisk (Programming Is Fun)
52 Lectures
4 hours
DigiFisk (Programming Is Fun)
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2007,
"s": 1898,
"text": "Social Buttons library is a set of CSS Buttons made in pure CSS and are based on Bootstrap and Font Awesome."
},
{
"code": null,
"e": 2162,
"s": 2007,
"text": "To load the bootstrap-social.css library, download the bootstrap-social.css from github and paste the following line in the <head> section of the webpage."
},
{
"code": null,
"e": 2237,
"s": 2162,
"text": "<head>\n <link rel = \"stylesheet\" href = \"bootstrap-social.css\">\n</head>\n"
},
{
"code": null,
"e": 2339,
"s": 2237,
"text": "Create a button using html anchor tag and add styles btn, btn-block with social specifier btn-social."
},
{
"code": null,
"e": 2852,
"s": 2339,
"text": "<html>\n <head>\n <link rel = \"stylesheet\" href = \"https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.3.0/css/font-awesome.min.css\">\n <link rel = \"stylesheet\" href = \"http://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css\">\n <link rel = \"stylesheet\" href = \"/css_buttons/bootstrap-social.css\">\n </head>\n \n <body>\n <a class = \"btn btn-block btn-social btn-twitter\">\n <span class = \"fa fa-twitter\"></span>\n Login with Twitter\n </a>\n </body>\n</html>"
},
{
"code": null,
"e": 2891,
"s": 2852,
"text": "It will produce the following output −"
},
{
"code": null,
"e": 3079,
"s": 2891,
"text": "You can increase or decrease the size of an button by defining its size using CSS and using it along with the class name, as shown below. In the given example, we have changes four sizes."
},
{
"code": null,
"e": 4049,
"s": 3079,
"text": "<html>\n <head>\n <link rel = \"stylesheet\" href = \"https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.3.0/css/font-awesome.min.css\">\n <link rel = \"stylesheet\" href = \"http://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css\">\n <link rel = \"stylesheet\" href = \"/css_buttons/bootstrap-social.css\">\n </head>\n \n <body>\n <a class = \"btn btn-block btn-lg btn-social btn-twitter\">\n <span class = \"fa fa-twitter\"></span>\n Login with Twitter\n </a>\n <a class = \"btn btn-block btn-md btn-social btn-twitter\">\n <span class = \"fa fa-twitter\"></span>\n Login with Twitter\n </a>\n <a class = \"btn btn-block btn-sm btn-social btn-twitter\">\n <span class = \"fa fa-twitter\"></span>\n Login with Twitter\n </a>\n <a class = \"btn btn-block btn-xs btn-social btn-twitter\">\n <span class = \"fa fa-twitter\"></span>\n Login with Twitter\n </a>\n </body>\n</html>"
},
{
"code": null,
"e": 4088,
"s": 4049,
"text": "It will produce the following output −"
},
{
"code": null,
"e": 4149,
"s": 4088,
"text": "The following example shows how to choose icon only buttons."
},
{
"code": null,
"e": 4620,
"s": 4149,
"text": "<html>\n <head>\n <link rel = \"stylesheet\" href = \"https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.3.0/css/font-awesome.min.css\">\n <link rel = \"stylesheet\" href = \"http://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css\">\n <link rel = \"stylesheet\" href = \"bootstrap-social.css\">\n </head>\n \n <body>\n <a class = \"btn btn-social-icon btn-twitter\">\n <span class = \"fa fa-twitter\"></span>\n </a> \n </body> \n</html>"
},
{
"code": null,
"e": 4659,
"s": 4620,
"text": "It will produce the following output −"
},
{
"code": null,
"e": 4694,
"s": 4659,
"text": "\n 33 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 4708,
"s": 4694,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 4743,
"s": 4708,
"text": "\n 26 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 4760,
"s": 4743,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 4795,
"s": 4760,
"text": "\n 44 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 4826,
"s": 4795,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 4861,
"s": 4826,
"text": "\n 21 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 4892,
"s": 4861,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 4927,
"s": 4892,
"text": "\n 51 Lectures \n 7.5 hours \n"
},
{
"code": null,
"e": 4958,
"s": 4927,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 4991,
"s": 4958,
"text": "\n 52 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 5022,
"s": 4991,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 5029,
"s": 5022,
"text": " Print"
},
{
"code": null,
"e": 5040,
"s": 5029,
"text": " Add Notes"
}
] |
Abstraction in R Programming - GeeksforGeeks | 11 Nov, 2020
People who’ve been using the R language for any period of time have likely grown to be conversant in passing features as arguments to other functions. However, people are a whole lot much less probably to go back functions from their personal custom code. This is simply too horrific because doing so can open up a whole new international of abstraction that may greatly lower the quantity and complexity of the code vital to finish sure styles of duties. Here we offer a few short examples of ways R programmers can make use of lexical closures to encapsulate both records and strategies.
To begin with, an easy instance, assume you want a function that provides add_2() to its argument. You could probably write something like this:
R
add_2 <- function(y) { 2 + y }
Which does precisely what you’ll anticipate:
> add_2(1:10)
[1] 3 4 5 6 7 8 9 10 11 12
Now suppose you need every other feature that rather provides 7 to its argument. The herbal issue to do could be to write down any other characteristic, much like add_2, where the 2 is replaced with a 7. But this would be grossly inefficient: if within the future you discover that you made a mistake and also you in truth want to multiply the values instead of adding them, you will be pressured to trade the code in places. In this trivial instance, that won’t be plenty of hassle, but for greater complicated projects, duplicating code is a recipe for catastrophe. A higher concept could be to put in writing a characteristic that takes one argument, x, that returns every other function which provides its argument, y, to x. In different words, something like this:
R
add_x <- function(x) { function(y) { x + y }}
Now, while you name add_x with an argument, you may get back a feature that does precisely what you need:
R
add_2 <- add_x(2)add_7 <- add_x(7)
> add_2(1:10)
[1] 3 4 5 6 7 8 9 10 11 12
> add_7(1:10)
[1] 8 9 10 11 12 13 14 15 16 17
So this doesn’t seem too earth-shattering. But if you look closely at the definition of add_x, you may notice something odd: how does the return characteristic realize in which to discover x when it’s referred to as at a later point?
It turns out that R is lexically scoped, which means that features deliver with them a connection with the environment within which they were described. In this case, when you call add_x, the x argument you offer receives attached to the environment for the return characteristic. In different phrases, on this simple instance, you may think about R as simply changing all instances of the x variable within the feature to be lower back with the value you specify whilst you known as add_x. Ok, so this may be a neat trick, however, how this can be used extra productively? For a slightly extra complicated instance, think you’re doing some complex bootstrapping, and, for efficiency, you pre-allocate container vectors to keep the results. This is easy if you have just a single vector of effects—all you need to do is take into account to iterate an index counter whenever you upload an end result to the vector.
R
for (i in 1:nboot) { bootmeans[i] <- mean(sample(data, length(data), replace = TRUE))}
> mean(data)
[1] 0.0196
> mean(bootmeans)
[1] 0.0188
But think you need to track several extraordinary statistics, every requiring you to maintain track of a unique index variable. If your bootstrapping ordinary is even a little bit complicated, this could be tedious and vulnerable to blunders. By the use of closures, you may summary away all of this bookkeeping. Here is a constructor function that wraps a pre-allocated container vector:
R
make_container <- function(n) { x <- numeric(n) i <- 1 function(value = NULL) { if (is.null(value)) { return(x) } else { x[i] <<- value i <<- i + 1 } }}
When you call make_container with an issue, it pre-allocates a numeric vector of the specified period, n, and returns a feature that permits you to feature statistics to that vector while not having to fear approximately keeping the music of an index. If you don’t the argument to that return feature is NULL, the entire vector is the lower back.
R
bootmeans <- make_container(nboot) for (i in 1:nboot)bootmeans(mean(sample(data, length(data), replace = TRUE)))
> mean(data)
[1] 0.0196
> mean(bootmeans())
[1] 0.0207
Here make_container is tremendously easy, but it may be as complicated as you need. For example, you could want to have the constructor function carry out some expensive calculations which you could instead no longer do on every occasion the character is known as. In reality, that is what I even have completed within the boolean3 package deal to decrease the range of calculations performed at each new release of the optimization habitual.
Picked
R-OOPs
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Change column name of a given DataFrame in R
How to Replace specific values in column in R DataFrame ?
Adding elements in a vector in R programming - append() method
How to change Row Names of DataFrame in R ?
Filter data by multiple conditions in R using Dplyr
Change Color of Bars in Barchart using ggplot2 in R
Loops in R (for, while, repeat)
Convert Factor to Numeric and Numeric to Factor in R Programming
How to Change Axis Scales in R Plots?
Group by function in R using Dplyr | [
{
"code": null,
"e": 28679,
"s": 28651,
"text": "\n11 Nov, 2020"
},
{
"code": null,
"e": 29269,
"s": 28679,
"text": "People who’ve been using the R language for any period of time have likely grown to be conversant in passing features as arguments to other functions. However, people are a whole lot much less probably to go back functions from their personal custom code. This is simply too horrific because doing so can open up a whole new international of abstraction that may greatly lower the quantity and complexity of the code vital to finish sure styles of duties. Here we offer a few short examples of ways R programmers can make use of lexical closures to encapsulate both records and strategies."
},
{
"code": null,
"e": 29414,
"s": 29269,
"text": "To begin with, an easy instance, assume you want a function that provides add_2() to its argument. You could probably write something like this:"
},
{
"code": null,
"e": 29416,
"s": 29414,
"text": "R"
},
{
"code": "add_2 <- function(y) { 2 + y }",
"e": 29447,
"s": 29416,
"text": null
},
{
"code": null,
"e": 29492,
"s": 29447,
"text": "Which does precisely what you’ll anticipate:"
},
{
"code": null,
"e": 29534,
"s": 29492,
"text": "> add_2(1:10)\n[1] 3 4 5 6 7 8 9 10 11 12\n"
},
{
"code": null,
"e": 30304,
"s": 29534,
"text": "Now suppose you need every other feature that rather provides 7 to its argument. The herbal issue to do could be to write down any other characteristic, much like add_2, where the 2 is replaced with a 7. But this would be grossly inefficient: if within the future you discover that you made a mistake and also you in truth want to multiply the values instead of adding them, you will be pressured to trade the code in places. In this trivial instance, that won’t be plenty of hassle, but for greater complicated projects, duplicating code is a recipe for catastrophe. A higher concept could be to put in writing a characteristic that takes one argument, x, that returns every other function which provides its argument, y, to x. In different words, something like this:"
},
{
"code": null,
"e": 30306,
"s": 30304,
"text": "R"
},
{
"code": "add_x <- function(x) { function(y) { x + y }}",
"e": 30354,
"s": 30306,
"text": null
},
{
"code": null,
"e": 30460,
"s": 30354,
"text": "Now, while you name add_x with an argument, you may get back a feature that does precisely what you need:"
},
{
"code": null,
"e": 30462,
"s": 30460,
"text": "R"
},
{
"code": "add_2 <- add_x(2)add_7 <- add_x(7)",
"e": 30497,
"s": 30462,
"text": null
},
{
"code": null,
"e": 30585,
"s": 30497,
"text": "> add_2(1:10)\n[1] 3 4 5 6 7 8 9 10 11 12\n> add_7(1:10)\n[1] 8 9 10 11 12 13 14 15 16 17\n"
},
{
"code": null,
"e": 30819,
"s": 30585,
"text": "So this doesn’t seem too earth-shattering. But if you look closely at the definition of add_x, you may notice something odd: how does the return characteristic realize in which to discover x when it’s referred to as at a later point?"
},
{
"code": null,
"e": 31734,
"s": 30819,
"text": "It turns out that R is lexically scoped, which means that features deliver with them a connection with the environment within which they were described. In this case, when you call add_x, the x argument you offer receives attached to the environment for the return characteristic. In different phrases, on this simple instance, you may think about R as simply changing all instances of the x variable within the feature to be lower back with the value you specify whilst you known as add_x. Ok, so this may be a neat trick, however, how this can be used extra productively? For a slightly extra complicated instance, think you’re doing some complex bootstrapping, and, for efficiency, you pre-allocate container vectors to keep the results. This is easy if you have just a single vector of effects—all you need to do is take into account to iterate an index counter whenever you upload an end result to the vector."
},
{
"code": null,
"e": 31736,
"s": 31734,
"text": "R"
},
{
"code": "for (i in 1:nboot) { bootmeans[i] <- mean(sample(data, length(data), replace = TRUE))}",
"e": 31852,
"s": 31736,
"text": null
},
{
"code": null,
"e": 31906,
"s": 31852,
"text": "> mean(data)\n[1] 0.0196\n> mean(bootmeans)\n[1] 0.0188\n"
},
{
"code": null,
"e": 32295,
"s": 31906,
"text": "But think you need to track several extraordinary statistics, every requiring you to maintain track of a unique index variable. If your bootstrapping ordinary is even a little bit complicated, this could be tedious and vulnerable to blunders. By the use of closures, you may summary away all of this bookkeeping. Here is a constructor function that wraps a pre-allocated container vector:"
},
{
"code": null,
"e": 32297,
"s": 32295,
"text": "R"
},
{
"code": "make_container <- function(n) { x <- numeric(n) i <- 1 function(value = NULL) { if (is.null(value)) { return(x) } else { x[i] <<- value i <<- i + 1 } }}",
"e": 32516,
"s": 32297,
"text": null
},
{
"code": null,
"e": 32863,
"s": 32516,
"text": "When you call make_container with an issue, it pre-allocates a numeric vector of the specified period, n, and returns a feature that permits you to feature statistics to that vector while not having to fear approximately keeping the music of an index. If you don’t the argument to that return feature is NULL, the entire vector is the lower back."
},
{
"code": null,
"e": 32865,
"s": 32863,
"text": "R"
},
{
"code": "bootmeans <- make_container(nboot) for (i in 1:nboot)bootmeans(mean(sample(data, length(data), replace = TRUE)))",
"e": 33001,
"s": 32865,
"text": null
},
{
"code": null,
"e": 33057,
"s": 33001,
"text": "> mean(data)\n[1] 0.0196\n> mean(bootmeans())\n[1] 0.0207\n"
},
{
"code": null,
"e": 33500,
"s": 33057,
"text": "Here make_container is tremendously easy, but it may be as complicated as you need. For example, you could want to have the constructor function carry out some expensive calculations which you could instead no longer do on every occasion the character is known as. In reality, that is what I even have completed within the boolean3 package deal to decrease the range of calculations performed at each new release of the optimization habitual."
},
{
"code": null,
"e": 33507,
"s": 33500,
"text": "Picked"
},
{
"code": null,
"e": 33514,
"s": 33507,
"text": "R-OOPs"
},
{
"code": null,
"e": 33525,
"s": 33514,
"text": "R Language"
},
{
"code": null,
"e": 33623,
"s": 33525,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 33632,
"s": 33623,
"text": "Comments"
},
{
"code": null,
"e": 33645,
"s": 33632,
"text": "Old Comments"
},
{
"code": null,
"e": 33690,
"s": 33645,
"text": "Change column name of a given DataFrame in R"
},
{
"code": null,
"e": 33748,
"s": 33690,
"text": "How to Replace specific values in column in R DataFrame ?"
},
{
"code": null,
"e": 33811,
"s": 33748,
"text": "Adding elements in a vector in R programming - append() method"
},
{
"code": null,
"e": 33855,
"s": 33811,
"text": "How to change Row Names of DataFrame in R ?"
},
{
"code": null,
"e": 33907,
"s": 33855,
"text": "Filter data by multiple conditions in R using Dplyr"
},
{
"code": null,
"e": 33959,
"s": 33907,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 33991,
"s": 33959,
"text": "Loops in R (for, while, repeat)"
},
{
"code": null,
"e": 34056,
"s": 33991,
"text": "Convert Factor to Numeric and Numeric to Factor in R Programming"
},
{
"code": null,
"e": 34094,
"s": 34056,
"text": "How to Change Axis Scales in R Plots?"
}
] |
Kotlin | Filtering Collections | 21 Feb, 2022
In Kotlin, filtering is a prominent task of collection processing. The filtering conditions are defined by predicates – lambda functions that take a collection element and return true when the given element matches the predicate, and false means it doesn’t match the predicate.
There are standard library contains number of functions that let you filter the collections in a single call.
These functions don’t change the contents of the original collection or available for immutable and mutable both.
We can assign it to a variable or chain the functions after filtering to operate the filtering result.
The basic function is filter() to be used for filtering.
When filter() function is called with a predicate, it returns the collection elements that match the predicate.
For List and Set, the resulting collection is also List but for Map it will return Map.
Kotlin program of using the filter function on list and Map collection –
Java
fun main(args: Array<String>){ //declaring a list of elements val list = listOf("geeks","for","geeks","hello","world") //filtering all words with length > 4 val longerThan4 = list.filter { it.length > 4 } println(longerThan4) //declaring a map of string to integers val numbersMap = mapOf("key13" to 10, "key25" to 20, "key34" to 30, "key45" to 40, "key55" to 50 ) //filtering the map with some predicates val filteredMap = numbersMap.filter { (key, value) -> key.endsWith("5") && value > 20} println(filteredMap)}
Output:
[geeks, geeks, hello, world]
{key45=40, key55=50}
If we want to filter using element index or position, we have to use filterIndexed().
filterIndexed() function takes a predicate with two arguments: index and the value of an element.
We can filter the collections by negative conditions by using filterNot().
Kotlin program of using the filterIndexed() and filterNot() functions –
Java
fun main(args: Array<String>) { val words = listOf("geek","for","geeks","all","world") //filtering a list by : words having length < 6 and index != 0 val filteredIndex = words.filterIndexed { index, s -> (index != 0) && (s.length < 6) } //filtering words having length >=3 using filterNot val filteredNot = words.filterNot { it.length <= 3 } println(filteredIndex) println(filteredNot)}
Output:
[for, geeks, all, world]
[geek, geeks, world]
There is another filtering function partition() which filters a collection by a predicate and separates all the elements, which don’t match the predicate and put in a different list. Basically, it returns a pair of list: the first list containing the elements that match the predicate and the second list contains all the element from the original collection which don’t match the predicate.Kotlin program of using partitioning –
Java
fun main(args: Array<String>) { val words = listOf("geek","for","geeks","hello","world") //partitioning the words by length > 4 and length <= 4 val (first, second) = words.partition { it.length > 4 } println(first) println(second)}
Output:
[geeks, hello, world]
[geek, for]
Some of the functions to test a predicate against the collection elements are following:
any() : It returns true if atleast one element matches the given predicate.
none() : It returns true if none of the elements match the given predicate.
all() : It returns true if all the elements of the collection match the given predicate.
Note: all() returns true when called with any valid predicate on an empty collection. This is known as vacuous truth. We can use any() and none() without a predicate, it will just check for the emptiness of the collection, i.e. any() will return true if collection has elements and false if its empty; none() do just opposite of any().Kotlin program of using any(), none() and all() functions –
Java
fun main(args: Array<String>) { val words = listOf("geeks","for","geeeks","hello","world") //checking if atleast one word ends with s or not println("Any element matches? "+words.any { it.endsWith("s") }) //checking if no word ends with a or not println("No element matches? "+words.none { it.endsWith("a") }) println("All element match? "+words.all { it.endsWith("d") }) //checking if all words end with d or not //when predicate is empty, it checks for emptiness println(words.any()) println(words.none()) //all function on an empty list println(emptyList<Int>().all { it > 5 }) // vacuous truth val empty = emptyList<String>() //any function on an empty list returns false println(empty.any()) //none function on an empty list returns true println(empty.none())}
Output:
Any element matches? true
No element matches? true
All element match? false
true
false
true
false
true
sagar0719kumar
Picked
Kotlin
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Add Views Dynamically and Store Data in Arraylist in Android?
How to Communicate Between Fragments in Android?
Retrofit with Kotlin Coroutine in Android
Suspend Function In Kotlin Coroutines
How to Get Current Location in Android?
Dagger Hilt in Android with Example
Scopes in Kotlin Coroutines
Kotlin extension function
Kotlin Sealed Classes
Singleton Class in Kotlin | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n21 Feb, 2022"
},
{
"code": null,
"e": 332,
"s": 52,
"text": "In Kotlin, filtering is a prominent task of collection processing. The filtering conditions are defined by predicates – lambda functions that take a collection element and return true when the given element matches the predicate, and false means it doesn’t match the predicate. "
},
{
"code": null,
"e": 442,
"s": 332,
"text": "There are standard library contains number of functions that let you filter the collections in a single call."
},
{
"code": null,
"e": 556,
"s": 442,
"text": "These functions don’t change the contents of the original collection or available for immutable and mutable both."
},
{
"code": null,
"e": 659,
"s": 556,
"text": "We can assign it to a variable or chain the functions after filtering to operate the filtering result."
},
{
"code": null,
"e": 720,
"s": 663,
"text": "The basic function is filter() to be used for filtering."
},
{
"code": null,
"e": 832,
"s": 720,
"text": "When filter() function is called with a predicate, it returns the collection elements that match the predicate."
},
{
"code": null,
"e": 920,
"s": 832,
"text": "For List and Set, the resulting collection is also List but for Map it will return Map."
},
{
"code": null,
"e": 995,
"s": 920,
"text": "Kotlin program of using the filter function on list and Map collection – "
},
{
"code": null,
"e": 1000,
"s": 995,
"text": "Java"
},
{
"code": "fun main(args: Array<String>){ //declaring a list of elements val list = listOf(\"geeks\",\"for\",\"geeks\",\"hello\",\"world\") //filtering all words with length > 4 val longerThan4 = list.filter { it.length > 4 } println(longerThan4) //declaring a map of string to integers val numbersMap = mapOf(\"key13\" to 10, \"key25\" to 20, \"key34\" to 30, \"key45\" to 40, \"key55\" to 50 ) //filtering the map with some predicates val filteredMap = numbersMap.filter { (key, value) -> key.endsWith(\"5\") && value > 20} println(filteredMap)}",
"e": 1563,
"s": 1000,
"text": null
},
{
"code": null,
"e": 1573,
"s": 1563,
"text": "Output: "
},
{
"code": null,
"e": 1623,
"s": 1573,
"text": "[geeks, geeks, hello, world]\n{key45=40, key55=50}"
},
{
"code": null,
"e": 1713,
"s": 1627,
"text": "If we want to filter using element index or position, we have to use filterIndexed()."
},
{
"code": null,
"e": 1811,
"s": 1713,
"text": "filterIndexed() function takes a predicate with two arguments: index and the value of an element."
},
{
"code": null,
"e": 1886,
"s": 1811,
"text": "We can filter the collections by negative conditions by using filterNot()."
},
{
"code": null,
"e": 1960,
"s": 1886,
"text": "Kotlin program of using the filterIndexed() and filterNot() functions – "
},
{
"code": null,
"e": 1965,
"s": 1960,
"text": "Java"
},
{
"code": "fun main(args: Array<String>) { val words = listOf(\"geek\",\"for\",\"geeks\",\"all\",\"world\") //filtering a list by : words having length < 6 and index != 0 val filteredIndex = words.filterIndexed { index, s -> (index != 0) && (s.length < 6) } //filtering words having length >=3 using filterNot val filteredNot = words.filterNot { it.length <= 3 } println(filteredIndex) println(filteredNot)}",
"e": 2384,
"s": 1965,
"text": null
},
{
"code": null,
"e": 2394,
"s": 2384,
"text": "Output: "
},
{
"code": null,
"e": 2440,
"s": 2394,
"text": "[for, geeks, all, world]\n[geek, geeks, world]"
},
{
"code": null,
"e": 2874,
"s": 2442,
"text": "There is another filtering function partition() which filters a collection by a predicate and separates all the elements, which don’t match the predicate and put in a different list. Basically, it returns a pair of list: the first list containing the elements that match the predicate and the second list contains all the element from the original collection which don’t match the predicate.Kotlin program of using partitioning – "
},
{
"code": null,
"e": 2879,
"s": 2874,
"text": "Java"
},
{
"code": "fun main(args: Array<String>) { val words = listOf(\"geek\",\"for\",\"geeks\",\"hello\",\"world\") //partitioning the words by length > 4 and length <= 4 val (first, second) = words.partition { it.length > 4 } println(first) println(second)}",
"e": 3129,
"s": 2879,
"text": null
},
{
"code": null,
"e": 3139,
"s": 3129,
"text": "Output: "
},
{
"code": null,
"e": 3173,
"s": 3139,
"text": "[geeks, hello, world]\n[geek, for]"
},
{
"code": null,
"e": 3266,
"s": 3175,
"text": "Some of the functions to test a predicate against the collection elements are following: "
},
{
"code": null,
"e": 3342,
"s": 3266,
"text": "any() : It returns true if atleast one element matches the given predicate."
},
{
"code": null,
"e": 3418,
"s": 3342,
"text": "none() : It returns true if none of the elements match the given predicate."
},
{
"code": null,
"e": 3507,
"s": 3418,
"text": "all() : It returns true if all the elements of the collection match the given predicate."
},
{
"code": null,
"e": 3904,
"s": 3507,
"text": "Note: all() returns true when called with any valid predicate on an empty collection. This is known as vacuous truth. We can use any() and none() without a predicate, it will just check for the emptiness of the collection, i.e. any() will return true if collection has elements and false if its empty; none() do just opposite of any().Kotlin program of using any(), none() and all() functions – "
},
{
"code": null,
"e": 3909,
"s": 3904,
"text": "Java"
},
{
"code": "fun main(args: Array<String>) { val words = listOf(\"geeks\",\"for\",\"geeeks\",\"hello\",\"world\") //checking if atleast one word ends with s or not println(\"Any element matches? \"+words.any { it.endsWith(\"s\") }) //checking if no word ends with a or not println(\"No element matches? \"+words.none { it.endsWith(\"a\") }) println(\"All element match? \"+words.all { it.endsWith(\"d\") }) //checking if all words end with d or not //when predicate is empty, it checks for emptiness println(words.any()) println(words.none()) //all function on an empty list println(emptyList<Int>().all { it > 5 }) // vacuous truth val empty = emptyList<String>() //any function on an empty list returns false println(empty.any()) //none function on an empty list returns true println(empty.none())}",
"e": 4735,
"s": 3909,
"text": null
},
{
"code": null,
"e": 4745,
"s": 4735,
"text": "Output: "
},
{
"code": null,
"e": 4848,
"s": 4745,
"text": "Any element matches? true\nNo element matches? true\nAll element match? false\ntrue\nfalse\ntrue\nfalse\ntrue"
},
{
"code": null,
"e": 4865,
"s": 4850,
"text": "sagar0719kumar"
},
{
"code": null,
"e": 4872,
"s": 4865,
"text": "Picked"
},
{
"code": null,
"e": 4879,
"s": 4872,
"text": "Kotlin"
},
{
"code": null,
"e": 4977,
"s": 4879,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5046,
"s": 4977,
"text": "How to Add Views Dynamically and Store Data in Arraylist in Android?"
},
{
"code": null,
"e": 5095,
"s": 5046,
"text": "How to Communicate Between Fragments in Android?"
},
{
"code": null,
"e": 5137,
"s": 5095,
"text": "Retrofit with Kotlin Coroutine in Android"
},
{
"code": null,
"e": 5175,
"s": 5137,
"text": "Suspend Function In Kotlin Coroutines"
},
{
"code": null,
"e": 5215,
"s": 5175,
"text": "How to Get Current Location in Android?"
},
{
"code": null,
"e": 5251,
"s": 5215,
"text": "Dagger Hilt in Android with Example"
},
{
"code": null,
"e": 5279,
"s": 5251,
"text": "Scopes in Kotlin Coroutines"
},
{
"code": null,
"e": 5305,
"s": 5279,
"text": "Kotlin extension function"
},
{
"code": null,
"e": 5327,
"s": 5305,
"text": "Kotlin Sealed Classes"
}
] |
Rearrange an array in order – smallest, largest, 2nd smallest, 2nd largest, .. | 27 Jun, 2022
Given an array of integers, the task is to print the array in the order – smallest number, the Largest number, 2nd smallest number, 2nd largest number, 3rd smallest number, 3rd largest number, and so on.....
Examples:
Input : arr[] = [5, 8, 1, 4, 2, 9, 3, 7, 6]
Output :arr[] = {1, 9, 2, 8, 3, 7, 4, 6, 5}
Input : arr[] = [1, 2, 3, 4]
Output :arr[] = {1, 4, 2, 3}
A simple solution is to first find the smallest element and swap it with the first element. Then find the largest element, swap it with the second element, and so on. The time complexity of this solution is O(n2).
An efficient solution is to use sorting.
Sort the elements of the array. Take two variables say i and j and point them to the first and last index of the array respectively. Now run a loop and store the elements in the array one by one by incrementing i and decrementing j.
Sort the elements of the array.
Take two variables say i and j and point them to the first and last index of the array respectively.
Now run a loop and store the elements in the array one by one by incrementing i and decrementing j.
Let’s take an array with input 5, 8, 1, 4, 2, 9, 3, 7, 6 and sort them so the array becomes 1, 2, 3, 4, 5, 6, 7, 8, 9. Now take two variables to say i and j and point them to the first and last index of the array respectively, run a loop, and store the value into a new array by incrementing I and decrementing j.get that the final result as 1 9 2 8 3 7 4 6 5.
The flowchart is as follows:
flowchart- rearrangearray
C++
Java
Python3
C#
PHP
Javascript
// C++ program to print the array in given order#include <bits/stdc++.h>using namespace std; // Function which arrange the array.void rearrangeArray(int arr[], int n){ // Sorting the array elements sort(arr, arr + n); int tempArr[n]; // To store modified array // Adding numbers from sorted array to // new array accordingly int ArrIndex = 0; // Traverse from begin and end simultaneously for (int i = 0, j = n - 1; i <= n / 2 || j > n / 2; i++, j--) { tempArr[ArrIndex] = arr[i]; ArrIndex++; tempArr[ArrIndex] = arr[j]; ArrIndex++; } // Modifying original array for (int i = 0; i < n; i++) arr[i] = tempArr[i];} // Driver Codeint main(){ int arr[] = { 5, 8, 1, 4, 2, 9, 3, 7, 6 }; int n = sizeof(arr) / sizeof(arr[0]); rearrangeArray(arr, n); for (int i = 0; i < n; i++) cout << arr[i] << " "; return 0;}
// Java program to print the array in given orderimport java.util.Arrays; public class GFG { // Function which arrange the array. static void rearrangeArray(int arr[], int n) { // Sorting the array elements Arrays.sort(arr); int[] tempArr = new int[n]; // To store modified array // Adding numbers from sorted array to // new array accordingly int ArrIndex = 0; // Traverse from begin and end simultaneously for (int i = 0, j = n-1; i <= n / 2 || j > n / 2; i++, j--) { if(ArrIndex < n) { tempArr[ArrIndex] = arr[i]; ArrIndex++; } if(ArrIndex < n) { tempArr[ArrIndex] = arr[j]; ArrIndex++; } } // Modifying original array for (int i = 0; i < n; i++) arr[i] = tempArr[i]; } // Driver Code public static void main(String args[]) { int arr[] = { 5, 8, 1, 4, 2, 9, 3, 7, 6 }; int n = arr.length; rearrangeArray(arr, n); for (int i = 0; i < n; i++) System.out.print(arr[i]+" "); }}// This code is contributed by Sumit Ghosh
# Python 3 program to print# the array in given order # Function which arrange the# array.def rearrangeArray(arr, n) : # Sorting the array elements arr.sort() # To store modified array tempArr = [0] * (n + 1) # Adding numbers from sorted # array to new array accordingly ArrIndex = 0 # Traverse from begin and end # simultaneously i = 0 j = n-1 while(i <= n // 2 or j > n // 2 ) : tempArr[ArrIndex] = arr[i] ArrIndex = ArrIndex + 1 tempArr[ArrIndex] = arr[j] ArrIndex = ArrIndex + 1 i = i + 1 j = j - 1 # Modifying original array for i in range(0, n) : arr[i] = tempArr[i] # Driver Codearr = [ 5, 8, 1, 4, 2, 9, 3, 7, 6 ]n = len(arr)rearrangeArray(arr, n) for i in range(0, n) : print( arr[i], end = " ") # This code is contributed by Nikita Tiwari.
// C# program to print the// array in given orderusing System; public class GFG { // Function which arrange the array. static void rearrangeArray(int []arr, int n) { // Sorting the array elements Array.Sort(arr); // To store modified array int []tempArr = new int[n]; // Adding numbers from sorted array // to new array accordingly int ArrIndex = 0; // Traverse from begin and end simultaneously for (int i = 0, j = n-1; i <= n / 2 || j > n / 2; i++, j--) { if(ArrIndex < n) { tempArr[ArrIndex] = arr[i]; ArrIndex++; } if(ArrIndex < n) { tempArr[ArrIndex] = arr[j]; ArrIndex++; } } // Modifying original array for (int i = 0; i < n; i++) arr[i] = tempArr[i]; } // Driver Code public static void Main(String []args) { int []arr = {5, 8, 1, 4, 2, 9, 3, 7, 6}; int n = arr.Length; rearrangeArray(arr, n); for (int i = 0; i < n; i++) Console.Write(arr[i] + " "); }} // This code is contributed by Nitin Mittal.
<?php// PHP program to print// the array in given order // Function which// arrange the array.function rearrangeArray($arr, $n){ // Sorting the // array elements sort($arr); // To store modified array $tempArr = array($n); // Adding numbers from // sorted array to new // array accordingly $ArrIndex = 0; // Traverse from begin // and end simultaneously for ($i = 0, $j = $n - 1; $i <= $n / 2 || $j > $n / 2; $i++, $j--) { $tempArr[$ArrIndex] = $arr[$i]; $ArrIndex++; $tempArr[$ArrIndex] = $arr[$j]; $ArrIndex++; } // Modifying original array for ($i = 0; $i < $n; $i++) $arr[$i] = $tempArr[$i]; for ($i = 0; $i < $n; $i++) echo $arr[$i] . " ";} // Driver Code$arr = array(5, 8, 1, 4, 2, 9, 3, 7, 6 );$n = count($arr) ;rearrangeArray($arr, $n); // This code is contributed// by Sam007?>
<script> // Javascript program to print the// array in given order // Function which arrange the array.function rearrangeArray(arr, n){ // Sorting the array elements arr.sort(); // To store modified array let tempArr = new Array(n); // Adding numbers from sorted array // to new array accordingly let ArrIndex = 0; // Traverse from begin and end simultaneously for (let i = 0, j = n-1; i <= n / 2 || j > n / 2; i++, j--) { if(ArrIndex < n) { tempArr[ArrIndex] = arr[i]; ArrIndex++; } if(ArrIndex < n) { tempArr[ArrIndex] = arr[j]; ArrIndex++; } } // Modifying original array for (let i = 0; i < n; i++) arr[i] = tempArr[i];} // Driver Code let arr =[5, 8, 1, 4, 2, 9, 3, 7, 6]let n = arr.length;rearrangeArray(arr, n); for (let i = 0; i < n; i++) document.write(arr[i] + " "); </script>
1 9 2 8 3 7 4 6 5
Time Complexity: O(n log n), Auxiliary Space: O(n)
This article is contributed by Ayush Saxena. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or if you want to share more information about the topic discussed above.
nitin mittal
Sam007
mohit kumar 29
sweetyty
khushboogoyal499
guptavivek0503
array-rearrange
Arrays
Sorting
Arrays
Sorting
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
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
Merge Sort
Bubble Sort Algorithm
QuickSort
Insertion Sort
Selection Sort Algorithm | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n27 Jun, 2022"
},
{
"code": null,
"e": 260,
"s": 52,
"text": "Given an array of integers, the task is to print the array in the order – smallest number, the Largest number, 2nd smallest number, 2nd largest number, 3rd smallest number, 3rd largest number, and so on....."
},
{
"code": null,
"e": 272,
"s": 260,
"text": "Examples: "
},
{
"code": null,
"e": 419,
"s": 272,
"text": "Input : arr[] = [5, 8, 1, 4, 2, 9, 3, 7, 6]\nOutput :arr[] = {1, 9, 2, 8, 3, 7, 4, 6, 5}\n\nInput : arr[] = [1, 2, 3, 4]\nOutput :arr[] = {1, 4, 2, 3}"
},
{
"code": null,
"e": 633,
"s": 419,
"text": "A simple solution is to first find the smallest element and swap it with the first element. Then find the largest element, swap it with the second element, and so on. The time complexity of this solution is O(n2)."
},
{
"code": null,
"e": 675,
"s": 633,
"text": "An efficient solution is to use sorting. "
},
{
"code": null,
"e": 908,
"s": 675,
"text": "Sort the elements of the array. Take two variables say i and j and point them to the first and last index of the array respectively. Now run a loop and store the elements in the array one by one by incrementing i and decrementing j."
},
{
"code": null,
"e": 941,
"s": 908,
"text": "Sort the elements of the array. "
},
{
"code": null,
"e": 1043,
"s": 941,
"text": "Take two variables say i and j and point them to the first and last index of the array respectively. "
},
{
"code": null,
"e": 1143,
"s": 1043,
"text": "Now run a loop and store the elements in the array one by one by incrementing i and decrementing j."
},
{
"code": null,
"e": 1505,
"s": 1143,
"text": "Let’s take an array with input 5, 8, 1, 4, 2, 9, 3, 7, 6 and sort them so the array becomes 1, 2, 3, 4, 5, 6, 7, 8, 9. Now take two variables to say i and j and point them to the first and last index of the array respectively, run a loop, and store the value into a new array by incrementing I and decrementing j.get that the final result as 1 9 2 8 3 7 4 6 5. "
},
{
"code": null,
"e": 1534,
"s": 1505,
"text": "The flowchart is as follows:"
},
{
"code": null,
"e": 1560,
"s": 1534,
"text": "flowchart- rearrangearray"
},
{
"code": null,
"e": 1564,
"s": 1560,
"text": "C++"
},
{
"code": null,
"e": 1569,
"s": 1564,
"text": "Java"
},
{
"code": null,
"e": 1577,
"s": 1569,
"text": "Python3"
},
{
"code": null,
"e": 1580,
"s": 1577,
"text": "C#"
},
{
"code": null,
"e": 1584,
"s": 1580,
"text": "PHP"
},
{
"code": null,
"e": 1595,
"s": 1584,
"text": "Javascript"
},
{
"code": "// C++ program to print the array in given order#include <bits/stdc++.h>using namespace std; // Function which arrange the array.void rearrangeArray(int arr[], int n){ // Sorting the array elements sort(arr, arr + n); int tempArr[n]; // To store modified array // Adding numbers from sorted array to // new array accordingly int ArrIndex = 0; // Traverse from begin and end simultaneously for (int i = 0, j = n - 1; i <= n / 2 || j > n / 2; i++, j--) { tempArr[ArrIndex] = arr[i]; ArrIndex++; tempArr[ArrIndex] = arr[j]; ArrIndex++; } // Modifying original array for (int i = 0; i < n; i++) arr[i] = tempArr[i];} // Driver Codeint main(){ int arr[] = { 5, 8, 1, 4, 2, 9, 3, 7, 6 }; int n = sizeof(arr) / sizeof(arr[0]); rearrangeArray(arr, n); for (int i = 0; i < n; i++) cout << arr[i] << \" \"; return 0;}",
"e": 2505,
"s": 1595,
"text": null
},
{
"code": "// Java program to print the array in given orderimport java.util.Arrays; public class GFG { // Function which arrange the array. static void rearrangeArray(int arr[], int n) { // Sorting the array elements Arrays.sort(arr); int[] tempArr = new int[n]; // To store modified array // Adding numbers from sorted array to // new array accordingly int ArrIndex = 0; // Traverse from begin and end simultaneously for (int i = 0, j = n-1; i <= n / 2 || j > n / 2; i++, j--) { if(ArrIndex < n) { tempArr[ArrIndex] = arr[i]; ArrIndex++; } if(ArrIndex < n) { tempArr[ArrIndex] = arr[j]; ArrIndex++; } } // Modifying original array for (int i = 0; i < n; i++) arr[i] = tempArr[i]; } // Driver Code public static void main(String args[]) { int arr[] = { 5, 8, 1, 4, 2, 9, 3, 7, 6 }; int n = arr.length; rearrangeArray(arr, n); for (int i = 0; i < n; i++) System.out.print(arr[i]+\" \"); }}// This code is contributed by Sumit Ghosh",
"e": 3798,
"s": 2505,
"text": null
},
{
"code": "# Python 3 program to print# the array in given order # Function which arrange the# array.def rearrangeArray(arr, n) : # Sorting the array elements arr.sort() # To store modified array tempArr = [0] * (n + 1) # Adding numbers from sorted # array to new array accordingly ArrIndex = 0 # Traverse from begin and end # simultaneously i = 0 j = n-1 while(i <= n // 2 or j > n // 2 ) : tempArr[ArrIndex] = arr[i] ArrIndex = ArrIndex + 1 tempArr[ArrIndex] = arr[j] ArrIndex = ArrIndex + 1 i = i + 1 j = j - 1 # Modifying original array for i in range(0, n) : arr[i] = tempArr[i] # Driver Codearr = [ 5, 8, 1, 4, 2, 9, 3, 7, 6 ]n = len(arr)rearrangeArray(arr, n) for i in range(0, n) : print( arr[i], end = \" \") # This code is contributed by Nikita Tiwari.",
"e": 4674,
"s": 3798,
"text": null
},
{
"code": "// C# program to print the// array in given orderusing System; public class GFG { // Function which arrange the array. static void rearrangeArray(int []arr, int n) { // Sorting the array elements Array.Sort(arr); // To store modified array int []tempArr = new int[n]; // Adding numbers from sorted array // to new array accordingly int ArrIndex = 0; // Traverse from begin and end simultaneously for (int i = 0, j = n-1; i <= n / 2 || j > n / 2; i++, j--) { if(ArrIndex < n) { tempArr[ArrIndex] = arr[i]; ArrIndex++; } if(ArrIndex < n) { tempArr[ArrIndex] = arr[j]; ArrIndex++; } } // Modifying original array for (int i = 0; i < n; i++) arr[i] = tempArr[i]; } // Driver Code public static void Main(String []args) { int []arr = {5, 8, 1, 4, 2, 9, 3, 7, 6}; int n = arr.Length; rearrangeArray(arr, n); for (int i = 0; i < n; i++) Console.Write(arr[i] + \" \"); }} // This code is contributed by Nitin Mittal.",
"e": 5963,
"s": 4674,
"text": null
},
{
"code": "<?php// PHP program to print// the array in given order // Function which// arrange the array.function rearrangeArray($arr, $n){ // Sorting the // array elements sort($arr); // To store modified array $tempArr = array($n); // Adding numbers from // sorted array to new // array accordingly $ArrIndex = 0; // Traverse from begin // and end simultaneously for ($i = 0, $j = $n - 1; $i <= $n / 2 || $j > $n / 2; $i++, $j--) { $tempArr[$ArrIndex] = $arr[$i]; $ArrIndex++; $tempArr[$ArrIndex] = $arr[$j]; $ArrIndex++; } // Modifying original array for ($i = 0; $i < $n; $i++) $arr[$i] = $tempArr[$i]; for ($i = 0; $i < $n; $i++) echo $arr[$i] . \" \";} // Driver Code$arr = array(5, 8, 1, 4, 2, 9, 3, 7, 6 );$n = count($arr) ;rearrangeArray($arr, $n); // This code is contributed// by Sam007?>",
"e": 6884,
"s": 5963,
"text": null
},
{
"code": "<script> // Javascript program to print the// array in given order // Function which arrange the array.function rearrangeArray(arr, n){ // Sorting the array elements arr.sort(); // To store modified array let tempArr = new Array(n); // Adding numbers from sorted array // to new array accordingly let ArrIndex = 0; // Traverse from begin and end simultaneously for (let i = 0, j = n-1; i <= n / 2 || j > n / 2; i++, j--) { if(ArrIndex < n) { tempArr[ArrIndex] = arr[i]; ArrIndex++; } if(ArrIndex < n) { tempArr[ArrIndex] = arr[j]; ArrIndex++; } } // Modifying original array for (let i = 0; i < n; i++) arr[i] = tempArr[i];} // Driver Code let arr =[5, 8, 1, 4, 2, 9, 3, 7, 6]let n = arr.length;rearrangeArray(arr, n); for (let i = 0; i < n; i++) document.write(arr[i] + \" \"); </script>",
"e": 7867,
"s": 6884,
"text": null
},
{
"code": null,
"e": 7886,
"s": 7867,
"text": "1 9 2 8 3 7 4 6 5 "
},
{
"code": null,
"e": 7937,
"s": 7886,
"text": "Time Complexity: O(n log n), Auxiliary Space: O(n)"
},
{
"code": null,
"e": 8233,
"s": 7937,
"text": "This article is contributed by Ayush Saxena. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 8362,
"s": 8233,
"text": "Please write comments if you find anything incorrect, or if you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 8375,
"s": 8362,
"text": "nitin mittal"
},
{
"code": null,
"e": 8382,
"s": 8375,
"text": "Sam007"
},
{
"code": null,
"e": 8397,
"s": 8382,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 8406,
"s": 8397,
"text": "sweetyty"
},
{
"code": null,
"e": 8423,
"s": 8406,
"text": "khushboogoyal499"
},
{
"code": null,
"e": 8438,
"s": 8423,
"text": "guptavivek0503"
},
{
"code": null,
"e": 8454,
"s": 8438,
"text": "array-rearrange"
},
{
"code": null,
"e": 8461,
"s": 8454,
"text": "Arrays"
},
{
"code": null,
"e": 8469,
"s": 8461,
"text": "Sorting"
},
{
"code": null,
"e": 8476,
"s": 8469,
"text": "Arrays"
},
{
"code": null,
"e": 8484,
"s": 8476,
"text": "Sorting"
},
{
"code": null,
"e": 8582,
"s": 8484,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 8597,
"s": 8582,
"text": "Arrays in Java"
},
{
"code": null,
"e": 8643,
"s": 8597,
"text": "Write a program to reverse an array or string"
},
{
"code": null,
"e": 8711,
"s": 8643,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 8755,
"s": 8711,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 8787,
"s": 8755,
"text": "Largest Sum Contiguous Subarray"
},
{
"code": null,
"e": 8798,
"s": 8787,
"text": "Merge Sort"
},
{
"code": null,
"e": 8820,
"s": 8798,
"text": "Bubble Sort Algorithm"
},
{
"code": null,
"e": 8830,
"s": 8820,
"text": "QuickSort"
},
{
"code": null,
"e": 8845,
"s": 8830,
"text": "Insertion Sort"
}
] |
Noise removal using Median filter in C++ | 18 Jan, 2022
Median filtering is a nonlinear process useful in reducing impulsive, or salt-and-pepper noise. The median filter is also used to preserve edge properties while reducing the noise. Also, the smoothing techniques, like Gaussian blur is also used to reduce noise but it can’t preserve the edge properties. The median filter is widely used in digital image processing just because it preserves edge properties.
Approach :
Store the pixel values of input image in an array.
For each pixel value store all the neighbor pixel value including that cell in a new array (called window).
Sort the window array.
Median of window array is used to store output image pixel intensity.
Boundary Issues Example: 2D Median filtering example using a 3 x 3 sampling window: Extending border values outside with values at the boundary.
Edge preservation : All smoothing techniques are used to remove noise. The median filter is also one kind of smoothing technique like Gaussian filter, but the only difference between the median filter and Gaussian filter is that the median filter preserves edge property while Gaussian filter does not. Edge preservation is an important property because edges are important for visual appearance. For edge preservation property median filter is widely used in digital image processing.
C++ implementation of median filter algorithm.
C++
#include <iostream>#include <fstream>#include <sstream>using namespace std; /* Function to sort an array using insertion sort*/void insertionSort(int arr[], int n){ int i, key, j; for (i = 1; i < n; i++) { key = arr[i]; j = i - 1; /* Move elements of arr[0..i-1], that are greater than key, to one position ahead of their current position */ while (j >= 0 && arr[j] > key) { arr[j + 1] = arr[j]; j = j - 1; } arr[j + 1] = key; }} int array[2000][2000];int arr[2000][2000];int main(){ int window[9],row = 0, col = 0, numrows = 0, numcols = 0,MAX=0; ifstream infile("Saltpepper.pgm"); stringstream ss; string inputLine = ""; // First line : version getline(infile,inputLine); if(inputLine.compare("P2") != 0) cerr << "Version error" << endl; else cout << "Version : " << inputLine << endl; // Continue with a stringstream ss << infile.rdbuf(); // Secondline : size of image ss >> numcols >> numrows >> MAX; //print total number of rows, columns and maximum intensity of image cout << numcols << " columns and " << numrows << " rows" <<endl<<" Maximum Intensity "<< MAX <<endl; //Initialize a new array of same size of image with 0 for(row = 0; row <= numrows; ++row) array[row][0]=0; for( col = 0; col<=numcols; ++col ) array[0][col]=0; // Following lines : data for(row = 1; row <= numrows; ++row) { for (col = 1; col <= numcols; ++col) { //original data store in new array ss >> array[row][col]; } } // Now print the array to see the result for(row = 1; row <= numrows; ++row) { for(col = 1; col <= numcols; ++col) { //neighbor pixel values are stored in window including this pixel window[0] = array[row-1][col-1]; window[1] = array[row-1][col]; window[2] = array[row-1][col+1]; window[3] = array[row][col-1]; window[4] = array[row][col]; window[5] = array[row][col+1]; window[6] = array[row+1][col-1]; window[7] = array[row+1][col]; window[8] = array[row+1][col+1]; //sort window array insertionSort(window,9); //put the median to the new array arr[row][col]=window[4]; } } ofstream outfile; //new file open to store the output image outfile.open("Medianfilter.pnm"); outfile<<"P2"<<endl; outfile<<numcols<<" "<<numrows<<endl; outfile<<"255"<<endl; for(row = 1; row <= numrows; ++row) { for (col = 1; col <= numcols; ++col) { //store resultant pixel values to the output file outfile << arr[row][col]<<" "; } } outfile.close(); infile.close(); return 0 ;}
Input Image
Output Image
arorakashish0911
sumitgumber28
Image-Processing
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n18 Jan, 2022"
},
{
"code": null,
"e": 460,
"s": 52,
"text": "Median filtering is a nonlinear process useful in reducing impulsive, or salt-and-pepper noise. The median filter is also used to preserve edge properties while reducing the noise. Also, the smoothing techniques, like Gaussian blur is also used to reduce noise but it can’t preserve the edge properties. The median filter is widely used in digital image processing just because it preserves edge properties."
},
{
"code": null,
"e": 472,
"s": 460,
"text": "Approach : "
},
{
"code": null,
"e": 523,
"s": 472,
"text": "Store the pixel values of input image in an array."
},
{
"code": null,
"e": 631,
"s": 523,
"text": "For each pixel value store all the neighbor pixel value including that cell in a new array (called window)."
},
{
"code": null,
"e": 654,
"s": 631,
"text": "Sort the window array."
},
{
"code": null,
"e": 724,
"s": 654,
"text": "Median of window array is used to store output image pixel intensity."
},
{
"code": null,
"e": 871,
"s": 724,
"text": "Boundary Issues Example: 2D Median filtering example using a 3 x 3 sampling window: Extending border values outside with values at the boundary. "
},
{
"code": null,
"e": 1358,
"s": 871,
"text": "Edge preservation : All smoothing techniques are used to remove noise. The median filter is also one kind of smoothing technique like Gaussian filter, but the only difference between the median filter and Gaussian filter is that the median filter preserves edge property while Gaussian filter does not. Edge preservation is an important property because edges are important for visual appearance. For edge preservation property median filter is widely used in digital image processing. "
},
{
"code": null,
"e": 1406,
"s": 1358,
"text": "C++ implementation of median filter algorithm. "
},
{
"code": null,
"e": 1410,
"s": 1406,
"text": "C++"
},
{
"code": "#include <iostream>#include <fstream>#include <sstream>using namespace std; /* Function to sort an array using insertion sort*/void insertionSort(int arr[], int n){ int i, key, j; for (i = 1; i < n; i++) { key = arr[i]; j = i - 1; /* Move elements of arr[0..i-1], that are greater than key, to one position ahead of their current position */ while (j >= 0 && arr[j] > key) { arr[j + 1] = arr[j]; j = j - 1; } arr[j + 1] = key; }} int array[2000][2000];int arr[2000][2000];int main(){ int window[9],row = 0, col = 0, numrows = 0, numcols = 0,MAX=0; ifstream infile(\"Saltpepper.pgm\"); stringstream ss; string inputLine = \"\"; // First line : version getline(infile,inputLine); if(inputLine.compare(\"P2\") != 0) cerr << \"Version error\" << endl; else cout << \"Version : \" << inputLine << endl; // Continue with a stringstream ss << infile.rdbuf(); // Secondline : size of image ss >> numcols >> numrows >> MAX; //print total number of rows, columns and maximum intensity of image cout << numcols << \" columns and \" << numrows << \" rows\" <<endl<<\" Maximum Intensity \"<< MAX <<endl; //Initialize a new array of same size of image with 0 for(row = 0; row <= numrows; ++row) array[row][0]=0; for( col = 0; col<=numcols; ++col ) array[0][col]=0; // Following lines : data for(row = 1; row <= numrows; ++row) { for (col = 1; col <= numcols; ++col) { //original data store in new array ss >> array[row][col]; } } // Now print the array to see the result for(row = 1; row <= numrows; ++row) { for(col = 1; col <= numcols; ++col) { //neighbor pixel values are stored in window including this pixel window[0] = array[row-1][col-1]; window[1] = array[row-1][col]; window[2] = array[row-1][col+1]; window[3] = array[row][col-1]; window[4] = array[row][col]; window[5] = array[row][col+1]; window[6] = array[row+1][col-1]; window[7] = array[row+1][col]; window[8] = array[row+1][col+1]; //sort window array insertionSort(window,9); //put the median to the new array arr[row][col]=window[4]; } } ofstream outfile; //new file open to store the output image outfile.open(\"Medianfilter.pnm\"); outfile<<\"P2\"<<endl; outfile<<numcols<<\" \"<<numrows<<endl; outfile<<\"255\"<<endl; for(row = 1; row <= numrows; ++row) { for (col = 1; col <= numcols; ++col) { //store resultant pixel values to the output file outfile << arr[row][col]<<\" \"; } } outfile.close(); infile.close(); return 0 ;}",
"e": 4284,
"s": 1410,
"text": null
},
{
"code": null,
"e": 4297,
"s": 4284,
"text": "Input Image "
},
{
"code": null,
"e": 4311,
"s": 4297,
"text": "Output Image "
},
{
"code": null,
"e": 4330,
"s": 4313,
"text": "arorakashish0911"
},
{
"code": null,
"e": 4344,
"s": 4330,
"text": "sumitgumber28"
},
{
"code": null,
"e": 4361,
"s": 4344,
"text": "Image-Processing"
},
{
"code": null,
"e": 4368,
"s": 4361,
"text": "Python"
}
] |
Proof that Hamiltonian Path is NP-Complete | 01 Jun, 2022
Prerequisite : NP-Completeness The class of languages for which membership can be decided quickly fall in the class of P and The class of languages for which membership can be verified quickly fall in the class of NP(stands for problem solved in Non-deterministic Turing Machine in polynomial time). In straight words, every NP problem has its own polynomial-time verifier. A verifier for a language A is an algorithm V, where
A = {w | V accepts (w, c) for some string c}
where c is certificate or proof that w is a member of A.
We are interested in NP-Complete problems. NP-Complete problem is defined as follows:
(1)The problem itself is in NP class.
(2)All other problems in NP class can be polynomial time reducible to that.
(B is polynomial time reducible to C is denoted as )
If the 2nd condition is only satisfied then the problem is called NP-Hard. But it is not possible to reduce every NP problem into another NP problem to show its NP-Completeness all the time. That is why if we want to show a problem is NP-Complete we just show that the problem is in NP and any NP-Complete problem is reducible to that then we are done, i.e. if B is NP-Complete and for C in NP, then C is NP-Complete. We have to show Hamiltonian Path is NP-Complete. Hamiltonian Path or HAMPATH in a directed graph G is a directed path that goes through each node exactly once. We Consider the problem of testing whether a directed graph contain a Hamiltonian path connecting two specified nodes, i.e.
HAMPATH = {(G, s, t) | G is directed graph with a Hamiltonian path from s to t}
To prove HAMPATH is NP-Complete we have to prove that HAMPATH is in NP. To prove HAMPATH is in NP we must have a polynomial-time verifier. Even though we don’t have a fast polynomial time algorithm to determine whether a graph contains a HAMPATH or not, if such a path is discovered somehow (maybe with exponential time brute force searching) we could easily-work it out whether the path is HAMPATH or not, in polynomial time. Here the certificate will be a Hamiltonian path from s to t itself in G if exists. So HAMPATH is in NP proved. So, now we have to show that every problem to NP class is polynomial time reducible to HAMPATH to show its NP-Completeness. Rather we shall show 3SAT (A NP-Complete problem proved previously from SAT(Circuit Satisfiability Problem)) is polynomial time reducible to HAMPATH. We will convert a given cnf (Conjunctive Normal Form) form to a graph where gadgets (structure to simulate variables and clauses) will mimic the variables and clauses (several literals or variables connected with ). We have to prove now For each 3-cnf formula we will show how to build graph G with s and t, where a Hamiltonian path exists between s and t iff is satisfiable. We start with a 3-cnf formula containing k clauses,
where each is a literal or . Let be the l variables of .Now we show how to convert to a graph G. The graph G that we construct has various parts to represent the variables and clauses that appear in . We represent each variable with a diamond-shaped structure that contains a horizontal row of nodes as shown in following figure. We specify the number of nodes that appear in the horizontal row later. The following figure depicts the global structure of G. It shows all the elements of G and their relationships, except the edges that represent the relationship of the variables to the clauses that contain them. Each diamond structure contains a horizontal row of nodes connected by edges running in both directions. The horizontal row contains 2k nodes (as 2 nodes for each clause) plus, k-1 extra nodes in between every two nodes for a clause plus, 2 nodes on the ends belonging to the diamonds; total 3k+1 nodes. Following diagram gives a clear picture. If variable appears in clause , we add the following two edges from the jth pair in the ith diamond to the jth clause node. If appears in clause c_j, we add two edges from the jth pair in the ith diamond to the jth clause node, as in the following figure. After we add all the edges corresponding to each occurrence of or in each clause, the construction of G is complete. To show its correctness we will prove if is satisfiable, a Hamiltonian path exists from s to t and conversely, if such a path exists is satisfiable. Suppose that is satisfiable. To demonstrate a Hamiltonian path from s to t, we first ignore the clause nodes. The path begins at s, goes through each diamond in turn and ends up at t. To hit horizontal nodes in a diamond. the path either zig-zags from left to right or zag-zigs from right to left; the satisfying assignment to determines whether is assigned TRUE or FALSE respectively. We show both cases in the following figure.
So far this path covers all the nodes in G except the clause nodes. We can easily include them by adding detours at the horizontal nodes. In each clause, we select one of the literals assigned TRUE, by satisfying assignment. If we selected in clause , we can detour at the jth pair in the ith diamond. Doing so is possible because must be TRUE, so the path zig-zags from left to right through the corresponding diamond. Hence the edges to the node are in the correct order to allow a detour and return. Similarly, if we selected in clause , we can detour at the jth pair in the ith diamond because must be FALSE, so the path zag-zigs from right to left through the corresponding diamond. Hence the edges to he node are again in the correct order to allow a detour and return. Every time one detour is taken if each literal in clause provides an option for detour. Thus each node is visited exactly once and thus Hamiltonian Path is constructed. For the reverse direction, if G has a Hamiltonian path from s to t, we demonstrate a satisfying assignment for . If the Hamiltonian path is normal i.e. it goes through diamonds in order from top to bottom node except the detour for the closure nodes; we can easily obtain the satisfying assignment. If the path zig-zags in diamond we assign the variables as TRUE and if it zag-zigs then assign it FALSE. Because every node appears on the path by observing how the detour is taken we may determine corresponding TRUE variables. All that remains to be shown that Hamiltonian path must be normal means the path enters a clause from one diamond but returns to another like in the following figure.
The path goes from node to c; but instead of returning to in the same diamond, it returns to in the different diamond. If that occurs then either or must be a separator node. If were a separator node, the only edges entering in would be from or . If were a separator node then and would be in same clause, then edges that enters from , and c. In either case path cannot enter from because is only available node that points at, so path must exit via . Hence Hamiltonian path must be normal. This reduction obviously operates in polynomial time and hence the proof is complete that HAMPATH is NP-Complete. Images reference: https://tr.m.wikipedia.org/wiki/Hamilton_yolu
surinderdawra388
NP Complete
Graph
Theory of Computation & Automata
Graph
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Breadth First Search or BFS for a Graph
Depth First Search or DFS for a Graph
Dijkstra's shortest path algorithm | Greedy Algo-7
Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5
Graph and its representations
Difference between DFA and NFA
Boyer-Moore Majority Voting Algorithm
Variation of Turing Machine
Design 101 sequence detector (Mealy machine)
Post Correspondence Problem | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n01 Jun, 2022"
},
{
"code": null,
"e": 481,
"s": 54,
"text": "Prerequisite : NP-Completeness The class of languages for which membership can be decided quickly fall in the class of P and The class of languages for which membership can be verified quickly fall in the class of NP(stands for problem solved in Non-deterministic Turing Machine in polynomial time). In straight words, every NP problem has its own polynomial-time verifier. A verifier for a language A is an algorithm V, where"
},
{
"code": null,
"e": 583,
"s": 481,
"text": "A = {w | V accepts (w, c) for some string c}\nwhere c is certificate or proof that w is a member of A."
},
{
"code": null,
"e": 669,
"s": 583,
"text": "We are interested in NP-Complete problems. NP-Complete problem is defined as follows:"
},
{
"code": null,
"e": 836,
"s": 669,
"text": "(1)The problem itself is in NP class.\n(2)All other problems in NP class can be polynomial time reducible to that.\n(B is polynomial time reducible to C is denoted as )"
},
{
"code": null,
"e": 1538,
"s": 836,
"text": "If the 2nd condition is only satisfied then the problem is called NP-Hard. But it is not possible to reduce every NP problem into another NP problem to show its NP-Completeness all the time. That is why if we want to show a problem is NP-Complete we just show that the problem is in NP and any NP-Complete problem is reducible to that then we are done, i.e. if B is NP-Complete and for C in NP, then C is NP-Complete. We have to show Hamiltonian Path is NP-Complete. Hamiltonian Path or HAMPATH in a directed graph G is a directed path that goes through each node exactly once. We Consider the problem of testing whether a directed graph contain a Hamiltonian path connecting two specified nodes, i.e."
},
{
"code": null,
"e": 1618,
"s": 1538,
"text": "HAMPATH = {(G, s, t) | G is directed graph with a Hamiltonian path from s to t}"
},
{
"code": null,
"e": 2858,
"s": 1618,
"text": "To prove HAMPATH is NP-Complete we have to prove that HAMPATH is in NP. To prove HAMPATH is in NP we must have a polynomial-time verifier. Even though we don’t have a fast polynomial time algorithm to determine whether a graph contains a HAMPATH or not, if such a path is discovered somehow (maybe with exponential time brute force searching) we could easily-work it out whether the path is HAMPATH or not, in polynomial time. Here the certificate will be a Hamiltonian path from s to t itself in G if exists. So HAMPATH is in NP proved. So, now we have to show that every problem to NP class is polynomial time reducible to HAMPATH to show its NP-Completeness. Rather we shall show 3SAT (A NP-Complete problem proved previously from SAT(Circuit Satisfiability Problem)) is polynomial time reducible to HAMPATH. We will convert a given cnf (Conjunctive Normal Form) form to a graph where gadgets (structure to simulate variables and clauses) will mimic the variables and clauses (several literals or variables connected with ). We have to prove now For each 3-cnf formula we will show how to build graph G with s and t, where a Hamiltonian path exists between s and t iff is satisfiable. We start with a 3-cnf formula containing k clauses,"
},
{
"code": null,
"e": 4776,
"s": 2858,
"text": "where each is a literal or . Let be the l variables of .Now we show how to convert to a graph G. The graph G that we construct has various parts to represent the variables and clauses that appear in . We represent each variable with a diamond-shaped structure that contains a horizontal row of nodes as shown in following figure. We specify the number of nodes that appear in the horizontal row later. The following figure depicts the global structure of G. It shows all the elements of G and their relationships, except the edges that represent the relationship of the variables to the clauses that contain them. Each diamond structure contains a horizontal row of nodes connected by edges running in both directions. The horizontal row contains 2k nodes (as 2 nodes for each clause) plus, k-1 extra nodes in between every two nodes for a clause plus, 2 nodes on the ends belonging to the diamonds; total 3k+1 nodes. Following diagram gives a clear picture. If variable appears in clause , we add the following two edges from the jth pair in the ith diamond to the jth clause node. If appears in clause c_j, we add two edges from the jth pair in the ith diamond to the jth clause node, as in the following figure. After we add all the edges corresponding to each occurrence of or in each clause, the construction of G is complete. To show its correctness we will prove if is satisfiable, a Hamiltonian path exists from s to t and conversely, if such a path exists is satisfiable. Suppose that is satisfiable. To demonstrate a Hamiltonian path from s to t, we first ignore the clause nodes. The path begins at s, goes through each diamond in turn and ends up at t. To hit horizontal nodes in a diamond. the path either zig-zags from left to right or zag-zigs from right to left; the satisfying assignment to determines whether is assigned TRUE or FALSE respectively. We show both cases in the following figure. "
},
{
"code": null,
"e": 6417,
"s": 4776,
"text": "So far this path covers all the nodes in G except the clause nodes. We can easily include them by adding detours at the horizontal nodes. In each clause, we select one of the literals assigned TRUE, by satisfying assignment. If we selected in clause , we can detour at the jth pair in the ith diamond. Doing so is possible because must be TRUE, so the path zig-zags from left to right through the corresponding diamond. Hence the edges to the node are in the correct order to allow a detour and return. Similarly, if we selected in clause , we can detour at the jth pair in the ith diamond because must be FALSE, so the path zag-zigs from right to left through the corresponding diamond. Hence the edges to he node are again in the correct order to allow a detour and return. Every time one detour is taken if each literal in clause provides an option for detour. Thus each node is visited exactly once and thus Hamiltonian Path is constructed. For the reverse direction, if G has a Hamiltonian path from s to t, we demonstrate a satisfying assignment for . If the Hamiltonian path is normal i.e. it goes through diamonds in order from top to bottom node except the detour for the closure nodes; we can easily obtain the satisfying assignment. If the path zig-zags in diamond we assign the variables as TRUE and if it zag-zigs then assign it FALSE. Because every node appears on the path by observing how the detour is taken we may determine corresponding TRUE variables. All that remains to be shown that Hamiltonian path must be normal means the path enters a clause from one diamond but returns to another like in the following figure. "
},
{
"code": null,
"e": 7086,
"s": 6417,
"text": "The path goes from node to c; but instead of returning to in the same diamond, it returns to in the different diamond. If that occurs then either or must be a separator node. If were a separator node, the only edges entering in would be from or . If were a separator node then and would be in same clause, then edges that enters from , and c. In either case path cannot enter from because is only available node that points at, so path must exit via . Hence Hamiltonian path must be normal. This reduction obviously operates in polynomial time and hence the proof is complete that HAMPATH is NP-Complete. Images reference: https://tr.m.wikipedia.org/wiki/Hamilton_yolu"
},
{
"code": null,
"e": 7103,
"s": 7086,
"text": "surinderdawra388"
},
{
"code": null,
"e": 7115,
"s": 7103,
"text": "NP Complete"
},
{
"code": null,
"e": 7121,
"s": 7115,
"text": "Graph"
},
{
"code": null,
"e": 7154,
"s": 7121,
"text": "Theory of Computation & Automata"
},
{
"code": null,
"e": 7160,
"s": 7154,
"text": "Graph"
},
{
"code": null,
"e": 7258,
"s": 7160,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 7298,
"s": 7258,
"text": "Breadth First Search or BFS for a Graph"
},
{
"code": null,
"e": 7336,
"s": 7298,
"text": "Depth First Search or DFS for a Graph"
},
{
"code": null,
"e": 7387,
"s": 7336,
"text": "Dijkstra's shortest path algorithm | Greedy Algo-7"
},
{
"code": null,
"e": 7438,
"s": 7387,
"text": "Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5"
},
{
"code": null,
"e": 7468,
"s": 7438,
"text": "Graph and its representations"
},
{
"code": null,
"e": 7499,
"s": 7468,
"text": "Difference between DFA and NFA"
},
{
"code": null,
"e": 7537,
"s": 7499,
"text": "Boyer-Moore Majority Voting Algorithm"
},
{
"code": null,
"e": 7565,
"s": 7537,
"text": "Variation of Turing Machine"
},
{
"code": null,
"e": 7610,
"s": 7565,
"text": "Design 101 sequence detector (Mealy machine)"
}
] |
Print Right View of a Binary Tree | 11 Jun, 2022
Given a Binary Tree, print Right view of it. Right view of a Binary Tree is set of nodes visible when tree is visited from Right side.
Right view of following tree is 1 3 7 8
1
/ \
2 3
/ \ / \
4 5 6 7
\
8
The problem can be solved using simple recursive traversal. We can keep track of level of a node by passing a parameter to all recursive calls. The idea is to keep track of maximum level also. And traverse the tree in a manner that right subtree is visited before left subtree. Whenever we see a node whose level is more than maximum level so far, we print the node because this is the last node in its level (Note that we traverse the right subtree before left subtree). Following is the implementation of this approach.
C++
C
Java
Python
C#
Javascript
// C++ program to print right view of Binary Tree#include <bits/stdc++.h>using namespace std; struct Node{ int data; struct Node *left, *right;}; // A utility function to// create a new Binary Tree Nodestruct Node *newNode(int item){ struct Node *temp = (struct Node *)malloc( sizeof(struct Node)); temp->data = item; temp->left = temp->right = NULL; return temp;} // Recursive function to print// right view of a binary tree.void rightViewUtil(struct Node *root, int level, int *max_level){ // Base Case if (root == NULL) return; // If this is the last Node of its level if (*max_level < level) { cout << root->data << "\t"; *max_level = level; } // Recur for right subtree first, // then left subtree rightViewUtil(root->right, level + 1, max_level); rightViewUtil(root->left, level + 1, max_level);} // A wrapper over rightViewUtil()void rightView(struct Node *root){ int max_level = 0; rightViewUtil(root, 1, &max_level);} // Driver Codeint main(){ struct Node *root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); root->right->left = newNode(6); root->right->right = newNode(7); root->right->right->right = newNode(8); rightView(root); return 0;} // This code is contributed by SHUBHAMSINGH10
// C program to print right view of Binary Tree#include<stdio.h>#include<stdlib.h> struct Node{ int data; struct Node *left, *right;}; // A utility function to create a new Binary Tree Nodestruct Node *newNode(int item){ struct Node *temp = (struct Node *)malloc(sizeof(struct Node)); temp->data = item; temp->left = temp->right = NULL; return temp;} // Recursive function to print right view of a binary tree.void rightViewUtil(struct Node *root, int level, int *max_level){ // Base Case if (root==NULL) return; // If this is the last Node of its level if (*max_level < level) { printf("%d\t", root->data); *max_level = level; } // Recur for right subtree first, then left subtree rightViewUtil(root->right, level+1, max_level); rightViewUtil(root->left, level+1, max_level);} // A wrapper over rightViewUtil()void rightView(struct Node *root){ int max_level = 0; rightViewUtil(root, 1, &max_level);} // Driver Program to test above functionsint main(){ struct Node *root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); root->right->left = newNode(6); root->right->right = newNode(7); root->right->left->right = newNode(8); rightView(root); return 0;}
// Java program to print right view of binary tree // A binary tree nodeclass Node { int data; Node left, right; Node(int item) { data = item; left = right = null; }} // class to access maximum level by referenceclass Max_level { int max_level;} class BinaryTree { Node root; Max_level max = new Max_level(); // Recursive function to print right view of a binary tree. void rightViewUtil(Node node, int level, Max_level max_level) { // Base Case if (node == null) return; // If this is the last Node of its level if (max_level.max_level < level) { System.out.print(node.data + " "); max_level.max_level = level; } // Recur for right subtree first, then left subtree rightViewUtil(node.right, level + 1, max_level); rightViewUtil(node.left, level + 1, max_level); } void rightView() { rightView(root); } // A wrapper over rightViewUtil() void rightView(Node node) { rightViewUtil(node, 1, max); } // Driver program to test the above functions 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); tree.root.right.left = new Node(6); tree.root.right.right = new Node(7); tree.root.right.left.right = new Node(8); tree.rightView(); }} // This code has been contributed by Mayank Jaiswal
# Python program to print right view of Binary Tree # A binary tree nodeclass Node: # A constructor to create a new Binary tree Node def __init__(self, item): self.data = item self.left = None self.right = None # Recursive function to print right view of Binary Tree# used max_level as reference list ..only max_level[0]# is helpful to usdef rightViewUtil(root, level, max_level): # Base Case if root is None: return # If this is the last node of its level if (max_level[0] < level): print "%d " %(root.data), max_level[0] = level # Recur for right subtree first, then left subtree rightViewUtil(root.right, level+1, max_level) rightViewUtil(root.left, level+1, max_level) def rightView(root): max_level = [0] rightViewUtil(root, 1, max_level) # Driver program to test above functionroot = Node(1)root.left = Node(2)root.right = Node(3)root.left.left = Node(4)root.left.right = Node(5)root.right.left = Node(6)root.right.right = Node(7)root.right.left.right = Node(8) rightView(root) # This code is contributed by Nikhil Kumar Singh(nickzuck_007)
using System; // C# program to print right view of binary tree // A binary tree nodepublic class Node{ public int data; public Node left, right; public Node(int item) { data = item; left = right = null; }} // class to access maximum level by referencepublic class Max_level{ public int max_level;} public class BinaryTree{ public Node root; public Max_level max = new Max_level(); // Recursive function to print right view of a binary tree. public virtual void rightViewUtil(Node node, int level, Max_level max_level) { // Base Case if (node == null) { return; } // If this is the last Node of its level if (max_level.max_level < level) { Console.Write(node.data + " "); max_level.max_level = level; } // Recur for right subtree first, then left subtree rightViewUtil(node.right, level + 1, max_level); rightViewUtil(node.left, level + 1, max_level); } public virtual void rightView() { rightView(root); } // A wrapper over rightViewUtil() public virtual void rightView(Node node) { rightViewUtil(node, 1, max); } // Driver program to test the above functions 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); tree.root.right.left = new Node(6); tree.root.right.right = new Node(7); tree.root.right.left.right = new Node(8); tree.rightView(); }} // This code is contributed by Shrikant13
<script> // JavaScript program to print // right view of binary tree class Node { constructor(item) { this.left = null; this.right = null; this.data = item; } } let max_level = 0; let root; // Recursive function to print right view of a binary tree. function rightViewUtil(node, level) { // Base Case if (node == null) return; // If this is the last Node of its level if (max_level < level) { document.write(node.data + " "); max_level = level; } // Recur for right subtree first, then left subtree rightViewUtil(node.right, level + 1); rightViewUtil(node.left, level + 1); } function rightView() { rightview(root); } // A wrapper over rightViewUtil() function rightview(node) { rightViewUtil(node, 1); } 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); root.right.left = new Node(6); root.right.right = new Node(7); root.right.left.right = new Node(8); rightView(); </script>
1 3 7 8
Right view of Binary Tree using QueueTime Complexity: The function does a simple traversal of the tree, so the complexity is O(n).
Auxiliary Space: O(n)
Chapters
descriptions off, selected
captions settings, opens captions settings dialog
captions off, selected
English
default, selected
This is a modal window.
Beginning of dialog window. Escape will cancel and close the window.
End of dialog window.
Method 2: In this method, level order traversal based solution is discussed. If we observe carefully, we will see that our main task is to print the right most node of every level. So, we will do a level order traversal on the tree and print the last node at every level. Below is the implementation of above approach:
C++
Java
Python3
C#
Javascript
// C++ program to print left view of// Binary Tree #include <bits/stdc++.h>using namespace std; // A Binary Tree Nodestruct Node { int data; struct Node *left, *right;}; // Utility function to create a new tree nodeNode* newNode(int data){ Node* temp = new Node; temp->data = data; temp->left = temp->right = NULL; return temp;} // function to print Right view of// binary treevoid printRightView(Node* root){ if (root == NULL) return; queue<Node*> q; q.push(root); while (!q.empty()) { // get number of nodes for each level int n = q.size(); // traverse all the nodes of the current level while (n--) { Node* x = q.front(); q.pop(); // print the last node of each level if (n == 0) { cout << x->data << " "; } // if left child is not null push it into the // queue if (x->left) q.push(x->left); // if right child is not null push it into the // queue if (x->right) q.push(x->right); } }} // Driver codeint main(){ // Let's construct the tree as // shown in example Node* root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); root->right->left = newNode(6); root->right->right = newNode(7); root->right->left->right = newNode(8); printRightView(root);} // This code is contributed by// Snehasish Dhar
// JAVA program to print right view of// Binary Tree import java.io.*;import java.util.LinkedList;import java.util.Queue; // A Binary Tree Nodeclass Node { int data; Node left, right; public Node(int d) { data = d; left = right = null; }} class BinaryTree { Node root; // function to print Right view of // binary tree void rightView(Node root) { if (root == null) { return; } Queue<Node> q = new LinkedList<>(); q.add(root); while (!q.isEmpty()) { // get number of nodes for each level int n = q.size(); // traverse all the nodes of the current level for (int i = 0; i < n; i++) { Node curr = q.peek(); q.remove(); // print the last node of each level if (i == n - 1) { System.out.print(curr.data); System.out.print(" "); } // if left child is not null add it into // the // queue if (curr.left != null) { q.add(curr.left); } // if right child is not null add it into // the // queue if (curr.right != null) { q.add(curr.right); } } } } // Driver code public static void main(String[] args) { // Let's construct the tree as // shown in example 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); tree.root.right.left = new Node(6); tree.root.right.right = new Node(7); tree.root.right.left.right = new Node(8); tree.rightView(tree.root); }} // This code is contributed by Biswajit Rajak
# Python3 program to print right# view of Binary Treefrom collections import deque # A binary tree nodeclass Node: # A constructor to create a new # Binary tree Node def __init__(self, val): self.data = val self.left = None self.right = None # Function to print Right view of# binary treedef rightView(root): if root is None: return q = deque() q.append(root) while q: # Get number of nodes for each level n = len(q) # Traverse all the nodes of the # current level while n > 0: n -= 1 # Get the front node in the queue node = q.popleft() # Print the last node of each level if n == 0: print(node.data, end = " ") # If left child is not null push it # into the queue if node.left: q.append(node.left) # If right child is not null push # it into the queue if node.right: q.append(node.right) # Driver code # Let's construct the tree as# shown in exampleroot = Node(1)root.left = Node(2)root.right = Node(3)root.left.left = Node(4)root.left.right = Node(5)root.right.left = Node(6)root.right.right = Node(7)root.right.left.right = Node(8) rightView(root) # This code is contributed by Pulkit Pansari
// C# program to print right view of// Binary Treeusing System;using System.Collections.Generic; // A Binary Tree Nodepublic class Node { public int data; public Node left, right; public Node(int d) { data = d; left = right = null; }} public class BinaryTree { public Node root; // function to print Right view of // binary tree public void rightView(Node root) { if (root == null) { return; } Queue<Node > q = new Queue<Node>(); q.Enqueue(root); while (q.Count!=0) { // get number of nodes for each level int n = q.Count; // traverse all the nodes of the current level for (int i = 0; i < n; i++) { Node curr = q.Peek(); q.Dequeue(); // print the last node of each level if (i == n - 1) { Console.Write(curr.data); Console.Write(" "); } // if left child is not null add it into // the // queue if (curr.left != null) { q.Enqueue(curr.left); } // if right child is not null add it into // the // queue if (curr.right != null) { q.Enqueue(curr.right); } } } } // Driver Code public static void Main() { // Let's construct the tree as // shown in example 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); tree.root.right.left = new Node(6); tree.root.right.right = new Node(7); tree.root.right.left.right = new Node(8); tree.rightView(tree.root); }} // This code is contributed by jana_sayantan.
<script> // JavaScript program to print left view of Binary Tree class Node { constructor(data) { this.left = null; this.right = null; this.data = data; } } // Utility function to create a new tree node function newNode(data) { let temp = new Node(data); return temp; } // function to print Right view of // binary tree function printRightView(root) { if (root == null) return; let q = []; q.push(root); while (q.length > 0) { // get number of nodes for each level let n = q.length; // traverse all the nodes of the current level while (n-- > 0) { let x = q[0]; q.shift(); // print the last node of each level if (n == 0) { document.write(x.data + " "); } // if left child is not null push it into the // queue if (x.left != null) q.push(x.left); // if right child is not null push it into the // queue if (x.right != null) q.push(x.right); } } } // Let's construct the tree as // shown in example let root = newNode(1); root.left = newNode(2); root.right = newNode(3); root.left.left = newNode(4); root.left.right = newNode(5); root.right.left = newNode(6); root.right.right = newNode(7); root.right.left.right = newNode(8); printRightView(root); </script>
1 3 7 8
Time Complexity: O(n), where n is the number of nodes in the binary tree.
Auxiliary Space: O(n) since using auxiliary space for queue
Print Right View of a Binary Tree | GeeksforGeeks - YouTubeGeeksforGeeks529K subscribersPrint Right View of a Binary Tree | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 5:33•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=rnRRlhTflLs" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
This article is contributed by Biswajit Rajak. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
shrikanth13
SHUBHAMSINGH10
dsnehasish74
mukesh07
pansaripulkit13
divyeshrabadiya07
rajakbiswajit409
chauhanankur94
jana_sayantan
polymatir3j
Accolite
Adobe
Amazon
MakeMyTrip
Snapdeal
tree-view
Tree
Accolite
Amazon
Snapdeal
MakeMyTrip
Adobe
Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to Data Structures
Introduction to Tree Data Structure
Inorder Tree Traversal without Recursion
What is Data Structure: Types, Classifications and Applications
Binary Tree | Set 3 (Types of Binary Tree)
A program to check if a binary tree is BST or not
Binary Tree | Set 2 (Properties)
Diameter of a Binary Tree
Lowest Common Ancestor in a Binary Tree | Set 1 | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n11 Jun, 2022"
},
{
"code": null,
"e": 190,
"s": 54,
"text": "Given a Binary Tree, print Right view of it. Right view of a Binary Tree is set of nodes visible when tree is visited from Right side. "
},
{
"code": null,
"e": 352,
"s": 190,
"text": "Right view of following tree is 1 3 7 8\n\n 1\n / \\\n 2 3\n / \\ / \\\n 4 5 6 7\n \\\n 8"
},
{
"code": null,
"e": 875,
"s": 352,
"text": "The problem can be solved using simple recursive traversal. We can keep track of level of a node by passing a parameter to all recursive calls. The idea is to keep track of maximum level also. And traverse the tree in a manner that right subtree is visited before left subtree. Whenever we see a node whose level is more than maximum level so far, we print the node because this is the last node in its level (Note that we traverse the right subtree before left subtree). Following is the implementation of this approach. "
},
{
"code": null,
"e": 879,
"s": 875,
"text": "C++"
},
{
"code": null,
"e": 881,
"s": 879,
"text": "C"
},
{
"code": null,
"e": 886,
"s": 881,
"text": "Java"
},
{
"code": null,
"e": 893,
"s": 886,
"text": "Python"
},
{
"code": null,
"e": 896,
"s": 893,
"text": "C#"
},
{
"code": null,
"e": 907,
"s": 896,
"text": "Javascript"
},
{
"code": "// C++ program to print right view of Binary Tree#include <bits/stdc++.h>using namespace std; struct Node{ int data; struct Node *left, *right;}; // A utility function to// create a new Binary Tree Nodestruct Node *newNode(int item){ struct Node *temp = (struct Node *)malloc( sizeof(struct Node)); temp->data = item; temp->left = temp->right = NULL; return temp;} // Recursive function to print// right view of a binary tree.void rightViewUtil(struct Node *root, int level, int *max_level){ // Base Case if (root == NULL) return; // If this is the last Node of its level if (*max_level < level) { cout << root->data << \"\\t\"; *max_level = level; } // Recur for right subtree first, // then left subtree rightViewUtil(root->right, level + 1, max_level); rightViewUtil(root->left, level + 1, max_level);} // A wrapper over rightViewUtil()void rightView(struct Node *root){ int max_level = 0; rightViewUtil(root, 1, &max_level);} // Driver Codeint main(){ struct Node *root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); root->right->left = newNode(6); root->right->right = newNode(7); root->right->right->right = newNode(8); rightView(root); return 0;} // This code is contributed by SHUBHAMSINGH10",
"e": 2330,
"s": 907,
"text": null
},
{
"code": "// C program to print right view of Binary Tree#include<stdio.h>#include<stdlib.h> struct Node{ int data; struct Node *left, *right;}; // A utility function to create a new Binary Tree Nodestruct Node *newNode(int item){ struct Node *temp = (struct Node *)malloc(sizeof(struct Node)); temp->data = item; temp->left = temp->right = NULL; return temp;} // Recursive function to print right view of a binary tree.void rightViewUtil(struct Node *root, int level, int *max_level){ // Base Case if (root==NULL) return; // If this is the last Node of its level if (*max_level < level) { printf(\"%d\\t\", root->data); *max_level = level; } // Recur for right subtree first, then left subtree rightViewUtil(root->right, level+1, max_level); rightViewUtil(root->left, level+1, max_level);} // A wrapper over rightViewUtil()void rightView(struct Node *root){ int max_level = 0; rightViewUtil(root, 1, &max_level);} // Driver Program to test above functionsint main(){ struct Node *root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); root->right->left = newNode(6); root->right->right = newNode(7); root->right->left->right = newNode(8); rightView(root); return 0;}",
"e": 3664,
"s": 2330,
"text": null
},
{
"code": "// Java program to print right view of binary tree // A binary tree nodeclass Node { int data; Node left, right; Node(int item) { data = item; left = right = null; }} // class to access maximum level by referenceclass Max_level { int max_level;} class BinaryTree { Node root; Max_level max = new Max_level(); // Recursive function to print right view of a binary tree. void rightViewUtil(Node node, int level, Max_level max_level) { // Base Case if (node == null) return; // If this is the last Node of its level if (max_level.max_level < level) { System.out.print(node.data + \" \"); max_level.max_level = level; } // Recur for right subtree first, then left subtree rightViewUtil(node.right, level + 1, max_level); rightViewUtil(node.left, level + 1, max_level); } void rightView() { rightView(root); } // A wrapper over rightViewUtil() void rightView(Node node) { rightViewUtil(node, 1, max); } // Driver program to test the above functions 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); tree.root.right.left = new Node(6); tree.root.right.right = new Node(7); tree.root.right.left.right = new Node(8); tree.rightView(); }} // This code has been contributed by Mayank Jaiswal",
"e": 5298,
"s": 3664,
"text": null
},
{
"code": "# Python program to print right view of Binary Tree # A binary tree nodeclass Node: # A constructor to create a new Binary tree Node def __init__(self, item): self.data = item self.left = None self.right = None # Recursive function to print right view of Binary Tree# used max_level as reference list ..only max_level[0]# is helpful to usdef rightViewUtil(root, level, max_level): # Base Case if root is None: return # If this is the last node of its level if (max_level[0] < level): print \"%d \" %(root.data), max_level[0] = level # Recur for right subtree first, then left subtree rightViewUtil(root.right, level+1, max_level) rightViewUtil(root.left, level+1, max_level) def rightView(root): max_level = [0] rightViewUtil(root, 1, max_level) # Driver program to test above functionroot = Node(1)root.left = Node(2)root.right = Node(3)root.left.left = Node(4)root.left.right = Node(5)root.right.left = Node(6)root.right.right = Node(7)root.right.left.right = Node(8) rightView(root) # This code is contributed by Nikhil Kumar Singh(nickzuck_007)",
"e": 6438,
"s": 5298,
"text": null
},
{
"code": "using System; // C# program to print right view of binary tree // A binary tree nodepublic class Node{ public int data; public Node left, right; public Node(int item) { data = item; left = right = null; }} // class to access maximum level by referencepublic class Max_level{ public int max_level;} public class BinaryTree{ public Node root; public Max_level max = new Max_level(); // Recursive function to print right view of a binary tree. public virtual void rightViewUtil(Node node, int level, Max_level max_level) { // Base Case if (node == null) { return; } // If this is the last Node of its level if (max_level.max_level < level) { Console.Write(node.data + \" \"); max_level.max_level = level; } // Recur for right subtree first, then left subtree rightViewUtil(node.right, level + 1, max_level); rightViewUtil(node.left, level + 1, max_level); } public virtual void rightView() { rightView(root); } // A wrapper over rightViewUtil() public virtual void rightView(Node node) { rightViewUtil(node, 1, max); } // Driver program to test the above functions 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); tree.root.right.left = new Node(6); tree.root.right.right = new Node(7); tree.root.right.left.right = new Node(8); tree.rightView(); }} // This code is contributed by Shrikant13",
"e": 8240,
"s": 6438,
"text": null
},
{
"code": "<script> // JavaScript program to print // right view of binary tree class Node { constructor(item) { this.left = null; this.right = null; this.data = item; } } let max_level = 0; let root; // Recursive function to print right view of a binary tree. function rightViewUtil(node, level) { // Base Case if (node == null) return; // If this is the last Node of its level if (max_level < level) { document.write(node.data + \" \"); max_level = level; } // Recur for right subtree first, then left subtree rightViewUtil(node.right, level + 1); rightViewUtil(node.left, level + 1); } function rightView() { rightview(root); } // A wrapper over rightViewUtil() function rightview(node) { rightViewUtil(node, 1); } 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); root.right.left = new Node(6); root.right.right = new Node(7); root.right.left.right = new Node(8); rightView(); </script>",
"e": 9458,
"s": 8240,
"text": null
},
{
"code": null,
"e": 9479,
"s": 9458,
"text": "1 3 7 8 "
},
{
"code": null,
"e": 9610,
"s": 9479,
"text": "Right view of Binary Tree using QueueTime Complexity: The function does a simple traversal of the tree, so the complexity is O(n)."
},
{
"code": null,
"e": 9632,
"s": 9610,
"text": "Auxiliary Space: O(n)"
},
{
"code": null,
"e": 9641,
"s": 9632,
"text": "Chapters"
},
{
"code": null,
"e": 9668,
"s": 9641,
"text": "descriptions off, selected"
},
{
"code": null,
"e": 9718,
"s": 9668,
"text": "captions settings, opens captions settings dialog"
},
{
"code": null,
"e": 9741,
"s": 9718,
"text": "captions off, selected"
},
{
"code": null,
"e": 9749,
"s": 9741,
"text": "English"
},
{
"code": null,
"e": 9767,
"s": 9749,
"text": "default, selected"
},
{
"code": null,
"e": 9791,
"s": 9767,
"text": "This is a modal window."
},
{
"code": null,
"e": 9860,
"s": 9791,
"text": "Beginning of dialog window. Escape will cancel and close the window."
},
{
"code": null,
"e": 9882,
"s": 9860,
"text": "End of dialog window."
},
{
"code": null,
"e": 10201,
"s": 9882,
"text": "Method 2: In this method, level order traversal based solution is discussed. If we observe carefully, we will see that our main task is to print the right most node of every level. So, we will do a level order traversal on the tree and print the last node at every level. Below is the implementation of above approach:"
},
{
"code": null,
"e": 10205,
"s": 10201,
"text": "C++"
},
{
"code": null,
"e": 10210,
"s": 10205,
"text": "Java"
},
{
"code": null,
"e": 10218,
"s": 10210,
"text": "Python3"
},
{
"code": null,
"e": 10221,
"s": 10218,
"text": "C#"
},
{
"code": null,
"e": 10232,
"s": 10221,
"text": "Javascript"
},
{
"code": "// C++ program to print left view of// Binary Tree #include <bits/stdc++.h>using namespace std; // A Binary Tree Nodestruct Node { int data; struct Node *left, *right;}; // Utility function to create a new tree nodeNode* newNode(int data){ Node* temp = new Node; temp->data = data; temp->left = temp->right = NULL; return temp;} // function to print Right view of// binary treevoid printRightView(Node* root){ if (root == NULL) return; queue<Node*> q; q.push(root); while (!q.empty()) { // get number of nodes for each level int n = q.size(); // traverse all the nodes of the current level while (n--) { Node* x = q.front(); q.pop(); // print the last node of each level if (n == 0) { cout << x->data << \" \"; } // if left child is not null push it into the // queue if (x->left) q.push(x->left); // if right child is not null push it into the // queue if (x->right) q.push(x->right); } }} // Driver codeint main(){ // Let's construct the tree as // shown in example Node* root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); root->right->left = newNode(6); root->right->right = newNode(7); root->right->left->right = newNode(8); printRightView(root);} // This code is contributed by// Snehasish Dhar",
"e": 11793,
"s": 10232,
"text": null
},
{
"code": "// JAVA program to print right view of// Binary Tree import java.io.*;import java.util.LinkedList;import java.util.Queue; // A Binary Tree Nodeclass Node { int data; Node left, right; public Node(int d) { data = d; left = right = null; }} class BinaryTree { Node root; // function to print Right view of // binary tree void rightView(Node root) { if (root == null) { return; } Queue<Node> q = new LinkedList<>(); q.add(root); while (!q.isEmpty()) { // get number of nodes for each level int n = q.size(); // traverse all the nodes of the current level for (int i = 0; i < n; i++) { Node curr = q.peek(); q.remove(); // print the last node of each level if (i == n - 1) { System.out.print(curr.data); System.out.print(\" \"); } // if left child is not null add it into // the // queue if (curr.left != null) { q.add(curr.left); } // if right child is not null add it into // the // queue if (curr.right != null) { q.add(curr.right); } } } } // Driver code public static void main(String[] args) { // Let's construct the tree as // shown in example 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); tree.root.right.left = new Node(6); tree.root.right.right = new Node(7); tree.root.right.left.right = new Node(8); tree.rightView(tree.root); }} // This code is contributed by Biswajit Rajak",
"e": 13785,
"s": 11793,
"text": null
},
{
"code": "# Python3 program to print right# view of Binary Treefrom collections import deque # A binary tree nodeclass Node: # A constructor to create a new # Binary tree Node def __init__(self, val): self.data = val self.left = None self.right = None # Function to print Right view of# binary treedef rightView(root): if root is None: return q = deque() q.append(root) while q: # Get number of nodes for each level n = len(q) # Traverse all the nodes of the # current level while n > 0: n -= 1 # Get the front node in the queue node = q.popleft() # Print the last node of each level if n == 0: print(node.data, end = \" \") # If left child is not null push it # into the queue if node.left: q.append(node.left) # If right child is not null push # it into the queue if node.right: q.append(node.right) # Driver code # Let's construct the tree as# shown in exampleroot = Node(1)root.left = Node(2)root.right = Node(3)root.left.left = Node(4)root.left.right = Node(5)root.right.left = Node(6)root.right.right = Node(7)root.right.left.right = Node(8) rightView(root) # This code is contributed by Pulkit Pansari",
"e": 15171,
"s": 13785,
"text": null
},
{
"code": "// C# program to print right view of// Binary Treeusing System;using System.Collections.Generic; // A Binary Tree Nodepublic class Node { public int data; public Node left, right; public Node(int d) { data = d; left = right = null; }} public class BinaryTree { public Node root; // function to print Right view of // binary tree public void rightView(Node root) { if (root == null) { return; } Queue<Node > q = new Queue<Node>(); q.Enqueue(root); while (q.Count!=0) { // get number of nodes for each level int n = q.Count; // traverse all the nodes of the current level for (int i = 0; i < n; i++) { Node curr = q.Peek(); q.Dequeue(); // print the last node of each level if (i == n - 1) { Console.Write(curr.data); Console.Write(\" \"); } // if left child is not null add it into // the // queue if (curr.left != null) { q.Enqueue(curr.left); } // if right child is not null add it into // the // queue if (curr.right != null) { q.Enqueue(curr.right); } } } } // Driver Code public static void Main() { // Let's construct the tree as // shown in example 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); tree.root.right.left = new Node(6); tree.root.right.right = new Node(7); tree.root.right.left.right = new Node(8); tree.rightView(tree.root); }} // This code is contributed by jana_sayantan.",
"e": 16871,
"s": 15171,
"text": null
},
{
"code": "<script> // JavaScript program to print left view of Binary Tree class Node { constructor(data) { this.left = null; this.right = null; this.data = data; } } // Utility function to create a new tree node function newNode(data) { let temp = new Node(data); return temp; } // function to print Right view of // binary tree function printRightView(root) { if (root == null) return; let q = []; q.push(root); while (q.length > 0) { // get number of nodes for each level let n = q.length; // traverse all the nodes of the current level while (n-- > 0) { let x = q[0]; q.shift(); // print the last node of each level if (n == 0) { document.write(x.data + \" \"); } // if left child is not null push it into the // queue if (x.left != null) q.push(x.left); // if right child is not null push it into the // queue if (x.right != null) q.push(x.right); } } } // Let's construct the tree as // shown in example let root = newNode(1); root.left = newNode(2); root.right = newNode(3); root.left.left = newNode(4); root.left.right = newNode(5); root.right.left = newNode(6); root.right.right = newNode(7); root.right.left.right = newNode(8); printRightView(root); </script>",
"e": 18512,
"s": 16871,
"text": null
},
{
"code": null,
"e": 18521,
"s": 18512,
"text": "1 3 7 8 "
},
{
"code": null,
"e": 18595,
"s": 18521,
"text": "Time Complexity: O(n), where n is the number of nodes in the binary tree."
},
{
"code": null,
"e": 18655,
"s": 18595,
"text": "Auxiliary Space: O(n) since using auxiliary space for queue"
},
{
"code": null,
"e": 19539,
"s": 18655,
"text": "Print Right View of a Binary Tree | GeeksforGeeks - YouTubeGeeksforGeeks529K subscribersPrint Right View of a Binary Tree | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 5:33•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=rnRRlhTflLs\" 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": 19711,
"s": 19539,
"text": "This article is contributed by Biswajit Rajak. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above "
},
{
"code": null,
"e": 19723,
"s": 19711,
"text": "shrikanth13"
},
{
"code": null,
"e": 19738,
"s": 19723,
"text": "SHUBHAMSINGH10"
},
{
"code": null,
"e": 19751,
"s": 19738,
"text": "dsnehasish74"
},
{
"code": null,
"e": 19760,
"s": 19751,
"text": "mukesh07"
},
{
"code": null,
"e": 19776,
"s": 19760,
"text": "pansaripulkit13"
},
{
"code": null,
"e": 19794,
"s": 19776,
"text": "divyeshrabadiya07"
},
{
"code": null,
"e": 19811,
"s": 19794,
"text": "rajakbiswajit409"
},
{
"code": null,
"e": 19826,
"s": 19811,
"text": "chauhanankur94"
},
{
"code": null,
"e": 19840,
"s": 19826,
"text": "jana_sayantan"
},
{
"code": null,
"e": 19852,
"s": 19840,
"text": "polymatir3j"
},
{
"code": null,
"e": 19861,
"s": 19852,
"text": "Accolite"
},
{
"code": null,
"e": 19867,
"s": 19861,
"text": "Adobe"
},
{
"code": null,
"e": 19874,
"s": 19867,
"text": "Amazon"
},
{
"code": null,
"e": 19885,
"s": 19874,
"text": "MakeMyTrip"
},
{
"code": null,
"e": 19894,
"s": 19885,
"text": "Snapdeal"
},
{
"code": null,
"e": 19904,
"s": 19894,
"text": "tree-view"
},
{
"code": null,
"e": 19909,
"s": 19904,
"text": "Tree"
},
{
"code": null,
"e": 19918,
"s": 19909,
"text": "Accolite"
},
{
"code": null,
"e": 19925,
"s": 19918,
"text": "Amazon"
},
{
"code": null,
"e": 19934,
"s": 19925,
"text": "Snapdeal"
},
{
"code": null,
"e": 19945,
"s": 19934,
"text": "MakeMyTrip"
},
{
"code": null,
"e": 19951,
"s": 19945,
"text": "Adobe"
},
{
"code": null,
"e": 19956,
"s": 19951,
"text": "Tree"
},
{
"code": null,
"e": 20054,
"s": 19956,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 20086,
"s": 20054,
"text": "Introduction to Data Structures"
},
{
"code": null,
"e": 20122,
"s": 20086,
"text": "Introduction to Tree Data Structure"
},
{
"code": null,
"e": 20163,
"s": 20122,
"text": "Inorder Tree Traversal without Recursion"
},
{
"code": null,
"e": 20227,
"s": 20163,
"text": "What is Data Structure: Types, Classifications and Applications"
},
{
"code": null,
"e": 20270,
"s": 20227,
"text": "Binary Tree | Set 3 (Types of Binary Tree)"
},
{
"code": null,
"e": 20320,
"s": 20270,
"text": "A program to check if a binary tree is BST or not"
},
{
"code": null,
"e": 20353,
"s": 20320,
"text": "Binary Tree | Set 2 (Properties)"
},
{
"code": null,
"e": 20379,
"s": 20353,
"text": "Diameter of a Binary Tree"
}
] |
DetailView – Class Based Views Django | 22 Jan, 2020
Detail View refers to a view (logic) to display one instances of a table in the database. We have already discussed basics of Detail View in Detail View – Function based Views Django. Class-based views provide an alternative way to implement views as Python objects instead of functions. They do not replace function-based views, but have certain differences and advantages when compared to function-based views:
Organization of code related to specific HTTP methods (GET, POST, etc.) can be addressed by separate methods instead of conditional branching.
Object oriented techniques such as mixins (multiple inheritance) can be used to factor code into reusable components.
Class based views are simpler and efficient to manage than function-based views. A function based view with tons of lines of code can be converted into a class based views with few lines only. This is where Object Oriented Programming comes into impact.
Illustration of How to create and use Detail view using an Example. Consider a project named geeksforgeeks having an app named geeks.
Refer to the following articles to check how to create a project and an app in Django.
How to Create a Basic Project using MVT in Django?
How to Create an App in Django ?
After you have a project and an app, let’s create a model of which we will be creating instances through our view. In geeks/models.py,
# import the standard Django Model# from built-in libraryfrom django.db import models # declare a new model with a name "GeeksModel"class GeeksModel(models.Model): # fields of the model title = models.CharField(max_length = 200) description = models.TextField() # renames the instances of the model # with their title name def __str__(self): return self.title
After creating this model, we need to run two commands in order to create Database for the same.
Python manage.py makemigrations
Python manage.py migrate
Now let’s create some instances of this model using shell, run form bash,
Python manage.py shell
Enter following commands
>>> from geeks.models import GeeksModel
>>> GeeksModel.objects.create(
title="title1",
description="description1").save()
>>> GeeksModel.objects.create(
title="title2",
description="description2").save()
>>> GeeksModel.objects.create(
title="title2",
description="description2").save()
Now we have everything ready for back end. Verify that instances have been created from http://localhost:8000/admin/geeks/geeksmodel/
Class Based Views automatically setup everything from A to Z. One just needs to specify which model to create DetailView for, then Class based DetailView will automatically try to find a template in app_name/modelname_detail.html. In our case it is geeks/templates/geeks/geeksmodel_detail.html. Let’s create our class based view. In geeks/views.py,
from django.views.generic.detail import DetailView from .models import GeeksModel class GeeksDetailView(DetailView): # specify the model to use model = GeeksModel
Now create a url path to map the view. In geeks/urls.py,
from django.urls import path # importing views from views..pyfrom .views import GeeksDetailViewurlpatterns = [ # <pk> is identification for id field, # slug can also be used path('<pk>/', GeeksDetailView.as_view()),]
Create a template in templates/geeks/geeksmodel_detail.html,
<h1>{{ object.title }}</h1><p>{{ object.description }}</p>
Let’s check what is there on http://localhost:8000/1/
By default DetailView will only display fields of a table. If one wants to modify this context data before sending it to template or add some extra field, context data can be overriden.In geeks/views.py,
from django.views.generic.detail import DetailView from .models import GeeksModel class GeeksDetailView(DetailView): # specify the model to use model = GeeksModel # override context data def get_context_data(self, *args, **kwargs): context = super(GeeksDetailView, self).get_context_data(*args, **kwargs) # add extra field context["category"] = "MISC" return context
In geeks/templates/geeksmodel_detail.html,
<h1>{{ object.title }}</h1><p>{{ object.description }}</p><p>{{ category }}</p>
Now check, if the category is added.
Django-views
Python Django
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n22 Jan, 2020"
},
{
"code": null,
"e": 466,
"s": 53,
"text": "Detail View refers to a view (logic) to display one instances of a table in the database. We have already discussed basics of Detail View in Detail View – Function based Views Django. Class-based views provide an alternative way to implement views as Python objects instead of functions. They do not replace function-based views, but have certain differences and advantages when compared to function-based views:"
},
{
"code": null,
"e": 609,
"s": 466,
"text": "Organization of code related to specific HTTP methods (GET, POST, etc.) can be addressed by separate methods instead of conditional branching."
},
{
"code": null,
"e": 727,
"s": 609,
"text": "Object oriented techniques such as mixins (multiple inheritance) can be used to factor code into reusable components."
},
{
"code": null,
"e": 981,
"s": 727,
"text": "Class based views are simpler and efficient to manage than function-based views. A function based view with tons of lines of code can be converted into a class based views with few lines only. This is where Object Oriented Programming comes into impact."
},
{
"code": null,
"e": 1115,
"s": 981,
"text": "Illustration of How to create and use Detail view using an Example. Consider a project named geeksforgeeks having an app named geeks."
},
{
"code": null,
"e": 1202,
"s": 1115,
"text": "Refer to the following articles to check how to create a project and an app in Django."
},
{
"code": null,
"e": 1253,
"s": 1202,
"text": "How to Create a Basic Project using MVT in Django?"
},
{
"code": null,
"e": 1286,
"s": 1253,
"text": "How to Create an App in Django ?"
},
{
"code": null,
"e": 1421,
"s": 1286,
"text": "After you have a project and an app, let’s create a model of which we will be creating instances through our view. In geeks/models.py,"
},
{
"code": "# import the standard Django Model# from built-in libraryfrom django.db import models # declare a new model with a name \"GeeksModel\"class GeeksModel(models.Model): # fields of the model title = models.CharField(max_length = 200) description = models.TextField() # renames the instances of the model # with their title name def __str__(self): return self.title",
"e": 1812,
"s": 1421,
"text": null
},
{
"code": null,
"e": 1909,
"s": 1812,
"text": "After creating this model, we need to run two commands in order to create Database for the same."
},
{
"code": null,
"e": 1967,
"s": 1909,
"text": "Python manage.py makemigrations\nPython manage.py migrate\n"
},
{
"code": null,
"e": 2041,
"s": 1967,
"text": "Now let’s create some instances of this model using shell, run form bash,"
},
{
"code": null,
"e": 2064,
"s": 2041,
"text": "Python manage.py shell"
},
{
"code": null,
"e": 2089,
"s": 2064,
"text": "Enter following commands"
},
{
"code": null,
"e": 2514,
"s": 2089,
"text": ">>> from geeks.models import GeeksModel\n>>> GeeksModel.objects.create(\n title=\"title1\",\n description=\"description1\").save()\n>>> GeeksModel.objects.create(\n title=\"title2\",\n description=\"description2\").save()\n>>> GeeksModel.objects.create(\n title=\"title2\",\n description=\"description2\").save()\n"
},
{
"code": null,
"e": 2648,
"s": 2514,
"text": "Now we have everything ready for back end. Verify that instances have been created from http://localhost:8000/admin/geeks/geeksmodel/"
},
{
"code": null,
"e": 2997,
"s": 2648,
"text": "Class Based Views automatically setup everything from A to Z. One just needs to specify which model to create DetailView for, then Class based DetailView will automatically try to find a template in app_name/modelname_detail.html. In our case it is geeks/templates/geeks/geeksmodel_detail.html. Let’s create our class based view. In geeks/views.py,"
},
{
"code": "from django.views.generic.detail import DetailView from .models import GeeksModel class GeeksDetailView(DetailView): # specify the model to use model = GeeksModel",
"e": 3168,
"s": 2997,
"text": null
},
{
"code": null,
"e": 3225,
"s": 3168,
"text": "Now create a url path to map the view. In geeks/urls.py,"
},
{
"code": "from django.urls import path # importing views from views..pyfrom .views import GeeksDetailViewurlpatterns = [ # <pk> is identification for id field, # slug can also be used path('<pk>/', GeeksDetailView.as_view()),]",
"e": 3452,
"s": 3225,
"text": null
},
{
"code": null,
"e": 3513,
"s": 3452,
"text": "Create a template in templates/geeks/geeksmodel_detail.html,"
},
{
"code": "<h1>{{ object.title }}</h1><p>{{ object.description }}</p>",
"e": 3572,
"s": 3513,
"text": null
},
{
"code": null,
"e": 3626,
"s": 3572,
"text": "Let’s check what is there on http://localhost:8000/1/"
},
{
"code": null,
"e": 3830,
"s": 3626,
"text": "By default DetailView will only display fields of a table. If one wants to modify this context data before sending it to template or add some extra field, context data can be overriden.In geeks/views.py,"
},
{
"code": "from django.views.generic.detail import DetailView from .models import GeeksModel class GeeksDetailView(DetailView): # specify the model to use model = GeeksModel # override context data def get_context_data(self, *args, **kwargs): context = super(GeeksDetailView, self).get_context_data(*args, **kwargs) # add extra field context[\"category\"] = \"MISC\" return context",
"e": 4262,
"s": 3830,
"text": null
},
{
"code": null,
"e": 4305,
"s": 4262,
"text": "In geeks/templates/geeksmodel_detail.html,"
},
{
"code": "<h1>{{ object.title }}</h1><p>{{ object.description }}</p><p>{{ category }}</p>",
"e": 4385,
"s": 4305,
"text": null
},
{
"code": null,
"e": 4422,
"s": 4385,
"text": "Now check, if the category is added."
},
{
"code": null,
"e": 4435,
"s": 4422,
"text": "Django-views"
},
{
"code": null,
"e": 4449,
"s": 4435,
"text": "Python Django"
},
{
"code": null,
"e": 4456,
"s": 4449,
"text": "Python"
}
] |
Convert HTML table into CSV file in python | 21 Apr, 2020
CSV file is a Comma Separated Value file that uses a comma to separate values. CSV file is a useful thing in today’s world when we are talking about machine learning, data handling, and data visualization. In this article, we will discuss how to convert an HTML table into a CSV file.
Example: Suppose HTML file looks like,
HTML table can be converted to CSV file using BeautifulSoup and Pandas module of Python. These modules do not comes built-in with Python. To install them type the below command in the terminal.
pip install BeautifulSoup
pip install pandas
Python3 Code for converting the HTML table into CSV file
# Importing the required modules import osimport sysimport pandas as pdfrom bs4 import BeautifulSoup path = 'html.html' # empty listdata = [] # for getting the header from# the HTML filelist_header = []soup = BeautifulSoup(open(path),'html.parser')header = soup.find_all("table")[0].find("tr") for items in header: try: list_header.append(items.get_text()) except: continue # for getting the data HTML_data = soup.find_all("table")[0].find_all("tr")[1:] for element in HTML_data: sub_data = [] for sub_element in element: try: sub_data.append(sub_element.get_text()) except: continue data.append(sub_data) # Storing the data into Pandas# DataFrame dataFrame = pd.DataFrame(data = data, columns = list_header) # Converting Pandas DataFrame# into CSV filedataFrame.to_csv('Geeks.csv')
Output:
python-csv
python-utility
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
Iterate over a list in Python
Python OOPs Concepts | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n21 Apr, 2020"
},
{
"code": null,
"e": 339,
"s": 54,
"text": "CSV file is a Comma Separated Value file that uses a comma to separate values. CSV file is a useful thing in today’s world when we are talking about machine learning, data handling, and data visualization. In this article, we will discuss how to convert an HTML table into a CSV file."
},
{
"code": null,
"e": 378,
"s": 339,
"text": "Example: Suppose HTML file looks like,"
},
{
"code": null,
"e": 572,
"s": 378,
"text": "HTML table can be converted to CSV file using BeautifulSoup and Pandas module of Python. These modules do not comes built-in with Python. To install them type the below command in the terminal."
},
{
"code": null,
"e": 618,
"s": 572,
"text": "pip install BeautifulSoup\npip install pandas\n"
},
{
"code": null,
"e": 675,
"s": 618,
"text": "Python3 Code for converting the HTML table into CSV file"
},
{
"code": "# Importing the required modules import osimport sysimport pandas as pdfrom bs4 import BeautifulSoup path = 'html.html' # empty listdata = [] # for getting the header from# the HTML filelist_header = []soup = BeautifulSoup(open(path),'html.parser')header = soup.find_all(\"table\")[0].find(\"tr\") for items in header: try: list_header.append(items.get_text()) except: continue # for getting the data HTML_data = soup.find_all(\"table\")[0].find_all(\"tr\")[1:] for element in HTML_data: sub_data = [] for sub_element in element: try: sub_data.append(sub_element.get_text()) except: continue data.append(sub_data) # Storing the data into Pandas# DataFrame dataFrame = pd.DataFrame(data = data, columns = list_header) # Converting Pandas DataFrame# into CSV filedataFrame.to_csv('Geeks.csv')",
"e": 1535,
"s": 675,
"text": null
},
{
"code": null,
"e": 1543,
"s": 1535,
"text": "Output:"
},
{
"code": null,
"e": 1554,
"s": 1543,
"text": "python-csv"
},
{
"code": null,
"e": 1569,
"s": 1554,
"text": "python-utility"
},
{
"code": null,
"e": 1576,
"s": 1569,
"text": "Python"
},
{
"code": null,
"e": 1674,
"s": 1576,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1692,
"s": 1674,
"text": "Python Dictionary"
},
{
"code": null,
"e": 1734,
"s": 1692,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 1756,
"s": 1734,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 1791,
"s": 1756,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 1817,
"s": 1791,
"text": "Python String | replace()"
},
{
"code": null,
"e": 1849,
"s": 1817,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 1878,
"s": 1849,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 1905,
"s": 1878,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 1935,
"s": 1905,
"text": "Iterate over a list in Python"
}
] |
LMN – Digital Electronics | 28 Jun, 2021
See Last Minute Notes on all subjects here.We will discuss the important key points useful for GATE exams in summarized form. For details you may refer this.
Logic Gates:
Note: NAND and NOR gates are called UNIVERSAL GATES because all other gates can be constructed from any of them.
K-map example of 3 variables: : F(A,B,C)=π(0,3,6,7)From red group we find terms
A B C’
Taking complement of these two
A’ B’ C
Now sum up them(A’ + B’ + C)From green group we find terms
B C
Taking complement of these two terms
B’ C’
Now sum up them(B’+C’)From brown group we find terms
A’ B’ C’
Taking complement of these two
A B C
Now sum up them(A + B + C)We will take product of these three terms :Final expression (A’ + B’ + C) (B’ + C’) (A + B + C) Number of NAND or NOR gate required to implement other GATE:
Combinational circuits: In combinational circuits, output depends on present input only; it does not require any feedback and memory.
Multiplexer : It selects the input from one of many input lines and sends it single output line. The input line chosen from output is based upon set of selection lines.For 2n input lines, there will be n select lines and 1 output lines.
Note: No. of mux required to implement n x 1 mux using m x 1 mux is ceil(n-1 / m-1)A⊕B.No. of mux required to implement 16 x 1 mux using 4 x 1 mux is ceil(15/3)=5.
Demultiplexer: It selects the input from one input line and sends it to one out of many output lines. The output line chosen is based upon set of selection lines. For 1 input lines, there will be n select lines and 2n output lines.
Note: No. of mux required to implement 1 x n mux using 1 x m mux is ceil(n-1 / m-1)A⊕B.No. of mux required to implement 1 x 16 mux using 1 x 4 mux is ceil(15/3)=5.
Encoder: For 2n input lines, it has n output. It can be used to convert octal or hexadecimal to binary data.
Decoder: For n input lines, it has either 2n outputs or less then that. It can be used to convert binary data to other codes like octal or hexadecimal.
Code Converter: Code converters are used to convert one type of code to others.
BCD to Excess-3: It will add 0011(value 3) to binary code.Function:4 bit Input(ABCD) with A as MSB and 4 bit output(WXYZ) with W as MSB, O/P isZ=D’Y=CD + C’D’X=B’D + B’C + BC’D’W=A + BC + BD
Binary to Gray ConverterFunction:4 bit Input(B3B2B1B0) with B3 as MSB and 4 bit output(G3G2G1G0) with G3 as MSB, O/P isG3=B3G2=B3⊕ B2G1=B2⊕ B1G0=B1⊕ B0
Gray to Binary ConverterFunction:4 bit Input(G3G2G1G0) with G3 as MSB and 4 bit output(B3B2B1B0) with B3 as MSB, O/P isB3=G3B2=B3⊕G2B1=B2⊕G1B0=B1⊕G0
Flip-Flops: Flip-Flop are sequential circuits where O/P depends on present input as well as previous output.
S-R Flip-Flops:Characteristics equation: Qn = S + R̄ Qn
J-K Flip-Flops:Characteristics equation: Qn = J Q̄n + R̄ Qn
D Flip-Flops:Characteristics equation: Qn+1 = D
T Flip-Flops:Characteristics equation: Qn+1 = T Q̄n + T̄ Qn
Counters is a device which stores (and sometimes displays) the number of times a particular event or process has occurred, often in relationship to a clock signal.
Counters are basically divided into two types:
Asynchronous counter: In asynchronous counter we don’t use universal clock, only first flip flop is driven by main clock and the clock input of rest of the following counters is driven by output of previous flip flops.
Synchronous counter: Unlike the asynchronous counter, synchronous counter has one global clock which drives each flip flop so output changes in parallel. The one advantage of synchronous counter over asynchronous counter is, it can operate on higher frequency than asynchronous counter as it does not have cumulative delay because of same clock is given to each flip flop.
Important point: Number of flip flops used in counter are always greater than equal to (log2 n) where n=number of states in counter.
This article has been contributed by Sonal Tuteja.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
Digital Electronics & Logic Design
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n28 Jun, 2021"
},
{
"code": null,
"e": 212,
"s": 54,
"text": "See Last Minute Notes on all subjects here.We will discuss the important key points useful for GATE exams in summarized form. For details you may refer this."
},
{
"code": null,
"e": 225,
"s": 212,
"text": "Logic Gates:"
},
{
"code": null,
"e": 338,
"s": 225,
"text": "Note: NAND and NOR gates are called UNIVERSAL GATES because all other gates can be constructed from any of them."
},
{
"code": null,
"e": 418,
"s": 338,
"text": "K-map example of 3 variables: : F(A,B,C)=π(0,3,6,7)From red group we find terms"
},
{
"code": null,
"e": 433,
"s": 418,
"text": "A B C’"
},
{
"code": null,
"e": 464,
"s": 433,
"text": "Taking complement of these two"
},
{
"code": null,
"e": 480,
"s": 464,
"text": "A’ B’ C"
},
{
"code": null,
"e": 539,
"s": 480,
"text": "Now sum up them(A’ + B’ + C)From green group we find terms"
},
{
"code": null,
"e": 551,
"s": 539,
"text": "B C"
},
{
"code": null,
"e": 588,
"s": 551,
"text": "Taking complement of these two terms"
},
{
"code": null,
"e": 602,
"s": 588,
"text": "B’ C’"
},
{
"code": null,
"e": 655,
"s": 602,
"text": "Now sum up them(B’+C’)From brown group we find terms"
},
{
"code": null,
"e": 664,
"s": 655,
"text": "A’ B’ C’"
},
{
"code": null,
"e": 695,
"s": 664,
"text": "Taking complement of these two"
},
{
"code": null,
"e": 701,
"s": 695,
"text": "A B C"
},
{
"code": null,
"e": 884,
"s": 701,
"text": "Now sum up them(A + B + C)We will take product of these three terms :Final expression (A’ + B’ + C) (B’ + C’) (A + B + C) Number of NAND or NOR gate required to implement other GATE:"
},
{
"code": null,
"e": 1018,
"s": 884,
"text": "Combinational circuits: In combinational circuits, output depends on present input only; it does not require any feedback and memory."
},
{
"code": null,
"e": 1255,
"s": 1018,
"text": "Multiplexer : It selects the input from one of many input lines and sends it single output line. The input line chosen from output is based upon set of selection lines.For 2n input lines, there will be n select lines and 1 output lines."
},
{
"code": null,
"e": 1419,
"s": 1255,
"text": "Note: No. of mux required to implement n x 1 mux using m x 1 mux is ceil(n-1 / m-1)A⊕B.No. of mux required to implement 16 x 1 mux using 4 x 1 mux is ceil(15/3)=5."
},
{
"code": null,
"e": 1651,
"s": 1419,
"text": "Demultiplexer: It selects the input from one input line and sends it to one out of many output lines. The output line chosen is based upon set of selection lines. For 1 input lines, there will be n select lines and 2n output lines."
},
{
"code": null,
"e": 1815,
"s": 1651,
"text": "Note: No. of mux required to implement 1 x n mux using 1 x m mux is ceil(n-1 / m-1)A⊕B.No. of mux required to implement 1 x 16 mux using 1 x 4 mux is ceil(15/3)=5."
},
{
"code": null,
"e": 1924,
"s": 1815,
"text": "Encoder: For 2n input lines, it has n output. It can be used to convert octal or hexadecimal to binary data."
},
{
"code": null,
"e": 2076,
"s": 1924,
"text": "Decoder: For n input lines, it has either 2n outputs or less then that. It can be used to convert binary data to other codes like octal or hexadecimal."
},
{
"code": null,
"e": 2156,
"s": 2076,
"text": "Code Converter: Code converters are used to convert one type of code to others."
},
{
"code": null,
"e": 2347,
"s": 2156,
"text": "BCD to Excess-3: It will add 0011(value 3) to binary code.Function:4 bit Input(ABCD) with A as MSB and 4 bit output(WXYZ) with W as MSB, O/P isZ=D’Y=CD + C’D’X=B’D + B’C + BC’D’W=A + BC + BD"
},
{
"code": null,
"e": 2499,
"s": 2347,
"text": "Binary to Gray ConverterFunction:4 bit Input(B3B2B1B0) with B3 as MSB and 4 bit output(G3G2G1G0) with G3 as MSB, O/P isG3=B3G2=B3⊕ B2G1=B2⊕ B1G0=B1⊕ B0"
},
{
"code": null,
"e": 2648,
"s": 2499,
"text": "Gray to Binary ConverterFunction:4 bit Input(G3G2G1G0) with G3 as MSB and 4 bit output(B3B2B1B0) with B3 as MSB, O/P isB3=G3B2=B3⊕G2B1=B2⊕G1B0=B1⊕G0"
},
{
"code": null,
"e": 2757,
"s": 2648,
"text": "Flip-Flops: Flip-Flop are sequential circuits where O/P depends on present input as well as previous output."
},
{
"code": null,
"e": 2813,
"s": 2757,
"text": "S-R Flip-Flops:Characteristics equation: Qn = S + R̄ Qn"
},
{
"code": null,
"e": 2873,
"s": 2813,
"text": "J-K Flip-Flops:Characteristics equation: Qn = J Q̄n + R̄ Qn"
},
{
"code": null,
"e": 2921,
"s": 2873,
"text": "D Flip-Flops:Characteristics equation: Qn+1 = D"
},
{
"code": null,
"e": 2981,
"s": 2921,
"text": "T Flip-Flops:Characteristics equation: Qn+1 = T Q̄n + T̄ Qn"
},
{
"code": null,
"e": 3147,
"s": 2983,
"text": "Counters is a device which stores (and sometimes displays) the number of times a particular event or process has occurred, often in relationship to a clock signal."
},
{
"code": null,
"e": 3194,
"s": 3147,
"text": "Counters are basically divided into two types:"
},
{
"code": null,
"e": 3413,
"s": 3194,
"text": "Asynchronous counter: In asynchronous counter we don’t use universal clock, only first flip flop is driven by main clock and the clock input of rest of the following counters is driven by output of previous flip flops."
},
{
"code": null,
"e": 3786,
"s": 3413,
"text": "Synchronous counter: Unlike the asynchronous counter, synchronous counter has one global clock which drives each flip flop so output changes in parallel. The one advantage of synchronous counter over asynchronous counter is, it can operate on higher frequency than asynchronous counter as it does not have cumulative delay because of same clock is given to each flip flop."
},
{
"code": null,
"e": 3919,
"s": 3786,
"text": "Important point: Number of flip flops used in counter are always greater than equal to (log2 n) where n=number of states in counter."
},
{
"code": null,
"e": 3970,
"s": 3919,
"text": "This article has been contributed by Sonal Tuteja."
},
{
"code": null,
"e": 4094,
"s": 3970,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above"
},
{
"code": null,
"e": 4129,
"s": 4094,
"text": "Digital Electronics & Logic Design"
}
] |
Python | Pandas.CategoricalDtype() | 10 Mar, 2022
pandas.api.types.CategoricalDtype(categories = None, ordered = None) : This class is useful for specifying the type of Categorical data independent of the values, with categories and orderness.
Parameters- categories : [index like] Unique categorization of the categories. ordered : [boolean] If false, then the categorical is treated as unordered. Return- Type specification for categorical data
Code:
Python3
# Python code explaining# numpy.pandas.CategoricalDtype() # importing librariesimport numpy as npimport pandas as pdfrom pandas.api.types import CategoricalDtype a = CategoricalDtype(['a', 'b', 'c'], ordered=True)print ("a : ", a) b = CategoricalDtype(['a', 'b', 'c'])print ("\nb : ", b) print ("\nTrue / False : ", a == CategoricalDtype(['a', 'b', 'c'], ordered=False)) c = pd.api.types.CategoricalDtype(categories=["a","b","d","c"], ordered=True)print ("\nType : ", c)
Python3
c1 = pd.Series(['a', 'b', 'a', 'e'], dtype = c)print ("c1 : \n", c1) c2 = pd.DataFrame({'A': list('abca'), 'B': list('bccd')}) c3 = CategoricalDtype(categories=list('abcd'), ordered=True) c4 = c2.astype(c3) print ("\n c4['A'] : \n", c4['A'])
rkbhola5
Python pandas-datatypes
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n10 Mar, 2022"
},
{
"code": null,
"e": 224,
"s": 28,
"text": "pandas.api.types.CategoricalDtype(categories = None, ordered = None) : This class is useful for specifying the type of Categorical data independent of the values, with categories and orderness. "
},
{
"code": null,
"e": 427,
"s": 224,
"text": "Parameters- categories : [index like] Unique categorization of the categories. ordered : [boolean] If false, then the categorical is treated as unordered. Return- Type specification for categorical data"
},
{
"code": null,
"e": 435,
"s": 427,
"text": "Code: "
},
{
"code": null,
"e": 443,
"s": 435,
"text": "Python3"
},
{
"code": "# Python code explaining# numpy.pandas.CategoricalDtype() # importing librariesimport numpy as npimport pandas as pdfrom pandas.api.types import CategoricalDtype a = CategoricalDtype(['a', 'b', 'c'], ordered=True)print (\"a : \", a) b = CategoricalDtype(['a', 'b', 'c'])print (\"\\nb : \", b) print (\"\\nTrue / False : \", a == CategoricalDtype(['a', 'b', 'c'], ordered=False)) c = pd.api.types.CategoricalDtype(categories=[\"a\",\"b\",\"d\",\"c\"], ordered=True)print (\"\\nType : \", c)",
"e": 971,
"s": 443,
"text": null
},
{
"code": null,
"e": 979,
"s": 971,
"text": "Python3"
},
{
"code": "c1 = pd.Series(['a', 'b', 'a', 'e'], dtype = c)print (\"c1 : \\n\", c1) c2 = pd.DataFrame({'A': list('abca'), 'B': list('bccd')}) c3 = CategoricalDtype(categories=list('abcd'), ordered=True) c4 = c2.astype(c3) print (\"\\n c4['A'] : \\n\", c4['A'])",
"e": 1227,
"s": 979,
"text": null
},
{
"code": null,
"e": 1236,
"s": 1227,
"text": "rkbhola5"
},
{
"code": null,
"e": 1260,
"s": 1236,
"text": "Python pandas-datatypes"
},
{
"code": null,
"e": 1274,
"s": 1260,
"text": "Python-pandas"
},
{
"code": null,
"e": 1281,
"s": 1274,
"text": "Python"
}
] |
How to convert an object to string using JavaScript? | 23 May, 2019
Below are the methods to convert different objects to string.Method 1: Using the function String()The String() function converts the value of an object to a string.Syntax:
String(object)
Parameter:
JavaScript Object
Example :
<script> var bool_to_s1 = Boolean(0);var bool_to_s2 = Boolean(1);var num_to_s = 1234; document.write( typeof( bool_to_s1)+"<br>"); document.write( typeof(String( bool_to_s1))+ "<br>"); document.write( typeof( bool_to_s2)+ "<br>"); document.write(typeof(String( bool_to_s2))+ "<br>"); document.write( typeof( num_to_s)+ "<br>"); document.write(typeof(String( num_to_s))+ "<br>"); </script>
Output:
boolean
string
boolean
string
number
string
Method 2:Using JSON.stringify()JSON.stringify() converts the javascript object to string which is needed to send data over web server.
Syntax:
JSON.stringify(obj)
Parameter:
Can be object, array
Example:
<script>var obj_to_str = { name: "GeeksForGeeks", city: "Noida", contact:2488 };var myJSON = JSON.stringify(obj_to_str);document.write(myJSON)</script>
Output:
{"name":"GeeksForGeeks", "city":"Noida", "contact":2488}
More about JSON.stringify()
javascript-object
javascript-string
Picked
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
Difference Between PUT and PATCH Request
Roadmap to Learn JavaScript For Beginners
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ? | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n23 May, 2019"
},
{
"code": null,
"e": 200,
"s": 28,
"text": "Below are the methods to convert different objects to string.Method 1: Using the function String()The String() function converts the value of an object to a string.Syntax:"
},
{
"code": null,
"e": 215,
"s": 200,
"text": "String(object)"
},
{
"code": null,
"e": 226,
"s": 215,
"text": "Parameter:"
},
{
"code": null,
"e": 244,
"s": 226,
"text": "JavaScript Object"
},
{
"code": null,
"e": 254,
"s": 244,
"text": "Example :"
},
{
"code": "<script> var bool_to_s1 = Boolean(0);var bool_to_s2 = Boolean(1);var num_to_s = 1234; document.write( typeof( bool_to_s1)+\"<br>\"); document.write( typeof(String( bool_to_s1))+ \"<br>\"); document.write( typeof( bool_to_s2)+ \"<br>\"); document.write(typeof(String( bool_to_s2))+ \"<br>\"); document.write( typeof( num_to_s)+ \"<br>\"); document.write(typeof(String( num_to_s))+ \"<br>\"); </script> ",
"e": 674,
"s": 254,
"text": null
},
{
"code": null,
"e": 682,
"s": 674,
"text": "Output:"
},
{
"code": null,
"e": 726,
"s": 682,
"text": "boolean\nstring\nboolean\nstring\nnumber\nstring"
},
{
"code": null,
"e": 861,
"s": 726,
"text": "Method 2:Using JSON.stringify()JSON.stringify() converts the javascript object to string which is needed to send data over web server."
},
{
"code": null,
"e": 869,
"s": 861,
"text": "Syntax:"
},
{
"code": null,
"e": 890,
"s": 869,
"text": " JSON.stringify(obj)"
},
{
"code": null,
"e": 901,
"s": 890,
"text": "Parameter:"
},
{
"code": null,
"e": 922,
"s": 901,
"text": "Can be object, array"
},
{
"code": null,
"e": 931,
"s": 922,
"text": "Example:"
},
{
"code": "<script>var obj_to_str = { name: \"GeeksForGeeks\", city: \"Noida\", contact:2488 };var myJSON = JSON.stringify(obj_to_str);document.write(myJSON)</script>",
"e": 1083,
"s": 931,
"text": null
},
{
"code": null,
"e": 1091,
"s": 1083,
"text": "Output:"
},
{
"code": null,
"e": 1148,
"s": 1091,
"text": "{\"name\":\"GeeksForGeeks\", \"city\":\"Noida\", \"contact\":2488}"
},
{
"code": null,
"e": 1176,
"s": 1148,
"text": "More about JSON.stringify()"
},
{
"code": null,
"e": 1194,
"s": 1176,
"text": "javascript-object"
},
{
"code": null,
"e": 1212,
"s": 1194,
"text": "javascript-string"
},
{
"code": null,
"e": 1219,
"s": 1212,
"text": "Picked"
},
{
"code": null,
"e": 1230,
"s": 1219,
"text": "JavaScript"
},
{
"code": null,
"e": 1247,
"s": 1230,
"text": "Web Technologies"
},
{
"code": null,
"e": 1345,
"s": 1247,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1406,
"s": 1345,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 1478,
"s": 1406,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 1518,
"s": 1478,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 1559,
"s": 1518,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 1601,
"s": 1559,
"text": "Roadmap to Learn JavaScript For Beginners"
},
{
"code": null,
"e": 1663,
"s": 1601,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 1696,
"s": 1663,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 1757,
"s": 1696,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 1807,
"s": 1757,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
How to create texture background using CSS ? | 18 Jun, 2020
Introduction: We can use CSS property to texture the background of web page by using an image editor to cut out a portion of the background. Apply CSS background-repeat property to make the small image fill the area where it is used. CSS provides many styling properties of background including coloring the background, background images, etc. Background properties are background-color, background-image, background-position, background-attachment.
Approach of texturing the background: There are some steps for texturing the background using CSS with example and the explanation.
Create a html file using html tags.<html> <head> <title> Texture Background Using CSS </title></head><body></body> </html>
<html> <head> <title> Texture Background Using CSS </title></head><body></body> </html>
Choose the texture color that we want to set in Background. Save the texture color in image format like(.png, .jpg etc)
Suppose we want to set the background of this web page using internal sheet CSS. So write the following code in head section.<style> body { background-image: url("BG.jpg"); background-repeat: repeat/no-repeat; background-size: 1600px 840px: }</style>
<style> body { background-image: url("BG.jpg"); background-repeat: repeat/no-repeat; background-size: 1600px 840px: }</style>
Example:
<!DOCTYPE><html> <head> <title> Texture Background using CSS </title> <style> body { background-image: url("https://contribute.geeksforgeeks.org/wp-content/uploads/backgroundimage-1.png"); background-repeat: no-repeapt; } </style></head> <body> <h1> This is our texture background </h1></body> </html>
Explanation: In this code, we are placing the image in the background through background-image:url(“backgroundimage-1.png”); in the form of .jpg. It can be in .png also.Here, we are not repeating the image in the background so, the image shown only one time in the background, background-repeat:no-repeapt; this syntax means image is not repeating. These all commands are written in <style> tag using CSS.Output:
Akanksha_Rai
CSS-Misc
HTML-Misc
Picked
CSS
HTML
Web Technologies
Web technologies Questions
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Types of CSS (Cascading Style Sheet)
Design a Tribute Page using HTML & CSS
How to set space between the flexbox ?
How to position a div at the bottom of its container using CSS?
How to Upload Image into Database and Display it using PHP ?
REST API (Introduction)
Hide or show elements in HTML using display property
How to set the default value for an HTML <select> element ?
How to set input type date in dd-mm-yyyy format using HTML ?
Types of CSS (Cascading Style Sheet) | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n18 Jun, 2020"
},
{
"code": null,
"e": 478,
"s": 28,
"text": "Introduction: We can use CSS property to texture the background of web page by using an image editor to cut out a portion of the background. Apply CSS background-repeat property to make the small image fill the area where it is used. CSS provides many styling properties of background including coloring the background, background images, etc. Background properties are background-color, background-image, background-position, background-attachment."
},
{
"code": null,
"e": 610,
"s": 478,
"text": "Approach of texturing the background: There are some steps for texturing the background using CSS with example and the explanation."
},
{
"code": null,
"e": 756,
"s": 610,
"text": "Create a html file using html tags.<html> <head> <title> Texture Background Using CSS </title></head><body></body> </html>"
},
{
"code": "<html> <head> <title> Texture Background Using CSS </title></head><body></body> </html>",
"e": 867,
"s": 756,
"text": null
},
{
"code": null,
"e": 987,
"s": 867,
"text": "Choose the texture color that we want to set in Background. Save the texture color in image format like(.png, .jpg etc)"
},
{
"code": null,
"e": 1265,
"s": 987,
"text": "Suppose we want to set the background of this web page using internal sheet CSS. So write the following code in head section.<style> body { background-image: url(\"BG.jpg\"); background-repeat: repeat/no-repeat; background-size: 1600px 840px: }</style>"
},
{
"code": "<style> body { background-image: url(\"BG.jpg\"); background-repeat: repeat/no-repeat; background-size: 1600px 840px: }</style>",
"e": 1418,
"s": 1265,
"text": null
},
{
"code": null,
"e": 1427,
"s": 1418,
"text": "Example:"
},
{
"code": "<!DOCTYPE><html> <head> <title> Texture Background using CSS </title> <style> body { background-image: url(\"https://contribute.geeksforgeeks.org/wp-content/uploads/backgroundimage-1.png\"); background-repeat: no-repeapt; } </style></head> <body> <h1> This is our texture background </h1></body> </html>",
"e": 1809,
"s": 1427,
"text": null
},
{
"code": null,
"e": 2222,
"s": 1809,
"text": "Explanation: In this code, we are placing the image in the background through background-image:url(“backgroundimage-1.png”); in the form of .jpg. It can be in .png also.Here, we are not repeating the image in the background so, the image shown only one time in the background, background-repeat:no-repeapt; this syntax means image is not repeating. These all commands are written in <style> tag using CSS.Output:"
},
{
"code": null,
"e": 2235,
"s": 2222,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 2244,
"s": 2235,
"text": "CSS-Misc"
},
{
"code": null,
"e": 2254,
"s": 2244,
"text": "HTML-Misc"
},
{
"code": null,
"e": 2261,
"s": 2254,
"text": "Picked"
},
{
"code": null,
"e": 2265,
"s": 2261,
"text": "CSS"
},
{
"code": null,
"e": 2270,
"s": 2265,
"text": "HTML"
},
{
"code": null,
"e": 2287,
"s": 2270,
"text": "Web Technologies"
},
{
"code": null,
"e": 2314,
"s": 2287,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 2319,
"s": 2314,
"text": "HTML"
},
{
"code": null,
"e": 2417,
"s": 2319,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2454,
"s": 2417,
"text": "Types of CSS (Cascading Style Sheet)"
},
{
"code": null,
"e": 2493,
"s": 2454,
"text": "Design a Tribute Page using HTML & CSS"
},
{
"code": null,
"e": 2532,
"s": 2493,
"text": "How to set space between the flexbox ?"
},
{
"code": null,
"e": 2596,
"s": 2532,
"text": "How to position a div at the bottom of its container using CSS?"
},
{
"code": null,
"e": 2657,
"s": 2596,
"text": "How to Upload Image into Database and Display it using PHP ?"
},
{
"code": null,
"e": 2681,
"s": 2657,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 2734,
"s": 2681,
"text": "Hide or show elements in HTML using display property"
},
{
"code": null,
"e": 2794,
"s": 2734,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 2855,
"s": 2794,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
}
] |
Partial Methods in C# | 23 Jan, 2019
C# contains a special method is known as a partial method, which contains declaration part in one partial class and definition part in another partial class or may contain both declaration and definition in the same partial class.Basically, partial methods exist in the partial class, or in the struct. A partial method may or may not contain implementation if a partial method doesn’t contain an implementation in any part then the compiler will not create that method in the final class or driver class. A partial method is declared with the help of the partial keyword as shown below.
Syntax:
partial void method_name
{
// Code
}
Important Points:
The declaration of the partial method must begin with partial modifier.
The partial method may contain ref.
The partial method does not contain out parameters.
It is implicitly private method.
It can be a static method.
Partial method is generic.
It can have only void return type.
A partial method is created only in partial class or in partial struct.
Example: We have a class named as Circle. The functionality of the Circle class is chopped into two different files named as circle1.cs and circle2.cs. These circle1.cs and circle2.cs files contain the partial class of the Circle class and partial method, i.e area. The circle1.cs file contains the declaration of the partial area() method and circle2.cs file contains the implementation of the area method as shown below:
circle1.cs
public partial class Circle { // This file only contains // declaration of partial method partial void area(int p); public void Display() { Console.WriteLine("Example of partial method"); }}
circle2.cs
public partial class Circle { public void newarea(int a) { area(int a); } // This is the definition of // partial method partial void area(int r) { int A = 3.14 * r * r; Console.WriteLine("Area is : {0}", A); }}
When we execute the above code, then compiler combines circle1.cs and circle2.cs into a single file, i.e. circle as shown below.
circle
public class Circle { public void Display() { Console.WriteLine("Example of partial method"); } public void newarea(int a) { area(int a); } private void area(int r) { int A = 3.14 * r * r; Console.WriteLine("Area is : {0}", A); }}
CSharp-OOP
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to .NET Framework
C# | Multiple inheritance using interfaces
Differences Between .NET Core and .NET Framework
C# | Constructors
C# | String.IndexOf( ) Method | Set - 1
C# | Class and Object
Difference between Ref and Out keywords in C#
C# | Arrays
C# | Encapsulation
C# | Replace() Method | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n23 Jan, 2019"
},
{
"code": null,
"e": 640,
"s": 52,
"text": "C# contains a special method is known as a partial method, which contains declaration part in one partial class and definition part in another partial class or may contain both declaration and definition in the same partial class.Basically, partial methods exist in the partial class, or in the struct. A partial method may or may not contain implementation if a partial method doesn’t contain an implementation in any part then the compiler will not create that method in the final class or driver class. A partial method is declared with the help of the partial keyword as shown below."
},
{
"code": null,
"e": 648,
"s": 640,
"text": "Syntax:"
},
{
"code": null,
"e": 690,
"s": 648,
"text": "partial void method_name\n{\n // Code\n}\n"
},
{
"code": null,
"e": 708,
"s": 690,
"text": "Important Points:"
},
{
"code": null,
"e": 780,
"s": 708,
"text": "The declaration of the partial method must begin with partial modifier."
},
{
"code": null,
"e": 816,
"s": 780,
"text": "The partial method may contain ref."
},
{
"code": null,
"e": 868,
"s": 816,
"text": "The partial method does not contain out parameters."
},
{
"code": null,
"e": 901,
"s": 868,
"text": "It is implicitly private method."
},
{
"code": null,
"e": 928,
"s": 901,
"text": "It can be a static method."
},
{
"code": null,
"e": 955,
"s": 928,
"text": "Partial method is generic."
},
{
"code": null,
"e": 990,
"s": 955,
"text": "It can have only void return type."
},
{
"code": null,
"e": 1062,
"s": 990,
"text": "A partial method is created only in partial class or in partial struct."
},
{
"code": null,
"e": 1485,
"s": 1062,
"text": "Example: We have a class named as Circle. The functionality of the Circle class is chopped into two different files named as circle1.cs and circle2.cs. These circle1.cs and circle2.cs files contain the partial class of the Circle class and partial method, i.e area. The circle1.cs file contains the declaration of the partial area() method and circle2.cs file contains the implementation of the area method as shown below:"
},
{
"code": null,
"e": 1496,
"s": 1485,
"text": "circle1.cs"
},
{
"code": "public partial class Circle { // This file only contains // declaration of partial method partial void area(int p); public void Display() { Console.WriteLine(\"Example of partial method\"); }}",
"e": 1716,
"s": 1496,
"text": null
},
{
"code": null,
"e": 1727,
"s": 1716,
"text": "circle2.cs"
},
{
"code": "public partial class Circle { public void newarea(int a) { area(int a); } // This is the definition of // partial method partial void area(int r) { int A = 3.14 * r * r; Console.WriteLine(\"Area is : {0}\", A); }}",
"e": 1988,
"s": 1727,
"text": null
},
{
"code": null,
"e": 2117,
"s": 1988,
"text": "When we execute the above code, then compiler combines circle1.cs and circle2.cs into a single file, i.e. circle as shown below."
},
{
"code": null,
"e": 2124,
"s": 2117,
"text": "circle"
},
{
"code": "public class Circle { public void Display() { Console.WriteLine(\"Example of partial method\"); } public void newarea(int a) { area(int a); } private void area(int r) { int A = 3.14 * r * r; Console.WriteLine(\"Area is : {0}\", A); }}",
"e": 2416,
"s": 2124,
"text": null
},
{
"code": null,
"e": 2427,
"s": 2416,
"text": "CSharp-OOP"
},
{
"code": null,
"e": 2430,
"s": 2427,
"text": "C#"
},
{
"code": null,
"e": 2528,
"s": 2430,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2559,
"s": 2528,
"text": "Introduction to .NET Framework"
},
{
"code": null,
"e": 2602,
"s": 2559,
"text": "C# | Multiple inheritance using interfaces"
},
{
"code": null,
"e": 2651,
"s": 2602,
"text": "Differences Between .NET Core and .NET Framework"
},
{
"code": null,
"e": 2669,
"s": 2651,
"text": "C# | Constructors"
},
{
"code": null,
"e": 2709,
"s": 2669,
"text": "C# | String.IndexOf( ) Method | Set - 1"
},
{
"code": null,
"e": 2731,
"s": 2709,
"text": "C# | Class and Object"
},
{
"code": null,
"e": 2777,
"s": 2731,
"text": "Difference between Ref and Out keywords in C#"
},
{
"code": null,
"e": 2789,
"s": 2777,
"text": "C# | Arrays"
},
{
"code": null,
"e": 2808,
"s": 2789,
"text": "C# | Encapsulation"
}
] |
Program to find number of solutions in Quadratic Equation | 22 Apr, 2021
Given an equation with value a, b, and c, where a and b is any value and c is constant, find how many solutions thus this quadratic equation have?Examples:
Input :
Output : 2 solutions
Input :
Output : no solution
Solution: To check whether the equation has a solution or not, quadratic formula for discriminant is used.
The formula is given as,
Respective conditions are given as,
if the discriminant is positive , then the quadratic equation has two solutions.
if the discriminant is equal , then the quadratic equation has one solution.
if the discriminant is negative , then the quadratic equation has no solution.
Programs:
C++
Java
Python3
C#
PHP
Javascript
// C++ Program to find the solutions of specified equations#include <iostream>using namespace std; // Method to check for solutions of equationsvoid checkSolution(int a, int b, int c){ // If the expression is greater than 0, then 2 solutions if (((b * b) - (4 * a * c)) > 0) cout << "2 solutions"; // If the expression is equal 0, then 2 solutions else if (((b * b) - (4 * a * c)) == 0) cout << "1 solution"; // Else no solutions else cout << "No solutions";} int main(){ int a = 2, b = 5, c = 2; checkSolution(a, b, c); return 0;}
// Java Program to find the solutions of specified equationspublic class GFG { // Method to check for solutions of equations static void checkSolution(int a, int b, int c) { // If the expression is greater than 0, // then 2 solutions if (((b * b) - (4 * a * c)) > 0) System.out.println("2 solutions"); // If the expression is equal 0, then 2 solutions else if (((b * b) - (4 * a * c)) == 0) System.out.println("1 solution"); // Else no solutions else System.out.println("No solutions"); } // Driver Code public static void main(String[] args) { int a = 2, b = 5, c = 2; checkSolution(a, b, c); }}
# Python3 Program to find the# solutions of specified equations # function to check for# solutions of equationsdef checkSolution(a, b, c) : # If the expression is greater # than 0, then 2 solutions if ((b * b) - (4 * a * c)) > 0 : print("2 solutions") # If the expression is equal 0, # then 1 solutions elif ((b * b) - (4 * a * c)) == 0 : print("1 solution") # Else no solutions else : print("No solutions") # Driver codeif __name__ == "__main__" : a, b, c = 2, 5, 2 checkSolution(a, b, c) # This code is contributed# by ANKITRAI1
// C# Program to find the solutions// of specified equationsusing System;class GFG{ // Method to check for solutions of equationsstatic void checkSolution(int a, int b, int c){ // If the expression is greater // than 0, then 2 solutions if (((b * b) - (4 * a * c)) > 0) Console.WriteLine("2 solutions"); // If the expression is equal to 0, // then 2 solutions else if (((b * b) - (4 * a * c)) == 0) Console.WriteLine("1 solution"); // Else no solutions else Console.WriteLine("No solutions");} // Driver Codepublic static void Main(){ int a = 2, b = 5, c = 2; checkSolution(a, b, c);}} // This code is contributed by inder_verma
<?php// Program to find the solutions// of specified equations // Method to check for solutions// of equationsfunction checkSolution($a, $b, $c){ // If the expression is greater // than 0, then 2 solutions if ((($b * $b) - (4 * $a * $c)) > 0) echo "2 solutions"; // If the expression is equal 0, // then 2 solutions else if ((($b * $b) - (4 * $a * $c)) == 0) echo "1 solution"; // Else no solutions else echo"No solutions";} // Driver Code$a = 2; $b = 5; $c = 2;checkSolution($a, $b, $c); // This code is contributed// by inder_verma?>
<script> // Javascript Program to find the solutions// of specified equations // Method to check for solutions of equationsfunction checkSolution(a, b, c){ // If the expression is greater than 0, // then 2 solutions if (((b * b) - (4 * a * c)) > 0) document.write("2 solutions"); // If the expression is equal 0, then 2 solutions else if (((b * b) - (4 * a * c)) == 0) document.write("1 solution"); // Else no solutions else document.write("No solutions");} // Driver Codevar a = 2, b = 5, c = 2; checkSolution(a, b, c); // This code is contributed by Ankita saini </script>
Output:
2 solutions
inderDuMCA
ankthon
ankita_saini
Algebra
Technical Scripter 2018
Mathematical
School Programming
Technical Scripter
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Algorithm to solve Rubik's Cube
Program to print prime numbers from 1 to N.
Merge two sorted arrays with O(1) extra space
Segment Tree | Set 1 (Sum of given range)
Fizz Buzz Implementation
Python Dictionary
Reverse a string in Java
Arrays in C/C++
Introduction To PYTHON
Interfaces in Java | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n22 Apr, 2021"
},
{
"code": null,
"e": 186,
"s": 28,
"text": "Given an equation with value a, b, and c, where a and b is any value and c is constant, find how many solutions thus this quadratic equation have?Examples: "
},
{
"code": null,
"e": 246,
"s": 186,
"text": "Input : \nOutput : 2 solutions\nInput : \nOutput : no solution"
},
{
"code": null,
"e": 354,
"s": 246,
"text": "Solution: To check whether the equation has a solution or not, quadratic formula for discriminant is used. "
},
{
"code": null,
"e": 380,
"s": 354,
"text": "The formula is given as, "
},
{
"code": null,
"e": 418,
"s": 380,
"text": "Respective conditions are given as, "
},
{
"code": null,
"e": 499,
"s": 418,
"text": "if the discriminant is positive , then the quadratic equation has two solutions."
},
{
"code": null,
"e": 576,
"s": 499,
"text": "if the discriminant is equal , then the quadratic equation has one solution."
},
{
"code": null,
"e": 655,
"s": 576,
"text": "if the discriminant is negative , then the quadratic equation has no solution."
},
{
"code": null,
"e": 667,
"s": 655,
"text": "Programs: "
},
{
"code": null,
"e": 671,
"s": 667,
"text": "C++"
},
{
"code": null,
"e": 676,
"s": 671,
"text": "Java"
},
{
"code": null,
"e": 684,
"s": 676,
"text": "Python3"
},
{
"code": null,
"e": 687,
"s": 684,
"text": "C#"
},
{
"code": null,
"e": 691,
"s": 687,
"text": "PHP"
},
{
"code": null,
"e": 702,
"s": 691,
"text": "Javascript"
},
{
"code": "// C++ Program to find the solutions of specified equations#include <iostream>using namespace std; // Method to check for solutions of equationsvoid checkSolution(int a, int b, int c){ // If the expression is greater than 0, then 2 solutions if (((b * b) - (4 * a * c)) > 0) cout << \"2 solutions\"; // If the expression is equal 0, then 2 solutions else if (((b * b) - (4 * a * c)) == 0) cout << \"1 solution\"; // Else no solutions else cout << \"No solutions\";} int main(){ int a = 2, b = 5, c = 2; checkSolution(a, b, c); return 0;}",
"e": 1285,
"s": 702,
"text": null
},
{
"code": "// Java Program to find the solutions of specified equationspublic class GFG { // Method to check for solutions of equations static void checkSolution(int a, int b, int c) { // If the expression is greater than 0, // then 2 solutions if (((b * b) - (4 * a * c)) > 0) System.out.println(\"2 solutions\"); // If the expression is equal 0, then 2 solutions else if (((b * b) - (4 * a * c)) == 0) System.out.println(\"1 solution\"); // Else no solutions else System.out.println(\"No solutions\"); } // Driver Code public static void main(String[] args) { int a = 2, b = 5, c = 2; checkSolution(a, b, c); }}",
"e": 2007,
"s": 1285,
"text": null
},
{
"code": "# Python3 Program to find the# solutions of specified equations # function to check for# solutions of equationsdef checkSolution(a, b, c) : # If the expression is greater # than 0, then 2 solutions if ((b * b) - (4 * a * c)) > 0 : print(\"2 solutions\") # If the expression is equal 0, # then 1 solutions elif ((b * b) - (4 * a * c)) == 0 : print(\"1 solution\") # Else no solutions else : print(\"No solutions\") # Driver codeif __name__ == \"__main__\" : a, b, c = 2, 5, 2 checkSolution(a, b, c) # This code is contributed# by ANKITRAI1",
"e": 2593,
"s": 2007,
"text": null
},
{
"code": "// C# Program to find the solutions// of specified equationsusing System;class GFG{ // Method to check for solutions of equationsstatic void checkSolution(int a, int b, int c){ // If the expression is greater // than 0, then 2 solutions if (((b * b) - (4 * a * c)) > 0) Console.WriteLine(\"2 solutions\"); // If the expression is equal to 0, // then 2 solutions else if (((b * b) - (4 * a * c)) == 0) Console.WriteLine(\"1 solution\"); // Else no solutions else Console.WriteLine(\"No solutions\");} // Driver Codepublic static void Main(){ int a = 2, b = 5, c = 2; checkSolution(a, b, c);}} // This code is contributed by inder_verma",
"e": 3276,
"s": 2593,
"text": null
},
{
"code": "<?php// Program to find the solutions// of specified equations // Method to check for solutions// of equationsfunction checkSolution($a, $b, $c){ // If the expression is greater // than 0, then 2 solutions if ((($b * $b) - (4 * $a * $c)) > 0) echo \"2 solutions\"; // If the expression is equal 0, // then 2 solutions else if ((($b * $b) - (4 * $a * $c)) == 0) echo \"1 solution\"; // Else no solutions else echo\"No solutions\";} // Driver Code$a = 2; $b = 5; $c = 2;checkSolution($a, $b, $c); // This code is contributed// by inder_verma?>",
"e": 3873,
"s": 3276,
"text": null
},
{
"code": "<script> // Javascript Program to find the solutions// of specified equations // Method to check for solutions of equationsfunction checkSolution(a, b, c){ // If the expression is greater than 0, // then 2 solutions if (((b * b) - (4 * a * c)) > 0) document.write(\"2 solutions\"); // If the expression is equal 0, then 2 solutions else if (((b * b) - (4 * a * c)) == 0) document.write(\"1 solution\"); // Else no solutions else document.write(\"No solutions\");} // Driver Codevar a = 2, b = 5, c = 2; checkSolution(a, b, c); // This code is contributed by Ankita saini </script>",
"e": 4497,
"s": 3873,
"text": null
},
{
"code": null,
"e": 4506,
"s": 4497,
"text": "Output: "
},
{
"code": null,
"e": 4518,
"s": 4506,
"text": "2 solutions"
},
{
"code": null,
"e": 4531,
"s": 4520,
"text": "inderDuMCA"
},
{
"code": null,
"e": 4539,
"s": 4531,
"text": "ankthon"
},
{
"code": null,
"e": 4552,
"s": 4539,
"text": "ankita_saini"
},
{
"code": null,
"e": 4560,
"s": 4552,
"text": "Algebra"
},
{
"code": null,
"e": 4584,
"s": 4560,
"text": "Technical Scripter 2018"
},
{
"code": null,
"e": 4597,
"s": 4584,
"text": "Mathematical"
},
{
"code": null,
"e": 4616,
"s": 4597,
"text": "School Programming"
},
{
"code": null,
"e": 4635,
"s": 4616,
"text": "Technical Scripter"
},
{
"code": null,
"e": 4648,
"s": 4635,
"text": "Mathematical"
},
{
"code": null,
"e": 4746,
"s": 4648,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4778,
"s": 4746,
"text": "Algorithm to solve Rubik's Cube"
},
{
"code": null,
"e": 4822,
"s": 4778,
"text": "Program to print prime numbers from 1 to N."
},
{
"code": null,
"e": 4868,
"s": 4822,
"text": "Merge two sorted arrays with O(1) extra space"
},
{
"code": null,
"e": 4910,
"s": 4868,
"text": "Segment Tree | Set 1 (Sum of given range)"
},
{
"code": null,
"e": 4935,
"s": 4910,
"text": "Fizz Buzz Implementation"
},
{
"code": null,
"e": 4953,
"s": 4935,
"text": "Python Dictionary"
},
{
"code": null,
"e": 4978,
"s": 4953,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 4994,
"s": 4978,
"text": "Arrays in C/C++"
},
{
"code": null,
"e": 5017,
"s": 4994,
"text": "Introduction To PYTHON"
}
] |
Is Learning Rate Useful in Artificial Neural Networks? | by Ahmed Gad | Towards Data Science | This article will help you understand why we need the learning rate and whether it is useful or not for training an artificial neural network. Using a very simple Python code for a single layer perceptron, the learning rate value will get changed to catch its idea.
An obstacle for newbies in artificial neural networks is the learning rate. I was asked many times about the effect of the learning rate in the training of the artificial neural networks (ANNs). Why we use learning rate? What is the best value for the learning rate? In this article, I will try to make things simpler by providing an example that shows how learning rate is useful in order to train an ANN. I will start by explaining our example with Python code before working with the learning rate.
A very very simple example is used to get us out of complexity and allow us to just focus on the learning rate. A single numerical input will get applied to a single layer perceptron. If the input is 250 or smaller, its value will get returned as the output of the network. If the input is larger than 250, then it will be clipped to just 250. Figure 1 shows a table with the 6 samples used for training.
The architecture of the ANN used is shown in figure 2. There are just input and output layers. The input layer has just a single neuron for our single input. The output layer has just a single neuron for generating the output. The output layer neuron is responsible for mapping the input to the correct output. There is also a bias applied to the output layer neuron with weight b and value +1. There is also a weight W for the input.
The equation and the graph of the activation function used in this example are as shown figure 3. When the input is below or equal to 250, the output will be the same as the input. Otherwise, it will be clipped to 250.
The Python code implementing the entire network is shown below. We will discuss all of it until making it easy as much as possible then focus on changing the learning rate to find out how it affects the network training.
1. import numpy 2. 3. def activation_function(inpt): 4. if(inpt > 250): 5. return 250 # clip the result to 250 6. else: 7. return inpt # just return the input 8. 9. def prediction_error(desired, expected): 10. return numpy.abs(numpy.mean(desired-expected)) # absolute error 11. 12. def update_weights(weights, predicted, idx): 13. weights = weights + .00001*(desired_output[idx] - predicted)*inputs[idx] # updating weights 14. return weights # new updated weights 15. 16. weights = numpy.array([0.05, .1]) #bias & weight of input 17. inputs = numpy.array([60, 40, 100, 300, -50, 310]) # training inputs 18. desired_output = numpy.array([60, 40, 150, 250, -50, 250]) # training outputs 19. 20. def training_loop(inpt, weights): 21. error = 1 22. idx = 0 # start by the first training sample 23. iteration = 0 #loop iteration variable 24. while(iteration < 2000 or error >= 0.01): #while(error >= 0.1): 25. predicted = activation_function(weights[0]*1+weights[1]*inputs[idx]) 26. error = prediction_error(desired_output[idx], predicted) 27. weights = update_weights(weights, predicted, idx) 28. idx = idx + 1 # go to the next sample 29. idx = idx % inputs.shape[0] # restricts the index to the range of our samples 30. iteration = iteration + 1 # next iteration 31. return error, weights 32. 33. error, new_weights = training_loop(inputs, weights) 34. print('--------------Final Results----------------') 35. print('Learned Weights : ', new_weights) 36. new_inputs = numpy.array([10, 240, 550, -160]) 37. new_outputs = numpy.array([10, 240, 250, -160]) 38. for i in range(new_inputs.shape[0]): 39. print('Sample ', i+1, '. Expected = ', new_outputs[i], ' , Predicted = ', activation_function(new_weights[0]*1+new_weights[1]*new_inputs[i]))
Lines 17 and 18 are responsible for creating two arrays (inputs and desired_output) holding the training input and output data presented in the previous table. Each input will have an output according to the activation function used.
Line 16 creates an array of the network weights. There are just two weights: one for the input and another for the bias. They were randomly initialized to 0.05 for the bias and 0.1 for the input.
The activation function itself is implemented using the activation_function(inpt) method from line 3 to 7. It accepts a single argument which is the input and returns a single value which is the expected output.
Because there may be an error in the prediction, we need to measure that error to know how far we are from the correct prediction. For that reason, there is a method implemented from line 9 to 10 called prediction_error(desired, expected) that accepts two inputs: the desired and expected outputs. That method just calculates the absolute difference between each desired and expected outputs. The best value for any error is for sure 0. This is the optimal value.
What if there was a prediction error? In this case, we must make a change to the network. But what exactly to change? It is the network weights. For updating the network weights, there is a method called update_weights(weights, predicted, idx) defined from line 13 to 14. It accepts three inputs: old weights, predicted output, and the index of the input that has a false prediction. The equation used to update the weights is shown in figure 4.
The equation uses the weights of the current step (n) to generate the weights of the next step (n+1). This equation is what we will use for knowing how the learning rate affects the learning process.
Finally, we need to concatenate all of these together to make the network learn. This is done using the training_loop(inpt, weights) method defined from line 20 to 31. It goes into a training loop. The loop is used to map the inputs to their outputs with the least possible prediction error.
The loop does three operations:
Output Prediction.Error Calculation.Updating Weights.
Output Prediction.
Error Calculation.
Updating Weights.
After getting the idea of the example and its Python code, let us start showing how the learning rate is useful in order to get the best results.
In the previously discussed example, line 13 has the weights update equation in which the learning rate is used. At first, let us assume that we have not used the learning rate completely. The equation will as follows:
weights = weights + (desired_output[idx] — predicted)*inputs[idx]
Let us see the effect of removing the learning rate. In the iteration of the training loop, the network has the following inputs (b=0.05 and W=0.1, Input = 60, and desired output=60).
The expected output which is the result of the activation function as in line 25 will be activation_function(0.05(+1) + 0.1(60)). The predicted output will be 6.05.
In line 26, the prediction error will be calculated by getting the difference between the desired and the predicted output. The error will be abs(60–6.05)=53.95.
Then in line 27 the weights will get updated according to the above equation. The new weights will be [0.05, 0.1] + (53.95)*60 = [0.05, 0.1] + 3237 = [3237.05, 3237.1].
It seems that the new weights are too different from the previous weights. Each weight got increased by 3,237 which is too large. But let us continue making the next prediction.
In the next iteration, the network will have these inputs applied: (b=3237.05 and W=3237.1, Input = 40, and desired output=40). The expected output will be activation_function((3237.05 + 3237.1(40)) = 250. The prediction error will be abs(40–250) = 210. The error is very large. It is larger than the previous error. Thus we have to update the weights again. According to the above equation, the new weights will be [3237.05, 3237.1] + (-210)*40 = [3237.05, 3237.1] + -8400 = [-5162.95, -5162.9].
The table shown in figure 5 summarizes the results of the first three iterations.
As we go into more iterations, the results get worse. The magnitude of the weights is changing rapidly and sometimes with changing its signs. They are moving from very large positive value to very large negative value. How can we stop this large and abrupt changes in the weights? How to scale down the value by which the weights are updated?
If we looked at the value by which the weights are changing by from the previous table, it seems that the value is very large. This means that the network changes its weights with large speed. It is like someone that makes large moves within small times. At one time, the person is in the far east and after a very short time, that person will be in the far west. We just need to make it slower.
If we are able to scale down this value to get smaller then everything will be alright. But how?
Getting back to the part of the code that generates this value, it looks that the update equation is what generates it. Specifically this part:
(desired_output[idx] — predicted)*inputs[idx]
We can scale this part by multiplying it by a small value such as 0.1. So, rather than generating 3237.0 as the updated value in the first iteration, it will be reduced to just 323.7. We can even scale this value to a smaller value by decreasing the scale value to say 0.001. Using 0.001, the value will be just 3.327.
We can catch it now. This scaling value is the learning rate. Choosing small values for the learning rate makes the rate of weights update smaller and avoids abrupt changes. As the value gets larger as the changes are faster and as a result bad results.
There is no value we can say it is the best value for the learning rate. The learning rate is a hyperparameter. A hyperparameter has its value determined by experiments. We try different values and use the value that gives best results. There are some ways that just helps you select values of hyperparameters.
For our problem, I deduced that a value of .00001 works fine. After training the network with that learning rate, we can make a test. The table in figure 6 shows the results of prediction of 4 new testing samples. It seems that results are now much better after using the learning rate.
The original article is available at LinkedIn in this link: https://www.linkedin.com/pulse/learning-rate-useful-artificial-neural-networks-ahmed-gad/
It is also shared at KDnuggets in this page: https://www.kdnuggets.com/2018/01/learning-rate-useful-neural-network.html
The article reshared at TDS on 28–6–2018.
Ahmed Fawzy Gad | [
{
"code": null,
"e": 438,
"s": 172,
"text": "This article will help you understand why we need the learning rate and whether it is useful or not for training an artificial neural network. Using a very simple Python code for a single layer perceptron, the learning rate value will get changed to catch its idea."
},
{
"code": null,
"e": 940,
"s": 438,
"text": "An obstacle for newbies in artificial neural networks is the learning rate. I was asked many times about the effect of the learning rate in the training of the artificial neural networks (ANNs). Why we use learning rate? What is the best value for the learning rate? In this article, I will try to make things simpler by providing an example that shows how learning rate is useful in order to train an ANN. I will start by explaining our example with Python code before working with the learning rate."
},
{
"code": null,
"e": 1345,
"s": 940,
"text": "A very very simple example is used to get us out of complexity and allow us to just focus on the learning rate. A single numerical input will get applied to a single layer perceptron. If the input is 250 or smaller, its value will get returned as the output of the network. If the input is larger than 250, then it will be clipped to just 250. Figure 1 shows a table with the 6 samples used for training."
},
{
"code": null,
"e": 1780,
"s": 1345,
"text": "The architecture of the ANN used is shown in figure 2. There are just input and output layers. The input layer has just a single neuron for our single input. The output layer has just a single neuron for generating the output. The output layer neuron is responsible for mapping the input to the correct output. There is also a bias applied to the output layer neuron with weight b and value +1. There is also a weight W for the input."
},
{
"code": null,
"e": 1999,
"s": 1780,
"text": "The equation and the graph of the activation function used in this example are as shown figure 3. When the input is below or equal to 250, the output will be the same as the input. Otherwise, it will be clipped to 250."
},
{
"code": null,
"e": 2220,
"s": 1999,
"text": "The Python code implementing the entire network is shown below. We will discuss all of it until making it easy as much as possible then focus on changing the learning rate to find out how it affects the network training."
},
{
"code": null,
"e": 4110,
"s": 2220,
"text": "1. import numpy 2. 3. def activation_function(inpt): 4. if(inpt > 250): 5. return 250 # clip the result to 250 6. else: 7. return inpt # just return the input 8. 9. def prediction_error(desired, expected): 10. return numpy.abs(numpy.mean(desired-expected)) # absolute error 11. 12. def update_weights(weights, predicted, idx): 13. weights = weights + .00001*(desired_output[idx] - predicted)*inputs[idx] # updating weights 14. return weights # new updated weights 15. 16. weights = numpy.array([0.05, .1]) #bias & weight of input 17. inputs = numpy.array([60, 40, 100, 300, -50, 310]) # training inputs 18. desired_output = numpy.array([60, 40, 150, 250, -50, 250]) # training outputs 19. 20. def training_loop(inpt, weights): 21. error = 1 22. idx = 0 # start by the first training sample 23. iteration = 0 #loop iteration variable 24. while(iteration < 2000 or error >= 0.01): #while(error >= 0.1): 25. predicted = activation_function(weights[0]*1+weights[1]*inputs[idx]) 26. error = prediction_error(desired_output[idx], predicted) 27. weights = update_weights(weights, predicted, idx) 28. idx = idx + 1 # go to the next sample 29. idx = idx % inputs.shape[0] # restricts the index to the range of our samples 30. iteration = iteration + 1 # next iteration 31. return error, weights 32. 33. error, new_weights = training_loop(inputs, weights) 34. print('--------------Final Results----------------') 35. print('Learned Weights : ', new_weights) 36. new_inputs = numpy.array([10, 240, 550, -160]) 37. new_outputs = numpy.array([10, 240, 250, -160]) 38. for i in range(new_inputs.shape[0]): 39. print('Sample ', i+1, '. Expected = ', new_outputs[i], ' , Predicted = ', activation_function(new_weights[0]*1+new_weights[1]*new_inputs[i]))"
},
{
"code": null,
"e": 4344,
"s": 4110,
"text": "Lines 17 and 18 are responsible for creating two arrays (inputs and desired_output) holding the training input and output data presented in the previous table. Each input will have an output according to the activation function used."
},
{
"code": null,
"e": 4540,
"s": 4344,
"text": "Line 16 creates an array of the network weights. There are just two weights: one for the input and another for the bias. They were randomly initialized to 0.05 for the bias and 0.1 for the input."
},
{
"code": null,
"e": 4752,
"s": 4540,
"text": "The activation function itself is implemented using the activation_function(inpt) method from line 3 to 7. It accepts a single argument which is the input and returns a single value which is the expected output."
},
{
"code": null,
"e": 5216,
"s": 4752,
"text": "Because there may be an error in the prediction, we need to measure that error to know how far we are from the correct prediction. For that reason, there is a method implemented from line 9 to 10 called prediction_error(desired, expected) that accepts two inputs: the desired and expected outputs. That method just calculates the absolute difference between each desired and expected outputs. The best value for any error is for sure 0. This is the optimal value."
},
{
"code": null,
"e": 5662,
"s": 5216,
"text": "What if there was a prediction error? In this case, we must make a change to the network. But what exactly to change? It is the network weights. For updating the network weights, there is a method called update_weights(weights, predicted, idx) defined from line 13 to 14. It accepts three inputs: old weights, predicted output, and the index of the input that has a false prediction. The equation used to update the weights is shown in figure 4."
},
{
"code": null,
"e": 5862,
"s": 5662,
"text": "The equation uses the weights of the current step (n) to generate the weights of the next step (n+1). This equation is what we will use for knowing how the learning rate affects the learning process."
},
{
"code": null,
"e": 6154,
"s": 5862,
"text": "Finally, we need to concatenate all of these together to make the network learn. This is done using the training_loop(inpt, weights) method defined from line 20 to 31. It goes into a training loop. The loop is used to map the inputs to their outputs with the least possible prediction error."
},
{
"code": null,
"e": 6186,
"s": 6154,
"text": "The loop does three operations:"
},
{
"code": null,
"e": 6240,
"s": 6186,
"text": "Output Prediction.Error Calculation.Updating Weights."
},
{
"code": null,
"e": 6259,
"s": 6240,
"text": "Output Prediction."
},
{
"code": null,
"e": 6278,
"s": 6259,
"text": "Error Calculation."
},
{
"code": null,
"e": 6296,
"s": 6278,
"text": "Updating Weights."
},
{
"code": null,
"e": 6442,
"s": 6296,
"text": "After getting the idea of the example and its Python code, let us start showing how the learning rate is useful in order to get the best results."
},
{
"code": null,
"e": 6661,
"s": 6442,
"text": "In the previously discussed example, line 13 has the weights update equation in which the learning rate is used. At first, let us assume that we have not used the learning rate completely. The equation will as follows:"
},
{
"code": null,
"e": 6727,
"s": 6661,
"text": "weights = weights + (desired_output[idx] — predicted)*inputs[idx]"
},
{
"code": null,
"e": 6911,
"s": 6727,
"text": "Let us see the effect of removing the learning rate. In the iteration of the training loop, the network has the following inputs (b=0.05 and W=0.1, Input = 60, and desired output=60)."
},
{
"code": null,
"e": 7076,
"s": 6911,
"text": "The expected output which is the result of the activation function as in line 25 will be activation_function(0.05(+1) + 0.1(60)). The predicted output will be 6.05."
},
{
"code": null,
"e": 7238,
"s": 7076,
"text": "In line 26, the prediction error will be calculated by getting the difference between the desired and the predicted output. The error will be abs(60–6.05)=53.95."
},
{
"code": null,
"e": 7407,
"s": 7238,
"text": "Then in line 27 the weights will get updated according to the above equation. The new weights will be [0.05, 0.1] + (53.95)*60 = [0.05, 0.1] + 3237 = [3237.05, 3237.1]."
},
{
"code": null,
"e": 7585,
"s": 7407,
"text": "It seems that the new weights are too different from the previous weights. Each weight got increased by 3,237 which is too large. But let us continue making the next prediction."
},
{
"code": null,
"e": 8082,
"s": 7585,
"text": "In the next iteration, the network will have these inputs applied: (b=3237.05 and W=3237.1, Input = 40, and desired output=40). The expected output will be activation_function((3237.05 + 3237.1(40)) = 250. The prediction error will be abs(40–250) = 210. The error is very large. It is larger than the previous error. Thus we have to update the weights again. According to the above equation, the new weights will be [3237.05, 3237.1] + (-210)*40 = [3237.05, 3237.1] + -8400 = [-5162.95, -5162.9]."
},
{
"code": null,
"e": 8164,
"s": 8082,
"text": "The table shown in figure 5 summarizes the results of the first three iterations."
},
{
"code": null,
"e": 8507,
"s": 8164,
"text": "As we go into more iterations, the results get worse. The magnitude of the weights is changing rapidly and sometimes with changing its signs. They are moving from very large positive value to very large negative value. How can we stop this large and abrupt changes in the weights? How to scale down the value by which the weights are updated?"
},
{
"code": null,
"e": 8903,
"s": 8507,
"text": "If we looked at the value by which the weights are changing by from the previous table, it seems that the value is very large. This means that the network changes its weights with large speed. It is like someone that makes large moves within small times. At one time, the person is in the far east and after a very short time, that person will be in the far west. We just need to make it slower."
},
{
"code": null,
"e": 9000,
"s": 8903,
"text": "If we are able to scale down this value to get smaller then everything will be alright. But how?"
},
{
"code": null,
"e": 9144,
"s": 9000,
"text": "Getting back to the part of the code that generates this value, it looks that the update equation is what generates it. Specifically this part:"
},
{
"code": null,
"e": 9190,
"s": 9144,
"text": "(desired_output[idx] — predicted)*inputs[idx]"
},
{
"code": null,
"e": 9509,
"s": 9190,
"text": "We can scale this part by multiplying it by a small value such as 0.1. So, rather than generating 3237.0 as the updated value in the first iteration, it will be reduced to just 323.7. We can even scale this value to a smaller value by decreasing the scale value to say 0.001. Using 0.001, the value will be just 3.327."
},
{
"code": null,
"e": 9763,
"s": 9509,
"text": "We can catch it now. This scaling value is the learning rate. Choosing small values for the learning rate makes the rate of weights update smaller and avoids abrupt changes. As the value gets larger as the changes are faster and as a result bad results."
},
{
"code": null,
"e": 10074,
"s": 9763,
"text": "There is no value we can say it is the best value for the learning rate. The learning rate is a hyperparameter. A hyperparameter has its value determined by experiments. We try different values and use the value that gives best results. There are some ways that just helps you select values of hyperparameters."
},
{
"code": null,
"e": 10361,
"s": 10074,
"text": "For our problem, I deduced that a value of .00001 works fine. After training the network with that learning rate, we can make a test. The table in figure 6 shows the results of prediction of 4 new testing samples. It seems that results are now much better after using the learning rate."
},
{
"code": null,
"e": 10511,
"s": 10361,
"text": "The original article is available at LinkedIn in this link: https://www.linkedin.com/pulse/learning-rate-useful-artificial-neural-networks-ahmed-gad/"
},
{
"code": null,
"e": 10631,
"s": 10511,
"text": "It is also shared at KDnuggets in this page: https://www.kdnuggets.com/2018/01/learning-rate-useful-neural-network.html"
},
{
"code": null,
"e": 10673,
"s": 10631,
"text": "The article reshared at TDS on 28–6–2018."
}
] |
Detect cycle in the graph using degrees of nodes of graph - GeeksforGeeks | 02 Jul, 2021
Given a graph, the task is to detect a cycle in the graph using degrees of the nodes in the graph and print all the nodes that are involved in any of the cycles. If there is no cycle in the graph then print -1.
Examples:
Input:
Output: 0 1 2
Approach: Recursively remove all vertices of degree 1. This can be done efficiently by storing a map of vertices to their degrees. Initially, traverse the map and store all the vertices with degree = 1 in a queue. Traverse the queue as long as it is not empty. For each node in the queue, mark it as visited, and iterate through all the nodes that are connected to it (using the adjacency list), and decrement the degree of each of those nodes by one in the map. Add all nodes whose degree becomes equal to one to the queue. At the end of this algorithm, all the nodes that are unvisited are part of the cycle.
Below is the implementation of the above approach:
C++14
Java
Python3
C#
Javascript
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Graph classclass Graph{public: // No. of vertices of graph int v; // Adjacency List vector<int> *l; Graph(int v) { this->v = v; this->l = new vector<int>[v]; } void addedge(int i, int j) { l[i].push_back(j); l[j].push_back(i); }}; // Function to find a cycle in the given graph if existsvoid findCycle(int n, int r, Graph g){ // HashMap to store the degree of each node unordered_map<int, int> degree; for (int i = 0; i < g.v; i++) degree[i] = g.l[i].size(); // Array to track visited nodes int visited[g.v] = {0}; // Queue to store the nodes of degree 1 queue<int> q; // Continuously adding those nodes whose // degree is 1 to the queue while (true) { // Adding nodes to queue whose degree is 1 // and is not visited for (int i = 0; i < degree.size(); i++) if (degree.at(i) == 1 and !visited[i]) q.push(i); // If queue becomes empty then get out // of the continuous loop if (q.empty()) break; while (!q.empty()) { // Remove the front element from the queue int temp = q.front(); q.pop(); // Mark the removed element visited visited[temp] = 1; // Decrement the degree of all those nodes // adjacent to removed node for (int i = 0; i < g.l[temp].size(); i++) { int value = degree[g.l[temp][i]]; degree[g.l[temp][i]] = --value; } } } int flag = 0; // Checking all the nodes which are not visited // i.e. they are part of the cycle for (int i = 0; i < g.v; i++) if (visited[i] == 0) flag = 1; if (flag == 0) cout << "-1"; else { for (int i = 0; i < g.v; i++) if (visited[i] == 0) cout << i << " "; }} // Driver Codeint main(){ // No of nodes int n = 5; // No of edges int e = 5; Graph g(n); g.addedge(0, 1); g.addedge(0, 2); g.addedge(0, 3); g.addedge(1, 2); g.addedge(3, 4); findCycle(n, e, g); return 0;} // This code is contributed by// sanjeev2552
// Java implementation of the approachimport java.util.*; // Graph classclass Graph { // No. of vertices of graph int v; // Adjacency List @SuppressWarnings("unchecked") ArrayList<ArrayList<Integer>> l; Graph(int v) { this.v = v; this.l = new ArrayList<>(); for (int i = 0; i < v; i++) { l.add(new ArrayList<>()); } } void addedge(int i, int j) { l.get(i).add(j); l.get(j).add(i); }} class GFG { // Function to find a cycle in the given graph if exists static void findCycle(int n, int e, Graph g) { // HashMap to store the degree of each node HashMap<Integer, Integer> degree = new HashMap<>(); for (int i = 0; i < n; i++) degree.put(i, g.l.get(i).size()); // Array to track visited nodes int visited[] = new int[g.v]; // Initially all nodes are not visited for (int i = 0; i < visited.length; i++) visited[i] = 0; // Queue to store the nodes of degree 1 Queue<Integer> q = new LinkedList<>(); // Continuously adding those nodes whose // degree is 1 to the queue while (true) { // Adding nodes to queue whose degree is 1 // and is not visited for (int i = 0; i < degree.size(); i++){ if ((int)degree.get(i) == 1 && visited[i] == 0) q.add(i); } // If queue becomes empty then get out // of the continuous loop if (q.isEmpty()) break; while (!q.isEmpty()) { // Remove the front element from the queue int temp = (int)q.poll(); // Mark the removed element visited visited[temp] = 1; // Decrement the degree of all those nodes // adjacent to removed node for (int i = 0; i < g.l.get(temp).size(); i++) { int value = (int)degree.get((int)g.l.get(temp).get(i)); degree.replace(g.l.get(temp).get(i), --value); } } } int flag = 0; // Checking all the nodes which are not visited // i.e. they are part of the cycle for (int i = 0; i < visited.length; i++) if (visited[i] == 0) flag = 1; if (flag == 0) System.out.print("-1"); else { for (int i = 0; i < visited.length; i++) if (visited[i] == 0) System.out.print(i + " "); } } // Driver code public static void main(String[] args) { // No of nodes int n = 5; // No of edges int e = 5; Graph g = new Graph(n); g.addedge(0, 1); g.addedge(0, 2); g.addedge(0, 3); g.addedge(1, 2); g.addedge(3, 4); findCycle(n, e, g); }}// This Code has been contributed by Mukul Sharma
# Python3 implementation of the approach # Graph classclass Graph: def __init__(self, v): # No. of vertices of graph self.v = v # Adjacency List self.l = [0] * v for i in range(self.v): self.l[i] = [] def addedge(self, i: int, j: int): self.l[i].append(j) self.l[j].append(i) # Function to find a cycle in the given graph if existsdef findCycle(n: int, e: int, g: Graph) -> None: # HashMap to store the degree of each node degree = dict() for i in range(len(g.l)): degree[i] = len(g.l[i]) # Array to track visited nodes visited = [0] * g.v # Initially all nodes are not visited for i in range(len(visited)): visited[i] = 0 # Queue to store the nodes of degree 1 q = list() # Continuously adding those nodes whose # degree is 1 to the queue while True: # Adding nodes to queue whose degree is 1 # and is not visited for i in range(len(degree)): if degree[i] == 1 and visited[i] == 0: q.append(i) # If queue becomes empty then get out # of the continuous loop if len(q) == 0: break while q: # Remove the front element from the queue temp = q.pop() # Mark the removed element visited visited[temp] = 1 # Decrement the degree of all those nodes # adjacent to removed node for i in range(len(g.l[temp])): value = degree[g.l[temp][i]] degree[g.l[temp][i]] = value - 1 flag = 0 # Checking all the nodes which are not visited # i.e. they are part of the cycle for i in range(len(visited)): if visited[i] == 0: flag = 1 if flag == 0: print("-1") else: for i in range(len(visited)): if visited[i] == 0: print(i, end = " ") # Driver Codeif __name__ == "__main__": # No of nodes n = 5 # No of edges e = 5 g = Graph(n) g.addedge(0, 1) g.addedge(0, 2) g.addedge(0, 3) g.addedge(1, 2) g.addedge(3, 4) findCycle(n, e, g) # This code is contributed by# sanjeev2552
// C# implementation of the approachusing System;using System.Collections.Generic; // Graph classpublic class Graph{ // No. of vertices of graph public int v; // Adjacency List public List<int> []l; public Graph(int v) { this.v = v; this.l = new List<int>[v]; for(int i = 0; i < v; i++) { l[i] = new List<int>(); } } public void addedge(int i, int j) { l[i].Add(j); l[j].Add(i); }} class GFG{ // Function to find a cycle in the// given graph if existsstatic void findCycle(int n, int e, Graph g){ // Dictionary to store the degree of each node Dictionary<int, int> degree = new Dictionary<int, int>(); for(int i = 0; i < g.l.Length; i++) degree.Add(i, g.l[i].Count); // Array to track visited nodes int []visited = new int[g.v]; // Initially all nodes are not visited for(int i = 0; i < visited.Length; i++) visited[i] = 0; // Queue to store the nodes of degree 1 List<int> q = new List<int>(); // Continuously adding those nodes whose // degree is 1 to the queue while (true) { // Adding nodes to queue whose degree is 1 // and is not visited for(int i = 0; i < degree.Count; i++) if ((int)degree[i] == 1 && visited[i] == 0) q.Add(i); // If queue becomes empty then get out // of the continuous loop if (q.Count!=0) break; while (q.Count != 0) { // Remove the front element from the queue int temp = q[0]; q.RemoveAt(0); // Mark the removed element visited visited[temp] = 1; // Decrement the degree of all those nodes // adjacent to removed node for(int i = 0; i < g.l[temp].Count; i++) { int value = (int)degree[(int)g.l[temp][i]]; degree[g.l[temp][i]] = value -= 1; } } } int flag = 0; // Checking all the nodes which are not visited // i.e. they are part of the cycle for(int i = 0; i < visited.Length; i++) if (visited[i] == 0) flag = 1; if (flag == 0) Console.Write("-1"); else { for(int i = 0; i < visited.Length-2; i++) if (visited[i] == 0) Console.Write(i + " "); }} // Driver codepublic static void Main(String[] args){ // No of nodes int n = 5; // No of edges int e = 5; Graph g = new Graph(n); g.addedge(0, 1); g.addedge(0, 2); g.addedge(0, 3); g.addedge(1, 2); g.addedge(3, 4); findCycle(n, e, g);}} // This code is contributed by Princi Singh
<script> // Javascript implementation of the approach // Graph classclass Graph{ constructor(v) { // No. of vertices of graph this.v = v; // Adjacency List this.l = Array.from( Array(this.v), () => Array()); } addedge(i, j) { this.l[i].push(j); this.l[j].push(i); }} // Function to find a cycle in the// given graph if existsfunction findCycle(n, e, g){ // Dictionary to store the degree of each node var degree = new Map(); for(var i = 0; i < g.l.length; i++) degree.set(i, g.l[i].length); // Array to track visited nodes var visited = Array(g.v).fill(0); // Initially all nodes are not visited for(var i = 0; i < visited.length; i++) visited[i] = 0; // Queue to store the nodes of degree 1 var q = []; // Continuously adding those nodes whose // degree is 1 to the queue while (true) { // Adding nodes to queue whose degree is 1 // and is not visited for(var i = 0; i < degree.size; i++) if (degree.has(i) && visited[i] == 0) q.push(i); // If queue becomes empty then get out // of the continuous loop if (q.length != 0) break; while (q.length != 0) { // Remove the front element from the queue var temp = q[0]; q.shift(); // Mark the removed element visited visited[temp] = 1; // Decrement the degree of all those nodes // adjacent to removed node for(var i = 0; i < g.l[temp].length; i++) { var value = degree.get(g.l[temp][i]); degree.set(g.l[temp][i], value - 1); } } } var flag = 0; // Checking all the nodes which are not visited // i.e. they are part of the cycle for(var i = 0; i < visited.length; i++) if (visited[i] == 0) flag = 1; if (flag == 0) document.write("-1"); else { for(var i = 0; i < visited.length - 2; i++) if (visited[i] == 0) document.write(i + " "); }} // Driver code // No of nodesvar n = 5; // No of edgesvar e = 5;var g = new Graph(n); g.addedge(0, 1);g.addedge(0, 2);g.addedge(0, 3);g.addedge(1, 2);g.addedge(3, 4); findCycle(n, e, g); // This code is contributed by noob2000 </script>
0 1 2
sanjeev2552
princi singh
msharma04
noob2000
graph-cycle
Graph
Recursion
Recursion
Graph
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Vertex Cover Problem | Set 1 (Introduction and Approximate Algorithm)
Best First Search (Informed Search)
Graph Coloring | Set 2 (Greedy Algorithm)
Find if there is a path between two vertices in a directed graph
Shortest Path in a weighted Graph where weight of an edge is 1 or 2
Write a program to print all permutations of a given string
Program for Tower of Hanoi
Recursion
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
Program for Sum of the digits of a given number | [
{
"code": null,
"e": 25010,
"s": 24982,
"text": "\n02 Jul, 2021"
},
{
"code": null,
"e": 25221,
"s": 25010,
"text": "Given a graph, the task is to detect a cycle in the graph using degrees of the nodes in the graph and print all the nodes that are involved in any of the cycles. If there is no cycle in the graph then print -1."
},
{
"code": null,
"e": 25232,
"s": 25221,
"text": "Examples: "
},
{
"code": null,
"e": 25241,
"s": 25232,
"text": "Input: "
},
{
"code": null,
"e": 25256,
"s": 25241,
"text": "Output: 0 1 2 "
},
{
"code": null,
"e": 25867,
"s": 25256,
"text": "Approach: Recursively remove all vertices of degree 1. This can be done efficiently by storing a map of vertices to their degrees. Initially, traverse the map and store all the vertices with degree = 1 in a queue. Traverse the queue as long as it is not empty. For each node in the queue, mark it as visited, and iterate through all the nodes that are connected to it (using the adjacency list), and decrement the degree of each of those nodes by one in the map. Add all nodes whose degree becomes equal to one to the queue. At the end of this algorithm, all the nodes that are unvisited are part of the cycle."
},
{
"code": null,
"e": 25920,
"s": 25867,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 25926,
"s": 25920,
"text": "C++14"
},
{
"code": null,
"e": 25931,
"s": 25926,
"text": "Java"
},
{
"code": null,
"e": 25939,
"s": 25931,
"text": "Python3"
},
{
"code": null,
"e": 25942,
"s": 25939,
"text": "C#"
},
{
"code": null,
"e": 25953,
"s": 25942,
"text": "Javascript"
},
{
"code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Graph classclass Graph{public: // No. of vertices of graph int v; // Adjacency List vector<int> *l; Graph(int v) { this->v = v; this->l = new vector<int>[v]; } void addedge(int i, int j) { l[i].push_back(j); l[j].push_back(i); }}; // Function to find a cycle in the given graph if existsvoid findCycle(int n, int r, Graph g){ // HashMap to store the degree of each node unordered_map<int, int> degree; for (int i = 0; i < g.v; i++) degree[i] = g.l[i].size(); // Array to track visited nodes int visited[g.v] = {0}; // Queue to store the nodes of degree 1 queue<int> q; // Continuously adding those nodes whose // degree is 1 to the queue while (true) { // Adding nodes to queue whose degree is 1 // and is not visited for (int i = 0; i < degree.size(); i++) if (degree.at(i) == 1 and !visited[i]) q.push(i); // If queue becomes empty then get out // of the continuous loop if (q.empty()) break; while (!q.empty()) { // Remove the front element from the queue int temp = q.front(); q.pop(); // Mark the removed element visited visited[temp] = 1; // Decrement the degree of all those nodes // adjacent to removed node for (int i = 0; i < g.l[temp].size(); i++) { int value = degree[g.l[temp][i]]; degree[g.l[temp][i]] = --value; } } } int flag = 0; // Checking all the nodes which are not visited // i.e. they are part of the cycle for (int i = 0; i < g.v; i++) if (visited[i] == 0) flag = 1; if (flag == 0) cout << \"-1\"; else { for (int i = 0; i < g.v; i++) if (visited[i] == 0) cout << i << \" \"; }} // Driver Codeint main(){ // No of nodes int n = 5; // No of edges int e = 5; Graph g(n); g.addedge(0, 1); g.addedge(0, 2); g.addedge(0, 3); g.addedge(1, 2); g.addedge(3, 4); findCycle(n, e, g); return 0;} // This code is contributed by// sanjeev2552",
"e": 28268,
"s": 25953,
"text": null
},
{
"code": "// Java implementation of the approachimport java.util.*; // Graph classclass Graph { // No. of vertices of graph int v; // Adjacency List @SuppressWarnings(\"unchecked\") ArrayList<ArrayList<Integer>> l; Graph(int v) { this.v = v; this.l = new ArrayList<>(); for (int i = 0; i < v; i++) { l.add(new ArrayList<>()); } } void addedge(int i, int j) { l.get(i).add(j); l.get(j).add(i); }} class GFG { // Function to find a cycle in the given graph if exists static void findCycle(int n, int e, Graph g) { // HashMap to store the degree of each node HashMap<Integer, Integer> degree = new HashMap<>(); for (int i = 0; i < n; i++) degree.put(i, g.l.get(i).size()); // Array to track visited nodes int visited[] = new int[g.v]; // Initially all nodes are not visited for (int i = 0; i < visited.length; i++) visited[i] = 0; // Queue to store the nodes of degree 1 Queue<Integer> q = new LinkedList<>(); // Continuously adding those nodes whose // degree is 1 to the queue while (true) { // Adding nodes to queue whose degree is 1 // and is not visited for (int i = 0; i < degree.size(); i++){ if ((int)degree.get(i) == 1 && visited[i] == 0) q.add(i); } // If queue becomes empty then get out // of the continuous loop if (q.isEmpty()) break; while (!q.isEmpty()) { // Remove the front element from the queue int temp = (int)q.poll(); // Mark the removed element visited visited[temp] = 1; // Decrement the degree of all those nodes // adjacent to removed node for (int i = 0; i < g.l.get(temp).size(); i++) { int value = (int)degree.get((int)g.l.get(temp).get(i)); degree.replace(g.l.get(temp).get(i), --value); } } } int flag = 0; // Checking all the nodes which are not visited // i.e. they are part of the cycle for (int i = 0; i < visited.length; i++) if (visited[i] == 0) flag = 1; if (flag == 0) System.out.print(\"-1\"); else { for (int i = 0; i < visited.length; i++) if (visited[i] == 0) System.out.print(i + \" \"); } } // Driver code public static void main(String[] args) { // No of nodes int n = 5; // No of edges int e = 5; Graph g = new Graph(n); g.addedge(0, 1); g.addedge(0, 2); g.addedge(0, 3); g.addedge(1, 2); g.addedge(3, 4); findCycle(n, e, g); }}// This Code has been contributed by Mukul Sharma",
"e": 31275,
"s": 28268,
"text": null
},
{
"code": "# Python3 implementation of the approach # Graph classclass Graph: def __init__(self, v): # No. of vertices of graph self.v = v # Adjacency List self.l = [0] * v for i in range(self.v): self.l[i] = [] def addedge(self, i: int, j: int): self.l[i].append(j) self.l[j].append(i) # Function to find a cycle in the given graph if existsdef findCycle(n: int, e: int, g: Graph) -> None: # HashMap to store the degree of each node degree = dict() for i in range(len(g.l)): degree[i] = len(g.l[i]) # Array to track visited nodes visited = [0] * g.v # Initially all nodes are not visited for i in range(len(visited)): visited[i] = 0 # Queue to store the nodes of degree 1 q = list() # Continuously adding those nodes whose # degree is 1 to the queue while True: # Adding nodes to queue whose degree is 1 # and is not visited for i in range(len(degree)): if degree[i] == 1 and visited[i] == 0: q.append(i) # If queue becomes empty then get out # of the continuous loop if len(q) == 0: break while q: # Remove the front element from the queue temp = q.pop() # Mark the removed element visited visited[temp] = 1 # Decrement the degree of all those nodes # adjacent to removed node for i in range(len(g.l[temp])): value = degree[g.l[temp][i]] degree[g.l[temp][i]] = value - 1 flag = 0 # Checking all the nodes which are not visited # i.e. they are part of the cycle for i in range(len(visited)): if visited[i] == 0: flag = 1 if flag == 0: print(\"-1\") else: for i in range(len(visited)): if visited[i] == 0: print(i, end = \" \") # Driver Codeif __name__ == \"__main__\": # No of nodes n = 5 # No of edges e = 5 g = Graph(n) g.addedge(0, 1) g.addedge(0, 2) g.addedge(0, 3) g.addedge(1, 2) g.addedge(3, 4) findCycle(n, e, g) # This code is contributed by# sanjeev2552",
"e": 33463,
"s": 31275,
"text": null
},
{
"code": "// C# implementation of the approachusing System;using System.Collections.Generic; // Graph classpublic class Graph{ // No. of vertices of graph public int v; // Adjacency List public List<int> []l; public Graph(int v) { this.v = v; this.l = new List<int>[v]; for(int i = 0; i < v; i++) { l[i] = new List<int>(); } } public void addedge(int i, int j) { l[i].Add(j); l[j].Add(i); }} class GFG{ // Function to find a cycle in the// given graph if existsstatic void findCycle(int n, int e, Graph g){ // Dictionary to store the degree of each node Dictionary<int, int> degree = new Dictionary<int, int>(); for(int i = 0; i < g.l.Length; i++) degree.Add(i, g.l[i].Count); // Array to track visited nodes int []visited = new int[g.v]; // Initially all nodes are not visited for(int i = 0; i < visited.Length; i++) visited[i] = 0; // Queue to store the nodes of degree 1 List<int> q = new List<int>(); // Continuously adding those nodes whose // degree is 1 to the queue while (true) { // Adding nodes to queue whose degree is 1 // and is not visited for(int i = 0; i < degree.Count; i++) if ((int)degree[i] == 1 && visited[i] == 0) q.Add(i); // If queue becomes empty then get out // of the continuous loop if (q.Count!=0) break; while (q.Count != 0) { // Remove the front element from the queue int temp = q[0]; q.RemoveAt(0); // Mark the removed element visited visited[temp] = 1; // Decrement the degree of all those nodes // adjacent to removed node for(int i = 0; i < g.l[temp].Count; i++) { int value = (int)degree[(int)g.l[temp][i]]; degree[g.l[temp][i]] = value -= 1; } } } int flag = 0; // Checking all the nodes which are not visited // i.e. they are part of the cycle for(int i = 0; i < visited.Length; i++) if (visited[i] == 0) flag = 1; if (flag == 0) Console.Write(\"-1\"); else { for(int i = 0; i < visited.Length-2; i++) if (visited[i] == 0) Console.Write(i + \" \"); }} // Driver codepublic static void Main(String[] args){ // No of nodes int n = 5; // No of edges int e = 5; Graph g = new Graph(n); g.addedge(0, 1); g.addedge(0, 2); g.addedge(0, 3); g.addedge(1, 2); g.addedge(3, 4); findCycle(n, e, g);}} // This code is contributed by Princi Singh",
"e": 36245,
"s": 33463,
"text": null
},
{
"code": "<script> // Javascript implementation of the approach // Graph classclass Graph{ constructor(v) { // No. of vertices of graph this.v = v; // Adjacency List this.l = Array.from( Array(this.v), () => Array()); } addedge(i, j) { this.l[i].push(j); this.l[j].push(i); }} // Function to find a cycle in the// given graph if existsfunction findCycle(n, e, g){ // Dictionary to store the degree of each node var degree = new Map(); for(var i = 0; i < g.l.length; i++) degree.set(i, g.l[i].length); // Array to track visited nodes var visited = Array(g.v).fill(0); // Initially all nodes are not visited for(var i = 0; i < visited.length; i++) visited[i] = 0; // Queue to store the nodes of degree 1 var q = []; // Continuously adding those nodes whose // degree is 1 to the queue while (true) { // Adding nodes to queue whose degree is 1 // and is not visited for(var i = 0; i < degree.size; i++) if (degree.has(i) && visited[i] == 0) q.push(i); // If queue becomes empty then get out // of the continuous loop if (q.length != 0) break; while (q.length != 0) { // Remove the front element from the queue var temp = q[0]; q.shift(); // Mark the removed element visited visited[temp] = 1; // Decrement the degree of all those nodes // adjacent to removed node for(var i = 0; i < g.l[temp].length; i++) { var value = degree.get(g.l[temp][i]); degree.set(g.l[temp][i], value - 1); } } } var flag = 0; // Checking all the nodes which are not visited // i.e. they are part of the cycle for(var i = 0; i < visited.length; i++) if (visited[i] == 0) flag = 1; if (flag == 0) document.write(\"-1\"); else { for(var i = 0; i < visited.length - 2; i++) if (visited[i] == 0) document.write(i + \" \"); }} // Driver code // No of nodesvar n = 5; // No of edgesvar e = 5;var g = new Graph(n); g.addedge(0, 1);g.addedge(0, 2);g.addedge(0, 3);g.addedge(1, 2);g.addedge(3, 4); findCycle(n, e, g); // This code is contributed by noob2000 </script>",
"e": 38670,
"s": 36245,
"text": null
},
{
"code": null,
"e": 38676,
"s": 38670,
"text": "0 1 2"
},
{
"code": null,
"e": 38690,
"s": 38678,
"text": "sanjeev2552"
},
{
"code": null,
"e": 38703,
"s": 38690,
"text": "princi singh"
},
{
"code": null,
"e": 38713,
"s": 38703,
"text": "msharma04"
},
{
"code": null,
"e": 38722,
"s": 38713,
"text": "noob2000"
},
{
"code": null,
"e": 38734,
"s": 38722,
"text": "graph-cycle"
},
{
"code": null,
"e": 38740,
"s": 38734,
"text": "Graph"
},
{
"code": null,
"e": 38750,
"s": 38740,
"text": "Recursion"
},
{
"code": null,
"e": 38760,
"s": 38750,
"text": "Recursion"
},
{
"code": null,
"e": 38766,
"s": 38760,
"text": "Graph"
},
{
"code": null,
"e": 38864,
"s": 38766,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 38873,
"s": 38864,
"text": "Comments"
},
{
"code": null,
"e": 38886,
"s": 38873,
"text": "Old Comments"
},
{
"code": null,
"e": 38956,
"s": 38886,
"text": "Vertex Cover Problem | Set 1 (Introduction and Approximate Algorithm)"
},
{
"code": null,
"e": 38992,
"s": 38956,
"text": "Best First Search (Informed Search)"
},
{
"code": null,
"e": 39034,
"s": 38992,
"text": "Graph Coloring | Set 2 (Greedy Algorithm)"
},
{
"code": null,
"e": 39099,
"s": 39034,
"text": "Find if there is a path between two vertices in a directed graph"
},
{
"code": null,
"e": 39167,
"s": 39099,
"text": "Shortest Path in a weighted Graph where weight of an edge is 1 or 2"
},
{
"code": null,
"e": 39227,
"s": 39167,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 39254,
"s": 39227,
"text": "Program for Tower of Hanoi"
},
{
"code": null,
"e": 39264,
"s": 39254,
"text": "Recursion"
},
{
"code": null,
"e": 39349,
"s": 39264,
"text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)"
}
] |
Python program to count the number of characters in a String - GeeksforGeeks | 01 Oct, 2020
Given a String. The task is to return the number of characters in the string.
Examples:
Input : test_str = ‘geeksforgeeks !!$*** best 4 all Geeks 10-0’ Output : 25Explanation : Only alphabets, when counted are 25
Input : test_str = ‘geeksforgeeks !!$*** best for all Geeks 10—0’ Output : 27Explanation : Only alphabets, when counted are 27
Method #1 : Using isalpha() + len()
In this approach, we check for each character to be alphabet using isalpha() and len() is used to get the length of the list of alphabets to get count.
Python3
# Python3 code to demonstrate working of# Alphabets Frequency in String# Using isalpha() + len() # initializing stringtest_str = 'geeksforgeeks !!$ is best 4 all Geeks 10-0' # printing original stringprint("The original string is : " + str(test_str)) # isalpha() to computation of Alphabetsres = len([ele for ele in test_str if ele.isalpha()]) # printing resultprint("Count of Alphabets : " + str(res))
The original string is : geeksforgeeks !!$ is best 4 all Geeks 10-0Count of Alphabets : 27
Method #2 : Using ascii_uppercase() + ascii_lowercase() + len()
In this, we perform the task of getting alphabets as a combination of upper and lowercase, using inbuilt functions, len() returns frequency.
Python3
# Python3 code to demonstrate working of# Alphabets Frequency in String# Using ascii_uppercase() + ascii_lowercase() + len()import string # initializing stringtest_str = 'geeksforgeeks !!$ is best 4 all Geeks 10-0' # printing original stringprint("The original string is : " + str(test_str)) # ascii_lowercase and ascii_uppercase# to check for Alphabetsres = len([ele for ele in test_str if ele in string.ascii_uppercase or ele in string.ascii_lowercase]) # printing resultprint("Count of Alphabets : " + str(res))
The original string is : geeksforgeeks !!$ is best 4 all Geeks 10-0Count of Alphabets : 27
Python string-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 ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Python String | replace()
*args and **kwargs in Python
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": 25531,
"s": 25503,
"text": "\n01 Oct, 2020"
},
{
"code": null,
"e": 25609,
"s": 25531,
"text": "Given a String. The task is to return the number of characters in the string."
},
{
"code": null,
"e": 25619,
"s": 25609,
"text": "Examples:"
},
{
"code": null,
"e": 25744,
"s": 25619,
"text": "Input : test_str = ‘geeksforgeeks !!$*** best 4 all Geeks 10-0’ Output : 25Explanation : Only alphabets, when counted are 25"
},
{
"code": null,
"e": 25871,
"s": 25744,
"text": "Input : test_str = ‘geeksforgeeks !!$*** best for all Geeks 10—0’ Output : 27Explanation : Only alphabets, when counted are 27"
},
{
"code": null,
"e": 25907,
"s": 25871,
"text": "Method #1 : Using isalpha() + len()"
},
{
"code": null,
"e": 26059,
"s": 25907,
"text": "In this approach, we check for each character to be alphabet using isalpha() and len() is used to get the length of the list of alphabets to get count."
},
{
"code": null,
"e": 26067,
"s": 26059,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate working of# Alphabets Frequency in String# Using isalpha() + len() # initializing stringtest_str = 'geeksforgeeks !!$ is best 4 all Geeks 10-0' # printing original stringprint(\"The original string is : \" + str(test_str)) # isalpha() to computation of Alphabetsres = len([ele for ele in test_str if ele.isalpha()]) # printing resultprint(\"Count of Alphabets : \" + str(res))",
"e": 26474,
"s": 26067,
"text": null
},
{
"code": null,
"e": 26565,
"s": 26474,
"text": "The original string is : geeksforgeeks !!$ is best 4 all Geeks 10-0Count of Alphabets : 27"
},
{
"code": null,
"e": 26629,
"s": 26565,
"text": "Method #2 : Using ascii_uppercase() + ascii_lowercase() + len()"
},
{
"code": null,
"e": 26770,
"s": 26629,
"text": "In this, we perform the task of getting alphabets as a combination of upper and lowercase, using inbuilt functions, len() returns frequency."
},
{
"code": null,
"e": 26778,
"s": 26770,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate working of# Alphabets Frequency in String# Using ascii_uppercase() + ascii_lowercase() + len()import string # initializing stringtest_str = 'geeksforgeeks !!$ is best 4 all Geeks 10-0' # printing original stringprint(\"The original string is : \" + str(test_str)) # ascii_lowercase and ascii_uppercase# to check for Alphabetsres = len([ele for ele in test_str if ele in string.ascii_uppercase or ele in string.ascii_lowercase]) # printing resultprint(\"Count of Alphabets : \" + str(res))",
"e": 27297,
"s": 26778,
"text": null
},
{
"code": null,
"e": 27388,
"s": 27297,
"text": "The original string is : geeksforgeeks !!$ is best 4 all Geeks 10-0Count of Alphabets : 27"
},
{
"code": null,
"e": 27411,
"s": 27388,
"text": "Python string-programs"
},
{
"code": null,
"e": 27418,
"s": 27411,
"text": "Python"
},
{
"code": null,
"e": 27434,
"s": 27418,
"text": "Python Programs"
},
{
"code": null,
"e": 27532,
"s": 27434,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27564,
"s": 27532,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27586,
"s": 27564,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 27628,
"s": 27586,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 27654,
"s": 27628,
"text": "Python String | replace()"
},
{
"code": null,
"e": 27683,
"s": 27654,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 27705,
"s": 27683,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 27744,
"s": 27705,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 27790,
"s": 27744,
"text": "Python | Split string into list of characters"
},
{
"code": null,
"e": 27828,
"s": 27790,
"text": "Python | Convert a list to dictionary"
}
] |
BlackRock Interview Experience (On-campus) - GeeksforGeeks | 09 Sep, 2020
BlackRock was one of the Super-Dream companies that visited VIT. Eligibility criteria were 60% or CGPA 6 in Xth, XIIth, and pursuing a degree with no standing arrears. 1000 students(Company was open to all branches) were short-listed for the online test for tech. profile(I would be describing the process for tech profile only as that is the one I applied for).
Online test: The test had 3 sections
Software aptitude section- A problem was described and a detailed flow chart was provided with some statements missing in some boxes. The questions were like, “Which of the following statements/ commands would come in box x”. There were 3 problems like this and each problem had 4-5 questions. Data structures and Algorithms section- Detailed knowledge of trees was needed. Questions ranged from basic concepts like tree traversals to a detailed understanding of AVL trees. SQL section- 25 MCQs on SQL was asked. Questions involved choosing the suitable query for the given output of the database provided, basic concepts of DBMS. I would recommend stronghold on the basics of SQL and good practice of SQL questions on Hackerrank.
Software aptitude section- A problem was described and a detailed flow chart was provided with some statements missing in some boxes. The questions were like, “Which of the following statements/ commands would come in box x”. There were 3 problems like this and each problem had 4-5 questions.
Data structures and Algorithms section- Detailed knowledge of trees was needed. Questions ranged from basic concepts like tree traversals to a detailed understanding of AVL trees.
SQL section- 25 MCQs on SQL was asked. Questions involved choosing the suitable query for the given output of the database provided, basic concepts of DBMS. I would recommend stronghold on the basics of SQL and good practice of SQL questions on Hackerrank.
After this round 152 students were shortlisted for the interviews. As per my experience, there is no exact number of rounds that you have to go through. Some students had 2 technical rounds. I had only one technical round followed by 1 HR round.
Technical Interview: The interview went on for about 1 hour. There were 2 interviewers:-
Interviewer 1: Tell us about yourself.
Me: Mentioned my name, pursuing my B.Tech. in CSE from VIT which you already know, focusing on programming and my core CS subjects like OS, CN, DBMS these days, have made some decent projects on web-development like to follow tech. trends, other areas of knowledge include penetration testing and ethical hacking, and I make great pasta.
Both laughed. Then a detailed discussion on my web-dev projects followed. I would suggest not to write anything on your resume that you have not done by yourself or don’t know. They go in-depth of it and you will struggle if you try to bluff. After spending about 35 minutes on my projects they moved to data structures and algorithms.
Interviewer 2: How good you think you are in DS and algo?
Me: Not an expert but I would rate my self 3.5 out of 5.
2 problems were asked.
Problem 1: Find an element In an array in which numbers are in decreasing order first and then the number is in increasing order. Example: {9, 8 , 7, 6, 10, 11, 12, 13} find 12.Very simple problem. I asked many questions about the problem like is the point of transition of the array from decreasing to increasing presence in the center, is it a string input or a number input, is there a situation where the number to search will not be present in the array. It’s always a good practice to ask questions and not jump on solutions. It shows that you are approaching the problem from a wider perspective. Remember, they are not looking for how fast you can solve the problem. They want to see how you approach a problem. They are interested in your problem-solving skills.I gave the brute force a linear approach. Then I gave the optimized approach of finding the point of transition in a long time by ‘divide array in 2 part’ strategy and then applying binary search on the required sub-array. Both said its a good solution.Problem 2: There’s a cricket match going on and you have a stream of scores coming to you. You have to keep a record of the largest n scores with you. How you would do it.Again, I asked questions. Whether I have some scores with me already and then new scores are coming or I’m empty and then scores start to come one by one? Are the scores coming in sorted order? I took a stack and tried solving the question. One of them asked why this data structure. I said that I was just running the problem and not finalizing my decision. Then I gave my solution of using a min-heap. Both said your solution is perfect.
Problem 1: Find an element In an array in which numbers are in decreasing order first and then the number is in increasing order. Example: {9, 8 , 7, 6, 10, 11, 12, 13} find 12.Very simple problem. I asked many questions about the problem like is the point of transition of the array from decreasing to increasing presence in the center, is it a string input or a number input, is there a situation where the number to search will not be present in the array. It’s always a good practice to ask questions and not jump on solutions. It shows that you are approaching the problem from a wider perspective. Remember, they are not looking for how fast you can solve the problem. They want to see how you approach a problem. They are interested in your problem-solving skills.I gave the brute force a linear approach. Then I gave the optimized approach of finding the point of transition in a long time by ‘divide array in 2 part’ strategy and then applying binary search on the required sub-array. Both said its a good solution.
Problem 1: Find an element In an array in which numbers are in decreasing order first and then the number is in increasing order.
Example:
{9, 8 , 7, 6, 10, 11, 12, 13} find 12.
Very simple problem. I asked many questions about the problem like is the point of transition of the array from decreasing to increasing presence in the center, is it a string input or a number input, is there a situation where the number to search will not be present in the array. It’s always a good practice to ask questions and not jump on solutions. It shows that you are approaching the problem from a wider perspective. Remember, they are not looking for how fast you can solve the problem. They want to see how you approach a problem. They are interested in your problem-solving skills.
I gave the brute force a linear approach. Then I gave the optimized approach of finding the point of transition in a long time by ‘divide array in 2 part’ strategy and then applying binary search on the required sub-array. Both said its a good solution.
Problem 2: There’s a cricket match going on and you have a stream of scores coming to you. You have to keep a record of the largest n scores with you. How you would do it.Again, I asked questions. Whether I have some scores with me already and then new scores are coming or I’m empty and then scores start to come one by one? Are the scores coming in sorted order? I took a stack and tried solving the question. One of them asked why this data structure. I said that I was just running the problem and not finalizing my decision. Then I gave my solution of using a min-heap. Both said your solution is perfect.
Problem 2: There’s a cricket match going on and you have a stream of scores coming to you. You have to keep a record of the largest n scores with you. How you would do it.
Again, I asked questions. Whether I have some scores with me already and then new scores are coming or I’m empty and then scores start to come one by one? Are the scores coming in sorted order? I took a stack and tried solving the question. One of them asked why this data structure. I said that I was just running the problem and not finalizing my decision. Then I gave my solution of using a min-heap. Both said your solution is perfect.
After this:
Interviewer 2: Do you have any questions?
Me: Yes, how has the company tackled this current pandemic situation because being an American company it got hit pretty badly with stocks fell steeply but ever since May the business seems to have got back on track.
Answered..
Me: One last question ma’am. Have I cleared this round?
Both laughed and one of them said, “Oh very nice, HR will tell you that, keep your fingers crossed.”
And it ended. After about 30 minutes I got a call and the person said you will have your HR round which is the final round at 8:10 PM. I joined the call at 8:10. HR said that there had been a clash as he was taking another interview. I was rescheduled to 9:10 PM.
Note: If you don’t have many projects in your resume then you’ll be asked questions on OOPs and CS core subjects.
HR Interview: The idea in my mind was to not make it a round of questions and answers but a normal chat about the things he wants to talk about. He asked me about my hobbies which led us to a conversation on EDM and rock. He asked me about my family background and the failures that I had faced and how I faced them. I asked him about his working experience and what difference he has seen among the students he has hired in India, Australia, and other countries. I think the key is to listen to what the person is saying and ask questions about something that he has said. If you listen closely you will get questions in your mind and never hesitate to ask. Take every question to be an open-ended question and talk about your experiences in group projects, in college, something that you like.
That’s it. Got a mail from the Placement cell the next morning which stated that I have been selected by the company.
Tips: Don’t think of being calm and chill. It’s an interview and you will be nervous. Just remember that the person interviewing you has also been this nervous when he was giving one of the first interviews of his/her life. It’s normal and happens to everybody. You will feel relaxed automatically and your interviewer will be surprised to see how you are so calm and confident in this situation.
BlackRock
Marketing
On-Campus
Interview Experiences
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Amazon Interview Experience for SDE-1 (Off-Campus)
Amazon AWS Interview Experience for SDE-1
Amazon Interview Experience for SDE-1 (Off-Campus) 2022
Amazon Interview Experience
Amazon Interview Experience for SDE-1
EPAM Interview Experience (Off-Campus)
Amazon Interview Experience (Off-Campus) 2022
JPMorgan Chase & Co. Code for Good Internship Interview Experience 2021
Amazon Interview Experience for SDE-1 (On-Campus)
Freshworks/Freshdesk Interview Experience for Software Developer (On-Campus) | [
{
"code": null,
"e": 26321,
"s": 26293,
"text": "\n09 Sep, 2020"
},
{
"code": null,
"e": 26684,
"s": 26321,
"text": "BlackRock was one of the Super-Dream companies that visited VIT. Eligibility criteria were 60% or CGPA 6 in Xth, XIIth, and pursuing a degree with no standing arrears. 1000 students(Company was open to all branches) were short-listed for the online test for tech. profile(I would be describing the process for tech profile only as that is the one I applied for)."
},
{
"code": null,
"e": 26721,
"s": 26684,
"text": "Online test: The test had 3 sections"
},
{
"code": null,
"e": 27455,
"s": 26721,
"text": "Software aptitude section- A problem was described and a detailed flow chart was provided with some statements missing in some boxes. The questions were like, “Which of the following statements/ commands would come in box x”. There were 3 problems like this and each problem had 4-5 questions. Data structures and Algorithms section- Detailed knowledge of trees was needed. Questions ranged from basic concepts like tree traversals to a detailed understanding of AVL trees. SQL section- 25 MCQs on SQL was asked. Questions involved choosing the suitable query for the given output of the database provided, basic concepts of DBMS. I would recommend stronghold on the basics of SQL and good practice of SQL questions on Hackerrank."
},
{
"code": null,
"e": 27751,
"s": 27455,
"text": "Software aptitude section- A problem was described and a detailed flow chart was provided with some statements missing in some boxes. The questions were like, “Which of the following statements/ commands would come in box x”. There were 3 problems like this and each problem had 4-5 questions. "
},
{
"code": null,
"e": 27933,
"s": 27751,
"text": "Data structures and Algorithms section- Detailed knowledge of trees was needed. Questions ranged from basic concepts like tree traversals to a detailed understanding of AVL trees. "
},
{
"code": null,
"e": 28191,
"s": 27933,
"text": "SQL section- 25 MCQs on SQL was asked. Questions involved choosing the suitable query for the given output of the database provided, basic concepts of DBMS. I would recommend stronghold on the basics of SQL and good practice of SQL questions on Hackerrank."
},
{
"code": null,
"e": 28437,
"s": 28191,
"text": "After this round 152 students were shortlisted for the interviews. As per my experience, there is no exact number of rounds that you have to go through. Some students had 2 technical rounds. I had only one technical round followed by 1 HR round."
},
{
"code": null,
"e": 28527,
"s": 28437,
"text": "Technical Interview: The interview went on for about 1 hour. There were 2 interviewers:-"
},
{
"code": null,
"e": 28566,
"s": 28527,
"text": "Interviewer 1: Tell us about yourself."
},
{
"code": null,
"e": 28904,
"s": 28566,
"text": "Me: Mentioned my name, pursuing my B.Tech. in CSE from VIT which you already know, focusing on programming and my core CS subjects like OS, CN, DBMS these days, have made some decent projects on web-development like to follow tech. trends, other areas of knowledge include penetration testing and ethical hacking, and I make great pasta."
},
{
"code": null,
"e": 29240,
"s": 28904,
"text": "Both laughed. Then a detailed discussion on my web-dev projects followed. I would suggest not to write anything on your resume that you have not done by yourself or don’t know. They go in-depth of it and you will struggle if you try to bluff. After spending about 35 minutes on my projects they moved to data structures and algorithms."
},
{
"code": null,
"e": 29298,
"s": 29240,
"text": "Interviewer 2: How good you think you are in DS and algo?"
},
{
"code": null,
"e": 29355,
"s": 29298,
"text": "Me: Not an expert but I would rate my self 3.5 out of 5."
},
{
"code": null,
"e": 29378,
"s": 29355,
"text": "2 problems were asked."
},
{
"code": null,
"e": 31013,
"s": 29378,
"text": "Problem 1: Find an element In an array in which numbers are in decreasing order first and then the number is in increasing order. Example: {9, 8 , 7, 6, 10, 11, 12, 13} find 12.Very simple problem. I asked many questions about the problem like is the point of transition of the array from decreasing to increasing presence in the center, is it a string input or a number input, is there a situation where the number to search will not be present in the array. It’s always a good practice to ask questions and not jump on solutions. It shows that you are approaching the problem from a wider perspective. Remember, they are not looking for how fast you can solve the problem. They want to see how you approach a problem. They are interested in your problem-solving skills.I gave the brute force a linear approach. Then I gave the optimized approach of finding the point of transition in a long time by ‘divide array in 2 part’ strategy and then applying binary search on the required sub-array. Both said its a good solution.Problem 2: There’s a cricket match going on and you have a stream of scores coming to you. You have to keep a record of the largest n scores with you. How you would do it.Again, I asked questions. Whether I have some scores with me already and then new scores are coming or I’m empty and then scores start to come one by one? Are the scores coming in sorted order? I took a stack and tried solving the question. One of them asked why this data structure. I said that I was just running the problem and not finalizing my decision. Then I gave my solution of using a min-heap. Both said your solution is perfect."
},
{
"code": null,
"e": 32038,
"s": 31013,
"text": "Problem 1: Find an element In an array in which numbers are in decreasing order first and then the number is in increasing order. Example: {9, 8 , 7, 6, 10, 11, 12, 13} find 12.Very simple problem. I asked many questions about the problem like is the point of transition of the array from decreasing to increasing presence in the center, is it a string input or a number input, is there a situation where the number to search will not be present in the array. It’s always a good practice to ask questions and not jump on solutions. It shows that you are approaching the problem from a wider perspective. Remember, they are not looking for how fast you can solve the problem. They want to see how you approach a problem. They are interested in your problem-solving skills.I gave the brute force a linear approach. Then I gave the optimized approach of finding the point of transition in a long time by ‘divide array in 2 part’ strategy and then applying binary search on the required sub-array. Both said its a good solution."
},
{
"code": null,
"e": 32169,
"s": 32038,
"text": "Problem 1: Find an element In an array in which numbers are in decreasing order first and then the number is in increasing order. "
},
{
"code": null,
"e": 32179,
"s": 32169,
"text": "Example: "
},
{
"code": null,
"e": 32218,
"s": 32179,
"text": "{9, 8 , 7, 6, 10, 11, 12, 13} find 12."
},
{
"code": null,
"e": 32813,
"s": 32218,
"text": "Very simple problem. I asked many questions about the problem like is the point of transition of the array from decreasing to increasing presence in the center, is it a string input or a number input, is there a situation where the number to search will not be present in the array. It’s always a good practice to ask questions and not jump on solutions. It shows that you are approaching the problem from a wider perspective. Remember, they are not looking for how fast you can solve the problem. They want to see how you approach a problem. They are interested in your problem-solving skills."
},
{
"code": null,
"e": 33067,
"s": 32813,
"text": "I gave the brute force a linear approach. Then I gave the optimized approach of finding the point of transition in a long time by ‘divide array in 2 part’ strategy and then applying binary search on the required sub-array. Both said its a good solution."
},
{
"code": null,
"e": 33678,
"s": 33067,
"text": "Problem 2: There’s a cricket match going on and you have a stream of scores coming to you. You have to keep a record of the largest n scores with you. How you would do it.Again, I asked questions. Whether I have some scores with me already and then new scores are coming or I’m empty and then scores start to come one by one? Are the scores coming in sorted order? I took a stack and tried solving the question. One of them asked why this data structure. I said that I was just running the problem and not finalizing my decision. Then I gave my solution of using a min-heap. Both said your solution is perfect."
},
{
"code": null,
"e": 33850,
"s": 33678,
"text": "Problem 2: There’s a cricket match going on and you have a stream of scores coming to you. You have to keep a record of the largest n scores with you. How you would do it."
},
{
"code": null,
"e": 34290,
"s": 33850,
"text": "Again, I asked questions. Whether I have some scores with me already and then new scores are coming or I’m empty and then scores start to come one by one? Are the scores coming in sorted order? I took a stack and tried solving the question. One of them asked why this data structure. I said that I was just running the problem and not finalizing my decision. Then I gave my solution of using a min-heap. Both said your solution is perfect."
},
{
"code": null,
"e": 34302,
"s": 34290,
"text": "After this:"
},
{
"code": null,
"e": 34344,
"s": 34302,
"text": "Interviewer 2: Do you have any questions?"
},
{
"code": null,
"e": 34561,
"s": 34344,
"text": "Me: Yes, how has the company tackled this current pandemic situation because being an American company it got hit pretty badly with stocks fell steeply but ever since May the business seems to have got back on track."
},
{
"code": null,
"e": 34572,
"s": 34561,
"text": "Answered.."
},
{
"code": null,
"e": 34628,
"s": 34572,
"text": "Me: One last question ma’am. Have I cleared this round?"
},
{
"code": null,
"e": 34729,
"s": 34628,
"text": "Both laughed and one of them said, “Oh very nice, HR will tell you that, keep your fingers crossed.”"
},
{
"code": null,
"e": 34993,
"s": 34729,
"text": "And it ended. After about 30 minutes I got a call and the person said you will have your HR round which is the final round at 8:10 PM. I joined the call at 8:10. HR said that there had been a clash as he was taking another interview. I was rescheduled to 9:10 PM."
},
{
"code": null,
"e": 35107,
"s": 34993,
"text": "Note: If you don’t have many projects in your resume then you’ll be asked questions on OOPs and CS core subjects."
},
{
"code": null,
"e": 35904,
"s": 35107,
"text": "HR Interview: The idea in my mind was to not make it a round of questions and answers but a normal chat about the things he wants to talk about. He asked me about my hobbies which led us to a conversation on EDM and rock. He asked me about my family background and the failures that I had faced and how I faced them. I asked him about his working experience and what difference he has seen among the students he has hired in India, Australia, and other countries. I think the key is to listen to what the person is saying and ask questions about something that he has said. If you listen closely you will get questions in your mind and never hesitate to ask. Take every question to be an open-ended question and talk about your experiences in group projects, in college, something that you like. "
},
{
"code": null,
"e": 36023,
"s": 35904,
"text": "That’s it. Got a mail from the Placement cell the next morning which stated that I have been selected by the company. "
},
{
"code": null,
"e": 36423,
"s": 36023,
"text": "Tips: Don’t think of being calm and chill. It’s an interview and you will be nervous. Just remember that the person interviewing you has also been this nervous when he was giving one of the first interviews of his/her life. It’s normal and happens to everybody. You will feel relaxed automatically and your interviewer will be surprised to see how you are so calm and confident in this situation. "
},
{
"code": null,
"e": 36436,
"s": 36426,
"text": "BlackRock"
},
{
"code": null,
"e": 36446,
"s": 36436,
"text": "Marketing"
},
{
"code": null,
"e": 36456,
"s": 36446,
"text": "On-Campus"
},
{
"code": null,
"e": 36478,
"s": 36456,
"text": "Interview Experiences"
},
{
"code": null,
"e": 36576,
"s": 36478,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 36627,
"s": 36576,
"text": "Amazon Interview Experience for SDE-1 (Off-Campus)"
},
{
"code": null,
"e": 36669,
"s": 36627,
"text": "Amazon AWS Interview Experience for SDE-1"
},
{
"code": null,
"e": 36725,
"s": 36669,
"text": "Amazon Interview Experience for SDE-1 (Off-Campus) 2022"
},
{
"code": null,
"e": 36753,
"s": 36725,
"text": "Amazon Interview Experience"
},
{
"code": null,
"e": 36791,
"s": 36753,
"text": "Amazon Interview Experience for SDE-1"
},
{
"code": null,
"e": 36830,
"s": 36791,
"text": "EPAM Interview Experience (Off-Campus)"
},
{
"code": null,
"e": 36876,
"s": 36830,
"text": "Amazon Interview Experience (Off-Campus) 2022"
},
{
"code": null,
"e": 36948,
"s": 36876,
"text": "JPMorgan Chase & Co. Code for Good Internship Interview Experience 2021"
},
{
"code": null,
"e": 36998,
"s": 36948,
"text": "Amazon Interview Experience for SDE-1 (On-Campus)"
}
] |
Ruby | Array uniq() function - GeeksforGeeks | 06 Dec, 2019
Array#uniq() : uniq() is a Array class method which returns a new array by removing duplicate values in the array.
Syntax: Array.uniq()
Parameter: Array
Return: a new array by removing duplicate values in the array
Example #1 :
# Ruby code for uniq() method # declaring arraya = [18, 22, 33, nil, 5, 6] # declaring arrayb = [1, 4, 1, 1, 88, 9] # declaring arrayc = [18, 22, 50, 6] # uniq method exampleputs "uniq() method form : #{a.uniq()}\n\n" puts "uniq() method form : #{b.uniq()}\n\n" puts "uniq() method form : #{c.uniq()}\n\n"
Output :
uniq() method form : [18, 22, 33, nil, 5, 6]
uniq() method form : [1, 4, 88, 9]
uniq() method form : [18, 22, 50, 6]
Example #2 :
# Ruby code for uniq() method # declaring arraya = ["abc", "nil", "dog"] # declaring arrayc = ["cat", nil] # declaring arrayb = ["cow", "gogoog", "dog"] # uniq method exampleputs "uniq() method form : #{a.uniq()}\n\n" puts "uniq() method form : #{b.uniq()}\n\n" puts "uniq() method form : #{c.uniq()}\n\n"
Output :
uniq() method form : ["abc", "nil", "dog"]
uniq() method form : ["cow", "gogoog", "dog"]
uniq() 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.
Include v/s Extend in Ruby
Global Variable in Ruby
Ruby | Hash delete() function
Ruby | Types of Variables
Ruby | Enumerator each_with_index function
Ruby | Case Statement
Ruby | Array select() function
Ruby | Numeric round() function
Ruby | Data Types
Ruby | String capitalize() Method | [
{
"code": null,
"e": 24955,
"s": 24927,
"text": "\n06 Dec, 2019"
},
{
"code": null,
"e": 25070,
"s": 24955,
"text": "Array#uniq() : uniq() is a Array class method which returns a new array by removing duplicate values in the array."
},
{
"code": null,
"e": 25091,
"s": 25070,
"text": "Syntax: Array.uniq()"
},
{
"code": null,
"e": 25108,
"s": 25091,
"text": "Parameter: Array"
},
{
"code": null,
"e": 25170,
"s": 25108,
"text": "Return: a new array by removing duplicate values in the array"
},
{
"code": null,
"e": 25183,
"s": 25170,
"text": "Example #1 :"
},
{
"code": "# Ruby code for uniq() method # declaring arraya = [18, 22, 33, nil, 5, 6] # declaring arrayb = [1, 4, 1, 1, 88, 9] # declaring arrayc = [18, 22, 50, 6] # uniq method exampleputs \"uniq() method form : #{a.uniq()}\\n\\n\" puts \"uniq() method form : #{b.uniq()}\\n\\n\" puts \"uniq() method form : #{c.uniq()}\\n\\n\"",
"e": 25495,
"s": 25183,
"text": null
},
{
"code": null,
"e": 25504,
"s": 25495,
"text": "Output :"
},
{
"code": null,
"e": 25625,
"s": 25504,
"text": "uniq() method form : [18, 22, 33, nil, 5, 6]\n\nuniq() method form : [1, 4, 88, 9]\n\nuniq() method form : [18, 22, 50, 6]\n\n"
},
{
"code": null,
"e": 25638,
"s": 25625,
"text": "Example #2 :"
},
{
"code": "# Ruby code for uniq() method # declaring arraya = [\"abc\", \"nil\", \"dog\"] # declaring arrayc = [\"cat\", nil] # declaring arrayb = [\"cow\", \"gogoog\", \"dog\"] # uniq method exampleputs \"uniq() method form : #{a.uniq()}\\n\\n\" puts \"uniq() method form : #{b.uniq()}\\n\\n\" puts \"uniq() method form : #{c.uniq()}\\n\\n\"",
"e": 25952,
"s": 25638,
"text": null
},
{
"code": null,
"e": 25961,
"s": 25952,
"text": "Output :"
},
{
"code": null,
"e": 26088,
"s": 25961,
"text": "uniq() method form : [\"abc\", \"nil\", \"dog\"]\n\nuniq() method form : [\"cow\", \"gogoog\", \"dog\"]\n\nuniq() method form : [\"cat\", nil]\n\n"
},
{
"code": null,
"e": 26105,
"s": 26088,
"text": "Ruby Array-class"
},
{
"code": null,
"e": 26118,
"s": 26105,
"text": "Ruby-Methods"
},
{
"code": null,
"e": 26123,
"s": 26118,
"text": "Ruby"
},
{
"code": null,
"e": 26221,
"s": 26123,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26248,
"s": 26221,
"text": "Include v/s Extend in Ruby"
},
{
"code": null,
"e": 26272,
"s": 26248,
"text": "Global Variable in Ruby"
},
{
"code": null,
"e": 26302,
"s": 26272,
"text": "Ruby | Hash delete() function"
},
{
"code": null,
"e": 26328,
"s": 26302,
"text": "Ruby | Types of Variables"
},
{
"code": null,
"e": 26371,
"s": 26328,
"text": "Ruby | Enumerator each_with_index function"
},
{
"code": null,
"e": 26393,
"s": 26371,
"text": "Ruby | Case Statement"
},
{
"code": null,
"e": 26424,
"s": 26393,
"text": "Ruby | Array select() function"
},
{
"code": null,
"e": 26456,
"s": 26424,
"text": "Ruby | Numeric round() function"
},
{
"code": null,
"e": 26474,
"s": 26456,
"text": "Ruby | Data Types"
}
] |
How to Implement Shapeable ImageView in Android? - GeeksforGeeks | 20 Dec, 2021
In Android, ShapeableImageView is used to change the shape of your image to circle, diamond, etc. Also, you can set a corner radius to your ImageView. You can do much more by using this ShapeableImageView with minimal code. So in this article, we are going to make a ShapableImageView in android. By implementing this application we will get a basic idea of how editing of photos is done in android applications. Here we will implement two features i.e to cut or round the corners of an image.
Here we will be using two images, one image we will edit with XML code and the other with java code. Using SeekBar the user can round or cut all four corners of the image separately. Note that we are going to implement this application using Java language. A sample video is given below to get an idea about what we are going to do in this article.
Step 1: Creating a new project
Open a new project.
We will be working on Empty Activity with language as Java. Leave all other options unchanged.
You can change the name of the project at your convenience.
There will be two default files named activity_main.xml and MainActivity.java.
If you don’t know how to create a new project in Android Studio then you can refer to How to Create/Start a New Project in Android Studio?
Step 2: Adding the required dependency
Open Gradle Scripts > build.gradle(module). Go to app > right click > open module settings > dependencies > Add dependency > Library dependency.
Type material in the search bar and click on search. Select the dependency shown in the below image-
Click on sync now to save the changes.
Step 3: Working with the activity_main.xml file
Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file.
XML
<?xml version="1.0" encoding="utf-8"?> <!-- Linear layout as parent layout--><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" android:padding="16dp" android:gravity="center" tools:context=".MainActivity"> <!-- text view to show the text "using xml"--> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Using xml" android:textStyle="bold" android:textSize="20sp" android:padding="12dp" /> <!-- shapable image view--> <com.google.android.material.imageview.ShapeableImageView android:layout_width="339dp" android:layout_height="230dp" android:adjustViewBounds="true" android:scaleType="centerCrop" android:src="@drawable/gfg" app:shapeAppearance="@style/CornerCut" /> <!-- text view to show the text "using java"--> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Using Java" android:textSize="20sp" android:textStyle="bold" android:padding="12dp" /> <!-- shapable image view--> <com.google.android.material.imageview.ShapeableImageView android:layout_width="339dp" android:layout_height="230dp" android:layout_weight="1" android:id="@+id/image_View" android:src="@drawable/gfg" android:adjustViewBounds="true" android:scaleType="centerCrop" /> <!-- spinner to provide options of round and cur--> <Spinner android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/sp_family" android:padding="12dp" android:layout_marginTop="16dp" /> <!-- seekbar for top left corner--> <SeekBar android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/sb_top_left" android:layout_marginTop="16dp" /> <!-- seekbar for top right corner--> <SeekBar android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/sb_top_right" android:layout_marginTop="8dp" /> <!-- seekbar for bottom left corner--> <SeekBar android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/sb_bottom_left" android:layout_marginTop="8dp" /> <!-- seekbar for bottom right corner--> <SeekBar android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/sb_bottom_right" android:layout_marginTop="8dp" /> </LinearLayout>
Step 4: Working on themes.xml file
Navigate to res > values > themes > themes.xml file and use the below code in it.
XML
<resources xmlns:tools="http://schemas.android.com/tools"> <!-- Base application theme. --> <style name="Theme.ShapableImageView" parent="Theme.MaterialComponents.DayNight.DarkActionBar"> <!-- Primary brand color. --> <item name="colorPrimary">@color/purple_500</item> <item name="colorPrimaryVariant">@color/purple_700</item> <item name="colorOnPrimary">@color/white</item> <!-- Secondary brand color. --> <item name="colorSecondary">@color/teal_200</item> <item name="colorSecondaryVariant">@color/teal_700</item> <item name="colorOnSecondary">@color/black</item> <!-- Status bar color. --> <item name="android:statusBarColor" tools:targetApi="l">?attr/colorPrimaryVariant</item> <!-- Customize your theme here. --> </style> <style name="CornerCut" parent=""> <item name="cornerFamilyTopLeft">rounded</item> <item name="cornerFamilyTopRight">cut</item> <item name="cornerFamilyBottomLeft">cut</item> <item name="cornerFamilyBottomRight">rounded</item> <item name="cornerSizeTopLeft">50%</item> <item name="cornerSizeTopRight">25%</item> <item name="cornerSizeBottomLeft">25%</item> <item name="cornerSizeBottomRight">50%</item> </style></resources>
After executing the above code design of the activity_main.xml file looks like this.
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
package com.example.shapableimageview; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle;import android.view.View;import android.widget.AdapterView;import android.widget.ArrayAdapter;import android.widget.SeekBar;import android.widget.Spinner; import com.google.android.material.imageview.ShapeableImageView;import com.google.android.material.shape.CornerFamily; import java.util.ArrayList; public class MainActivity extends AppCompatActivity implements SeekBar.OnSeekBarChangeListener { // Initialize variable ShapeableImageView imageView; Spinner spFamily; SeekBar sbTopLeft,sbTopRight,sbBottomLeft,sbBottomRight; int cornerFamily= CornerFamily.CUT,topLeft=0,topRight=0,bottomLeft=0,bottomRight=0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // assign variable imageView=findViewById(R.id.image_View); spFamily=findViewById(R.id.sp_family); sbTopLeft=findViewById(R.id.sb_top_left); sbTopRight=findViewById(R.id.sb_top_right); sbBottomLeft=findViewById(R.id.sb_bottom_left); sbBottomRight=findViewById(R.id.sb_bottom_right); // Initialize array list ArrayList<String> arrayList=new ArrayList<>(); // add values in array List arrayList.add("cut"); arrayList.add("rounded"); // set adapter spFamily.setAdapter(new ArrayAdapter<>(MainActivity.this, android.R.layout.simple_spinner_dropdown_item,arrayList)); // Set Listener on spinner spFamily.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { // check condition if(position==0) { // when cut selected cornerFamily=CornerFamily.CUT; } else { // when rounded selected cornerFamily=CornerFamily.ROUNDED; } // create update method updateImage(); } @Override public void onNothingSelected(AdapterView<?> parent) { } }); // set listener on all seekbar sbTopLeft.setOnSeekBarChangeListener(this); sbTopRight.setOnSeekBarChangeListener(this); sbBottomRight.setOnSeekBarChangeListener(this); sbBottomLeft.setOnSeekBarChangeListener(this); } private void updateImage() { // set appearance imageView.setShapeAppearanceModel(imageView.getShapeAppearanceModel().toBuilder() .setTopLeftCorner(cornerFamily,topLeft) .setTopRightCorner(cornerFamily,topRight) .setBottomLeftCorner(cornerFamily,bottomLeft) .setBottomRightCorner(cornerFamily,bottomRight) .build()); } @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { switch (seekBar.getId()) { case R.id.sb_top_left: topLeft=progress; break; case R.id.sb_top_right: topRight=progress; break; case R.id.sb_bottom_left: bottomLeft=progress; break; case R.id.sb_bottom_right: bottomRight=progress; break; } // call update method updateImage(); } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { }}
Here is the final output of our application.
Output:
Android
Java
Java
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Resource Raw Folder in Android Studio
Flutter - Custom Bottom Navigation Bar
How to Read Data from SQLite Database in Android?
How to Post Data to API using Retrofit in Android?
Retrofit with Kotlin Coroutine in Android
Arrays in Java
Split() String method in Java with examples
For-each loop in Java
Object Oriented Programming (OOPs) Concept in Java
Arrays.sort() in Java with examples | [
{
"code": null,
"e": 26381,
"s": 26353,
"text": "\n20 Dec, 2021"
},
{
"code": null,
"e": 26875,
"s": 26381,
"text": "In Android, ShapeableImageView is used to change the shape of your image to circle, diamond, etc. Also, you can set a corner radius to your ImageView. You can do much more by using this ShapeableImageView with minimal code. So in this article, we are going to make a ShapableImageView in android. By implementing this application we will get a basic idea of how editing of photos is done in android applications. Here we will implement two features i.e to cut or round the corners of an image."
},
{
"code": null,
"e": 27224,
"s": 26875,
"text": "Here we will be using two images, one image we will edit with XML code and the other with java code. Using SeekBar the user can round or cut all four corners of the image separately. Note that we are going to implement this application using Java language. A sample video is given below to get an idea about what we are going to do in this article."
},
{
"code": null,
"e": 27255,
"s": 27224,
"text": "Step 1: Creating a new project"
},
{
"code": null,
"e": 27275,
"s": 27255,
"text": "Open a new project."
},
{
"code": null,
"e": 27370,
"s": 27275,
"text": "We will be working on Empty Activity with language as Java. Leave all other options unchanged."
},
{
"code": null,
"e": 27430,
"s": 27370,
"text": "You can change the name of the project at your convenience."
},
{
"code": null,
"e": 27509,
"s": 27430,
"text": "There will be two default files named activity_main.xml and MainActivity.java."
},
{
"code": null,
"e": 27649,
"s": 27509,
"text": "If you don’t know how to create a new project in Android Studio then you can refer to How to Create/Start a New Project in Android Studio? "
},
{
"code": null,
"e": 27688,
"s": 27649,
"text": "Step 2: Adding the required dependency"
},
{
"code": null,
"e": 27833,
"s": 27688,
"text": "Open Gradle Scripts > build.gradle(module). Go to app > right click > open module settings > dependencies > Add dependency > Library dependency."
},
{
"code": null,
"e": 27934,
"s": 27833,
"text": "Type material in the search bar and click on search. Select the dependency shown in the below image-"
},
{
"code": null,
"e": 27973,
"s": 27934,
"text": "Click on sync now to save the changes."
},
{
"code": null,
"e": 28021,
"s": 27973,
"text": "Step 3: Working with the activity_main.xml file"
},
{
"code": null,
"e": 28164,
"s": 28021,
"text": "Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. "
},
{
"code": null,
"e": 28168,
"s": 28164,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?> <!-- Linear layout as parent layout--><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\" android:padding=\"16dp\" android:gravity=\"center\" tools:context=\".MainActivity\"> <!-- text view to show the text \"using xml\"--> <TextView android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:text=\"Using xml\" android:textStyle=\"bold\" android:textSize=\"20sp\" android:padding=\"12dp\" /> <!-- shapable image view--> <com.google.android.material.imageview.ShapeableImageView android:layout_width=\"339dp\" android:layout_height=\"230dp\" android:adjustViewBounds=\"true\" android:scaleType=\"centerCrop\" android:src=\"@drawable/gfg\" app:shapeAppearance=\"@style/CornerCut\" /> <!-- text view to show the text \"using java\"--> <TextView android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:text=\"Using Java\" android:textSize=\"20sp\" android:textStyle=\"bold\" android:padding=\"12dp\" /> <!-- shapable image view--> <com.google.android.material.imageview.ShapeableImageView android:layout_width=\"339dp\" android:layout_height=\"230dp\" android:layout_weight=\"1\" android:id=\"@+id/image_View\" android:src=\"@drawable/gfg\" android:adjustViewBounds=\"true\" android:scaleType=\"centerCrop\" /> <!-- spinner to provide options of round and cur--> <Spinner android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:id=\"@+id/sp_family\" android:padding=\"12dp\" android:layout_marginTop=\"16dp\" /> <!-- seekbar for top left corner--> <SeekBar android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:id=\"@+id/sb_top_left\" android:layout_marginTop=\"16dp\" /> <!-- seekbar for top right corner--> <SeekBar android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:id=\"@+id/sb_top_right\" android:layout_marginTop=\"8dp\" /> <!-- seekbar for bottom left corner--> <SeekBar android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:id=\"@+id/sb_bottom_left\" android:layout_marginTop=\"8dp\" /> <!-- seekbar for bottom right corner--> <SeekBar android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:id=\"@+id/sb_bottom_right\" android:layout_marginTop=\"8dp\" /> </LinearLayout>",
"e": 31125,
"s": 28168,
"text": null
},
{
"code": null,
"e": 31160,
"s": 31125,
"text": "Step 4: Working on themes.xml file"
},
{
"code": null,
"e": 31242,
"s": 31160,
"text": "Navigate to res > values > themes > themes.xml file and use the below code in it."
},
{
"code": null,
"e": 31246,
"s": 31242,
"text": "XML"
},
{
"code": "<resources xmlns:tools=\"http://schemas.android.com/tools\"> <!-- Base application theme. --> <style name=\"Theme.ShapableImageView\" parent=\"Theme.MaterialComponents.DayNight.DarkActionBar\"> <!-- Primary brand color. --> <item name=\"colorPrimary\">@color/purple_500</item> <item name=\"colorPrimaryVariant\">@color/purple_700</item> <item name=\"colorOnPrimary\">@color/white</item> <!-- Secondary brand color. --> <item name=\"colorSecondary\">@color/teal_200</item> <item name=\"colorSecondaryVariant\">@color/teal_700</item> <item name=\"colorOnSecondary\">@color/black</item> <!-- Status bar color. --> <item name=\"android:statusBarColor\" tools:targetApi=\"l\">?attr/colorPrimaryVariant</item> <!-- Customize your theme here. --> </style> <style name=\"CornerCut\" parent=\"\"> <item name=\"cornerFamilyTopLeft\">rounded</item> <item name=\"cornerFamilyTopRight\">cut</item> <item name=\"cornerFamilyBottomLeft\">cut</item> <item name=\"cornerFamilyBottomRight\">rounded</item> <item name=\"cornerSizeTopLeft\">50%</item> <item name=\"cornerSizeTopRight\">25%</item> <item name=\"cornerSizeBottomLeft\">25%</item> <item name=\"cornerSizeBottomRight\">50%</item> </style></resources>",
"e": 32553,
"s": 31246,
"text": null
},
{
"code": null,
"e": 32638,
"s": 32553,
"text": "After executing the above code design of the activity_main.xml file looks like this."
},
{
"code": null,
"e": 32686,
"s": 32638,
"text": "Step 5: Working with the MainActivity.java file"
},
{
"code": null,
"e": 32876,
"s": 32686,
"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": 32881,
"s": 32876,
"text": "Java"
},
{
"code": "package com.example.shapableimageview; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle;import android.view.View;import android.widget.AdapterView;import android.widget.ArrayAdapter;import android.widget.SeekBar;import android.widget.Spinner; import com.google.android.material.imageview.ShapeableImageView;import com.google.android.material.shape.CornerFamily; import java.util.ArrayList; public class MainActivity extends AppCompatActivity implements SeekBar.OnSeekBarChangeListener { // Initialize variable ShapeableImageView imageView; Spinner spFamily; SeekBar sbTopLeft,sbTopRight,sbBottomLeft,sbBottomRight; int cornerFamily= CornerFamily.CUT,topLeft=0,topRight=0,bottomLeft=0,bottomRight=0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // assign variable imageView=findViewById(R.id.image_View); spFamily=findViewById(R.id.sp_family); sbTopLeft=findViewById(R.id.sb_top_left); sbTopRight=findViewById(R.id.sb_top_right); sbBottomLeft=findViewById(R.id.sb_bottom_left); sbBottomRight=findViewById(R.id.sb_bottom_right); // Initialize array list ArrayList<String> arrayList=new ArrayList<>(); // add values in array List arrayList.add(\"cut\"); arrayList.add(\"rounded\"); // set adapter spFamily.setAdapter(new ArrayAdapter<>(MainActivity.this, android.R.layout.simple_spinner_dropdown_item,arrayList)); // Set Listener on spinner spFamily.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { // check condition if(position==0) { // when cut selected cornerFamily=CornerFamily.CUT; } else { // when rounded selected cornerFamily=CornerFamily.ROUNDED; } // create update method updateImage(); } @Override public void onNothingSelected(AdapterView<?> parent) { } }); // set listener on all seekbar sbTopLeft.setOnSeekBarChangeListener(this); sbTopRight.setOnSeekBarChangeListener(this); sbBottomRight.setOnSeekBarChangeListener(this); sbBottomLeft.setOnSeekBarChangeListener(this); } private void updateImage() { // set appearance imageView.setShapeAppearanceModel(imageView.getShapeAppearanceModel().toBuilder() .setTopLeftCorner(cornerFamily,topLeft) .setTopRightCorner(cornerFamily,topRight) .setBottomLeftCorner(cornerFamily,bottomLeft) .setBottomRightCorner(cornerFamily,bottomRight) .build()); } @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { switch (seekBar.getId()) { case R.id.sb_top_left: topLeft=progress; break; case R.id.sb_top_right: topRight=progress; break; case R.id.sb_bottom_left: bottomLeft=progress; break; case R.id.sb_bottom_right: bottomRight=progress; break; } // call update method updateImage(); } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { }}",
"e": 36822,
"s": 32881,
"text": null
},
{
"code": null,
"e": 36867,
"s": 36822,
"text": "Here is the final output of our application."
},
{
"code": null,
"e": 36875,
"s": 36867,
"text": "Output:"
},
{
"code": null,
"e": 36883,
"s": 36875,
"text": "Android"
},
{
"code": null,
"e": 36888,
"s": 36883,
"text": "Java"
},
{
"code": null,
"e": 36893,
"s": 36888,
"text": "Java"
},
{
"code": null,
"e": 36901,
"s": 36893,
"text": "Android"
},
{
"code": null,
"e": 36999,
"s": 36901,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 37037,
"s": 36999,
"text": "Resource Raw Folder in Android Studio"
},
{
"code": null,
"e": 37076,
"s": 37037,
"text": "Flutter - Custom Bottom Navigation Bar"
},
{
"code": null,
"e": 37126,
"s": 37076,
"text": "How to Read Data from SQLite Database in Android?"
},
{
"code": null,
"e": 37177,
"s": 37126,
"text": "How to Post Data to API using Retrofit in Android?"
},
{
"code": null,
"e": 37219,
"s": 37177,
"text": "Retrofit with Kotlin Coroutine in Android"
},
{
"code": null,
"e": 37234,
"s": 37219,
"text": "Arrays in Java"
},
{
"code": null,
"e": 37278,
"s": 37234,
"text": "Split() String method in Java with examples"
},
{
"code": null,
"e": 37300,
"s": 37278,
"text": "For-each loop in Java"
},
{
"code": null,
"e": 37351,
"s": 37300,
"text": "Object Oriented Programming (OOPs) Concept in Java"
}
] |
Find Nth term of series 1, 4, 15, 72, 420... - GeeksforGeeks | 14 May, 2021
Given a number N. The task is to write a program to find the Nth term in the below series:
1, 4, 15, 72, 420...
Examples:
Input: 3
Output: 15
For N = 3, we know that the factorial of 3 is 6
Nth term = 6*(3+2)/2
= 15
Input: 6
Output: 2880
For N = 6, we know that the factorial of 6 is 720
Nth term = 620*(6+2)/2
= 2880
The idea is to first find the factorial of the given number N, that is N!. Now the N-th term in the above series will be:
N-th term = N! * (N + 2)/2
Below is the implementation of the above approach:
C++
Java
Python3
C#
PHP
Javascript
// CPP program to find N-th term of the series:// 1, 4, 15, 72, 420...#include <iostream>using namespace std; // Function to find factorial of Nint factorial(int N){ int fact = 1; for (int i = 1; i <= N; i++) fact = fact * i; // return factorial of N return fact;} // calculate Nth term of seriesint nthTerm(int N){ return (factorial(N) * (N + 2) / 2);} // Driver Functionint main(){ int N = 6; cout << nthTerm(N); return 0;}
// Java program to find N-th// term of the series:// 1, 4, 15, 72, 420import java.util.*;import java.lang.*;import java.io.*; class GFG{ // Function to find factorial of Nstatic int factorial(int N){ int fact = 1; for (int i = 1; i <= N; i++) fact = fact * i; // return factorial of N return fact;} // calculate Nth term of seriesstatic int nthTerm(int N){ return (factorial(N) * (N + 2) / 2);} // Driver Codepublic static void main(String args[]){ int N = 6; System.out.println(nthTerm(N));}} // This code is contributed by Subhadeep
# Python 3 program to find# N-th term of the series:# 1, 4, 15, 72, 420... # Function for finding# factorial of Ndef factorial(N) : fact = 1 for i in range(1, N + 1) : fact = fact * i # return factorial of N return fact # Function for calculating# Nth term of seriesdef nthTerm(N) : # return nth term return (factorial(N) * (N + 2) // 2) # Driver codeif __name__ == "__main__" : N = 6 # Function Calling print(nthTerm(N)) # This code is contributed# by ANKITRAI1
// C# program to find N-th// term of the series:// 1, 4, 15, 72, 420using System; class GFG{ // Function to find factorial of Nstatic int factorial(int N){ int fact = 1; for (int i = 1; i <= N; i++) fact = fact * i; // return factorial of N return fact;} // calculate Nth term of seriesstatic int nthTerm(int N){ return (factorial(N) * (N + 2) / 2);} // Driver Codepublic static void Main(){ int N = 6; Console.Write(nthTerm(N));}} // This code is contributed by ChitraNayal
<?php// PHP program to find// N-th term of the series:// 1, 4, 15, 72, 420... // Function for finding// factorial of Nfunction factorial($N){ $fact = 1; for($i = 1; $i <= $N; $i++) $fact = $fact * $i; // return factorial of N return $fact;} // Function for calculating// Nth term of seriesfunction nthTerm($N){ // return nth term return (factorial($N) * ($N + 2) / 2);} // Driver code$N = 6; // Function Callingecho nthTerm($N); // This code is contributed// by mits?>
<script> // JavaScript program to find N-th term of the series:// 1, 4, 15, 72, 420... // Function to find factorial of Nfunction factorial( N){ let fact = 1; for (let i = 1; i <= N; i++) fact = fact * i; // return factorial of N return fact;} // calculate Nth term of seriesfunction nthTerm(N){ return (factorial(N) * (N + 2) / 2);}// Driver code let N = 6; document.write( nthTerm(N) ); // This code contributed by aashish1995 </script>
2880
Another approach :(Using recursion)
C++
Java
Python3
C#
PHP
Javascript
// CPP program to find N-th term of the series:// 1, 4, 15, 72, 420...// Using recursion#include <iostream>using namespace std; // Function to find factorial of N// with recursionint factorial(int N){ // base condition if( N == 0 || N == 1 ) return 1; // use recursion return N * factorial( N - 1 );} // calculate Nth term of seriesint nthTerm(int N){ return (factorial(N) * (N + 2) / 2);} // Driver Functionint main(){ int N = 6; cout << nthTerm(N); return 0;}
// Java program to find N-th// term of the series:// 1, 4, 15, 72, 420import java.util.*;import java.lang.*;import java.io.*; class GFG{ // Function to find factorial of Nstatic int factorial(int N){ // base condition if( N == 0 || N == 1 ) return 1; // use recursion return N * factorial( N - 1 );} // calculate Nth term of seriesstatic int nthTerm(int N){ return (factorial(N) * (N + 2) / 2);} // Driver Codepublic static void main(String args[]){ int N = 6; System.out.println(nthTerm(N));}}
# Python3 program to find# N-th term of the series:# 1, 4, 15, 72, 420...# Using recursion # Function to find factorial# of N with recursiondef factorial(N): # base condition if N == 0 or N == 1: return 1 # use recursion return N * factorial(N - 1) def nthTerm(N): # calculate Nth term of series return (factorial(N) * (N + 2) // 2) # Driver codeN = 6print(nthTerm(N)) # This code is contributed# by Shrikant13
// C# program to find N-th// term of the series:// 1, 4, 15, 72, 420using System; class GFG{ // Function to find factorial of Nstatic int factorial(int N){ // base condition if( N == 0 || N == 1 ) return 1; // use recursion return N * factorial( N - 1 );} // calculate Nth term of seriesstatic int nthTerm(int N){ return (factorial(N) * (N + 2) / 2);} // Driver Codepublic static void Main(){ int N = 6; Console.Write(nthTerm(N));}} // This code is contributed by ChitraNayal
<?php// PHP program to find// N-th term of the series:// 1, 4, 15, 72, 420... // Function to find factorial// of N with recursionfunction factorial($N){ // base condition if($N == 0 or $N == 1) return 1; // use recursion return $N * factorial($N - 1);} // calculate Nth term of seriesfunction nthTerm($N){ return (factorial($N) * ($N + 2) / 2);} // Driver Code$N = 6; echo nthTerm($N); // This code is contributed// by Shashank?>
<script> // Javascript program to find N-th// term of the series:// 1, 4, 15, 72, 420 // Function to find factorial of Nfunction factorial(N){ // Base condition if (N == 0 || N == 1) return 1; // Use recursion return N * factorial(N - 1);} // Calculate Nth term of seriesfunction nthTerm(N){ return(factorial(N) * (N + 2) / 2);} // Driver Codelet N = 6; document.write(nthTerm(N)); // This code is contributed by avanitrachhadiya2155 </script>
2880
Time complexity: O(N)Note: Above code wouldn’t not work for large values of N. To find the values for large N, use the concept of Factorial for large numbers.
ankthon
tufan_gupta2000
Mithun Kumar
ukasp
Rajput-Ji
Shashank12
shrikanth13
aashish1995
avanitrachhadiya2155
factorial
C++
Pattern Searching
School Programming
Pattern Searching
factorial
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Operator Overloading in C++
Polymorphism in C++
Friend class and function in C++
Sorting a vector in C++
std::string class in C++
KMP Algorithm for Pattern Searching
Rabin-Karp Algorithm for Pattern Searching
Check if a string is substring of another
Naive algorithm for Pattern Searching
Boyer Moore Algorithm for Pattern Searching | [
{
"code": null,
"e": 25445,
"s": 25417,
"text": "\n14 May, 2021"
},
{
"code": null,
"e": 25537,
"s": 25445,
"text": "Given a number N. The task is to write a program to find the Nth term in the below series: "
},
{
"code": null,
"e": 25558,
"s": 25537,
"text": "1, 4, 15, 72, 420..."
},
{
"code": null,
"e": 25570,
"s": 25558,
"text": "Examples: "
},
{
"code": null,
"e": 25785,
"s": 25570,
"text": "Input: 3\nOutput: 15\nFor N = 3, we know that the factorial of 3 is 6\nNth term = 6*(3+2)/2\n = 15\n\nInput: 6\nOutput: 2880\nFor N = 6, we know that the factorial of 6 is 720\nNth term = 620*(6+2)/2\n = 2880"
},
{
"code": null,
"e": 25907,
"s": 25785,
"text": "The idea is to first find the factorial of the given number N, that is N!. Now the N-th term in the above series will be:"
},
{
"code": null,
"e": 25934,
"s": 25907,
"text": "N-th term = N! * (N + 2)/2"
},
{
"code": null,
"e": 25986,
"s": 25934,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 25990,
"s": 25986,
"text": "C++"
},
{
"code": null,
"e": 25995,
"s": 25990,
"text": "Java"
},
{
"code": null,
"e": 26003,
"s": 25995,
"text": "Python3"
},
{
"code": null,
"e": 26006,
"s": 26003,
"text": "C#"
},
{
"code": null,
"e": 26010,
"s": 26006,
"text": "PHP"
},
{
"code": null,
"e": 26021,
"s": 26010,
"text": "Javascript"
},
{
"code": "// CPP program to find N-th term of the series:// 1, 4, 15, 72, 420...#include <iostream>using namespace std; // Function to find factorial of Nint factorial(int N){ int fact = 1; for (int i = 1; i <= N; i++) fact = fact * i; // return factorial of N return fact;} // calculate Nth term of seriesint nthTerm(int N){ return (factorial(N) * (N + 2) / 2);} // Driver Functionint main(){ int N = 6; cout << nthTerm(N); return 0;}",
"e": 26506,
"s": 26021,
"text": null
},
{
"code": "// Java program to find N-th// term of the series:// 1, 4, 15, 72, 420import java.util.*;import java.lang.*;import java.io.*; class GFG{ // Function to find factorial of Nstatic int factorial(int N){ int fact = 1; for (int i = 1; i <= N; i++) fact = fact * i; // return factorial of N return fact;} // calculate Nth term of seriesstatic int nthTerm(int N){ return (factorial(N) * (N + 2) / 2);} // Driver Codepublic static void main(String args[]){ int N = 6; System.out.println(nthTerm(N));}} // This code is contributed by Subhadeep",
"e": 27092,
"s": 26506,
"text": null
},
{
"code": "# Python 3 program to find# N-th term of the series:# 1, 4, 15, 72, 420... # Function for finding# factorial of Ndef factorial(N) : fact = 1 for i in range(1, N + 1) : fact = fact * i # return factorial of N return fact # Function for calculating# Nth term of seriesdef nthTerm(N) : # return nth term return (factorial(N) * (N + 2) // 2) # Driver codeif __name__ == \"__main__\" : N = 6 # Function Calling print(nthTerm(N)) # This code is contributed# by ANKITRAI1",
"e": 27597,
"s": 27092,
"text": null
},
{
"code": "// C# program to find N-th// term of the series:// 1, 4, 15, 72, 420using System; class GFG{ // Function to find factorial of Nstatic int factorial(int N){ int fact = 1; for (int i = 1; i <= N; i++) fact = fact * i; // return factorial of N return fact;} // calculate Nth term of seriesstatic int nthTerm(int N){ return (factorial(N) * (N + 2) / 2);} // Driver Codepublic static void Main(){ int N = 6; Console.Write(nthTerm(N));}} // This code is contributed by ChitraNayal",
"e": 28123,
"s": 27597,
"text": null
},
{
"code": "<?php// PHP program to find// N-th term of the series:// 1, 4, 15, 72, 420... // Function for finding// factorial of Nfunction factorial($N){ $fact = 1; for($i = 1; $i <= $N; $i++) $fact = $fact * $i; // return factorial of N return $fact;} // Function for calculating// Nth term of seriesfunction nthTerm($N){ // return nth term return (factorial($N) * ($N + 2) / 2);} // Driver code$N = 6; // Function Callingecho nthTerm($N); // This code is contributed// by mits?>",
"e": 28629,
"s": 28123,
"text": null
},
{
"code": "<script> // JavaScript program to find N-th term of the series:// 1, 4, 15, 72, 420... // Function to find factorial of Nfunction factorial( N){ let fact = 1; for (let i = 1; i <= N; i++) fact = fact * i; // return factorial of N return fact;} // calculate Nth term of seriesfunction nthTerm(N){ return (factorial(N) * (N + 2) / 2);}// Driver code let N = 6; document.write( nthTerm(N) ); // This code contributed by aashish1995 </script>",
"e": 29114,
"s": 28629,
"text": null
},
{
"code": null,
"e": 29119,
"s": 29114,
"text": "2880"
},
{
"code": null,
"e": 29158,
"s": 29121,
"text": "Another approach :(Using recursion) "
},
{
"code": null,
"e": 29162,
"s": 29158,
"text": "C++"
},
{
"code": null,
"e": 29167,
"s": 29162,
"text": "Java"
},
{
"code": null,
"e": 29175,
"s": 29167,
"text": "Python3"
},
{
"code": null,
"e": 29178,
"s": 29175,
"text": "C#"
},
{
"code": null,
"e": 29182,
"s": 29178,
"text": "PHP"
},
{
"code": null,
"e": 29193,
"s": 29182,
"text": "Javascript"
},
{
"code": "// CPP program to find N-th term of the series:// 1, 4, 15, 72, 420...// Using recursion#include <iostream>using namespace std; // Function to find factorial of N// with recursionint factorial(int N){ // base condition if( N == 0 || N == 1 ) return 1; // use recursion return N * factorial( N - 1 );} // calculate Nth term of seriesint nthTerm(int N){ return (factorial(N) * (N + 2) / 2);} // Driver Functionint main(){ int N = 6; cout << nthTerm(N); return 0;}",
"e": 29696,
"s": 29193,
"text": null
},
{
"code": "// Java program to find N-th// term of the series:// 1, 4, 15, 72, 420import java.util.*;import java.lang.*;import java.io.*; class GFG{ // Function to find factorial of Nstatic int factorial(int N){ // base condition if( N == 0 || N == 1 ) return 1; // use recursion return N * factorial( N - 1 );} // calculate Nth term of seriesstatic int nthTerm(int N){ return (factorial(N) * (N + 2) / 2);} // Driver Codepublic static void main(String args[]){ int N = 6; System.out.println(nthTerm(N));}}",
"e": 30228,
"s": 29696,
"text": null
},
{
"code": "# Python3 program to find# N-th term of the series:# 1, 4, 15, 72, 420...# Using recursion # Function to find factorial# of N with recursiondef factorial(N): # base condition if N == 0 or N == 1: return 1 # use recursion return N * factorial(N - 1) def nthTerm(N): # calculate Nth term of series return (factorial(N) * (N + 2) // 2) # Driver codeN = 6print(nthTerm(N)) # This code is contributed# by Shrikant13",
"e": 30671,
"s": 30228,
"text": null
},
{
"code": "// C# program to find N-th// term of the series:// 1, 4, 15, 72, 420using System; class GFG{ // Function to find factorial of Nstatic int factorial(int N){ // base condition if( N == 0 || N == 1 ) return 1; // use recursion return N * factorial( N - 1 );} // calculate Nth term of seriesstatic int nthTerm(int N){ return (factorial(N) * (N + 2) / 2);} // Driver Codepublic static void Main(){ int N = 6; Console.Write(nthTerm(N));}} // This code is contributed by ChitraNayal",
"e": 31184,
"s": 30671,
"text": null
},
{
"code": "<?php// PHP program to find// N-th term of the series:// 1, 4, 15, 72, 420... // Function to find factorial// of N with recursionfunction factorial($N){ // base condition if($N == 0 or $N == 1) return 1; // use recursion return $N * factorial($N - 1);} // calculate Nth term of seriesfunction nthTerm($N){ return (factorial($N) * ($N + 2) / 2);} // Driver Code$N = 6; echo nthTerm($N); // This code is contributed// by Shashank?>",
"e": 31655,
"s": 31184,
"text": null
},
{
"code": "<script> // Javascript program to find N-th// term of the series:// 1, 4, 15, 72, 420 // Function to find factorial of Nfunction factorial(N){ // Base condition if (N == 0 || N == 1) return 1; // Use recursion return N * factorial(N - 1);} // Calculate Nth term of seriesfunction nthTerm(N){ return(factorial(N) * (N + 2) / 2);} // Driver Codelet N = 6; document.write(nthTerm(N)); // This code is contributed by avanitrachhadiya2155 </script>",
"e": 32135,
"s": 31655,
"text": null
},
{
"code": null,
"e": 32140,
"s": 32135,
"text": "2880"
},
{
"code": null,
"e": 32302,
"s": 32142,
"text": "Time complexity: O(N)Note: Above code wouldn’t not work for large values of N. To find the values for large N, use the concept of Factorial for large numbers. "
},
{
"code": null,
"e": 32310,
"s": 32302,
"text": "ankthon"
},
{
"code": null,
"e": 32326,
"s": 32310,
"text": "tufan_gupta2000"
},
{
"code": null,
"e": 32339,
"s": 32326,
"text": "Mithun Kumar"
},
{
"code": null,
"e": 32345,
"s": 32339,
"text": "ukasp"
},
{
"code": null,
"e": 32355,
"s": 32345,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 32366,
"s": 32355,
"text": "Shashank12"
},
{
"code": null,
"e": 32378,
"s": 32366,
"text": "shrikanth13"
},
{
"code": null,
"e": 32390,
"s": 32378,
"text": "aashish1995"
},
{
"code": null,
"e": 32411,
"s": 32390,
"text": "avanitrachhadiya2155"
},
{
"code": null,
"e": 32421,
"s": 32411,
"text": "factorial"
},
{
"code": null,
"e": 32425,
"s": 32421,
"text": "C++"
},
{
"code": null,
"e": 32443,
"s": 32425,
"text": "Pattern Searching"
},
{
"code": null,
"e": 32462,
"s": 32443,
"text": "School Programming"
},
{
"code": null,
"e": 32480,
"s": 32462,
"text": "Pattern Searching"
},
{
"code": null,
"e": 32490,
"s": 32480,
"text": "factorial"
},
{
"code": null,
"e": 32494,
"s": 32490,
"text": "CPP"
},
{
"code": null,
"e": 32592,
"s": 32494,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32620,
"s": 32592,
"text": "Operator Overloading in C++"
},
{
"code": null,
"e": 32640,
"s": 32620,
"text": "Polymorphism in C++"
},
{
"code": null,
"e": 32673,
"s": 32640,
"text": "Friend class and function in C++"
},
{
"code": null,
"e": 32697,
"s": 32673,
"text": "Sorting a vector in C++"
},
{
"code": null,
"e": 32722,
"s": 32697,
"text": "std::string class in C++"
},
{
"code": null,
"e": 32758,
"s": 32722,
"text": "KMP Algorithm for Pattern Searching"
},
{
"code": null,
"e": 32801,
"s": 32758,
"text": "Rabin-Karp Algorithm for Pattern Searching"
},
{
"code": null,
"e": 32843,
"s": 32801,
"text": "Check if a string is substring of another"
},
{
"code": null,
"e": 32881,
"s": 32843,
"text": "Naive algorithm for Pattern Searching"
}
] |
Simple Multithreaded Download Manager in Python - GeeksforGeeks | 25 Aug, 2016
Introduction
A Download Manager is basically a computer program dedicated to the task of downloading stand alone files from internet. Here, we are going to create a simple Download Manager with the help of threads in Python. Using multi-threading a file can be downloaded in the form of chunks simultaneously from different threads. To implement this, we are going to create simple command line tool which accepts the URL of the file and then downloads it.
PrerequisitesWindows machine with Python installed.
SetupDownload the below mentioned packages from command prompt.
Click package: Click is a Python package for creating beautiful command line interfaces with as little code as necessary. It’s the “Command Line Interface Creation Kit”.pip install clickRequests package: In this tool, we are going to download a file based on the URL(HTTP addresses). Requests is an HTTP Library written in Python which allows you to send HTTP requests. You can add headers, form data, multi-part files, and parameters with simple Python dictionaries and access the response data in the same way.pip install requeststhreading package: To work with threads we need threading package.pip install threading
Click package: Click is a Python package for creating beautiful command line interfaces with as little code as necessary. It’s the “Command Line Interface Creation Kit”.pip install click
pip install click
Requests package: In this tool, we are going to download a file based on the URL(HTTP addresses). Requests is an HTTP Library written in Python which allows you to send HTTP requests. You can add headers, form data, multi-part files, and parameters with simple Python dictionaries and access the response data in the same way.pip install requests
pip install requests
threading package: To work with threads we need threading package.pip install threading
pip install threading
Implementation
(Note: The program has been split into parts to make it easy to understand. Make sure that you are not missing any part of the code while running the code.)
Create new python file in editor
First import the required packages to that you’ll need to write
#N ote: This code will not work on online IDE # Importing the required packagesimport clickimport requestsimport threading # The below code is used for each chunk of file handled# by each thread for downloading the content from specified # location to storagedef Handler(start, end, url, filename): # specify the starting and ending of the file headers = {'Range': 'bytes=%d-%d' % (start, end)} # request the specified part and get into variable r = requests.get(url, headers=headers, stream=True) # open the file and write the content of the html page # into file. with open(filename, "r+b") as fp: fp.seek(start) var = fp.tell() fp.write(r.content)
Now we are going to implement the actual functionality of in the download_file function.
The first step is to decorate the function with click.command() so that we can add command line arguments. We can also give options for respective commands.
For our implementation upon entering command –help we are going to display the options that can be used. In our program there are two options that can be used. One is “number_of_threads” and the other is “name”. By default “number_of_threads” is taken as 4. To change it, we can specify while running the program.
“name” option is given so that we can give our own name to the file that is going to be downloaded. The arguments for the function can be specified using click.argument().
For our program we need to give the URL of the file we want to download.
#Note: This code will not work on online IDE @click.command(help="It downloads the specified file with specified name")@click.option('—number_of_threads',default=4, help="No of Threads")@click.option('--name',type=click.Path(),help="Name of the file with extension")@click.argument('url_of_file',type=click.Path())@click.pass_contextdef download_file(ctx,url_of_file,name,number_of_threads):
The following code goes under the “download_file” function.
In this function we first check for the “name”. If the “name” is not given then use the name from url.
Next step is to connect to the URL and Get the content and size of the content.
r = requests.head(url_of_file)if name: file_name = nameelse: file_name = url_of_file.split('/')[-1]try: file_size = int(r.headers['content-length'])except: print "Invalid URL" return
Create file with size of the content
part = int(file_size) / number_of_threadsfp = open(file_name, "wb")fp.write('\0' * file_size)fp.close()
Now we create Threads and pass the Handler function which has the main functionality :
for i in range(number_of_threads): start = part * i end = start + part # create a Thread with start and end locations t = threading.Thread(target=Handler, kwargs={'start': start, 'end': end, 'url': url_of_file, 'filename': file_name}) t.setDaemon(True) t.start()
Finally join the threads and call the “download_file” function from main
main_thread = threading.current_thread()for t in threading.enumerate(): if t is main_thread: continue t.join()print '%s downloaded' % file_name if __name__ == '__main__': download_file(obj={})
We are done with coding part and now follow the commands showed below to run the .py file.
“python filename.py” –-help
This command shows the “Usage” of the click command tool and options that the tool can accepts.Below is the sample command where we try to download an jpg image file from a URL and also gave a name and number_of_threads.
Finally, we are successfully done with it and this is one of the way to build a simple multithreaded download manager in Python.
This article is contributed by Rahul Bojanapally. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
GBlog
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
DSA Sheet by Love Babbar
How to Start Learning DSA?
Introduction to Recurrent Neural Network
12 pip Commands For Python Developers
A Freshers Guide To Programming
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe | [
{
"code": null,
"e": 26299,
"s": 26271,
"text": "\n25 Aug, 2016"
},
{
"code": null,
"e": 26312,
"s": 26299,
"text": "Introduction"
},
{
"code": null,
"e": 26756,
"s": 26312,
"text": "A Download Manager is basically a computer program dedicated to the task of downloading stand alone files from internet. Here, we are going to create a simple Download Manager with the help of threads in Python. Using multi-threading a file can be downloaded in the form of chunks simultaneously from different threads. To implement this, we are going to create simple command line tool which accepts the URL of the file and then downloads it."
},
{
"code": null,
"e": 26808,
"s": 26756,
"text": "PrerequisitesWindows machine with Python installed."
},
{
"code": null,
"e": 26872,
"s": 26808,
"text": "SetupDownload the below mentioned packages from command prompt."
},
{
"code": null,
"e": 27492,
"s": 26872,
"text": "Click package: Click is a Python package for creating beautiful command line interfaces with as little code as necessary. It’s the “Command Line Interface Creation Kit”.pip install clickRequests package: In this tool, we are going to download a file based on the URL(HTTP addresses). Requests is an HTTP Library written in Python which allows you to send HTTP requests. You can add headers, form data, multi-part files, and parameters with simple Python dictionaries and access the response data in the same way.pip install requeststhreading package: To work with threads we need threading package.pip install threading"
},
{
"code": null,
"e": 27679,
"s": 27492,
"text": "Click package: Click is a Python package for creating beautiful command line interfaces with as little code as necessary. It’s the “Command Line Interface Creation Kit”.pip install click"
},
{
"code": null,
"e": 27697,
"s": 27679,
"text": "pip install click"
},
{
"code": null,
"e": 28044,
"s": 27697,
"text": "Requests package: In this tool, we are going to download a file based on the URL(HTTP addresses). Requests is an HTTP Library written in Python which allows you to send HTTP requests. You can add headers, form data, multi-part files, and parameters with simple Python dictionaries and access the response data in the same way.pip install requests"
},
{
"code": null,
"e": 28065,
"s": 28044,
"text": "pip install requests"
},
{
"code": null,
"e": 28153,
"s": 28065,
"text": "threading package: To work with threads we need threading package.pip install threading"
},
{
"code": null,
"e": 28175,
"s": 28153,
"text": "pip install threading"
},
{
"code": null,
"e": 28190,
"s": 28175,
"text": "Implementation"
},
{
"code": null,
"e": 28347,
"s": 28190,
"text": "(Note: The program has been split into parts to make it easy to understand. Make sure that you are not missing any part of the code while running the code.)"
},
{
"code": null,
"e": 28380,
"s": 28347,
"text": "Create new python file in editor"
},
{
"code": null,
"e": 28444,
"s": 28380,
"text": "First import the required packages to that you’ll need to write"
},
{
"code": "#N ote: This code will not work on online IDE # Importing the required packagesimport clickimport requestsimport threading # The below code is used for each chunk of file handled# by each thread for downloading the content from specified # location to storagedef Handler(start, end, url, filename): # specify the starting and ending of the file headers = {'Range': 'bytes=%d-%d' % (start, end)} # request the specified part and get into variable r = requests.get(url, headers=headers, stream=True) # open the file and write the content of the html page # into file. with open(filename, \"r+b\") as fp: fp.seek(start) var = fp.tell() fp.write(r.content)",
"e": 29159,
"s": 28444,
"text": null
},
{
"code": null,
"e": 29248,
"s": 29159,
"text": "Now we are going to implement the actual functionality of in the download_file function."
},
{
"code": null,
"e": 29405,
"s": 29248,
"text": "The first step is to decorate the function with click.command() so that we can add command line arguments. We can also give options for respective commands."
},
{
"code": null,
"e": 29719,
"s": 29405,
"text": "For our implementation upon entering command –help we are going to display the options that can be used. In our program there are two options that can be used. One is “number_of_threads” and the other is “name”. By default “number_of_threads” is taken as 4. To change it, we can specify while running the program."
},
{
"code": null,
"e": 29892,
"s": 29719,
"text": "“name” option is given so that we can give our own name to the file that is going to be downloaded. The arguments for the function can be specified using click.argument()."
},
{
"code": null,
"e": 29965,
"s": 29892,
"text": "For our program we need to give the URL of the file we want to download."
},
{
"code": "#Note: This code will not work on online IDE @click.command(help=\"It downloads the specified file with specified name\")@click.option('—number_of_threads',default=4, help=\"No of Threads\")@click.option('--name',type=click.Path(),help=\"Name of the file with extension\")@click.argument('url_of_file',type=click.Path())@click.pass_contextdef download_file(ctx,url_of_file,name,number_of_threads):",
"e": 30358,
"s": 29965,
"text": null
},
{
"code": null,
"e": 30418,
"s": 30358,
"text": "The following code goes under the “download_file” function."
},
{
"code": null,
"e": 30521,
"s": 30418,
"text": "In this function we first check for the “name”. If the “name” is not given then use the name from url."
},
{
"code": null,
"e": 30601,
"s": 30521,
"text": "Next step is to connect to the URL and Get the content and size of the content."
},
{
"code": "r = requests.head(url_of_file)if name: file_name = nameelse: file_name = url_of_file.split('/')[-1]try: file_size = int(r.headers['content-length'])except: print \"Invalid URL\" return",
"e": 30799,
"s": 30601,
"text": null
},
{
"code": null,
"e": 30836,
"s": 30799,
"text": "Create file with size of the content"
},
{
"code": "part = int(file_size) / number_of_threadsfp = open(file_name, \"wb\")fp.write('\\0' * file_size)fp.close()",
"e": 30940,
"s": 30836,
"text": null
},
{
"code": null,
"e": 31027,
"s": 30940,
"text": "Now we create Threads and pass the Handler function which has the main functionality :"
},
{
"code": "for i in range(number_of_threads): start = part * i end = start + part # create a Thread with start and end locations t = threading.Thread(target=Handler, kwargs={'start': start, 'end': end, 'url': url_of_file, 'filename': file_name}) t.setDaemon(True) t.start()",
"e": 31348,
"s": 31027,
"text": null
},
{
"code": null,
"e": 31421,
"s": 31348,
"text": "Finally join the threads and call the “download_file” function from main"
},
{
"code": "main_thread = threading.current_thread()for t in threading.enumerate(): if t is main_thread: continue t.join()print '%s downloaded' % file_name if __name__ == '__main__': download_file(obj={})",
"e": 31631,
"s": 31421,
"text": null
},
{
"code": null,
"e": 31722,
"s": 31631,
"text": "We are done with coding part and now follow the commands showed below to run the .py file."
},
{
"code": null,
"e": 31750,
"s": 31722,
"text": "“python filename.py” –-help"
},
{
"code": null,
"e": 31971,
"s": 31750,
"text": "This command shows the “Usage” of the click command tool and options that the tool can accepts.Below is the sample command where we try to download an jpg image file from a URL and also gave a name and number_of_threads."
},
{
"code": null,
"e": 32100,
"s": 31971,
"text": "Finally, we are successfully done with it and this is one of the way to build a simple multithreaded download manager in Python."
},
{
"code": null,
"e": 32405,
"s": 32100,
"text": "This article is contributed by Rahul Bojanapally. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 32530,
"s": 32405,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 32536,
"s": 32530,
"text": "GBlog"
},
{
"code": null,
"e": 32543,
"s": 32536,
"text": "Python"
},
{
"code": null,
"e": 32641,
"s": 32543,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32666,
"s": 32641,
"text": "DSA Sheet by Love Babbar"
},
{
"code": null,
"e": 32693,
"s": 32666,
"text": "How to Start Learning DSA?"
},
{
"code": null,
"e": 32734,
"s": 32693,
"text": "Introduction to Recurrent Neural Network"
},
{
"code": null,
"e": 32772,
"s": 32734,
"text": "12 pip Commands For Python Developers"
},
{
"code": null,
"e": 32804,
"s": 32772,
"text": "A Freshers Guide To Programming"
},
{
"code": null,
"e": 32832,
"s": 32804,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 32882,
"s": 32832,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 32904,
"s": 32882,
"text": "Python map() function"
}
] |
How to set the overflow property to scroll in CSS ? - GeeksforGeeks | 03 Jun, 2021
In this article, we will see how to set the overflow property to scroll in CSS. The overflow property is used to control the big content. It tells what to do when an element’s content is too big to fit in the specified area. When the overflow property is set to scroll, the overflow is clipped, but a scrollbar is added to see the rest.
Example 1:
HTML
<!DOCTYPE html><html> <head> <style> p { width: 120px; height: 100px; border: 1px solid; overflow: scroll; color: green; } </style></head> <body> <h2>GEEKSFORGEEKS</h2> <p> The CSS overflow controls big content. It tells whether to clip content or to add scroll bars. </p></body> </html>
Output:
Example 2: In this example, we have to use the overflow-x property to scroll. The overflow-x property is used when the content is overflown at the left and right edges.
HTML
<!DOCTYPE html><html> <head> <style> p { color: green; width: 40px; border: 1px solid; overflow-x: scroll; } </style></head> <body> <h2>GEEKSFORGEEKS</h2> <p> The CSS overflow controls big content. It tells whether to clip content or to add scroll bars to show rest of the content. </p></body> </html>
Output:
Example 3: In this example, we have used the overflow-y property to scroll. The overflow-y property is used when the content overflows at the top and bottom edges
HTML
<!DOCTYPE html><html> <head> <style> p { color: green; height: 50px; width: 200px; border: 1px solid; overflow-y: scroll; } </style></head> <body> <h2>GEEKSFORGEEKS</h2> <p> The CSS overflow controls big content. It tells whether to clip content or to add scroll bars to show rest of the content. </p></body> </html>
Output:
CSS-Properties
CSS-Questions
Picked
CSS
Web Technologies
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?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
Difference between var, let and const keywords in JavaScript | [
{
"code": null,
"e": 26621,
"s": 26593,
"text": "\n03 Jun, 2021"
},
{
"code": null,
"e": 26958,
"s": 26621,
"text": "In this article, we will see how to set the overflow property to scroll in CSS. The overflow property is used to control the big content. It tells what to do when an element’s content is too big to fit in the specified area. When the overflow property is set to scroll, the overflow is clipped, but a scrollbar is added to see the rest."
},
{
"code": null,
"e": 26970,
"s": 26958,
"text": "Example 1: "
},
{
"code": null,
"e": 26975,
"s": 26970,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <style> p { width: 120px; height: 100px; border: 1px solid; overflow: scroll; color: green; } </style></head> <body> <h2>GEEKSFORGEEKS</h2> <p> The CSS overflow controls big content. It tells whether to clip content or to add scroll bars. </p></body> </html>",
"e": 27373,
"s": 26975,
"text": null
},
{
"code": null,
"e": 27382,
"s": 27373,
"text": "Output: "
},
{
"code": null,
"e": 27553,
"s": 27384,
"text": "Example 2: In this example, we have to use the overflow-x property to scroll. The overflow-x property is used when the content is overflown at the left and right edges."
},
{
"code": null,
"e": 27558,
"s": 27553,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <style> p { color: green; width: 40px; border: 1px solid; overflow-x: scroll; } </style></head> <body> <h2>GEEKSFORGEEKS</h2> <p> The CSS overflow controls big content. It tells whether to clip content or to add scroll bars to show rest of the content. </p></body> </html>",
"e": 27969,
"s": 27558,
"text": null
},
{
"code": null,
"e": 27978,
"s": 27969,
"text": "Output: "
},
{
"code": null,
"e": 28141,
"s": 27978,
"text": "Example 3: In this example, we have used the overflow-y property to scroll. The overflow-y property is used when the content overflows at the top and bottom edges"
},
{
"code": null,
"e": 28146,
"s": 28141,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <style> p { color: green; height: 50px; width: 200px; border: 1px solid; overflow-y: scroll; } </style></head> <body> <h2>GEEKSFORGEEKS</h2> <p> The CSS overflow controls big content. It tells whether to clip content or to add scroll bars to show rest of the content. </p></body> </html>",
"e": 28583,
"s": 28146,
"text": null
},
{
"code": null,
"e": 28592,
"s": 28583,
"text": "Output: "
},
{
"code": null,
"e": 28607,
"s": 28592,
"text": "CSS-Properties"
},
{
"code": null,
"e": 28621,
"s": 28607,
"text": "CSS-Questions"
},
{
"code": null,
"e": 28628,
"s": 28621,
"text": "Picked"
},
{
"code": null,
"e": 28632,
"s": 28628,
"text": "CSS"
},
{
"code": null,
"e": 28649,
"s": 28632,
"text": "Web Technologies"
},
{
"code": null,
"e": 28747,
"s": 28649,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28784,
"s": 28747,
"text": "Design a web page using HTML and CSS"
},
{
"code": null,
"e": 28823,
"s": 28784,
"text": "How to set space between the flexbox ?"
},
{
"code": null,
"e": 28852,
"s": 28823,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 28894,
"s": 28852,
"text": "Search Bar using HTML, CSS and JavaScript"
},
{
"code": null,
"e": 28929,
"s": 28894,
"text": "How to style a checkbox using CSS?"
},
{
"code": null,
"e": 28969,
"s": 28929,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 29002,
"s": 28969,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 29047,
"s": 29002,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 29090,
"s": 29047,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
How to create a Triangle Correlation Heatmap in seaborn - Python? - GeeksforGeeks | 29 Jul, 2021
Seaborn is a Python library that is based on matplotlib and is used for data visualization. It provides a medium to present data in a statistical graph format as an informative and attractive medium to impart some information. A heatmap is one of the components supported by seaborn where variation in related data is portrayed using a color palette. This article centrally focuses on a correlation heatmap and how seaborn in combination with pandas and matplotlib can be used to generate one for a dataframe.
Like any another Python library, seaborn can be easily installed using pip:
pip install seaborn
This library is a part of Anaconda distribution and usually works just by import if your IDE is supported by Anaconda, but it can be installed too by the following command:
conda install seaborn
A correlation heatmap is a heatmap that shows a 2D correlation matrix between two discrete dimensions, using colored cells to represent data from usually a monochromatic scale. The values of the first dimension appear as the rows of the table while of the second dimension as a column. The color of the cell is proportional to the number of measurements that match the dimensional value. This makes correlation heatmaps ideal for data analysis since it makes patterns easily readable and highlights the differences and variation in the same data. A correlation heatmap, like a regular heatmap is assisted by a colorbar making data easily readable and comprehensible.
A correlation heatmap is a rectangular representation of data and it repeats the same data description twice because the categories are repeated on both axis for computing analysis. Hence, the same result is obtained twice. A correlation heatmap that presents data only once without repetition that is categories are correlated only once is known as a triangle correlation heatmap. Since data is symmetric across the diagonal from left-top to right bottom the idea of obtaining a triangle correlation heatmap is to remove data above it so that it is depicted only once. The elements on the diagonal are the parts where categories of the same type correlate.
For plotting heatmap method of the seaborn module will be used. Along with that mask, argument will be passed. Mask is a heatmap attribute that takes a dataframe or a boolean array as an argument and displays only those positions which are marked as False or where masking is provided to be False.
Syntax:
heatmap(data, vmin, vmax, center, cmap,............................................................)
Except for data all other attributes are optional and data obviously will be the data to be plotted. The data here has to be passed with corr() method to generate a correlation heatmap. Also, corr() itself eliminates columns which will be of no use while generating a correlation heatmap and selects those which can be used.
For masking, here an array using NumPy is being generated as shown below:
np.triu(np.ones_like())
first, the ones_like() method of NumPy module will generate an array of size same as that of our data to be plotted containing only number one. Then, triu() method of the NumPy module will turn the matrix so formed into an upper triangular matrix, i.e. elements above the diagonal will be 1 and below, and on it will be 0. Masking will be applied to places where 1(True) is set.
The following steps show how a triangle correlation heatmap can be produced:
Import all required modules first
Import the file where your data is stored
Plot a heatmap
Mask the part of the heatmap that shouldn’t be displayed
Display it using matplotlib
Example 1:
For the example given below, here a dataset downloaded from kaggle.com is being used. The plot shows data related to bestseller novels of amazon.
Dataset used – Bestsellers
Python3
# import modulesimport matplotlib.pyplot as mpimport pandas as pdimport seaborn as sbimport numpy as np # import file with datadata = pd.read_csv("C:\\Users\\Vanshi\\Desktop\\gfg\\bestsellers.csv") # creating maskmask = np.triu(np.ones_like(data.corr())) # plotting a triangle correlation heatmapdataplot = sb.heatmap(data.corr(), cmap="YlGnBu", annot=True, mask=mask) # displaying heatmapmp.show()
Output:
Example 2:
The dataset used in this example is an exoplanet space research dataset compiled by nasa.
Dataset used – cumulative
Python3
# import modulesimport matplotlib.pyplot as mpimport pandas as pdimport seaborn as sbimport numpy as np # import file with datadata = pd.read_csv("C:\\Users\\Vanshi\\Desktop\\gfg\\cumulative.csv") # applying maskmask = np.triu(np.ones_like(data.corr())) # plotting a triangle correlation heatmapdataplot = sb.heatmap(data.corr(), mask=mask) # displaying heatmapmp.show()
Output:
simranarora5sos
Python-Seaborn
Technical Scripter 2020
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
Python Dictionary
Taking input in Python
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe | [
{
"code": null,
"e": 27981,
"s": 27953,
"text": "\n29 Jul, 2021"
},
{
"code": null,
"e": 28491,
"s": 27981,
"text": "Seaborn is a Python library that is based on matplotlib and is used for data visualization. It provides a medium to present data in a statistical graph format as an informative and attractive medium to impart some information. A heatmap is one of the components supported by seaborn where variation in related data is portrayed using a color palette. This article centrally focuses on a correlation heatmap and how seaborn in combination with pandas and matplotlib can be used to generate one for a dataframe."
},
{
"code": null,
"e": 28567,
"s": 28491,
"text": "Like any another Python library, seaborn can be easily installed using pip:"
},
{
"code": null,
"e": 28587,
"s": 28567,
"text": "pip install seaborn"
},
{
"code": null,
"e": 28760,
"s": 28587,
"text": "This library is a part of Anaconda distribution and usually works just by import if your IDE is supported by Anaconda, but it can be installed too by the following command:"
},
{
"code": null,
"e": 28782,
"s": 28760,
"text": "conda install seaborn"
},
{
"code": null,
"e": 29450,
"s": 28782,
"text": "A correlation heatmap is a heatmap that shows a 2D correlation matrix between two discrete dimensions, using colored cells to represent data from usually a monochromatic scale. The values of the first dimension appear as the rows of the table while of the second dimension as a column. The color of the cell is proportional to the number of measurements that match the dimensional value. This makes correlation heatmaps ideal for data analysis since it makes patterns easily readable and highlights the differences and variation in the same data. A correlation heatmap, like a regular heatmap is assisted by a colorbar making data easily readable and comprehensible. "
},
{
"code": null,
"e": 30108,
"s": 29450,
"text": "A correlation heatmap is a rectangular representation of data and it repeats the same data description twice because the categories are repeated on both axis for computing analysis. Hence, the same result is obtained twice. A correlation heatmap that presents data only once without repetition that is categories are correlated only once is known as a triangle correlation heatmap. Since data is symmetric across the diagonal from left-top to right bottom the idea of obtaining a triangle correlation heatmap is to remove data above it so that it is depicted only once. The elements on the diagonal are the parts where categories of the same type correlate."
},
{
"code": null,
"e": 30407,
"s": 30108,
"text": "For plotting heatmap method of the seaborn module will be used. Along with that mask, argument will be passed. Mask is a heatmap attribute that takes a dataframe or a boolean array as an argument and displays only those positions which are marked as False or where masking is provided to be False. "
},
{
"code": null,
"e": 30415,
"s": 30407,
"text": "Syntax:"
},
{
"code": null,
"e": 30516,
"s": 30415,
"text": "heatmap(data, vmin, vmax, center, cmap,............................................................)"
},
{
"code": null,
"e": 30841,
"s": 30516,
"text": "Except for data all other attributes are optional and data obviously will be the data to be plotted. The data here has to be passed with corr() method to generate a correlation heatmap. Also, corr() itself eliminates columns which will be of no use while generating a correlation heatmap and selects those which can be used."
},
{
"code": null,
"e": 30916,
"s": 30841,
"text": "For masking, here an array using NumPy is being generated as shown below: "
},
{
"code": null,
"e": 30940,
"s": 30916,
"text": "np.triu(np.ones_like())"
},
{
"code": null,
"e": 31319,
"s": 30940,
"text": "first, the ones_like() method of NumPy module will generate an array of size same as that of our data to be plotted containing only number one. Then, triu() method of the NumPy module will turn the matrix so formed into an upper triangular matrix, i.e. elements above the diagonal will be 1 and below, and on it will be 0. Masking will be applied to places where 1(True) is set."
},
{
"code": null,
"e": 31396,
"s": 31319,
"text": "The following steps show how a triangle correlation heatmap can be produced:"
},
{
"code": null,
"e": 31430,
"s": 31396,
"text": "Import all required modules first"
},
{
"code": null,
"e": 31472,
"s": 31430,
"text": "Import the file where your data is stored"
},
{
"code": null,
"e": 31487,
"s": 31472,
"text": "Plot a heatmap"
},
{
"code": null,
"e": 31544,
"s": 31487,
"text": "Mask the part of the heatmap that shouldn’t be displayed"
},
{
"code": null,
"e": 31572,
"s": 31544,
"text": "Display it using matplotlib"
},
{
"code": null,
"e": 31583,
"s": 31572,
"text": "Example 1:"
},
{
"code": null,
"e": 31729,
"s": 31583,
"text": "For the example given below, here a dataset downloaded from kaggle.com is being used. The plot shows data related to bestseller novels of amazon."
},
{
"code": null,
"e": 31756,
"s": 31729,
"text": "Dataset used – Bestsellers"
},
{
"code": null,
"e": 31764,
"s": 31756,
"text": "Python3"
},
{
"code": "# import modulesimport matplotlib.pyplot as mpimport pandas as pdimport seaborn as sbimport numpy as np # import file with datadata = pd.read_csv(\"C:\\\\Users\\\\Vanshi\\\\Desktop\\\\gfg\\\\bestsellers.csv\") # creating maskmask = np.triu(np.ones_like(data.corr())) # plotting a triangle correlation heatmapdataplot = sb.heatmap(data.corr(), cmap=\"YlGnBu\", annot=True, mask=mask) # displaying heatmapmp.show()",
"e": 32163,
"s": 31764,
"text": null
},
{
"code": null,
"e": 32171,
"s": 32163,
"text": "Output:"
},
{
"code": null,
"e": 32182,
"s": 32171,
"text": "Example 2:"
},
{
"code": null,
"e": 32272,
"s": 32182,
"text": "The dataset used in this example is an exoplanet space research dataset compiled by nasa."
},
{
"code": null,
"e": 32298,
"s": 32272,
"text": "Dataset used – cumulative"
},
{
"code": null,
"e": 32306,
"s": 32298,
"text": "Python3"
},
{
"code": "# import modulesimport matplotlib.pyplot as mpimport pandas as pdimport seaborn as sbimport numpy as np # import file with datadata = pd.read_csv(\"C:\\\\Users\\\\Vanshi\\\\Desktop\\\\gfg\\\\cumulative.csv\") # applying maskmask = np.triu(np.ones_like(data.corr())) # plotting a triangle correlation heatmapdataplot = sb.heatmap(data.corr(), mask=mask) # displaying heatmapmp.show()",
"e": 32677,
"s": 32306,
"text": null
},
{
"code": null,
"e": 32685,
"s": 32677,
"text": "Output:"
},
{
"code": null,
"e": 32701,
"s": 32685,
"text": "simranarora5sos"
},
{
"code": null,
"e": 32716,
"s": 32701,
"text": "Python-Seaborn"
},
{
"code": null,
"e": 32740,
"s": 32716,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 32747,
"s": 32740,
"text": "Python"
},
{
"code": null,
"e": 32766,
"s": 32747,
"text": "Technical Scripter"
},
{
"code": null,
"e": 32864,
"s": 32766,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32892,
"s": 32864,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 32942,
"s": 32892,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 32964,
"s": 32942,
"text": "Python map() function"
},
{
"code": null,
"e": 33008,
"s": 32964,
"text": "How to get column names in Pandas dataframe"
},
{
"code": null,
"e": 33026,
"s": 33008,
"text": "Python Dictionary"
},
{
"code": null,
"e": 33049,
"s": 33026,
"text": "Taking input in Python"
},
{
"code": null,
"e": 33084,
"s": 33049,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 33116,
"s": 33084,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 33138,
"s": 33116,
"text": "Enumerate() in Python"
}
] |
How to get the file name from full path using JavaScript ? - GeeksforGeeks | 10 Jun, 2019
Given a file name which contains the file path also, the task is to get the file name from full path. There are a few methods to solve this problem which are listed below:
replace() method: This method searches a string for a defined value, or a regular expression, and returns a new string with the replaced defined value.Syntax:string.replace(searchVal, newvalue)Parameters: This method accepts two parameters as mentioned above and described below:searchVal: This parameter is required. It specifies the value, or regular expression, that is going to replace by the new value.newvalue: This parameter is required. It specifies the value to be replaced with the search value.Return value: It returns a new string where the defines value(s) has been replaced by the new value.
Syntax:
string.replace(searchVal, newvalue)
Parameters: This method accepts two parameters as mentioned above and described below:
searchVal: This parameter is required. It specifies the value, or regular expression, that is going to replace by the new value.
newvalue: This parameter is required. It specifies the value to be replaced with the search value.
Return value: It returns a new string where the defines value(s) has been replaced by the new value.
split() method: This method is used to split a string into an array of substrings, and returns the new array.Syntax:string.split(separator, limit)Parameters: This method accepts two parameters as mentioned above and described below:separator: This parameter is optional. It specifies the character, or the regular expression, to use for splitting the string. If not used, the whole string will be returned (an array with only one item).limit: This parameter is optional. It specifies the integer that specifies the number of splits, items beyond the split limit will be excluded from the array.Return value: It returns a new Array, having the splitted items.
Syntax:
string.split(separator, limit)
Parameters: This method accepts two parameters as mentioned above and described below:
separator: This parameter is optional. It specifies the character, or the regular expression, to use for splitting the string. If not used, the whole string will be returned (an array with only one item).
limit: This parameter is optional. It specifies the integer that specifies the number of splits, items beyond the split limit will be excluded from the array.
Return value: It returns a new Array, having the splitted items.
JavaScript Array pop() Method: This method deletes the last element of an array, and returns deleted element.Syntax:array.pop()Return value: It returns any type, representing the deleted array item. This item can be a string, number, array, boolean, or any other object types which are allowed in an array.
Syntax:
array.pop()
Return value: It returns any type, representing the deleted array item. This item can be a string, number, array, boolean, or any other object types which are allowed in an array.
Example 1: This example gets the file name with the help of Regular Expression by using replace() method.
<!DOCTYPE HTML> <html> <head> <title> How to get the file name from a full path using JavaScript </title> </head> <body style = "text-align:center;"> <h1 style = "color:green;" > GeeksForGeeks </h1> <p id = "GFG_UP" style = "font-size: 15px; font-weight: bold;"> </p> <button onclick = "gfg_Run()"> get File Name </button> <p id = "GFG_DOWN" style = "color:green; font-size: 20px; font-weight: bold;"> </p> <script> var el_up = document.getElementById("GFG_UP"); var el_down = document.getElementById("GFG_DOWN"); var path = "Path = " + "C:\\Documents\\folder\\img\\GFG.jpg"; el_up.innerHTML = path; function gfg_Run() { el_down.innerHTML = path.replace(/^.*[\\\/]/, ''); } </script> </body> </html>
Output:
Before clicking on the button:
After clicking on the button:
Example 2: This example gets the file name with the help of repeated split() and pop() method.
<!DOCTYPE HTML> <html> <head> <title> How to get the file name from a full path using JavaScript </title> </head> <body style = "text-align:center;"> <h1 style = "color:green;" > GeeksForGeeks </h1> <p id = "GFG_UP" style = "font-size: 15px; font-weight: bold;"> </p> <button onclick = "gfg_Run()"> get File Name </button> <p id = "GFG_DOWN" style = "color:green; font-size: 20px; font-weight: bold;"> </p> <script> var el_up = document.getElementById("GFG_UP"); var el_down = document.getElementById("GFG_DOWN"); var path = "Path = " + "C:\\Documents\\folder\\img\\GFG.jpg"; el_up.innerHTML = path; function gfg_Run() { el_down.innerHTML = path.split('\\').pop().split('/').pop(); } </script> </body> </html>
Output:
Before clicking on the button:
After clicking on the button:
JavaScript-Misc
JavaScript
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to append HTML code to a div using JavaScript ?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS? | [
{
"code": null,
"e": 25817,
"s": 25789,
"text": "\n10 Jun, 2019"
},
{
"code": null,
"e": 25989,
"s": 25817,
"text": "Given a file name which contains the file path also, the task is to get the file name from full path. There are a few methods to solve this problem which are listed below:"
},
{
"code": null,
"e": 26595,
"s": 25989,
"text": "replace() method: This method searches a string for a defined value, or a regular expression, and returns a new string with the replaced defined value.Syntax:string.replace(searchVal, newvalue)Parameters: This method accepts two parameters as mentioned above and described below:searchVal: This parameter is required. It specifies the value, or regular expression, that is going to replace by the new value.newvalue: This parameter is required. It specifies the value to be replaced with the search value.Return value: It returns a new string where the defines value(s) has been replaced by the new value."
},
{
"code": null,
"e": 26603,
"s": 26595,
"text": "Syntax:"
},
{
"code": null,
"e": 26639,
"s": 26603,
"text": "string.replace(searchVal, newvalue)"
},
{
"code": null,
"e": 26726,
"s": 26639,
"text": "Parameters: This method accepts two parameters as mentioned above and described below:"
},
{
"code": null,
"e": 26855,
"s": 26726,
"text": "searchVal: This parameter is required. It specifies the value, or regular expression, that is going to replace by the new value."
},
{
"code": null,
"e": 26954,
"s": 26855,
"text": "newvalue: This parameter is required. It specifies the value to be replaced with the search value."
},
{
"code": null,
"e": 27055,
"s": 26954,
"text": "Return value: It returns a new string where the defines value(s) has been replaced by the new value."
},
{
"code": null,
"e": 27714,
"s": 27055,
"text": "split() method: This method is used to split a string into an array of substrings, and returns the new array.Syntax:string.split(separator, limit)Parameters: This method accepts two parameters as mentioned above and described below:separator: This parameter is optional. It specifies the character, or the regular expression, to use for splitting the string. If not used, the whole string will be returned (an array with only one item).limit: This parameter is optional. It specifies the integer that specifies the number of splits, items beyond the split limit will be excluded from the array.Return value: It returns a new Array, having the splitted items."
},
{
"code": null,
"e": 27722,
"s": 27714,
"text": "Syntax:"
},
{
"code": null,
"e": 27753,
"s": 27722,
"text": "string.split(separator, limit)"
},
{
"code": null,
"e": 27840,
"s": 27753,
"text": "Parameters: This method accepts two parameters as mentioned above and described below:"
},
{
"code": null,
"e": 28045,
"s": 27840,
"text": "separator: This parameter is optional. It specifies the character, or the regular expression, to use for splitting the string. If not used, the whole string will be returned (an array with only one item)."
},
{
"code": null,
"e": 28204,
"s": 28045,
"text": "limit: This parameter is optional. It specifies the integer that specifies the number of splits, items beyond the split limit will be excluded from the array."
},
{
"code": null,
"e": 28269,
"s": 28204,
"text": "Return value: It returns a new Array, having the splitted items."
},
{
"code": null,
"e": 28576,
"s": 28269,
"text": "JavaScript Array pop() Method: This method deletes the last element of an array, and returns deleted element.Syntax:array.pop()Return value: It returns any type, representing the deleted array item. This item can be a string, number, array, boolean, or any other object types which are allowed in an array."
},
{
"code": null,
"e": 28584,
"s": 28576,
"text": "Syntax:"
},
{
"code": null,
"e": 28596,
"s": 28584,
"text": "array.pop()"
},
{
"code": null,
"e": 28776,
"s": 28596,
"text": "Return value: It returns any type, representing the deleted array item. This item can be a string, number, array, boolean, or any other object types which are allowed in an array."
},
{
"code": null,
"e": 28882,
"s": 28776,
"text": "Example 1: This example gets the file name with the help of Regular Expression by using replace() method."
},
{
"code": "<!DOCTYPE HTML> <html> <head> <title> How to get the file name from a full path using JavaScript </title> </head> <body style = \"text-align:center;\"> <h1 style = \"color:green;\" > GeeksForGeeks </h1> <p id = \"GFG_UP\" style = \"font-size: 15px; font-weight: bold;\"> </p> <button onclick = \"gfg_Run()\"> get File Name </button> <p id = \"GFG_DOWN\" style = \"color:green; font-size: 20px; font-weight: bold;\"> </p> <script> var el_up = document.getElementById(\"GFG_UP\"); var el_down = document.getElementById(\"GFG_DOWN\"); var path = \"Path = \" + \"C:\\\\Documents\\\\folder\\\\img\\\\GFG.jpg\"; el_up.innerHTML = path; function gfg_Run() { el_down.innerHTML = path.replace(/^.*[\\\\\\/]/, ''); } </script> </body> </html>",
"e": 29943,
"s": 28882,
"text": null
},
{
"code": null,
"e": 29951,
"s": 29943,
"text": "Output:"
},
{
"code": null,
"e": 29982,
"s": 29951,
"text": "Before clicking on the button:"
},
{
"code": null,
"e": 30012,
"s": 29982,
"text": "After clicking on the button:"
},
{
"code": null,
"e": 30107,
"s": 30012,
"text": "Example 2: This example gets the file name with the help of repeated split() and pop() method."
},
{
"code": "<!DOCTYPE HTML> <html> <head> <title> How to get the file name from a full path using JavaScript </title> </head> <body style = \"text-align:center;\"> <h1 style = \"color:green;\" > GeeksForGeeks </h1> <p id = \"GFG_UP\" style = \"font-size: 15px; font-weight: bold;\"> </p> <button onclick = \"gfg_Run()\"> get File Name </button> <p id = \"GFG_DOWN\" style = \"color:green; font-size: 20px; font-weight: bold;\"> </p> <script> var el_up = document.getElementById(\"GFG_UP\"); var el_down = document.getElementById(\"GFG_DOWN\"); var path = \"Path = \" + \"C:\\\\Documents\\\\folder\\\\img\\\\GFG.jpg\"; el_up.innerHTML = path; function gfg_Run() { el_down.innerHTML = path.split('\\\\').pop().split('/').pop(); } </script> </body> </html> ",
"e": 31204,
"s": 30107,
"text": null
},
{
"code": null,
"e": 31212,
"s": 31204,
"text": "Output:"
},
{
"code": null,
"e": 31243,
"s": 31212,
"text": "Before clicking on the button:"
},
{
"code": null,
"e": 31273,
"s": 31243,
"text": "After clicking on the button:"
},
{
"code": null,
"e": 31289,
"s": 31273,
"text": "JavaScript-Misc"
},
{
"code": null,
"e": 31300,
"s": 31289,
"text": "JavaScript"
},
{
"code": null,
"e": 31317,
"s": 31300,
"text": "Web Technologies"
},
{
"code": null,
"e": 31344,
"s": 31317,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 31442,
"s": 31344,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31482,
"s": 31442,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 31527,
"s": 31482,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 31588,
"s": 31527,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 31660,
"s": 31588,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 31712,
"s": 31660,
"text": "How to append HTML code to a div using JavaScript ?"
},
{
"code": null,
"e": 31752,
"s": 31712,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 31785,
"s": 31752,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 31830,
"s": 31785,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 31873,
"s": 31830,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
Java Program to Extract Content From a XML Document - GeeksforGeeks | 02 Feb, 2022
An XML file contains data between the tags so it is complex to read the data when compared to other file formats like docx and txt. There are two types of parsers which parse an XML file:
Object-Based (e.g. D.O.M)
Event-Based (e.g. SAX, StAX)
In this article, we will discuss how to parse XML using Java DOM parser and Java SAX parser.
Java DOM Parser: DOM stands for Document Object Model. The DOM API provides the classes to read and write an XML file. DOM reads an entire document. It is useful when reading small to medium size XML files. It is a tree-based parser and a little slow when compared to SAX and occupies more space when loaded into memory. We can insert and delete nodes using the DOM API.
We have to follow the below process to extract data from an XML file in Java.
Instantiate XML file:
Get root node: We can use getDocumentElement() to get the root node and the element of the XML file.
Get all nodes: On using getElementByTagName() Returns a NodeList of all the Elements in document order with a given tag name and are contained in the document.
Get Node by text value: We can use getElementByTextValue() method in order to search for a node by its value.
Get Node by attribute value: we can use the getElementByTagName() method along with getAttribute() method.
Let’s now see an example on extracting data from XML using Java DOM Parser.
Create a .xml file, in this case, we have created Gfg.xml
XML
<?xml version="1.0"?> <class> <geek> <id>1</id> <username>geek1</username> <EnrolledCourse>D.S.A</EnrolledCourse> <mode>online self paced</mode> <duration>Lifetime</duration> </geek> <geek> <id>2</id> <username>geek2</username> <EnrolledCourse>System Design</EnrolledCourse> <mode>online live course</mode> <duration>10 Lectures</duration> </geek> <geek> <id>3</id> <username>geek3</username> <EnrolledCourse>Competitive Programming</EnrolledCourse> <mode>online live course</mode> <duration>8 weeks</duration> </geek> <geek> <id>4</id> <username>geek4</username> <EnrolledCourse>Complete Interview Preparation</EnrolledCourse> <mode>online self paced</mode> <duration>Lifetime</duration> </geek> </class>
Now create a java file for Java DOM parser. In this case GfgXmlExtractor.java
Java
import javax.xml.parsers.DocumentBuilderFactory;import javax.xml.parsers.DocumentBuilder;import org.w3c.dom.Document;import org.w3c.dom.NodeList;import org.w3c.dom.Node;import org.w3c.dom.Element;import java.io.File;public class GfgXmlExtractor { public static void main(String argv[]) { try { // creating a constructor of file class and // parsing an XML file File file = new File( "F:\\geeksforgeeks_contributions\\gfg.xml"); // Defines a factory API that enables // applications to obtain a parser that produces // DOM object trees from XML documents. DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); // we are creating an object of builder to parse // the xml file. DocumentBuilder db = dbf.newDocumentBuilder(); Document doc = db.parse(file); /*here normalize method Puts all Text nodes in the full depth of the sub-tree underneath this Node, including attribute nodes, into a "normal" form where only structure separates Text nodes, i.e., there are neither adjacent Text nodes nor empty Text nodes. */ doc.getDocumentElement().normalize(); System.out.println( "Root element: " + doc.getDocumentElement().getNodeName()); // Here nodeList contains all the nodes with // name geek. NodeList nodeList = doc.getElementsByTagName("geek"); // Iterate through all the nodes in NodeList // using for loop. for (int i = 0; i < nodeList.getLength(); ++i) { Node node = nodeList.item(i); System.out.println("\nNode Name :" + node.getNodeName()); if (node.getNodeType() == Node.ELEMENT_NODE) { Element tElement = (Element)node; System.out.println( "User id: " + tElement .getElementsByTagName("id") .item(0) .getTextContent()); System.out.println( "User Name: " + tElement .getElementsByTagName( "username") .item(0) .getTextContent()); System.out.println( "Enrolled Course: " + tElement .getElementsByTagName( "EnrolledCourse") .item(0) .getTextContent()); System.out.println( "Mode: " + tElement .getElementsByTagName("mode") .item(0) .getTextContent()); System.out.println( "Duration: " + tElement .getElementsByTagName( "duration") .item(0) .getTextContent()); } } } // This exception block catches all the exception // raised. // For example if we try to access a element by a // TagName that is not there in the XML etc. catch (Exception e) { System.out.println(e); } }}
Output
Root element: class
Node Name :geek
User id: 1
User Name: geek1
Enrolled Course: D.S.A
Mode: online self paced
Duration: Lifetime
Node Name :geek
User id: 2
User Name: geek2
Enrolled Course: System Design
Mode: online live course
Duration: 10 Lectures
Node Name :geek
User id: 3
User Name: geek3
Enrolled Course: Competitive Programming
Mode: online live course
Duration: 8 weeks
Node Name :geek
User id: 4
User Name: geek4
Enrolled Course: Complete Interview Preparation
Mode: online self paced
Duration: Lifetime
Method 2: Java SAX Parser
SAX Parser in java provides API to parse XML documents. SAX parser is a lot more different from DOM parser because it doesn’t load complete XML into memory and read XML document sequentially. In SAX, parsing is done by the ContentHandler interface and this interface is implemented by DefaultHandler class.
Let’s now see an example on extracting data from XML using Java SAX Parser.
Create a java file for SAX parser. In this case, we have created GfgSaxXmlExtractor.java
Java
import javax.xml.parsers.SAXParser;import javax.xml.parsers.SAXParserFactory;import org.xml.sax.Attributes;import org.xml.sax.SAXException;import org.xml.sax.helpers.DefaultHandler;public class GfgSaxXmlParser { public static void main(String args[]) { try { /*SAXParserFactory is a factory API that enables applications to configure and obtain a SAX based parser to parse XML documents. */ SAXParserFactory factory = SAXParserFactory.newInstance(); // Creating a new instance of a SAXParser using // the currently configured factory parameters. SAXParser saxParser = factory.newSAXParser(); // DefaultHandler is Default base class for SAX2 // event handlers. DefaultHandler handler = new DefaultHandler() { boolean id = false; boolean username = false; boolean EnrolledCourse = false; boolean mode = false; boolean duration = false; // Receive notification of the start of an // element. parser starts parsing a element // inside the document public void startElement( String uri, String localName, String qName, Attributes attributes) throws SAXException { if (qName.equalsIgnoreCase("Id")) { id = true; } if (qName.equalsIgnoreCase( "username")) { username = true; } if (qName.equalsIgnoreCase( "EnrolledCourse")) { EnrolledCourse = true; } if (qName.equalsIgnoreCase("mode")) { mode = true; } if (qName.equalsIgnoreCase( "duration")) { duration = true; } } // Receive notification of character data // inside an element, reads the text value of // the currently parsed element public void characters(char ch[], int start, int length) throws SAXException { if (id) { System.out.println( "ID : " + new String(ch, start, length)); id = false; } if (username) { System.out.println( "User Name: " + new String(ch, start, length)); username = false; } if (EnrolledCourse) { System.out.println( "Enrolled Course: " + new String(ch, start, length)); EnrolledCourse = false; } if (mode) { System.out.println( "mode: " + new String(ch, start, length)); mode = false; } if (duration) { System.out.println( "duration : " + new String(ch, start, length)); duration = false; } } }; /*Parse the content described by the giving Uniform Resource Identifier (URI) as XML using the specified DefaultHandler. */ saxParser.parse( "F:\\geeksforgeeks_contributions\\gfg.xml", handler); } catch (Exception e) { System.out.println(e); } }}
Output
ID : 1
User Name: geek1
Enrolled Course: D.S.A
mode: online self paced
duration : Lifetime
ID : 2
User Name: geek2
Enrolled Course: System Design
mode: online live course
duration : 10 Lectures
ID : 3
User Name: geek3
Enrolled Course: Competitive Programming
mode: online live course
duration : 8 weeks
ID : 4
User Name: geek4
Enrolled Course: Complete Interview Preparation
mode: online self paced
duration : Lifetime
rkbhola5
Java
Java Programs
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Constructors in Java
Exceptions in Java
Functional Interfaces in Java
Different ways of Reading a text file in Java
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
How to Iterate HashMap in Java?
Iterate through List in Java | [
{
"code": null,
"e": 25237,
"s": 25209,
"text": "\n02 Feb, 2022"
},
{
"code": null,
"e": 25425,
"s": 25237,
"text": "An XML file contains data between the tags so it is complex to read the data when compared to other file formats like docx and txt. There are two types of parsers which parse an XML file:"
},
{
"code": null,
"e": 25451,
"s": 25425,
"text": "Object-Based (e.g. D.O.M)"
},
{
"code": null,
"e": 25480,
"s": 25451,
"text": "Event-Based (e.g. SAX, StAX)"
},
{
"code": null,
"e": 25573,
"s": 25480,
"text": "In this article, we will discuss how to parse XML using Java DOM parser and Java SAX parser."
},
{
"code": null,
"e": 25944,
"s": 25573,
"text": "Java DOM Parser: DOM stands for Document Object Model. The DOM API provides the classes to read and write an XML file. DOM reads an entire document. It is useful when reading small to medium size XML files. It is a tree-based parser and a little slow when compared to SAX and occupies more space when loaded into memory. We can insert and delete nodes using the DOM API."
},
{
"code": null,
"e": 26135,
"s": 25944,
"text": "We have to follow the below process to extract data from an XML file in Java. "
},
{
"code": null,
"e": 26157,
"s": 26135,
"text": "Instantiate XML file:"
},
{
"code": null,
"e": 26258,
"s": 26157,
"text": "Get root node: We can use getDocumentElement() to get the root node and the element of the XML file."
},
{
"code": null,
"e": 26418,
"s": 26258,
"text": "Get all nodes: On using getElementByTagName() Returns a NodeList of all the Elements in document order with a given tag name and are contained in the document."
},
{
"code": null,
"e": 26528,
"s": 26418,
"text": "Get Node by text value: We can use getElementByTextValue() method in order to search for a node by its value."
},
{
"code": null,
"e": 26635,
"s": 26528,
"text": "Get Node by attribute value: we can use the getElementByTagName() method along with getAttribute() method."
},
{
"code": null,
"e": 26711,
"s": 26635,
"text": "Let’s now see an example on extracting data from XML using Java DOM Parser."
},
{
"code": null,
"e": 26769,
"s": 26711,
"text": "Create a .xml file, in this case, we have created Gfg.xml"
},
{
"code": null,
"e": 26773,
"s": 26769,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\"?> <class> <geek> <id>1</id> <username>geek1</username> <EnrolledCourse>D.S.A</EnrolledCourse> <mode>online self paced</mode> <duration>Lifetime</duration> </geek> <geek> <id>2</id> <username>geek2</username> <EnrolledCourse>System Design</EnrolledCourse> <mode>online live course</mode> <duration>10 Lectures</duration> </geek> <geek> <id>3</id> <username>geek3</username> <EnrolledCourse>Competitive Programming</EnrolledCourse> <mode>online live course</mode> <duration>8 weeks</duration> </geek> <geek> <id>4</id> <username>geek4</username> <EnrolledCourse>Complete Interview Preparation</EnrolledCourse> <mode>online self paced</mode> <duration>Lifetime</duration> </geek> </class>",
"e": 27712,
"s": 26773,
"text": null
},
{
"code": null,
"e": 27790,
"s": 27712,
"text": "Now create a java file for Java DOM parser. In this case GfgXmlExtractor.java"
},
{
"code": null,
"e": 27795,
"s": 27790,
"text": "Java"
},
{
"code": "import javax.xml.parsers.DocumentBuilderFactory;import javax.xml.parsers.DocumentBuilder;import org.w3c.dom.Document;import org.w3c.dom.NodeList;import org.w3c.dom.Node;import org.w3c.dom.Element;import java.io.File;public class GfgXmlExtractor { public static void main(String argv[]) { try { // creating a constructor of file class and // parsing an XML file File file = new File( \"F:\\\\geeksforgeeks_contributions\\\\gfg.xml\"); // Defines a factory API that enables // applications to obtain a parser that produces // DOM object trees from XML documents. DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); // we are creating an object of builder to parse // the xml file. DocumentBuilder db = dbf.newDocumentBuilder(); Document doc = db.parse(file); /*here normalize method Puts all Text nodes in the full depth of the sub-tree underneath this Node, including attribute nodes, into a \"normal\" form where only structure separates Text nodes, i.e., there are neither adjacent Text nodes nor empty Text nodes. */ doc.getDocumentElement().normalize(); System.out.println( \"Root element: \" + doc.getDocumentElement().getNodeName()); // Here nodeList contains all the nodes with // name geek. NodeList nodeList = doc.getElementsByTagName(\"geek\"); // Iterate through all the nodes in NodeList // using for loop. for (int i = 0; i < nodeList.getLength(); ++i) { Node node = nodeList.item(i); System.out.println(\"\\nNode Name :\" + node.getNodeName()); if (node.getNodeType() == Node.ELEMENT_NODE) { Element tElement = (Element)node; System.out.println( \"User id: \" + tElement .getElementsByTagName(\"id\") .item(0) .getTextContent()); System.out.println( \"User Name: \" + tElement .getElementsByTagName( \"username\") .item(0) .getTextContent()); System.out.println( \"Enrolled Course: \" + tElement .getElementsByTagName( \"EnrolledCourse\") .item(0) .getTextContent()); System.out.println( \"Mode: \" + tElement .getElementsByTagName(\"mode\") .item(0) .getTextContent()); System.out.println( \"Duration: \" + tElement .getElementsByTagName( \"duration\") .item(0) .getTextContent()); } } } // This exception block catches all the exception // raised. // For example if we try to access a element by a // TagName that is not there in the XML etc. catch (Exception e) { System.out.println(e); } }}",
"e": 31570,
"s": 27795,
"text": null
},
{
"code": null,
"e": 31577,
"s": 31570,
"text": "Output"
},
{
"code": null,
"e": 32101,
"s": 31577,
"text": "Root element: class\n\nNode Name :geek\nUser id: 1\nUser Name: geek1\nEnrolled Course: D.S.A\nMode: online self paced\nDuration: Lifetime\n\nNode Name :geek\nUser id: 2\nUser Name: geek2\nEnrolled Course: System Design\nMode: online live course\nDuration: 10 Lectures\n\nNode Name :geek\nUser id: 3\nUser Name: geek3\nEnrolled Course: Competitive Programming\nMode: online live course\nDuration: 8 weeks\n\nNode Name :geek\nUser id: 4\nUser Name: geek4\nEnrolled Course: Complete Interview Preparation\nMode: online self paced\nDuration: Lifetime\n\n\n\n\n"
},
{
"code": null,
"e": 32127,
"s": 32101,
"text": "Method 2: Java SAX Parser"
},
{
"code": null,
"e": 32434,
"s": 32127,
"text": "SAX Parser in java provides API to parse XML documents. SAX parser is a lot more different from DOM parser because it doesn’t load complete XML into memory and read XML document sequentially. In SAX, parsing is done by the ContentHandler interface and this interface is implemented by DefaultHandler class."
},
{
"code": null,
"e": 32510,
"s": 32434,
"text": "Let’s now see an example on extracting data from XML using Java SAX Parser."
},
{
"code": null,
"e": 32599,
"s": 32510,
"text": "Create a java file for SAX parser. In this case, we have created GfgSaxXmlExtractor.java"
},
{
"code": null,
"e": 32604,
"s": 32599,
"text": "Java"
},
{
"code": "import javax.xml.parsers.SAXParser;import javax.xml.parsers.SAXParserFactory;import org.xml.sax.Attributes;import org.xml.sax.SAXException;import org.xml.sax.helpers.DefaultHandler;public class GfgSaxXmlParser { public static void main(String args[]) { try { /*SAXParserFactory is a factory API that enables applications to configure and obtain a SAX based parser to parse XML documents. */ SAXParserFactory factory = SAXParserFactory.newInstance(); // Creating a new instance of a SAXParser using // the currently configured factory parameters. SAXParser saxParser = factory.newSAXParser(); // DefaultHandler is Default base class for SAX2 // event handlers. DefaultHandler handler = new DefaultHandler() { boolean id = false; boolean username = false; boolean EnrolledCourse = false; boolean mode = false; boolean duration = false; // Receive notification of the start of an // element. parser starts parsing a element // inside the document public void startElement( String uri, String localName, String qName, Attributes attributes) throws SAXException { if (qName.equalsIgnoreCase(\"Id\")) { id = true; } if (qName.equalsIgnoreCase( \"username\")) { username = true; } if (qName.equalsIgnoreCase( \"EnrolledCourse\")) { EnrolledCourse = true; } if (qName.equalsIgnoreCase(\"mode\")) { mode = true; } if (qName.equalsIgnoreCase( \"duration\")) { duration = true; } } // Receive notification of character data // inside an element, reads the text value of // the currently parsed element public void characters(char ch[], int start, int length) throws SAXException { if (id) { System.out.println( \"ID : \" + new String(ch, start, length)); id = false; } if (username) { System.out.println( \"User Name: \" + new String(ch, start, length)); username = false; } if (EnrolledCourse) { System.out.println( \"Enrolled Course: \" + new String(ch, start, length)); EnrolledCourse = false; } if (mode) { System.out.println( \"mode: \" + new String(ch, start, length)); mode = false; } if (duration) { System.out.println( \"duration : \" + new String(ch, start, length)); duration = false; } } }; /*Parse the content described by the giving Uniform Resource Identifier (URI) as XML using the specified DefaultHandler. */ saxParser.parse( \"F:\\\\geeksforgeeks_contributions\\\\gfg.xml\", handler); } catch (Exception e) { System.out.println(e); } }}",
"e": 36911,
"s": 32604,
"text": null
},
{
"code": null,
"e": 36918,
"s": 36911,
"text": "Output"
},
{
"code": null,
"e": 37338,
"s": 36918,
"text": "ID : 1\nUser Name: geek1\nEnrolled Course: D.S.A\nmode: online self paced\nduration : Lifetime\nID : 2\nUser Name: geek2\nEnrolled Course: System Design\nmode: online live course\nduration : 10 Lectures\nID : 3\nUser Name: geek3\nEnrolled Course: Competitive Programming\nmode: online live course\nduration : 8 weeks\nID : 4\nUser Name: geek4\nEnrolled Course: Complete Interview Preparation\nmode: online self paced\nduration : Lifetime\n"
},
{
"code": null,
"e": 37347,
"s": 37338,
"text": "rkbhola5"
},
{
"code": null,
"e": 37352,
"s": 37347,
"text": "Java"
},
{
"code": null,
"e": 37366,
"s": 37352,
"text": "Java Programs"
},
{
"code": null,
"e": 37371,
"s": 37366,
"text": "Java"
},
{
"code": null,
"e": 37469,
"s": 37371,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 37484,
"s": 37469,
"text": "Stream In Java"
},
{
"code": null,
"e": 37505,
"s": 37484,
"text": "Constructors in Java"
},
{
"code": null,
"e": 37524,
"s": 37505,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 37554,
"s": 37524,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 37600,
"s": 37554,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 37626,
"s": 37600,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 37660,
"s": 37626,
"text": "Convert Double to Integer in Java"
},
{
"code": null,
"e": 37707,
"s": 37660,
"text": "Implementing a Linked List in Java using Class"
},
{
"code": null,
"e": 37739,
"s": 37707,
"text": "How to Iterate HashMap in Java?"
}
] |
Modify values of a Data Frame in R Language - transform() Function - GeeksforGeeks | 26 May, 2020
transform() function in R Language is used to modify data. It converts the first argument to the data frame.This function is used to transform/modify the data frame in a quick and easy way.
Syntax:transform(data, value)
Parameters:data: Data Frame to be modifiedvalue: new modified value of data
Example 1: Use transform() on variables
# R program to illustrate# transform on variables # Create example data framedata <- data.frame(x1 = c(1, 2, 3, 4), x2 = c(5, 6, 7, 8)) # Apply transform functiondata_ex1 <- transform(data, x1 = x1 + 10) # Print data print(data_ex1)
Output:
x1= 11, 12, 13, 14.
x2 = 5, 6, 7, 8.
Here in the above code, we have a data framework and we transform it by adding 10(x1 = x1 + 10) to each of the values.The values of x2 will not get changed as we do not apply any transformation to it.
Example 2: Add new variables to data
# R program to illustrate # Adding new variables to data data <- data.frame(x1 = c(11, 12, 13, 14), x2 = c(5, 6, 7, 8)) # Apply transform functiondata_ex2 <- transform(data, x3 = c(1, 3, 3, 4)) print(data_ex2)
Output:
X1= 11, 12, 13, 14.
X2 = 5, 6, 7, 8.
X3 = 1, 3, 3, 4.
Here in the above code, we are adding a new variable x3 to the previous data.
R-Functions
Programming Language
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
5 Best Languages for Competitive Programming
Introduction of Object Oriented Programming
7 Highest Paying Programming Languages For Freelancers in 2022
R - Matrices
R - Charts and Graphs
Change column name of a given DataFrame in R
How to Replace specific values in column in R DataFrame ?
Filter data by multiple conditions in R using Dplyr
Loops in R (for, while, repeat)
Adding elements in a vector in R programming - append() method | [
{
"code": null,
"e": 25957,
"s": 25929,
"text": "\n26 May, 2020"
},
{
"code": null,
"e": 26147,
"s": 25957,
"text": "transform() function in R Language is used to modify data. It converts the first argument to the data frame.This function is used to transform/modify the data frame in a quick and easy way."
},
{
"code": null,
"e": 26177,
"s": 26147,
"text": "Syntax:transform(data, value)"
},
{
"code": null,
"e": 26253,
"s": 26177,
"text": "Parameters:data: Data Frame to be modifiedvalue: new modified value of data"
},
{
"code": null,
"e": 26293,
"s": 26253,
"text": "Example 1: Use transform() on variables"
},
{
"code": "# R program to illustrate# transform on variables # Create example data framedata <- data.frame(x1 = c(1, 2, 3, 4), x2 = c(5, 6, 7, 8)) # Apply transform functiondata_ex1 <- transform(data, x1 = x1 + 10) # Print data print(data_ex1) ",
"e": 26646,
"s": 26293,
"text": null
},
{
"code": null,
"e": 26654,
"s": 26646,
"text": "Output:"
},
{
"code": null,
"e": 26691,
"s": 26654,
"text": "x1= 11, 12, 13, 14.\nx2 = 5, 6, 7, 8."
},
{
"code": null,
"e": 26892,
"s": 26691,
"text": "Here in the above code, we have a data framework and we transform it by adding 10(x1 = x1 + 10) to each of the values.The values of x2 will not get changed as we do not apply any transformation to it."
},
{
"code": null,
"e": 26929,
"s": 26892,
"text": "Example 2: Add new variables to data"
},
{
"code": "# R program to illustrate # Adding new variables to data data <- data.frame(x1 = c(11, 12, 13, 14), x2 = c(5, 6, 7, 8)) # Apply transform functiondata_ex2 <- transform(data, x3 = c(1, 3, 3, 4)) print(data_ex2) ",
"e": 27175,
"s": 26929,
"text": null
},
{
"code": null,
"e": 27183,
"s": 27175,
"text": "Output:"
},
{
"code": null,
"e": 27238,
"s": 27183,
"text": "X1= 11, 12, 13, 14.\nX2 = 5, 6, 7, 8.\nX3 = 1, 3, 3, 4.\n"
},
{
"code": null,
"e": 27316,
"s": 27238,
"text": "Here in the above code, we are adding a new variable x3 to the previous data."
},
{
"code": null,
"e": 27328,
"s": 27316,
"text": "R-Functions"
},
{
"code": null,
"e": 27349,
"s": 27328,
"text": "Programming Language"
},
{
"code": null,
"e": 27360,
"s": 27349,
"text": "R Language"
},
{
"code": null,
"e": 27458,
"s": 27360,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27503,
"s": 27458,
"text": "5 Best Languages for Competitive Programming"
},
{
"code": null,
"e": 27547,
"s": 27503,
"text": "Introduction of Object Oriented Programming"
},
{
"code": null,
"e": 27610,
"s": 27547,
"text": "7 Highest Paying Programming Languages For Freelancers in 2022"
},
{
"code": null,
"e": 27623,
"s": 27610,
"text": "R - Matrices"
},
{
"code": null,
"e": 27645,
"s": 27623,
"text": "R - Charts and Graphs"
},
{
"code": null,
"e": 27690,
"s": 27645,
"text": "Change column name of a given DataFrame in R"
},
{
"code": null,
"e": 27748,
"s": 27690,
"text": "How to Replace specific values in column in R DataFrame ?"
},
{
"code": null,
"e": 27800,
"s": 27748,
"text": "Filter data by multiple conditions in R using Dplyr"
},
{
"code": null,
"e": 27832,
"s": 27800,
"text": "Loops in R (for, while, repeat)"
}
] |
How to use a DataLoader in PyTorch? - GeeksforGeeks | 24 Feb, 2021
Operating with large datasets requires loading them into memory all at once. In most cases, we face a memory outage due to the limited amount of memory available in the system. Also, the programs tend to run slowly due to heavy datasets loaded once. PyTorch offers a solution for parallelizing the data loading process with automatic batching by using DataLoader. Dataloader has been used to parallelize the data loading as this boosts up the speed and saves memory.
The dataloader constructor resides in the torch.utils.data package. It has various parameters among which the only mandatory argument to be passed is the dataset that has to be loaded, and the rest all are optional arguments.
Syntax:
DataLoader(dataset, shuffle=True, sampler=None, batch_size=32)
DataLoaders on Custom Datasets:
To implement dataloaders on a custom dataset we need to override the following two subclass functions:
The _len_() function: returns the size of the dataset.
The _getitem_() function: returns a sample of the given index from the dataset.
Python3
# importing the required librariesimport torchfrom torch.utils.data import Datasetfrom torch.utils.data import DataLoader # defining the Dataset classclass data_set(Dataset): def __init__(self): numbers = list(range(0, 100, 1)) self.data = numbers def __len__(self): return len(self.data) def __getitem__(self, index): return self.data[index] dataset = data_set() # implementing dataloader on the dataset and printing per batchdataloader = DataLoader(dataset, batch_size=10, shuffle=True)for i, batch in enumerate(dataloader): print(i, batch)
Output:
DataLoaders on Built-in Datasets:
Python3
# importing the required librariesimport torchfrom torch.utils.data import Datasetfrom torch.utils.data import DataLoaderimport seaborn as snsfrom torch.utils.data import TensorDataset # defining the dataset consisting of # two columns from iris datasetiris = sns.load_dataset('iris')petal_length = torch.tensor(iris['petal_length'])petal_width = torch.tensor(iris['petal_width'])dataset = TensorDataset(petal_length, petal_width) # implementing dataloader on the dataset # and printing per batchdataloader = DataLoader(dataset, batch_size=5, shuffle=True) for i in dataloader: print(i)
Output:
Picked
Python-PyTorch
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 | Get unique values from a list
Create a directory in Python
Defaultdict in Python
Python | Pandas dataframe.groupby() | [
{
"code": null,
"e": 25537,
"s": 25509,
"text": "\n24 Feb, 2021"
},
{
"code": null,
"e": 26004,
"s": 25537,
"text": "Operating with large datasets requires loading them into memory all at once. In most cases, we face a memory outage due to the limited amount of memory available in the system. Also, the programs tend to run slowly due to heavy datasets loaded once. PyTorch offers a solution for parallelizing the data loading process with automatic batching by using DataLoader. Dataloader has been used to parallelize the data loading as this boosts up the speed and saves memory."
},
{
"code": null,
"e": 26230,
"s": 26004,
"text": "The dataloader constructor resides in the torch.utils.data package. It has various parameters among which the only mandatory argument to be passed is the dataset that has to be loaded, and the rest all are optional arguments."
},
{
"code": null,
"e": 26238,
"s": 26230,
"text": "Syntax:"
},
{
"code": null,
"e": 26301,
"s": 26238,
"text": "DataLoader(dataset, shuffle=True, sampler=None, batch_size=32)"
},
{
"code": null,
"e": 26333,
"s": 26301,
"text": "DataLoaders on Custom Datasets:"
},
{
"code": null,
"e": 26437,
"s": 26333,
"text": "To implement dataloaders on a custom dataset we need to override the following two subclass functions: "
},
{
"code": null,
"e": 26492,
"s": 26437,
"text": "The _len_() function: returns the size of the dataset."
},
{
"code": null,
"e": 26572,
"s": 26492,
"text": "The _getitem_() function: returns a sample of the given index from the dataset."
},
{
"code": null,
"e": 26580,
"s": 26572,
"text": "Python3"
},
{
"code": "# importing the required librariesimport torchfrom torch.utils.data import Datasetfrom torch.utils.data import DataLoader # defining the Dataset classclass data_set(Dataset): def __init__(self): numbers = list(range(0, 100, 1)) self.data = numbers def __len__(self): return len(self.data) def __getitem__(self, index): return self.data[index] dataset = data_set() # implementing dataloader on the dataset and printing per batchdataloader = DataLoader(dataset, batch_size=10, shuffle=True)for i, batch in enumerate(dataloader): print(i, batch)",
"e": 27172,
"s": 26580,
"text": null
},
{
"code": null,
"e": 27180,
"s": 27172,
"text": "Output:"
},
{
"code": null,
"e": 27214,
"s": 27180,
"text": "DataLoaders on Built-in Datasets:"
},
{
"code": null,
"e": 27222,
"s": 27214,
"text": "Python3"
},
{
"code": "# importing the required librariesimport torchfrom torch.utils.data import Datasetfrom torch.utils.data import DataLoaderimport seaborn as snsfrom torch.utils.data import TensorDataset # defining the dataset consisting of # two columns from iris datasetiris = sns.load_dataset('iris')petal_length = torch.tensor(iris['petal_length'])petal_width = torch.tensor(iris['petal_width'])dataset = TensorDataset(petal_length, petal_width) # implementing dataloader on the dataset # and printing per batchdataloader = DataLoader(dataset, batch_size=5, shuffle=True) for i in dataloader: print(i)",
"e": 27863,
"s": 27222,
"text": null
},
{
"code": null,
"e": 27871,
"s": 27863,
"text": "Output:"
},
{
"code": null,
"e": 27878,
"s": 27871,
"text": "Picked"
},
{
"code": null,
"e": 27893,
"s": 27878,
"text": "Python-PyTorch"
},
{
"code": null,
"e": 27900,
"s": 27893,
"text": "Python"
},
{
"code": null,
"e": 27998,
"s": 27900,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28030,
"s": 27998,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28072,
"s": 28030,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 28114,
"s": 28072,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 28170,
"s": 28114,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 28197,
"s": 28170,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 28228,
"s": 28197,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 28267,
"s": 28228,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 28296,
"s": 28267,
"text": "Create a directory in Python"
},
{
"code": null,
"e": 28318,
"s": 28296,
"text": "Defaultdict in Python"
}
] |
Ittiam Written Test Questions - GeeksforGeeks | 29 Aug, 2018
Round 1(30 mins): Written TestIt was a written round (pen-paper). It started just after the company’s ppt (pre-placement talk). There were a total of 20 Mcqs (with negative marking), 10 from quantitative aptitude and 10 from technical aptitude to be solved in 30 mins.
Quant questions were from time&work, speed-distance(tricky one), few maths quesns viz. related to area of circle, mathematical reasoning (like questions on propositional logic, there exists and for all ->these type of questions can be found in discrete mathematics). Overall it was of average difficulty level.
1) What is the return value of count when the function start() is called with num value of 2017 in the following program:
int start(int num){ int count = 0; while (num > 0) { ++count; num = (num - 1) & num; } return count;}}
a)25b)1c)7d)8
Ans) c
2)Global Variables can be shared between :a)Between both two process and two threadsb)By processes only but not between Threadsc)By Threads only but not between processesd)By neither processes nor threads
Ans) c
3)You have 3 baskets, one with apples, one with oranges and one with both apples and oranges mixed. Each basket is closed and is labeled with ‘Apples’, ‘Oranges’ and ‘Apples and Oranges’. However, each of these labels is always placed incorrectly. How many fruits would you pick only one fruit from a basket to place the labels correctly on all the baskets?
a)3b)1c)4d)2
Ans) d
4)
#include<stdio,h> int main(void){ unsigned int x=10; unsigned int y=0; while (x > 0) { --x; ++y; } printf("%u", y);}
a)5b)7c)10d)The function does not return anythingAns) c
5)What is the final state that is been reached after the traversing of the string ‘000100110’:a)bb)fc)ad)e
Ans) b
6)Study the following table and answer the questions based on it.Expenditures of a Company (in Lakh Rupees) per Annum Over the given Years.
Year Item of Expenditure Salary Fuel and Transport
Bonus Interest on Loans Taxes
1998 288 98 3.00 23.4 83
1999 342 112 2.52 32.5 108
2000 324 101 3.84 41.6 74
2001 336 133 3.68 36.4 88
2002 420 142 3.96 49.4 98
What is the average amount of interest per year which the company had to pay during this period?a)Rs. 32.43 lakhsb)Rs. 33.72 lakhsc)Rs. 34.18 lakhsd)Rs. 36.66 lakhsAns) d
7) If a person walks at 14 km/hr instead of 10 km/hr, he would have walked 20 km more. The actual distance traveled by him is:a)50 kmb)56 kmc)70 kmd)80 kmAns) a
8) Which of the following line of code is suitable to start a thread?
class X implements Runnable { public static void main(String args[]) { /* Missing code? */ } public void run() {} }
a)Thread t = new Thread(X);b)Thread t = new Thread(X); t.start();c)X run = new X(); Thread t = new Thread(run); t.start();d)Thread t = new Thread(); x.run();
Ans) c
Ittiam Systems
Interview Experiences
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Amazon Interview Experience for SDE-1 (Off-Campus)
Amazon AWS Interview Experience for SDE-1
Difference between ANN, CNN and RNN
Amazon Interview Experience for SDE-1 (Off-Campus) 2022
Amazon Interview Experience
Amazon Interview Experience for SDE-1
Amazon Interview Experience (Off-Campus) 2022
Freshworks/Freshdesk Interview Experience for Software Developer (On-Campus)
JPMorgan Chase & Co. Code for Good Internship Interview Experience 2021
EPAM Interview Experience (Off-Campus) | [
{
"code": null,
"e": 26705,
"s": 26677,
"text": "\n29 Aug, 2018"
},
{
"code": null,
"e": 26974,
"s": 26705,
"text": "Round 1(30 mins): Written TestIt was a written round (pen-paper). It started just after the company’s ppt (pre-placement talk). There were a total of 20 Mcqs (with negative marking), 10 from quantitative aptitude and 10 from technical aptitude to be solved in 30 mins."
},
{
"code": null,
"e": 27285,
"s": 26974,
"text": "Quant questions were from time&work, speed-distance(tricky one), few maths quesns viz. related to area of circle, mathematical reasoning (like questions on propositional logic, there exists and for all ->these type of questions can be found in discrete mathematics). Overall it was of average difficulty level."
},
{
"code": null,
"e": 27407,
"s": 27285,
"text": "1) What is the return value of count when the function start() is called with num value of 2017 in the following program:"
},
{
"code": "int start(int num){ int count = 0; while (num > 0) { ++count; num = (num - 1) & num; } return count;}}",
"e": 27536,
"s": 27407,
"text": null
},
{
"code": null,
"e": 27550,
"s": 27536,
"text": "a)25b)1c)7d)8"
},
{
"code": null,
"e": 27557,
"s": 27550,
"text": "Ans) c"
},
{
"code": null,
"e": 27762,
"s": 27557,
"text": "2)Global Variables can be shared between :a)Between both two process and two threadsb)By processes only but not between Threadsc)By Threads only but not between processesd)By neither processes nor threads"
},
{
"code": null,
"e": 27769,
"s": 27762,
"text": "Ans) c"
},
{
"code": null,
"e": 28127,
"s": 27769,
"text": "3)You have 3 baskets, one with apples, one with oranges and one with both apples and oranges mixed. Each basket is closed and is labeled with ‘Apples’, ‘Oranges’ and ‘Apples and Oranges’. However, each of these labels is always placed incorrectly. How many fruits would you pick only one fruit from a basket to place the labels correctly on all the baskets?"
},
{
"code": null,
"e": 28140,
"s": 28127,
"text": "a)3b)1c)4d)2"
},
{
"code": null,
"e": 28147,
"s": 28140,
"text": "Ans) d"
},
{
"code": null,
"e": 28150,
"s": 28147,
"text": "4)"
},
{
"code": "#include<stdio,h> int main(void){ unsigned int x=10; unsigned int y=0; while (x > 0) { --x; ++y; } printf(\"%u\", y);} ",
"e": 28281,
"s": 28150,
"text": null
},
{
"code": null,
"e": 28337,
"s": 28281,
"text": "a)5b)7c)10d)The function does not return anythingAns) c"
},
{
"code": null,
"e": 28444,
"s": 28337,
"text": "5)What is the final state that is been reached after the traversing of the string ‘000100110’:a)bb)fc)ad)e"
},
{
"code": null,
"e": 28451,
"s": 28444,
"text": "Ans) b"
},
{
"code": null,
"e": 28591,
"s": 28451,
"text": "6)Study the following table and answer the questions based on it.Expenditures of a Company (in Lakh Rupees) per Annum Over the given Years."
},
{
"code": null,
"e": 28898,
"s": 28591,
"text": "Year Item of Expenditure Salary Fuel and Transport \n Bonus Interest on Loans Taxes\n1998 288 98 3.00 23.4 83\n1999 342 112 2.52 32.5 108\n2000 324 101 3.84 41.6 74\n2001 336 133 3.68 36.4 88\n2002 420 142 3.96 49.4 98"
},
{
"code": null,
"e": 29069,
"s": 28898,
"text": "What is the average amount of interest per year which the company had to pay during this period?a)Rs. 32.43 lakhsb)Rs. 33.72 lakhsc)Rs. 34.18 lakhsd)Rs. 36.66 lakhsAns) d"
},
{
"code": null,
"e": 29230,
"s": 29069,
"text": "7) If a person walks at 14 km/hr instead of 10 km/hr, he would have walked 20 km more. The actual distance traveled by him is:a)50 kmb)56 kmc)70 kmd)80 kmAns) a"
},
{
"code": null,
"e": 29300,
"s": 29230,
"text": "8) Which of the following line of code is suitable to start a thread?"
},
{
"code": "class X implements Runnable { public static void main(String args[]) { /* Missing code? */ } public void run() {} }",
"e": 29438,
"s": 29300,
"text": null
},
{
"code": null,
"e": 29596,
"s": 29438,
"text": "a)Thread t = new Thread(X);b)Thread t = new Thread(X); t.start();c)X run = new X(); Thread t = new Thread(run); t.start();d)Thread t = new Thread(); x.run();"
},
{
"code": null,
"e": 29603,
"s": 29596,
"text": "Ans) c"
},
{
"code": null,
"e": 29618,
"s": 29603,
"text": "Ittiam Systems"
},
{
"code": null,
"e": 29640,
"s": 29618,
"text": "Interview Experiences"
},
{
"code": null,
"e": 29738,
"s": 29640,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29789,
"s": 29738,
"text": "Amazon Interview Experience for SDE-1 (Off-Campus)"
},
{
"code": null,
"e": 29831,
"s": 29789,
"text": "Amazon AWS Interview Experience for SDE-1"
},
{
"code": null,
"e": 29867,
"s": 29831,
"text": "Difference between ANN, CNN and RNN"
},
{
"code": null,
"e": 29923,
"s": 29867,
"text": "Amazon Interview Experience for SDE-1 (Off-Campus) 2022"
},
{
"code": null,
"e": 29951,
"s": 29923,
"text": "Amazon Interview Experience"
},
{
"code": null,
"e": 29989,
"s": 29951,
"text": "Amazon Interview Experience for SDE-1"
},
{
"code": null,
"e": 30035,
"s": 29989,
"text": "Amazon Interview Experience (Off-Campus) 2022"
},
{
"code": null,
"e": 30112,
"s": 30035,
"text": "Freshworks/Freshdesk Interview Experience for Software Developer (On-Campus)"
},
{
"code": null,
"e": 30184,
"s": 30112,
"text": "JPMorgan Chase & Co. Code for Good Internship Interview Experience 2021"
}
] |
Print the nodes at odd levels of a tree - GeeksforGeeks | 16 Mar, 2022
Given a binary tree, print nodes of odd level in any order. Root is considered at level 1.
For example consider the following tree
1
/ \
2 3
/ \ \
4 5 6
/ \ /
7 8 9
Output 1 4 5 6
Method 1 (Recursive)
The idea is to pass initial level as odd and switch level flag in every recursive call. For every node, if odd flag is set, then print it.
C++
Java
Python3
C#
Javascript
// Recursive C++ program to print odd level nodes#include <bits/stdc++.h>using namespace std; struct Node { int data; Node* left, *right;}; void printOddNodes(Node *root, bool isOdd = true){ // If empty tree if (root == NULL) return; // If current node is of odd level if (isOdd) cout << root->data << " " ; // Recur for children with isOdd // switched. printOddNodes(root->left, !isOdd); printOddNodes(root->right, !isOdd);} // Utility method to create a nodestruct Node* newNode(int data){ struct Node* node = new Node; node->data = data; node->left = node->right = NULL; return (node);} // Driver codeint main(){ struct Node* root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); printOddNodes(root); return 0;}
// Recursive Java program to print odd level nodesclass GfG { static class Node { int data; Node left, right;} static void printOddNodes(Node root, boolean isOdd){ // If empty tree if (root == null) return; // If current node is of odd level if (isOdd == true) System.out.print(root.data + " "); // Recur for children with isOdd // switched. printOddNodes(root.left, !isOdd); printOddNodes(root.right, !isOdd);} // Utility method to create a nodestatic Node newNode(int data){ Node node = new Node(); node.data = data; node.left = null; node.right = null; return (node);} // Driver codepublic static void main(String[] args){ Node root = newNode(1); root.left = newNode(2); root.right = newNode(3); root.left.left = newNode(4); root.left.right = newNode(5); printOddNodes(root, true); }}
# Recursive Python3 program to print# odd level nodes # Utility method to create a nodeclass newNode: def __init__(self, data): self.data = data self.left = self.right = None def printOddNodes(root, isOdd = True): # If empty tree if (root == None): return # If current node is of odd level if (isOdd): print(root.data, end = " ") # Recur for children with isOdd # switched. printOddNodes(root.left, not isOdd) printOddNodes(root.right, not isOdd) # Driver codeif __name__ == '__main__': root = newNode(1) root.left = newNode(2) root.right = newNode(3) root.left.left = newNode(4) root.left.right = newNode(5) printOddNodes(root) # This code is contributed by PranchalK
using System; // Recursive C# program to print odd level nodes public class GfG{ public class Node{ public int data; public Node left, right;} public static void printOddNodes(Node root, bool isOdd){ // If empty tree if (root == null) { return; } // If current node is of odd level if (isOdd == true) { Console.Write(root.data + " "); } // Recur for children with isOdd // switched. printOddNodes(root.left, !isOdd); printOddNodes(root.right, !isOdd);} // Utility method to create a node public static Node newNode(int data){ Node node = new Node(); node.data = data; node.left = null; node.right = null; return (node);} // Driver code public static void Main(string[] args){ Node root = newNode(1); root.left = newNode(2); root.right = newNode(3); root.left.left = newNode(4); root.left.right = newNode(5); printOddNodes(root, true); }} // This code is contributed by Shrikant13
<script> // Recursive JavaScript program to print odd level nodes class Node { constructor(data) { this.left = null; this.right = null; this.data = data; } } function printOddNodes(root, isOdd) { // If empty tree if (root == null) return; // If current node is of odd level if (isOdd == true) document.write(root.data + " "); // Recur for children with isOdd // switched. printOddNodes(root.left, !isOdd); printOddNodes(root.right, !isOdd); } // Utility method to create a node function newNode(data) { let node = new Node(data); return (node); } let root = newNode(1); root.left = newNode(2); root.right = newNode(3); root.left.left = newNode(4); root.left.right = newNode(5); printOddNodes(root, true); </script>
Output:
1 4 5
Time complexity : O(n)Auxiliary Space: O(n) for Recursive Stack Space in case of Skewed Tree
Method 2 (Iterative)
The above code prints nodes in preorder way. If we wish to print nodes level by level, we can use level order traversal. The idea is based on Print level order traversal line by lineWe traverse nodes level by level. We switch odd level flag after every level.
C++
Java
Python3
C#
Javascript
// Iterative C++ program to print odd level nodes#include <bits/stdc++.h>using namespace std; struct Node { int data; Node* left, *right;}; // Iterative method to do level order traversal line by linevoid printOddNodes(Node *root){ // Base Case if (root == NULL) return; // Create an empty queue for level // order traversal queue<Node *> q; // Enqueue root and initialize level as odd q.push(root); bool isOdd = true; while (1) { // nodeCount (queue size) indicates // number of nodes at current level. int nodeCount = q.size(); if (nodeCount == 0) break; // Dequeue all nodes of current level // and Enqueue all nodes of next level while (nodeCount > 0) { Node *node = q.front(); if (isOdd) cout << node->data << " "; q.pop(); if (node->left != NULL) q.push(node->left); if (node->right != NULL) q.push(node->right); nodeCount--; } isOdd = !isOdd; }} // Utility method to create a nodestruct Node* newNode(int data){ struct Node* node = new Node; node->data = data; node->left = node->right = NULL; return (node);} // Driver codeint main(){ struct Node* root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); printOddNodes(root); return 0;}
// Iterative Java program to print odd level nodesimport java.util.*;class GfG { static class Node { int data; Node left, right;} // Iterative method to do level order traversal line by linestatic void printOddNodes(Node root){ // Base Case if (root == null) return; // Create an empty queue for level // order traversal Queue<Node> q = new LinkedList<Node> (); // Enqueue root and initialize level as odd q.add(root); boolean isOdd = true; while (true) { // nodeCount (queue size) indicates // number of nodes at current level. int nodeCount = q.size(); if (nodeCount == 0) break; // Dequeue all nodes of current level // and Enqueue all nodes of next level while (nodeCount > 0) { Node node = q.peek(); if (isOdd == true) System.out.print(node.data + " "); q.remove(); if (node.left != null) q.add(node.left); if (node.right != null) q.add(node.right); nodeCount--; } isOdd = !isOdd; }} // Utility method to create a nodestatic Node newNode(int data){ Node node = new Node(); node.data = data; node.left = null; node.right = null; return (node);} // Driver codepublic static void main(String[] args){ Node root = newNode(1); root.left = newNode(2); root.right = newNode(3); root.left.left = newNode(4); root.left.right = newNode(5); printOddNodes(root);}}
# Iterative Python3 program to print odd# level nodes # A Binary Tree Node# Utility function to create a# new tree Nodeclass newNode: def __init__(self, data): self.data = data self.left = self.right = None # Iterative method to do level order# traversal line by linedef printOddNodes(root) : # Base Case if (root == None): return # Create an empty queue for # level order traversal q = [] # Enqueue root and initialize # level as odd q.append(root) isOdd = True while (1) : # nodeCount (queue size) indicates # number of nodes at current level. nodeCount = len(q) if (nodeCount == 0) : break # Dequeue all nodes of current level # and Enqueue all nodes of next level while (nodeCount > 0): node = q[0] if (isOdd): print(node.data, end = " ") q.pop(0) if (node.left != None) : q.append(node.left) if (node.right != None) : q.append(node.right) nodeCount -= 1 isOdd = not isOdd # Driver Codeif __name__ == '__main__': root = newNode(1) root.left = newNode(2) root.right = newNode(3) root.left.left = newNode(4) root.left.right = newNode(5) printOddNodes(root) # This code is contributed# by SHUBHAMSINGH10
// Iterative C# program to// print odd level nodesusing System;using System.Collections.Generic; public class GfG{ public class Node { public int data; public Node left, right; } // Iterative method to do level // order traversal line by line static void printOddNodes(Node root) { // Base Case if (root == null) return; // Create an empty queue for level // order traversal Queue<Node> q = new Queue<Node> (); // Enqueue root and initialize level as odd q.Enqueue(root); bool isOdd = true; while (true) { // nodeCount (queue size) indicates // number of nodes at current level. int nodeCount = q.Count; if (nodeCount == 0) break; // Dequeue all nodes of current level // and Enqueue all nodes of next level while (nodeCount > 0) { Node node = q.Peek(); if (isOdd == true) Console.Write(node.data + " "); q.Dequeue(); if (node.left != null) q.Enqueue(node.left); if (node.right != null) q.Enqueue(node.right); nodeCount--; } isOdd = !isOdd; } } // Utility method to create a node static Node newNode(int data) { Node node = new Node(); node.data = data; node.left = null; node.right = null; return (node); } // Driver code public static void Main(String[] args) { Node root = newNode(1); root.left = newNode(2); root.right = newNode(3); root.left.left = newNode(4); root.left.right = newNode(5); printOddNodes(root); }} // This code has been contributed// by 29AjayKumar
<script>// Iterative Javascript program to print odd level nodes class Node{ constructor(data) { this.data=data; this.left=this.right=null; }} function printOddNodes(root){ // Base Case if (root == null) return; // Create an empty queue for level // order traversal let q = []; // Enqueue root and initialize level as odd q.push(root); let isOdd = true; while (true) { // nodeCount (queue size) indicates // number of nodes at current level. let nodeCount = q.length; if (nodeCount == 0) break; // Dequeue all nodes of current level // and Enqueue all nodes of next level while (nodeCount > 0) { let node = q[0]; if (isOdd == true) document.write(node.data + " "); q.shift(); if (node.left != null) q.push(node.left); if (node.right != null) q.push(node.right); nodeCount--; } isOdd = !isOdd; }} // Driver codelet 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);printOddNodes(root); // This code is contributed by rag2127</script>
Output:
1 4 5
Time complexity : O(n) Auxiliary Space: O(n) for Queue Data Structure
YouTubeGeeksforGeeks507K subscribersPrint the nodes at odd levels of a tree | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 5:21•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=38Sm_29KJ3E" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
This article is contributed by Pranav. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
prerna saini
shrikanth13
PranchalKatiyar
SHUBHAMSINGH10
29AjayKumar
anikakapoor
rameshtravel07
rag2127
prasanna1995
simmytarika5
Accolite
tree-level-order
Tree
Accolite
Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Tree Traversals (Inorder, Preorder and Postorder)
Binary Tree | Set 1 (Introduction)
AVL Tree | Set 1 (Insertion)
Level Order Binary Tree Traversal
Binary Tree | Set 3 (Types of Binary Tree)
Inorder Tree Traversal without Recursion
Write a Program to Find the Maximum Depth or Height of a Tree
Binary Tree | Set 2 (Properties)
Decision Tree
A program to check if a binary tree is BST or not | [
{
"code": null,
"e": 37091,
"s": 37063,
"text": "\n16 Mar, 2022"
},
{
"code": null,
"e": 37183,
"s": 37091,
"text": "Given a binary tree, print nodes of odd level in any order. Root is considered at level 1. "
},
{
"code": null,
"e": 37357,
"s": 37183,
"text": "For example consider the following tree\n 1\n / \\\n 2 3\n / \\ \\\n 4 5 6\n / \\ /\n 7 8 9\n\nOutput 1 4 5 6"
},
{
"code": null,
"e": 37382,
"s": 37361,
"text": "Method 1 (Recursive)"
},
{
"code": null,
"e": 37523,
"s": 37382,
"text": "The idea is to pass initial level as odd and switch level flag in every recursive call. For every node, if odd flag is set, then print it. "
},
{
"code": null,
"e": 37527,
"s": 37523,
"text": "C++"
},
{
"code": null,
"e": 37532,
"s": 37527,
"text": "Java"
},
{
"code": null,
"e": 37540,
"s": 37532,
"text": "Python3"
},
{
"code": null,
"e": 37543,
"s": 37540,
"text": "C#"
},
{
"code": null,
"e": 37554,
"s": 37543,
"text": "Javascript"
},
{
"code": "// Recursive C++ program to print odd level nodes#include <bits/stdc++.h>using namespace std; struct Node { int data; Node* left, *right;}; void printOddNodes(Node *root, bool isOdd = true){ // If empty tree if (root == NULL) return; // If current node is of odd level if (isOdd) cout << root->data << \" \" ; // Recur for children with isOdd // switched. printOddNodes(root->left, !isOdd); printOddNodes(root->right, !isOdd);} // Utility method to create a nodestruct Node* newNode(int data){ struct Node* node = new Node; node->data = data; node->left = node->right = NULL; return (node);} // Driver codeint main(){ struct Node* root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); printOddNodes(root); return 0;}",
"e": 38425,
"s": 37554,
"text": null
},
{
"code": "// Recursive Java program to print odd level nodesclass GfG { static class Node { int data; Node left, right;} static void printOddNodes(Node root, boolean isOdd){ // If empty tree if (root == null) return; // If current node is of odd level if (isOdd == true) System.out.print(root.data + \" \"); // Recur for children with isOdd // switched. printOddNodes(root.left, !isOdd); printOddNodes(root.right, !isOdd);} // Utility method to create a nodestatic Node newNode(int data){ Node node = new Node(); node.data = data; node.left = null; node.right = null; return (node);} // Driver codepublic static void main(String[] args){ Node root = newNode(1); root.left = newNode(2); root.right = newNode(3); root.left.left = newNode(4); root.left.right = newNode(5); printOddNodes(root, true); }}",
"e": 39284,
"s": 38425,
"text": null
},
{
"code": "# Recursive Python3 program to print# odd level nodes # Utility method to create a nodeclass newNode: def __init__(self, data): self.data = data self.left = self.right = None def printOddNodes(root, isOdd = True): # If empty tree if (root == None): return # If current node is of odd level if (isOdd): print(root.data, end = \" \") # Recur for children with isOdd # switched. printOddNodes(root.left, not isOdd) printOddNodes(root.right, not isOdd) # Driver codeif __name__ == '__main__': root = newNode(1) root.left = newNode(2) root.right = newNode(3) root.left.left = newNode(4) root.left.right = newNode(5) printOddNodes(root) # This code is contributed by PranchalK",
"e": 40037,
"s": 39284,
"text": null
},
{
"code": "using System; // Recursive C# program to print odd level nodes public class GfG{ public class Node{ public int data; public Node left, right;} public static void printOddNodes(Node root, bool isOdd){ // If empty tree if (root == null) { return; } // If current node is of odd level if (isOdd == true) { Console.Write(root.data + \" \"); } // Recur for children with isOdd // switched. printOddNodes(root.left, !isOdd); printOddNodes(root.right, !isOdd);} // Utility method to create a node public static Node newNode(int data){ Node node = new Node(); node.data = data; node.left = null; node.right = null; return (node);} // Driver code public static void Main(string[] args){ Node root = newNode(1); root.left = newNode(2); root.right = newNode(3); root.left.left = newNode(4); root.left.right = newNode(5); printOddNodes(root, true); }} // This code is contributed by Shrikant13",
"e": 41004,
"s": 40037,
"text": null
},
{
"code": "<script> // Recursive JavaScript program to print odd level nodes class Node { constructor(data) { this.left = null; this.right = null; this.data = data; } } function printOddNodes(root, isOdd) { // If empty tree if (root == null) return; // If current node is of odd level if (isOdd == true) document.write(root.data + \" \"); // Recur for children with isOdd // switched. printOddNodes(root.left, !isOdd); printOddNodes(root.right, !isOdd); } // Utility method to create a node function newNode(data) { let node = new Node(data); return (node); } let root = newNode(1); root.left = newNode(2); root.right = newNode(3); root.left.left = newNode(4); root.left.right = newNode(5); printOddNodes(root, true); </script>",
"e": 41921,
"s": 41004,
"text": null
},
{
"code": null,
"e": 41931,
"s": 41921,
"text": "Output: "
},
{
"code": null,
"e": 41937,
"s": 41931,
"text": "1 4 5"
},
{
"code": null,
"e": 42030,
"s": 41937,
"text": "Time complexity : O(n)Auxiliary Space: O(n) for Recursive Stack Space in case of Skewed Tree"
},
{
"code": null,
"e": 42051,
"s": 42030,
"text": "Method 2 (Iterative)"
},
{
"code": null,
"e": 42313,
"s": 42051,
"text": "The above code prints nodes in preorder way. If we wish to print nodes level by level, we can use level order traversal. The idea is based on Print level order traversal line by lineWe traverse nodes level by level. We switch odd level flag after every level. "
},
{
"code": null,
"e": 42317,
"s": 42313,
"text": "C++"
},
{
"code": null,
"e": 42322,
"s": 42317,
"text": "Java"
},
{
"code": null,
"e": 42330,
"s": 42322,
"text": "Python3"
},
{
"code": null,
"e": 42333,
"s": 42330,
"text": "C#"
},
{
"code": null,
"e": 42344,
"s": 42333,
"text": "Javascript"
},
{
"code": "// Iterative C++ program to print odd level nodes#include <bits/stdc++.h>using namespace std; struct Node { int data; Node* left, *right;}; // Iterative method to do level order traversal line by linevoid printOddNodes(Node *root){ // Base Case if (root == NULL) return; // Create an empty queue for level // order traversal queue<Node *> q; // Enqueue root and initialize level as odd q.push(root); bool isOdd = true; while (1) { // nodeCount (queue size) indicates // number of nodes at current level. int nodeCount = q.size(); if (nodeCount == 0) break; // Dequeue all nodes of current level // and Enqueue all nodes of next level while (nodeCount > 0) { Node *node = q.front(); if (isOdd) cout << node->data << \" \"; q.pop(); if (node->left != NULL) q.push(node->left); if (node->right != NULL) q.push(node->right); nodeCount--; } isOdd = !isOdd; }} // Utility method to create a nodestruct Node* newNode(int data){ struct Node* node = new Node; node->data = data; node->left = node->right = NULL; return (node);} // Driver codeint main(){ struct Node* root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); printOddNodes(root); return 0;}",
"e": 43836,
"s": 42344,
"text": null
},
{
"code": "// Iterative Java program to print odd level nodesimport java.util.*;class GfG { static class Node { int data; Node left, right;} // Iterative method to do level order traversal line by linestatic void printOddNodes(Node root){ // Base Case if (root == null) return; // Create an empty queue for level // order traversal Queue<Node> q = new LinkedList<Node> (); // Enqueue root and initialize level as odd q.add(root); boolean isOdd = true; while (true) { // nodeCount (queue size) indicates // number of nodes at current level. int nodeCount = q.size(); if (nodeCount == 0) break; // Dequeue all nodes of current level // and Enqueue all nodes of next level while (nodeCount > 0) { Node node = q.peek(); if (isOdd == true) System.out.print(node.data + \" \"); q.remove(); if (node.left != null) q.add(node.left); if (node.right != null) q.add(node.right); nodeCount--; } isOdd = !isOdd; }} // Utility method to create a nodestatic Node newNode(int data){ Node node = new Node(); node.data = data; node.left = null; node.right = null; return (node);} // Driver codepublic static void main(String[] args){ Node root = newNode(1); root.left = newNode(2); root.right = newNode(3); root.left.left = newNode(4); root.left.right = newNode(5); printOddNodes(root);}}",
"e": 45359,
"s": 43836,
"text": null
},
{
"code": "# Iterative Python3 program to print odd# level nodes # A Binary Tree Node# Utility function to create a# new tree Nodeclass newNode: def __init__(self, data): self.data = data self.left = self.right = None # Iterative method to do level order# traversal line by linedef printOddNodes(root) : # Base Case if (root == None): return # Create an empty queue for # level order traversal q = [] # Enqueue root and initialize # level as odd q.append(root) isOdd = True while (1) : # nodeCount (queue size) indicates # number of nodes at current level. nodeCount = len(q) if (nodeCount == 0) : break # Dequeue all nodes of current level # and Enqueue all nodes of next level while (nodeCount > 0): node = q[0] if (isOdd): print(node.data, end = \" \") q.pop(0) if (node.left != None) : q.append(node.left) if (node.right != None) : q.append(node.right) nodeCount -= 1 isOdd = not isOdd # Driver Codeif __name__ == '__main__': root = newNode(1) root.left = newNode(2) root.right = newNode(3) root.left.left = newNode(4) root.left.right = newNode(5) printOddNodes(root) # This code is contributed# by SHUBHAMSINGH10",
"e": 46755,
"s": 45359,
"text": null
},
{
"code": "// Iterative C# program to// print odd level nodesusing System;using System.Collections.Generic; public class GfG{ public class Node { public int data; public Node left, right; } // Iterative method to do level // order traversal line by line static void printOddNodes(Node root) { // Base Case if (root == null) return; // Create an empty queue for level // order traversal Queue<Node> q = new Queue<Node> (); // Enqueue root and initialize level as odd q.Enqueue(root); bool isOdd = true; while (true) { // nodeCount (queue size) indicates // number of nodes at current level. int nodeCount = q.Count; if (nodeCount == 0) break; // Dequeue all nodes of current level // and Enqueue all nodes of next level while (nodeCount > 0) { Node node = q.Peek(); if (isOdd == true) Console.Write(node.data + \" \"); q.Dequeue(); if (node.left != null) q.Enqueue(node.left); if (node.right != null) q.Enqueue(node.right); nodeCount--; } isOdd = !isOdd; } } // Utility method to create a node static Node newNode(int data) { Node node = new Node(); node.data = data; node.left = null; node.right = null; return (node); } // Driver code public static void Main(String[] args) { Node root = newNode(1); root.left = newNode(2); root.right = newNode(3); root.left.left = newNode(4); root.left.right = newNode(5); printOddNodes(root); }} // This code has been contributed// by 29AjayKumar",
"e": 48621,
"s": 46755,
"text": null
},
{
"code": "<script>// Iterative Javascript program to print odd level nodes class Node{ constructor(data) { this.data=data; this.left=this.right=null; }} function printOddNodes(root){ // Base Case if (root == null) return; // Create an empty queue for level // order traversal let q = []; // Enqueue root and initialize level as odd q.push(root); let isOdd = true; while (true) { // nodeCount (queue size) indicates // number of nodes at current level. let nodeCount = q.length; if (nodeCount == 0) break; // Dequeue all nodes of current level // and Enqueue all nodes of next level while (nodeCount > 0) { let node = q[0]; if (isOdd == true) document.write(node.data + \" \"); q.shift(); if (node.left != null) q.push(node.left); if (node.right != null) q.push(node.right); nodeCount--; } isOdd = !isOdd; }} // Driver codelet 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);printOddNodes(root); // This code is contributed by rag2127</script>",
"e": 49889,
"s": 48621,
"text": null
},
{
"code": null,
"e": 49899,
"s": 49889,
"text": "Output: "
},
{
"code": null,
"e": 49905,
"s": 49899,
"text": "1 4 5"
},
{
"code": null,
"e": 49976,
"s": 49905,
"text": "Time complexity : O(n) Auxiliary Space: O(n) for Queue Data Structure "
},
{
"code": null,
"e": 50814,
"s": 49976,
"text": "YouTubeGeeksforGeeks507K subscribersPrint the nodes at odd levels of a tree | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 5:21•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=38Sm_29KJ3E\" 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": 51229,
"s": 50814,
"text": "This article is contributed by Pranav. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 51242,
"s": 51229,
"text": "prerna saini"
},
{
"code": null,
"e": 51254,
"s": 51242,
"text": "shrikanth13"
},
{
"code": null,
"e": 51270,
"s": 51254,
"text": "PranchalKatiyar"
},
{
"code": null,
"e": 51285,
"s": 51270,
"text": "SHUBHAMSINGH10"
},
{
"code": null,
"e": 51297,
"s": 51285,
"text": "29AjayKumar"
},
{
"code": null,
"e": 51309,
"s": 51297,
"text": "anikakapoor"
},
{
"code": null,
"e": 51324,
"s": 51309,
"text": "rameshtravel07"
},
{
"code": null,
"e": 51332,
"s": 51324,
"text": "rag2127"
},
{
"code": null,
"e": 51345,
"s": 51332,
"text": "prasanna1995"
},
{
"code": null,
"e": 51358,
"s": 51345,
"text": "simmytarika5"
},
{
"code": null,
"e": 51367,
"s": 51358,
"text": "Accolite"
},
{
"code": null,
"e": 51384,
"s": 51367,
"text": "tree-level-order"
},
{
"code": null,
"e": 51389,
"s": 51384,
"text": "Tree"
},
{
"code": null,
"e": 51398,
"s": 51389,
"text": "Accolite"
},
{
"code": null,
"e": 51403,
"s": 51398,
"text": "Tree"
},
{
"code": null,
"e": 51501,
"s": 51403,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 51551,
"s": 51501,
"text": "Tree Traversals (Inorder, Preorder and Postorder)"
},
{
"code": null,
"e": 51586,
"s": 51551,
"text": "Binary Tree | Set 1 (Introduction)"
},
{
"code": null,
"e": 51615,
"s": 51586,
"text": "AVL Tree | Set 1 (Insertion)"
},
{
"code": null,
"e": 51649,
"s": 51615,
"text": "Level Order Binary Tree Traversal"
},
{
"code": null,
"e": 51692,
"s": 51649,
"text": "Binary Tree | Set 3 (Types of Binary Tree)"
},
{
"code": null,
"e": 51733,
"s": 51692,
"text": "Inorder Tree Traversal without Recursion"
},
{
"code": null,
"e": 51795,
"s": 51733,
"text": "Write a Program to Find the Maximum Depth or Height of a Tree"
},
{
"code": null,
"e": 51828,
"s": 51795,
"text": "Binary Tree | Set 2 (Properties)"
},
{
"code": null,
"e": 51842,
"s": 51828,
"text": "Decision Tree"
}
] |
Python | Filter a list based on the given list of strings - GeeksforGeeks | 25 Jun, 2019
Given a List, the task is to filter elements from list based on another list of strings. These type of problems are quite common while scraping websites.
Examples:
Input:
List_string1 = ['key', 'keys', 'keyword', 'keychain', 'keynote']
List_string2 = ['home/key/1.pdf',
'home/keys/2.pdf',
'home/keyword/3.pdf',
'home/keychain/4.pdf',
'home/Desktop/5.pdf',
'home/keynote/6.pdf']
Output:
['home/Desktop/5.pdf']
Explanation: We filter only those element from
list_string2 that do not have string in list_string1
Below are some ways to achieve the above task.
Method #1: Using Iteration
# Python code to filter element from list # based on another list of string. # List InitializationInput = ['key', 'keys', 'keyword', 'keychain', 'keynote']Input_string = ['home/key/1.pdf', 'home/keys/2.pdf', 'home/keyword/3.pdf', 'home/keychain/4.pdf', 'home/Desktop/5.pdf', 'home/keynote/6.pdf'] Output = Input_string.copy()temp = [] # Using iterationfor elem in Input_string: for n in Input: if n in elem: temp.append(elem) for elem in temp: if elem in Output: Output.remove(elem) # Printingprint("List of keywords are:", Input)print("Given list:", Input_string)print("filtered list is :", Output)
List of keywords are: [‘key’, ‘keys’, ‘keyword’, ‘keychain’, ‘keynote’]Given list: [‘home/key/1.pdf’, ‘home/keys/2.pdf’, ‘home/keyword/3.pdf’, ‘home/keychain/4.pdf’, ‘home/Desktop/5.pdf’, ‘home/keynote/6.pdf’]filtered list is : [‘home/Desktop/5.pdf’]
Method #2: Using list comprehension
# Python code to filter element from list # based on another list of string. # List InitializationInput = ['key', 'keys', 'keyword', 'keychain', 'keynote']Input_string = ['home/key/1.pdf', 'home/keys/2.pdf', 'home/keyword/3.pdf', 'home/keychain/4.pdf', 'home/Desktop/5.pdf', 'home/keynote/6.pdf'] # Using list comprehensionOutput = [b for b in Input_string if all(a not in b for a in Input)] # Printingprint("List of keywords are:", Input)print("Given list:", Input_string)print("filtered list is :", Output)
List of keywords are: [‘key’, ‘keys’, ‘keyword’, ‘keychain’, ‘keynote’]Given list: [‘home/key/1.pdf’, ‘home/keys/2.pdf’, ‘home/keyword/3.pdf’, ‘home/keychain/4.pdf’, ‘home/Desktop/5.pdf’, ‘home/keynote/6.pdf’]filtered list is : [‘home/Desktop/5.pdf’]
Python list-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": "\n25 Jun, 2019"
},
{
"code": null,
"e": 25691,
"s": 25537,
"text": "Given a List, the task is to filter elements from list based on another list of strings. These type of problems are quite common while scraping websites."
},
{
"code": null,
"e": 25701,
"s": 25691,
"text": "Examples:"
},
{
"code": null,
"e": 26097,
"s": 25701,
"text": "Input:\nList_string1 = ['key', 'keys', 'keyword', 'keychain', 'keynote']\nList_string2 = ['home/key/1.pdf',\n 'home/keys/2.pdf', \n 'home/keyword/3.pdf', \n 'home/keychain/4.pdf',\n 'home/Desktop/5.pdf', \n 'home/keynote/6.pdf']\nOutput:\n['home/Desktop/5.pdf']\n\nExplanation: We filter only those element from \nlist_string2 that do not have string in list_string1\n"
},
{
"code": null,
"e": 26144,
"s": 26097,
"text": "Below are some ways to achieve the above task."
},
{
"code": null,
"e": 26171,
"s": 26144,
"text": "Method #1: Using Iteration"
},
{
"code": "# Python code to filter element from list # based on another list of string. # List InitializationInput = ['key', 'keys', 'keyword', 'keychain', 'keynote']Input_string = ['home/key/1.pdf', 'home/keys/2.pdf', 'home/keyword/3.pdf', 'home/keychain/4.pdf', 'home/Desktop/5.pdf', 'home/keynote/6.pdf'] Output = Input_string.copy()temp = [] # Using iterationfor elem in Input_string: for n in Input: if n in elem: temp.append(elem) for elem in temp: if elem in Output: Output.remove(elem) # Printingprint(\"List of keywords are:\", Input)print(\"Given list:\", Input_string)print(\"filtered list is :\", Output)",
"e": 26852,
"s": 26171,
"text": null
},
{
"code": null,
"e": 27103,
"s": 26852,
"text": "List of keywords are: [‘key’, ‘keys’, ‘keyword’, ‘keychain’, ‘keynote’]Given list: [‘home/key/1.pdf’, ‘home/keys/2.pdf’, ‘home/keyword/3.pdf’, ‘home/keychain/4.pdf’, ‘home/Desktop/5.pdf’, ‘home/keynote/6.pdf’]filtered list is : [‘home/Desktop/5.pdf’]"
},
{
"code": null,
"e": 27140,
"s": 27103,
"text": " Method #2: Using list comprehension"
},
{
"code": "# Python code to filter element from list # based on another list of string. # List InitializationInput = ['key', 'keys', 'keyword', 'keychain', 'keynote']Input_string = ['home/key/1.pdf', 'home/keys/2.pdf', 'home/keyword/3.pdf', 'home/keychain/4.pdf', 'home/Desktop/5.pdf', 'home/keynote/6.pdf'] # Using list comprehensionOutput = [b for b in Input_string if all(a not in b for a in Input)] # Printingprint(\"List of keywords are:\", Input)print(\"Given list:\", Input_string)print(\"filtered list is :\", Output)",
"e": 27705,
"s": 27140,
"text": null
},
{
"code": null,
"e": 27956,
"s": 27705,
"text": "List of keywords are: [‘key’, ‘keys’, ‘keyword’, ‘keychain’, ‘keynote’]Given list: [‘home/key/1.pdf’, ‘home/keys/2.pdf’, ‘home/keyword/3.pdf’, ‘home/keychain/4.pdf’, ‘home/Desktop/5.pdf’, ‘home/keynote/6.pdf’]filtered list is : [‘home/Desktop/5.pdf’]"
},
{
"code": null,
"e": 27977,
"s": 27956,
"text": "Python list-programs"
},
{
"code": null,
"e": 27984,
"s": 27977,
"text": "Python"
},
{
"code": null,
"e": 28000,
"s": 27984,
"text": "Python Programs"
},
{
"code": null,
"e": 28098,
"s": 28000,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28130,
"s": 28098,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28172,
"s": 28130,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 28214,
"s": 28172,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 28270,
"s": 28214,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 28297,
"s": 28270,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 28319,
"s": 28297,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 28358,
"s": 28319,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 28404,
"s": 28358,
"text": "Python | Split string into list of characters"
},
{
"code": null,
"e": 28442,
"s": 28404,
"text": "Python | Convert a list to dictionary"
}
] |
p5.js | redraw() Function - GeeksforGeeks | 23 Aug, 2019
The redraw() function is used to execute the code within draw() function one time. This functions is used to update the display window only when it necessary. The redraw() function does not work when it is called inside the draw() function. The loop() and noLoop() function is used to enable/disable the animations.
Syntax:
redraw( n )
Parameters: This function accepts single parameter n which is used to set the redraw for n times. The default value of this function is 1.
Below example illustrates the redraw() function in p5.js:
Example:
let l = 0; function setup() { // Create canvas of given size createCanvas(500, 300); // Set the background color background('green'); } function draw() { // Set the stroke color stroke('black'); // Function to draw the line line(l, 0, l, height); } function mousePressed() { l += 1; redraw();}
Output:
JavaScript-p5.js
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Difference between var, let and const keywords in JavaScript
Difference Between PUT and PATCH Request
JavaScript | Promises
How to get character array from string in JavaScript?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Difference between var, let and const keywords in JavaScript | [
{
"code": null,
"e": 26627,
"s": 26599,
"text": "\n23 Aug, 2019"
},
{
"code": null,
"e": 26943,
"s": 26627,
"text": "The redraw() function is used to execute the code within draw() function one time. This functions is used to update the display window only when it necessary. The redraw() function does not work when it is called inside the draw() function. The loop() and noLoop() function is used to enable/disable the animations."
},
{
"code": null,
"e": 26951,
"s": 26943,
"text": "Syntax:"
},
{
"code": null,
"e": 26963,
"s": 26951,
"text": "redraw( n )"
},
{
"code": null,
"e": 27102,
"s": 26963,
"text": "Parameters: This function accepts single parameter n which is used to set the redraw for n times. The default value of this function is 1."
},
{
"code": null,
"e": 27160,
"s": 27102,
"text": "Below example illustrates the redraw() function in p5.js:"
},
{
"code": null,
"e": 27169,
"s": 27160,
"text": "Example:"
},
{
"code": "let l = 0; function setup() { // Create canvas of given size createCanvas(500, 300); // Set the background color background('green'); } function draw() { // Set the stroke color stroke('black'); // Function to draw the line line(l, 0, l, height); } function mousePressed() { l += 1; redraw();}",
"e": 27496,
"s": 27169,
"text": null
},
{
"code": null,
"e": 27504,
"s": 27496,
"text": "Output:"
},
{
"code": null,
"e": 27521,
"s": 27504,
"text": "JavaScript-p5.js"
},
{
"code": null,
"e": 27532,
"s": 27521,
"text": "JavaScript"
},
{
"code": null,
"e": 27549,
"s": 27532,
"text": "Web Technologies"
},
{
"code": null,
"e": 27647,
"s": 27549,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27687,
"s": 27647,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 27748,
"s": 27687,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 27789,
"s": 27748,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 27811,
"s": 27789,
"text": "JavaScript | Promises"
},
{
"code": null,
"e": 27865,
"s": 27811,
"text": "How to get character array from string in JavaScript?"
},
{
"code": null,
"e": 27905,
"s": 27865,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 27938,
"s": 27905,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 27981,
"s": 27938,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 28031,
"s": 27981,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
Compute the Value of Poisson Density in R Programming - dpois() Function - GeeksforGeeks | 04 Jan, 2022
dpois() function in R Language is used to compute the Poisson Density for a set of Integer values. It also creates a density plot of poisson distribution.
Syntax: dpois(vec, lambda)Parameters: vec: Sequence of integer values lambda: Average number of events per interval
Example 1:
Python3
# R program to compute# Poisson Density # Sequence of x-valuesx <- seq(-10, 10, by = 1) # Calling dpois() Functiony <- dpois(x, lambda = 5)y
Output:
[1] 0.000000000 0.000000000 0.000000000 0.000000000 0.000000000 0.000000000
[7] 0.000000000 0.000000000 0.000000000 0.000000000 0.006737947 0.033689735
[13] 0.084224337 0.140373896 0.175467370 0.175467370 0.146222808 0.104444863
[19] 0.065278039 0.036265577 0.018132789
Example 2:
Python3
# R program to compute# Poisson Density # Sequence of x-valuesx <- seq(-10, 20, by = 1) # Calling dpois() Functiony <- dpois(x, lambda = 15) # Plot a graphplot(y)
Output:
nnr223442
R Statistics-Function
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Replace specific values in column in R DataFrame ?
Filter data by multiple conditions in R using Dplyr
Loops in R (for, while, repeat)
Change Color of Bars in Barchart using ggplot2 in R
How to change Row Names of DataFrame in R ?
Group by function in R using Dplyr
How to Change Axis Scales in R Plots?
Printing Output of an R Program
How to Split Column Into Multiple Columns in R DataFrame?
K-Means Clustering in R Programming | [
{
"code": null,
"e": 26561,
"s": 26533,
"text": "\n04 Jan, 2022"
},
{
"code": null,
"e": 26717,
"s": 26561,
"text": "dpois() function in R Language is used to compute the Poisson Density for a set of Integer values. It also creates a density plot of poisson distribution. "
},
{
"code": null,
"e": 26834,
"s": 26717,
"text": "Syntax: dpois(vec, lambda)Parameters: vec: Sequence of integer values lambda: Average number of events per interval "
},
{
"code": null,
"e": 26846,
"s": 26834,
"text": "Example 1: "
},
{
"code": null,
"e": 26854,
"s": 26846,
"text": "Python3"
},
{
"code": "# R program to compute# Poisson Density # Sequence of x-valuesx <- seq(-10, 10, by = 1) # Calling dpois() Functiony <- dpois(x, lambda = 5)y",
"e": 26995,
"s": 26854,
"text": null
},
{
"code": null,
"e": 27004,
"s": 26995,
"text": "Output: "
},
{
"code": null,
"e": 27276,
"s": 27004,
"text": " [1] 0.000000000 0.000000000 0.000000000 0.000000000 0.000000000 0.000000000\n [7] 0.000000000 0.000000000 0.000000000 0.000000000 0.006737947 0.033689735\n[13] 0.084224337 0.140373896 0.175467370 0.175467370 0.146222808 0.104444863\n[19] 0.065278039 0.036265577 0.018132789"
},
{
"code": null,
"e": 27288,
"s": 27276,
"text": "Example 2: "
},
{
"code": null,
"e": 27296,
"s": 27288,
"text": "Python3"
},
{
"code": "# R program to compute# Poisson Density # Sequence of x-valuesx <- seq(-10, 20, by = 1) # Calling dpois() Functiony <- dpois(x, lambda = 15) # Plot a graphplot(y)",
"e": 27459,
"s": 27296,
"text": null
},
{
"code": null,
"e": 27468,
"s": 27459,
"text": "Output: "
},
{
"code": null,
"e": 27478,
"s": 27468,
"text": "nnr223442"
},
{
"code": null,
"e": 27500,
"s": 27478,
"text": "R Statistics-Function"
},
{
"code": null,
"e": 27511,
"s": 27500,
"text": "R Language"
},
{
"code": null,
"e": 27609,
"s": 27511,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27667,
"s": 27609,
"text": "How to Replace specific values in column in R DataFrame ?"
},
{
"code": null,
"e": 27719,
"s": 27667,
"text": "Filter data by multiple conditions in R using Dplyr"
},
{
"code": null,
"e": 27751,
"s": 27719,
"text": "Loops in R (for, while, repeat)"
},
{
"code": null,
"e": 27803,
"s": 27751,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 27847,
"s": 27803,
"text": "How to change Row Names of DataFrame in R ?"
},
{
"code": null,
"e": 27882,
"s": 27847,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 27920,
"s": 27882,
"text": "How to Change Axis Scales in R Plots?"
},
{
"code": null,
"e": 27952,
"s": 27920,
"text": "Printing Output of an R Program"
},
{
"code": null,
"e": 28010,
"s": 27952,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
}
] |
How to record and play audio in JavaScript ? - GeeksforGeeks | 24 Mar, 2022
JavaScript is a very flexible language and it provides many API support to do many useful things. Here one important thing is that record audio or video in web pages is also done using JavaScript. In this case, it will ask the user for microphone access to the browser and record the audio through the microphone and save the audio data chunks in form of binary value in an array and when we play the audio then retrieve chuck data and start playing. The same thing happens for video also, when we do video conferences then this actually happens in the server, only thing is that here we play the video at the same page, and in case of video conference the video will play at the other end.
This whole thing happens using an API, which is MediaRecorder API. This API provides functionality to record media such as audio or video. It is created using the MediaRecorder() constructor.
Here we use one property of JavaScript, which is mediaDevices property, which is used to get access to connected input media devices like microphones, webcams, etc. This property uses a method getUserMedia() to get permission for accessing the microphone, webcam etc. This method returns a promise to the navigator object.
The Promises are as follows:
If true:
resolve : If all permissions are achieved and the microphone or camera are working fine, then it returns a MediaStream object. This is the main recorded data.
If false:
NotAllowedError: If the user reject the permission for recording.
NotFoundError: If there is no media track.
NotReadableError: If the input devices are not found or the hardware is not working.
OverconstrainedError: If constraint audio settings are preventing.
AbortError: If generic unknown cause is found.
TypeError: If audio: false stated in the Javascript code.
Example:
javascript
<!DOCTYPE html><html> <head> <script> let audioIN = { audio: true }; // audio is true, for recording // Access the permission for use // the microphone navigator.mediaDevices.getUserMedia(audioIN) // 'then()' method returns a Promise .then(function (mediaStreamObj) { // Connect the media stream to the // first audio element let audio = document.querySelector('audio'); //returns the recorded audio via 'audio' tag // 'srcObject' is a property which // takes the media object // This is supported in the newer browsers if ("srcObject" in audio) { audio.srcObject = mediaStreamObj; } else { // Old version audio.src = window.URL .createObjectURL(mediaStreamObj); } // It will play the audio audio.onloadedmetadata = function (ev) { // Play the audio in the 2nd audio // element what is being recorded audio.play(); }; // Start record let start = document.getElementById('btnStart'); // Stop record let stop = document.getElementById('btnStop'); // 2nd audio tag for play the audio let playAudio = document.getElementById('adioPlay'); // This is the main thing to recorded // the audio 'MediaRecorder' API let mediaRecorder = new MediaRecorder(mediaStreamObj); // Pass the audio stream // Start event start.addEventListener('click', function (ev) { mediaRecorder.start(); // console.log(mediaRecorder.state); }) // Stop event stop.addEventListener('click', function (ev) { mediaRecorder.stop(); // console.log(mediaRecorder.state); }); // If audio data available then push // it to the chunk array mediaRecorder.ondataavailable = function (ev) { dataArray.push(ev.data); } // Chunk array to store the audio data let dataArray = []; // Convert the audio data in to blob // after stopping the recording mediaRecorder.onstop = function (ev) { // blob of type mp3 let audioData = new Blob(dataArray, { 'type': 'audio/mp3;' }); // After fill up the chunk // array make it empty dataArray = []; // Creating audio url with reference // of created blob named 'audioData' let audioSrc = window.URL .createObjectURL(audioData); // Pass the audio url to the 2nd video tag playAudio.src = audioSrc; } }) // If any error occurs then handles the error .catch(function (err) { console.log(err.name, err.message); }); </script></head> <body style="background-color:rgb(101, 185, 17); "> <header> <h1>Record and Play Audio in JavaScript</h1> </header> <!--button for 'start recording'--> <p> <button id="btnStart">START RECORDING</button> <button id="btnStop">STOP RECORDING</button> <!--button for 'stop recording'--> </p> <!--for record--> <audio controls></audio> <!--'controls' use for add play, pause, and volume--> <!--for play the audio--> <audio id="audioPlay" controls></audio></body> </html>
Output:
simmytarika5
surinderdawra388
HTML-Misc
JavaScript-Misc
Picked
HTML
JavaScript
Web Technologies
Web technologies Questions
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to update Node.js and NPM to next version ?
How to Insert Form Data into Database using PHP ?
REST API (Introduction)
Types of CSS (Cascading Style Sheet)
Form validation using HTML and JavaScript
Convert a string to an integer in JavaScript
How to calculate the number of days between two dates in javascript?
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
File uploading in React.js | [
{
"code": null,
"e": 24216,
"s": 24188,
"text": "\n24 Mar, 2022"
},
{
"code": null,
"e": 24907,
"s": 24216,
"text": "JavaScript is a very flexible language and it provides many API support to do many useful things. Here one important thing is that record audio or video in web pages is also done using JavaScript. In this case, it will ask the user for microphone access to the browser and record the audio through the microphone and save the audio data chunks in form of binary value in an array and when we play the audio then retrieve chuck data and start playing. The same thing happens for video also, when we do video conferences then this actually happens in the server, only thing is that here we play the video at the same page, and in case of video conference the video will play at the other end."
},
{
"code": null,
"e": 25099,
"s": 24907,
"text": "This whole thing happens using an API, which is MediaRecorder API. This API provides functionality to record media such as audio or video. It is created using the MediaRecorder() constructor."
},
{
"code": null,
"e": 25422,
"s": 25099,
"text": "Here we use one property of JavaScript, which is mediaDevices property, which is used to get access to connected input media devices like microphones, webcams, etc. This property uses a method getUserMedia() to get permission for accessing the microphone, webcam etc. This method returns a promise to the navigator object."
},
{
"code": null,
"e": 25451,
"s": 25422,
"text": "The Promises are as follows:"
},
{
"code": null,
"e": 25460,
"s": 25451,
"text": "If true:"
},
{
"code": null,
"e": 25619,
"s": 25460,
"text": "resolve : If all permissions are achieved and the microphone or camera are working fine, then it returns a MediaStream object. This is the main recorded data."
},
{
"code": null,
"e": 25629,
"s": 25619,
"text": "If false:"
},
{
"code": null,
"e": 25695,
"s": 25629,
"text": "NotAllowedError: If the user reject the permission for recording."
},
{
"code": null,
"e": 25738,
"s": 25695,
"text": "NotFoundError: If there is no media track."
},
{
"code": null,
"e": 25823,
"s": 25738,
"text": "NotReadableError: If the input devices are not found or the hardware is not working."
},
{
"code": null,
"e": 25890,
"s": 25823,
"text": "OverconstrainedError: If constraint audio settings are preventing."
},
{
"code": null,
"e": 25937,
"s": 25890,
"text": "AbortError: If generic unknown cause is found."
},
{
"code": null,
"e": 25995,
"s": 25937,
"text": "TypeError: If audio: false stated in the Javascript code."
},
{
"code": null,
"e": 26005,
"s": 25995,
"text": "Example: "
},
{
"code": null,
"e": 26016,
"s": 26005,
"text": "javascript"
},
{
"code": "<!DOCTYPE html><html> <head> <script> let audioIN = { audio: true }; // audio is true, for recording // Access the permission for use // the microphone navigator.mediaDevices.getUserMedia(audioIN) // 'then()' method returns a Promise .then(function (mediaStreamObj) { // Connect the media stream to the // first audio element let audio = document.querySelector('audio'); //returns the recorded audio via 'audio' tag // 'srcObject' is a property which // takes the media object // This is supported in the newer browsers if (\"srcObject\" in audio) { audio.srcObject = mediaStreamObj; } else { // Old version audio.src = window.URL .createObjectURL(mediaStreamObj); } // It will play the audio audio.onloadedmetadata = function (ev) { // Play the audio in the 2nd audio // element what is being recorded audio.play(); }; // Start record let start = document.getElementById('btnStart'); // Stop record let stop = document.getElementById('btnStop'); // 2nd audio tag for play the audio let playAudio = document.getElementById('adioPlay'); // This is the main thing to recorded // the audio 'MediaRecorder' API let mediaRecorder = new MediaRecorder(mediaStreamObj); // Pass the audio stream // Start event start.addEventListener('click', function (ev) { mediaRecorder.start(); // console.log(mediaRecorder.state); }) // Stop event stop.addEventListener('click', function (ev) { mediaRecorder.stop(); // console.log(mediaRecorder.state); }); // If audio data available then push // it to the chunk array mediaRecorder.ondataavailable = function (ev) { dataArray.push(ev.data); } // Chunk array to store the audio data let dataArray = []; // Convert the audio data in to blob // after stopping the recording mediaRecorder.onstop = function (ev) { // blob of type mp3 let audioData = new Blob(dataArray, { 'type': 'audio/mp3;' }); // After fill up the chunk // array make it empty dataArray = []; // Creating audio url with reference // of created blob named 'audioData' let audioSrc = window.URL .createObjectURL(audioData); // Pass the audio url to the 2nd video tag playAudio.src = audioSrc; } }) // If any error occurs then handles the error .catch(function (err) { console.log(err.name, err.message); }); </script></head> <body style=\"background-color:rgb(101, 185, 17); \"> <header> <h1>Record and Play Audio in JavaScript</h1> </header> <!--button for 'start recording'--> <p> <button id=\"btnStart\">START RECORDING</button> <button id=\"btnStop\">STOP RECORDING</button> <!--button for 'stop recording'--> </p> <!--for record--> <audio controls></audio> <!--'controls' use for add play, pause, and volume--> <!--for play the audio--> <audio id=\"audioPlay\" controls></audio></body> </html>",
"e": 29352,
"s": 26016,
"text": null
},
{
"code": null,
"e": 29362,
"s": 29352,
"text": "Output: "
},
{
"code": null,
"e": 29375,
"s": 29362,
"text": "simmytarika5"
},
{
"code": null,
"e": 29392,
"s": 29375,
"text": "surinderdawra388"
},
{
"code": null,
"e": 29402,
"s": 29392,
"text": "HTML-Misc"
},
{
"code": null,
"e": 29418,
"s": 29402,
"text": "JavaScript-Misc"
},
{
"code": null,
"e": 29425,
"s": 29418,
"text": "Picked"
},
{
"code": null,
"e": 29430,
"s": 29425,
"text": "HTML"
},
{
"code": null,
"e": 29441,
"s": 29430,
"text": "JavaScript"
},
{
"code": null,
"e": 29458,
"s": 29441,
"text": "Web Technologies"
},
{
"code": null,
"e": 29485,
"s": 29458,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 29490,
"s": 29485,
"text": "HTML"
},
{
"code": null,
"e": 29588,
"s": 29490,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29597,
"s": 29588,
"text": "Comments"
},
{
"code": null,
"e": 29610,
"s": 29597,
"text": "Old Comments"
},
{
"code": null,
"e": 29658,
"s": 29610,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 29708,
"s": 29658,
"text": "How to Insert Form Data into Database using PHP ?"
},
{
"code": null,
"e": 29732,
"s": 29708,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 29769,
"s": 29732,
"text": "Types of CSS (Cascading Style Sheet)"
},
{
"code": null,
"e": 29811,
"s": 29769,
"text": "Form validation using HTML and JavaScript"
},
{
"code": null,
"e": 29856,
"s": 29811,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 29925,
"s": 29856,
"text": "How to calculate the number of days between two dates in javascript?"
},
{
"code": null,
"e": 29986,
"s": 29925,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 30058,
"s": 29986,
"text": "Differences between Functional Components and Class Components in React"
}
] |
Dixon's Factorization Method with implementation - GeeksforGeeks | 30 Mar, 2020
Dixon’s Factorization method is an integer factorization algorithm. In this article, this method is explained to find the factors of a composite number.
Dixon Factorization is based on the well-known fact of number theory that:
If with it is likely that gcd(x – y, n) will be factor of n.
For example:
if N = 84923,by starting at 292, the first number greater than √N and counting up5052 mod 84923 = 256 = 162
So (505 – 16)(505 + 16) = 0 mod 84923.Computing the greatest common divisor of 505 – 16 and N using Euclid’s algorithm gives 163, which is a factor of N.
Dixon’s Factorization Algorithm:
Step 1: Choose a bound B and identify the factor base (P) of all primes less than or equal to B.
Step 2: Search for positive integer z, such that is B-Smooth.(1) B-Smooth: A positive integer is called B-Smooth if none of its prime factors is greater than B.For example:720 has prime factorization as 24 * 32 * 51Therefore 720 is 5 smooth because none of its prime factors is greater than 5.
(1)
B-Smooth: A positive integer is called B-Smooth if none of its prime factors is greater than B.For example:
720 has prime factorization as 24 * 32 * 51Therefore 720 is 5 smooth because none of its prime factors is greater than 5.
Step 3: After generating enough of these relations (generally few more than the size of P), we use the method of linear algebra (e.g Gaussian Elimination) to multiply together these relations. Repeat this step until we formed a sufficient number of smooth squares.
Step 4: After multiplying all these relations, we get the final equation say:a2 = b2 mod(N)
a2 = b2 mod(N)
Step 5: Therefore, the factors of the above equation can be determined as:GCD(a - b, N), GCD(a + b, N)
GCD(a - b, N), GCD(a + b, N)
Step by Step execution of the Dixon’s Factorization Algorithm:
Let’s say, we want to factor N = 23449 using bound B = 7. Therefore, the factor base P = {2, 3, 5, 7}.
Here, x = ceil(sqrt(n)) = 154. So, we search randomly for integers between 154 and N whose squares are B-Smooth.
As mentioned before, a positive integer is called B-Smooth if none of its prime factors is greater than B. So, let’s say, we find two numbers which are 970 and 8621 such that their none of their squares have prime factors greater than 7.
Starting here the first related squares we get are:9702 % 23499 = 2940 = 22 * 3 * 5 * 7286212 % 23499 = 11760 = 24 * 3 * 5 * 72
9702 % 23499 = 2940 = 22 * 3 * 5 * 72
86212 % 23499 = 11760 = 24 * 3 * 5 * 72
So, (970 * 8621)2 = (23 * 3 * 5 * 72)2 % 23499. That is:142562 = 58802 % 23499.
Now, we find:gcd(14256 - 5880, 23449) = 131
gcd(14256 + 5880, 23449) = 179
gcd(14256 - 5880, 23449) = 131
gcd(14256 + 5880, 23449) = 179
Therefore, the factors are:N = 131 * 179
Below is the implementation of the above approach:
C++
Python3
// C++ implementation of Dixon factorization algo#include<bits/stdc++.h>using namespace std;#include<vector> // Function to find the factors of a number// using the Dixon Factorization Algorithmvoid factor(int n){ // Factor base for the given number int base[4] = {2, 3, 5, 7}; // Starting from the ceil of the root // of the given number N int start = int(sqrt(n)); // Storing the related squares vector<vector<int> >pairs; // For every number from the square root // Till N int len=sizeof(base)/sizeof(base[0]); for(int i = start; i < n; i++) { vector<int> v; // Finding the related squares for(int j = 0; j < len; j++) { int lhs = ((int)pow(i,2))% n; int rhs = ((int)pow(base[j],2)) % n; // If the two numbers are the // related squares, then append // them to the array if(lhs == rhs) { v.push_back(i); v.push_back(base[j]); pairs.push_back(v); } } } vector<int>newvec; // For every pair in the array, compute the // GCD such that len = pairs.size(); for (int i = 0; i < len;i++){ int factor = __gcd(pairs[i][0] - pairs[i][1], n); // If we find a factor other than 1, then // appending it to the final factor array if(factor != 1) newvec.push_back(factor); } set<int>s; for (int i = 0; i < newvec.size(); i++) s.insert(newvec[i]); for(auto i = s.begin(); i != s.end(); i++) cout<<(*i)<<" ";} // Driver Codeint main(){ factor(23449);} // This code is contributed by chitranayal
# Python 3 implementation of Dixon factorization algo from math import sqrt, gcdimport numpy as np # Function to find the factors of a number# using the Dixon Factorization Algorithmdef factor(n): # Factor base for the given number base = [2, 3, 5, 7] # Starting from the ceil of the root # of the given number N start = int(sqrt(n)) # Storing the related squares pairs = [] # For every number from the square root # Till N for i in range(start, n): # Finding the related squares for j in range(len(base)): lhs = i**2 % n rhs = base[j]**2 % n # If the two numbers are the # related squares, then append # them to the array if(lhs == rhs): pairs.append([i, base[j]]) new = [] # For every pair in the array, compute the # GCD such that for i in range(len(pairs)): factor = gcd(pairs[i][0] - pairs[i][1], n) # If we find a factor other than 1, then # appending it to the final factor array if(factor != 1): new.append(factor) x = np.array(new) # Returning the unique factors in the array return(np.unique(x)) # Driver Codeif __name__ == "__main__": print(factor(23449))
[131 179]
ukasp
factor
number-theory
Numbers
Algorithms
Mathematical
number-theory
Mathematical
Numbers
Algorithms
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
DSA Sheet by Love Babbar
How to Start Learning DSA?
K means Clustering - Introduction
Types of Complexity Classes | P, NP, CoNP, NP hard and NP complete
Quadratic Probing in Hashing
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": 26027,
"s": 25999,
"text": "\n30 Mar, 2020"
},
{
"code": null,
"e": 26180,
"s": 26027,
"text": "Dixon’s Factorization method is an integer factorization algorithm. In this article, this method is explained to find the factors of a composite number."
},
{
"code": null,
"e": 26255,
"s": 26180,
"text": "Dixon Factorization is based on the well-known fact of number theory that:"
},
{
"code": null,
"e": 26318,
"s": 26255,
"text": "If with it is likely that gcd(x – y, n) will be factor of n."
},
{
"code": null,
"e": 26331,
"s": 26318,
"text": "For example:"
},
{
"code": null,
"e": 26439,
"s": 26331,
"text": "if N = 84923,by starting at 292, the first number greater than √N and counting up5052 mod 84923 = 256 = 162"
},
{
"code": null,
"e": 26593,
"s": 26439,
"text": "So (505 – 16)(505 + 16) = 0 mod 84923.Computing the greatest common divisor of 505 – 16 and N using Euclid’s algorithm gives 163, which is a factor of N."
},
{
"code": null,
"e": 26626,
"s": 26593,
"text": "Dixon’s Factorization Algorithm:"
},
{
"code": null,
"e": 26723,
"s": 26626,
"text": "Step 1: Choose a bound B and identify the factor base (P) of all primes less than or equal to B."
},
{
"code": null,
"e": 27020,
"s": 26723,
"text": "Step 2: Search for positive integer z, such that is B-Smooth.(1) B-Smooth: A positive integer is called B-Smooth if none of its prime factors is greater than B.For example:720 has prime factorization as 24 * 32 * 51Therefore 720 is 5 smooth because none of its prime factors is greater than 5."
},
{
"code": null,
"e": 27027,
"s": 27020,
"text": "(1) "
},
{
"code": null,
"e": 27135,
"s": 27027,
"text": "B-Smooth: A positive integer is called B-Smooth if none of its prime factors is greater than B.For example:"
},
{
"code": null,
"e": 27257,
"s": 27135,
"text": "720 has prime factorization as 24 * 32 * 51Therefore 720 is 5 smooth because none of its prime factors is greater than 5."
},
{
"code": null,
"e": 27522,
"s": 27257,
"text": "Step 3: After generating enough of these relations (generally few more than the size of P), we use the method of linear algebra (e.g Gaussian Elimination) to multiply together these relations. Repeat this step until we formed a sufficient number of smooth squares."
},
{
"code": null,
"e": 27615,
"s": 27522,
"text": "Step 4: After multiplying all these relations, we get the final equation say:a2 = b2 mod(N)\n"
},
{
"code": null,
"e": 27631,
"s": 27615,
"text": "a2 = b2 mod(N)\n"
},
{
"code": null,
"e": 27735,
"s": 27631,
"text": "Step 5: Therefore, the factors of the above equation can be determined as:GCD(a - b, N), GCD(a + b, N)\n"
},
{
"code": null,
"e": 27765,
"s": 27735,
"text": "GCD(a - b, N), GCD(a + b, N)\n"
},
{
"code": null,
"e": 27828,
"s": 27765,
"text": "Step by Step execution of the Dixon’s Factorization Algorithm:"
},
{
"code": null,
"e": 27931,
"s": 27828,
"text": "Let’s say, we want to factor N = 23449 using bound B = 7. Therefore, the factor base P = {2, 3, 5, 7}."
},
{
"code": null,
"e": 28044,
"s": 27931,
"text": "Here, x = ceil(sqrt(n)) = 154. So, we search randomly for integers between 154 and N whose squares are B-Smooth."
},
{
"code": null,
"e": 28282,
"s": 28044,
"text": "As mentioned before, a positive integer is called B-Smooth if none of its prime factors is greater than B. So, let’s say, we find two numbers which are 970 and 8621 such that their none of their squares have prime factors greater than 7."
},
{
"code": null,
"e": 28410,
"s": 28282,
"text": "Starting here the first related squares we get are:9702 % 23499 = 2940 = 22 * 3 * 5 * 7286212 % 23499 = 11760 = 24 * 3 * 5 * 72"
},
{
"code": null,
"e": 28448,
"s": 28410,
"text": "9702 % 23499 = 2940 = 22 * 3 * 5 * 72"
},
{
"code": null,
"e": 28488,
"s": 28448,
"text": "86212 % 23499 = 11760 = 24 * 3 * 5 * 72"
},
{
"code": null,
"e": 28568,
"s": 28488,
"text": "So, (970 * 8621)2 = (23 * 3 * 5 * 72)2 % 23499. That is:142562 = 58802 % 23499."
},
{
"code": null,
"e": 28643,
"s": 28568,
"text": "Now, we find:gcd(14256 - 5880, 23449) = 131\ngcd(14256 + 5880, 23449) = 179"
},
{
"code": null,
"e": 28705,
"s": 28643,
"text": "gcd(14256 - 5880, 23449) = 131\ngcd(14256 + 5880, 23449) = 179"
},
{
"code": null,
"e": 28746,
"s": 28705,
"text": "Therefore, the factors are:N = 131 * 179"
},
{
"code": null,
"e": 28797,
"s": 28746,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 28801,
"s": 28797,
"text": "C++"
},
{
"code": null,
"e": 28809,
"s": 28801,
"text": "Python3"
},
{
"code": "// C++ implementation of Dixon factorization algo#include<bits/stdc++.h>using namespace std;#include<vector> // Function to find the factors of a number// using the Dixon Factorization Algorithmvoid factor(int n){ // Factor base for the given number int base[4] = {2, 3, 5, 7}; // Starting from the ceil of the root // of the given number N int start = int(sqrt(n)); // Storing the related squares vector<vector<int> >pairs; // For every number from the square root // Till N int len=sizeof(base)/sizeof(base[0]); for(int i = start; i < n; i++) { vector<int> v; // Finding the related squares for(int j = 0; j < len; j++) { int lhs = ((int)pow(i,2))% n; int rhs = ((int)pow(base[j],2)) % n; // If the two numbers are the // related squares, then append // them to the array if(lhs == rhs) { v.push_back(i); v.push_back(base[j]); pairs.push_back(v); } } } vector<int>newvec; // For every pair in the array, compute the // GCD such that len = pairs.size(); for (int i = 0; i < len;i++){ int factor = __gcd(pairs[i][0] - pairs[i][1], n); // If we find a factor other than 1, then // appending it to the final factor array if(factor != 1) newvec.push_back(factor); } set<int>s; for (int i = 0; i < newvec.size(); i++) s.insert(newvec[i]); for(auto i = s.begin(); i != s.end(); i++) cout<<(*i)<<\" \";} // Driver Codeint main(){ factor(23449);} // This code is contributed by chitranayal",
"e": 30569,
"s": 28809,
"text": null
},
{
"code": "# Python 3 implementation of Dixon factorization algo from math import sqrt, gcdimport numpy as np # Function to find the factors of a number# using the Dixon Factorization Algorithmdef factor(n): # Factor base for the given number base = [2, 3, 5, 7] # Starting from the ceil of the root # of the given number N start = int(sqrt(n)) # Storing the related squares pairs = [] # For every number from the square root # Till N for i in range(start, n): # Finding the related squares for j in range(len(base)): lhs = i**2 % n rhs = base[j]**2 % n # If the two numbers are the # related squares, then append # them to the array if(lhs == rhs): pairs.append([i, base[j]]) new = [] # For every pair in the array, compute the # GCD such that for i in range(len(pairs)): factor = gcd(pairs[i][0] - pairs[i][1], n) # If we find a factor other than 1, then # appending it to the final factor array if(factor != 1): new.append(factor) x = np.array(new) # Returning the unique factors in the array return(np.unique(x)) # Driver Codeif __name__ == \"__main__\": print(factor(23449))",
"e": 31876,
"s": 30569,
"text": null
},
{
"code": null,
"e": 31887,
"s": 31876,
"text": "[131 179]\n"
},
{
"code": null,
"e": 31893,
"s": 31887,
"text": "ukasp"
},
{
"code": null,
"e": 31900,
"s": 31893,
"text": "factor"
},
{
"code": null,
"e": 31914,
"s": 31900,
"text": "number-theory"
},
{
"code": null,
"e": 31922,
"s": 31914,
"text": "Numbers"
},
{
"code": null,
"e": 31933,
"s": 31922,
"text": "Algorithms"
},
{
"code": null,
"e": 31946,
"s": 31933,
"text": "Mathematical"
},
{
"code": null,
"e": 31960,
"s": 31946,
"text": "number-theory"
},
{
"code": null,
"e": 31973,
"s": 31960,
"text": "Mathematical"
},
{
"code": null,
"e": 31981,
"s": 31973,
"text": "Numbers"
},
{
"code": null,
"e": 31992,
"s": 31981,
"text": "Algorithms"
},
{
"code": null,
"e": 32090,
"s": 31992,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32115,
"s": 32090,
"text": "DSA Sheet by Love Babbar"
},
{
"code": null,
"e": 32142,
"s": 32115,
"text": "How to Start Learning DSA?"
},
{
"code": null,
"e": 32176,
"s": 32142,
"text": "K means Clustering - Introduction"
},
{
"code": null,
"e": 32243,
"s": 32176,
"text": "Types of Complexity Classes | P, NP, CoNP, NP hard and NP complete"
},
{
"code": null,
"e": 32272,
"s": 32243,
"text": "Quadratic Probing in Hashing"
},
{
"code": null,
"e": 32302,
"s": 32272,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 32362,
"s": 32302,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 32377,
"s": 32362,
"text": "C++ Data Types"
},
{
"code": null,
"e": 32420,
"s": 32377,
"text": "Set in C++ Standard Template Library (STL)"
}
] |
Array range queries for searching an element - GeeksforGeeks | 21 Jun, 2021
Given an array of N elements and Q queries of the form L R X. For each query, you have to output if the element X exists in the array between the indices L and R(included).Prerequisite : Mo’s Algorithms Examples :
Input : N = 5
arr = [1, 1, 5, 4, 5]
Q = 3
1 3 2
2 5 1
3 5 5
Output : No
Yes
Yes
Explanation :
For the first query, 2 does not exist between the indices 1 and 3.
For the second query, 1 exists between the indices 2 and 5.
For the third query, 5 exists between the indices 3 and 5.
Naive Approach : The naive method would be to traverse the elements from L to R for each query, linearly searching for X. In the worst case, there can be N elements from L to R, hence the worst case time complexity for each query would be O(N). Therefore, for all the Q queries, the time complexity would turn out to be O(Q*N).Using Union-Find Method : This method checks only one element among all the consecutive equal values. If X is not equal to these values, then the algorithm skips all the other the other equal elements and continues traversal with the next different element. This algorithm is evidently useful only when there are consecutive equal elements in large amounts.Algorithm :
Merge all the consecutive equal elements in one group. While processing a query, start from R. Let index = R. Compare a[index] with X. If they are equal, then print “Yes” and break out of traversing the rest of the range. Else, skip all the consecutive elements belonging to the group of a[index]. Index becomes equal to one less than the index of the root of this group. Continue the above step either till X is found or till index becomes less than L. If index becomes less than L, print “No”.
Merge all the consecutive equal elements in one group.
While processing a query, start from R. Let index = R.
Compare a[index] with X. If they are equal, then print “Yes” and break out of traversing the rest of the range. Else, skip all the consecutive elements belonging to the group of a[index]. Index becomes equal to one less than the index of the root of this group.
Continue the above step either till X is found or till index becomes less than L.
If index becomes less than L, print “No”.
Below is the implementation of the above idea.
C++
Java
Python3
C#
Javascript
// Program to determine if the element// exists for different range queries#include <bits/stdc++.h>using namespace std; // Structure to represent a query rangestruct Query{ int L, R, X;}; const int maxn = 100; int root[maxn]; // Find the root of the group containing// the element at index xint find(int x){ return x == root[x] ? x : root[x] = find(root[x]);} // merge the two groups containing elements// at indices x and y into one groupint uni(int x, int y){ int p = find(x), q = find(y); if (p != q) { root[p] = root[q]; }} void initialize(int a[], int n, Query q[], int m){ // make n subsets with every // element as its root for (int i = 0; i < n; i++) root[i] = i; // consecutive elements equal in value are // merged into one single group for (int i = 1; i < n; i++) if (a[i] == a[i - 1]) uni(i, i - 1);} // Driver codeint main(){ int a[] = { 1, 1, 5, 4, 5 }; int n = sizeof(a) / sizeof(a[0]); Query q[] = { { 0, 2, 2 }, { 1, 4, 1 }, { 2, 4, 5 } }; int m = sizeof(q) / sizeof(q[0]); initialize(a, n, q, m); for (int i = 0; i < m; i++) { int flag = 0; int l = q[i].L, r = q[i].R, x = q[i].X; int p = r; while (p >= l) { // check if the current element in // consideration is equal to x or not // if it is equal, then x exists in the range if (a[p] == x) { flag = 1; break; } p = find(p) - 1; } // Print if x exists or not if (flag != 0) cout << x << " exists between [" << l << ", " << r << "] " << endl; else cout << x << " does not exist between [" << l << ", " << r << "] " << endl; }}
// Java program to determine if the element// exists for different range queriesimport java.util.*; class GFG{ // Structure to represent a query rangestatic class Query{ int L, R, X; public Query(int L, int R, int X) { this.L = L; this.R = R; this.X = X; }}; static int maxn = 100; static int []root = new int[maxn]; // Find the root of the group containing// the element at index xstatic int find(int x){ if(x == root[x]) return x; else return root[x] = find(root[x]);} // merge the two groups containing elements// at indices x and y into one groupstatic void uni(int x, int y){ int p = find(x), q = find(y); if (p != q) { root[p] = root[q]; }} static void initialize(int a[], int n, Query q[], int m){ // make n subsets with every // element as its root for (int i = 0; i < n; i++) root[i] = i; // consecutive elements equal in value are // merged into one single group for (int i = 1; i < n; i++) if (a[i] == a[i - 1]) uni(i, i - 1);} // Driver codepublic static void main(String args[]){ int a[] = { 1, 1, 5, 4, 5 }; int n = a.length; Query q[] = { new Query(0, 2, 2 ), new Query( 1, 4, 1 ), new Query( 2, 4, 5 ) }; int m = q.length; initialize(a, n, q, m); for (int i = 0; i < m; i++) { int flag = 0; int l = q[i].L, r = q[i].R, x = q[i].X; int p = r; while (p >= l) { // check if the current element in // consideration is equal to x or not // if it is equal, then x exists in the range if (a[p] == x) { flag = 1; break; } p = find(p) - 1; } // Print if x exists or not if (flag != 0) System.out.println(x + " exists between [" + l + ", " + r + "] "); else System.out.println(x + " does not exist between [" + l + ", " + r + "] "); }}} // This code is contributed by 29AjayKumar
# Python3 program to determine if the element# exists for different range queries # Structure to represent a query rangeclass Query: def __init__(self, L, R, X): self.L = L self.R = R self.X = X maxn = 100root = [0] * maxn # Find the root of the group containing# the element at index xdef find(x): if x == root[x]: return x else: root[x] = find(root[x]) return root[x] # merge the two groups containing elements# at indices x and y into one groupdef uni(x, y): p = find(x) q = find(y) if p != q: root[p] = root[q] def initialize(a, n, q, m): # make n subsets with every # element as its root for i in range(n): root[i] = i # consecutive elements equal in value are # merged into one single group for i in range(1, n): if a[i] == a[i - 1]: uni(i, i - 1) # Driver Codeif __name__ == "__main__": a = [1, 1, 5, 4, 5] n = len(a) q = [Query(0, 2, 2), Query(1, 4, 1), Query(2, 4, 5)] m = len(q) initialize(a, n, q, m) for i in range(m): flag = False l = q[i].L r = q[i].R x = q[i].X p = r while p >= l: # check if the current element in # consideration is equal to x or not # if it is equal, then x exists in the range if a[p] == x: flag = True break p = find(p) - 1 # Print if x exists or not if flag: print("%d exists between [%d, %d]" % (x, l, r)) else: print("%d does not exists between [%d, %d]" % (x, l, r)) # This code is contributed by# sanjeev2552
// C# program to determine if the element// exists for different range queriesusing System; class GFG{ // Structure to represent a query rangepublic class Query{ public int L, R, X; public Query(int L, int R, int X) { this.L = L; this.R = R; this.X = X; }}; static int maxn = 100; static int []root = new int[maxn]; // Find the root of the group containing// the element at index xstatic int find(int x){ if(x == root[x]) return x; else return root[x] = find(root[x]);} // merge the two groups containing elements// at indices x and y into one groupstatic void uni(int x, int y){ int p = find(x), q = find(y); if (p != q) { root[p] = root[q]; }} static void initialize(int []a, int n, Query []q, int m){ // make n subsets with every // element as its root for (int i = 0; i < n; i++) root[i] = i; // consecutive elements equal in value are // merged into one single group for (int i = 1; i < n; i++) if (a[i] == a[i - 1]) uni(i, i - 1);} // Driver codepublic static void Main(String []args){ int []a = { 1, 1, 5, 4, 5 }; int n = a.Length; Query []q = {new Query(0, 2, 2), new Query(1, 4, 1), new Query(2, 4, 5)}; int m = q.Length; initialize(a, n, q, m); for (int i = 0; i < m; i++) { int flag = 0; int l = q[i].L, r = q[i].R, x = q[i].X; int p = r; while (p >= l) { // check if the current element in // consideration is equal to x or not // if it is equal, then x exists in the range if (a[p] == x) { flag = 1; break; } p = find(p) - 1; } // Print if x exists or not if (flag != 0) Console.WriteLine(x + " exists between [" + l + ", " + r + "] "); else Console.WriteLine(x + " does not exist between [" + l + ", " + r + "] "); }}} // This code is contributed by PrinciRaj1992
<script>// Javascript program to determine if the element// exists for different range queries // Structure to represent a query rangeclass Query{ constructor(L, R, X) { this.L = L; this.R = R; this.X = X; }}; let maxn = 100; let root = new Array(maxn); // Find the root of the group containing// the element at index xfunction find(x){ if(x == root[x]) return x; else return root[x] = find(root[x]);} // merge the two groups containing elements// at indices x and y into one groupfunction uni(x, y){ let p = find(x), q = find(y); if (p != q) { root[p] = root[q]; }} function initialize(a, n, q, m){ // make n subsets with every // element as its root for (let i = 0; i < n; i++) root[i] = i; // consecutive elements equal in value are // merged into one single group for (let i = 1; i < n; i++) if (a[i] == a[i - 1]) uni(i, i - 1);} // Driver code let a = [ 1, 1, 5, 4, 5 ]; let n = a.length; let q = [ new Query(0, 2, 2 ), new Query( 1, 4, 1 ), new Query( 2, 4, 5 ) ]; let m = q.length; initialize(a, n, q, m); for (let i = 0; i < m; i++) { let flag = 0; let l = q[i].L, r = q[i].R, x = q[i].X; let p = r; while (p >= l) { // check if the current element in // consideration is equal to x or not // if it is equal, then x exists in the range if (a[p] == x) { flag = 1; break; } p = find(p) - 1; } // Print if x exists or not if (flag != 0) document.write(x + " exists between [" + l + ", " + r + "] " + "<br>"); else document.write(x + " does not exist between [" + l + ", " + r + "] " + "<br>"); } // This code is contributed by gfgking</script>
2 does not exist between [0, 2]
1 exists between [1, 4]
5 exists between [2, 4]
Efficient Approach(Using Mo’s Algorithm) : Mo’s algorithm is one of the finest applications for square root decomposition. It is based on the basic idea of using the answer to the previous query to compute the answer for the current query. This is made possible because the Mo’s algorithm is constructed in such a way that if F([L, R]) is known, then F([L + 1, R]), F([L – 1, R]), F([L, R + 1]) and F([L, R – 1]) can be computed easily, each in O(F) time.Answering queries in the order they are asked, then the time complexity is not improved to what is needed to be. To reduce the time complexity considerably, the queries are divided into blocks and then sorted. The exact algorithm to sort the queries is as follows :
Denote BLOCK_SIZE = sqrt(N)
All the queries with the same L/BLOCK_SIZE are put in the same block
Within a block, the queries are sorted based on their R values
The sort function thus compares two queries, Q1 and Q2 as follows: Q1 must come before Q2 if: 1. L1/BLOCK_SIZE<L2/BLOCK_SIZE 2. L1/BLOCK_SIZE=L2/BLOCK_SIZE and R1<R2
After sorting the queries, the next step is to compute the answer to the first query and consequently answer rest of the queries. To determine if a particular element exists or not, check the frequency of the element in that range. A non zero frequency confirms the existence of the element in that range. To store the frequency of the elements, STL map has been used in the following code. In the example given, first query after sorting the array of queries is {0, 2, 2}. Hash the frequencies of the elements in [0, 2] and then check the frequency of the element 2 from the map. Since, 2 occurs 0 times, print “No”. While processing the next query, which is {1, 4, 1} in this case, decrement the frequencies of the elements in the range [0, 1) and increment the frequencies of the elements in range [3, 4]. This step gives the frequencies of elements in [1, 4] and it can easily be seen from the map that 1 exists in this range.Time complexity : The pre-processing part, that is sorting the queries takes O(m Log m) time. The index variable for R changes at most times throughout the run and that for L changes its value at most times. Hence, processing all queries takes + = time.Below is the C++ implementation of the above idea :
CPP
// CPP code to determine if the element// exists for different range queries#include <bits/stdc++.h> using namespace std; // Variable to represent block size.// This is made global, so compare()// of sort can use it.int block; // Structure to represent a query rangestruct Query{ int L, R, X;}; // Function used to sort all queries so// that all queries of same block are// arranged together and within a block,// queries are sorted in increasing order// of R values.bool compare(Query x, Query y){ // Different blocks, sort by block. if (x.L / block != y.L / block) return x.L / block < y.L / block; // Same block, sort by R value return x.R < y.R;} // Determines if the element is present for all// query ranges. m is number of queries// n is size of array a[].void queryResults(int a[], int n, Query q[], int m){ // Find block size block = (int)sqrt(n); // Sort all queries so that queries of same // blocks are arranged together. sort(q, q + m, compare); // Initialize current L, current R int currL = 0, currR = 0; // To store the frequencies of // elements of the given range map<int, int> mp; // Traverse through all queries for (int i = 0; i < m; i++) { // L and R values of current range int L = q[i].L, R = q[i].R, X = q[i].X; // Decrement frequencies of extra elements // of previous range. For example if previous // range is [0, 3] and current range is [2, 5], // then the frequencies of a[0] and a[1] are decremented while (currL < L) { mp[a[currL]]--; currL++; } // Increment frequencies of elements of current Range while (currL > L) { mp[a[currL - 1]]++; currL--; } while (currR <= R) { mp[a[currR]]++; currR++; } // Decrement frequencies of elements of previous // range. For example when previous range is [0, 10] // and current range is [3, 8], then frequencies of // a[9] and a[10] are decremented while (currR > R + 1) { mp[a[currR - 1]]--; currR--; } // Print if X exists or not if (mp[X] != 0) cout << X << " exists between [" << L << ", " << R << "] " << endl; else cout << X << " does not exist between [" << L << ", " << R << "] " << endl; }} // Driver programint main(){ int a[] = { 1, 1, 5, 4, 5 }; int n = sizeof(a) / sizeof(a[0]); Query q[] = { { 0, 2, 2 }, { 1, 4, 1 }, { 2, 4, 5 } }; int m = sizeof(q) / sizeof(q[0]); queryResults(a, n, q, m); return 0;}
2 does not exist between [0, 2]
1 exists between [1, 4]
5 exists between [2, 4]
29AjayKumar
princiraj1992
sanjeev2552
gfgking
array-range-queries
Arrays
Searching
Arrays
Searching
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Arrays in Java
Arrays in C/C++
Program for array rotation
Stack Data Structure (Introduction and Program)
Largest Sum Contiguous Subarray
Binary Search
Linear Search
Find the Missing Number
K'th Smallest/Largest Element in Unsorted Array | Set 1
Program to find largest element in an array | [
{
"code": null,
"e": 41194,
"s": 41166,
"text": "\n21 Jun, 2021"
},
{
"code": null,
"e": 41410,
"s": 41194,
"text": "Given an array of N elements and Q queries of the form L R X. For each query, you have to output if the element X exists in the array between the indices L and R(included).Prerequisite : Mo’s Algorithms Examples : "
},
{
"code": null,
"e": 41757,
"s": 41410,
"text": "Input : N = 5\n arr = [1, 1, 5, 4, 5]\n Q = 3\n 1 3 2\n 2 5 1\n 3 5 5 \nOutput : No\n Yes\n Yes\nExplanation :\nFor the first query, 2 does not exist between the indices 1 and 3.\nFor the second query, 1 exists between the indices 2 and 5.\nFor the third query, 5 exists between the indices 3 and 5."
},
{
"code": null,
"e": 42455,
"s": 41757,
"text": "Naive Approach : The naive method would be to traverse the elements from L to R for each query, linearly searching for X. In the worst case, there can be N elements from L to R, hence the worst case time complexity for each query would be O(N). Therefore, for all the Q queries, the time complexity would turn out to be O(Q*N).Using Union-Find Method : This method checks only one element among all the consecutive equal values. If X is not equal to these values, then the algorithm skips all the other the other equal elements and continues traversal with the next different element. This algorithm is evidently useful only when there are consecutive equal elements in large amounts.Algorithm : "
},
{
"code": null,
"e": 42957,
"s": 42455,
"text": "Merge all the consecutive equal elements in one group. While processing a query, start from R. Let index = R. Compare a[index] with X. If they are equal, then print “Yes” and break out of traversing the rest of the range. Else, skip all the consecutive elements belonging to the group of a[index]. Index becomes equal to one less than the index of the root of this group. Continue the above step either till X is found or till index becomes less than L. If index becomes less than L, print “No”. "
},
{
"code": null,
"e": 43014,
"s": 42957,
"text": "Merge all the consecutive equal elements in one group. "
},
{
"code": null,
"e": 43071,
"s": 43014,
"text": "While processing a query, start from R. Let index = R. "
},
{
"code": null,
"e": 43335,
"s": 43071,
"text": "Compare a[index] with X. If they are equal, then print “Yes” and break out of traversing the rest of the range. Else, skip all the consecutive elements belonging to the group of a[index]. Index becomes equal to one less than the index of the root of this group. "
},
{
"code": null,
"e": 43419,
"s": 43335,
"text": "Continue the above step either till X is found or till index becomes less than L. "
},
{
"code": null,
"e": 43463,
"s": 43419,
"text": "If index becomes less than L, print “No”. "
},
{
"code": null,
"e": 43512,
"s": 43463,
"text": "Below is the implementation of the above idea. "
},
{
"code": null,
"e": 43516,
"s": 43512,
"text": "C++"
},
{
"code": null,
"e": 43521,
"s": 43516,
"text": "Java"
},
{
"code": null,
"e": 43529,
"s": 43521,
"text": "Python3"
},
{
"code": null,
"e": 43532,
"s": 43529,
"text": "C#"
},
{
"code": null,
"e": 43543,
"s": 43532,
"text": "Javascript"
},
{
"code": "// Program to determine if the element// exists for different range queries#include <bits/stdc++.h>using namespace std; // Structure to represent a query rangestruct Query{ int L, R, X;}; const int maxn = 100; int root[maxn]; // Find the root of the group containing// the element at index xint find(int x){ return x == root[x] ? x : root[x] = find(root[x]);} // merge the two groups containing elements// at indices x and y into one groupint uni(int x, int y){ int p = find(x), q = find(y); if (p != q) { root[p] = root[q]; }} void initialize(int a[], int n, Query q[], int m){ // make n subsets with every // element as its root for (int i = 0; i < n; i++) root[i] = i; // consecutive elements equal in value are // merged into one single group for (int i = 1; i < n; i++) if (a[i] == a[i - 1]) uni(i, i - 1);} // Driver codeint main(){ int a[] = { 1, 1, 5, 4, 5 }; int n = sizeof(a) / sizeof(a[0]); Query q[] = { { 0, 2, 2 }, { 1, 4, 1 }, { 2, 4, 5 } }; int m = sizeof(q) / sizeof(q[0]); initialize(a, n, q, m); for (int i = 0; i < m; i++) { int flag = 0; int l = q[i].L, r = q[i].R, x = q[i].X; int p = r; while (p >= l) { // check if the current element in // consideration is equal to x or not // if it is equal, then x exists in the range if (a[p] == x) { flag = 1; break; } p = find(p) - 1; } // Print if x exists or not if (flag != 0) cout << x << \" exists between [\" << l << \", \" << r << \"] \" << endl; else cout << x << \" does not exist between [\" << l << \", \" << r << \"] \" << endl; }}",
"e": 45389,
"s": 43543,
"text": null
},
{
"code": "// Java program to determine if the element// exists for different range queriesimport java.util.*; class GFG{ // Structure to represent a query rangestatic class Query{ int L, R, X; public Query(int L, int R, int X) { this.L = L; this.R = R; this.X = X; }}; static int maxn = 100; static int []root = new int[maxn]; // Find the root of the group containing// the element at index xstatic int find(int x){ if(x == root[x]) return x; else return root[x] = find(root[x]);} // merge the two groups containing elements// at indices x and y into one groupstatic void uni(int x, int y){ int p = find(x), q = find(y); if (p != q) { root[p] = root[q]; }} static void initialize(int a[], int n, Query q[], int m){ // make n subsets with every // element as its root for (int i = 0; i < n; i++) root[i] = i; // consecutive elements equal in value are // merged into one single group for (int i = 1; i < n; i++) if (a[i] == a[i - 1]) uni(i, i - 1);} // Driver codepublic static void main(String args[]){ int a[] = { 1, 1, 5, 4, 5 }; int n = a.length; Query q[] = { new Query(0, 2, 2 ), new Query( 1, 4, 1 ), new Query( 2, 4, 5 ) }; int m = q.length; initialize(a, n, q, m); for (int i = 0; i < m; i++) { int flag = 0; int l = q[i].L, r = q[i].R, x = q[i].X; int p = r; while (p >= l) { // check if the current element in // consideration is equal to x or not // if it is equal, then x exists in the range if (a[p] == x) { flag = 1; break; } p = find(p) - 1; } // Print if x exists or not if (flag != 0) System.out.println(x + \" exists between [\" + l + \", \" + r + \"] \"); else System.out.println(x + \" does not exist between [\" + l + \", \" + r + \"] \"); }}} // This code is contributed by 29AjayKumar",
"e": 47528,
"s": 45389,
"text": null
},
{
"code": "# Python3 program to determine if the element# exists for different range queries # Structure to represent a query rangeclass Query: def __init__(self, L, R, X): self.L = L self.R = R self.X = X maxn = 100root = [0] * maxn # Find the root of the group containing# the element at index xdef find(x): if x == root[x]: return x else: root[x] = find(root[x]) return root[x] # merge the two groups containing elements# at indices x and y into one groupdef uni(x, y): p = find(x) q = find(y) if p != q: root[p] = root[q] def initialize(a, n, q, m): # make n subsets with every # element as its root for i in range(n): root[i] = i # consecutive elements equal in value are # merged into one single group for i in range(1, n): if a[i] == a[i - 1]: uni(i, i - 1) # Driver Codeif __name__ == \"__main__\": a = [1, 1, 5, 4, 5] n = len(a) q = [Query(0, 2, 2), Query(1, 4, 1), Query(2, 4, 5)] m = len(q) initialize(a, n, q, m) for i in range(m): flag = False l = q[i].L r = q[i].R x = q[i].X p = r while p >= l: # check if the current element in # consideration is equal to x or not # if it is equal, then x exists in the range if a[p] == x: flag = True break p = find(p) - 1 # Print if x exists or not if flag: print(\"%d exists between [%d, %d]\" % (x, l, r)) else: print(\"%d does not exists between [%d, %d]\" % (x, l, r)) # This code is contributed by# sanjeev2552",
"e": 49209,
"s": 47528,
"text": null
},
{
"code": "// C# program to determine if the element// exists for different range queriesusing System; class GFG{ // Structure to represent a query rangepublic class Query{ public int L, R, X; public Query(int L, int R, int X) { this.L = L; this.R = R; this.X = X; }}; static int maxn = 100; static int []root = new int[maxn]; // Find the root of the group containing// the element at index xstatic int find(int x){ if(x == root[x]) return x; else return root[x] = find(root[x]);} // merge the two groups containing elements// at indices x and y into one groupstatic void uni(int x, int y){ int p = find(x), q = find(y); if (p != q) { root[p] = root[q]; }} static void initialize(int []a, int n, Query []q, int m){ // make n subsets with every // element as its root for (int i = 0; i < n; i++) root[i] = i; // consecutive elements equal in value are // merged into one single group for (int i = 1; i < n; i++) if (a[i] == a[i - 1]) uni(i, i - 1);} // Driver codepublic static void Main(String []args){ int []a = { 1, 1, 5, 4, 5 }; int n = a.Length; Query []q = {new Query(0, 2, 2), new Query(1, 4, 1), new Query(2, 4, 5)}; int m = q.Length; initialize(a, n, q, m); for (int i = 0; i < m; i++) { int flag = 0; int l = q[i].L, r = q[i].R, x = q[i].X; int p = r; while (p >= l) { // check if the current element in // consideration is equal to x or not // if it is equal, then x exists in the range if (a[p] == x) { flag = 1; break; } p = find(p) - 1; } // Print if x exists or not if (flag != 0) Console.WriteLine(x + \" exists between [\" + l + \", \" + r + \"] \"); else Console.WriteLine(x + \" does not exist between [\" + l + \", \" + r + \"] \"); }}} // This code is contributed by PrinciRaj1992",
"e": 51340,
"s": 49209,
"text": null
},
{
"code": "<script>// Javascript program to determine if the element// exists for different range queries // Structure to represent a query rangeclass Query{ constructor(L, R, X) { this.L = L; this.R = R; this.X = X; }}; let maxn = 100; let root = new Array(maxn); // Find the root of the group containing// the element at index xfunction find(x){ if(x == root[x]) return x; else return root[x] = find(root[x]);} // merge the two groups containing elements// at indices x and y into one groupfunction uni(x, y){ let p = find(x), q = find(y); if (p != q) { root[p] = root[q]; }} function initialize(a, n, q, m){ // make n subsets with every // element as its root for (let i = 0; i < n; i++) root[i] = i; // consecutive elements equal in value are // merged into one single group for (let i = 1; i < n; i++) if (a[i] == a[i - 1]) uni(i, i - 1);} // Driver code let a = [ 1, 1, 5, 4, 5 ]; let n = a.length; let q = [ new Query(0, 2, 2 ), new Query( 1, 4, 1 ), new Query( 2, 4, 5 ) ]; let m = q.length; initialize(a, n, q, m); for (let i = 0; i < m; i++) { let flag = 0; let l = q[i].L, r = q[i].R, x = q[i].X; let p = r; while (p >= l) { // check if the current element in // consideration is equal to x or not // if it is equal, then x exists in the range if (a[p] == x) { flag = 1; break; } p = find(p) - 1; } // Print if x exists or not if (flag != 0) document.write(x + \" exists between [\" + l + \", \" + r + \"] \" + \"<br>\"); else document.write(x + \" does not exist between [\" + l + \", \" + r + \"] \" + \"<br>\"); } // This code is contributed by gfgking</script>",
"e": 53309,
"s": 51340,
"text": null
},
{
"code": null,
"e": 53391,
"s": 53309,
"text": "2 does not exist between [0, 2] \n1 exists between [1, 4] \n5 exists between [2, 4]"
},
{
"code": null,
"e": 54116,
"s": 53393,
"text": "Efficient Approach(Using Mo’s Algorithm) : Mo’s algorithm is one of the finest applications for square root decomposition. It is based on the basic idea of using the answer to the previous query to compute the answer for the current query. This is made possible because the Mo’s algorithm is constructed in such a way that if F([L, R]) is known, then F([L + 1, R]), F([L – 1, R]), F([L, R + 1]) and F([L, R – 1]) can be computed easily, each in O(F) time.Answering queries in the order they are asked, then the time complexity is not improved to what is needed to be. To reduce the time complexity considerably, the queries are divided into blocks and then sorted. The exact algorithm to sort the queries is as follows : "
},
{
"code": null,
"e": 54144,
"s": 54116,
"text": "Denote BLOCK_SIZE = sqrt(N)"
},
{
"code": null,
"e": 54213,
"s": 54144,
"text": "All the queries with the same L/BLOCK_SIZE are put in the same block"
},
{
"code": null,
"e": 54276,
"s": 54213,
"text": "Within a block, the queries are sorted based on their R values"
},
{
"code": null,
"e": 54442,
"s": 54276,
"text": "The sort function thus compares two queries, Q1 and Q2 as follows: Q1 must come before Q2 if: 1. L1/BLOCK_SIZE<L2/BLOCK_SIZE 2. L1/BLOCK_SIZE=L2/BLOCK_SIZE and R1<R2"
},
{
"code": null,
"e": 55678,
"s": 54442,
"text": "After sorting the queries, the next step is to compute the answer to the first query and consequently answer rest of the queries. To determine if a particular element exists or not, check the frequency of the element in that range. A non zero frequency confirms the existence of the element in that range. To store the frequency of the elements, STL map has been used in the following code. In the example given, first query after sorting the array of queries is {0, 2, 2}. Hash the frequencies of the elements in [0, 2] and then check the frequency of the element 2 from the map. Since, 2 occurs 0 times, print “No”. While processing the next query, which is {1, 4, 1} in this case, decrement the frequencies of the elements in the range [0, 1) and increment the frequencies of the elements in range [3, 4]. This step gives the frequencies of elements in [1, 4] and it can easily be seen from the map that 1 exists in this range.Time complexity : The pre-processing part, that is sorting the queries takes O(m Log m) time. The index variable for R changes at most times throughout the run and that for L changes its value at most times. Hence, processing all queries takes + = time.Below is the C++ implementation of the above idea : "
},
{
"code": null,
"e": 55682,
"s": 55678,
"text": "CPP"
},
{
"code": "// CPP code to determine if the element// exists for different range queries#include <bits/stdc++.h> using namespace std; // Variable to represent block size.// This is made global, so compare()// of sort can use it.int block; // Structure to represent a query rangestruct Query{ int L, R, X;}; // Function used to sort all queries so// that all queries of same block are// arranged together and within a block,// queries are sorted in increasing order// of R values.bool compare(Query x, Query y){ // Different blocks, sort by block. if (x.L / block != y.L / block) return x.L / block < y.L / block; // Same block, sort by R value return x.R < y.R;} // Determines if the element is present for all// query ranges. m is number of queries// n is size of array a[].void queryResults(int a[], int n, Query q[], int m){ // Find block size block = (int)sqrt(n); // Sort all queries so that queries of same // blocks are arranged together. sort(q, q + m, compare); // Initialize current L, current R int currL = 0, currR = 0; // To store the frequencies of // elements of the given range map<int, int> mp; // Traverse through all queries for (int i = 0; i < m; i++) { // L and R values of current range int L = q[i].L, R = q[i].R, X = q[i].X; // Decrement frequencies of extra elements // of previous range. For example if previous // range is [0, 3] and current range is [2, 5], // then the frequencies of a[0] and a[1] are decremented while (currL < L) { mp[a[currL]]--; currL++; } // Increment frequencies of elements of current Range while (currL > L) { mp[a[currL - 1]]++; currL--; } while (currR <= R) { mp[a[currR]]++; currR++; } // Decrement frequencies of elements of previous // range. For example when previous range is [0, 10] // and current range is [3, 8], then frequencies of // a[9] and a[10] are decremented while (currR > R + 1) { mp[a[currR - 1]]--; currR--; } // Print if X exists or not if (mp[X] != 0) cout << X << \" exists between [\" << L << \", \" << R << \"] \" << endl; else cout << X << \" does not exist between [\" << L << \", \" << R << \"] \" << endl; }} // Driver programint main(){ int a[] = { 1, 1, 5, 4, 5 }; int n = sizeof(a) / sizeof(a[0]); Query q[] = { { 0, 2, 2 }, { 1, 4, 1 }, { 2, 4, 5 } }; int m = sizeof(q) / sizeof(q[0]); queryResults(a, n, q, m); return 0;}",
"e": 58392,
"s": 55682,
"text": null
},
{
"code": null,
"e": 58474,
"s": 58392,
"text": "2 does not exist between [0, 2] \n1 exists between [1, 4] \n5 exists between [2, 4]"
},
{
"code": null,
"e": 58488,
"s": 58476,
"text": "29AjayKumar"
},
{
"code": null,
"e": 58502,
"s": 58488,
"text": "princiraj1992"
},
{
"code": null,
"e": 58514,
"s": 58502,
"text": "sanjeev2552"
},
{
"code": null,
"e": 58522,
"s": 58514,
"text": "gfgking"
},
{
"code": null,
"e": 58542,
"s": 58522,
"text": "array-range-queries"
},
{
"code": null,
"e": 58549,
"s": 58542,
"text": "Arrays"
},
{
"code": null,
"e": 58559,
"s": 58549,
"text": "Searching"
},
{
"code": null,
"e": 58566,
"s": 58559,
"text": "Arrays"
},
{
"code": null,
"e": 58576,
"s": 58566,
"text": "Searching"
},
{
"code": null,
"e": 58674,
"s": 58576,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 58683,
"s": 58674,
"text": "Comments"
},
{
"code": null,
"e": 58696,
"s": 58683,
"text": "Old Comments"
},
{
"code": null,
"e": 58711,
"s": 58696,
"text": "Arrays in Java"
},
{
"code": null,
"e": 58727,
"s": 58711,
"text": "Arrays in C/C++"
},
{
"code": null,
"e": 58754,
"s": 58727,
"text": "Program for array rotation"
},
{
"code": null,
"e": 58802,
"s": 58754,
"text": "Stack Data Structure (Introduction and Program)"
},
{
"code": null,
"e": 58834,
"s": 58802,
"text": "Largest Sum Contiguous Subarray"
},
{
"code": null,
"e": 58848,
"s": 58834,
"text": "Binary Search"
},
{
"code": null,
"e": 58862,
"s": 58848,
"text": "Linear Search"
},
{
"code": null,
"e": 58886,
"s": 58862,
"text": "Find the Missing Number"
},
{
"code": null,
"e": 58942,
"s": 58886,
"text": "K'th Smallest/Largest Element in Unsorted Array | Set 1"
}
] |
Why switch keyword used in React Router v4 ? - GeeksforGeeks | 18 Oct, 2021
ReactJS is a javascript library that is used to build single-page applications (SPA). React by default does not provide the routing features. We can implement routing in ReactJS projects using React Router. React Router is a library that enables navigation among views of various components in a React Application, allows changing the browser URL, and keeps the UI in sync with the URL.
In this article, we will see how routing works in React Router and how we can take advantage of the Switch component provided by React Router.
Creating React Application And Installing Module:
Step 1: Create a React application using the following command.
npx create-react-app SWITCH_DEMO_APP
Step 2: After creating your project folder, move to it by using the following command.
cd SWITCH_DEMO_APP
Step 3: After creating the React application, Install the React Router as a dependency using the following command.
npm install --save react-router-dom
Project Structure: The project structure after deleting some unrequired files is shown in the picture mentioned below.
Project Structure
Example 1: Routing without Switch component – When we perform routing using React Router, whenever a page is rendered the URL path is being matched to each route. All the route paths that match the given URL path are rendered. The content of the App.js file is mentioned below. In this file, we have created four div, each containing a Link Component provided by React Router. We have also created five Routes i.e. home, profile, products, products/shoes, and a Route with a path equal to a * that is a wild card that matches with every URL path.
How does path matching work in React Router?
React router takes the relative URL and matches it with each path provided in the Route component. The route matching is done in a way that if a part of this relative URL is matched then that Route is rendered. For example, if the relative URL is /products/shoes then paths /, /products, and /products/shoes match the URL and all three routes are rendered but /profile does not match the URL.
Filename: App.js
Javascript
import React, { Fragment } from "react";import { BrowserRouter as Router, Link, Route } from "react-router-dom"; const Home = () => { return <h2>Home</h2>;}; const Profile = () => { return <h2>Profile</h2>;}; const Shoes = () => { return <h2>Shoes</h2>;}; const Products = () => { return <h2>Products</h2>;}; const App = () => { return ( <Fragment> <Router> <div> <Link to="/">Home</Link> </div> <div> <Link to="/products">Products</Link> </div> <div> <Link to="/products/shoes">Shoes</Link> </div> <div> <Link to="/profile">profile</Link> </div> <Route path="/"> <Home /> </Route> <Route path="/profile"> <Profile /> </Route> <Route path="/products"> <Products /> </Route> <Route path="/products/shoes"> <Shoes /> </Route> </Router> </Fragment> );}; export default App;
Step to Run Application: Run the application using the following command from the root directory of the project.
npm start
Output: Image showing the Webpage when we click the ‘shoes’ link.
Example 2: Routing using Switch Component – When we wrap our routes inside the Switch component then it makes sure that only one route is rendered at a time. So in this case, the first route that matches the relative URL with the paths of each Route component and only renders the first path that matches the part of the relative URL as we have discussed above.
Syntax: Syntax to use the Switch component is mentioned below.
<Switch>
<Route exact path='/'>
<A />
</Route>
<Route path='/b'>
<B />
</Route>
<Route exact path='/c'>
<C />
</Route>
<Route path='/d'>
<D />
</Route>
</Switch>
If two routes match with each other then we can use the exact prop as shown below.
<Route exact path='/'>
<Home />
</Route>
By using this exact prop, we make sure that the home route is only rendered when the relative URL exactly matches /. Now if the relative URL is /profile then only the profile route is rendered doesn’t matter if the profile Route is below / route in the code. The content of the App.js file when we use the Switch component is mentioned below.
Filename: App.js
Javascript
import React, { Fragment } from 'react';import { BrowserRouter as Router, Link, Route, Switch } from 'react-router-dom'; const Home = () => { return <h2>Home</h2>;}; const Profile = () => { return <h2>Profile</h2>;}; const Shoes = () => { return <h2>Shoes</h2>;}; const Products = () => { return <h2>Products</h2>;}; const App = () => { return ( <Fragment> <Router> <div> <Link to='/'>Home</Link> </div> <div> <Link to='/products'>Products</Link> </div> <div> <Link to='/products/shoes'>Shoes</Link> </div> <div> <Link to='/profile'>profile</Link> </div> <Switch> <Route exact path='/'> <Home /> </Route> <Route path='/profile'> <Profile /> </Route> <Route exact path='/products'> <Products /> </Route> <Route path='/products/shoes'> <Shoes /> </Route> </Switch> </Router> </Fragment> );}; export default App;
Step to Run Application: Run the application using the following command from the root directory of the project.
npm start
Output: Image showing the Webpage when we click the ‘shoes’ link when using Switch component
Picked
React-Questions
ReactJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ReactJS useNavigate() Hook
How to set background images in ReactJS ?
Axios in React: A Guide for Beginners
How to create a table in ReactJS ?
How to navigate on path by button click in react router ?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
Difference between var, let and const keywords in JavaScript | [
{
"code": null,
"e": 26181,
"s": 26153,
"text": "\n18 Oct, 2021"
},
{
"code": null,
"e": 26569,
"s": 26181,
"text": "ReactJS is a javascript library that is used to build single-page applications (SPA). React by default does not provide the routing features. We can implement routing in ReactJS projects using React Router. React Router is a library that enables navigation among views of various components in a React Application, allows changing the browser URL, and keeps the UI in sync with the URL. "
},
{
"code": null,
"e": 26712,
"s": 26569,
"text": "In this article, we will see how routing works in React Router and how we can take advantage of the Switch component provided by React Router."
},
{
"code": null,
"e": 26762,
"s": 26712,
"text": "Creating React Application And Installing Module:"
},
{
"code": null,
"e": 26826,
"s": 26762,
"text": "Step 1: Create a React application using the following command."
},
{
"code": null,
"e": 26863,
"s": 26826,
"text": "npx create-react-app SWITCH_DEMO_APP"
},
{
"code": null,
"e": 26950,
"s": 26863,
"text": "Step 2: After creating your project folder, move to it by using the following command."
},
{
"code": null,
"e": 26969,
"s": 26950,
"text": "cd SWITCH_DEMO_APP"
},
{
"code": null,
"e": 27085,
"s": 26969,
"text": "Step 3: After creating the React application, Install the React Router as a dependency using the following command."
},
{
"code": null,
"e": 27121,
"s": 27085,
"text": "npm install --save react-router-dom"
},
{
"code": null,
"e": 27240,
"s": 27121,
"text": "Project Structure: The project structure after deleting some unrequired files is shown in the picture mentioned below."
},
{
"code": null,
"e": 27258,
"s": 27240,
"text": "Project Structure"
},
{
"code": null,
"e": 27806,
"s": 27258,
"text": "Example 1: Routing without Switch component – When we perform routing using React Router, whenever a page is rendered the URL path is being matched to each route. All the route paths that match the given URL path are rendered. The content of the App.js file is mentioned below. In this file, we have created four div, each containing a Link Component provided by React Router. We have also created five Routes i.e. home, profile, products, products/shoes, and a Route with a path equal to a * that is a wild card that matches with every URL path. "
},
{
"code": null,
"e": 27851,
"s": 27806,
"text": "How does path matching work in React Router?"
},
{
"code": null,
"e": 28245,
"s": 27851,
"text": "React router takes the relative URL and matches it with each path provided in the Route component. The route matching is done in a way that if a part of this relative URL is matched then that Route is rendered. For example, if the relative URL is /products/shoes then paths /, /products, and /products/shoes match the URL and all three routes are rendered but /profile does not match the URL. "
},
{
"code": null,
"e": 28262,
"s": 28245,
"text": "Filename: App.js"
},
{
"code": null,
"e": 28273,
"s": 28262,
"text": "Javascript"
},
{
"code": "import React, { Fragment } from \"react\";import { BrowserRouter as Router, Link, Route } from \"react-router-dom\"; const Home = () => { return <h2>Home</h2>;}; const Profile = () => { return <h2>Profile</h2>;}; const Shoes = () => { return <h2>Shoes</h2>;}; const Products = () => { return <h2>Products</h2>;}; const App = () => { return ( <Fragment> <Router> <div> <Link to=\"/\">Home</Link> </div> <div> <Link to=\"/products\">Products</Link> </div> <div> <Link to=\"/products/shoes\">Shoes</Link> </div> <div> <Link to=\"/profile\">profile</Link> </div> <Route path=\"/\"> <Home /> </Route> <Route path=\"/profile\"> <Profile /> </Route> <Route path=\"/products\"> <Products /> </Route> <Route path=\"/products/shoes\"> <Shoes /> </Route> </Router> </Fragment> );}; export default App;",
"e": 29260,
"s": 28273,
"text": null
},
{
"code": null,
"e": 29373,
"s": 29260,
"text": "Step to Run Application: Run the application using the following command from the root directory of the project."
},
{
"code": null,
"e": 29383,
"s": 29373,
"text": "npm start"
},
{
"code": null,
"e": 29449,
"s": 29383,
"text": "Output: Image showing the Webpage when we click the ‘shoes’ link."
},
{
"code": null,
"e": 29812,
"s": 29449,
"text": "Example 2: Routing using Switch Component – When we wrap our routes inside the Switch component then it makes sure that only one route is rendered at a time. So in this case, the first route that matches the relative URL with the paths of each Route component and only renders the first path that matches the part of the relative URL as we have discussed above. "
},
{
"code": null,
"e": 29875,
"s": 29812,
"text": "Syntax: Syntax to use the Switch component is mentioned below."
},
{
"code": null,
"e": 30077,
"s": 29875,
"text": "<Switch>\n <Route exact path='/'>\n <A />\n </Route>\n <Route path='/b'>\n <B />\n </Route>\n <Route exact path='/c'>\n <C />\n </Route>\n <Route path='/d'>\n <D />\n </Route>\n</Switch>"
},
{
"code": null,
"e": 30160,
"s": 30077,
"text": "If two routes match with each other then we can use the exact prop as shown below."
},
{
"code": null,
"e": 30205,
"s": 30160,
"text": "<Route exact path='/'>\n <Home />\n</Route>"
},
{
"code": null,
"e": 30549,
"s": 30205,
"text": "By using this exact prop, we make sure that the home route is only rendered when the relative URL exactly matches /. Now if the relative URL is /profile then only the profile route is rendered doesn’t matter if the profile Route is below / route in the code. The content of the App.js file when we use the Switch component is mentioned below."
},
{
"code": null,
"e": 30566,
"s": 30549,
"text": "Filename: App.js"
},
{
"code": null,
"e": 30577,
"s": 30566,
"text": "Javascript"
},
{
"code": "import React, { Fragment } from 'react';import { BrowserRouter as Router, Link, Route, Switch } from 'react-router-dom'; const Home = () => { return <h2>Home</h2>;}; const Profile = () => { return <h2>Profile</h2>;}; const Shoes = () => { return <h2>Shoes</h2>;}; const Products = () => { return <h2>Products</h2>;}; const App = () => { return ( <Fragment> <Router> <div> <Link to='/'>Home</Link> </div> <div> <Link to='/products'>Products</Link> </div> <div> <Link to='/products/shoes'>Shoes</Link> </div> <div> <Link to='/profile'>profile</Link> </div> <Switch> <Route exact path='/'> <Home /> </Route> <Route path='/profile'> <Profile /> </Route> <Route exact path='/products'> <Products /> </Route> <Route path='/products/shoes'> <Shoes /> </Route> </Switch> </Router> </Fragment> );}; export default App;",
"e": 31639,
"s": 30577,
"text": null
},
{
"code": null,
"e": 31752,
"s": 31639,
"text": "Step to Run Application: Run the application using the following command from the root directory of the project."
},
{
"code": null,
"e": 31762,
"s": 31752,
"text": "npm start"
},
{
"code": null,
"e": 31855,
"s": 31762,
"text": "Output: Image showing the Webpage when we click the ‘shoes’ link when using Switch component"
},
{
"code": null,
"e": 31862,
"s": 31855,
"text": "Picked"
},
{
"code": null,
"e": 31878,
"s": 31862,
"text": "React-Questions"
},
{
"code": null,
"e": 31886,
"s": 31878,
"text": "ReactJS"
},
{
"code": null,
"e": 31903,
"s": 31886,
"text": "Web Technologies"
},
{
"code": null,
"e": 32001,
"s": 31903,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32028,
"s": 32001,
"text": "ReactJS useNavigate() Hook"
},
{
"code": null,
"e": 32070,
"s": 32028,
"text": "How to set background images in ReactJS ?"
},
{
"code": null,
"e": 32108,
"s": 32070,
"text": "Axios in React: A Guide for Beginners"
},
{
"code": null,
"e": 32143,
"s": 32108,
"text": "How to create a table in ReactJS ?"
},
{
"code": null,
"e": 32201,
"s": 32143,
"text": "How to navigate on path by button click in react router ?"
},
{
"code": null,
"e": 32241,
"s": 32201,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 32274,
"s": 32241,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 32319,
"s": 32274,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 32369,
"s": 32319,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
Importance of @JsonView annotation using Jackson in Java? | The JsonView annotation can be used to include/exclude a property during the serialization and deserialization process dynamically. We need to configure an ObjectMapper class to include the type of view used for writing a JSON from Java object using the writerWithView() method.
@Target(value={ANNOTATION_TYPE,METHOD,FIELD})
@Retention(value=RUNTIME)
public @interface JsonView
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonView;
import com.fasterxml.jackson.core.JsonProcessingException;
public class JsonViewAnnotationTest {
public static void main(String args[]) throws JsonProcessingException {
ObjectMapper objectMapper = new ObjectMapper();
String jsonString = objectMapper.writerWithView(Views.Public.class).writeValueAsString(new Person());
String jsonStringInternal = objectMapper.writerWithView(Views.Internal.class).writeValueAsString(new Person());
System.out.println(jsonString);
System.out.println(jsonStringInternal);
}
}
// Person class
class Person {
@JsonView(Views.Public.class)
public long personId = 115;
@JsonView(Views.Public.class)
public String personName = "Raja Ramesh";
@JsonView(Views.Internal.class)
public String gender = "male";
@Override
public String toString() {
return "Person{" +
"personId=" + personId +
", personName='" + personName + '\'' +
", gender='" + gender + '\'' +
'}';
}
}
class Views {
static class Public {}
static class Internal extends Public {}
}
{"personId":115,"personName":"Raja Ramesh"}
{"personId":115,"personName":"Raja Ramesh","gender":"male"} | [
{
"code": null,
"e": 1341,
"s": 1062,
"text": "The JsonView annotation can be used to include/exclude a property during the serialization and deserialization process dynamically. We need to configure an ObjectMapper class to include the type of view used for writing a JSON from Java object using the writerWithView() method."
},
{
"code": null,
"e": 1440,
"s": 1341,
"text": "@Target(value={ANNOTATION_TYPE,METHOD,FIELD})\n@Retention(value=RUNTIME)\npublic @interface JsonView"
},
{
"code": null,
"e": 2687,
"s": 1440,
"text": "import com.fasterxml.jackson.databind.ObjectMapper;\nimport com.fasterxml.jackson.annotation.JsonProperty;\nimport com.fasterxml.jackson.annotation.JsonView;\nimport com.fasterxml.jackson.core.JsonProcessingException;\npublic class JsonViewAnnotationTest {\n public static void main(String args[]) throws JsonProcessingException {\n ObjectMapper objectMapper = new ObjectMapper();\n String jsonString = objectMapper.writerWithView(Views.Public.class).writeValueAsString(new Person());\n String jsonStringInternal = objectMapper.writerWithView(Views.Internal.class).writeValueAsString(new Person());\n System.out.println(jsonString);\n System.out.println(jsonStringInternal);\n }\n}\n// Person class\nclass Person {\n @JsonView(Views.Public.class)\n public long personId = 115;\n @JsonView(Views.Public.class)\n public String personName = \"Raja Ramesh\";\n @JsonView(Views.Internal.class)\n public String gender = \"male\";\n @Override\n public String toString() {\n return \"Person{\" +\n \"personId=\" + personId +\n \", personName='\" + personName + '\\'' +\n \", gender='\" + gender + '\\'' +\n '}';\n }\n}\nclass Views {\n static class Public {}\n static class Internal extends Public {}\n}"
},
{
"code": null,
"e": 2791,
"s": 2687,
"text": "{\"personId\":115,\"personName\":\"Raja Ramesh\"}\n{\"personId\":115,\"personName\":\"Raja Ramesh\",\"gender\":\"male\"}"
}
] |
java.time.ZoneId.of() Method Example | The java.time.ZoneId.of(String zoneId) method obtains an instance of ZoneId from an ID ensuring that the ID is valid and available for use.
Following is the declaration for java.time.ZoneId.of(String zoneId) method.
public static ZoneId of(String zoneId)
zoneId − the time-zone ID, not null.
the zone ID, not null
DateTimeException − if the zone ID has an invalid format
DateTimeException − if the zone ID has an invalid format
ZoneRulesException − if the zone ID is a region ID that cannot be found.
ZoneRulesException − if the zone ID is a region ID that cannot be found.
The following example shows the usage of java.time.ZoneId.of(String zoneId) method.
package com.tutorialspoint;
import java.time.ZoneId;
public class ZoneIdDemo {
public static void main(String[] args) {
ZoneId zone = ZoneId.of("Z");
System.out.println(zone);
}
}
Let us compile and run the above program, this will produce the following result −
Z
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2055,
"s": 1915,
"text": "The java.time.ZoneId.of(String zoneId) method obtains an instance of ZoneId from an ID ensuring that the ID is valid and available for use."
},
{
"code": null,
"e": 2131,
"s": 2055,
"text": "Following is the declaration for java.time.ZoneId.of(String zoneId) method."
},
{
"code": null,
"e": 2171,
"s": 2131,
"text": "public static ZoneId of(String zoneId)\n"
},
{
"code": null,
"e": 2208,
"s": 2171,
"text": "zoneId − the time-zone ID, not null."
},
{
"code": null,
"e": 2230,
"s": 2208,
"text": "the zone ID, not null"
},
{
"code": null,
"e": 2287,
"s": 2230,
"text": "DateTimeException − if the zone ID has an invalid format"
},
{
"code": null,
"e": 2344,
"s": 2287,
"text": "DateTimeException − if the zone ID has an invalid format"
},
{
"code": null,
"e": 2417,
"s": 2344,
"text": "ZoneRulesException − if the zone ID is a region ID that cannot be found."
},
{
"code": null,
"e": 2490,
"s": 2417,
"text": "ZoneRulesException − if the zone ID is a region ID that cannot be found."
},
{
"code": null,
"e": 2574,
"s": 2490,
"text": "The following example shows the usage of java.time.ZoneId.of(String zoneId) method."
},
{
"code": null,
"e": 2778,
"s": 2574,
"text": "package com.tutorialspoint;\n\nimport java.time.ZoneId;\n\npublic class ZoneIdDemo {\n public static void main(String[] args) {\n \n ZoneId zone = ZoneId.of(\"Z\");\n System.out.println(zone); \n }\n}"
},
{
"code": null,
"e": 2861,
"s": 2778,
"text": "Let us compile and run the above program, this will produce the following result −"
},
{
"code": null,
"e": 2864,
"s": 2861,
"text": "Z\n"
},
{
"code": null,
"e": 2871,
"s": 2864,
"text": " Print"
},
{
"code": null,
"e": 2882,
"s": 2871,
"text": " Add Notes"
}
] |
JavaScript | JavaScript is a lightweight, interpreted programming language with object-oriented capabilities that allows you to build interactivity into otherwise static HTML pages.
Key Points
It is Lightweight, interpreted programming language.
It is Lightweight, interpreted programming language.
It is designed for creating network-centric applications.
It is designed for creating network-centric applications.
It is complementary to and integrated with Java.
It is complementary to and integrated with Java.
It is complementary to and integrated with HTML
It is complementary to and integrated with HTML
It is an open and cross-platform
It is an open and cross-platform
JavaScript statements are the commands to tell the browser to what action to perform. Statements are separated by semicolon (;).
Example of JavaScript statement:
document.getElementById("demo").innerHTML = "Welcome";
Following table shows the various JavaScript Statements −
JavaScript supports both C-style and C++-style comments, thus:
Any text between a // and the end of a line is treated as a comment and is ignored by JavaScript.
Any text between a // and the end of a line is treated as a comment and is ignored by JavaScript.
Any text between the characters /* and */ is treated as a comment. This may span multiple lines.
Any text between the characters /* and */ is treated as a comment. This may span multiple lines.
JavaScript also recognizes the HTML comment opening sequence <!--. JavaScript treats this as a single-line comment, just as it does the // comment.-->
JavaScript also recognizes the HTML comment opening sequence <!--. JavaScript treats this as a single-line comment, just as it does the // comment.-->
The HTML comment closing sequence --> is not recognized by JavaScript so it should be written as //-->.
The HTML comment closing sequence --> is not recognized by JavaScript so it should be written as //-->.
Example
<script language="javascript" type="text/javascript">
<!--
// this is a comment. It is similar to comments in C++
/*
* This is a multiline comment in JavaScript
* It is very similar to comments in C Programming
*/
//-->
<script>
Variables are referred as named containers for storing information. We can place data into these containers and then refer to the data simply by naming the container.
Here are the important rules that must be followed while declaring a variable in JavaScript.
In JavaScript variable names are case sensitive i.e. a is different from A.
In JavaScript variable names are case sensitive i.e. a is different from A.
Variable name can only be started with a underscore ( _ ) or a letter (from a to z or A to Z), or dollar ( $ ) sign.
Variable name can only be started with a underscore ( _ ) or a letter (from a to z or A to Z), or dollar ( $ ) sign.
Numbers (0 to 9) can only be used after a letter.
Numbers (0 to 9) can only be used after a letter.
No other special character is allowed in variable name.
No other special character is allowed in variable name.
Before you use a variable in a JavaScript program, you must declare it. Variables are declared with the var keyword as follows −
<script type="text/javascript">
<!--
var money;
var name, age;
//-->
</script>
Variables can be initialized at time of declaration or after declaration as follows −
<script type="text/javascript">
<!--
var name = "Ali";
var money;
money = 2000.50;
//-->
</script>
There are two kinds of data types as mentioned below −
Primitive Data Type
Primitive Data Type
Non Primitive Data Type
Non Primitive Data Type
The following table describes Primitive Data Types available in javaScript
Can contain groups of character as single value. It is represented in double quotes.E.g. var x= “tutorial”.
Contains the numbers with or without decimal. E.g. var x=44, y=44.56;
Contain only two values either true or false. E.g. var x=true, y= false.
Variable with no value is called Undefined. E.g. var x;
If we assign null to a variable, it becomes empty. E.g. var x=null;
The following table describes Non-Primitive Data Types in javaScript
Function is a group of reusable statements (Code) that can be called any where in a program. In javascript function keyword is used to declare or define a function.
Key Points
To define a function use function keyword followed by functionname, followed by parentheses ().
To define a function use function keyword followed by functionname, followed by parentheses ().
In parenthesis, we define parameters or attributes.
In parenthesis, we define parameters or attributes.
The group of reusabe statements (code) is enclosed in curly braces {}. This code is executed whenever function is called.
The group of reusabe statements (code) is enclosed in curly braces {}. This code is executed whenever function is called.
Syntax
function functionname (p1, p2) {
function coding...
}
Operators are used to perform operation on one, two or more operands. Operator is represented by a symbol such as +, =, *, % etc. Following are the operators supported by javascript −
Arithmetic Operators
Arithmetic Operators
Comparison Operators
Comparison Operators
Logical (or Relational) Operators
Logical (or Relational) Operators
Assignment Operators
Assignment Operators
Conditional (or ternary) Operators
Conditional (or ternary) Operators
Arithmetic Operators
Arithmetic Operators
Following table shows all the arithmetic operators supported by javascript −
Following table shows all the comparison operators supported by javascript −
Following table shows all the logical operators supported by javascript −
Following table shows all the assignment operators supported by javascript −
It is also called ternary operator, since it has three operands.
Control structure actually controls the flow of execution of a program. Following are the several control structure supported by javascript.
if ... else
if ... else
switch case
switch case
do while loop
do while loop
while loop
while loop
for loop
for loop
The if statement is the fundamental control statement that allows JavaScript to make decisions and execute statements conditionally.
Syntax
if (expression){
Statement(s) to be executed if expression is true
}
Example
<script type="text/javascript">
<!--
var age = 20;
if( age > 18 ){
document.write("<b>Qualifies for driving</b>");
}
//-->
</script>
The basic syntax of the switch statement is to give an expression to evaluate and several different statements to execute based on the value of the expression. The interpreter checks each case against the value of the expression until a match is found. If nothing matches, a default condition will be used.
Syntax
switch (expression) {
case condition 1: statement(s)
break;
case condition 2: statement(s)
break;
...
case condition n: statement(s)
break;
default: statement(s)
}
Example
<script type="text/javascript">
<!--
var grade='A';
document.write("Entering switch block<br/>");
switch (grade) {
case 'A': document.write("Good job<br/>");
break;
case 'B': document.write("Pretty good<br/>");
break;
case 'C': document.write("Passed<br/>");
break;
case 'D': document.write("Not so good<br/>");
break;
case 'F': document.write("Failed<br/>");
break;
default: document.write("Unknown grade<br/>")
}
document.write("Exiting switch block");
//-->
</script>
The do...while loop is similar to the while loop except that the condition check happens at the end of the loop. This means that the loop will always be executed at least once, even if the condition is false.
Syntax
do{
Statement(s) to be executed;
} while (expression);
Example
<script type="text/javascript">
<!--
var count = 0;
document.write("Starting Loop" + "<br/>");
do{
document.write("Current Count : " + count + "<br/>");
count++;
}while (count < 0);
document.write("Loop stopped!");
//-->
</script>
This will produce following result −
Starting Loop
Current Count : 0
Loop stopped!
The purpose of a while loop is to execute a statement or code block repeatedly as long as expression is true. Once expression becomes false, the loop will be exited.
Syntax
while (expression){
Statement(s) to be executed if expression is true
}
Example
<script type="text/javascript">
<!--
var count = 0;
document.write("Starting Loop" + "<br/>");
while (count < 10){
document.write("Current Count : " + count + "<br/>");
count++;
}
document.write("Loop stopped!");
//-->
</script>
This will produce following result −
Starting Loop
Current Count : 0
Current Count : 1
Current Count : 2
Current Count : 3
Current Count : 4
Current Count : 5
Current Count : 6
Current Count : 7
Current Count : 8
Current Count : 9
Loop stopped!
The for loop is the most compact form of looping and includes the following three important parts −
The loop initialization where we initialize our counter to a starting value. The initialization statement is executed before the loop begins.
The loop initialization where we initialize our counter to a starting value. The initialization statement is executed before the loop begins.
The test statement which will test if the given condition is true or not. If condition is true then code given inside the loop will be executed otherwise loop will come out.
The test statement which will test if the given condition is true or not. If condition is true then code given inside the loop will be executed otherwise loop will come out.
The iteration statement where you can increase or decrease your counter.
The iteration statement where you can increase or decrease your counter.
Syntax
for (initialization; test condition; iteration statement){
Statement(s) to be executed if test condition is true
}
Example
<script type="text/javascript">
<!--
var count;
document.write("Starting Loop" + "<br/>");
for(count = 0; count < 10; count++){
document.write("Current Count : " + count );
document.write("<br/>");
}
document.write("Loop stopped!");
//-->
</script>
This will produce following result which is similar to while loop −
Starting Loop
Current Count : 0
Current Count : 1
Current Count : 2
Current Count : 3
Current Count : 4
Current Count : 5
Current Count : 6
Current Count : 7
Current Count : 8
Current Count : 9
Loop stopped!
Following is the sample program that shows time, when we click in button.
<html>
<body>
<button onclick="this.innerHTML=Date()">The time is?</button>
<p>Click to display the date.</p>
<button onclick="displayDate()">The time is?</button>
<script>
function displayDate() {
document.getElementById("demo").innerHTML = Date();
}</script>
<p id="demo"></p>
</script>
</body>
</html>
Output
61 Lectures
8 hours
Amit Rana
13 Lectures
2.5 hours
Raghu Pandey
5 Lectures
38 mins
Harshit Srivastava
62 Lectures
3.5 hours
YouAccel
9 Lectures
36 mins
Korey Sheppard
10 Lectures
57 mins
Taurius Litvinavicius
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2642,
"s": 2473,
"text": "JavaScript is a lightweight, interpreted programming language with object-oriented capabilities that allows you to build interactivity into otherwise static HTML pages."
},
{
"code": null,
"e": 2653,
"s": 2642,
"text": "Key Points"
},
{
"code": null,
"e": 2706,
"s": 2653,
"text": "It is Lightweight, interpreted programming language."
},
{
"code": null,
"e": 2759,
"s": 2706,
"text": "It is Lightweight, interpreted programming language."
},
{
"code": null,
"e": 2817,
"s": 2759,
"text": "It is designed for creating network-centric applications."
},
{
"code": null,
"e": 2875,
"s": 2817,
"text": "It is designed for creating network-centric applications."
},
{
"code": null,
"e": 2924,
"s": 2875,
"text": "It is complementary to and integrated with Java."
},
{
"code": null,
"e": 2973,
"s": 2924,
"text": "It is complementary to and integrated with Java."
},
{
"code": null,
"e": 3021,
"s": 2973,
"text": "It is complementary to and integrated with HTML"
},
{
"code": null,
"e": 3069,
"s": 3021,
"text": "It is complementary to and integrated with HTML"
},
{
"code": null,
"e": 3102,
"s": 3069,
"text": "It is an open and cross-platform"
},
{
"code": null,
"e": 3135,
"s": 3102,
"text": "It is an open and cross-platform"
},
{
"code": null,
"e": 3264,
"s": 3135,
"text": "JavaScript statements are the commands to tell the browser to what action to perform. Statements are separated by semicolon (;)."
},
{
"code": null,
"e": 3297,
"s": 3264,
"text": "Example of JavaScript statement:"
},
{
"code": null,
"e": 3352,
"s": 3297,
"text": "document.getElementById(\"demo\").innerHTML = \"Welcome\";"
},
{
"code": null,
"e": 3410,
"s": 3352,
"text": "Following table shows the various JavaScript Statements −"
},
{
"code": null,
"e": 3473,
"s": 3410,
"text": "JavaScript supports both C-style and C++-style comments, thus:"
},
{
"code": null,
"e": 3571,
"s": 3473,
"text": "Any text between a // and the end of a line is treated as a comment and is ignored by JavaScript."
},
{
"code": null,
"e": 3669,
"s": 3571,
"text": "Any text between a // and the end of a line is treated as a comment and is ignored by JavaScript."
},
{
"code": null,
"e": 3766,
"s": 3669,
"text": "Any text between the characters /* and */ is treated as a comment. This may span multiple lines."
},
{
"code": null,
"e": 3863,
"s": 3766,
"text": "Any text between the characters /* and */ is treated as a comment. This may span multiple lines."
},
{
"code": null,
"e": 4014,
"s": 3863,
"text": "JavaScript also recognizes the HTML comment opening sequence <!--. JavaScript treats this as a single-line comment, just as it does the // comment.-->"
},
{
"code": null,
"e": 4165,
"s": 4014,
"text": "JavaScript also recognizes the HTML comment opening sequence <!--. JavaScript treats this as a single-line comment, just as it does the // comment.-->"
},
{
"code": null,
"e": 4269,
"s": 4165,
"text": "The HTML comment closing sequence --> is not recognized by JavaScript so it should be written as //-->."
},
{
"code": null,
"e": 4373,
"s": 4269,
"text": "The HTML comment closing sequence --> is not recognized by JavaScript so it should be written as //-->."
},
{
"code": null,
"e": 4381,
"s": 4373,
"text": "Example"
},
{
"code": null,
"e": 4654,
"s": 4381,
"text": "<script language=\"javascript\" type=\"text/javascript\">\n <!--\n\n // this is a comment. It is similar to comments in C++\n\n /*\n * This is a multiline comment in JavaScript\n * It is very similar to comments in C Programming\n */\n //-->\n<script>"
},
{
"code": null,
"e": 4821,
"s": 4654,
"text": "Variables are referred as named containers for storing information. We can place data into these containers and then refer to the data simply by naming the container."
},
{
"code": null,
"e": 4914,
"s": 4821,
"text": "Here are the important rules that must be followed while declaring a variable in JavaScript."
},
{
"code": null,
"e": 4990,
"s": 4914,
"text": "In JavaScript variable names are case sensitive i.e. a is different from A."
},
{
"code": null,
"e": 5066,
"s": 4990,
"text": "In JavaScript variable names are case sensitive i.e. a is different from A."
},
{
"code": null,
"e": 5183,
"s": 5066,
"text": "Variable name can only be started with a underscore ( _ ) or a letter (from a to z or A to Z), or dollar ( $ ) sign."
},
{
"code": null,
"e": 5300,
"s": 5183,
"text": "Variable name can only be started with a underscore ( _ ) or a letter (from a to z or A to Z), or dollar ( $ ) sign."
},
{
"code": null,
"e": 5350,
"s": 5300,
"text": "Numbers (0 to 9) can only be used after a letter."
},
{
"code": null,
"e": 5400,
"s": 5350,
"text": "Numbers (0 to 9) can only be used after a letter."
},
{
"code": null,
"e": 5456,
"s": 5400,
"text": "No other special character is allowed in variable name."
},
{
"code": null,
"e": 5512,
"s": 5456,
"text": "No other special character is allowed in variable name."
},
{
"code": null,
"e": 5641,
"s": 5512,
"text": "Before you use a variable in a JavaScript program, you must declare it. Variables are declared with the var keyword as follows −"
},
{
"code": null,
"e": 5738,
"s": 5641,
"text": "<script type=\"text/javascript\">\n <!--\n var money;\n var name, age;\n //-->\n</script>"
},
{
"code": null,
"e": 5824,
"s": 5738,
"text": "Variables can be initialized at time of declaration or after declaration as follows −"
},
{
"code": null,
"e": 5947,
"s": 5824,
"text": "<script type=\"text/javascript\">\n <!--\n var name = \"Ali\";\n var money;\n money = 2000.50;\n //-->\n</script>"
},
{
"code": null,
"e": 6002,
"s": 5947,
"text": "There are two kinds of data types as mentioned below −"
},
{
"code": null,
"e": 6022,
"s": 6002,
"text": "Primitive Data Type"
},
{
"code": null,
"e": 6042,
"s": 6022,
"text": "Primitive Data Type"
},
{
"code": null,
"e": 6066,
"s": 6042,
"text": "Non Primitive Data Type"
},
{
"code": null,
"e": 6090,
"s": 6066,
"text": "Non Primitive Data Type"
},
{
"code": null,
"e": 6165,
"s": 6090,
"text": "The following table describes Primitive Data Types available in javaScript"
},
{
"code": null,
"e": 6273,
"s": 6165,
"text": "Can contain groups of character as single value. It is represented in double quotes.E.g. var x= “tutorial”."
},
{
"code": null,
"e": 6344,
"s": 6273,
"text": "Contains the numbers with or without decimal. E.g. var x=44, y=44.56;"
},
{
"code": null,
"e": 6417,
"s": 6344,
"text": "Contain only two values either true or false. E.g. var x=true, y= false."
},
{
"code": null,
"e": 6473,
"s": 6417,
"text": "Variable with no value is called Undefined. E.g. var x;"
},
{
"code": null,
"e": 6541,
"s": 6473,
"text": "If we assign null to a variable, it becomes empty. E.g. var x=null;"
},
{
"code": null,
"e": 6610,
"s": 6541,
"text": "The following table describes Non-Primitive Data Types in javaScript"
},
{
"code": null,
"e": 6776,
"s": 6610,
"text": "Function is a group of reusable statements (Code) that can be called any where in a program. In javascript function keyword is used to declare or define a function. "
},
{
"code": null,
"e": 6787,
"s": 6776,
"text": "Key Points"
},
{
"code": null,
"e": 6884,
"s": 6787,
"text": "To define a function use function keyword followed by functionname, followed by parentheses ()."
},
{
"code": null,
"e": 6981,
"s": 6884,
"text": "To define a function use function keyword followed by functionname, followed by parentheses ()."
},
{
"code": null,
"e": 7033,
"s": 6981,
"text": "In parenthesis, we define parameters or attributes."
},
{
"code": null,
"e": 7085,
"s": 7033,
"text": "In parenthesis, we define parameters or attributes."
},
{
"code": null,
"e": 7207,
"s": 7085,
"text": "The group of reusabe statements (code) is enclosed in curly braces {}. This code is executed whenever function is called."
},
{
"code": null,
"e": 7329,
"s": 7207,
"text": "The group of reusabe statements (code) is enclosed in curly braces {}. This code is executed whenever function is called."
},
{
"code": null,
"e": 7336,
"s": 7329,
"text": "Syntax"
},
{
"code": null,
"e": 7393,
"s": 7336,
"text": "function functionname (p1, p2) {\n function coding...\n}"
},
{
"code": null,
"e": 7578,
"s": 7393,
"text": "Operators are used to perform operation on one, two or more operands. Operator is represented by a symbol such as +, =, *, % etc. Following are the operators supported by javascript −"
},
{
"code": null,
"e": 7599,
"s": 7578,
"text": "Arithmetic Operators"
},
{
"code": null,
"e": 7620,
"s": 7599,
"text": "Arithmetic Operators"
},
{
"code": null,
"e": 7641,
"s": 7620,
"text": "Comparison Operators"
},
{
"code": null,
"e": 7662,
"s": 7641,
"text": "Comparison Operators"
},
{
"code": null,
"e": 7696,
"s": 7662,
"text": "Logical (or Relational) Operators"
},
{
"code": null,
"e": 7730,
"s": 7696,
"text": "Logical (or Relational) Operators"
},
{
"code": null,
"e": 7751,
"s": 7730,
"text": "Assignment Operators"
},
{
"code": null,
"e": 7772,
"s": 7751,
"text": "Assignment Operators"
},
{
"code": null,
"e": 7807,
"s": 7772,
"text": "Conditional (or ternary) Operators"
},
{
"code": null,
"e": 7842,
"s": 7807,
"text": "Conditional (or ternary) Operators"
},
{
"code": null,
"e": 7863,
"s": 7842,
"text": "Arithmetic Operators"
},
{
"code": null,
"e": 7884,
"s": 7863,
"text": "Arithmetic Operators"
},
{
"code": null,
"e": 7961,
"s": 7884,
"text": "Following table shows all the arithmetic operators supported by javascript −"
},
{
"code": null,
"e": 8038,
"s": 7961,
"text": "Following table shows all the comparison operators supported by javascript −"
},
{
"code": null,
"e": 8112,
"s": 8038,
"text": "Following table shows all the logical operators supported by javascript −"
},
{
"code": null,
"e": 8189,
"s": 8112,
"text": "Following table shows all the assignment operators supported by javascript −"
},
{
"code": null,
"e": 8254,
"s": 8189,
"text": "It is also called ternary operator, since it has three operands."
},
{
"code": null,
"e": 8395,
"s": 8254,
"text": "Control structure actually controls the flow of execution of a program. Following are the several control structure supported by javascript."
},
{
"code": null,
"e": 8407,
"s": 8395,
"text": "if ... else"
},
{
"code": null,
"e": 8419,
"s": 8407,
"text": "if ... else"
},
{
"code": null,
"e": 8431,
"s": 8419,
"text": "switch case"
},
{
"code": null,
"e": 8443,
"s": 8431,
"text": "switch case"
},
{
"code": null,
"e": 8457,
"s": 8443,
"text": "do while loop"
},
{
"code": null,
"e": 8471,
"s": 8457,
"text": "do while loop"
},
{
"code": null,
"e": 8482,
"s": 8471,
"text": "while loop"
},
{
"code": null,
"e": 8493,
"s": 8482,
"text": "while loop"
},
{
"code": null,
"e": 8502,
"s": 8493,
"text": "for loop"
},
{
"code": null,
"e": 8511,
"s": 8502,
"text": "for loop"
},
{
"code": null,
"e": 8644,
"s": 8511,
"text": "The if statement is the fundamental control statement that allows JavaScript to make decisions and execute statements conditionally."
},
{
"code": null,
"e": 8651,
"s": 8644,
"text": "Syntax"
},
{
"code": null,
"e": 8723,
"s": 8651,
"text": "if (expression){\n Statement(s) to be executed if expression is true\n}"
},
{
"code": null,
"e": 8731,
"s": 8723,
"text": "Example"
},
{
"code": null,
"e": 8897,
"s": 8731,
"text": "<script type=\"text/javascript\">\n <!--\n var age = 20;\n if( age > 18 ){\n document.write(\"<b>Qualifies for driving</b>\");\n }\n //-->\n</script>"
},
{
"code": null,
"e": 9204,
"s": 8897,
"text": "The basic syntax of the switch statement is to give an expression to evaluate and several different statements to execute based on the value of the expression. The interpreter checks each case against the value of the expression until a match is found. If nothing matches, a default condition will be used."
},
{
"code": null,
"e": 9211,
"s": 9204,
"text": "Syntax"
},
{
"code": null,
"e": 9450,
"s": 9211,
"text": "switch (expression) {\n case condition 1: statement(s)\n break;\n case condition 2: statement(s)\n break;\n ...\n case condition n: statement(s)\n break;\n default: statement(s)\n}"
},
{
"code": null,
"e": 9458,
"s": 9450,
"text": "Example"
},
{
"code": null,
"e": 10080,
"s": 9458,
"text": "<script type=\"text/javascript\">\n <!--\n var grade='A';\n document.write(\"Entering switch block<br/>\");\n switch (grade) {\n case 'A': document.write(\"Good job<br/>\");\n break;\n case 'B': document.write(\"Pretty good<br/>\");\n break;\n case 'C': document.write(\"Passed<br/>\");\n break;\n case 'D': document.write(\"Not so good<br/>\");\n break;\n case 'F': document.write(\"Failed<br/>\");\n break;\n default: document.write(\"Unknown grade<br/>\")\n }\n document.write(\"Exiting switch block\");\n //-->\n</script>"
},
{
"code": null,
"e": 10289,
"s": 10080,
"text": "The do...while loop is similar to the while loop except that the condition check happens at the end of the loop. This means that the loop will always be executed at least once, even if the condition is false."
},
{
"code": null,
"e": 10296,
"s": 10289,
"text": "Syntax"
},
{
"code": null,
"e": 10354,
"s": 10296,
"text": "do{\n Statement(s) to be executed;\n} while (expression);"
},
{
"code": null,
"e": 10362,
"s": 10354,
"text": "Example"
},
{
"code": null,
"e": 10647,
"s": 10362,
"text": "<script type=\"text/javascript\">\n <!--\n var count = 0;\n document.write(\"Starting Loop\" + \"<br/>\");\n do{\n document.write(\"Current Count : \" + count + \"<br/>\");\n count++;\n }while (count < 0);\n document.write(\"Loop stopped!\");\n //-->\n</script>"
},
{
"code": null,
"e": 10684,
"s": 10647,
"text": "This will produce following result −"
},
{
"code": null,
"e": 10732,
"s": 10684,
"text": "Starting Loop\nCurrent Count : 0\nLoop stopped! \n"
},
{
"code": null,
"e": 10898,
"s": 10732,
"text": "The purpose of a while loop is to execute a statement or code block repeatedly as long as expression is true. Once expression becomes false, the loop will be exited."
},
{
"code": null,
"e": 10905,
"s": 10898,
"text": "Syntax"
},
{
"code": null,
"e": 10980,
"s": 10905,
"text": "while (expression){\n Statement(s) to be executed if expression is true\n}"
},
{
"code": null,
"e": 10988,
"s": 10980,
"text": "Example"
},
{
"code": null,
"e": 11271,
"s": 10988,
"text": "<script type=\"text/javascript\">\n <!--\n var count = 0;\n document.write(\"Starting Loop\" + \"<br/>\");\n while (count < 10){\n document.write(\"Current Count : \" + count + \"<br/>\");\n count++;\n }\n document.write(\"Loop stopped!\");\n //-->\n</script>"
},
{
"code": null,
"e": 11308,
"s": 11271,
"text": "This will produce following result −"
},
{
"code": null,
"e": 11518,
"s": 11308,
"text": "Starting Loop\nCurrent Count : 0\nCurrent Count : 1\nCurrent Count : 2\nCurrent Count : 3\nCurrent Count : 4\nCurrent Count : 5\nCurrent Count : 6\nCurrent Count : 7\nCurrent Count : 8\nCurrent Count : 9\nLoop stopped! \n"
},
{
"code": null,
"e": 11618,
"s": 11518,
"text": "The for loop is the most compact form of looping and includes the following three important parts −"
},
{
"code": null,
"e": 11760,
"s": 11618,
"text": "The loop initialization where we initialize our counter to a starting value. The initialization statement is executed before the loop begins."
},
{
"code": null,
"e": 11902,
"s": 11760,
"text": "The loop initialization where we initialize our counter to a starting value. The initialization statement is executed before the loop begins."
},
{
"code": null,
"e": 12076,
"s": 11902,
"text": "The test statement which will test if the given condition is true or not. If condition is true then code given inside the loop will be executed otherwise loop will come out."
},
{
"code": null,
"e": 12250,
"s": 12076,
"text": "The test statement which will test if the given condition is true or not. If condition is true then code given inside the loop will be executed otherwise loop will come out."
},
{
"code": null,
"e": 12323,
"s": 12250,
"text": "The iteration statement where you can increase or decrease your counter."
},
{
"code": null,
"e": 12396,
"s": 12323,
"text": "The iteration statement where you can increase or decrease your counter."
},
{
"code": null,
"e": 12403,
"s": 12396,
"text": "Syntax"
},
{
"code": null,
"e": 12521,
"s": 12403,
"text": "for (initialization; test condition; iteration statement){\n Statement(s) to be executed if test condition is true\n}"
},
{
"code": null,
"e": 12529,
"s": 12521,
"text": "Example"
},
{
"code": null,
"e": 12832,
"s": 12529,
"text": "<script type=\"text/javascript\">\n <!--\n var count;\n document.write(\"Starting Loop\" + \"<br/>\");\n for(count = 0; count < 10; count++){\n document.write(\"Current Count : \" + count );\n document.write(\"<br/>\");\n }\n document.write(\"Loop stopped!\");\n //-->\n</script>"
},
{
"code": null,
"e": 12900,
"s": 12832,
"text": "This will produce following result which is similar to while loop −"
},
{
"code": null,
"e": 13110,
"s": 12900,
"text": "Starting Loop\nCurrent Count : 0\nCurrent Count : 1\nCurrent Count : 2\nCurrent Count : 3\nCurrent Count : 4\nCurrent Count : 5\nCurrent Count : 6\nCurrent Count : 7\nCurrent Count : 8\nCurrent Count : 9\nLoop stopped! \n"
},
{
"code": null,
"e": 13184,
"s": 13110,
"text": "Following is the sample program that shows time, when we click in button."
},
{
"code": null,
"e": 13565,
"s": 13184,
"text": "<html>\n <body>\n <button onclick=\"this.innerHTML=Date()\">The time is?</button>\n <p>Click to display the date.</p>\n <button onclick=\"displayDate()\">The time is?</button>\n <script>\n function displayDate() {\n document.getElementById(\"demo\").innerHTML = Date();\n }</script>\n\n <p id=\"demo\"></p>\n </script>\n </body>\n</html>"
},
{
"code": null,
"e": 13572,
"s": 13565,
"text": "Output"
},
{
"code": null,
"e": 13605,
"s": 13572,
"text": "\n 61 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 13616,
"s": 13605,
"text": " Amit Rana"
},
{
"code": null,
"e": 13651,
"s": 13616,
"text": "\n 13 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 13665,
"s": 13651,
"text": " Raghu Pandey"
},
{
"code": null,
"e": 13696,
"s": 13665,
"text": "\n 5 Lectures \n 38 mins\n"
},
{
"code": null,
"e": 13716,
"s": 13696,
"text": " Harshit Srivastava"
},
{
"code": null,
"e": 13751,
"s": 13716,
"text": "\n 62 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 13761,
"s": 13751,
"text": " YouAccel"
},
{
"code": null,
"e": 13792,
"s": 13761,
"text": "\n 9 Lectures \n 36 mins\n"
},
{
"code": null,
"e": 13808,
"s": 13792,
"text": " Korey Sheppard"
},
{
"code": null,
"e": 13840,
"s": 13808,
"text": "\n 10 Lectures \n 57 mins\n"
},
{
"code": null,
"e": 13863,
"s": 13840,
"text": " Taurius Litvinavicius"
},
{
"code": null,
"e": 13870,
"s": 13863,
"text": " Print"
},
{
"code": null,
"e": 13881,
"s": 13870,
"text": " Add Notes"
}
] |
Yii - Rules of URL | A URL rule is an instance if yii\web\UrlRule. The urlManager components uses the URL rules declared in its rules property when the pretty URL format is enabled.
To parse a request, the URL manager obtains the rules in the order they are declared and looks for the first rule.
Step 1 − Modify the urlManager component in the config/web.php file.
'urlManager' => [
'showScriptName' => false,
'enablePrettyUrl' => true,
'rules' => [
'about' => 'site/about',
]
],
Step 2 − Go to your web browser at http://localhost:8080/about, you will see the about page.
A URL rule can be associated with query parameters in this pattern −
<ParamName:RegExp>, where −
ParamName − The parameter name
ParamName − The parameter name
RegExp − An optional regular expression used to match parameter values
RegExp − An optional regular expression used to match parameter values
Suppose, we have declared the following URL rules −
[
'articles/<year:\d{4}>/<category>' => 'article/index',
'articles' => 'article/index',
'article/<id:\d+>' => 'article/view',
]
When the rules are used for parsing −
/index.php/articles is parsed into the article/index
/index.php/articles/2014/php is parsed into the article/index
/index.php/article/100 is parsed into the article/view
/index.php/articles/php is parsed into articles/php
When the rules are used for creating URLs −
Url::to(['article/index']) creates /index.php/articles
Url::to(['article/index']) creates /index.php/articles
Url::to(['article/index', 'year' => 2014, 'category' => 'php']) creates /index.php/articles/2014/php
Url::to(['article/index', 'year' => 2014, 'category' => 'php']) creates /index.php/articles/2014/php
Url::to(['article/view', 'id' => 100]) creates /index.php/article/100
Url::to(['article/view', 'id' => 100]) creates /index.php/article/100
Url::to(['article/view', 'id' => 100, 'source' => 'ad']) creates /index.php/article/100?source=ad
Url::to(['article/view', 'id' => 100, 'source' => 'ad']) creates /index.php/article/100?source=ad
Url::to(['article/index', 'category' => 'php']) creates /index.php/article/index?category=php
Url::to(['article/index', 'category' => 'php']) creates /index.php/article/index?category=php
To add a suffix to the URL, you should configure the yii\web\UrlManager::$suffix property.
Step 3 − Modify the urlComponent in the config/web.php file.
'urlManager' => [
'showScriptName' => false,
'enablePrettyUrl' => true,
'enableStrictParsing' => true,
'suffix' => '.html'
],
Step 4 − Type the address http://localhost:8080/site/contact.html in the address bar of the web browser and you will see the following on your screen. Notice the html suffix.
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2994,
"s": 2833,
"text": "A URL rule is an instance if yii\\web\\UrlRule. The urlManager components uses the URL rules declared in its rules property when the pretty URL format is enabled."
},
{
"code": null,
"e": 3109,
"s": 2994,
"text": "To parse a request, the URL manager obtains the rules in the order they are declared and looks for the first rule."
},
{
"code": null,
"e": 3178,
"s": 3109,
"text": "Step 1 − Modify the urlManager component in the config/web.php file."
},
{
"code": null,
"e": 3311,
"s": 3178,
"text": "'urlManager' => [\n 'showScriptName' => false,\n 'enablePrettyUrl' => true,\n 'rules' => [\n 'about' => 'site/about',\n ]\n],"
},
{
"code": null,
"e": 3404,
"s": 3311,
"text": "Step 2 − Go to your web browser at http://localhost:8080/about, you will see the about page."
},
{
"code": null,
"e": 3473,
"s": 3404,
"text": "A URL rule can be associated with query parameters in this pattern −"
},
{
"code": null,
"e": 3501,
"s": 3473,
"text": "<ParamName:RegExp>, where −"
},
{
"code": null,
"e": 3532,
"s": 3501,
"text": "ParamName − The parameter name"
},
{
"code": null,
"e": 3563,
"s": 3532,
"text": "ParamName − The parameter name"
},
{
"code": null,
"e": 3634,
"s": 3563,
"text": "RegExp − An optional regular expression used to match parameter values"
},
{
"code": null,
"e": 3705,
"s": 3634,
"text": "RegExp − An optional regular expression used to match parameter values"
},
{
"code": null,
"e": 3757,
"s": 3705,
"text": "Suppose, we have declared the following URL rules −"
},
{
"code": null,
"e": 3894,
"s": 3757,
"text": "[\n 'articles/<year:\\d{4}>/<category>' => 'article/index',\n 'articles' => 'article/index',\n 'article/<id:\\d+>' => 'article/view',\n]"
},
{
"code": null,
"e": 3932,
"s": 3894,
"text": "When the rules are used for parsing −"
},
{
"code": null,
"e": 3985,
"s": 3932,
"text": "/index.php/articles is parsed into the article/index"
},
{
"code": null,
"e": 4047,
"s": 3985,
"text": "/index.php/articles/2014/php is parsed into the article/index"
},
{
"code": null,
"e": 4102,
"s": 4047,
"text": "/index.php/article/100 is parsed into the article/view"
},
{
"code": null,
"e": 4154,
"s": 4102,
"text": "/index.php/articles/php is parsed into articles/php"
},
{
"code": null,
"e": 4198,
"s": 4154,
"text": "When the rules are used for creating URLs −"
},
{
"code": null,
"e": 4253,
"s": 4198,
"text": "Url::to(['article/index']) creates /index.php/articles"
},
{
"code": null,
"e": 4308,
"s": 4253,
"text": "Url::to(['article/index']) creates /index.php/articles"
},
{
"code": null,
"e": 4409,
"s": 4308,
"text": "Url::to(['article/index', 'year' => 2014, 'category' => 'php']) creates /index.php/articles/2014/php"
},
{
"code": null,
"e": 4510,
"s": 4409,
"text": "Url::to(['article/index', 'year' => 2014, 'category' => 'php']) creates /index.php/articles/2014/php"
},
{
"code": null,
"e": 4580,
"s": 4510,
"text": "Url::to(['article/view', 'id' => 100]) creates /index.php/article/100"
},
{
"code": null,
"e": 4650,
"s": 4580,
"text": "Url::to(['article/view', 'id' => 100]) creates /index.php/article/100"
},
{
"code": null,
"e": 4748,
"s": 4650,
"text": "Url::to(['article/view', 'id' => 100, 'source' => 'ad']) creates /index.php/article/100?source=ad"
},
{
"code": null,
"e": 4846,
"s": 4748,
"text": "Url::to(['article/view', 'id' => 100, 'source' => 'ad']) creates /index.php/article/100?source=ad"
},
{
"code": null,
"e": 4940,
"s": 4846,
"text": "Url::to(['article/index', 'category' => 'php']) creates /index.php/article/index?category=php"
},
{
"code": null,
"e": 5034,
"s": 4940,
"text": "Url::to(['article/index', 'category' => 'php']) creates /index.php/article/index?category=php"
},
{
"code": null,
"e": 5125,
"s": 5034,
"text": "To add a suffix to the URL, you should configure the yii\\web\\UrlManager::$suffix property."
},
{
"code": null,
"e": 5186,
"s": 5125,
"text": "Step 3 − Modify the urlComponent in the config/web.php file."
},
{
"code": null,
"e": 5324,
"s": 5186,
"text": "'urlManager' => [\n 'showScriptName' => false,\n 'enablePrettyUrl' => true,\n 'enableStrictParsing' => true,\n 'suffix' => '.html'\n],"
},
{
"code": null,
"e": 5499,
"s": 5324,
"text": "Step 4 − Type the address http://localhost:8080/site/contact.html in the address bar of the web browser and you will see the following on your screen. Notice the html suffix."
},
{
"code": null,
"e": 5506,
"s": 5499,
"text": " Print"
},
{
"code": null,
"e": 5517,
"s": 5506,
"text": " Add Notes"
}
] |
Spring MVC - TextArea Example | The following example explains how to use TextArea in forms using the Spring Web MVC framework. To begin with, let us have a working Eclipse IDE in place and follow the subsequent steps to develop a Dynamic Form based Web Application using the Spring Web Framework.
package com.tutorialspoint;
public class User {
private String username;
private String password;
private String address;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
package com.tutorialspoint;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.ui.ModelMap;
@Controller
public class UserController {
@RequestMapping(value = "/user", method = RequestMethod.GET)
public ModelAndView user() {
return new ModelAndView("user", "command", new User());
}
@RequestMapping(value = "/addUser", method = RequestMethod.POST)
public String addUser(@ModelAttribute("SpringWeb")User user,
ModelMap model) {
model.addAttribute("username", user.getUsername());
model.addAttribute("password", user.getPassword());
model.addAttribute("address", user.getAddress());
return "users";
}
}
Here, for the first service method user(), we have passed a blank User object in the ModelAndView object with name "command", because the spring framework expects an object with name "command", if you are using <form:form> tags in your JSP file. So, when the user() method is called, it returns the user.jsp view.
The second service method addUser() will be called against a POST method on the HelloWeb/addUser URL. You will prepare your model object based on the submitted information. Finally, the "users" view will be returned from the service method, which will result in rendering the users.jsp.
<%@taglib uri = "http://www.springframework.org/tags/form" prefix = "form"%>
<html>
<head>
<title>Spring MVC Form Handling</title>
</head>
<body>
<h2>User Information</h2>
<form:form method = "POST" action = "/HelloWeb/addUser">
<table>
<tr>
<td><form:label path = "username">User Name</form:label></td>
<td><form:input path = "username" /></td>
</tr>
<tr>
<td><form:label path = "password">Age</form:label></td>
<td><form:password path = "password" /></td>
</tr>
<tr>
<td><form:label path = "address">Address</form:label></td>
<td><form:textarea path = "address" rows = "5" cols = "30" /></td>
</tr>
<tr>
<td colspan = "2">
<input type = "submit" value = "Submit"/>
</td>
</tr>
</table>
</form:form>
</body>
</html>
Here, we are using <form:textarea /> tag to render a HTML textarea box. For example −
<form:textarea path = "address" rows = "5" cols = "30" />
It will render the following HTML content.
<textarea id = "address" name = "address" rows = "5" cols = "30"></textarea>
<%@taglib uri = "http://www.springframework.org/tags/form" prefix = "form"%>
<html>
<head>
<title>Spring MVC Form Handling</title>
</head>
<body>
<h2>Submitted User Information</h2>
<table>
<tr>
<td>Username</td>
<td>${username}</td>
</tr>
<tr>
<td>Password</td>
<td>${password}</td>
</tr>
<tr>
<td>Address</td>
<td>${address}</td>
</tr>
</table>
</body>
</html>
Once you are done with creating source and configuration files, export your application. Right click on your application, use Export → WAR File option and save your HelloWeb.war file in Tomcat's webapps folder.
Now, start your Tomcat server and make sure you are able to access other webpages from webapps folder using a standard browser. Try a URL –http://localhost:8080/HelloWeb/user and we will see the following screen if everything is fine with the Spring Web Application.
After submitting the required information, click on the submit button to submit the form. We will see the following screen, if everything is fine with the Spring Web Application.
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 3057,
"s": 2791,
"text": "The following example explains how to use TextArea in forms using the Spring Web MVC framework. To begin with, let us have a working Eclipse IDE in place and follow the subsequent steps to develop a Dynamic Form based Web Application using the Spring Web Framework."
},
{
"code": null,
"e": 3622,
"s": 3057,
"text": "package com.tutorialspoint;\n\npublic class User {\n\t\n private String username;\n private String password;\n private String address;\n\n public String getUsername() {\n return username;\n }\n public void setUsername(String username) {\n this.username = username;\n }\n\n public String getPassword() {\n return password;\n }\n public void setPassword(String password) {\n this.password = password;\n }\n public String getAddress() {\n return address;\n }\n public void setAddress(String address) {\n this.address = address;\n }\n}\n"
},
{
"code": null,
"e": 4552,
"s": 3622,
"text": "package com.tutorialspoint;\n\nimport org.springframework.stereotype.Controller;\nimport org.springframework.web.bind.annotation.ModelAttribute;\nimport org.springframework.web.bind.annotation.RequestMapping;\nimport org.springframework.web.bind.annotation.RequestMethod;\nimport org.springframework.web.servlet.ModelAndView;\nimport org.springframework.ui.ModelMap;\n\n@Controller\npublic class UserController {\n\n @RequestMapping(value = \"/user\", method = RequestMethod.GET)\n public ModelAndView user() {\n return new ModelAndView(\"user\", \"command\", new User());\n }\n\n @RequestMapping(value = \"/addUser\", method = RequestMethod.POST)\n public String addUser(@ModelAttribute(\"SpringWeb\")User user, \n ModelMap model) {\n model.addAttribute(\"username\", user.getUsername());\n model.addAttribute(\"password\", user.getPassword());\n model.addAttribute(\"address\", user.getAddress());\n\t \n return \"users\";\n }\n}"
},
{
"code": null,
"e": 4866,
"s": 4552,
"text": "Here, for the first service method user(), we have passed a blank User object in the ModelAndView object with name \"command\", because the spring framework expects an object with name \"command\", if you are using <form:form> tags in your JSP file. So, when the user() method is called, it returns the user.jsp view."
},
{
"code": null,
"e": 5153,
"s": 4866,
"text": "The second service method addUser() will be called against a POST method on the HelloWeb/addUser URL. You will prepare your model object based on the submitted information. Finally, the \"users\" view will be returned from the service method, which will result in rendering the users.jsp."
},
{
"code": null,
"e": 6099,
"s": 5153,
"text": "<%@taglib uri = \"http://www.springframework.org/tags/form\" prefix = \"form\"%>\n<html>\n <head>\n <title>Spring MVC Form Handling</title>\n </head>\n <body>\n\n <h2>User Information</h2>\n <form:form method = \"POST\" action = \"/HelloWeb/addUser\">\n <table>\n <tr>\n <td><form:label path = \"username\">User Name</form:label></td>\n <td><form:input path = \"username\" /></td>\n </tr>\n <tr>\n <td><form:label path = \"password\">Age</form:label></td>\n <td><form:password path = \"password\" /></td>\n </tr> \n <tr>\n <td><form:label path = \"address\">Address</form:label></td>\n <td><form:textarea path = \"address\" rows = \"5\" cols = \"30\" /></td>\n </tr> \n <tr>\n <td colspan = \"2\">\n <input type = \"submit\" value = \"Submit\"/>\n </td>\n </tr>\n </table> \n </form:form>\n </body>\n</html>"
},
{
"code": null,
"e": 6185,
"s": 6099,
"text": "Here, we are using <form:textarea /> tag to render a HTML textarea box. For example −"
},
{
"code": null,
"e": 6243,
"s": 6185,
"text": "<form:textarea path = \"address\" rows = \"5\" cols = \"30\" />"
},
{
"code": null,
"e": 6286,
"s": 6243,
"text": "It will render the following HTML content."
},
{
"code": null,
"e": 6363,
"s": 6286,
"text": "<textarea id = \"address\" name = \"address\" rows = \"5\" cols = \"30\"></textarea>"
},
{
"code": null,
"e": 6898,
"s": 6363,
"text": "<%@taglib uri = \"http://www.springframework.org/tags/form\" prefix = \"form\"%>\n<html>\n <head>\n <title>Spring MVC Form Handling</title>\n </head>\n <body>\n\n <h2>Submitted User Information</h2>\n <table>\n <tr>\n <td>Username</td>\n <td>${username}</td>\n </tr>\n <tr>\n <td>Password</td>\n <td>${password}</td>\n </tr> \n <tr>\n <td>Address</td>\n <td>${address}</td>\n </tr> \n </table> \n </body>\n</html>"
},
{
"code": null,
"e": 7109,
"s": 6898,
"text": "Once you are done with creating source and configuration files, export your application. Right click on your application, use Export → WAR File option and save your HelloWeb.war file in Tomcat's webapps folder."
},
{
"code": null,
"e": 7376,
"s": 7109,
"text": "Now, start your Tomcat server and make sure you are able to access other webpages from webapps folder using a standard browser. Try a URL –http://localhost:8080/HelloWeb/user and we will see the following screen if everything is fine with the Spring Web Application."
},
{
"code": null,
"e": 7555,
"s": 7376,
"text": "After submitting the required information, click on the submit button to submit the form. We will see the following screen, if everything is fine with the Spring Web Application."
},
{
"code": null,
"e": 7562,
"s": 7555,
"text": " Print"
},
{
"code": null,
"e": 7573,
"s": 7562,
"text": " Add Notes"
}
] |
Filtering array to contain palindrome elements in JavaScript | We are required to write a JavaScript function that takes in an array of String / Number literals and returns a subarray of all the elements that were palindrome in the original array.
If the input array is −
const arr = ['carecar', 1344, 12321, 'did', 'cannot'];
Then the output should be −
const output = [12321, 'did'];
We will create a helper function that takes in a number or a string and checks if its a boolean or not.
Then we will loop over the array, filter the palindrome elements and return the filtered array.
Therefore, let’s write the code for this function −
The code for this will be −
const arr = ['carecar', 1344, 12321, 'did', 'cannot'];
const isPalindrome = el => {
const str = String(el);
let i = 0;
let j = str.length - 1;
while(i < j) {
if(str[i] === str[j]) {
i++;
j--;
} else {
return false;
}
}
return true;
};
const findPalindrome = arr => {
return arr.filter(el => isPalindrome(el));
};
console.log(findPalindrome(arr));
The output in the console will be −
[ 12321, 'did' ] | [
{
"code": null,
"e": 1247,
"s": 1062,
"text": "We are required to write a JavaScript function that takes in an array of String / Number literals and returns a subarray of all the elements that were palindrome in the original array."
},
{
"code": null,
"e": 1271,
"s": 1247,
"text": "If the input array is −"
},
{
"code": null,
"e": 1326,
"s": 1271,
"text": "const arr = ['carecar', 1344, 12321, 'did', 'cannot'];"
},
{
"code": null,
"e": 1354,
"s": 1326,
"text": "Then the output should be −"
},
{
"code": null,
"e": 1385,
"s": 1354,
"text": "const output = [12321, 'did'];"
},
{
"code": null,
"e": 1489,
"s": 1385,
"text": "We will create a helper function that takes in a number or a string and checks if its a boolean or not."
},
{
"code": null,
"e": 1585,
"s": 1489,
"text": "Then we will loop over the array, filter the palindrome elements and return the filtered array."
},
{
"code": null,
"e": 1637,
"s": 1585,
"text": "Therefore, let’s write the code for this function −"
},
{
"code": null,
"e": 1665,
"s": 1637,
"text": "The code for this will be −"
},
{
"code": null,
"e": 2078,
"s": 1665,
"text": "const arr = ['carecar', 1344, 12321, 'did', 'cannot'];\nconst isPalindrome = el => {\n const str = String(el);\n let i = 0;\n let j = str.length - 1;\n while(i < j) {\n if(str[i] === str[j]) {\n i++;\n j--;\n } else {\n return false;\n }\n }\n return true;\n};\nconst findPalindrome = arr => {\n return arr.filter(el => isPalindrome(el));\n};\nconsole.log(findPalindrome(arr));"
},
{
"code": null,
"e": 2114,
"s": 2078,
"text": "The output in the console will be −"
},
{
"code": null,
"e": 2131,
"s": 2114,
"text": "[ 12321, 'did' ]"
}
] |
C++ Set Library - begin Function | It returns an iterator referring to the first element in the set container.
Following are the ways in which std::set::begin works in various C++ versions.
iterator begin();
const_iterator begin() const;
iterator begin() noexcept;
const_iterator begin() const noexcept;
It returns an iterator referring to the first element in the set container.
It never throws exceptions.
Time complexity is contstant.
The following example shows the usage of std::set::begin.
#include <iostream>
#include <set>
int main () {
int myints[] = {50,40,30,20,10};
std::set<int> myset (myints,myints+10);
std::cout << "myset contains:";
for (std::set<int>::iterator it = myset.begin(); it!=myset.end(); ++it)
std::cout << ' ' << *it;
std::cout << '\n';
return 0;
}
The above program will compile and execute properly.
myset contains: 0 1 10 20 30 40 50 26390 2065620553
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2679,
"s": 2603,
"text": "It returns an iterator referring to the first element in the set container."
},
{
"code": null,
"e": 2758,
"s": 2679,
"text": "Following are the ways in which std::set::begin works in various C++ versions."
},
{
"code": null,
"e": 2807,
"s": 2758,
"text": "iterator begin();\nconst_iterator begin() const;\n"
},
{
"code": null,
"e": 2875,
"s": 2807,
"text": " iterator begin() noexcept;\nconst_iterator begin() const noexcept;\n"
},
{
"code": null,
"e": 2951,
"s": 2875,
"text": "It returns an iterator referring to the first element in the set container."
},
{
"code": null,
"e": 2979,
"s": 2951,
"text": "It never throws exceptions."
},
{
"code": null,
"e": 3009,
"s": 2979,
"text": "Time complexity is contstant."
},
{
"code": null,
"e": 3067,
"s": 3009,
"text": "The following example shows the usage of std::set::begin."
},
{
"code": null,
"e": 3377,
"s": 3067,
"text": "#include <iostream>\n#include <set>\n\nint main () {\n int myints[] = {50,40,30,20,10};\n std::set<int> myset (myints,myints+10);\n\n std::cout << \"myset contains:\";\n for (std::set<int>::iterator it = myset.begin(); it!=myset.end(); ++it)\n std::cout << ' ' << *it;\n\n std::cout << '\\n';\n\n return 0;\n}"
},
{
"code": null,
"e": 3430,
"s": 3377,
"text": "The above program will compile and execute properly."
},
{
"code": null,
"e": 3483,
"s": 3430,
"text": "myset contains: 0 1 10 20 30 40 50 26390 2065620553\n"
},
{
"code": null,
"e": 3490,
"s": 3483,
"text": " Print"
},
{
"code": null,
"e": 3501,
"s": 3490,
"text": " Add Notes"
}
] |
Generate Random double type number in Java | In order to generate Random double type numbers in Java, we use the nextDouble() method of the java.util.Random class. This returns the next random double value between 0.0 (inclusive) and 1.0 (exclusive) from the random generator sequence.
Declaration - The java.util.Random.nextDouble() method is declared as follows −
public float nextDouble()
Let us see a program to generate random double type numbers in Java −
Live Demo
import java.util.Random;
public class Example {
public static void main(String[] args) {
Random rd = new Random(); // creating Random object
System.out.println(rd.nextDouble()); // displaying a random double value between 0.0 & 1.0
}
}
0.40755033612457214
Note - The output might vary on Online Compilers. | [
{
"code": null,
"e": 1303,
"s": 1062,
"text": "In order to generate Random double type numbers in Java, we use the nextDouble() method of the java.util.Random class. This returns the next random double value between 0.0 (inclusive) and 1.0 (exclusive) from the random generator sequence."
},
{
"code": null,
"e": 1383,
"s": 1303,
"text": "Declaration - The java.util.Random.nextDouble() method is declared as follows −"
},
{
"code": null,
"e": 1409,
"s": 1383,
"text": "public float nextDouble()"
},
{
"code": null,
"e": 1479,
"s": 1409,
"text": "Let us see a program to generate random double type numbers in Java −"
},
{
"code": null,
"e": 1490,
"s": 1479,
"text": " Live Demo"
},
{
"code": null,
"e": 1744,
"s": 1490,
"text": "import java.util.Random;\npublic class Example {\n public static void main(String[] args) {\n Random rd = new Random(); // creating Random object\n System.out.println(rd.nextDouble()); // displaying a random double value between 0.0 & 1.0\n }\n}"
},
{
"code": null,
"e": 1764,
"s": 1744,
"text": "0.40755033612457214"
},
{
"code": null,
"e": 1814,
"s": 1764,
"text": "Note - The output might vary on Online Compilers."
}
] |
Unvalidated Redirects and Forwards | Most web applications on the internet frequently redirect and forward users to other pages or other external websites. However, without validating the credibility of those pages, hackers can redirect victims to phishing or malware sites, or use forwards to access unauthorized pages.
Let us understand Threat Agents, Attack Vectors, Security Weakness, Technical Impact and Business Impacts of this flaw with the help of simple diagram.
Some classic examples of Unvalidated Redirects and Forwards are as given −
Let us say the application has a page - redirect.jsp, which takes a parameter redirectrul. The hacker adds a malicious URL that redirects users which performs phishing/installs malware.
Let us say the application has a page - redirect.jsp, which takes a parameter redirectrul. The hacker adds a malicious URL that redirects users which performs phishing/installs malware.
http://www.mywebapp.com/redirect.jsp?redirectrul=hacker.com
All web application used to forward users to different parts of the site. In order to achieve the same, some pages use a parameter to indicate where the user should be redirected if an operation is successful. The attacker crafts an URL that passes the application's access control check and then forwards the attacker to administrative functionality for which the attacker has not got the access.
All web application used to forward users to different parts of the site. In order to achieve the same, some pages use a parameter to indicate where the user should be redirected if an operation is successful. The attacker crafts an URL that passes the application's access control check and then forwards the attacker to administrative functionality for which the attacker has not got the access.
http://www.mywebapp.com/checkstatus.jsp?fwd=appadmin.jsp
It is better to avoid using redirects and forwards.
It is better to avoid using redirects and forwards.
If it is unavoidable, then it should be done without involving user parameters in redirecting the destination.
If it is unavoidable, then it should be done without involving user parameters in redirecting the destination.
36 Lectures
5 hours
Sharad Kumar
26 Lectures
2.5 hours
Harshit Srivastava
47 Lectures
2 hours
Dhabaleshwar Das
14 Lectures
1.5 hours
Harshit Srivastava
38 Lectures
3 hours
Harshit Srivastava
32 Lectures
3 hours
Harshit Srivastava
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2724,
"s": 2440,
"text": "Most web applications on the internet frequently redirect and forward users to other pages or other external websites. However, without validating the credibility of those pages, hackers can redirect victims to phishing or malware sites, or use forwards to access unauthorized pages."
},
{
"code": null,
"e": 2876,
"s": 2724,
"text": "Let us understand Threat Agents, Attack Vectors, Security Weakness, Technical Impact and Business Impacts of this flaw with the help of simple diagram."
},
{
"code": null,
"e": 2951,
"s": 2876,
"text": "Some classic examples of Unvalidated Redirects and Forwards are as given −"
},
{
"code": null,
"e": 3137,
"s": 2951,
"text": "Let us say the application has a page - redirect.jsp, which takes a parameter redirectrul. The hacker adds a malicious URL that redirects users which performs phishing/installs malware."
},
{
"code": null,
"e": 3323,
"s": 3137,
"text": "Let us say the application has a page - redirect.jsp, which takes a parameter redirectrul. The hacker adds a malicious URL that redirects users which performs phishing/installs malware."
},
{
"code": null,
"e": 3384,
"s": 3323,
"text": "http://www.mywebapp.com/redirect.jsp?redirectrul=hacker.com\n"
},
{
"code": null,
"e": 3782,
"s": 3384,
"text": "All web application used to forward users to different parts of the site. In order to achieve the same, some pages use a parameter to indicate where the user should be redirected if an operation is successful. The attacker crafts an URL that passes the application's access control check and then forwards the attacker to administrative functionality for which the attacker has not got the access."
},
{
"code": null,
"e": 4180,
"s": 3782,
"text": "All web application used to forward users to different parts of the site. In order to achieve the same, some pages use a parameter to indicate where the user should be redirected if an operation is successful. The attacker crafts an URL that passes the application's access control check and then forwards the attacker to administrative functionality for which the attacker has not got the access."
},
{
"code": null,
"e": 4238,
"s": 4180,
"text": "http://www.mywebapp.com/checkstatus.jsp?fwd=appadmin.jsp\n"
},
{
"code": null,
"e": 4290,
"s": 4238,
"text": "It is better to avoid using redirects and forwards."
},
{
"code": null,
"e": 4342,
"s": 4290,
"text": "It is better to avoid using redirects and forwards."
},
{
"code": null,
"e": 4453,
"s": 4342,
"text": "If it is unavoidable, then it should be done without involving user parameters in redirecting the destination."
},
{
"code": null,
"e": 4564,
"s": 4453,
"text": "If it is unavoidable, then it should be done without involving user parameters in redirecting the destination."
},
{
"code": null,
"e": 4597,
"s": 4564,
"text": "\n 36 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 4611,
"s": 4597,
"text": " Sharad Kumar"
},
{
"code": null,
"e": 4646,
"s": 4611,
"text": "\n 26 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 4666,
"s": 4646,
"text": " Harshit Srivastava"
},
{
"code": null,
"e": 4699,
"s": 4666,
"text": "\n 47 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 4717,
"s": 4699,
"text": " Dhabaleshwar Das"
},
{
"code": null,
"e": 4752,
"s": 4717,
"text": "\n 14 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 4772,
"s": 4752,
"text": " Harshit Srivastava"
},
{
"code": null,
"e": 4805,
"s": 4772,
"text": "\n 38 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 4825,
"s": 4805,
"text": " Harshit Srivastava"
},
{
"code": null,
"e": 4858,
"s": 4825,
"text": "\n 32 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 4878,
"s": 4858,
"text": " Harshit Srivastava"
},
{
"code": null,
"e": 4885,
"s": 4878,
"text": " Print"
},
{
"code": null,
"e": 4896,
"s": 4885,
"text": " Add Notes"
}
] |
What is difference between onCreate() and onStart() on Android? | This example demonstrates the difference between onCreate() and onStart() in Android.
Note −
onCreate() is called when the when the activity is first created.
onStart() is called when the activity is becoming visible to the user.
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"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Have a very nice day!"
android:textSize="35dp"
android:textStyle="bold"
android:textColor="@color/colorAccent"
android:layout_centerInParent="true"
android:padding="20sp"
android:layout_gravity="center_vertical" />
</LinearLayout>
Step 3 − Add the following code to src/MainActivity.java
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
public class MainActivity extends AppCompatActivity {
public static final String TAG = "Have a nice day!";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.i(TAG,"onCreate");
}
protected void onStart(){
super.onStart();
Log.i(TAG,"onStart");
}
}
Step 4 − Add the following code to androidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.sample">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −
Click here to download the project code. | [
{
"code": null,
"e": 1148,
"s": 1062,
"text": "This example demonstrates the difference between onCreate() and onStart() in Android."
},
{
"code": null,
"e": 1155,
"s": 1148,
"text": "Note −"
},
{
"code": null,
"e": 1221,
"s": 1155,
"text": "onCreate() is called when the when the activity is first created."
},
{
"code": null,
"e": 1292,
"s": 1221,
"text": "onStart() is called when the activity is becoming visible to the user."
},
{
"code": null,
"e": 1421,
"s": 1292,
"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": 1486,
"s": 1421,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 2146,
"s": 1486,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<LinearLayout 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:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n android:text=\"Have a very nice day!\"\n android:textSize=\"35dp\"\n android:textStyle=\"bold\"\n android:textColor=\"@color/colorAccent\"\n android:layout_centerInParent=\"true\"\n android:padding=\"20sp\"\n android:layout_gravity=\"center_vertical\" />\n</LinearLayout>"
},
{
"code": null,
"e": 2203,
"s": 2146,
"text": "Step 3 − Add the following code to src/MainActivity.java"
},
{
"code": null,
"e": 2691,
"s": 2203,
"text": "import android.support.v7.app.AppCompatActivity;\nimport android.os.Bundle;\nimport android.util.Log;\npublic class MainActivity extends AppCompatActivity {\n public static final String TAG = \"Have a nice day!\";\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n Log.i(TAG,\"onCreate\");\n }\n protected void onStart(){\n super.onStart();\n Log.i(TAG,\"onStart\");\n }\n}"
},
{
"code": null,
"e": 2746,
"s": 2691,
"text": "Step 4 − Add the following code to androidManifest.xml"
},
{
"code": null,
"e": 3416,
"s": 2746,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"app.com.sample\">\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": 3763,
"s": 3416,
"text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −"
},
{
"code": null,
"e": 3804,
"s": 3763,
"text": "Click here to download the project code."
}
] |
Hungarian Algorithm for Assignment Problem | Set 2 (Implementation) | 20 Jul, 2021
Given a 2D array, arr of size N*N where arr[i][j] denotes the cost to complete the jth job by the ith worker. Any worker can be assigned to perform any job. The task is to assign the jobs such that exactly one worker can perform exactly one job in such a way that the total cost of the assignment is minimized.
Example
Input: arr[][] = {{3, 5}, {10, 1}}Output: 4Explanation: The optimal assignment is to assign job 1 to the 1st worker, job 2 to the 2nd worker.Hence, the optimal cost is 3 + 1 = 4.
Input: arr[][] = {{2500, 4000, 3500}, {4000, 6000, 3500}, {2000, 4000, 2500}}Output: 4Explanation: The optimal assignment is to assign job 2 to the 1st worker, job 3 to the 2nd worker and job 1 to the 3rd worker.Hence, the optimal cost is 4000 + 3500 + 2000 = 9500.
Different approaches to solve this problem are discussed in this article.
Approach: The idea is to use the Hungarian Algorithm to solve this problem. The algorithm is as follows:
For each row of the matrix, find the smallest element and subtract it from every element in its row.Repeat the step 1 for all columns.Cover all zeros in the matrix using the minimum number of horizontal and vertical lines.Test for Optimality: If the minimum number of covering lines is N, an optimal assignment is possible. Else if lines are lesser than N, an optimal assignment is not found and must proceed to step 5.Determine the smallest entry not covered by any line. Subtract this entry from each uncovered row, and then add it to each covered column. Return to step 3.
For each row of the matrix, find the smallest element and subtract it from every element in its row.
Repeat the step 1 for all columns.
Cover all zeros in the matrix using the minimum number of horizontal and vertical lines.
Test for Optimality: If the minimum number of covering lines is N, an optimal assignment is possible. Else if lines are lesser than N, an optimal assignment is not found and must proceed to step 5.
Determine the smallest entry not covered by any line. Subtract this entry from each uncovered row, and then add it to each covered column. Return to step 3.
Consider an example to understand the approach:
Let the 2D array be:
2500 4000 35004000 6000 35002000 4000 2500
Step 1: Subtract minimum of every row. 2500, 3500 and 2000 are subtracted from rows 1, 2 and 3 respectively.
0 1500 1000500 2500 00 2000 500
Step 2: Subtract minimum of every column. 0, 1500 and 0 are subtracted from columns 1, 2 and 3 respectively.
0 0 1000500 1000 00 500 500
Step 3: Cover all zeroes with minimum number of horizontal and vertical lines.
Step 4: Since we need 3 lines to cover all zeroes, the optimal assignment is found.
2500 4000 3500 4000 6000 3500 2000 4000 2500
So the optimal cost is 4000 + 3500 + 2000 = 9500
For implementing the above algorithm, the idea is to use the max_cost_assignment() function defined in the dlib library. This function is an implementation of the Hungarian algorithm (also known as the Kuhn-Munkres algorithm) which runs in O(N3) time. It solves the optimal assignment problem.
Below is the implementation of the above approach:
Python
# Python program for the above approachimport dlib # Function to find out the best# assignment of people to jobs so that# total cost of the assignment is minimizeddef minCost(arr): # Call the max_cost_assignment() function # and store the assignment assignment = dlib.max_cost_assignment(arr) # Print the optimal cost print(dlib.assignment_cost(arr, assignment)) # Driver Code # Given 2D arrayarr = dlib.matrix([[3, 5], [10, 1]]) # Function CallminCost(arr)
4
Time Complexity: O(N3)Auxiliary Space: O(N2)
Google
Graph
Mathematical
Google
Mathematical
Graph
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Find if there is a path between two vertices in a directed graph
Introduction to Data Structures
What is Data Structure: Types, Classifications and Applications
Find if there is a path between two vertices in an undirected graph
Minimum steps to reach target by a Knight | Set 1
Program for Fibonacci numbers
Set in C++ Standard Template Library (STL)
Write a program to print all permutations of a given string
C++ Data Types
Merge two sorted arrays | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n20 Jul, 2021"
},
{
"code": null,
"e": 365,
"s": 54,
"text": "Given a 2D array, arr of size N*N where arr[i][j] denotes the cost to complete the jth job by the ith worker. Any worker can be assigned to perform any job. The task is to assign the jobs such that exactly one worker can perform exactly one job in such a way that the total cost of the assignment is minimized."
},
{
"code": null,
"e": 373,
"s": 365,
"text": "Example"
},
{
"code": null,
"e": 552,
"s": 373,
"text": "Input: arr[][] = {{3, 5}, {10, 1}}Output: 4Explanation: The optimal assignment is to assign job 1 to the 1st worker, job 2 to the 2nd worker.Hence, the optimal cost is 3 + 1 = 4."
},
{
"code": null,
"e": 818,
"s": 552,
"text": "Input: arr[][] = {{2500, 4000, 3500}, {4000, 6000, 3500}, {2000, 4000, 2500}}Output: 4Explanation: The optimal assignment is to assign job 2 to the 1st worker, job 3 to the 2nd worker and job 1 to the 3rd worker.Hence, the optimal cost is 4000 + 3500 + 2000 = 9500."
},
{
"code": null,
"e": 892,
"s": 818,
"text": "Different approaches to solve this problem are discussed in this article."
},
{
"code": null,
"e": 997,
"s": 892,
"text": "Approach: The idea is to use the Hungarian Algorithm to solve this problem. The algorithm is as follows:"
},
{
"code": null,
"e": 1573,
"s": 997,
"text": "For each row of the matrix, find the smallest element and subtract it from every element in its row.Repeat the step 1 for all columns.Cover all zeros in the matrix using the minimum number of horizontal and vertical lines.Test for Optimality: If the minimum number of covering lines is N, an optimal assignment is possible. Else if lines are lesser than N, an optimal assignment is not found and must proceed to step 5.Determine the smallest entry not covered by any line. Subtract this entry from each uncovered row, and then add it to each covered column. Return to step 3."
},
{
"code": null,
"e": 1674,
"s": 1573,
"text": "For each row of the matrix, find the smallest element and subtract it from every element in its row."
},
{
"code": null,
"e": 1709,
"s": 1674,
"text": "Repeat the step 1 for all columns."
},
{
"code": null,
"e": 1798,
"s": 1709,
"text": "Cover all zeros in the matrix using the minimum number of horizontal and vertical lines."
},
{
"code": null,
"e": 1996,
"s": 1798,
"text": "Test for Optimality: If the minimum number of covering lines is N, an optimal assignment is possible. Else if lines are lesser than N, an optimal assignment is not found and must proceed to step 5."
},
{
"code": null,
"e": 2153,
"s": 1996,
"text": "Determine the smallest entry not covered by any line. Subtract this entry from each uncovered row, and then add it to each covered column. Return to step 3."
},
{
"code": null,
"e": 2201,
"s": 2153,
"text": "Consider an example to understand the approach:"
},
{
"code": null,
"e": 2222,
"s": 2201,
"text": "Let the 2D array be:"
},
{
"code": null,
"e": 2265,
"s": 2222,
"text": "2500 4000 35004000 6000 35002000 4000 2500"
},
{
"code": null,
"e": 2374,
"s": 2265,
"text": "Step 1: Subtract minimum of every row. 2500, 3500 and 2000 are subtracted from rows 1, 2 and 3 respectively."
},
{
"code": null,
"e": 2415,
"s": 2374,
"text": "0 1500 1000500 2500 00 2000 500"
},
{
"code": null,
"e": 2524,
"s": 2415,
"text": "Step 2: Subtract minimum of every column. 0, 1500 and 0 are subtracted from columns 1, 2 and 3 respectively."
},
{
"code": null,
"e": 2563,
"s": 2524,
"text": "0 0 1000500 1000 00 500 500"
},
{
"code": null,
"e": 2642,
"s": 2563,
"text": "Step 3: Cover all zeroes with minimum number of horizontal and vertical lines."
},
{
"code": null,
"e": 2727,
"s": 2642,
"text": "Step 4: Since we need 3 lines to cover all zeroes, the optimal assignment is found. "
},
{
"code": null,
"e": 2779,
"s": 2727,
"text": " 2500 4000 3500 4000 6000 3500 2000 4000 2500"
},
{
"code": null,
"e": 2828,
"s": 2779,
"text": "So the optimal cost is 4000 + 3500 + 2000 = 9500"
},
{
"code": null,
"e": 3123,
"s": 2828,
"text": "For implementing the above algorithm, the idea is to use the max_cost_assignment() function defined in the dlib library. This function is an implementation of the Hungarian algorithm (also known as the Kuhn-Munkres algorithm) which runs in O(N3) time. It solves the optimal assignment problem. "
},
{
"code": null,
"e": 3174,
"s": 3123,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 3181,
"s": 3174,
"text": "Python"
},
{
"code": "# Python program for the above approachimport dlib # Function to find out the best# assignment of people to jobs so that# total cost of the assignment is minimizeddef minCost(arr): # Call the max_cost_assignment() function # and store the assignment assignment = dlib.max_cost_assignment(arr) # Print the optimal cost print(dlib.assignment_cost(arr, assignment)) # Driver Code # Given 2D arrayarr = dlib.matrix([[3, 5], [10, 1]]) # Function CallminCost(arr)",
"e": 3664,
"s": 3181,
"text": null
},
{
"code": null,
"e": 3666,
"s": 3664,
"text": "4"
},
{
"code": null,
"e": 3711,
"s": 3666,
"text": "Time Complexity: O(N3)Auxiliary Space: O(N2)"
},
{
"code": null,
"e": 3718,
"s": 3711,
"text": "Google"
},
{
"code": null,
"e": 3724,
"s": 3718,
"text": "Graph"
},
{
"code": null,
"e": 3737,
"s": 3724,
"text": "Mathematical"
},
{
"code": null,
"e": 3744,
"s": 3737,
"text": "Google"
},
{
"code": null,
"e": 3757,
"s": 3744,
"text": "Mathematical"
},
{
"code": null,
"e": 3763,
"s": 3757,
"text": "Graph"
},
{
"code": null,
"e": 3861,
"s": 3763,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3926,
"s": 3861,
"text": "Find if there is a path between two vertices in a directed graph"
},
{
"code": null,
"e": 3958,
"s": 3926,
"text": "Introduction to Data Structures"
},
{
"code": null,
"e": 4022,
"s": 3958,
"text": "What is Data Structure: Types, Classifications and Applications"
},
{
"code": null,
"e": 4090,
"s": 4022,
"text": "Find if there is a path between two vertices in an undirected graph"
},
{
"code": null,
"e": 4140,
"s": 4090,
"text": "Minimum steps to reach target by a Knight | Set 1"
},
{
"code": null,
"e": 4170,
"s": 4140,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 4213,
"s": 4170,
"text": "Set in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 4273,
"s": 4213,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 4288,
"s": 4273,
"text": "C++ Data Types"
}
] |
Linux | Uptime command with examples | 27 May, 2019
Uptime Command In Linux: It is used to find out how long the system is active (running). This command returns set of values that involve, the current time, and the amount of time system is in running state, number of users currently logged into, and the load time for the past 1, 5 and 15 minutes respectively.
Syntax:
uptime [-options]
Example:Input
[mistersubha@server-1 ~]$uptime
08:24:37 up 207 days, 11:10, 0 users, load average: 0.00, 0.03, 0.05
Output
From the above code, the output has got four parts: Current time, Uptime, Number of Users, and average load as mentioned earlier.
uptime has got few options to tailor outputs and to those who are unaware of the options of the newbies working with uptime can use the option “-h” (which means help). This will give the options available to the preceding command.
[mistersubha@server-1 ~]$uptime -h
Usage:
uptime [options]
Options:
-p, --pretty show uptime in pretty format
-h, --help display this help and exit
-s, --since system up since
-V, --version output version information and exit
For more details see uptime(1).
Just to make sure you get the uptime in human-readable format, you can use option “p”
[mistersubha@server-1 ~]$uptime -p
up 29 weeks, 4 days, 11 hours, 1 minute
Option “s” is used to get the starting time/specified time when the system started has been running.
[mistersubha@server-1 ~]$uptime -s
2017-11-10 20:14:15
Version information can be shown using option “V”.
[mistersubha@server-1 ~]$uptime -V
uptime from procps-ng 3.3.10
There are few other ways to find the uptime and output header of command “w” is similar to that of output of “uptime” command.
linux-command
Linux-system-commands
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
tar command in Linux with examples
'crontab' in Linux with Examples
Conditional Statements | Shell Script
Tail command in Linux with examples
UDP Server-Client implementation in C
Docker - COPY Instruction
scp command in Linux with Examples
diff command in Linux with examples
Cat command in Linux with examples
echo command in Linux with Examples | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n27 May, 2019"
},
{
"code": null,
"e": 339,
"s": 28,
"text": "Uptime Command In Linux: It is used to find out how long the system is active (running). This command returns set of values that involve, the current time, and the amount of time system is in running state, number of users currently logged into, and the load time for the past 1, 5 and 15 minutes respectively."
},
{
"code": null,
"e": 347,
"s": 339,
"text": "Syntax:"
},
{
"code": null,
"e": 365,
"s": 347,
"text": "uptime [-options]"
},
{
"code": null,
"e": 379,
"s": 365,
"text": "Example:Input"
},
{
"code": null,
"e": 513,
"s": 379,
"text": "[mistersubha@server-1 ~]$uptime \n 08:24:37 up 207 days, 11:10, 0 users, load average: 0.00, 0.03, 0.05 \n"
},
{
"code": null,
"e": 520,
"s": 513,
"text": "Output"
},
{
"code": null,
"e": 650,
"s": 520,
"text": "From the above code, the output has got four parts: Current time, Uptime, Number of Users, and average load as mentioned earlier."
},
{
"code": null,
"e": 881,
"s": 650,
"text": "uptime has got few options to tailor outputs and to those who are unaware of the options of the newbies working with uptime can use the option “-h” (which means help). This will give the options available to the preceding command."
},
{
"code": null,
"e": 1157,
"s": 881,
"text": "[mistersubha@server-1 ~]$uptime -h\n\nUsage:\nuptime [options]\n\nOptions:\n -p, --pretty show uptime in pretty format\n -h, --help display this help and exit\n -s, --since system up since\n -V, --version output version information and exit\n\nFor more details see uptime(1).\n"
},
{
"code": null,
"e": 1243,
"s": 1157,
"text": "Just to make sure you get the uptime in human-readable format, you can use option “p”"
},
{
"code": null,
"e": 1319,
"s": 1243,
"text": "[mistersubha@server-1 ~]$uptime -p\nup 29 weeks, 4 days, 11 hours, 1 minute\n"
},
{
"code": null,
"e": 1420,
"s": 1319,
"text": "Option “s” is used to get the starting time/specified time when the system started has been running."
},
{
"code": null,
"e": 1476,
"s": 1420,
"text": "[mistersubha@server-1 ~]$uptime -s\n2017-11-10 20:14:15\n"
},
{
"code": null,
"e": 1527,
"s": 1476,
"text": "Version information can be shown using option “V”."
},
{
"code": null,
"e": 1592,
"s": 1527,
"text": "[mistersubha@server-1 ~]$uptime -V\nuptime from procps-ng 3.3.10\n"
},
{
"code": null,
"e": 1719,
"s": 1592,
"text": "There are few other ways to find the uptime and output header of command “w” is similar to that of output of “uptime” command."
},
{
"code": null,
"e": 1733,
"s": 1719,
"text": "linux-command"
},
{
"code": null,
"e": 1755,
"s": 1733,
"text": "Linux-system-commands"
},
{
"code": null,
"e": 1766,
"s": 1755,
"text": "Linux-Unix"
},
{
"code": null,
"e": 1864,
"s": 1766,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1899,
"s": 1864,
"text": "tar command in Linux with examples"
},
{
"code": null,
"e": 1932,
"s": 1899,
"text": "'crontab' in Linux with Examples"
},
{
"code": null,
"e": 1970,
"s": 1932,
"text": "Conditional Statements | Shell Script"
},
{
"code": null,
"e": 2006,
"s": 1970,
"text": "Tail command in Linux with examples"
},
{
"code": null,
"e": 2044,
"s": 2006,
"text": "UDP Server-Client implementation in C"
},
{
"code": null,
"e": 2070,
"s": 2044,
"text": "Docker - COPY Instruction"
},
{
"code": null,
"e": 2105,
"s": 2070,
"text": "scp command in Linux with Examples"
},
{
"code": null,
"e": 2141,
"s": 2105,
"text": "diff command in Linux with examples"
},
{
"code": null,
"e": 2176,
"s": 2141,
"text": "Cat command in Linux with examples"
}
] |
Dplyr – Find Mean for multiple columns in R | 14 Sep, 2021
In this article, we will discuss how to calculate the mean for multiple columns using dplyr package of R programming language.
The mutate() method adds new variables and preserves existing ones. It is used to carry out addition of more variables. The original sequence of rows and columns remain unaltered during this method application.
Syntax: mutate(.data, name-value)
Parameter:
.data – The data frame or table to be appended
name-value – The new column name and a function to define values
The rowMeans() returns the mean value of each row in the data set. The function prototype is inclusive of optional parameters including the na.rm logical parameter which is an indicator of whether to omit N/A values.
Syntax:
rowMeans (data-set)
The dataset is produced by selecting a particular set of columns to produce mean from. The select() method is used for data frame filtering based on a set of conditions.
Syntax:
select (data-set, cols-to-select)
Thus in order to find the mean for multiple columns of a dataframe using R programming language first we need a dataframe. Then columns from this dataframe can be selected using select() method and the selected columns are passed to rowMeans() function for further processing. The results are added to the dataframe using a separate column using mutate() function.
There can be multiple ways of selecting columns
Example: Calculating mean of multiple columns by selecting columns via vector
R
library("dplyr") # creating a data framedata_frame <- data.frame(col1 = c(1,2,3,4), col2 = c(2.3,5.6,3.4,1.2), col3 = c(5,6,7,8)) print("Original DataFrame") print(data_frame) data_frame_mod <- mutate(data_frame, mean_col = rowMeans(select(data_frame, c(col2,col3)), na.rm = TRUE))print("Modified DataFrame")print(data_frame_mod)
Output:
[1] "Original DataFrame"
col1 col2 col3
1 1 2.3 5
2 2 5.6 6
3 3 3.4 7
4 4 1.2 8
[1] "Modified DataFrame"
col1 col2 col3 mean_col
1 1 2.3 5 3.65
2 2 5.6 6 5.80
3 3 3.4 7 5.20
4 4 1.2 8 4.60
The column means can be calculated for all the other columns using the : operator specified in the select() method.
Example: Finding mean for multiple columns by selecting columns via : operator
R
library("dplyr") # creating a data framedata_frame <- data.frame(col1 = c(1,2,3,4), col2 = c(2.3,5.6,3.4,1.2), col3 = c(5,6,7,8))print("Original DataFrame") print(data_frame) data_frame_mod <- mutate(data_frame, mean_col = rowMeans(select(data_frame, col1:col3), na.rm = TRUE)) print("Modified DataFrame")print(data_frame_mod)
Output
[1] "Original DataFrame"
col1 col2 col3
1 1 2.3 5
2 2 5.6 6
3 3 3.4 7
4 4 1.2 8
[1] "Modified DataFrame"
col1 col2 col3 mean_col
1 1 2.3 5 2.766667
2 2 5.6 6 4.533333
3 3 3.4 7 4.466667
4 4 1.2 8 4.400000
A specific set of columns can also be extracted from the data frame using methods starts_with() that contains a string. All the columns whose names match with the string are returned in the dataframe.
Example: Finding mean of multiple columns by selecting columns by starts_with()
R
library("dplyr") # creating a data framedata_frame <- data.frame(col1 = c(1,2,3,4), col2 = c(2.3,5.6,3.4,1.2), nextcol2 = c(1,2,3,0), col3 = c(5,6,7,8), nextcol = c(4,5,6,7) )print("Original DataFrame")print(data_frame) print("Modified DataFrame") data_frame %>% mutate(mean_col = rowMeans(select(data_frame, starts_with('next')), na.rm = TRUE))
Output
[1] "Original DataFrame"
col1 col2 nextcol2 col3 nextcol
1 1 2.3 1 5 4
2 2 5.6 2 6 5
3 3 3.4 3 7 6
4 4 1.2 0 8 7
[1] "Modified DataFrame"
col1 col2 nextcol2 col3 nextcol mean_col
1 1 2.3 1 5 4 2.5
2 2 5.6 2 6 5 3.5
3 3 3.4 3 7 6 4.5
4 4 1.2 0 8 7 3.5
Picked
R Dplyr
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Change Color of Bars in Barchart using ggplot2 in R
How to Split Column Into Multiple Columns in R DataFrame?
Group by function in R using Dplyr
How to Change Axis Scales in R Plots?
R - if statement
Logistic Regression in R Programming
How to filter R DataFrame by values in a column?
Replace Specific Characters in String in R
How to import an Excel File into R ?
Joining of Dataframes in R Programming | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n14 Sep, 2021"
},
{
"code": null,
"e": 155,
"s": 28,
"text": "In this article, we will discuss how to calculate the mean for multiple columns using dplyr package of R programming language."
},
{
"code": null,
"e": 366,
"s": 155,
"text": "The mutate() method adds new variables and preserves existing ones. It is used to carry out addition of more variables. The original sequence of rows and columns remain unaltered during this method application."
},
{
"code": null,
"e": 400,
"s": 366,
"text": "Syntax: mutate(.data, name-value)"
},
{
"code": null,
"e": 411,
"s": 400,
"text": "Parameter:"
},
{
"code": null,
"e": 458,
"s": 411,
"text": ".data – The data frame or table to be appended"
},
{
"code": null,
"e": 523,
"s": 458,
"text": "name-value – The new column name and a function to define values"
},
{
"code": null,
"e": 740,
"s": 523,
"text": "The rowMeans() returns the mean value of each row in the data set. The function prototype is inclusive of optional parameters including the na.rm logical parameter which is an indicator of whether to omit N/A values."
},
{
"code": null,
"e": 748,
"s": 740,
"text": "Syntax:"
},
{
"code": null,
"e": 768,
"s": 748,
"text": "rowMeans (data-set)"
},
{
"code": null,
"e": 938,
"s": 768,
"text": "The dataset is produced by selecting a particular set of columns to produce mean from. The select() method is used for data frame filtering based on a set of conditions."
},
{
"code": null,
"e": 946,
"s": 938,
"text": "Syntax:"
},
{
"code": null,
"e": 980,
"s": 946,
"text": "select (data-set, cols-to-select)"
},
{
"code": null,
"e": 1345,
"s": 980,
"text": "Thus in order to find the mean for multiple columns of a dataframe using R programming language first we need a dataframe. Then columns from this dataframe can be selected using select() method and the selected columns are passed to rowMeans() function for further processing. The results are added to the dataframe using a separate column using mutate() function."
},
{
"code": null,
"e": 1393,
"s": 1345,
"text": "There can be multiple ways of selecting columns"
},
{
"code": null,
"e": 1471,
"s": 1393,
"text": "Example: Calculating mean of multiple columns by selecting columns via vector"
},
{
"code": null,
"e": 1473,
"s": 1471,
"text": "R"
},
{
"code": "library(\"dplyr\") # creating a data framedata_frame <- data.frame(col1 = c(1,2,3,4), col2 = c(2.3,5.6,3.4,1.2), col3 = c(5,6,7,8)) print(\"Original DataFrame\") print(data_frame) data_frame_mod <- mutate(data_frame, mean_col = rowMeans(select(data_frame, c(col2,col3)), na.rm = TRUE))print(\"Modified DataFrame\")print(data_frame_mod)",
"e": 1900,
"s": 1473,
"text": null
},
{
"code": null,
"e": 1908,
"s": 1900,
"text": "Output:"
},
{
"code": null,
"e": 2180,
"s": 1908,
"text": "[1] \"Original DataFrame\" \ncol1 col2 col3 \n1 1 2.3 5 \n2 2 5.6 6 \n3 3 3.4 7 \n4 4 1.2 8 \n[1] \"Modified DataFrame\" \ncol1 col2 col3 mean_col \n1 1 2.3 5 3.65 \n2 2 5.6 6 5.80 \n3 3 3.4 7 5.20 \n4 4 1.2 8 4.60"
},
{
"code": null,
"e": 2296,
"s": 2180,
"text": "The column means can be calculated for all the other columns using the : operator specified in the select() method."
},
{
"code": null,
"e": 2376,
"s": 2296,
"text": "Example: Finding mean for multiple columns by selecting columns via : operator "
},
{
"code": null,
"e": 2378,
"s": 2376,
"text": "R"
},
{
"code": "library(\"dplyr\") # creating a data framedata_frame <- data.frame(col1 = c(1,2,3,4), col2 = c(2.3,5.6,3.4,1.2), col3 = c(5,6,7,8))print(\"Original DataFrame\") print(data_frame) data_frame_mod <- mutate(data_frame, mean_col = rowMeans(select(data_frame, col1:col3), na.rm = TRUE)) print(\"Modified DataFrame\")print(data_frame_mod)",
"e": 2802,
"s": 2378,
"text": null
},
{
"code": null,
"e": 2809,
"s": 2802,
"text": "Output"
},
{
"code": null,
"e": 3085,
"s": 2809,
"text": "[1] \"Original DataFrame\" \n col1 col2 col3 \n1 1 2.3 5 \n2 2 5.6 6 \n3 3 3.4 7 \n4 4 1.2 8 \n[1] \"Modified DataFrame\" \n col1 col2 col3 mean_col \n1 1 2.3 5 2.766667 \n2 2 5.6 6 4.533333 \n3 3 3.4 7 4.466667 \n4 4 1.2 8 4.400000"
},
{
"code": null,
"e": 3286,
"s": 3085,
"text": "A specific set of columns can also be extracted from the data frame using methods starts_with() that contains a string. All the columns whose names match with the string are returned in the dataframe."
},
{
"code": null,
"e": 3366,
"s": 3286,
"text": "Example: Finding mean of multiple columns by selecting columns by starts_with()"
},
{
"code": null,
"e": 3368,
"s": 3366,
"text": "R"
},
{
"code": "library(\"dplyr\") # creating a data framedata_frame <- data.frame(col1 = c(1,2,3,4), col2 = c(2.3,5.6,3.4,1.2), nextcol2 = c(1,2,3,0), col3 = c(5,6,7,8), nextcol = c(4,5,6,7) )print(\"Original DataFrame\")print(data_frame) print(\"Modified DataFrame\") data_frame %>% mutate(mean_col = rowMeans(select(data_frame, starts_with('next')), na.rm = TRUE))",
"e": 3873,
"s": 3368,
"text": null
},
{
"code": null,
"e": 3880,
"s": 3873,
"text": "Output"
},
{
"code": null,
"e": 4371,
"s": 3880,
"text": "[1] \"Original DataFrame\" \ncol1 col2 nextcol2 col3 nextcol \n1 1 2.3 1 5 4 \n2 2 5.6 2 6 5 \n3 3 3.4 3 7 6 \n4 4 1.2 0 8 7 \n[1] \"Modified DataFrame\"\n col1 col2 nextcol2 col3 nextcol mean_col \n1 1 2.3 1 5 4 2.5 \n2 2 5.6 2 6 5 3.5 \n3 3 3.4 3 7 6 4.5 \n4 4 1.2 0 8 7 3.5"
},
{
"code": null,
"e": 4378,
"s": 4371,
"text": "Picked"
},
{
"code": null,
"e": 4386,
"s": 4378,
"text": "R Dplyr"
},
{
"code": null,
"e": 4397,
"s": 4386,
"text": "R Language"
},
{
"code": null,
"e": 4495,
"s": 4397,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4547,
"s": 4495,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 4605,
"s": 4547,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 4640,
"s": 4605,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 4678,
"s": 4640,
"text": "How to Change Axis Scales in R Plots?"
},
{
"code": null,
"e": 4695,
"s": 4678,
"text": "R - if statement"
},
{
"code": null,
"e": 4732,
"s": 4695,
"text": "Logistic Regression in R Programming"
},
{
"code": null,
"e": 4781,
"s": 4732,
"text": "How to filter R DataFrame by values in a column?"
},
{
"code": null,
"e": 4824,
"s": 4781,
"text": "Replace Specific Characters in String in R"
},
{
"code": null,
"e": 4861,
"s": 4824,
"text": "How to import an Excel File into R ?"
}
] |
Java.util.LinkedList.offer(), offerFirst(), offerLast() in Java | 04 Oct, 2021
Linked list also has a function that does the work of flexible addition of elements and helps addition both at front and back of the list, these functions literally “offer” the facility and named offer(). Three types are available and are discussed in this very article below.
1. offer(E e) : This method adds the specified element as the tail (last element) of this list.
Declaration :
public boolean offer(E e)
Parameters :
e: the element to add
Return Value :
This method returns true
Java
// Java code to demonstrate the working// of offer(E e) in linked listimport java.util.*;public class LinkedListoffer1 { public static void main(String[] args) { // Declaring a LinkedList LinkedList list = new LinkedList(); // adding elements list.add("Geeks"); list.add(4); list.add("Geeks"); list.add(8); // printing the list System.out.println("The initial Linked list is : " + list); // offering a new element // adds element at tail. list.offer("Astha"); // printing the new list System.out.println("LinkedList after insertion using offer() : " + list); }}
Output :
The initial Linked list is : [Geeks, 4, Geeks, 8]
LinkedList after insertion using offer() : [Geeks, 4, Geeks, 8, Astha]
2. offerFirst(E e) : This method inserts the specified element at the front of this list.
Declaration :
public boolean offerFirst(E e)
Parameters :
e : the element to add
Return Value :
This method returns true
Java
// Java code to demonstrate the working// of offerFirst(E e) in linked listimport java.util.*;public class LinkedListOfferFirst { public static void main(String[] args) { // Declaring a LinkedList LinkedList list = new LinkedList(); // adding elements list.add("Geeks"); list.add(4); list.add("Geeks"); list.add(8); // printing the list System.out.println("The initial Linked list is : " + list); // offering a new element // adds element at head. list.offerFirst("Astha"); // printing the new list System.out.println("LinkedList after insertion using offerFirst() : " + list); }}
Output :
The initial Linked list is : [Geeks, 4, Geeks, 8]
LinkedList after insertion using offerFirst() : [Astha, Geeks, 4, Geeks, 8]
3. offerLast(E e) : This method inserts the specified element at the end of this list.
Declaration :
public boolean offerLast(E e)
Parameters :
e:the element to add
Return Value :
This method returns true
Java
// Java code to demonstrate the working// of offerLast(E e) in linked listimport java.util.*;public class LinkedListOfferLast { public static void main(String[] args) { // Declaring a LinkedList LinkedList list = new LinkedList(); // adding elements list.add("Geeks"); list.add(4); list.add("Geeks"); list.add(8); // printing the list System.out.println("The initial Linked list is : " + list); // offering a new element // adds element at end. list.offerLast("Astha"); // printing the new list System.out.println("LinkedList after insertion using offerLast() : " + list); }}
Output :
The initial Linked list is : [Geeks, 4, Geeks, 8]
LinkedList after insertion using offerLast() : [Geeks, 4, Geeks, 8, Astha]
Practical Application : This quality of “flexible addition” of these functions can be done in cases of priority addition in queues where elements having a greater no. than threshold have to be handled before the elements lesser than that. Small piece of code below discusses this.
Java
// Java code to demonstrate the application// of offer() in linked listimport java.util.*;public class LinkedListOfferLast { public static void main(String[] args) { // Declaring LinkedLists LinkedList<Integer> list = new LinkedList<Integer>(); LinkedList prioList = new LinkedList(); // adding elements list.add(12); list.add(4); list.add(8); list.add(10); list.add(3); list.add(15); // declaring threshold int thres = 10; // printing the list System.out.println("The initial Linked list is : " + list); while (!list.isEmpty()) { int t = list.poll(); // adding >=10 numbers at front rest at back if (t >= 10) prioList.offerFirst(t); else prioList.offerLast(t); } // The resultant list is System.out.println("The prioritized Linked list is : " + prioList); }}
Output :
The initial Linked list is : [12, 4, 8, 10, 3, 15]
The prioritized Linked list is : [15, 10, 12, 4, 8, 3]
This article is contributed by Astha Tyagi. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
khushboogoyal499
Java - util package
Java-Collections
Java-Functions
java-LinkedList
Linked Lists
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
How to iterate any Map in Java
Interfaces in Java
HashMap in Java with Examples
Collections in Java
Multidimensional Arrays in Java
Stream In Java
Singleton Class in Java
Set in Java
Stack Class in Java | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n04 Oct, 2021"
},
{
"code": null,
"e": 306,
"s": 28,
"text": "Linked list also has a function that does the work of flexible addition of elements and helps addition both at front and back of the list, these functions literally “offer” the facility and named offer(). Three types are available and are discussed in this very article below. "
},
{
"code": null,
"e": 403,
"s": 306,
"text": "1. offer(E e) : This method adds the specified element as the tail (last element) of this list. "
},
{
"code": null,
"e": 534,
"s": 403,
"text": "Declaration : \n public boolean offer(E e)\nParameters : \n e: the element to add\nReturn Value : \n This method returns true "
},
{
"code": null,
"e": 539,
"s": 534,
"text": "Java"
},
{
"code": "// Java code to demonstrate the working// of offer(E e) in linked listimport java.util.*;public class LinkedListoffer1 { public static void main(String[] args) { // Declaring a LinkedList LinkedList list = new LinkedList(); // adding elements list.add(\"Geeks\"); list.add(4); list.add(\"Geeks\"); list.add(8); // printing the list System.out.println(\"The initial Linked list is : \" + list); // offering a new element // adds element at tail. list.offer(\"Astha\"); // printing the new list System.out.println(\"LinkedList after insertion using offer() : \" + list); }}",
"e": 1210,
"s": 539,
"text": null
},
{
"code": null,
"e": 1220,
"s": 1210,
"text": "Output : "
},
{
"code": null,
"e": 1341,
"s": 1220,
"text": "The initial Linked list is : [Geeks, 4, Geeks, 8]\nLinkedList after insertion using offer() : [Geeks, 4, Geeks, 8, Astha]"
},
{
"code": null,
"e": 1433,
"s": 1341,
"text": "2. offerFirst(E e) : This method inserts the specified element at the front of this list. "
},
{
"code": null,
"e": 1569,
"s": 1433,
"text": "Declaration : \n public boolean offerFirst(E e)\nParameters : \n e : the element to add\nReturn Value : \n This method returns true"
},
{
"code": null,
"e": 1574,
"s": 1569,
"text": "Java"
},
{
"code": "// Java code to demonstrate the working// of offerFirst(E e) in linked listimport java.util.*;public class LinkedListOfferFirst { public static void main(String[] args) { // Declaring a LinkedList LinkedList list = new LinkedList(); // adding elements list.add(\"Geeks\"); list.add(4); list.add(\"Geeks\"); list.add(8); // printing the list System.out.println(\"The initial Linked list is : \" + list); // offering a new element // adds element at head. list.offerFirst(\"Astha\"); // printing the new list System.out.println(\"LinkedList after insertion using offerFirst() : \" + list); }}",
"e": 2264,
"s": 1574,
"text": null
},
{
"code": null,
"e": 2274,
"s": 2264,
"text": "Output : "
},
{
"code": null,
"e": 2400,
"s": 2274,
"text": "The initial Linked list is : [Geeks, 4, Geeks, 8]\nLinkedList after insertion using offerFirst() : [Astha, Geeks, 4, Geeks, 8]"
},
{
"code": null,
"e": 2488,
"s": 2400,
"text": "3. offerLast(E e) : This method inserts the specified element at the end of this list. "
},
{
"code": null,
"e": 2622,
"s": 2488,
"text": "Declaration : \n public boolean offerLast(E e)\nParameters : \n e:the element to add\nReturn Value : \n This method returns true"
},
{
"code": null,
"e": 2627,
"s": 2622,
"text": "Java"
},
{
"code": "// Java code to demonstrate the working// of offerLast(E e) in linked listimport java.util.*;public class LinkedListOfferLast { public static void main(String[] args) { // Declaring a LinkedList LinkedList list = new LinkedList(); // adding elements list.add(\"Geeks\"); list.add(4); list.add(\"Geeks\"); list.add(8); // printing the list System.out.println(\"The initial Linked list is : \" + list); // offering a new element // adds element at end. list.offerLast(\"Astha\"); // printing the new list System.out.println(\"LinkedList after insertion using offerLast() : \" + list); }}",
"e": 3312,
"s": 2627,
"text": null
},
{
"code": null,
"e": 3322,
"s": 3312,
"text": "Output : "
},
{
"code": null,
"e": 3447,
"s": 3322,
"text": "The initial Linked list is : [Geeks, 4, Geeks, 8]\nLinkedList after insertion using offerLast() : [Geeks, 4, Geeks, 8, Astha]"
},
{
"code": null,
"e": 3730,
"s": 3447,
"text": "Practical Application : This quality of “flexible addition” of these functions can be done in cases of priority addition in queues where elements having a greater no. than threshold have to be handled before the elements lesser than that. Small piece of code below discusses this. "
},
{
"code": null,
"e": 3735,
"s": 3730,
"text": "Java"
},
{
"code": "// Java code to demonstrate the application// of offer() in linked listimport java.util.*;public class LinkedListOfferLast { public static void main(String[] args) { // Declaring LinkedLists LinkedList<Integer> list = new LinkedList<Integer>(); LinkedList prioList = new LinkedList(); // adding elements list.add(12); list.add(4); list.add(8); list.add(10); list.add(3); list.add(15); // declaring threshold int thres = 10; // printing the list System.out.println(\"The initial Linked list is : \" + list); while (!list.isEmpty()) { int t = list.poll(); // adding >=10 numbers at front rest at back if (t >= 10) prioList.offerFirst(t); else prioList.offerLast(t); } // The resultant list is System.out.println(\"The prioritized Linked list is : \" + prioList); }}",
"e": 4709,
"s": 3735,
"text": null
},
{
"code": null,
"e": 4719,
"s": 4709,
"text": "Output : "
},
{
"code": null,
"e": 4825,
"s": 4719,
"text": "The initial Linked list is : [12, 4, 8, 10, 3, 15]\nThe prioritized Linked list is : [15, 10, 12, 4, 8, 3]"
},
{
"code": null,
"e": 5246,
"s": 4825,
"text": "This article is contributed by Astha Tyagi. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 5263,
"s": 5246,
"text": "khushboogoyal499"
},
{
"code": null,
"e": 5283,
"s": 5263,
"text": "Java - util package"
},
{
"code": null,
"e": 5300,
"s": 5283,
"text": "Java-Collections"
},
{
"code": null,
"e": 5315,
"s": 5300,
"text": "Java-Functions"
},
{
"code": null,
"e": 5331,
"s": 5315,
"text": "java-LinkedList"
},
{
"code": null,
"e": 5344,
"s": 5331,
"text": "Linked Lists"
},
{
"code": null,
"e": 5349,
"s": 5344,
"text": "Java"
},
{
"code": null,
"e": 5354,
"s": 5349,
"text": "Java"
},
{
"code": null,
"e": 5371,
"s": 5354,
"text": "Java-Collections"
},
{
"code": null,
"e": 5469,
"s": 5371,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5520,
"s": 5469,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 5551,
"s": 5520,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 5570,
"s": 5551,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 5600,
"s": 5570,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 5620,
"s": 5600,
"text": "Collections in Java"
},
{
"code": null,
"e": 5652,
"s": 5620,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 5667,
"s": 5652,
"text": "Stream In Java"
},
{
"code": null,
"e": 5691,
"s": 5667,
"text": "Singleton Class in Java"
},
{
"code": null,
"e": 5703,
"s": 5691,
"text": "Set in Java"
}
] |
Node.js Stream readable.read() Method | 12 Oct, 2021
The readable.read() method is an inbuilt application programming interface of Stream module which is used to read the data out of the internal buffer. It returns data as a buffer object if no encoding is being specified or if the stream is working in object mode.
Syntax:
readable.read( size )
Parameters: This method accepts single parameter size which specifies the number of bytes to be read from the internal buffer.
Return Value: If this method is used then the data read after this method is displayed in the output and if no data exist in the buffer then null is returned.
Below examples illustrate the use of readable.read() method in Node.js:
Example 1:
// Node.js program to demonstrate the // readable.read() method // Include fs moduleconst fs = require("fs"); // Constructing readable streamconst readable = fs.createReadStream("input.txt"); // Instructions for reading datareadable.on('readable', () => { let chunk; // Using while loop and calling // read method while (null !== (chunk = readable.read())) { // Displaying the chunk console.log(`read: ${chunk}`); }});console.log("done");
Output:
done
read: hello
Here, in the above example the data read from the buffer is ‘hello’ so it is returned.
Example 2:
// Node.js program to demonstrate the // readable.read() method // Include fs moduleconst fs = require("fs"); // Constructing readable streamconst readable = fs.createReadStream("input.txt"); // Instructions for reading datareadable.on('readable', () => { let chunk; // Using while loop and calling // read method with parameter while (null !== (chunk = readable.read(1))) { // Displaying the chunk console.log(`read: ${chunk}`); }});console.log("done");
Output:
done
read: h
read: e
read: l
read: l
read: o
In the above example the size of the data is stated so only one byte is read in each step from the file “input.txt” which contains data ‘hello’.
Reference: https://nodejs.org/api/stream.html#stream_readable_read_size
Node.js-Stream-module
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to install the previous version of node.js and npm ?
Difference between promise and async await in Node.js
Mongoose | findByIdAndUpdate() Function
JWT Authentication with Node.js
Node.js forEach() function
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
Differences between Functional Components and Class Components in React | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n12 Oct, 2021"
},
{
"code": null,
"e": 292,
"s": 28,
"text": "The readable.read() method is an inbuilt application programming interface of Stream module which is used to read the data out of the internal buffer. It returns data as a buffer object if no encoding is being specified or if the stream is working in object mode."
},
{
"code": null,
"e": 300,
"s": 292,
"text": "Syntax:"
},
{
"code": null,
"e": 322,
"s": 300,
"text": "readable.read( size )"
},
{
"code": null,
"e": 449,
"s": 322,
"text": "Parameters: This method accepts single parameter size which specifies the number of bytes to be read from the internal buffer."
},
{
"code": null,
"e": 608,
"s": 449,
"text": "Return Value: If this method is used then the data read after this method is displayed in the output and if no data exist in the buffer then null is returned."
},
{
"code": null,
"e": 680,
"s": 608,
"text": "Below examples illustrate the use of readable.read() method in Node.js:"
},
{
"code": null,
"e": 691,
"s": 680,
"text": "Example 1:"
},
{
"code": "// Node.js program to demonstrate the // readable.read() method // Include fs moduleconst fs = require(\"fs\"); // Constructing readable streamconst readable = fs.createReadStream(\"input.txt\"); // Instructions for reading datareadable.on('readable', () => { let chunk; // Using while loop and calling // read method while (null !== (chunk = readable.read())) { // Displaying the chunk console.log(`read: ${chunk}`); }});console.log(\"done\");",
"e": 1159,
"s": 691,
"text": null
},
{
"code": null,
"e": 1167,
"s": 1159,
"text": "Output:"
},
{
"code": null,
"e": 1184,
"s": 1167,
"text": "done\nread: hello"
},
{
"code": null,
"e": 1271,
"s": 1184,
"text": "Here, in the above example the data read from the buffer is ‘hello’ so it is returned."
},
{
"code": null,
"e": 1282,
"s": 1271,
"text": "Example 2:"
},
{
"code": "// Node.js program to demonstrate the // readable.read() method // Include fs moduleconst fs = require(\"fs\"); // Constructing readable streamconst readable = fs.createReadStream(\"input.txt\"); // Instructions for reading datareadable.on('readable', () => { let chunk; // Using while loop and calling // read method with parameter while (null !== (chunk = readable.read(1))) { // Displaying the chunk console.log(`read: ${chunk}`); }});console.log(\"done\");",
"e": 1761,
"s": 1282,
"text": null
},
{
"code": null,
"e": 1769,
"s": 1761,
"text": "Output:"
},
{
"code": null,
"e": 1815,
"s": 1769,
"text": "done\nread: h\nread: e\nread: l\nread: l\nread: o\n"
},
{
"code": null,
"e": 1960,
"s": 1815,
"text": "In the above example the size of the data is stated so only one byte is read in each step from the file “input.txt” which contains data ‘hello’."
},
{
"code": null,
"e": 2032,
"s": 1960,
"text": "Reference: https://nodejs.org/api/stream.html#stream_readable_read_size"
},
{
"code": null,
"e": 2054,
"s": 2032,
"text": "Node.js-Stream-module"
},
{
"code": null,
"e": 2062,
"s": 2054,
"text": "Node.js"
},
{
"code": null,
"e": 2079,
"s": 2062,
"text": "Web Technologies"
},
{
"code": null,
"e": 2177,
"s": 2079,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2234,
"s": 2177,
"text": "How to install the previous version of node.js and npm ?"
},
{
"code": null,
"e": 2288,
"s": 2234,
"text": "Difference between promise and async await in Node.js"
},
{
"code": null,
"e": 2328,
"s": 2288,
"text": "Mongoose | findByIdAndUpdate() Function"
},
{
"code": null,
"e": 2360,
"s": 2328,
"text": "JWT Authentication with Node.js"
},
{
"code": null,
"e": 2387,
"s": 2360,
"text": "Node.js forEach() function"
},
{
"code": null,
"e": 2449,
"s": 2387,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 2510,
"s": 2449,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 2560,
"s": 2510,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 2603,
"s": 2560,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
JoomScan Vulnerability Scanner Tool in Kali Linux | 27 Sep, 2021
JoomScan is a free and Open source tool available on GitHub. It’s a vulnerability scanner tool. This tool is written in perl programming language. When a website is being created developers knowingly or unknowingly do some mistakes in code. A hacker can take advantage of that vulnerability and can access the website data. Joomscan is a tool that can be used to find those vulnerabilities it is also called OWASP Joomla vulnerability scanner.
Joomla tool is used as a scanner.
Joomla tool is used to find a vulnerability.
Joomla tool is used to scan CMS.
Joomla, WordPress can be scanned by JoomlaScan.
OWASP JoomScan is included in Kali Linux distributions.
Step 1: Open you terminal of kali Linux and move to the desktop and Now create a new directory called joomla using the following command.
cd Desktop
mkdir joomla
cd joomla
Step 2: Now you are under joomla directory here you have to download and install joom tool from GitHub now go to GitHub and search for joom tool .or clone it using the following command.
git clone https://github.com/rezasp/joomscan.git
Step 3: The tool has been downloaded in the joom directory and moves the joomscan dir.
ls
cd joomscan
Step 4: Now you have to run the tool using the following command.
perl joomscan.pl
Usages:
perl joomscan.pl -u www.website.com
Enumerate installed components... :
perl joomscan.pl -u www.website.com --ec
Set cookie :
perl joomscan.pl --url www.website.com --cookie "test=demo;"
Set proxy :
perl joomscan.pl -u www.website.com --proxy https://127.0.0.1:443
Set user-agent :
perl joomscan.pl -u www.website.com -a "Googlebot/2.1 (+http://www.website.com/bot.html)"
Set random user-agent :
perl joomscan.pl --url www.website.com -r
Let’s scan google.com:
perl joomscan.pl -u www.google.com
as5853535
varshagumber28
Cyber-security
Kali-Linux
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ZIP command in Linux with examples
tar command in Linux with examples
curl command in Linux with Examples
SORT command in Linux/Unix with examples
'crontab' in Linux with Examples
Conditional Statements | Shell Script
TCP Server-Client implementation in C
Tail command in Linux with examples
Docker - COPY Instruction
scp command in Linux with Examples | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n27 Sep, 2021"
},
{
"code": null,
"e": 472,
"s": 28,
"text": "JoomScan is a free and Open source tool available on GitHub. It’s a vulnerability scanner tool. This tool is written in perl programming language. When a website is being created developers knowingly or unknowingly do some mistakes in code. A hacker can take advantage of that vulnerability and can access the website data. Joomscan is a tool that can be used to find those vulnerabilities it is also called OWASP Joomla vulnerability scanner."
},
{
"code": null,
"e": 506,
"s": 472,
"text": "Joomla tool is used as a scanner."
},
{
"code": null,
"e": 551,
"s": 506,
"text": "Joomla tool is used to find a vulnerability."
},
{
"code": null,
"e": 584,
"s": 551,
"text": "Joomla tool is used to scan CMS."
},
{
"code": null,
"e": 632,
"s": 584,
"text": "Joomla, WordPress can be scanned by JoomlaScan."
},
{
"code": null,
"e": 688,
"s": 632,
"text": "OWASP JoomScan is included in Kali Linux distributions."
},
{
"code": null,
"e": 826,
"s": 688,
"text": "Step 1: Open you terminal of kali Linux and move to the desktop and Now create a new directory called joomla using the following command."
},
{
"code": null,
"e": 861,
"s": 826,
"text": "cd Desktop\nmkdir joomla\ncd joomla "
},
{
"code": null,
"e": 1048,
"s": 861,
"text": "Step 2: Now you are under joomla directory here you have to download and install joom tool from GitHub now go to GitHub and search for joom tool .or clone it using the following command."
},
{
"code": null,
"e": 1097,
"s": 1048,
"text": "git clone https://github.com/rezasp/joomscan.git"
},
{
"code": null,
"e": 1184,
"s": 1097,
"text": "Step 3: The tool has been downloaded in the joom directory and moves the joomscan dir."
},
{
"code": null,
"e": 1199,
"s": 1184,
"text": "ls\ncd joomscan"
},
{
"code": null,
"e": 1265,
"s": 1199,
"text": "Step 4: Now you have to run the tool using the following command."
},
{
"code": null,
"e": 1282,
"s": 1265,
"text": "perl joomscan.pl"
},
{
"code": null,
"e": 1290,
"s": 1282,
"text": "Usages:"
},
{
"code": null,
"e": 1728,
"s": 1290,
"text": "perl joomscan.pl -u www.website.com\nEnumerate installed components... :\nperl joomscan.pl -u www.website.com --ec\nSet cookie :\nperl joomscan.pl --url www.website.com --cookie \"test=demo;\"\nSet proxy :\nperl joomscan.pl -u www.website.com --proxy https://127.0.0.1:443\nSet user-agent :\nperl joomscan.pl -u www.website.com -a \"Googlebot/2.1 (+http://www.website.com/bot.html)\"\nSet random user-agent :\nperl joomscan.pl --url www.website.com -r"
},
{
"code": null,
"e": 1751,
"s": 1728,
"text": "Let’s scan google.com:"
},
{
"code": null,
"e": 1787,
"s": 1751,
"text": "perl joomscan.pl -u www.google.com "
},
{
"code": null,
"e": 1797,
"s": 1787,
"text": "as5853535"
},
{
"code": null,
"e": 1812,
"s": 1797,
"text": "varshagumber28"
},
{
"code": null,
"e": 1827,
"s": 1812,
"text": "Cyber-security"
},
{
"code": null,
"e": 1838,
"s": 1827,
"text": "Kali-Linux"
},
{
"code": null,
"e": 1849,
"s": 1838,
"text": "Linux-Unix"
},
{
"code": null,
"e": 1947,
"s": 1849,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1982,
"s": 1947,
"text": "ZIP command in Linux with examples"
},
{
"code": null,
"e": 2017,
"s": 1982,
"text": "tar command in Linux with examples"
},
{
"code": null,
"e": 2053,
"s": 2017,
"text": "curl command in Linux with Examples"
},
{
"code": null,
"e": 2094,
"s": 2053,
"text": "SORT command in Linux/Unix with examples"
},
{
"code": null,
"e": 2127,
"s": 2094,
"text": "'crontab' in Linux with Examples"
},
{
"code": null,
"e": 2165,
"s": 2127,
"text": "Conditional Statements | Shell Script"
},
{
"code": null,
"e": 2203,
"s": 2165,
"text": "TCP Server-Client implementation in C"
},
{
"code": null,
"e": 2239,
"s": 2203,
"text": "Tail command in Linux with examples"
},
{
"code": null,
"e": 2265,
"s": 2239,
"text": "Docker - COPY Instruction"
}
] |
java.time.ZoneOffset Class in Java | 06 Sep, 2021
A time-zone offset is that the amount of your time that a time-zone differs from Greenwich/UTC. This is often usually a hard and fast number of hours and minutes. From the time package of java, ZoneOffset class is employed to represent the fixed zone offset from UTC zone and inherits the ZoneId class and implements the Comparable interface.
public final class ZoneOffset extends ZoneId
implements TemporalAccessor, TemporalAdjuster, Comparable<ZoneOffset>, Serializable
ZoneOffset class has three fields:
MAX: It is the maximum supported zone offsets.
MIN: It is the minimum supported zone offsets.
UTC: It is the time zone offset constant for UTC.
Method of ZoneOffset class
1. ofHoursMinutes() Method:
syntax:
public static ZoneOffset ofHoursMinutes(int Hours, int Minutes)
This method is used to obtain an instance of ZoneOffset using an offset in hours and minutes.
Java
// Example of ofHoursMinutes() Methodimport java.time.ZoneOffset; public class GFG { public static void main(String[] args) { ZoneOffset zone = ZoneOffset.ofHoursMinutes(7,15); System.out.println(zone); } }
+07:15
2. ofHours() Method
syntax:
public static ZoneOffset ofHours(int hours)
Obtains an instance of ZoneOffset using an offset in hours.
Java
//Example of ofHours() Methodimport java.time.*;import java.time.ZoneOffset; public class GFG { public static void main(String[] args) { ZoneOffset zone = ZoneOffset.ofHours(4); System.out.println(zone); } }
+04:00
adnanirshad158
Java-time package
Java-ZoneOffset
Picked
Technical Scripter 2020
Java
Technical Scripter
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
Strings in Java
Java Programming Examples
Abstraction in Java
HashSet in Java | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n06 Sep, 2021"
},
{
"code": null,
"e": 371,
"s": 28,
"text": "A time-zone offset is that the amount of your time that a time-zone differs from Greenwich/UTC. This is often usually a hard and fast number of hours and minutes. From the time package of java, ZoneOffset class is employed to represent the fixed zone offset from UTC zone and inherits the ZoneId class and implements the Comparable interface."
},
{
"code": null,
"e": 420,
"s": 371,
"text": "public final class ZoneOffset extends ZoneId "
},
{
"code": null,
"e": 506,
"s": 420,
"text": "implements TemporalAccessor, TemporalAdjuster, Comparable<ZoneOffset>, Serializable "
},
{
"code": null,
"e": 541,
"s": 506,
"text": "ZoneOffset class has three fields:"
},
{
"code": null,
"e": 588,
"s": 541,
"text": "MAX: It is the maximum supported zone offsets."
},
{
"code": null,
"e": 635,
"s": 588,
"text": "MIN: It is the minimum supported zone offsets."
},
{
"code": null,
"e": 685,
"s": 635,
"text": "UTC: It is the time zone offset constant for UTC."
},
{
"code": null,
"e": 712,
"s": 685,
"text": "Method of ZoneOffset class"
},
{
"code": null,
"e": 740,
"s": 712,
"text": "1. ofHoursMinutes() Method:"
},
{
"code": null,
"e": 748,
"s": 740,
"text": "syntax:"
},
{
"code": null,
"e": 812,
"s": 748,
"text": "public static ZoneOffset ofHoursMinutes(int Hours, int Minutes)"
},
{
"code": null,
"e": 906,
"s": 812,
"text": "This method is used to obtain an instance of ZoneOffset using an offset in hours and minutes."
},
{
"code": null,
"e": 911,
"s": 906,
"text": "Java"
},
{
"code": "// Example of ofHoursMinutes() Methodimport java.time.ZoneOffset; public class GFG { public static void main(String[] args) { ZoneOffset zone = ZoneOffset.ofHoursMinutes(7,15); System.out.println(zone); } }",
"e": 1130,
"s": 911,
"text": null
},
{
"code": null,
"e": 1137,
"s": 1130,
"text": "+07:15"
},
{
"code": null,
"e": 1157,
"s": 1137,
"text": "2. ofHours() Method"
},
{
"code": null,
"e": 1165,
"s": 1157,
"text": "syntax:"
},
{
"code": null,
"e": 1209,
"s": 1165,
"text": "public static ZoneOffset ofHours(int hours)"
},
{
"code": null,
"e": 1269,
"s": 1209,
"text": "Obtains an instance of ZoneOffset using an offset in hours."
},
{
"code": null,
"e": 1274,
"s": 1269,
"text": "Java"
},
{
"code": "//Example of ofHours() Methodimport java.time.*;import java.time.ZoneOffset; public class GFG { public static void main(String[] args) { ZoneOffset zone = ZoneOffset.ofHours(4); System.out.println(zone); } }",
"e": 1494,
"s": 1274,
"text": null
},
{
"code": null,
"e": 1501,
"s": 1494,
"text": "+04:00"
},
{
"code": null,
"e": 1516,
"s": 1501,
"text": "adnanirshad158"
},
{
"code": null,
"e": 1534,
"s": 1516,
"text": "Java-time package"
},
{
"code": null,
"e": 1550,
"s": 1534,
"text": "Java-ZoneOffset"
},
{
"code": null,
"e": 1557,
"s": 1550,
"text": "Picked"
},
{
"code": null,
"e": 1581,
"s": 1557,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 1586,
"s": 1581,
"text": "Java"
},
{
"code": null,
"e": 1605,
"s": 1586,
"text": "Technical Scripter"
},
{
"code": null,
"e": 1610,
"s": 1605,
"text": "Java"
},
{
"code": null,
"e": 1708,
"s": 1610,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1723,
"s": 1708,
"text": "Stream In Java"
},
{
"code": null,
"e": 1744,
"s": 1723,
"text": "Introduction to Java"
},
{
"code": null,
"e": 1765,
"s": 1744,
"text": "Constructors in Java"
},
{
"code": null,
"e": 1784,
"s": 1765,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 1801,
"s": 1784,
"text": "Generics in Java"
},
{
"code": null,
"e": 1831,
"s": 1801,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 1847,
"s": 1831,
"text": "Strings in Java"
},
{
"code": null,
"e": 1873,
"s": 1847,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 1893,
"s": 1873,
"text": "Abstraction in Java"
}
] |
Command line arguments example in C | 25 Apr, 2022
Prerequisite: Command_line_argument. The problem is to find the largest integer among the three using command line arguments. Notes:
Command-line arguments are given after the name of the program in the command-line shell of Operating Systems. To pass command line arguments, we typically define main() with two arguments: the first argument is the number of command-line arguments and the second is a list of command-line arguments.
int main(int argc, char *argv[]) { /* ... */ }
atoi – Used to convert string numbers to integers
Examples:
Input : filename 8 9 45
Output : 45 is largest
Input : filename 8 9 9
Output : Two equal number entered
Input : filename 8 -9 9
Output : negative number entered
When calling the program, we pass three integers along with its filename, and then the program prints out the largest of the three numbers. Approach:
The program “return 1” if one of the two following conditions is satisfied:If any two numbers are the same, print the statement “two equal numbers entered”.If any of the numbers is negative, print “negative number entered”.Else “return 0” if three different integers are entered.
The program “return 1” if one of the two following conditions is satisfied:If any two numbers are the same, print the statement “two equal numbers entered”.If any of the numbers is negative, print “negative number entered”.
If any two numbers are the same, print the statement “two equal numbers entered”.
If any of the numbers is negative, print “negative number entered”.
Else “return 0” if three different integers are entered.
For better understanding, run this code for yourself.
C
// C program for finding the largest integer// among three numbers using command line arguments#include <stdio.h>#include <stdlib.h> // Taking argument as command lineint main(int argc, char *argv[]){ int a, b, c; // Checking if number of argument is // equal to 4 or not. if (argc < 4 || argc > 5) { printf("enter 4 arguments only eg.\"filename arg1 arg2 arg3!!\""); return 0; } // Converting string type to integer type // using function "atoi( argument)" a = atoi(argv[1]); b = atoi(argv[2]); c = atoi(argv[3]); // Checking if all the numbers are positive of not if (a < 0 || b < 0 || c < 0) { printf("enter only positive values in arguments !!"); return 1; } // Checking if all the numbers are different or not if (!(a != b && b != c && a != c)) { printf("please enter three different value "); return 1; } else { // Checking condition for "a" to be largest if (a > b && a > c) printf("%d is largest", a); // Checking condition for "b" to be largest else if (b > c && b > a) printf ("%d is largest", b); // Checking condition for "c" to be largest.. else if (c > a && c > b) printf("%d is largest ",c); } return 0;}
Output :
vbsesa7h62yn5zrw0sff53coo6p9d08z1cxjkhky
C Language
C Programs
C++ Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Substring in C++
Function Pointer in C
Left Shift and Right Shift Operators in C/C++
Different Methods to Reverse a String in C++
std::string class in C++
Strings in C
Arrow operator -> in C/C++ with Examples
Basics of File Handling in C
UDP Server-Client implementation in C
Header files in C/C++ and its uses | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n25 Apr, 2022"
},
{
"code": null,
"e": 185,
"s": 52,
"text": "Prerequisite: Command_line_argument. The problem is to find the largest integer among the three using command line arguments. Notes:"
},
{
"code": null,
"e": 486,
"s": 185,
"text": "Command-line arguments are given after the name of the program in the command-line shell of Operating Systems. To pass command line arguments, we typically define main() with two arguments: the first argument is the number of command-line arguments and the second is a list of command-line arguments."
},
{
"code": null,
"e": 533,
"s": 486,
"text": "int main(int argc, char *argv[]) { /* ... */ }"
},
{
"code": null,
"e": 583,
"s": 533,
"text": "atoi – Used to convert string numbers to integers"
},
{
"code": null,
"e": 593,
"s": 583,
"text": "Examples:"
},
{
"code": null,
"e": 759,
"s": 593,
"text": "Input : filename 8 9 45\nOutput : 45 is largest\n\nInput : filename 8 9 9\nOutput : Two equal number entered\n\nInput : filename 8 -9 9\nOutput : negative number entered"
},
{
"code": null,
"e": 909,
"s": 759,
"text": "When calling the program, we pass three integers along with its filename, and then the program prints out the largest of the three numbers. Approach:"
},
{
"code": null,
"e": 1189,
"s": 909,
"text": "The program “return 1” if one of the two following conditions is satisfied:If any two numbers are the same, print the statement “two equal numbers entered”.If any of the numbers is negative, print “negative number entered”.Else “return 0” if three different integers are entered."
},
{
"code": null,
"e": 1413,
"s": 1189,
"text": "The program “return 1” if one of the two following conditions is satisfied:If any two numbers are the same, print the statement “two equal numbers entered”.If any of the numbers is negative, print “negative number entered”."
},
{
"code": null,
"e": 1495,
"s": 1413,
"text": "If any two numbers are the same, print the statement “two equal numbers entered”."
},
{
"code": null,
"e": 1563,
"s": 1495,
"text": "If any of the numbers is negative, print “negative number entered”."
},
{
"code": null,
"e": 1620,
"s": 1563,
"text": "Else “return 0” if three different integers are entered."
},
{
"code": null,
"e": 1674,
"s": 1620,
"text": "For better understanding, run this code for yourself."
},
{
"code": null,
"e": 1676,
"s": 1674,
"text": "C"
},
{
"code": "// C program for finding the largest integer// among three numbers using command line arguments#include <stdio.h>#include <stdlib.h> // Taking argument as command lineint main(int argc, char *argv[]){ int a, b, c; // Checking if number of argument is // equal to 4 or not. if (argc < 4 || argc > 5) { printf(\"enter 4 arguments only eg.\\\"filename arg1 arg2 arg3!!\\\"\"); return 0; } // Converting string type to integer type // using function \"atoi( argument)\" a = atoi(argv[1]); b = atoi(argv[2]); c = atoi(argv[3]); // Checking if all the numbers are positive of not if (a < 0 || b < 0 || c < 0) { printf(\"enter only positive values in arguments !!\"); return 1; } // Checking if all the numbers are different or not if (!(a != b && b != c && a != c)) { printf(\"please enter three different value \"); return 1; } else { // Checking condition for \"a\" to be largest if (a > b && a > c) printf(\"%d is largest\", a); // Checking condition for \"b\" to be largest else if (b > c && b > a) printf (\"%d is largest\", b); // Checking condition for \"c\" to be largest.. else if (c > a && c > b) printf(\"%d is largest \",c); } return 0;}",
"e": 3003,
"s": 1676,
"text": null
},
{
"code": null,
"e": 3012,
"s": 3003,
"text": "Output :"
},
{
"code": null,
"e": 3057,
"s": 3016,
"text": "vbsesa7h62yn5zrw0sff53coo6p9d08z1cxjkhky"
},
{
"code": null,
"e": 3068,
"s": 3057,
"text": "C Language"
},
{
"code": null,
"e": 3079,
"s": 3068,
"text": "C Programs"
},
{
"code": null,
"e": 3092,
"s": 3079,
"text": "C++ Programs"
},
{
"code": null,
"e": 3190,
"s": 3092,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3207,
"s": 3190,
"text": "Substring in C++"
},
{
"code": null,
"e": 3229,
"s": 3207,
"text": "Function Pointer in C"
},
{
"code": null,
"e": 3275,
"s": 3229,
"text": "Left Shift and Right Shift Operators in C/C++"
},
{
"code": null,
"e": 3320,
"s": 3275,
"text": "Different Methods to Reverse a String in C++"
},
{
"code": null,
"e": 3345,
"s": 3320,
"text": "std::string class in C++"
},
{
"code": null,
"e": 3358,
"s": 3345,
"text": "Strings in C"
},
{
"code": null,
"e": 3399,
"s": 3358,
"text": "Arrow operator -> in C/C++ with Examples"
},
{
"code": null,
"e": 3428,
"s": 3399,
"text": "Basics of File Handling in C"
},
{
"code": null,
"e": 3466,
"s": 3428,
"text": "UDP Server-Client implementation in C"
}
] |
What is the role of $routeProvider in AngularJS? | 23 May, 2022
Routing is allows us create Single Page Applications.To do this, we use ng-view and ng-template directives, and $routeProvider services.
We use $routeProvider to configure the routes.
The config() takes a function which takes the $routeProvider as parameter and the routing configuration goes inside the function.
$routeProvider is a simple API which accepts either when() or otherwise() method.
We need to install the ngRoute module.
html
<html> <head> <title>GFG</title> <script src ="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"> </script> <script src ="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular-route.min.js"> </script> </head> <body> <div ng-app = "mainApp"> <p><a href = "#addStudent"> Add Student</a></p> <p><a href = "#viewStudents"> Display Student</a></p> <div ng-view></div> <script type = "text/ng-template" id = "addStudent.htm"> <h2> Add Student </h2> {{message}} </script> <script type = "text/ng-template" id = "viewStudents.htm"> <h2> Display Student </h2> {{message}} </script> </div> <script> var mainApp =angular.module("mainApp", ['ngRoute']); mainApp.config(['$routeProvider', function($routeProvider) { $routeProvider .when('/addStudent', { templateUrl: 'addStudent.htm', controller: 'AddStudentController' }) .when('/viewStudents', { templateUrl: 'viewStudents.htm', controller: 'ViewStudentsController' }) .otherwise({ redirectTo: '/addStudent' }); }]); mainApp.controller('AddStudentController', function($scope) { $scope.message = "Add The Students"; }); mainApp.controller('ViewStudentsController', function($scope) { $scope.message = "Display all the students"; }); </script> </body></html>
output
Explanation:
$routeProvider is a function under config (mainApp module) using the key as ‘$routeProvider’.
$routeProvider.when defines the URL “/addStudent”.
The default view is set by “otherwise”.
“controller” is used for the view.
How To Configure The $routeprovider?
The $routeProvider is creates the $route service.
By configuring the $routeProvider before the $route service we can set routes in HTML templates which will be displayed.
The $routeProvider is configured with the help of calls to the when() and otherwise() functions.
when() function takes route path and a JavaScript object as parameters.
otherwise() takes a JavaScript object as parameters.
Syntax to configure the routes in AngularJS:
var app = angular.module("appName", ['ngRoute']);
app.config(function($routeProvider) {
$routeProvider
.when('/1stview', {
templateUrl: '1stview.html',
controller: 'Controller1'
})
.when('/view2', {
templateUrl: '2ndview.html',
controller: 'Controller2'
})
.otherwise({
redirectTo: '/1stview'
});
});
Path is the URL after the hash(#) symbol.
Route contains two properties:
templateUrlcontroller
templateUrl
controller
The $routeProvider can be used to define the page when the user clicks the link.
html
<!DOCTYPE html><html> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"> </script> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular-route.js"> </script> <body ng-app="myApp"> <p><a href="#/!"> GFG</a></p> <p>Click on the links below.</p> <a href="#!C">Code 1</a> <a href="#!C++">Code 2</a> <div ng-view></div> <script> var app = angular.module("myApp", ["ngRoute"]); app.config(function ($routeProvider) { $routeProvider .when("/", { templateUrl: "main.htm", }) .when("/C", { templateUrl: "C.htm", }) .when("/C++", { templateUrl: "C++.htm", }); }); </script> </body></html>
sweetyty
AngularJS-Misc
AngularJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Routing in Angular 9/10
Angular PrimeNG Dropdown Component
Angular 10 (blur) Event
How to make a Bootstrap Modal Popup in Angular 9/8 ?
How to create module with Routing in Angular 9 ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ? | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n23 May, 2022"
},
{
"code": null,
"e": 165,
"s": 28,
"text": "Routing is allows us create Single Page Applications.To do this, we use ng-view and ng-template directives, and $routeProvider services."
},
{
"code": null,
"e": 212,
"s": 165,
"text": "We use $routeProvider to configure the routes."
},
{
"code": null,
"e": 342,
"s": 212,
"text": "The config() takes a function which takes the $routeProvider as parameter and the routing configuration goes inside the function."
},
{
"code": null,
"e": 425,
"s": 342,
"text": "$routeProvider is a simple API which accepts either when() or otherwise() method."
},
{
"code": null,
"e": 464,
"s": 425,
"text": "We need to install the ngRoute module."
},
{
"code": null,
"e": 469,
"s": 464,
"text": "html"
},
{
"code": "<html> <head> <title>GFG</title> <script src =\"https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js\"> </script> <script src =\"https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular-route.min.js\"> </script> </head> <body> <div ng-app = \"mainApp\"> <p><a href = \"#addStudent\"> Add Student</a></p> <p><a href = \"#viewStudents\"> Display Student</a></p> <div ng-view></div> <script type = \"text/ng-template\" id = \"addStudent.htm\"> <h2> Add Student </h2> {{message}} </script> <script type = \"text/ng-template\" id = \"viewStudents.htm\"> <h2> Display Student </h2> {{message}} </script> </div> <script> var mainApp =angular.module(\"mainApp\", ['ngRoute']); mainApp.config(['$routeProvider', function($routeProvider) { $routeProvider .when('/addStudent', { templateUrl: 'addStudent.htm', controller: 'AddStudentController' }) .when('/viewStudents', { templateUrl: 'viewStudents.htm', controller: 'ViewStudentsController' }) .otherwise({ redirectTo: '/addStudent' }); }]); mainApp.controller('AddStudentController', function($scope) { $scope.message = \"Add The Students\"; }); mainApp.controller('ViewStudentsController', function($scope) { $scope.message = \"Display all the students\"; }); </script> </body></html>",
"e": 2237,
"s": 469,
"text": null
},
{
"code": null,
"e": 2244,
"s": 2237,
"text": "output"
},
{
"code": null,
"e": 2257,
"s": 2244,
"text": "Explanation:"
},
{
"code": null,
"e": 2351,
"s": 2257,
"text": "$routeProvider is a function under config (mainApp module) using the key as ‘$routeProvider’."
},
{
"code": null,
"e": 2402,
"s": 2351,
"text": "$routeProvider.when defines the URL “/addStudent”."
},
{
"code": null,
"e": 2443,
"s": 2402,
"text": " The default view is set by “otherwise”."
},
{
"code": null,
"e": 2478,
"s": 2443,
"text": "“controller” is used for the view."
},
{
"code": null,
"e": 2515,
"s": 2478,
"text": "How To Configure The $routeprovider?"
},
{
"code": null,
"e": 2565,
"s": 2515,
"text": "The $routeProvider is creates the $route service."
},
{
"code": null,
"e": 2686,
"s": 2565,
"text": "By configuring the $routeProvider before the $route service we can set routes in HTML templates which will be displayed."
},
{
"code": null,
"e": 2783,
"s": 2686,
"text": "The $routeProvider is configured with the help of calls to the when() and otherwise() functions."
},
{
"code": null,
"e": 2855,
"s": 2783,
"text": "when() function takes route path and a JavaScript object as parameters."
},
{
"code": null,
"e": 2908,
"s": 2855,
"text": "otherwise() takes a JavaScript object as parameters."
},
{
"code": null,
"e": 2953,
"s": 2908,
"text": "Syntax to configure the routes in AngularJS:"
},
{
"code": null,
"e": 3301,
"s": 2953,
"text": "var app = angular.module(\"appName\", ['ngRoute']); \n \napp.config(function($routeProvider) { \n$routeProvider \n .when('/1stview', { \n templateUrl: '1stview.html', \n controller: 'Controller1' \n }) \n .when('/view2', { \n templateUrl: '2ndview.html', \n controller: 'Controller2' \n }) \n .otherwise({ \n redirectTo: '/1stview' \n }); \n}); "
},
{
"code": null,
"e": 3343,
"s": 3301,
"text": "Path is the URL after the hash(#) symbol."
},
{
"code": null,
"e": 3374,
"s": 3343,
"text": "Route contains two properties:"
},
{
"code": null,
"e": 3396,
"s": 3374,
"text": "templateUrlcontroller"
},
{
"code": null,
"e": 3408,
"s": 3396,
"text": "templateUrl"
},
{
"code": null,
"e": 3419,
"s": 3408,
"text": "controller"
},
{
"code": null,
"e": 3500,
"s": 3419,
"text": "The $routeProvider can be used to define the page when the user clicks the link."
},
{
"code": null,
"e": 3505,
"s": 3500,
"text": "html"
},
{
"code": "<!DOCTYPE html><html> <script src=\"https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js\"> </script> <script src=\"https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular-route.js\"> </script> <body ng-app=\"myApp\"> <p><a href=\"#/!\"> GFG</a></p> <p>Click on the links below.</p> <a href=\"#!C\">Code 1</a> <a href=\"#!C++\">Code 2</a> <div ng-view></div> <script> var app = angular.module(\"myApp\", [\"ngRoute\"]); app.config(function ($routeProvider) { $routeProvider .when(\"/\", { templateUrl: \"main.htm\", }) .when(\"/C\", { templateUrl: \"C.htm\", }) .when(\"/C++\", { templateUrl: \"C++.htm\", }); }); </script> </body></html>",
"e": 4437,
"s": 3505,
"text": null
},
{
"code": null,
"e": 4446,
"s": 4437,
"text": "sweetyty"
},
{
"code": null,
"e": 4461,
"s": 4446,
"text": "AngularJS-Misc"
},
{
"code": null,
"e": 4471,
"s": 4461,
"text": "AngularJS"
},
{
"code": null,
"e": 4488,
"s": 4471,
"text": "Web Technologies"
},
{
"code": null,
"e": 4586,
"s": 4488,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4610,
"s": 4586,
"text": "Routing in Angular 9/10"
},
{
"code": null,
"e": 4645,
"s": 4610,
"text": "Angular PrimeNG Dropdown Component"
},
{
"code": null,
"e": 4669,
"s": 4645,
"text": "Angular 10 (blur) Event"
},
{
"code": null,
"e": 4722,
"s": 4669,
"text": "How to make a Bootstrap Modal Popup in Angular 9/8 ?"
},
{
"code": null,
"e": 4771,
"s": 4722,
"text": "How to create module with Routing in Angular 9 ?"
},
{
"code": null,
"e": 4833,
"s": 4771,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 4866,
"s": 4833,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 4927,
"s": 4866,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 4977,
"s": 4927,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
GATE | GATE CS 1999 | Question 18 | 24 Oct, 2018
Consider the join of a relation R with a relation S. If K has m tuples and S has n tuples, then the maximum and minimum sizes of the join respectively are:(A) m+n and 0(B) mn and 0(C) m+n and m-n(D) mn and m+nAnswer: (B)Explanation: When there is no foreign key constraint between two tables then the max and min number of tuples in their join is mn and 0 respectively.Quiz of this Question
GATE CS 1999
GATE-GATE CS 1999
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n24 Oct, 2018"
},
{
"code": null,
"e": 444,
"s": 53,
"text": "Consider the join of a relation R with a relation S. If K has m tuples and S has n tuples, then the maximum and minimum sizes of the join respectively are:(A) m+n and 0(B) mn and 0(C) m+n and m-n(D) mn and m+nAnswer: (B)Explanation: When there is no foreign key constraint between two tables then the max and min number of tuples in their join is mn and 0 respectively.Quiz of this Question"
},
{
"code": null,
"e": 457,
"s": 444,
"text": "GATE CS 1999"
},
{
"code": null,
"e": 475,
"s": 457,
"text": "GATE-GATE CS 1999"
},
{
"code": null,
"e": 480,
"s": 475,
"text": "GATE"
}
] |
get_screenshot_as_png driver method – Selenium Python | 15 May, 2020
Selenium’s Python Module is built to perform automated testing with Python. Selenium Python bindings provides a simple API to write functional/acceptance tests using Selenium WebDriver. To open a webpage using Selenium Python, checkout – Navigating links using get method – Selenium Python. Just being able to go to places isn’t terribly useful. What we’d really like to do is to interact with the pages, or, more specifically, the HTML elements within a page. There are multiple strategies to find an element using Selenium, checkout – Locating Strategies. Selenium WebDriver offers various useful methods to control the session, or in other words, browser. For example, adding a cookie, pressing back button, navigating among tabs, etc.
This article revolves around get_screenshot_as_png driver method in Selenium. get_screenshot_as_png method saves a screenshot of the current window as binary data.
Syntax –
driver.get_screenshot_as_png()
Example –Now one can use get_screenshot_as_png method as a driver method as below –
diver.get("https://www.geeksforgeeks.org/")
driver.get_screenshot_as_png()
To demonstrate, get_screenshot_as_png method of WebDriver in Selenium Python. Let’ s visit https://www.geeksforgeeks.org/ and operate on driver object. Let’s get screenshot,
Program –
# import webdriverfrom selenium import webdriver # create webdriver objectdriver = webdriver.Firefox() # get geeksforgeeks.orgdriver.get("https://www.geeksforgeeks.org/") # get Screenshotprint(driver.get_screenshot_as_png())
Output –Screenshot added –
Python-selenium
selenium
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n15 May, 2020"
},
{
"code": null,
"e": 767,
"s": 28,
"text": "Selenium’s Python Module is built to perform automated testing with Python. Selenium Python bindings provides a simple API to write functional/acceptance tests using Selenium WebDriver. To open a webpage using Selenium Python, checkout – Navigating links using get method – Selenium Python. Just being able to go to places isn’t terribly useful. What we’d really like to do is to interact with the pages, or, more specifically, the HTML elements within a page. There are multiple strategies to find an element using Selenium, checkout – Locating Strategies. Selenium WebDriver offers various useful methods to control the session, or in other words, browser. For example, adding a cookie, pressing back button, navigating among tabs, etc."
},
{
"code": null,
"e": 931,
"s": 767,
"text": "This article revolves around get_screenshot_as_png driver method in Selenium. get_screenshot_as_png method saves a screenshot of the current window as binary data."
},
{
"code": null,
"e": 940,
"s": 931,
"text": "Syntax –"
},
{
"code": null,
"e": 971,
"s": 940,
"text": "driver.get_screenshot_as_png()"
},
{
"code": null,
"e": 1055,
"s": 971,
"text": "Example –Now one can use get_screenshot_as_png method as a driver method as below –"
},
{
"code": null,
"e": 1131,
"s": 1055,
"text": "diver.get(\"https://www.geeksforgeeks.org/\")\ndriver.get_screenshot_as_png()\n"
},
{
"code": null,
"e": 1305,
"s": 1131,
"text": "To demonstrate, get_screenshot_as_png method of WebDriver in Selenium Python. Let’ s visit https://www.geeksforgeeks.org/ and operate on driver object. Let’s get screenshot,"
},
{
"code": null,
"e": 1315,
"s": 1305,
"text": "Program –"
},
{
"code": "# import webdriverfrom selenium import webdriver # create webdriver objectdriver = webdriver.Firefox() # get geeksforgeeks.orgdriver.get(\"https://www.geeksforgeeks.org/\") # get Screenshotprint(driver.get_screenshot_as_png())",
"e": 1545,
"s": 1315,
"text": null
},
{
"code": null,
"e": 1572,
"s": 1545,
"text": "Output –Screenshot added –"
},
{
"code": null,
"e": 1588,
"s": 1572,
"text": "Python-selenium"
},
{
"code": null,
"e": 1597,
"s": 1588,
"text": "selenium"
},
{
"code": null,
"e": 1604,
"s": 1597,
"text": "Python"
}
] |
Maximum sum in circular array such that no two elements are adjacent | 16 Jun, 2022
Given a circular array containing of positive integers value. The task is to find the maximum sum of a subsequence with the constraint that no 2 numbers in the sequence should be adjacent in the array.Examples:
Input: circular arr = {1, 2, 3, 1}
Output : 4
subsequence will be(1, 3), hence 1 + 3 = 4
Input: circular arr = {1, 2, 3, 4, 5, 1}
Output: 9
subsequence will be(1, 3, 5), hence 1 + 3 + 5 = 9
Naive Approach: This problem is extension to the problem https://www.geeksforgeeks.org/find-maximum-possible-stolen-value-houses/ .In this problem the arr elements are arranged in circular fashion so the 1st and the last element are also adjacent. So we can not take first and last element together so we can take either of the element1 or last element. So first we can take element 1 and exclude last element and calculate the maximum sum subsequence where no two selected elements are adjacent and then also we can calculate another answer by excluding 1st element and including last element. And we will take maximum of two.
Implementation of recursion approach:
C++
// CPP program to find maximum sum in a circular array// such that no elements are adjacent in the sum.#include<iostream>using namespace std; // calculate the maximum stolen valueint helper(int* arr, int n){ // base case if (n < 0) { return 0; } if (n == 0) { return arr[0]; } // if current element is pick then previous cannot be // picked int pick = arr[n] + helper(arr, n - 2); // if current element is not picked then previous // element is picked int notPick = helper(arr, n - 1); // return max of picked and not picked return max(pick, notPick);} int maxLoot(int* arr, int n){ // case 1: Last elenent is exluded we have to calculate // result for first n-1 houses. int ans1 = helper(arr, n - 1); // case 2: First element is excluded we have to // calculate result 2 to n houses. int ans2 = helper(arr + 1, n - 1); return max(ans1, ans2);}// Driver to test above codeint main(){ int arr[] = { 1, 2, 3, 1 }; int n = sizeof(arr) / sizeof(arr[0]); cout << "Maximum loot possible : " << maxLoot(arr, n - 1); return 0;}// This code is contributed by Sanskar Bharadia
Maximum loot possible : 4
Complexity Analysis:
Time Complexity: O(2n).
Auxiliary Space: O(N)
Approach The problem can be solved using DP. An approach has already been discussed in this post, but it for an array. We can treat the circular subarray a two arrays one from (0th to n-2-th) and (1st to n-1-th) index, and use the approach used in the previous post. The maximum sum returned by both will be the answer.
Below is the implementation of the above approach.
C++
Java
Python 3
C#
PHP
Javascript
// CPP program to find maximum sum in a circular array// such that no elements are adjacent in the sum.#include <bits/stdc++.h>using namespace std; // Function to calculate the sum// from 0th position to(n-2)th positionint maxSum1(int arr[], int n){ int dp[n]; int maxi = 0; for (int i = 0; i < n - 1; i++) { // copy the element of original array to dp[] dp[i] = arr[i]; // find the maximum element in the array if (maxi < arr[i]) maxi = arr[i]; } // start from 2nd to n-1th pos for (int i = 2; i < n - 1; i++) { // traverse for all pairs // bottom-up approach for (int j = 0; j < i - 1; j++) { // dp-condition if (dp[i] < dp[j] + arr[i]) { dp[i] = dp[j] + arr[i]; // find maximum sum if (maxi < dp[i]) maxi = dp[i]; } } } // return the maximum return maxi;} // Function to find the maximum sum// from 1st position to n-1-th positionint maxSum2(int arr[], int n){ int dp[n]; int maxi = 0; for (int i = 1; i < n; i++) { dp[i] = arr[i]; if (maxi < arr[i]) maxi = arr[i]; } // Traverse from third to n-th pos for (int i = 3; i < n; i++) { // bottom-up approach for (int j = 1; j < i - 1; j++) { // dp condition if (dp[i] < arr[i] + dp[j]) { dp[i] = arr[i] + dp[j]; // find max sum if (maxi < dp[i]) maxi = dp[i]; } } } // return max return maxi;} int findMaxSum(int arr[], int n){ return max(maxSum1(arr, n), maxSum2(arr, n));} // Driver Codeint main(){ int arr[] = { 1, 2, 3, 1 }; int n = sizeof(arr)/sizeof(arr[0]); cout << findMaxSum(arr, n); return 0;}
// Java program to find maximum sum in a circular array// such that no elements are adjacent in the sum. import java.io.*; class GFG { // Function to calculate the sum// from 0th position to(n-2)th positionstatic int maxSum1(int arr[], int n){ int dp[]=new int[n]; int maxi = 0; for (int i = 0; i < n - 1; i++) { // copy the element of original array to dp[] dp[i] = arr[i]; // find the maximum element in the array if (maxi < arr[i]) maxi = arr[i]; } // start from 2nd to n-1th pos for (int i = 2; i < n - 1; i++) { // traverse for all pairs // bottom-up approach for (int j = 0; j < i - 1; j++) { // dp-condition if (dp[i] < dp[j] + arr[i]) { dp[i] = dp[j] + arr[i]; // find maximum sum if (maxi < dp[i]) maxi = dp[i]; } } } // return the maximum return maxi;} // Function to find the maximum sum// from 1st position to n-1-th positionstatic int maxSum2(int arr[], int n){ int dp[]=new int[n]; int maxi = 0; for (int i = 1; i < n; i++) { dp[i] = arr[i]; if (maxi < arr[i]) maxi = arr[i]; } // Traverse from third to n-th pos for (int i = 3; i < n; i++) { // bottom-up approach for (int j = 1; j < i - 1; j++) { // dp condition if (dp[i] < arr[i] + dp[j]) { dp[i] = arr[i] + dp[j]; // find max sum if (maxi < dp[i]) maxi = dp[i]; } } } // return max return maxi;} static int findMaxSum(int arr[], int n){ int t=Math.max(maxSum1(arr, n), maxSum2(arr, n)); return t;} // Driver Code public static void main (String[] args) { int arr[] = { 1, 2, 3, 1 }; int n = arr.length; System.out.println(findMaxSum(arr, n)); }}
# Python 3 program to find maximum sum# in a circular array such that no# elements are adjacent in the sum. # Function to calculate the sum from# 0th position to(n-2)th positiondef maxSum1(arr, n): dp = [0] * n maxi = 0 for i in range(n - 1): # copy the element of original # array to dp[] dp[i] = arr[i] # find the maximum element in the array if (maxi < arr[i]): maxi = arr[i] # start from 2nd to n-1th pos for i in range(2, n - 1): # traverse for all pairs bottom-up # approach for j in range(i - 1) : # dp-condition if (dp[i] < dp[j] + arr[i]): dp[i] = dp[j] + arr[i] # find maximum sum if (maxi < dp[i]): maxi = dp[i] # return the maximum return maxi # Function to find the maximum sum# from 1st position to n-1-th positiondef maxSum2(arr, n): dp = [0] * n maxi = 0 for i in range(1, n): dp[i] = arr[i] if (maxi < arr[i]): maxi = arr[i] # Traverse from third to n-th pos for i in range(3, n): # bottom-up approach for j in range(1, i - 1) : # dp condition if (dp[i] < arr[i] + dp[j]): dp[i] = arr[i] + dp[j] # find max sum if (maxi < dp[i]): maxi = dp[i] # return max return maxi def findMaxSum(arr, n): return max(maxSum1(arr, n), maxSum2(arr, n)) # Driver Codeif __name__ == "__main__": arr = [ 1, 2, 3, 1 ] n = len(arr) print(findMaxSum(arr, n)) # This code is contributed by ita_c
// C# program to find maximum sum// in a circular array such that// no elements are adjacent in the sum.using System; class GFG{// Function to calculate the sum// from 0th position to(n-2)th positionstatic int maxSum1(int []arr, int n){ int []dp = new int[n]; int maxi = 0; for (int i = 0; i < n - 1; i++) { // copy the element of original // array to dp[] dp[i] = arr[i]; // find the maximum element // in the array if (maxi < arr[i]) maxi = arr[i]; } // start from 2nd to n-1th pos for (int i = 2; i < n - 1; i++) { // traverse for all pairs // bottom-up approach for (int j = 0; j < i - 1; j++) { // dp-condition if (dp[i] < dp[j] + arr[i]) { dp[i] = dp[j] + arr[i]; // find maximum sum if (maxi < dp[i]) maxi = dp[i]; } } } // return the maximum return maxi;} // Function to find the maximum sum// from 1st position to n-1-th positionstatic int maxSum2(int []arr, int n){ int []dp = new int[n]; int maxi = 0; for (int i = 1; i < n; i++) { dp[i] = arr[i]; if (maxi < arr[i]) maxi = arr[i]; } // Traverse from third to n-th pos for (int i = 3; i < n; i++) { // bottom-up approach for (int j = 1; j < i - 1; j++) { // dp condition if (dp[i] < arr[i] + dp[j]) { dp[i] = arr[i] + dp[j]; // find max sum if (maxi < dp[i]) maxi = dp[i]; } } } // return max return maxi;} static int findMaxSum(int []arr, int n){ int t = Math.Max(maxSum1(arr, n), maxSum2(arr, n)); return t;} // Driver Codestatic public void Main (){ int []arr = { 1, 2, 3, 1 }; int n = arr.Length; Console.WriteLine(findMaxSum(arr, n));}} // This code is contributed// by Sach_Code
<?php// PHP program to find maximum sum in// a circular array such that no// elements are adjacent in the sum.// Function to calculate the sum// from 0th position to(n-2)th position function maxSum1($arr, $n){ $dp[$n] = array(); $maxi = 0; for ($i = 0; $i < $n - 1; $i++) { // copy the element of original // array to dp[] $dp[$i] = $arr[$i]; // find the maximum element in the array if ($maxi < $arr[$i]) $maxi = $arr[$i]; } // start from 2nd to n-1th pos for ($i = 2; $i < $n - 1; $i++) { // traverse for all pairs // bottom-up approach for ( $j = 0; $j < $i - 1; $j++) { // dp-condition if ($dp[$i] < $dp[$j] + $arr[$i]) { $dp[$i] = $dp[$j] + $arr[$i]; // find maximum sum if ($maxi < $dp[$i]) $maxi = $dp[$i]; } } } // return the maximum return $maxi;} // Function to find the maximum sum// from 1st position to n-1-th positionfunction maxSum2($arr, $n){ $dp[$n] = array(); $maxi = 0; for ($i = 1; $i < $n; $i++) { $dp[$i] = $arr[$i]; if ($maxi < $arr[$i]) $maxi = $arr[$i]; } // Traverse from third to n-th pos for ($i = 3; $i < $n; $i++) { // bottom-up approach for ($j = 1; $j < $i - 1; $j++) { // dp condition if ($dp[$i] < $arr[$i] + $dp[$j]) { $dp[$i] = $arr[$i] + $dp[$j]; // find max sum if ($maxi < $dp[$i]) $maxi = $dp[$i]; } } } // return max return $maxi;} function findMaxSum($arr, $n){ return max(maxSum1($arr, $n), maxSum2($arr, $n));} // Driver Code$arr = array(1, 2, 3, 1 );$n = sizeof($arr);echo findMaxSum($arr, $n); // This code is contributed// by Sach_Code?>
<script> // JavaScript program to find maximum sum// in a circular array such that// no elements are adjacent in the sum. // Function to calculate the sum// from 0th position to(n-2)th positionfunction maxSum1(arr, n){ let dp = new Array(n); let maxi = 0; for (i = 0; i < n - 1; i++) { // copy the element of original // array to dp[] dp[i] = arr[i]; // find the maximum element // in the array if (maxi < arr[i]) maxi = arr[i]; } // start from 2nd to n-1th pos for (i = 2; i < n - 1; i++) { // traverse for all pairs // bottom-up approach for (j = 0; j < i - 1; j++) { // dp-condition if (dp[i] < dp[j] + arr[i]) { dp[i] = dp[j] + arr[i]; // find maximum sum if (maxi < dp[i]) maxi = dp[i]; } } } // return the maximum return maxi;} // Function to find the maximum sum// from 1st position to n-1-th positionfunction maxSum2(arr, n){ let dp = new Array(n); let maxi = 0; for (i = 1; i < n; i++) { dp[i] = arr[i]; if (maxi < arr[i]) maxi = arr[i]; } // Traverse from third to n-th pos for (i = 3; i < n; i++) { // bottom-up approach for (j = 1; j < i - 1; j++) { // dp condition if (dp[i] < arr[i] + dp[j]) { dp[i] = arr[i] + dp[j]; // find max sum if (maxi < dp[i]) maxi = dp[i]; } } } // return max return maxi;} function findMaxSum(arr, n){ let t = Math.max(maxSum1(arr, n), maxSum2(arr, n)); return t;} // Driver Code let arr = [1, 2, 3, 1 ];let n = arr.length;document.write(findMaxSum(arr, n)); // This code is contributed by mohit kumar 29.</script>
4
Time Complexity: O(N^2)
Space optimization approach: As we can see the dp[i] is calculated form previous values so we can just store those previous values in variables.
C++
// C++ program to find the maximum stolen value#include <iostream>using namespace std; // calculate the maximum stolen valueint findMaxSum(int arr[], int n){ if (n == 0) return 0; int value1 = arr[0]; if (n == 1) return value1; int value2 = 0; // case 1: check for 1 to n-1 houses. // contains maximum stolen value at the end int max_val1, max_val2; // Fill remaining positions for (int i = 1; i < n - 1; i++) { int first = value1; int second = arr[i]; if (i > 1) { second += value2; } int curr = max(first, second); value2 = value1; value1 = curr; } // case 2: check for 2 to n houses. max_val1 = value1; value1 = arr[1]; value2 = 0; for (int i = 2; i < n; i++) { int first = value1; int second = arr[i]; if (i > 1) { second += value2; } int curr = max(first, second); value2 = value1; value1 = curr; } max_val2 = value1; return max(max_val1, max_val2);} // Driver to test above codeint main(){ // Value of houses int arr[] = { 6, 7, 1, 3, 8, 2, 4 }; int n = sizeof(arr) / sizeof(arr[0]); cout << findMaxSum(arr, n); return 0;}
19
Complexity Analysis:
Time Complexity: O(N).
Space Complexity: O(1).
Mohd_Saliem
Sach_Code
ukasp
mohit kumar 29
kapoorsagar226
sanskar84
Arrays
Dynamic Programming
Arrays
Dynamic Programming
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n16 Jun, 2022"
},
{
"code": null,
"e": 267,
"s": 54,
"text": "Given a circular array containing of positive integers value. The task is to find the maximum sum of a subsequence with the constraint that no 2 numbers in the sequence should be adjacent in the array.Examples: "
},
{
"code": null,
"e": 460,
"s": 267,
"text": "Input: circular arr = {1, 2, 3, 1}\nOutput : 4\nsubsequence will be(1, 3), hence 1 + 3 = 4 \n\nInput: circular arr = {1, 2, 3, 4, 5, 1}\nOutput: 9\nsubsequence will be(1, 3, 5), hence 1 + 3 + 5 = 9 "
},
{
"code": null,
"e": 1091,
"s": 462,
"text": "Naive Approach: This problem is extension to the problem https://www.geeksforgeeks.org/find-maximum-possible-stolen-value-houses/ .In this problem the arr elements are arranged in circular fashion so the 1st and the last element are also adjacent. So we can not take first and last element together so we can take either of the element1 or last element. So first we can take element 1 and exclude last element and calculate the maximum sum subsequence where no two selected elements are adjacent and then also we can calculate another answer by excluding 1st element and including last element. And we will take maximum of two."
},
{
"code": null,
"e": 1129,
"s": 1091,
"text": "Implementation of recursion approach:"
},
{
"code": null,
"e": 1133,
"s": 1129,
"text": "C++"
},
{
"code": "// CPP program to find maximum sum in a circular array// such that no elements are adjacent in the sum.#include<iostream>using namespace std; // calculate the maximum stolen valueint helper(int* arr, int n){ // base case if (n < 0) { return 0; } if (n == 0) { return arr[0]; } // if current element is pick then previous cannot be // picked int pick = arr[n] + helper(arr, n - 2); // if current element is not picked then previous // element is picked int notPick = helper(arr, n - 1); // return max of picked and not picked return max(pick, notPick);} int maxLoot(int* arr, int n){ // case 1: Last elenent is exluded we have to calculate // result for first n-1 houses. int ans1 = helper(arr, n - 1); // case 2: First element is excluded we have to // calculate result 2 to n houses. int ans2 = helper(arr + 1, n - 1); return max(ans1, ans2);}// Driver to test above codeint main(){ int arr[] = { 1, 2, 3, 1 }; int n = sizeof(arr) / sizeof(arr[0]); cout << \"Maximum loot possible : \" << maxLoot(arr, n - 1); return 0;}// This code is contributed by Sanskar Bharadia",
"e": 2297,
"s": 1133,
"text": null
},
{
"code": null,
"e": 2323,
"s": 2297,
"text": "Maximum loot possible : 4"
},
{
"code": null,
"e": 2344,
"s": 2323,
"text": "Complexity Analysis:"
},
{
"code": null,
"e": 2369,
"s": 2344,
"text": "Time Complexity: O(2n)."
},
{
"code": null,
"e": 2391,
"s": 2369,
"text": "Auxiliary Space: O(N)"
},
{
"code": null,
"e": 2713,
"s": 2391,
"text": "Approach The problem can be solved using DP. An approach has already been discussed in this post, but it for an array. We can treat the circular subarray a two arrays one from (0th to n-2-th) and (1st to n-1-th) index, and use the approach used in the previous post. The maximum sum returned by both will be the answer. "
},
{
"code": null,
"e": 2768,
"s": 2715,
"text": "Below is the implementation of the above approach. "
},
{
"code": null,
"e": 2772,
"s": 2768,
"text": "C++"
},
{
"code": null,
"e": 2777,
"s": 2772,
"text": "Java"
},
{
"code": null,
"e": 2786,
"s": 2777,
"text": "Python 3"
},
{
"code": null,
"e": 2789,
"s": 2786,
"text": "C#"
},
{
"code": null,
"e": 2793,
"s": 2789,
"text": "PHP"
},
{
"code": null,
"e": 2804,
"s": 2793,
"text": "Javascript"
},
{
"code": "// CPP program to find maximum sum in a circular array// such that no elements are adjacent in the sum.#include <bits/stdc++.h>using namespace std; // Function to calculate the sum// from 0th position to(n-2)th positionint maxSum1(int arr[], int n){ int dp[n]; int maxi = 0; for (int i = 0; i < n - 1; i++) { // copy the element of original array to dp[] dp[i] = arr[i]; // find the maximum element in the array if (maxi < arr[i]) maxi = arr[i]; } // start from 2nd to n-1th pos for (int i = 2; i < n - 1; i++) { // traverse for all pairs // bottom-up approach for (int j = 0; j < i - 1; j++) { // dp-condition if (dp[i] < dp[j] + arr[i]) { dp[i] = dp[j] + arr[i]; // find maximum sum if (maxi < dp[i]) maxi = dp[i]; } } } // return the maximum return maxi;} // Function to find the maximum sum// from 1st position to n-1-th positionint maxSum2(int arr[], int n){ int dp[n]; int maxi = 0; for (int i = 1; i < n; i++) { dp[i] = arr[i]; if (maxi < arr[i]) maxi = arr[i]; } // Traverse from third to n-th pos for (int i = 3; i < n; i++) { // bottom-up approach for (int j = 1; j < i - 1; j++) { // dp condition if (dp[i] < arr[i] + dp[j]) { dp[i] = arr[i] + dp[j]; // find max sum if (maxi < dp[i]) maxi = dp[i]; } } } // return max return maxi;} int findMaxSum(int arr[], int n){ return max(maxSum1(arr, n), maxSum2(arr, n));} // Driver Codeint main(){ int arr[] = { 1, 2, 3, 1 }; int n = sizeof(arr)/sizeof(arr[0]); cout << findMaxSum(arr, n); return 0;}",
"e": 4648,
"s": 2804,
"text": null
},
{
"code": "// Java program to find maximum sum in a circular array// such that no elements are adjacent in the sum. import java.io.*; class GFG { // Function to calculate the sum// from 0th position to(n-2)th positionstatic int maxSum1(int arr[], int n){ int dp[]=new int[n]; int maxi = 0; for (int i = 0; i < n - 1; i++) { // copy the element of original array to dp[] dp[i] = arr[i]; // find the maximum element in the array if (maxi < arr[i]) maxi = arr[i]; } // start from 2nd to n-1th pos for (int i = 2; i < n - 1; i++) { // traverse for all pairs // bottom-up approach for (int j = 0; j < i - 1; j++) { // dp-condition if (dp[i] < dp[j] + arr[i]) { dp[i] = dp[j] + arr[i]; // find maximum sum if (maxi < dp[i]) maxi = dp[i]; } } } // return the maximum return maxi;} // Function to find the maximum sum// from 1st position to n-1-th positionstatic int maxSum2(int arr[], int n){ int dp[]=new int[n]; int maxi = 0; for (int i = 1; i < n; i++) { dp[i] = arr[i]; if (maxi < arr[i]) maxi = arr[i]; } // Traverse from third to n-th pos for (int i = 3; i < n; i++) { // bottom-up approach for (int j = 1; j < i - 1; j++) { // dp condition if (dp[i] < arr[i] + dp[j]) { dp[i] = arr[i] + dp[j]; // find max sum if (maxi < dp[i]) maxi = dp[i]; } } } // return max return maxi;} static int findMaxSum(int arr[], int n){ int t=Math.max(maxSum1(arr, n), maxSum2(arr, n)); return t;} // Driver Code public static void main (String[] args) { int arr[] = { 1, 2, 3, 1 }; int n = arr.length; System.out.println(findMaxSum(arr, n)); }}",
"e": 6601,
"s": 4648,
"text": null
},
{
"code": "# Python 3 program to find maximum sum# in a circular array such that no# elements are adjacent in the sum. # Function to calculate the sum from# 0th position to(n-2)th positiondef maxSum1(arr, n): dp = [0] * n maxi = 0 for i in range(n - 1): # copy the element of original # array to dp[] dp[i] = arr[i] # find the maximum element in the array if (maxi < arr[i]): maxi = arr[i] # start from 2nd to n-1th pos for i in range(2, n - 1): # traverse for all pairs bottom-up # approach for j in range(i - 1) : # dp-condition if (dp[i] < dp[j] + arr[i]): dp[i] = dp[j] + arr[i] # find maximum sum if (maxi < dp[i]): maxi = dp[i] # return the maximum return maxi # Function to find the maximum sum# from 1st position to n-1-th positiondef maxSum2(arr, n): dp = [0] * n maxi = 0 for i in range(1, n): dp[i] = arr[i] if (maxi < arr[i]): maxi = arr[i] # Traverse from third to n-th pos for i in range(3, n): # bottom-up approach for j in range(1, i - 1) : # dp condition if (dp[i] < arr[i] + dp[j]): dp[i] = arr[i] + dp[j] # find max sum if (maxi < dp[i]): maxi = dp[i] # return max return maxi def findMaxSum(arr, n): return max(maxSum1(arr, n), maxSum2(arr, n)) # Driver Codeif __name__ == \"__main__\": arr = [ 1, 2, 3, 1 ] n = len(arr) print(findMaxSum(arr, n)) # This code is contributed by ita_c",
"e": 8245,
"s": 6601,
"text": null
},
{
"code": "// C# program to find maximum sum// in a circular array such that// no elements are adjacent in the sum.using System; class GFG{// Function to calculate the sum// from 0th position to(n-2)th positionstatic int maxSum1(int []arr, int n){ int []dp = new int[n]; int maxi = 0; for (int i = 0; i < n - 1; i++) { // copy the element of original // array to dp[] dp[i] = arr[i]; // find the maximum element // in the array if (maxi < arr[i]) maxi = arr[i]; } // start from 2nd to n-1th pos for (int i = 2; i < n - 1; i++) { // traverse for all pairs // bottom-up approach for (int j = 0; j < i - 1; j++) { // dp-condition if (dp[i] < dp[j] + arr[i]) { dp[i] = dp[j] + arr[i]; // find maximum sum if (maxi < dp[i]) maxi = dp[i]; } } } // return the maximum return maxi;} // Function to find the maximum sum// from 1st position to n-1-th positionstatic int maxSum2(int []arr, int n){ int []dp = new int[n]; int maxi = 0; for (int i = 1; i < n; i++) { dp[i] = arr[i]; if (maxi < arr[i]) maxi = arr[i]; } // Traverse from third to n-th pos for (int i = 3; i < n; i++) { // bottom-up approach for (int j = 1; j < i - 1; j++) { // dp condition if (dp[i] < arr[i] + dp[j]) { dp[i] = arr[i] + dp[j]; // find max sum if (maxi < dp[i]) maxi = dp[i]; } } } // return max return maxi;} static int findMaxSum(int []arr, int n){ int t = Math.Max(maxSum1(arr, n), maxSum2(arr, n)); return t;} // Driver Codestatic public void Main (){ int []arr = { 1, 2, 3, 1 }; int n = arr.Length; Console.WriteLine(findMaxSum(arr, n));}} // This code is contributed// by Sach_Code",
"e": 10264,
"s": 8245,
"text": null
},
{
"code": "<?php// PHP program to find maximum sum in// a circular array such that no// elements are adjacent in the sum.// Function to calculate the sum// from 0th position to(n-2)th position function maxSum1($arr, $n){ $dp[$n] = array(); $maxi = 0; for ($i = 0; $i < $n - 1; $i++) { // copy the element of original // array to dp[] $dp[$i] = $arr[$i]; // find the maximum element in the array if ($maxi < $arr[$i]) $maxi = $arr[$i]; } // start from 2nd to n-1th pos for ($i = 2; $i < $n - 1; $i++) { // traverse for all pairs // bottom-up approach for ( $j = 0; $j < $i - 1; $j++) { // dp-condition if ($dp[$i] < $dp[$j] + $arr[$i]) { $dp[$i] = $dp[$j] + $arr[$i]; // find maximum sum if ($maxi < $dp[$i]) $maxi = $dp[$i]; } } } // return the maximum return $maxi;} // Function to find the maximum sum// from 1st position to n-1-th positionfunction maxSum2($arr, $n){ $dp[$n] = array(); $maxi = 0; for ($i = 1; $i < $n; $i++) { $dp[$i] = $arr[$i]; if ($maxi < $arr[$i]) $maxi = $arr[$i]; } // Traverse from third to n-th pos for ($i = 3; $i < $n; $i++) { // bottom-up approach for ($j = 1; $j < $i - 1; $j++) { // dp condition if ($dp[$i] < $arr[$i] + $dp[$j]) { $dp[$i] = $arr[$i] + $dp[$j]; // find max sum if ($maxi < $dp[$i]) $maxi = $dp[$i]; } } } // return max return $maxi;} function findMaxSum($arr, $n){ return max(maxSum1($arr, $n), maxSum2($arr, $n));} // Driver Code$arr = array(1, 2, 3, 1 );$n = sizeof($arr);echo findMaxSum($arr, $n); // This code is contributed// by Sach_Code?>",
"e": 12202,
"s": 10264,
"text": null
},
{
"code": "<script> // JavaScript program to find maximum sum// in a circular array such that// no elements are adjacent in the sum. // Function to calculate the sum// from 0th position to(n-2)th positionfunction maxSum1(arr, n){ let dp = new Array(n); let maxi = 0; for (i = 0; i < n - 1; i++) { // copy the element of original // array to dp[] dp[i] = arr[i]; // find the maximum element // in the array if (maxi < arr[i]) maxi = arr[i]; } // start from 2nd to n-1th pos for (i = 2; i < n - 1; i++) { // traverse for all pairs // bottom-up approach for (j = 0; j < i - 1; j++) { // dp-condition if (dp[i] < dp[j] + arr[i]) { dp[i] = dp[j] + arr[i]; // find maximum sum if (maxi < dp[i]) maxi = dp[i]; } } } // return the maximum return maxi;} // Function to find the maximum sum// from 1st position to n-1-th positionfunction maxSum2(arr, n){ let dp = new Array(n); let maxi = 0; for (i = 1; i < n; i++) { dp[i] = arr[i]; if (maxi < arr[i]) maxi = arr[i]; } // Traverse from third to n-th pos for (i = 3; i < n; i++) { // bottom-up approach for (j = 1; j < i - 1; j++) { // dp condition if (dp[i] < arr[i] + dp[j]) { dp[i] = arr[i] + dp[j]; // find max sum if (maxi < dp[i]) maxi = dp[i]; } } } // return max return maxi;} function findMaxSum(arr, n){ let t = Math.max(maxSum1(arr, n), maxSum2(arr, n)); return t;} // Driver Code let arr = [1, 2, 3, 1 ];let n = arr.length;document.write(findMaxSum(arr, n)); // This code is contributed by mohit kumar 29.</script>",
"e": 14122,
"s": 12202,
"text": null
},
{
"code": null,
"e": 14124,
"s": 14122,
"text": "4"
},
{
"code": null,
"e": 14149,
"s": 14124,
"text": "Time Complexity: O(N^2) "
},
{
"code": null,
"e": 14294,
"s": 14149,
"text": "Space optimization approach: As we can see the dp[i] is calculated form previous values so we can just store those previous values in variables."
},
{
"code": null,
"e": 14298,
"s": 14294,
"text": "C++"
},
{
"code": "// C++ program to find the maximum stolen value#include <iostream>using namespace std; // calculate the maximum stolen valueint findMaxSum(int arr[], int n){ if (n == 0) return 0; int value1 = arr[0]; if (n == 1) return value1; int value2 = 0; // case 1: check for 1 to n-1 houses. // contains maximum stolen value at the end int max_val1, max_val2; // Fill remaining positions for (int i = 1; i < n - 1; i++) { int first = value1; int second = arr[i]; if (i > 1) { second += value2; } int curr = max(first, second); value2 = value1; value1 = curr; } // case 2: check for 2 to n houses. max_val1 = value1; value1 = arr[1]; value2 = 0; for (int i = 2; i < n; i++) { int first = value1; int second = arr[i]; if (i > 1) { second += value2; } int curr = max(first, second); value2 = value1; value1 = curr; } max_val2 = value1; return max(max_val1, max_val2);} // Driver to test above codeint main(){ // Value of houses int arr[] = { 6, 7, 1, 3, 8, 2, 4 }; int n = sizeof(arr) / sizeof(arr[0]); cout << findMaxSum(arr, n); return 0;}",
"e": 15537,
"s": 14298,
"text": null
},
{
"code": null,
"e": 15540,
"s": 15537,
"text": "19"
},
{
"code": null,
"e": 15561,
"s": 15540,
"text": "Complexity Analysis:"
},
{
"code": null,
"e": 15585,
"s": 15561,
"text": "Time Complexity: O(N)."
},
{
"code": null,
"e": 15610,
"s": 15585,
"text": "Space Complexity: O(1). "
},
{
"code": null,
"e": 15622,
"s": 15610,
"text": "Mohd_Saliem"
},
{
"code": null,
"e": 15632,
"s": 15622,
"text": "Sach_Code"
},
{
"code": null,
"e": 15638,
"s": 15632,
"text": "ukasp"
},
{
"code": null,
"e": 15653,
"s": 15638,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 15668,
"s": 15653,
"text": "kapoorsagar226"
},
{
"code": null,
"e": 15678,
"s": 15668,
"text": "sanskar84"
},
{
"code": null,
"e": 15685,
"s": 15678,
"text": "Arrays"
},
{
"code": null,
"e": 15705,
"s": 15685,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 15712,
"s": 15705,
"text": "Arrays"
},
{
"code": null,
"e": 15732,
"s": 15712,
"text": "Dynamic Programming"
}
] |
How to Encrypt and Decrypt Strings in Python? | 08 Jun, 2022
In this article, we will learn about Encryption, Decryption and implement them with Python.
Encryption:
Encryption is the process of encoding the data. i.e converting plain text into ciphertext. This conversion is done with a key called an encryption key.
Decryption:
Decryption is the process of decoding the encoded data. Converting the ciphertext into plain text. This process requires a key that we used for encryption.
We require a key for encryption. There are two main types of keys used for encryption and decryption. They are Symmetric-key and Asymmetric-key.
Symmetric-key Encryption:
In symmetric-key encryption, the data is encoded and decoded with the same key. This is the easiest way of encryption, but also less secure. The receiver needs the key for decryption, so a safe way need for transferring keys. Anyone with the key can read the data in the middle.
Example:
Install the python cryptography library with the following command.
pip install cryptography
Steps:
Import Fernet
Then generate an encryption key, that can be used for encryption and decryption.
Convert the string to a byte string, so that it can be encrypted.
Instance the Fernet class with the encryption key.
Then encrypt the string with the Fernet instance.
Then it can be decrypted with Fernet class instance and it should be instanced with the same key used for encryption.
Python3
from cryptography.fernet import Fernet # we will be encrypting the below string.message = "hello geeks" # generate a key for encryption and decryption# You can use fernet to generate# the key or use random key generator# here I'm using fernet to generate key key = Fernet.generate_key() # Instance the Fernet class with the key fernet = Fernet(key) # then use the Fernet class instance# to encrypt the string string must# be encoded to byte string before encryptionencMessage = fernet.encrypt(message.encode()) print("original string: ", message)print("encrypted string: ", encMessage) # decrypt the encrypted string with the# Fernet instance of the key,# that was used for encrypting the string# encoded byte string is returned by decrypt method,# so decode it to string with decode methodsdecMessage = fernet.decrypt(encMessage).decode() print("decrypted string: ", decMessage)
Output:
Asymmetric-key Encryption:
In Asymmetric-key Encryption, we use two keys a public key and a private key. The public key is used to encrypt the data and the private key is used to decrypt the data. By the name, the public key can be public (can be sent to anyone who needs to send data). No one has your private key, so no one in the middle can read your data.
Example:
Install the python rsa library with the following command.
pip install rsa
Steps:
Import rsa library
Generate public and private keys with rsa.newkeys() method.
Encode the string to byte string.
Then encrypt the byte string with the public key.
Then the encrypted string can be decrypted with the private key.
The public key can only be used for encryption and the private can only be used for decryption.
Python3
import rsa # generate public and private keys with# rsa.newkeys method,this method accepts# key length as its parameter# key length should be atleast 16publicKey, privateKey = rsa.newkeys(512) # this is the string that we will be encryptingmessage = "hello geeks" # rsa.encrypt method is used to encrypt# string with public key string should be# encode to byte string before encryption# with encode methodencMessage = rsa.encrypt(message.encode(), publicKey) print("original string: ", message)print("encrypted string: ", encMessage) # the encrypted message can be decrypted# with ras.decrypt method and private key# decrypt method returns encoded byte string,# use decode method to convert it to string# public key cannot be used for decryptiondecMessage = rsa.decrypt(encMessage, privateKey).decode() print("decrypted string: ", decMessage)
Output:
gabaa406
simmytarika5
harshmaster07705
cryptography
Picked
Python
cryptography
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
Iterate over a list in Python
Python OOPs Concepts | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n08 Jun, 2022"
},
{
"code": null,
"e": 147,
"s": 54,
"text": "In this article, we will learn about Encryption, Decryption and implement them with Python. "
},
{
"code": null,
"e": 159,
"s": 147,
"text": "Encryption:"
},
{
"code": null,
"e": 311,
"s": 159,
"text": "Encryption is the process of encoding the data. i.e converting plain text into ciphertext. This conversion is done with a key called an encryption key."
},
{
"code": null,
"e": 323,
"s": 311,
"text": "Decryption:"
},
{
"code": null,
"e": 479,
"s": 323,
"text": "Decryption is the process of decoding the encoded data. Converting the ciphertext into plain text. This process requires a key that we used for encryption."
},
{
"code": null,
"e": 624,
"s": 479,
"text": "We require a key for encryption. There are two main types of keys used for encryption and decryption. They are Symmetric-key and Asymmetric-key."
},
{
"code": null,
"e": 650,
"s": 624,
"text": "Symmetric-key Encryption:"
},
{
"code": null,
"e": 929,
"s": 650,
"text": "In symmetric-key encryption, the data is encoded and decoded with the same key. This is the easiest way of encryption, but also less secure. The receiver needs the key for decryption, so a safe way need for transferring keys. Anyone with the key can read the data in the middle."
},
{
"code": null,
"e": 938,
"s": 929,
"text": "Example:"
},
{
"code": null,
"e": 1007,
"s": 938,
"text": "Install the python cryptography library with the following command. "
},
{
"code": null,
"e": 1032,
"s": 1007,
"text": "pip install cryptography"
},
{
"code": null,
"e": 1039,
"s": 1032,
"text": "Steps:"
},
{
"code": null,
"e": 1053,
"s": 1039,
"text": "Import Fernet"
},
{
"code": null,
"e": 1134,
"s": 1053,
"text": "Then generate an encryption key, that can be used for encryption and decryption."
},
{
"code": null,
"e": 1200,
"s": 1134,
"text": "Convert the string to a byte string, so that it can be encrypted."
},
{
"code": null,
"e": 1251,
"s": 1200,
"text": "Instance the Fernet class with the encryption key."
},
{
"code": null,
"e": 1301,
"s": 1251,
"text": "Then encrypt the string with the Fernet instance."
},
{
"code": null,
"e": 1419,
"s": 1301,
"text": "Then it can be decrypted with Fernet class instance and it should be instanced with the same key used for encryption."
},
{
"code": null,
"e": 1427,
"s": 1419,
"text": "Python3"
},
{
"code": "from cryptography.fernet import Fernet # we will be encrypting the below string.message = \"hello geeks\" # generate a key for encryption and decryption# You can use fernet to generate# the key or use random key generator# here I'm using fernet to generate key key = Fernet.generate_key() # Instance the Fernet class with the key fernet = Fernet(key) # then use the Fernet class instance# to encrypt the string string must# be encoded to byte string before encryptionencMessage = fernet.encrypt(message.encode()) print(\"original string: \", message)print(\"encrypted string: \", encMessage) # decrypt the encrypted string with the# Fernet instance of the key,# that was used for encrypting the string# encoded byte string is returned by decrypt method,# so decode it to string with decode methodsdecMessage = fernet.decrypt(encMessage).decode() print(\"decrypted string: \", decMessage)",
"e": 2307,
"s": 1427,
"text": null
},
{
"code": null,
"e": 2315,
"s": 2307,
"text": "Output:"
},
{
"code": null,
"e": 2342,
"s": 2315,
"text": "Asymmetric-key Encryption:"
},
{
"code": null,
"e": 2675,
"s": 2342,
"text": "In Asymmetric-key Encryption, we use two keys a public key and a private key. The public key is used to encrypt the data and the private key is used to decrypt the data. By the name, the public key can be public (can be sent to anyone who needs to send data). No one has your private key, so no one in the middle can read your data."
},
{
"code": null,
"e": 2684,
"s": 2675,
"text": "Example:"
},
{
"code": null,
"e": 2744,
"s": 2684,
"text": "Install the python rsa library with the following command. "
},
{
"code": null,
"e": 2760,
"s": 2744,
"text": "pip install rsa"
},
{
"code": null,
"e": 2767,
"s": 2760,
"text": "Steps:"
},
{
"code": null,
"e": 2786,
"s": 2767,
"text": "Import rsa library"
},
{
"code": null,
"e": 2846,
"s": 2786,
"text": "Generate public and private keys with rsa.newkeys() method."
},
{
"code": null,
"e": 2880,
"s": 2846,
"text": "Encode the string to byte string."
},
{
"code": null,
"e": 2930,
"s": 2880,
"text": "Then encrypt the byte string with the public key."
},
{
"code": null,
"e": 2995,
"s": 2930,
"text": "Then the encrypted string can be decrypted with the private key."
},
{
"code": null,
"e": 3091,
"s": 2995,
"text": "The public key can only be used for encryption and the private can only be used for decryption."
},
{
"code": null,
"e": 3099,
"s": 3091,
"text": "Python3"
},
{
"code": "import rsa # generate public and private keys with# rsa.newkeys method,this method accepts# key length as its parameter# key length should be atleast 16publicKey, privateKey = rsa.newkeys(512) # this is the string that we will be encryptingmessage = \"hello geeks\" # rsa.encrypt method is used to encrypt# string with public key string should be# encode to byte string before encryption# with encode methodencMessage = rsa.encrypt(message.encode(), publicKey) print(\"original string: \", message)print(\"encrypted string: \", encMessage) # the encrypted message can be decrypted# with ras.decrypt method and private key# decrypt method returns encoded byte string,# use decode method to convert it to string# public key cannot be used for decryptiondecMessage = rsa.decrypt(encMessage, privateKey).decode() print(\"decrypted string: \", decMessage)",
"e": 3966,
"s": 3099,
"text": null
},
{
"code": null,
"e": 3974,
"s": 3966,
"text": "Output:"
},
{
"code": null,
"e": 3983,
"s": 3974,
"text": "gabaa406"
},
{
"code": null,
"e": 3996,
"s": 3983,
"text": "simmytarika5"
},
{
"code": null,
"e": 4013,
"s": 3996,
"text": "harshmaster07705"
},
{
"code": null,
"e": 4026,
"s": 4013,
"text": "cryptography"
},
{
"code": null,
"e": 4033,
"s": 4026,
"text": "Picked"
},
{
"code": null,
"e": 4040,
"s": 4033,
"text": "Python"
},
{
"code": null,
"e": 4053,
"s": 4040,
"text": "cryptography"
},
{
"code": null,
"e": 4151,
"s": 4053,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4169,
"s": 4151,
"text": "Python Dictionary"
},
{
"code": null,
"e": 4211,
"s": 4169,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 4233,
"s": 4211,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 4268,
"s": 4233,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 4294,
"s": 4268,
"text": "Python String | replace()"
},
{
"code": null,
"e": 4326,
"s": 4294,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 4355,
"s": 4326,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 4382,
"s": 4355,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 4412,
"s": 4382,
"text": "Iterate over a list in Python"
}
] |
Java Lambda Expression with Collections | 24 Jun, 2022
In this article, Lambda Expression with Collections is discussed with examples of sorting different collections like ArrayList, TreeSet, TreeMap, etc. Sorting Collections with Comparator (or without Lambda): We can use Comparator interface to sort, It only contains one abstract method: – compare(). An interface that only contains only a single abstract method then it is called a Functional Interface.
Use of Comparator(I): –
Prototype of compare() method: –
While defining our own sorting, JVM is always going to call Comparator to compare() method.
returns negative value(-1), if and only if obj1 has to come before obj2.
returns positive value(+1), if and only if obj1 has to come after obj2.
returns zero(0), if and only if obj1 and obj2 are equal.
In List, Set, Map, or anywhere else when we want to define our own sorting method, JVM will always call compare() method internally. When there is Functional Interface concept used, then we can use Lambda Expression in its place. Sorting elements of List(I) with Lambda
Expression: – Using lambda expression in place of comparator object for defining our own sorting in collections.
Java
import java.util.*; public class Demo { public static void main(String[] args) { ArrayList<Integer> al = new ArrayList<Integer>(); al.add(205); al.add(102); al.add(98); al.add(275); al.add(203); System.out.println("Elements of the ArrayList " + "before sorting : " + al); // using lambda expression in place of comparator object Collections.sort(al, (o1, o2) -> (o1 > o2) ? -1 : (o1 < o2) ? 1 : 0); System.out.println("Elements of the ArrayList after" + " sorting : " + al); }}
Sorting TreeSet using Lambda Expression:
Java
import java.util.*; public class Demo { public static void main(String[] args) { TreeSet<Integer> h = new TreeSet<Integer>((o1, o2) -> (o1 > o2) ? -1 : (o1 < o2) ? 1 : 0); h.add(850); h.add(235); h.add(1080); h.add(15); h.add(5); System.out.println("Elements of the TreeSet after" + " sorting are: " + h); }}
Sorting elements of TreeMap using Lambda Expression: Sorting will be done on the basis of the keys and not its value.
Java
import java.util.*; public class Demo { public static void main(String[] args) { TreeMap<Integer, String> m = new TreeMap<Integer, String>((o1, o2) -> (o1 > o2) ? -1 : (o1 < o2) ? 1 : 0); m.put(1, "Apple"); m.put(4, "Mango"); m.put(5, "Orange"); m.put(2, "Banana"); m.put(3, "Grapes"); System.out.println("Elements of the TreeMap " + "after sorting are : " + m); }}
It is also possible to specify a reverse comparator via a lambda expression directly in the call to the TreeSet() constructor, as shown here:
Java
// Use a lambda expression to create a reverse comapratorimport java.util.*; class GFG{public static void main(String args[]){ // Pass a reverse comparator to TreeSet() via a lambda expression TreeSet<String> ts=new TreeSet<String>((aStr,bStr) -> bStr.compareTo(aStr)); // Add elements to the Treeset ts.add("A"); ts.add("B"); ts.add("C"); ts.add("D"); ts.add("E"); ts.add("F"); ts.add("G"); //Display the elements . for(String element : ts) System.out.println(element + ""); System.out.println();}}
G
F
E
D
C
B
A
singhankitasingh066
Java-ArrayList
Java-Collections
java-lambda
Java-List-Programs
java-TreeMap
java-treeset
Java
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
Functional Interfaces in Java
Java Programming Examples
Strings in Java
Differences between JDK, JRE and JVM
Abstraction in Java | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n24 Jun, 2022"
},
{
"code": null,
"e": 456,
"s": 52,
"text": "In this article, Lambda Expression with Collections is discussed with examples of sorting different collections like ArrayList, TreeSet, TreeMap, etc. Sorting Collections with Comparator (or without Lambda): We can use Comparator interface to sort, It only contains one abstract method: – compare(). An interface that only contains only a single abstract method then it is called a Functional Interface."
},
{
"code": null,
"e": 480,
"s": 456,
"text": "Use of Comparator(I): –"
},
{
"code": null,
"e": 513,
"s": 480,
"text": "Prototype of compare() method: –"
},
{
"code": null,
"e": 605,
"s": 513,
"text": "While defining our own sorting, JVM is always going to call Comparator to compare() method."
},
{
"code": null,
"e": 678,
"s": 605,
"text": "returns negative value(-1), if and only if obj1 has to come before obj2."
},
{
"code": null,
"e": 750,
"s": 678,
"text": "returns positive value(+1), if and only if obj1 has to come after obj2."
},
{
"code": null,
"e": 807,
"s": 750,
"text": "returns zero(0), if and only if obj1 and obj2 are equal."
},
{
"code": null,
"e": 1077,
"s": 807,
"text": "In List, Set, Map, or anywhere else when we want to define our own sorting method, JVM will always call compare() method internally. When there is Functional Interface concept used, then we can use Lambda Expression in its place. Sorting elements of List(I) with Lambda"
},
{
"code": null,
"e": 1191,
"s": 1077,
"text": "Expression: – Using lambda expression in place of comparator object for defining our own sorting in collections. "
},
{
"code": null,
"e": 1196,
"s": 1191,
"text": "Java"
},
{
"code": "import java.util.*; public class Demo { public static void main(String[] args) { ArrayList<Integer> al = new ArrayList<Integer>(); al.add(205); al.add(102); al.add(98); al.add(275); al.add(203); System.out.println(\"Elements of the ArrayList \" + \"before sorting : \" + al); // using lambda expression in place of comparator object Collections.sort(al, (o1, o2) -> (o1 > o2) ? -1 : (o1 < o2) ? 1 : 0); System.out.println(\"Elements of the ArrayList after\" + \" sorting : \" + al); }}",
"e": 1864,
"s": 1196,
"text": null
},
{
"code": null,
"e": 1905,
"s": 1864,
"text": "Sorting TreeSet using Lambda Expression:"
},
{
"code": null,
"e": 1910,
"s": 1905,
"text": "Java"
},
{
"code": "import java.util.*; public class Demo { public static void main(String[] args) { TreeSet<Integer> h = new TreeSet<Integer>((o1, o2) -> (o1 > o2) ? -1 : (o1 < o2) ? 1 : 0); h.add(850); h.add(235); h.add(1080); h.add(15); h.add(5); System.out.println(\"Elements of the TreeSet after\" + \" sorting are: \" + h); }}",
"e": 2379,
"s": 1910,
"text": null
},
{
"code": null,
"e": 2498,
"s": 2379,
"text": "Sorting elements of TreeMap using Lambda Expression: Sorting will be done on the basis of the keys and not its value. "
},
{
"code": null,
"e": 2503,
"s": 2498,
"text": "Java"
},
{
"code": "import java.util.*; public class Demo { public static void main(String[] args) { TreeMap<Integer, String> m = new TreeMap<Integer, String>((o1, o2) -> (o1 > o2) ? -1 : (o1 < o2) ? 1 : 0); m.put(1, \"Apple\"); m.put(4, \"Mango\"); m.put(5, \"Orange\"); m.put(2, \"Banana\"); m.put(3, \"Grapes\"); System.out.println(\"Elements of the TreeMap \" + \"after sorting are : \" + m); }}",
"e": 3019,
"s": 2503,
"text": null
},
{
"code": null,
"e": 3161,
"s": 3019,
"text": "It is also possible to specify a reverse comparator via a lambda expression directly in the call to the TreeSet() constructor, as shown here:"
},
{
"code": null,
"e": 3166,
"s": 3161,
"text": "Java"
},
{
"code": "// Use a lambda expression to create a reverse comapratorimport java.util.*; class GFG{public static void main(String args[]){ // Pass a reverse comparator to TreeSet() via a lambda expression TreeSet<String> ts=new TreeSet<String>((aStr,bStr) -> bStr.compareTo(aStr)); // Add elements to the Treeset ts.add(\"A\"); ts.add(\"B\"); ts.add(\"C\"); ts.add(\"D\"); ts.add(\"E\"); ts.add(\"F\"); ts.add(\"G\"); //Display the elements . for(String element : ts) System.out.println(element + \"\"); System.out.println();}}",
"e": 3692,
"s": 3166,
"text": null
},
{
"code": null,
"e": 3706,
"s": 3692,
"text": "G\nF\nE\nD\nC\nB\nA"
},
{
"code": null,
"e": 3726,
"s": 3706,
"text": "singhankitasingh066"
},
{
"code": null,
"e": 3741,
"s": 3726,
"text": "Java-ArrayList"
},
{
"code": null,
"e": 3758,
"s": 3741,
"text": "Java-Collections"
},
{
"code": null,
"e": 3770,
"s": 3758,
"text": "java-lambda"
},
{
"code": null,
"e": 3789,
"s": 3770,
"text": "Java-List-Programs"
},
{
"code": null,
"e": 3802,
"s": 3789,
"text": "java-TreeMap"
},
{
"code": null,
"e": 3815,
"s": 3802,
"text": "java-treeset"
},
{
"code": null,
"e": 3820,
"s": 3815,
"text": "Java"
},
{
"code": null,
"e": 3825,
"s": 3820,
"text": "Java"
},
{
"code": null,
"e": 3842,
"s": 3825,
"text": "Java-Collections"
},
{
"code": null,
"e": 3940,
"s": 3842,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3955,
"s": 3940,
"text": "Stream In Java"
},
{
"code": null,
"e": 3976,
"s": 3955,
"text": "Introduction to Java"
},
{
"code": null,
"e": 3997,
"s": 3976,
"text": "Constructors in Java"
},
{
"code": null,
"e": 4016,
"s": 3997,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 4033,
"s": 4016,
"text": "Generics in Java"
},
{
"code": null,
"e": 4063,
"s": 4033,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 4089,
"s": 4063,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 4105,
"s": 4089,
"text": "Strings in Java"
},
{
"code": null,
"e": 4142,
"s": 4105,
"text": "Differences between JDK, JRE and JVM"
}
] |
jQuery UI dialog open() Method | 13 Jan, 2021
open() Method is used to open the dialog. This method does not accept any argument
Syntax:
$( ".selector" ).dialog("open");
Approach: First, add jQuery UI scripts needed for your project.
<link href = “https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css” rel = “stylesheet”><script src = “https://code.jquery.com/jquery-1.10.2.js”></script><script src = “https://code.jquery.com/ui/1.10.4/jquery-ui.js”></script>
Example:
HTML
<!doctype html><html lang="en"> <head> <meta charset="utf-8"> <link href="https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css" rel="stylesheet"> <script src="https://code.jquery.com/jquery-1.10.2.js"></script> <script src="https://code.jquery.com/ui/1.10.4/jquery-ui.js"> </script> <script> $(function () { $("#gfg").dialog({ autoOpen: false, }); $("#geeks").click(function () { $("#gfg").dialog("open"); }); }); </script></head> <body> <div id="gfg" title="GeeksforGeeks"> Jquery UI| open dialog method </div> <button id="geeks">Open Dialog</button></body> </html>
Output:
jQuery-UI
HTML
JQuery
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
REST API (Introduction)
Design a Tribute Page using HTML & CSS
Build a Survey Form using HTML and CSS
Angular File Upload
Design a web page using HTML and CSS
JQuery | Set the value of an input text field
How to change selected value of a drop-down list using jQuery?
Form validation using jQuery
How to add options to a select element using jQuery?
jQuery | children() with Examples | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n13 Jan, 2021"
},
{
"code": null,
"e": 111,
"s": 28,
"text": "open() Method is used to open the dialog. This method does not accept any argument"
},
{
"code": null,
"e": 119,
"s": 111,
"text": "Syntax:"
},
{
"code": null,
"e": 152,
"s": 119,
"text": "$( \".selector\" ).dialog(\"open\");"
},
{
"code": null,
"e": 216,
"s": 152,
"text": "Approach: First, add jQuery UI scripts needed for your project."
},
{
"code": null,
"e": 457,
"s": 216,
"text": "<link href = “https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css” rel = “stylesheet”><script src = “https://code.jquery.com/jquery-1.10.2.js”></script><script src = “https://code.jquery.com/ui/1.10.4/jquery-ui.js”></script>"
},
{
"code": null,
"e": 466,
"s": 457,
"text": "Example:"
},
{
"code": null,
"e": 471,
"s": 466,
"text": "HTML"
},
{
"code": "<!doctype html><html lang=\"en\"> <head> <meta charset=\"utf-8\"> <link href=\"https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css\" rel=\"stylesheet\"> <script src=\"https://code.jquery.com/jquery-1.10.2.js\"></script> <script src=\"https://code.jquery.com/ui/1.10.4/jquery-ui.js\"> </script> <script> $(function () { $(\"#gfg\").dialog({ autoOpen: false, }); $(\"#geeks\").click(function () { $(\"#gfg\").dialog(\"open\"); }); }); </script></head> <body> <div id=\"gfg\" title=\"GeeksforGeeks\"> Jquery UI| open dialog method </div> <button id=\"geeks\">Open Dialog</button></body> </html>",
"e": 1198,
"s": 471,
"text": null
},
{
"code": null,
"e": 1206,
"s": 1198,
"text": "Output:"
},
{
"code": null,
"e": 1216,
"s": 1206,
"text": "jQuery-UI"
},
{
"code": null,
"e": 1221,
"s": 1216,
"text": "HTML"
},
{
"code": null,
"e": 1228,
"s": 1221,
"text": "JQuery"
},
{
"code": null,
"e": 1245,
"s": 1228,
"text": "Web Technologies"
},
{
"code": null,
"e": 1250,
"s": 1245,
"text": "HTML"
},
{
"code": null,
"e": 1348,
"s": 1250,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1372,
"s": 1348,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 1411,
"s": 1372,
"text": "Design a Tribute Page using HTML & CSS"
},
{
"code": null,
"e": 1450,
"s": 1411,
"text": "Build a Survey Form using HTML and CSS"
},
{
"code": null,
"e": 1470,
"s": 1450,
"text": "Angular File Upload"
},
{
"code": null,
"e": 1507,
"s": 1470,
"text": "Design a web page using HTML and CSS"
},
{
"code": null,
"e": 1553,
"s": 1507,
"text": "JQuery | Set the value of an input text field"
},
{
"code": null,
"e": 1616,
"s": 1553,
"text": "How to change selected value of a drop-down list using jQuery?"
},
{
"code": null,
"e": 1645,
"s": 1616,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 1698,
"s": 1645,
"text": "How to add options to a select element using jQuery?"
}
] |
Top 10 Books That Every Programmer Must Read Once | 28 Feb, 2022
If we find a person with a rare intellect, we should ask him about the books he reads. A book can define a person’s nature and intelligence. If you are a coder, you should be also a good reader because it develops the mind and the mind is your weapon. you have to train it daily. Before finding any solution to a problem Reading and understanding the problems is the most important if you are a coder or any problem solver. Without good reading and comprehension skills, a person takes more time to understand the problems before solving it.
Below there is the list of top 10 books every programmer should read. These books not only teach the syntax and semantics of programming languages but also help you to think, organize, and become a good problem solver, which is indeed the most important lesson for a coder. These books are not only for mastering a particular programming language like C++, Java or Python but will help you to become a Better Programmer.
This is one of the best classic books for beginners and will teach you all tricks and patterns of writing good and clean code. Every code which runs is not a clean code. Most of the beginner programmer done this mistake, they just try to solve the problem and hence forgets these factors to write a clean and perfect professional code. A Clean Code should be properly readable, well structured so that it could be reused and debug easily.
Ideas Presented:
How to properly name a variable?
How to write a better method?
How to structure your code better?
What is the code smell?
Why another approach is better than this one?
According to many software developers in the world, this book is literally a Bible to them. This book will help you build a proper concept about software development, estimates, project management, and troubles in software development. The main theme of this book is “Brooks’ Law ” which says “adding manpower to a late software project makes it later”.
Ideas Presented:
The mythical man-month: measuring useful work in man-months is a myth,
Essence and Accidents of Software Engineering,
When working on a second system, you should keep in mind that you shouldn’t over-engineer it,
Any attempt to fix a errors can lead you to many new errors.
This is book is Andrew Hunt and David Thomas, about programming and software engineering. The unique feature of this book is it teaches us in a pragmatic way with a collection of tips to improve the programming and development process rather than the theoretical way. This book will help you to become a pragmatic programmer, an early adopter, to have fast adaptation, inquisitiveness and critical thinking, realism, and being a jack-of-all-trades. The book presents development methodologies and caveats, analogies and short stories too, for example, the broken windows theory, the story of the stone soup, or the boiling frog.
Ideas presented:
Present development methodologies and process using many analogies and short stories. e.g, the stone soup, or the story of the boiling frog
Many concepts were named which get popular for this book, such as code katas,
More use of methods for making and preserving codes highly adjustable,
Useful recommendations for estimates of time and expense
Introduces you to methods of work that you may not yet have considered.
If you are want to be a great software engineer you should read this book once. This book provides the most useful practical guides of programming and helping developers write better software for more than a decade. This book has the rare blend of classic and fully updated with revised leading-edge coding concepts and example. With these proper concepts, you can easily understand the art and science of software construction.
Ideas Represented:
Software craftsmanship, e.g, layout, style, character, themes and self-documentation
Coding, debugging, integration and testing for software development,
Other important software development aspects such as requirements and documentation,
The techniques of creating a high-quality code, code improvements and system considerations.
This is another classic book written by the famous computer scientist Professor Donald Knuth. This book is very popular and highly praised by many of the top programmers in the world for the combined mathematical exactness with an outstanding humour throughout the chapters. Through his well-known book series ‘art of computer programming’, for his major contributions to the analysis of algorithms, Knuth was awarded the Turing Award in 1974. The book begins with basic programming concepts and techniques, explores various programming algorithms and describes their analysis efficiently and then focuses particularly on the representation of information inside a computer(information structure).
Ideas Presented:
How to deal with the structural relationships between data elements efficiently,
How to solve problems effectively using the basic concepts of fundamental Algorithms,
Semi-numerical Algorithms and Combinatorial Algorithms
Minimum-Comparison Sorting or Optimum Sorting
This book is slightly different from the other classics books on the list but this book is one of the most influential books to helps a person think like a programmer. Every concept is properly covered with practical problems and various effective and efficient solutions. This is pleasant to read because the writing style is simply great.
This book may not a usual book of new programming concepts but it is the best practical programming book to practice and follow with clear cut examples. The book challenges your understanding of the core concepts in memory, CPU, and algorithms and gradually increment the difficulties rather than giving you the answer right away because the main motto of this book is to help you become a better problem solver. This book is the best place to practice problems of data structure and algorithms especially searching, sorting, heaps etc. It Is really a masterpiece created by Jon Bentley fully justifying the name “Programming Pearls”.
This book introduces us with “The Hidden Language of Computer Hardware and Software” in an outstanding way for anyone who’s ever wondered about the magic and secret inner life of computers and how the working of these complex system and other smart machines.
Nowadays the low-level details gets masked due to the level of abstractions but if you go through this book you can understand those awesome older technologies like Morse code, Braille, and Boolean logic, to understand vacuum tubes, transistors, and integrated circuits. Sometimes to solve a very complicated bug you have to drive deeper to the dead ends of the electronic, binary computer with a von Neumann architecture to reach a scalable solution. It also easily explained many recent developments topics, like floating-point arithmetic, operating systems, packet-based communication protocols, and GUIs.
This is the single famous book widely used as the textbook for understanding and using an algorithm by Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest, and Clifford Stein. With over 10, 000 citations documented on CiteSeerX, this book is commonly cited as a reference for algorithms in published papers. The book was also a bestseller programming book with half a million sold copies during its first 20 years.
Each chapter in this book covers a broad range of algorithms, its design techniques and areas of application in depth. Instead of a specific programming language, programming examples are written using pseudo code with rigor and comprehensiveness.
This book is written by y Martin Fowler is an essential book for software developers which offers start-to-finish strategies for working more effectively with large software and improving the design of existing code.
Refactoring is the process of rewriting codes, without changing the functionality, to improve the readability, testability, or maintainability of your code. If you are interested in improving and maintaining the quality of your code this book is for you which contains step by step instructions for implementation of more than 40 proven refactorings example illustrating with details as to when and why to use the refactoring. In the second edition of this classic book, it switched from Java to JavaScript for most of the examples but the ideas can be applied to any Object-oriented programming language. The book is well written, provides samples, examples, diagrams, steps to follow, side-notes, commentary, and basically everything you would need to fully understand a refactoring method.
This is hailed as one of the greatest software development books ever written, describing into great detail on the many different design patterns. It has been influential to the field of software engineering and was written by Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides, with a foreword by Grady Booch.
This book is a must-read for a budding architect or designer of a complex system. You will most likely be required to read this book to avoid and handle common problems that the industry faces. This book contains the in-detail description of the many different design patterns and regarded as an important source for object-oriented design theory and practice that have been developed over the years to help software engineers.
The authors discuss various things like the tension between inheritance and encapsulation, parameterized types, Supporting Multiple Look-And-Feel Standards, Embellishing the User Interface, Supporting Multiple Window Systems etc.
rkbhola5
GBlog
TechTips
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n28 Feb, 2022"
},
{
"code": null,
"e": 572,
"s": 28,
"text": "If we find a person with a rare intellect, we should ask him about the books he reads. A book can define a person’s nature and intelligence. If you are a coder, you should be also a good reader because it develops the mind and the mind is your weapon. you have to train it daily. Before finding any solution to a problem Reading and understanding the problems is the most important if you are a coder or any problem solver. Without good reading and comprehension skills, a person takes more time to understand the problems before solving it. "
},
{
"code": null,
"e": 996,
"s": 574,
"text": "Below there is the list of top 10 books every programmer should read. These books not only teach the syntax and semantics of programming languages but also help you to think, organize, and become a good problem solver, which is indeed the most important lesson for a coder. These books are not only for mastering a particular programming language like C++, Java or Python but will help you to become a Better Programmer. "
},
{
"code": null,
"e": 1436,
"s": 996,
"text": "This is one of the best classic books for beginners and will teach you all tricks and patterns of writing good and clean code. Every code which runs is not a clean code. Most of the beginner programmer done this mistake, they just try to solve the problem and hence forgets these factors to write a clean and perfect professional code. A Clean Code should be properly readable, well structured so that it could be reused and debug easily. "
},
{
"code": null,
"e": 1453,
"s": 1436,
"text": "Ideas Presented:"
},
{
"code": null,
"e": 1486,
"s": 1453,
"text": "How to properly name a variable?"
},
{
"code": null,
"e": 1516,
"s": 1486,
"text": "How to write a better method?"
},
{
"code": null,
"e": 1551,
"s": 1516,
"text": "How to structure your code better?"
},
{
"code": null,
"e": 1575,
"s": 1551,
"text": "What is the code smell?"
},
{
"code": null,
"e": 1621,
"s": 1575,
"text": "Why another approach is better than this one?"
},
{
"code": null,
"e": 1976,
"s": 1621,
"text": "According to many software developers in the world, this book is literally a Bible to them. This book will help you build a proper concept about software development, estimates, project management, and troubles in software development. The main theme of this book is “Brooks’ Law ” which says “adding manpower to a late software project makes it later”. "
},
{
"code": null,
"e": 1993,
"s": 1976,
"text": "Ideas Presented:"
},
{
"code": null,
"e": 2064,
"s": 1993,
"text": "The mythical man-month: measuring useful work in man-months is a myth,"
},
{
"code": null,
"e": 2111,
"s": 2064,
"text": "Essence and Accidents of Software Engineering,"
},
{
"code": null,
"e": 2205,
"s": 2111,
"text": "When working on a second system, you should keep in mind that you shouldn’t over-engineer it,"
},
{
"code": null,
"e": 2267,
"s": 2205,
"text": "Any attempt to fix a errors can lead you to many new errors. "
},
{
"code": null,
"e": 2896,
"s": 2267,
"text": "This is book is Andrew Hunt and David Thomas, about programming and software engineering. The unique feature of this book is it teaches us in a pragmatic way with a collection of tips to improve the programming and development process rather than the theoretical way. This book will help you to become a pragmatic programmer, an early adopter, to have fast adaptation, inquisitiveness and critical thinking, realism, and being a jack-of-all-trades. The book presents development methodologies and caveats, analogies and short stories too, for example, the broken windows theory, the story of the stone soup, or the boiling frog."
},
{
"code": null,
"e": 2913,
"s": 2896,
"text": "Ideas presented:"
},
{
"code": null,
"e": 3053,
"s": 2913,
"text": "Present development methodologies and process using many analogies and short stories. e.g, the stone soup, or the story of the boiling frog"
},
{
"code": null,
"e": 3131,
"s": 3053,
"text": "Many concepts were named which get popular for this book, such as code katas,"
},
{
"code": null,
"e": 3202,
"s": 3131,
"text": "More use of methods for making and preserving codes highly adjustable,"
},
{
"code": null,
"e": 3259,
"s": 3202,
"text": "Useful recommendations for estimates of time and expense"
},
{
"code": null,
"e": 3331,
"s": 3259,
"text": "Introduces you to methods of work that you may not yet have considered."
},
{
"code": null,
"e": 3761,
"s": 3331,
"text": "If you are want to be a great software engineer you should read this book once. This book provides the most useful practical guides of programming and helping developers write better software for more than a decade. This book has the rare blend of classic and fully updated with revised leading-edge coding concepts and example. With these proper concepts, you can easily understand the art and science of software construction. "
},
{
"code": null,
"e": 3781,
"s": 3761,
"text": "Ideas Represented: "
},
{
"code": null,
"e": 3866,
"s": 3781,
"text": "Software craftsmanship, e.g, layout, style, character, themes and self-documentation"
},
{
"code": null,
"e": 3935,
"s": 3866,
"text": "Coding, debugging, integration and testing for software development,"
},
{
"code": null,
"e": 4020,
"s": 3935,
"text": "Other important software development aspects such as requirements and documentation,"
},
{
"code": null,
"e": 4113,
"s": 4020,
"text": "The techniques of creating a high-quality code, code improvements and system considerations."
},
{
"code": null,
"e": 4813,
"s": 4113,
"text": "This is another classic book written by the famous computer scientist Professor Donald Knuth. This book is very popular and highly praised by many of the top programmers in the world for the combined mathematical exactness with an outstanding humour throughout the chapters. Through his well-known book series ‘art of computer programming’, for his major contributions to the analysis of algorithms, Knuth was awarded the Turing Award in 1974. The book begins with basic programming concepts and techniques, explores various programming algorithms and describes their analysis efficiently and then focuses particularly on the representation of information inside a computer(information structure). "
},
{
"code": null,
"e": 4831,
"s": 4813,
"text": "Ideas Presented: "
},
{
"code": null,
"e": 4912,
"s": 4831,
"text": "How to deal with the structural relationships between data elements efficiently,"
},
{
"code": null,
"e": 4998,
"s": 4912,
"text": "How to solve problems effectively using the basic concepts of fundamental Algorithms,"
},
{
"code": null,
"e": 5053,
"s": 4998,
"text": "Semi-numerical Algorithms and Combinatorial Algorithms"
},
{
"code": null,
"e": 5099,
"s": 5053,
"text": "Minimum-Comparison Sorting or Optimum Sorting"
},
{
"code": null,
"e": 5441,
"s": 5099,
"text": "This book is slightly different from the other classics books on the list but this book is one of the most influential books to helps a person think like a programmer. Every concept is properly covered with practical problems and various effective and efficient solutions. This is pleasant to read because the writing style is simply great. "
},
{
"code": null,
"e": 6077,
"s": 5441,
"text": "This book may not a usual book of new programming concepts but it is the best practical programming book to practice and follow with clear cut examples. The book challenges your understanding of the core concepts in memory, CPU, and algorithms and gradually increment the difficulties rather than giving you the answer right away because the main motto of this book is to help you become a better problem solver. This book is the best place to practice problems of data structure and algorithms especially searching, sorting, heaps etc. It Is really a masterpiece created by Jon Bentley fully justifying the name “Programming Pearls”. "
},
{
"code": null,
"e": 6337,
"s": 6077,
"text": "This book introduces us with “The Hidden Language of Computer Hardware and Software” in an outstanding way for anyone who’s ever wondered about the magic and secret inner life of computers and how the working of these complex system and other smart machines. "
},
{
"code": null,
"e": 6948,
"s": 6337,
"text": "Nowadays the low-level details gets masked due to the level of abstractions but if you go through this book you can understand those awesome older technologies like Morse code, Braille, and Boolean logic, to understand vacuum tubes, transistors, and integrated circuits. Sometimes to solve a very complicated bug you have to drive deeper to the dead ends of the electronic, binary computer with a von Neumann architecture to reach a scalable solution. It also easily explained many recent developments topics, like floating-point arithmetic, operating systems, packet-based communication protocols, and GUIs. "
},
{
"code": null,
"e": 7369,
"s": 6948,
"text": "This is the single famous book widely used as the textbook for understanding and using an algorithm by Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest, and Clifford Stein. With over 10, 000 citations documented on CiteSeerX, this book is commonly cited as a reference for algorithms in published papers. The book was also a bestseller programming book with half a million sold copies during its first 20 years. "
},
{
"code": null,
"e": 7619,
"s": 7369,
"text": "Each chapter in this book covers a broad range of algorithms, its design techniques and areas of application in depth. Instead of a specific programming language, programming examples are written using pseudo code with rigor and comprehensiveness. "
},
{
"code": null,
"e": 7837,
"s": 7619,
"text": "This book is written by y Martin Fowler is an essential book for software developers which offers start-to-finish strategies for working more effectively with large software and improving the design of existing code. "
},
{
"code": null,
"e": 8632,
"s": 7837,
"text": "Refactoring is the process of rewriting codes, without changing the functionality, to improve the readability, testability, or maintainability of your code. If you are interested in improving and maintaining the quality of your code this book is for you which contains step by step instructions for implementation of more than 40 proven refactorings example illustrating with details as to when and why to use the refactoring. In the second edition of this classic book, it switched from Java to JavaScript for most of the examples but the ideas can be applied to any Object-oriented programming language. The book is well written, provides samples, examples, diagrams, steps to follow, side-notes, commentary, and basically everything you would need to fully understand a refactoring method. "
},
{
"code": null,
"e": 8955,
"s": 8632,
"text": "This is hailed as one of the greatest software development books ever written, describing into great detail on the many different design patterns. It has been influential to the field of software engineering and was written by Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides, with a foreword by Grady Booch. "
},
{
"code": null,
"e": 9385,
"s": 8955,
"text": "This book is a must-read for a budding architect or designer of a complex system. You will most likely be required to read this book to avoid and handle common problems that the industry faces. This book contains the in-detail description of the many different design patterns and regarded as an important source for object-oriented design theory and practice that have been developed over the years to help software engineers. "
},
{
"code": null,
"e": 9616,
"s": 9385,
"text": "The authors discuss various things like the tension between inheritance and encapsulation, parameterized types, Supporting Multiple Look-And-Feel Standards, Embellishing the User Interface, Supporting Multiple Window Systems etc. "
},
{
"code": null,
"e": 9625,
"s": 9616,
"text": "rkbhola5"
},
{
"code": null,
"e": 9631,
"s": 9625,
"text": "GBlog"
},
{
"code": null,
"e": 9640,
"s": 9631,
"text": "TechTips"
}
] |
Variable Arguments (Varargs) in C# | Use the param keyword to get the variable arguments in C#.
Let us see an example to multiply integers. We have used params keyword to accept any number of int values −
static int Multiply(params int[] b)
The above allows us to find multiplication of numbers with one as well as two int values. The fllowing calls the same function with multiple values −
int mulVal1 = Multiply(5);
int mulVal2 = Multiply(5, 10);
Let us see the complete code to understand how variable arguments work in C# −
using System;
class Program {
static void Main() {
int mulVal1 = Multiply(5);
int mulVal2 = Multiply(5, 10);
Console.WriteLine(mulVal1);
Console.WriteLine(mulVal2);
}
static int Multiply(params int[] b) {
int mul =1;
foreach (int a in b) {
mul = mul*a;
}
return mul;
}
} | [
{
"code": null,
"e": 1246,
"s": 1187,
"text": "Use the param keyword to get the variable arguments in C#."
},
{
"code": null,
"e": 1355,
"s": 1246,
"text": "Let us see an example to multiply integers. We have used params keyword to accept any number of int values −"
},
{
"code": null,
"e": 1391,
"s": 1355,
"text": "static int Multiply(params int[] b)"
},
{
"code": null,
"e": 1541,
"s": 1391,
"text": "The above allows us to find multiplication of numbers with one as well as two int values. The fllowing calls the same function with multiple values −"
},
{
"code": null,
"e": 1599,
"s": 1541,
"text": "int mulVal1 = Multiply(5);\nint mulVal2 = Multiply(5, 10);"
},
{
"code": null,
"e": 1678,
"s": 1599,
"text": "Let us see the complete code to understand how variable arguments work in C# −"
},
{
"code": null,
"e": 2021,
"s": 1678,
"text": "using System;\n\nclass Program {\n static void Main() {\n int mulVal1 = Multiply(5);\n int mulVal2 = Multiply(5, 10);\n\n Console.WriteLine(mulVal1);\n Console.WriteLine(mulVal2);\n }\n\n static int Multiply(params int[] b) {\n int mul =1;\n foreach (int a in b) {\n mul = mul*a;\n }\n return mul;\n }\n}"
}
] |
What is Local Host? | 02 Nov, 2021
When you call an IP address on your computer, you try to contact another computer on the internet but when you call the IP address 127.0.0.1 then you are communicating with the local host. Localhost is always your own computer. Your computer is talking to itself when you call the local host. Your computer does not always directly identify the local host. Within your personal network localhost has a separate IP address like 192.168.0.1. (for most cases) which is different from the one you use on the internet. This is usually dynamically assigned by the internet service provider (ISP). Localhost can be seen as a server that is used on your own computer.
This term is generally used in the context of networks. Localhost is not just the name for the virtual server but it is also its domain name. Just like .example, .test, or .invalid, ., .localhost is a top-level domain reserved for documentation and testing purposes. While accessing the domain, a loopback is triggered. If you access “http://localhost” in the browser, the request will not be forwarded to the internet through the router. It will instead remain in your own system. Localhost has the IP address 127.0.0.1. This refers back to your own server.
127.0.0.1 – how does loopback work? To communicate with each other within a network IP addresses are used. The participants in the network have their own unique addresses. Using TCP/IP data packets are able to reach the correct destination. The protocol pair Transmission Control Protocol (TCP) and Internet Protocol (IP) are some of the main features of the internet. TCP/IP is also used outside of the internet in local networks. The Internet Protocol is responsible for allowing the IP address and subnet mask to address subscribers in a network during the transmission.
The allocation of public IP addresses is regulated by an international organization which is the Internet Corporation for Assigned Names and Numbers (ICANN). ICANN is also responsible for the allocation of domain names called the Domain Name System (DNS). But certain address ranges are reserved for special purposes, like the range from 127.0.0.0 to 127.255.255.255. There is no reliable information on why that range was chosen. IP addresses on the internet are divided into different classes. The first class Class A started with 0.0.0.0 (reserved address) and ended with 127.255.255.255. 127 is the last block of the Class A network. Its important position could have been the reason for its selection.
Within this address range, a Localnet can be set up. The special thing about this range is that IP addresses are not uniquely assigned in it, as is usually the case. Also, it was reserved by ICANN.
If you enter an IP address or corresponding domain name in your browser, the router forwards your request to the internet which connects you to the server. This means that if you enter 172.217.0.0, you will reach the Google homepage but the situation is different with 127.0.0.1. The requests to this address will not be forwarded to the internet. TCP/IP recognizes from the first block (127) that you don’t want to access the internet, you are calling yourself instead. This then triggers the loopback.
The reason why a loopback device is created is so that the backlink to your own computer works. Through the operating system, this is a virtual interface that is created. The interface is called lo or lo0 and can also be displayed using the ifconfig command in Unix systems. A similar command for Windows is ipconfig.
What is localhost used for? Developers use the local host to test web applications and programs. Network administrators use the loopback to test network connections. Another use for the localhost is the host’s file, where you can use the loopback to block malicious websites.
For Testing Purposes – Web servers mainly use the local host for the programming applications that need to communicate over the internet. During development, it is important to find out whether the application actually works as developed once it has internet access. Localhosts’ other functions are only possible if the required files can be found on the internet. As we can see that there is a difference between opening an HTML document on your PC or loading it onto a server and accessing it. Releasing a product without testing it doesn’t make sense. So loopback is used by developers to test them. They can stimulate a connection while also avoiding network errors. The connection just stays completely inside their own system.
Another advantage of using localhost for testing purposes is the speed. Usually, more than 100 milliseconds are taken when you send a request over the internet. The maximum transmission time is just one millisecond for sending a ping to localhost. The correctness of the internet protocol can also be implemented using this technology.
If you want to set up your own test server on your PC to address it through the local host, the right software is needed. Softwares such as XAMPP specifically designed for use as localhost can be used.
To block websites – Localhost can also block the host’s files. This file is a predecessor of the Domain Name System (DNS). In this IP addresses can be assigned to the corresponding domains. The domain name is translated into an IP address when you enter a website address in the browser. It used to be the host file, but today usually the global DNS is used but the host file is still present in most operating systems. In Windows, the file is found under \system32\drivers\etc\hosts whereas, with macOS and other Unix systems, it is found under /etc/hosts.
There are probably these two entries left if there are no file changes done:
127.0.0.1 localhost
::1 localhost
The name resolution for the localhost need not have to be done over the internet. Localhost can also use the host file to block certain websites. For this, the website to be blocked must be entered into the list and the IP address 127.0.0.1 must be assigned to the domain. If you or a malicious script try to call up the locked domain, the browser will check the host’s file first and will find your entry there. The domain name 0.0.0.0 can also be used.
The browser will then try to access the corresponding website on the server with 127.0.0.1. However, it is unlikely that the browser will be able to locate it, as the requested file will not be there. However, if your own test server is set up, then the browser may find home.html, which is just your own file. An error message appears instead of the requested website if you have not set up your own test server. Ad inserts throughout the system can be switched off using this technology. To avoid every entry manually, you can find finished and regularly extended host files on the Internet.
pall58183
karthiksrinivasprasad
Pushpender007
23603vaibhav2021
Computer Networks-Network Layer
Computer Networks
Computer Networks
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GSM in Wireless Communication
Socket Programming in Python
Differences between IPv4 and IPv6
Secure Socket Layer (SSL)
Wireless Application Protocol
Mobile Internet Protocol (or Mobile IP)
UDP Server-Client implementation in C
Caesar Cipher in Cryptography
Advanced Encryption Standard (AES) | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n02 Nov, 2021"
},
{
"code": null,
"e": 713,
"s": 52,
"text": "When you call an IP address on your computer, you try to contact another computer on the internet but when you call the IP address 127.0.0.1 then you are communicating with the local host. Localhost is always your own computer. Your computer is talking to itself when you call the local host. Your computer does not always directly identify the local host. Within your personal network localhost has a separate IP address like 192.168.0.1. (for most cases) which is different from the one you use on the internet. This is usually dynamically assigned by the internet service provider (ISP). Localhost can be seen as a server that is used on your own computer. "
},
{
"code": null,
"e": 1273,
"s": 713,
"text": "This term is generally used in the context of networks. Localhost is not just the name for the virtual server but it is also its domain name. Just like .example, .test, or .invalid, ., .localhost is a top-level domain reserved for documentation and testing purposes. While accessing the domain, a loopback is triggered. If you access “http://localhost” in the browser, the request will not be forwarded to the internet through the router. It will instead remain in your own system. Localhost has the IP address 127.0.0.1. This refers back to your own server. "
},
{
"code": null,
"e": 1848,
"s": 1273,
"text": "127.0.0.1 – how does loopback work? To communicate with each other within a network IP addresses are used. The participants in the network have their own unique addresses. Using TCP/IP data packets are able to reach the correct destination. The protocol pair Transmission Control Protocol (TCP) and Internet Protocol (IP) are some of the main features of the internet. TCP/IP is also used outside of the internet in local networks. The Internet Protocol is responsible for allowing the IP address and subnet mask to address subscribers in a network during the transmission. "
},
{
"code": null,
"e": 2556,
"s": 1848,
"text": "The allocation of public IP addresses is regulated by an international organization which is the Internet Corporation for Assigned Names and Numbers (ICANN). ICANN is also responsible for the allocation of domain names called the Domain Name System (DNS). But certain address ranges are reserved for special purposes, like the range from 127.0.0.0 to 127.255.255.255. There is no reliable information on why that range was chosen. IP addresses on the internet are divided into different classes. The first class Class A started with 0.0.0.0 (reserved address) and ended with 127.255.255.255. 127 is the last block of the Class A network. Its important position could have been the reason for its selection. "
},
{
"code": null,
"e": 2755,
"s": 2556,
"text": "Within this address range, a Localnet can be set up. The special thing about this range is that IP addresses are not uniquely assigned in it, as is usually the case. Also, it was reserved by ICANN. "
},
{
"code": null,
"e": 3260,
"s": 2755,
"text": "If you enter an IP address or corresponding domain name in your browser, the router forwards your request to the internet which connects you to the server. This means that if you enter 172.217.0.0, you will reach the Google homepage but the situation is different with 127.0.0.1. The requests to this address will not be forwarded to the internet. TCP/IP recognizes from the first block (127) that you don’t want to access the internet, you are calling yourself instead. This then triggers the loopback. "
},
{
"code": null,
"e": 3579,
"s": 3260,
"text": "The reason why a loopback device is created is so that the backlink to your own computer works. Through the operating system, this is a virtual interface that is created. The interface is called lo or lo0 and can also be displayed using the ifconfig command in Unix systems. A similar command for Windows is ipconfig. "
},
{
"code": null,
"e": 3856,
"s": 3579,
"text": "What is localhost used for? Developers use the local host to test web applications and programs. Network administrators use the loopback to test network connections. Another use for the localhost is the host’s file, where you can use the loopback to block malicious websites. "
},
{
"code": null,
"e": 4590,
"s": 3856,
"text": "For Testing Purposes – Web servers mainly use the local host for the programming applications that need to communicate over the internet. During development, it is important to find out whether the application actually works as developed once it has internet access. Localhosts’ other functions are only possible if the required files can be found on the internet. As we can see that there is a difference between opening an HTML document on your PC or loading it onto a server and accessing it. Releasing a product without testing it doesn’t make sense. So loopback is used by developers to test them. They can stimulate a connection while also avoiding network errors. The connection just stays completely inside their own system. "
},
{
"code": null,
"e": 4927,
"s": 4590,
"text": "Another advantage of using localhost for testing purposes is the speed. Usually, more than 100 milliseconds are taken when you send a request over the internet. The maximum transmission time is just one millisecond for sending a ping to localhost. The correctness of the internet protocol can also be implemented using this technology. "
},
{
"code": null,
"e": 5130,
"s": 4927,
"text": "If you want to set up your own test server on your PC to address it through the local host, the right software is needed. Softwares such as XAMPP specifically designed for use as localhost can be used. "
},
{
"code": null,
"e": 5689,
"s": 5130,
"text": "To block websites – Localhost can also block the host’s files. This file is a predecessor of the Domain Name System (DNS). In this IP addresses can be assigned to the corresponding domains. The domain name is translated into an IP address when you enter a website address in the browser. It used to be the host file, but today usually the global DNS is used but the host file is still present in most operating systems. In Windows, the file is found under \\system32\\drivers\\etc\\hosts whereas, with macOS and other Unix systems, it is found under /etc/hosts. "
},
{
"code": null,
"e": 5767,
"s": 5689,
"text": "There are probably these two entries left if there are no file changes done: "
},
{
"code": null,
"e": 5825,
"s": 5769,
"text": " 127.0.0.1 localhost\n\n ::1 localhost "
},
{
"code": null,
"e": 6281,
"s": 5825,
"text": "The name resolution for the localhost need not have to be done over the internet. Localhost can also use the host file to block certain websites. For this, the website to be blocked must be entered into the list and the IP address 127.0.0.1 must be assigned to the domain. If you or a malicious script try to call up the locked domain, the browser will check the host’s file first and will find your entry there. The domain name 0.0.0.0 can also be used. "
},
{
"code": null,
"e": 6876,
"s": 6281,
"text": "The browser will then try to access the corresponding website on the server with 127.0.0.1. However, it is unlikely that the browser will be able to locate it, as the requested file will not be there. However, if your own test server is set up, then the browser may find home.html, which is just your own file. An error message appears instead of the requested website if you have not set up your own test server. Ad inserts throughout the system can be switched off using this technology. To avoid every entry manually, you can find finished and regularly extended host files on the Internet. "
},
{
"code": null,
"e": 6886,
"s": 6876,
"text": "pall58183"
},
{
"code": null,
"e": 6908,
"s": 6886,
"text": "karthiksrinivasprasad"
},
{
"code": null,
"e": 6922,
"s": 6908,
"text": "Pushpender007"
},
{
"code": null,
"e": 6939,
"s": 6922,
"text": "23603vaibhav2021"
},
{
"code": null,
"e": 6971,
"s": 6939,
"text": "Computer Networks-Network Layer"
},
{
"code": null,
"e": 6989,
"s": 6971,
"text": "Computer Networks"
},
{
"code": null,
"e": 7007,
"s": 6989,
"text": "Computer Networks"
},
{
"code": null,
"e": 7105,
"s": 7007,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 7135,
"s": 7105,
"text": "GSM in Wireless Communication"
},
{
"code": null,
"e": 7164,
"s": 7135,
"text": "Socket Programming in Python"
},
{
"code": null,
"e": 7198,
"s": 7164,
"text": "Differences between IPv4 and IPv6"
},
{
"code": null,
"e": 7224,
"s": 7198,
"text": "Secure Socket Layer (SSL)"
},
{
"code": null,
"e": 7254,
"s": 7224,
"text": "Wireless Application Protocol"
},
{
"code": null,
"e": 7294,
"s": 7254,
"text": "Mobile Internet Protocol (or Mobile IP)"
},
{
"code": null,
"e": 7332,
"s": 7294,
"text": "UDP Server-Client implementation in C"
},
{
"code": null,
"e": 7362,
"s": 7332,
"text": "Caesar Cipher in Cryptography"
}
] |
Machine Learning - Performance Metrics | There are various metrics which we can use to evaluate the performance of ML algorithms, classification as well as regression algorithms. We must carefully choose the metrics for evaluating ML performance because −
How the performance of ML algorithms is measured and compared will be dependent entirely on the metric you choose.
How the performance of ML algorithms is measured and compared will be dependent entirely on the metric you choose.
How you weight the importance of various characteristics in the result will be influenced completely by the metric you choose.
How you weight the importance of various characteristics in the result will be influenced completely by the metric you choose.
We have discussed classification and its algorithms in the previous chapters. Here, we are going to discuss various performance metrics that can be used to evaluate predictions for classification problems.
It is the easiest way to measure the performance of a classification problem where the output can be of two or more type of classes. A confusion matrix is nothing but a table with two dimensions viz. “Actual” and “Predicted” and furthermore, both the dimensions have “True Positives (TP)”, “True Negatives (TN)”, “False Positives (FP)”, “False Negatives (FN)” as shown below −
Explanation of the terms associated with confusion matrix are as follows −
True Positives (TP) − It is the case when both actual class & predicted class of data point is 1.
True Positives (TP) − It is the case when both actual class & predicted class of data point is 1.
True Negatives (TN) − It is the case when both actual class & predicted class of data point is 0.
True Negatives (TN) − It is the case when both actual class & predicted class of data point is 0.
False Positives (FP) − It is the case when actual class of data point is 0 & predicted class of data point is 1.
False Positives (FP) − It is the case when actual class of data point is 0 & predicted class of data point is 1.
False Negatives (FN) − It is the case when actual class of data point is 1 & predicted class of data point is 0.
False Negatives (FN) − It is the case when actual class of data point is 1 & predicted class of data point is 0.
We can use confusion_matrix function of sklearn.metrics to compute Confusion Matrix of our classification model.
It is most common performance metric for classification algorithms. It may be defined as the number of correct predictions made as a ratio of all predictions made. We can easily calculate it by confusion matrix with the help of following formula −
We can use accuracy_score function of sklearn.metrics to compute accuracy of our classification model.
This report consists of the scores of Precisions, Recall, F1 and Support. They are explained as follows −
Precision, used in document retrievals, may be defined as the number of correct documents returned by our ML model. We can easily calculate it by confusion matrix with the help of following formula −
Recall may be defined as the number of positives returned by our ML model. We can easily calculate it by confusion matrix with the help of following formula −
Specificity, in contrast to recall, may be defined as the number of negatives returned by our ML model. We can easily calculate it by confusion matrix with the help of following formula −
Support may be defined as the number of samples of the true response that lies in each class of target values.
This score will give us the harmonic mean of precision and recall. Mathematically, F1 score is the weighted average of the precision and recall. The best value of F1 would be 1 and worst would be 0. We can calculate F1 score with the help of following formula −
F1 = 2 ∗ (precision ∗ recall) / (precision + recall)
F1 score is having equal relative contribution of precision and recall.
We can use classification_report function of sklearn.metrics to get the classification report of our classification model.
AUC (Area Under Curve)-ROC (Receiver Operating Characteristic) is a performance metric, based on varying threshold values, for classification problems. As name suggests, ROC is a probability curve and AUC measure the separability. In simple words, AUC-ROC metric will tell us about the capability of model in distinguishing the classes. Higher the AUC, better the model.
Mathematically, it can be created by plotting TPR (True Positive Rate) i.e. Sensitivity or recall vs FPR (False Positive Rate) i.e. 1-Specificity, at various threshold values. Following is the graph showing ROC, AUC having TPR at y-axis and FPR at x-axis −
We can use roc_auc_score function of sklearn.metrics to compute AUC-ROC.
It is also called Logistic regression loss or cross-entropy loss. It basically defined on probability estimates and measures the performance of a classification model where the input is a probability value between 0 and 1. It can be understood more clearly by differentiating it with accuracy. As we know that accuracy is the count of predictions (predicted value = actual value) in our model whereas Log Loss is the amount of uncertainty of our prediction based on how much it varies from the actual label. With the help of Log Loss value, we can have more accurate view of the performance of our model. We can use log_loss function of sklearn.metrics to compute Log Loss.
The following is a simple recipe in Python which will give us an insight about how we can use the above explained performance metrics on binary classification model −
from sklearn.metrics import confusion_matrix
from sklearn.metrics import accuracy_score
from sklearn.metrics import classification_report
from sklearn.metrics import roc_auc_score
from sklearn.metrics import log_loss
X_actual = [1, 1, 0, 1, 0, 0, 1, 0, 0, 0]
Y_predic = [1, 0, 1, 1, 1, 0, 1, 1, 0, 0]
results = confusion_matrix(X_actual, Y_predic)
print ('Confusion Matrix :')
print(results)
print ('Accuracy Score is',accuracy_score(X_actual, Y_predic))
print ('Classification Report : ')
print (classification_report(X_actual, Y_predic))
print('AUC-ROC:',roc_auc_score(X_actual, Y_predic))
print('LOGLOSS Value is',log_loss(X_actual, Y_predic))
Confusion Matrix :
[
[3 3]
[1 3]
]
Accuracy Score is 0.6
Classification Report :
precision recall f1-score support
0 0.75 0.50 0.60 6
1 0.50 0.75 0.60 4
micro avg 0.60 0.60 0.60 10
macro avg 0.62 0.62 0.60 10
weighted avg 0.65 0.60 0.60 10
AUC-ROC: 0.625
LOGLOSS Value is 13.815750437193334
We have discussed regression and its algorithms in previous chapters. Here, we are going to discuss various performance metrics that can be used to evaluate predictions for regression problems.
It is the simplest error metric used in regression problems. It is basically the sum of average of the absolute difference between the predicted and actual values. In simple words, with MAE, we can get an idea of how wrong the predictions were. MAE does not indicate the direction of the model i.e. no indication about underperformance or overperformance of the model. The following is the formula to calculate MAE −
Here, Y=Actual Output Values
And Y^= Predicted Output Values.
We can use mean_absolute_error function of sklearn.metrics to compute MAE.
MSE is like the MAE, but the only difference is that the it squares the difference of actual and predicted output values before summing them all instead of using the absolute value. The difference can be noticed in the following equation −
Here, Y=Actual Output Values
And Y^ = Predicted Output Values.
We can use mean_squared_error function of sklearn.metrics to compute MSE.
R Squared metric is generally used for explanatory purpose and provides an indication of the goodness or fit of a set of predicted output values to the actual output values. The following formula will help us understanding it −
In the above equation, numerator is MSE and the denominator is the variance in Y values.
We can use r2_score function of sklearn.metrics to compute R squared value.
The following is a simple recipe in Python which will give us an insight about how we can use the above explained performance metrics on regression model −
from sklearn.metrics import r2_score
from sklearn.metrics import mean_absolute_error
from sklearn.metrics import mean_squared_error
X_actual = [5, -1, 2, 10]
Y_predic = [3.5, -0.9, 2, 9.9]
print ('R Squared =',r2_score(X_actual, Y_predic))
print ('MAE =',mean_absolute_error(X_actual, Y_predic))
print ('MSE =',mean_squared_error(X_actual, Y_predic))
R Squared = 0.9656060606060606
MAE = 0.42499999999999993
MSE = 0.5674999999999999
168 Lectures
13.5 hours
Er. Himanshu Vasishta
64 Lectures
10.5 hours
Eduonix Learning Solutions
91 Lectures
10 hours
Abhilash Nelson
54 Lectures
6 hours
Abhishek And Pukhraj
49 Lectures
5 hours
Abhishek And Pukhraj
35 Lectures
4 hours
Abhishek And Pukhraj
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2519,
"s": 2304,
"text": "There are various metrics which we can use to evaluate the performance of ML algorithms, classification as well as regression algorithms. We must carefully choose the metrics for evaluating ML performance because −"
},
{
"code": null,
"e": 2634,
"s": 2519,
"text": "How the performance of ML algorithms is measured and compared will be dependent entirely on the metric you choose."
},
{
"code": null,
"e": 2749,
"s": 2634,
"text": "How the performance of ML algorithms is measured and compared will be dependent entirely on the metric you choose."
},
{
"code": null,
"e": 2876,
"s": 2749,
"text": "How you weight the importance of various characteristics in the result will be influenced completely by the metric you choose."
},
{
"code": null,
"e": 3003,
"s": 2876,
"text": "How you weight the importance of various characteristics in the result will be influenced completely by the metric you choose."
},
{
"code": null,
"e": 3209,
"s": 3003,
"text": "We have discussed classification and its algorithms in the previous chapters. Here, we are going to discuss various performance metrics that can be used to evaluate predictions for classification problems."
},
{
"code": null,
"e": 3586,
"s": 3209,
"text": "It is the easiest way to measure the performance of a classification problem where the output can be of two or more type of classes. A confusion matrix is nothing but a table with two dimensions viz. “Actual” and “Predicted” and furthermore, both the dimensions have “True Positives (TP)”, “True Negatives (TN)”, “False Positives (FP)”, “False Negatives (FN)” as shown below −"
},
{
"code": null,
"e": 3661,
"s": 3586,
"text": "Explanation of the terms associated with confusion matrix are as follows −"
},
{
"code": null,
"e": 3759,
"s": 3661,
"text": "True Positives (TP) − It is the case when both actual class & predicted class of data point is 1."
},
{
"code": null,
"e": 3857,
"s": 3759,
"text": "True Positives (TP) − It is the case when both actual class & predicted class of data point is 1."
},
{
"code": null,
"e": 3955,
"s": 3857,
"text": "True Negatives (TN) − It is the case when both actual class & predicted class of data point is 0."
},
{
"code": null,
"e": 4053,
"s": 3955,
"text": "True Negatives (TN) − It is the case when both actual class & predicted class of data point is 0."
},
{
"code": null,
"e": 4166,
"s": 4053,
"text": "False Positives (FP) − It is the case when actual class of data point is 0 & predicted class of data point is 1."
},
{
"code": null,
"e": 4279,
"s": 4166,
"text": "False Positives (FP) − It is the case when actual class of data point is 0 & predicted class of data point is 1."
},
{
"code": null,
"e": 4392,
"s": 4279,
"text": "False Negatives (FN) − It is the case when actual class of data point is 1 & predicted class of data point is 0."
},
{
"code": null,
"e": 4505,
"s": 4392,
"text": "False Negatives (FN) − It is the case when actual class of data point is 1 & predicted class of data point is 0."
},
{
"code": null,
"e": 4618,
"s": 4505,
"text": "We can use confusion_matrix function of sklearn.metrics to compute Confusion Matrix of our classification model."
},
{
"code": null,
"e": 4866,
"s": 4618,
"text": "It is most common performance metric for classification algorithms. It may be defined as the number of correct predictions made as a ratio of all predictions made. We can easily calculate it by confusion matrix with the help of following formula −"
},
{
"code": null,
"e": 4969,
"s": 4866,
"text": "We can use accuracy_score function of sklearn.metrics to compute accuracy of our classification model."
},
{
"code": null,
"e": 5075,
"s": 4969,
"text": "This report consists of the scores of Precisions, Recall, F1 and Support. They are explained as follows −"
},
{
"code": null,
"e": 5275,
"s": 5075,
"text": "Precision, used in document retrievals, may be defined as the number of correct documents returned by our ML model. We can easily calculate it by confusion matrix with the help of following formula −"
},
{
"code": null,
"e": 5434,
"s": 5275,
"text": "Recall may be defined as the number of positives returned by our ML model. We can easily calculate it by confusion matrix with the help of following formula −"
},
{
"code": null,
"e": 5622,
"s": 5434,
"text": "Specificity, in contrast to recall, may be defined as the number of negatives returned by our ML model. We can easily calculate it by confusion matrix with the help of following formula −"
},
{
"code": null,
"e": 5733,
"s": 5622,
"text": "Support may be defined as the number of samples of the true response that lies in each class of target values."
},
{
"code": null,
"e": 5995,
"s": 5733,
"text": "This score will give us the harmonic mean of precision and recall. Mathematically, F1 score is the weighted average of the precision and recall. The best value of F1 would be 1 and worst would be 0. We can calculate F1 score with the help of following formula −"
},
{
"code": null,
"e": 6048,
"s": 5995,
"text": "F1 = 2 ∗ (precision ∗ recall) / (precision + recall)"
},
{
"code": null,
"e": 6120,
"s": 6048,
"text": "F1 score is having equal relative contribution of precision and recall."
},
{
"code": null,
"e": 6243,
"s": 6120,
"text": "We can use classification_report function of sklearn.metrics to get the classification report of our classification model."
},
{
"code": null,
"e": 6614,
"s": 6243,
"text": "AUC (Area Under Curve)-ROC (Receiver Operating Characteristic) is a performance metric, based on varying threshold values, for classification problems. As name suggests, ROC is a probability curve and AUC measure the separability. In simple words, AUC-ROC metric will tell us about the capability of model in distinguishing the classes. Higher the AUC, better the model."
},
{
"code": null,
"e": 6871,
"s": 6614,
"text": "Mathematically, it can be created by plotting TPR (True Positive Rate) i.e. Sensitivity or recall vs FPR (False Positive Rate) i.e. 1-Specificity, at various threshold values. Following is the graph showing ROC, AUC having TPR at y-axis and FPR at x-axis −"
},
{
"code": null,
"e": 6944,
"s": 6871,
"text": "We can use roc_auc_score function of sklearn.metrics to compute AUC-ROC."
},
{
"code": null,
"e": 7618,
"s": 6944,
"text": "It is also called Logistic regression loss or cross-entropy loss. It basically defined on probability estimates and measures the performance of a classification model where the input is a probability value between 0 and 1. It can be understood more clearly by differentiating it with accuracy. As we know that accuracy is the count of predictions (predicted value = actual value) in our model whereas Log Loss is the amount of uncertainty of our prediction based on how much it varies from the actual label. With the help of Log Loss value, we can have more accurate view of the performance of our model. We can use log_loss function of sklearn.metrics to compute Log Loss."
},
{
"code": null,
"e": 7785,
"s": 7618,
"text": "The following is a simple recipe in Python which will give us an insight about how we can use the above explained performance metrics on binary classification model −"
},
{
"code": null,
"e": 8432,
"s": 7785,
"text": "from sklearn.metrics import confusion_matrix\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.metrics import classification_report\nfrom sklearn.metrics import roc_auc_score\nfrom sklearn.metrics import log_loss\nX_actual = [1, 1, 0, 1, 0, 0, 1, 0, 0, 0]\nY_predic = [1, 0, 1, 1, 1, 0, 1, 1, 0, 0]\nresults = confusion_matrix(X_actual, Y_predic)\nprint ('Confusion Matrix :')\nprint(results)\nprint ('Accuracy Score is',accuracy_score(X_actual, Y_predic))\nprint ('Classification Report : ')\nprint (classification_report(X_actual, Y_predic))\nprint('AUC-ROC:',roc_auc_score(X_actual, Y_predic))\nprint('LOGLOSS Value is',log_loss(X_actual, Y_predic))"
},
{
"code": null,
"e": 8912,
"s": 8432,
"text": "Confusion Matrix :\n[\n [3 3]\n [1 3]\n]\nAccuracy Score is 0.6\nClassification Report :\n precision recall f1-score support\n 0 0.75 0.50 0.60 6\n 1 0.50 0.75 0.60 4\nmicro avg 0.60 0.60 0.60 10\nmacro avg 0.62 0.62 0.60 10\nweighted avg 0.65 0.60 0.60 10\nAUC-ROC: 0.625\nLOGLOSS Value is 13.815750437193334\n"
},
{
"code": null,
"e": 9106,
"s": 8912,
"text": "We have discussed regression and its algorithms in previous chapters. Here, we are going to discuss various performance metrics that can be used to evaluate predictions for regression problems."
},
{
"code": null,
"e": 9523,
"s": 9106,
"text": "It is the simplest error metric used in regression problems. It is basically the sum of average of the absolute difference between the predicted and actual values. In simple words, with MAE, we can get an idea of how wrong the predictions were. MAE does not indicate the direction of the model i.e. no indication about underperformance or overperformance of the model. The following is the formula to calculate MAE −"
},
{
"code": null,
"e": 9552,
"s": 9523,
"text": "Here, Y=Actual Output Values"
},
{
"code": null,
"e": 9585,
"s": 9552,
"text": "And Y^= Predicted Output Values."
},
{
"code": null,
"e": 9660,
"s": 9585,
"text": "We can use mean_absolute_error function of sklearn.metrics to compute MAE."
},
{
"code": null,
"e": 9900,
"s": 9660,
"text": "MSE is like the MAE, but the only difference is that the it squares the difference of actual and predicted output values before summing them all instead of using the absolute value. The difference can be noticed in the following equation −"
},
{
"code": null,
"e": 9929,
"s": 9900,
"text": "Here, Y=Actual Output Values"
},
{
"code": null,
"e": 9964,
"s": 9929,
"text": "And Y^ = Predicted Output Values."
},
{
"code": null,
"e": 10038,
"s": 9964,
"text": "We can use mean_squared_error function of sklearn.metrics to compute MSE."
},
{
"code": null,
"e": 10266,
"s": 10038,
"text": "R Squared metric is generally used for explanatory purpose and provides an indication of the goodness or fit of a set of predicted output values to the actual output values. The following formula will help us understanding it −"
},
{
"code": null,
"e": 10355,
"s": 10266,
"text": "In the above equation, numerator is MSE and the denominator is the variance in Y values."
},
{
"code": null,
"e": 10431,
"s": 10355,
"text": "We can use r2_score function of sklearn.metrics to compute R squared value."
},
{
"code": null,
"e": 10587,
"s": 10431,
"text": "The following is a simple recipe in Python which will give us an insight about how we can use the above explained performance metrics on regression model −"
},
{
"code": null,
"e": 10938,
"s": 10587,
"text": "from sklearn.metrics import r2_score\nfrom sklearn.metrics import mean_absolute_error\nfrom sklearn.metrics import mean_squared_error\nX_actual = [5, -1, 2, 10]\nY_predic = [3.5, -0.9, 2, 9.9]\nprint ('R Squared =',r2_score(X_actual, Y_predic))\nprint ('MAE =',mean_absolute_error(X_actual, Y_predic))\nprint ('MSE =',mean_squared_error(X_actual, Y_predic))"
},
{
"code": null,
"e": 11021,
"s": 10938,
"text": "R Squared = 0.9656060606060606\nMAE = 0.42499999999999993\nMSE = 0.5674999999999999\n"
},
{
"code": null,
"e": 11058,
"s": 11021,
"text": "\n 168 Lectures \n 13.5 hours \n"
},
{
"code": null,
"e": 11081,
"s": 11058,
"text": " Er. Himanshu Vasishta"
},
{
"code": null,
"e": 11117,
"s": 11081,
"text": "\n 64 Lectures \n 10.5 hours \n"
},
{
"code": null,
"e": 11145,
"s": 11117,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 11179,
"s": 11145,
"text": "\n 91 Lectures \n 10 hours \n"
},
{
"code": null,
"e": 11196,
"s": 11179,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 11229,
"s": 11196,
"text": "\n 54 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 11251,
"s": 11229,
"text": " Abhishek And Pukhraj"
},
{
"code": null,
"e": 11284,
"s": 11251,
"text": "\n 49 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 11306,
"s": 11284,
"text": " Abhishek And Pukhraj"
},
{
"code": null,
"e": 11339,
"s": 11306,
"text": "\n 35 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 11361,
"s": 11339,
"text": " Abhishek And Pukhraj"
},
{
"code": null,
"e": 11368,
"s": 11361,
"text": " Print"
},
{
"code": null,
"e": 11379,
"s": 11368,
"text": " Add Notes"
}
] |
C++ Program to Find element at given index after a number of rotations - GeeksforGeeks | 19 Jan, 2022
An array consisting of N integers is given. There are several Right Circular Rotations of range[L..R] that we perform. After performing these rotations, we need to find element at a given index.Examples :
Input : arr[] : {1, 2, 3, 4, 5}
ranges[] = { {0, 2}, {0, 3} }
index : 1
Output : 3
Explanation : After first given rotation {0, 2}
arr[] = {3, 1, 2, 4, 5}
After second rotation {0, 3}
arr[] = {4, 3, 1, 2, 5}
After all rotations we have element 3 at given
index 1.
Method : Brute-force The brute force approach is to actually rotate the array for all given ranges, finally return the element in at given index in the modified array.Method : Efficient We can do offline processing after saving all ranges. Suppose, our rotate ranges are : [0..2] and [0..3] We run through these ranges from reverse.After range [0..3], index 0 will have the element which was on index 3. So, we can change 0 to 3, i.e. if index = left, index will be changed to right. After range [0..2], index 3 will remain unaffected.So, we can make 3 cases : If index = left, index will be changed to right. If index is not bounds by the range, no effect of rotation. If index is in bounds, index will have the element at index-1.Below is the implementation :
For better explanation:-
10 20 30 40 50
Index: 1
Rotations: {0,2} {1,4} {0,3}
Answer: Index 1 will have 30 after all the 3 rotations in the order {0,2} {1,4} {0,3}.
We performed {0,2} on A and now we have a new array A1.
We performed {1,4} on A1 and now we have a new array A2.
We performed {0,3} on A2 and now we have a new array A3.
Now we are looking for the value at index 1 in A3.
But A3 is {0,3} done on A2.
So index 1 in A3 is index 0 in A2.
But A2 is {1,4} done on A1.
So index 0 in A2 is also index 0 in A1 as it does not lie in the range {1,4}.
But A1 is {0,2} done on A.
So index 0 in A1 is index 2 in A.
On observing it, we are going deeper into the previous rotations starting from the latest rotation.
{0,3}
|
{1,4}
|
{0,2}
This is the reason we are processing the rotations in reverse order.
Please note that we are not rotating the elements in the reverse order, just processing the index from reverse.
Because if we actually rotate in reverse order, we might get a completely different answer as in case of rotations the order matters.
C++
// CPP code to rotate an array// and answer the index query#include <bits/stdc++.h>using namespace std; // Function to compute the element at// given indexint findElement(int arr[], int ranges[][2], int rotations, int index){ for (int i = rotations - 1; i >= 0; i--) { // Range[left...right] int left = ranges[i][0]; int right = ranges[i][1]; // Rotation will not have any effect if (left <= index && right >= index) { if (index == left) index = right; else index--; } } // Returning new element return arr[index];} // Driverint main(){ int arr[] = { 1, 2, 3, 4, 5 }; // No. of rotations int rotations = 2; // Ranges according to 0-based indexing int ranges[rotations][2] = { { 0, 2 }, { 0, 3 } }; int index = 1; cout << findElement(arr, ranges, rotations, index); return 0; }
Output :
3
Please refer complete article on Find element at given index after a number of rotations for more details!
khushboogoyal499
array-range-queries
rotation
Arrays
C++
C++ Programs
Arrays
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Chocolate Distribution Problem
Reversal algorithm for array rotation
Window Sliding Technique
Next Greater Element
Find duplicates in O(n) time and O(1) extra space | Set 1
Vector in C++ STL
Inheritance in C++
Initialize a vector in C++ (6 different ways)
Map in C++ Standard Template Library (STL)
std::sort() in C++ STL | [
{
"code": null,
"e": 26151,
"s": 26123,
"text": "\n19 Jan, 2022"
},
{
"code": null,
"e": 26358,
"s": 26151,
"text": "An array consisting of N integers is given. There are several Right Circular Rotations of range[L..R] that we perform. After performing these rotations, we need to find element at a given index.Examples : "
},
{
"code": null,
"e": 26686,
"s": 26358,
"text": "Input : arr[] : {1, 2, 3, 4, 5}\n ranges[] = { {0, 2}, {0, 3} }\n index : 1\nOutput : 3\nExplanation : After first given rotation {0, 2}\n arr[] = {3, 1, 2, 4, 5}\n After second rotation {0, 3} \n arr[] = {4, 3, 1, 2, 5}\nAfter all rotations we have element 3 at given\nindex 1. "
},
{
"code": null,
"e": 27452,
"s": 26688,
"text": "Method : Brute-force The brute force approach is to actually rotate the array for all given ranges, finally return the element in at given index in the modified array.Method : Efficient We can do offline processing after saving all ranges. Suppose, our rotate ranges are : [0..2] and [0..3] We run through these ranges from reverse.After range [0..3], index 0 will have the element which was on index 3. So, we can change 0 to 3, i.e. if index = left, index will be changed to right. After range [0..2], index 3 will remain unaffected.So, we can make 3 cases : If index = left, index will be changed to right. If index is not bounds by the range, no effect of rotation. If index is in bounds, index will have the element at index-1.Below is the implementation : "
},
{
"code": null,
"e": 27477,
"s": 27452,
"text": "For better explanation:-"
},
{
"code": null,
"e": 27492,
"s": 27477,
"text": "10 20 30 40 50"
},
{
"code": null,
"e": 27501,
"s": 27492,
"text": "Index: 1"
},
{
"code": null,
"e": 27530,
"s": 27501,
"text": "Rotations: {0,2} {1,4} {0,3}"
},
{
"code": null,
"e": 27617,
"s": 27530,
"text": "Answer: Index 1 will have 30 after all the 3 rotations in the order {0,2} {1,4} {0,3}."
},
{
"code": null,
"e": 27673,
"s": 27617,
"text": "We performed {0,2} on A and now we have a new array A1."
},
{
"code": null,
"e": 27730,
"s": 27673,
"text": "We performed {1,4} on A1 and now we have a new array A2."
},
{
"code": null,
"e": 27787,
"s": 27730,
"text": "We performed {0,3} on A2 and now we have a new array A3."
},
{
"code": null,
"e": 27838,
"s": 27787,
"text": "Now we are looking for the value at index 1 in A3."
},
{
"code": null,
"e": 27866,
"s": 27838,
"text": "But A3 is {0,3} done on A2."
},
{
"code": null,
"e": 27901,
"s": 27866,
"text": "So index 1 in A3 is index 0 in A2."
},
{
"code": null,
"e": 27929,
"s": 27901,
"text": "But A2 is {1,4} done on A1."
},
{
"code": null,
"e": 28007,
"s": 27929,
"text": "So index 0 in A2 is also index 0 in A1 as it does not lie in the range {1,4}."
},
{
"code": null,
"e": 28034,
"s": 28007,
"text": "But A1 is {0,2} done on A."
},
{
"code": null,
"e": 28068,
"s": 28034,
"text": "So index 0 in A1 is index 2 in A."
},
{
"code": null,
"e": 28168,
"s": 28068,
"text": "On observing it, we are going deeper into the previous rotations starting from the latest rotation."
},
{
"code": null,
"e": 28174,
"s": 28168,
"text": "{0,3}"
},
{
"code": null,
"e": 28176,
"s": 28174,
"text": "|"
},
{
"code": null,
"e": 28182,
"s": 28176,
"text": "{1,4}"
},
{
"code": null,
"e": 28184,
"s": 28182,
"text": "|"
},
{
"code": null,
"e": 28190,
"s": 28184,
"text": "{0,2}"
},
{
"code": null,
"e": 28259,
"s": 28190,
"text": "This is the reason we are processing the rotations in reverse order."
},
{
"code": null,
"e": 28371,
"s": 28259,
"text": "Please note that we are not rotating the elements in the reverse order, just processing the index from reverse."
},
{
"code": null,
"e": 28506,
"s": 28371,
"text": "Because if we actually rotate in reverse order, we might get a completely different answer as in case of rotations the order matters. "
},
{
"code": null,
"e": 28510,
"s": 28506,
"text": "C++"
},
{
"code": "// CPP code to rotate an array// and answer the index query#include <bits/stdc++.h>using namespace std; // Function to compute the element at// given indexint findElement(int arr[], int ranges[][2], int rotations, int index){ for (int i = rotations - 1; i >= 0; i--) { // Range[left...right] int left = ranges[i][0]; int right = ranges[i][1]; // Rotation will not have any effect if (left <= index && right >= index) { if (index == left) index = right; else index--; } } // Returning new element return arr[index];} // Driverint main(){ int arr[] = { 1, 2, 3, 4, 5 }; // No. of rotations int rotations = 2; // Ranges according to 0-based indexing int ranges[rotations][2] = { { 0, 2 }, { 0, 3 } }; int index = 1; cout << findElement(arr, ranges, rotations, index); return 0; }",
"e": 29439,
"s": 28510,
"text": null
},
{
"code": null,
"e": 29449,
"s": 29439,
"text": "Output : "
},
{
"code": null,
"e": 29451,
"s": 29449,
"text": "3"
},
{
"code": null,
"e": 29559,
"s": 29451,
"text": "Please refer complete article on Find element at given index after a number of rotations for more details! "
},
{
"code": null,
"e": 29576,
"s": 29559,
"text": "khushboogoyal499"
},
{
"code": null,
"e": 29596,
"s": 29576,
"text": "array-range-queries"
},
{
"code": null,
"e": 29605,
"s": 29596,
"text": "rotation"
},
{
"code": null,
"e": 29612,
"s": 29605,
"text": "Arrays"
},
{
"code": null,
"e": 29616,
"s": 29612,
"text": "C++"
},
{
"code": null,
"e": 29629,
"s": 29616,
"text": "C++ Programs"
},
{
"code": null,
"e": 29636,
"s": 29629,
"text": "Arrays"
},
{
"code": null,
"e": 29640,
"s": 29636,
"text": "CPP"
},
{
"code": null,
"e": 29738,
"s": 29640,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29769,
"s": 29738,
"text": "Chocolate Distribution Problem"
},
{
"code": null,
"e": 29807,
"s": 29769,
"text": "Reversal algorithm for array rotation"
},
{
"code": null,
"e": 29832,
"s": 29807,
"text": "Window Sliding Technique"
},
{
"code": null,
"e": 29853,
"s": 29832,
"text": "Next Greater Element"
},
{
"code": null,
"e": 29911,
"s": 29853,
"text": "Find duplicates in O(n) time and O(1) extra space | Set 1"
},
{
"code": null,
"e": 29929,
"s": 29911,
"text": "Vector in C++ STL"
},
{
"code": null,
"e": 29948,
"s": 29929,
"text": "Inheritance in C++"
},
{
"code": null,
"e": 29994,
"s": 29948,
"text": "Initialize a vector in C++ (6 different ways)"
},
{
"code": null,
"e": 30037,
"s": 29994,
"text": "Map in C++ Standard Template Library (STL)"
}
] |
Django Templates | Set - 1 - GeeksforGeeks | 26 Aug, 2019
There are two types of web pages – Static and Dynamic pages. Static webpages are those pages whose content is static i.e. they don’t change with time. Every time you open that page, you see the same content. Their content is independent of time, location, user, etc. Dynamic webpages are those pages whose content are generated dynamically i.e. They vary as per location, time, user and on various factors.
Django framework efficiently handles and generates dynamically HTML web pages which are visible to end-user. Django mainly functions with backend so, in order to provide frontend and provide a layout to our website, we use templates. There are two methods of adding the template to our website depending on our need.
We can use a single template directory which will be spread over the entire project.For each app of our project, we can create a different template directory.
We can use a single template directory which will be spread over the entire project.
For each app of our project, we can create a different template directory.
For our current project, we will create a single template directory which will be spread over the entire project for simplicity. App-level templates are generally used in big projects or in case we want to provide a different layout to each component of our webpage.
Create a template directory in the same directory as our project. In our case, which is geeksforgeeks. So, our directory structure is now,Now, navigate to geeksforgeeks/geeks_site/settings.py.
TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, },]
In above code, modify
'DIRS': []
as
'DIRS': [os.path.join(BASE_DIR, 'templates')]
Above line links our project to our template directory using the os module. If you print BASE_DIR in your terminal, you will see the directory of your project. For example in my case, it is
/home/ankush/Desktop/Programming/webproject/geeksforgeeks
Now our command will join our BASE_DIR to ‘templates’ and feed it to ‘DIRS’ key of TEMPLATE. Now, we can our save HTML codes in geeksforgeeks/templates directory and can access it from our code.
Python Django
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python | [
{
"code": null,
"e": 25533,
"s": 25505,
"text": "\n26 Aug, 2019"
},
{
"code": null,
"e": 25940,
"s": 25533,
"text": "There are two types of web pages – Static and Dynamic pages. Static webpages are those pages whose content is static i.e. they don’t change with time. Every time you open that page, you see the same content. Their content is independent of time, location, user, etc. Dynamic webpages are those pages whose content are generated dynamically i.e. They vary as per location, time, user and on various factors."
},
{
"code": null,
"e": 26257,
"s": 25940,
"text": "Django framework efficiently handles and generates dynamically HTML web pages which are visible to end-user. Django mainly functions with backend so, in order to provide frontend and provide a layout to our website, we use templates. There are two methods of adding the template to our website depending on our need."
},
{
"code": null,
"e": 26416,
"s": 26257,
"text": "We can use a single template directory which will be spread over the entire project.For each app of our project, we can create a different template directory."
},
{
"code": null,
"e": 26501,
"s": 26416,
"text": "We can use a single template directory which will be spread over the entire project."
},
{
"code": null,
"e": 26576,
"s": 26501,
"text": "For each app of our project, we can create a different template directory."
},
{
"code": null,
"e": 26843,
"s": 26576,
"text": "For our current project, we will create a single template directory which will be spread over the entire project for simplicity. App-level templates are generally used in big projects or in case we want to provide a different layout to each component of our webpage."
},
{
"code": null,
"e": 27036,
"s": 26843,
"text": "Create a template directory in the same directory as our project. In our case, which is geeksforgeeks. So, our directory structure is now,Now, navigate to geeksforgeeks/geeks_site/settings.py."
},
{
"code": "TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, },]",
"e": 27506,
"s": 27036,
"text": null
},
{
"code": null,
"e": 27528,
"s": 27506,
"text": "In above code, modify"
},
{
"code": null,
"e": 27589,
"s": 27528,
"text": "'DIRS': []\n\nas\n'DIRS': [os.path.join(BASE_DIR, 'templates')]"
},
{
"code": null,
"e": 27779,
"s": 27589,
"text": "Above line links our project to our template directory using the os module. If you print BASE_DIR in your terminal, you will see the directory of your project. For example in my case, it is"
},
{
"code": null,
"e": 27837,
"s": 27779,
"text": "/home/ankush/Desktop/Programming/webproject/geeksforgeeks"
},
{
"code": null,
"e": 28032,
"s": 27837,
"text": "Now our command will join our BASE_DIR to ‘templates’ and feed it to ‘DIRS’ key of TEMPLATE. Now, we can our save HTML codes in geeksforgeeks/templates directory and can access it from our code."
},
{
"code": null,
"e": 28046,
"s": 28032,
"text": "Python Django"
},
{
"code": null,
"e": 28053,
"s": 28046,
"text": "Python"
},
{
"code": null,
"e": 28151,
"s": 28053,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28169,
"s": 28151,
"text": "Python Dictionary"
},
{
"code": null,
"e": 28201,
"s": 28169,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28223,
"s": 28201,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 28265,
"s": 28223,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 28291,
"s": 28265,
"text": "Python String | replace()"
},
{
"code": null,
"e": 28320,
"s": 28291,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 28364,
"s": 28320,
"text": "Reading and Writing to text files in Python"
},
{
"code": null,
"e": 28401,
"s": 28364,
"text": "Create a Pandas DataFrame from Lists"
},
{
"code": null,
"e": 28443,
"s": 28401,
"text": "How To Convert Python Dictionary To JSON?"
}
] |
How to switch between multiple windows of Electron JS application ? - GeeksforGeeks | 06 Aug, 2021
If you have prior knowledge of Web Application Development and thinking to jump into the building of Desktop Application, you are at the right place to start with.
ElectronJS is an open-source framework that helps to develop a cross-platform desktop application using simple HTML, CSS, and JavaScript. Even if you want to develop an application using Angular or React and trying to build the desktop version of it, Electron JS provides you the same support. Electron uses a headless Chromium browser which provides access to Node JS APIs through Electron’s own APIs.
In any web application, while we click on some links, sometimes a new tab in the browser opens with new content. Also, we think that you observe the same behavior in the case of Desktop Application. When we click on some button in any Desktop Application, it opens a new window on top of the previous window, and until we close the top window (or the new window), the main window won’t work. Electron provides this functionality of opening multiple windows based on button click or click on any link.
For understanding, let’s say you develop one application, and you want to open the Settings page in another window. And this tutorial will demonstrate how to open the Settings page in a new window using Electron JS.
We assume that you are familiar with the basic setup of the Electron Application (If not, please go through Create Basic Electron Application). Node and npm need to be installed in your system to run the Electron application.
Project Structure: Let’s begin with the basic structure of the project as follows.
Project Structure
node_modules: This contains the node JS packages which has been created while you do npm init -y
app.js: This the main Electron JS file, where we specify our application window configurations
index.html: This is the main HTML file (Consider it as the main page of our application)
package-lock.json: This file has automatically been generated by npm while we modify something in node_modules or package.json
package.json: This file has been generated by npm and it contains the additional dependencies of our project (like an electron) and some other settings
settings.html: This is the settings HTML file (which will be shown to settings window)
package.json
{
"name": "electron-app",
"version": "1.0.0",
"description": "",
"main": "app.js",
"scripts": {
"start": "electron ."
},
"author": "Sandip",
"license": "ISC",
"dependencies": {
"electron": "^12.0.2"
}
}
Copy the main script file (main.js) from Create Basic Electron Application to our app.js which acts as the main process of our application.
Write simple HTML code in index.html (As if it is your first window or main window) as follows
index.html
<!DOCTYPE html><html> <head> <title>First Window</title> </head> <body> <div> <h1 style="color: green;"> Hello : This is first window </h1> <br /> <button onclick="goToSettingsWindow()"> Go to Settings Window </button> </div> </body></html>
Output:
Initial Window
app.js: We intend to open a new Settings window while you click on the “Go to Settings Window” button. Let’s check the necessary changes to be done in the app.js file.
app.js
const { app, BrowserWindow, ipcMain } = require("electron");const path = require("path"); let mainWindow; // Function to create independent window or main windowfunction createWindow() { mainWindow = new BrowserWindow({ width: 800, height: 600, // Make sure to add webPreferences with // nodeIntegration and contextIsolation webPreferences: { nodeIntegration: true, contextIsolation: false, }, show: false, }); // Main window loads index.html file mainWindow.loadFile("index.html"); // To maximize the window mainWindow.maximize(); mainWindow.show();} // Function to create child window of parent onefunction createChildWindow() { childWindow = new BrowserWindow({ width: 1000, height: 700, modal: true, show: false, parent: mainWindow, // Make sure to add parent window here // Make sure to add webPreferences with below configuration webPreferences: { nodeIntegration: true, contextIsolation: false, enableRemoteModule: true, }, }); // Child window loads settings.html file childWindow.loadFile("settings.html"); childWindow.once("ready-to-show", () => { childWindow.show(); });} ipcMain.on("openChildWindow", (event, arg) => { createChildWindow();}); app.whenReady().then(() => { createWindow(); app.on("activate", () => { if (BrowserWindow.getAllWindows().length === 0) { createWindow(); } });}); app.on("window-all-closed", () => { if (process.platform !== "darwin") { app.quit(); }});
Import ipcMain from electron module
Add createChildWindow() method as above which basically includes all the settings and configuration of child window (i.e. Settings Window)
If you do, childWindow.parent = mainWindow as above, then until child window will be closed, parent window will be disabled.
If you omit childWindow.parent, then a new window will be opened, but there will not be any connection between the child window and the parent window.
Include ipcMain.on(‘openChildWindow’, (event, arg) => { createChildWindow(); } ); basically call createChildWindow() method while we send “openChildWindow” event on button click through ipcRenderer.
Add webPreferences property with all the key-values as mentioned above to mainWindow object which enables us to use Electron’s remote, ipcRenderer for working with child window.
Let’s add the below script in index.html
Javascript
const ipc = window.require('electron').ipcRenderer; // Function that will be called on click // event of "Go to settings window" buttonfunction goToSettingsWindow(){ // Make sure to do ipc.send('some String'), // where 'some String' must be same with // the first parameter of ipcMain.on() in app.js ipc.send('openChildWindow'); }
Here we are using ipcRenderer of electron module to send an event ‘openChildWindow‘ and ipcMain (specified in app.js) is listening this event and call createChildWindow() method.
Let’s create a settings.html file that will be shown in the child window on the button click (‘Go to Settings Window’ button) in the main window.
settings.html
<!DOCTYPE html><html><head> <title>Settings</title></head><body> <div> <h1 style="color: green;"> Hello : This is Settings window </h1> <button onclick="goToFirstWindow()"> Go to Main Window </button> </div></body></html>
Output: Before adding “Go to Main Window” functionality, let’s check the output of opening the settings window
Let’s add the below script in settings.html to close the settings window and come back to the main window (If you close the window by clicking Window close (the X button in the top-right corner), it is also possible, but sometimes we need to do some other action to be performed before closing the window, like Database update or config update and for that, you need to close the window on button click)
Javascript
const remote = window.require("electron").remote; function goToFirstWindow() { //code for some other action to be performed //Code to close the window after doing other actions remote.getCurrentWindow().close();}
Here we are accessing remote object of electron module to get currentWindow object.
Output: Let’s check our final application.
saurabh1990aror
ElectronJS
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between var, let and const keywords in JavaScript
Difference Between PUT and PATCH Request
How to get character array from string in JavaScript?
How to remove duplicate elements from JavaScript Array ?
How to get selected value in dropdown list using JavaScript ?
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS? | [
{
"code": null,
"e": 25244,
"s": 25216,
"text": "\n06 Aug, 2021"
},
{
"code": null,
"e": 25410,
"s": 25244,
"text": "If you have prior knowledge of Web Application Development and thinking to jump into the building of Desktop Application, you are at the right place to start with. "
},
{
"code": null,
"e": 25813,
"s": 25410,
"text": "ElectronJS is an open-source framework that helps to develop a cross-platform desktop application using simple HTML, CSS, and JavaScript. Even if you want to develop an application using Angular or React and trying to build the desktop version of it, Electron JS provides you the same support. Electron uses a headless Chromium browser which provides access to Node JS APIs through Electron’s own APIs."
},
{
"code": null,
"e": 26315,
"s": 25813,
"text": "In any web application, while we click on some links, sometimes a new tab in the browser opens with new content. Also, we think that you observe the same behavior in the case of Desktop Application. When we click on some button in any Desktop Application, it opens a new window on top of the previous window, and until we close the top window (or the new window), the main window won’t work. Electron provides this functionality of opening multiple windows based on button click or click on any link. "
},
{
"code": null,
"e": 26532,
"s": 26315,
"text": "For understanding, let’s say you develop one application, and you want to open the Settings page in another window. And this tutorial will demonstrate how to open the Settings page in a new window using Electron JS. "
},
{
"code": null,
"e": 26759,
"s": 26532,
"text": "We assume that you are familiar with the basic setup of the Electron Application (If not, please go through Create Basic Electron Application). Node and npm need to be installed in your system to run the Electron application. "
},
{
"code": null,
"e": 26842,
"s": 26759,
"text": "Project Structure: Let’s begin with the basic structure of the project as follows."
},
{
"code": null,
"e": 26860,
"s": 26842,
"text": "Project Structure"
},
{
"code": null,
"e": 26957,
"s": 26860,
"text": "node_modules: This contains the node JS packages which has been created while you do npm init -y"
},
{
"code": null,
"e": 27052,
"s": 26957,
"text": "app.js: This the main Electron JS file, where we specify our application window configurations"
},
{
"code": null,
"e": 27141,
"s": 27052,
"text": "index.html: This is the main HTML file (Consider it as the main page of our application)"
},
{
"code": null,
"e": 27268,
"s": 27141,
"text": "package-lock.json: This file has automatically been generated by npm while we modify something in node_modules or package.json"
},
{
"code": null,
"e": 27420,
"s": 27268,
"text": "package.json: This file has been generated by npm and it contains the additional dependencies of our project (like an electron) and some other settings"
},
{
"code": null,
"e": 27507,
"s": 27420,
"text": "settings.html: This is the settings HTML file (which will be shown to settings window)"
},
{
"code": null,
"e": 27520,
"s": 27507,
"text": "package.json"
},
{
"code": null,
"e": 27751,
"s": 27520,
"text": "{\n \"name\": \"electron-app\",\n \"version\": \"1.0.0\",\n \"description\": \"\",\n \"main\": \"app.js\",\n \"scripts\": {\n \"start\": \"electron .\"\n },\n \"author\": \"Sandip\",\n \"license\": \"ISC\",\n \"dependencies\": {\n \"electron\": \"^12.0.2\"\n }\n}"
},
{
"code": null,
"e": 27891,
"s": 27751,
"text": "Copy the main script file (main.js) from Create Basic Electron Application to our app.js which acts as the main process of our application."
},
{
"code": null,
"e": 27989,
"s": 27893,
"text": "Write simple HTML code in index.html (As if it is your first window or main window) as follows "
},
{
"code": null,
"e": 28000,
"s": 27989,
"text": "index.html"
},
{
"code": "<!DOCTYPE html><html> <head> <title>First Window</title> </head> <body> <div> <h1 style=\"color: green;\"> Hello : This is first window </h1> <br /> <button onclick=\"goToSettingsWindow()\"> Go to Settings Window </button> </div> </body></html>",
"e": 28357,
"s": 28000,
"text": null
},
{
"code": null,
"e": 28366,
"s": 28357,
"text": "Output: "
},
{
"code": null,
"e": 28381,
"s": 28366,
"text": "Initial Window"
},
{
"code": null,
"e": 28553,
"s": 28385,
"text": "app.js: We intend to open a new Settings window while you click on the “Go to Settings Window” button. Let’s check the necessary changes to be done in the app.js file."
},
{
"code": null,
"e": 28560,
"s": 28553,
"text": "app.js"
},
{
"code": "const { app, BrowserWindow, ipcMain } = require(\"electron\");const path = require(\"path\"); let mainWindow; // Function to create independent window or main windowfunction createWindow() { mainWindow = new BrowserWindow({ width: 800, height: 600, // Make sure to add webPreferences with // nodeIntegration and contextIsolation webPreferences: { nodeIntegration: true, contextIsolation: false, }, show: false, }); // Main window loads index.html file mainWindow.loadFile(\"index.html\"); // To maximize the window mainWindow.maximize(); mainWindow.show();} // Function to create child window of parent onefunction createChildWindow() { childWindow = new BrowserWindow({ width: 1000, height: 700, modal: true, show: false, parent: mainWindow, // Make sure to add parent window here // Make sure to add webPreferences with below configuration webPreferences: { nodeIntegration: true, contextIsolation: false, enableRemoteModule: true, }, }); // Child window loads settings.html file childWindow.loadFile(\"settings.html\"); childWindow.once(\"ready-to-show\", () => { childWindow.show(); });} ipcMain.on(\"openChildWindow\", (event, arg) => { createChildWindow();}); app.whenReady().then(() => { createWindow(); app.on(\"activate\", () => { if (BrowserWindow.getAllWindows().length === 0) { createWindow(); } });}); app.on(\"window-all-closed\", () => { if (process.platform !== \"darwin\") { app.quit(); }});",
"e": 30075,
"s": 28560,
"text": null
},
{
"code": null,
"e": 30113,
"s": 30077,
"text": "Import ipcMain from electron module"
},
{
"code": null,
"e": 30252,
"s": 30113,
"text": "Add createChildWindow() method as above which basically includes all the settings and configuration of child window (i.e. Settings Window)"
},
{
"code": null,
"e": 30377,
"s": 30252,
"text": "If you do, childWindow.parent = mainWindow as above, then until child window will be closed, parent window will be disabled."
},
{
"code": null,
"e": 30528,
"s": 30377,
"text": "If you omit childWindow.parent, then a new window will be opened, but there will not be any connection between the child window and the parent window."
},
{
"code": null,
"e": 30727,
"s": 30528,
"text": "Include ipcMain.on(‘openChildWindow’, (event, arg) => { createChildWindow(); } ); basically call createChildWindow() method while we send “openChildWindow” event on button click through ipcRenderer."
},
{
"code": null,
"e": 30905,
"s": 30727,
"text": "Add webPreferences property with all the key-values as mentioned above to mainWindow object which enables us to use Electron’s remote, ipcRenderer for working with child window."
},
{
"code": null,
"e": 30947,
"s": 30905,
"text": "Let’s add the below script in index.html"
},
{
"code": null,
"e": 30958,
"s": 30947,
"text": "Javascript"
},
{
"code": "const ipc = window.require('electron').ipcRenderer; // Function that will be called on click // event of \"Go to settings window\" buttonfunction goToSettingsWindow(){ // Make sure to do ipc.send('some String'), // where 'some String' must be same with // the first parameter of ipcMain.on() in app.js ipc.send('openChildWindow'); }",
"e": 31308,
"s": 30958,
"text": null
},
{
"code": null,
"e": 31488,
"s": 31308,
"text": "Here we are using ipcRenderer of electron module to send an event ‘openChildWindow‘ and ipcMain (specified in app.js) is listening this event and call createChildWindow() method."
},
{
"code": null,
"e": 31634,
"s": 31488,
"text": "Let’s create a settings.html file that will be shown in the child window on the button click (‘Go to Settings Window’ button) in the main window."
},
{
"code": null,
"e": 31648,
"s": 31634,
"text": "settings.html"
},
{
"code": "<!DOCTYPE html><html><head> <title>Settings</title></head><body> <div> <h1 style=\"color: green;\"> Hello : This is Settings window </h1> <button onclick=\"goToFirstWindow()\"> Go to Main Window </button> </div></body></html>",
"e": 31925,
"s": 31648,
"text": null
},
{
"code": null,
"e": 32036,
"s": 31925,
"text": "Output: Before adding “Go to Main Window” functionality, let’s check the output of opening the settings window"
},
{
"code": null,
"e": 32442,
"s": 32038,
"text": "Let’s add the below script in settings.html to close the settings window and come back to the main window (If you close the window by clicking Window close (the X button in the top-right corner), it is also possible, but sometimes we need to do some other action to be performed before closing the window, like Database update or config update and for that, you need to close the window on button click)"
},
{
"code": null,
"e": 32453,
"s": 32442,
"text": "Javascript"
},
{
"code": "const remote = window.require(\"electron\").remote; function goToFirstWindow() { //code for some other action to be performed //Code to close the window after doing other actions remote.getCurrentWindow().close();}",
"e": 32672,
"s": 32453,
"text": null
},
{
"code": null,
"e": 32756,
"s": 32672,
"text": "Here we are accessing remote object of electron module to get currentWindow object."
},
{
"code": null,
"e": 32799,
"s": 32756,
"text": "Output: Let’s check our final application."
},
{
"code": null,
"e": 32815,
"s": 32799,
"text": "saurabh1990aror"
},
{
"code": null,
"e": 32826,
"s": 32815,
"text": "ElectronJS"
},
{
"code": null,
"e": 32837,
"s": 32826,
"text": "JavaScript"
},
{
"code": null,
"e": 32854,
"s": 32837,
"text": "Web Technologies"
},
{
"code": null,
"e": 32952,
"s": 32854,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32961,
"s": 32952,
"text": "Comments"
},
{
"code": null,
"e": 32974,
"s": 32961,
"text": "Old Comments"
},
{
"code": null,
"e": 33035,
"s": 32974,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 33076,
"s": 33035,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 33130,
"s": 33076,
"text": "How to get character array from string in JavaScript?"
},
{
"code": null,
"e": 33187,
"s": 33130,
"text": "How to remove duplicate elements from JavaScript Array ?"
},
{
"code": null,
"e": 33249,
"s": 33187,
"text": "How to get selected value in dropdown list using JavaScript ?"
},
{
"code": null,
"e": 33291,
"s": 33249,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 33324,
"s": 33291,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 33386,
"s": 33324,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 33429,
"s": 33386,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
Maximum width of a binary tree - GeeksforGeeks | 10 Jan, 2022
Given a binary tree, write a function to get the maximum width of the given tree. Width of a tree is maximum of widths of all levels.
Let us consider the below example tree.
1
/ \
2 3
/ \ \
4 5 8
/ \
6 7
For the above tree, width of level 1 is 1, width of level 2 is 2, width of level 3 is 3 width of level 4 is 2. So the maximum width of the tree is 3.
Method 1 (Using Level Order Traversal) This method mainly involves two functions. One is to count nodes at a given level (getWidth), and other is to get the maximum width of the tree(getMaxWidth). getMaxWidth() makes use of getWidth() to get the width of all levels starting from root.
/*Function to print level order traversal of tree*/
getMaxWidth(tree)
maxWdth = 0
for i = 1 to height(tree)
width = getWidth(tree, i);
if(width > maxWdth)
maxWdth = width
return maxWidth
/*Function to get width of a given level */
getWidth(tree, level)
if tree is NULL then return 0;
if level is 1, then return 1;
else if level greater than 1, then
return getWidth(tree->left, level-1) +
getWidth(tree->right, level-1);
Below is the implementation of the above idea:
C++
C
Java
Python3
C#
Javascript
// C++ program to calculate width of binary tree#include <bits/stdc++.h>using namespace std; /* A binary tree node has data, pointer to left childand a pointer to right child */class node {public: int data; node* left; node* right;}; /*Function prototypes*/int getWidth(node* root, int level);int height(node* node);node* newNode(int data); /* Function to get the maximum width of a binary tree*/int getMaxWidth(node* root){ int maxWidth = 0; int width; int h = height(root); int i; /* Get width of each level and compare the width with maximum width so far */ for (i = 1; i <= h; i++) { width = getWidth(root, i); if (width > maxWidth) maxWidth = width; } return maxWidth;} /* Get width of a given level */int getWidth(node* root, int level){ if (root == NULL) return 0; if (level == 1) return 1; else if (level > 1) return getWidth(root->left, level - 1) + getWidth(root->right, level - 1);} /* UTILITY FUNCTIONS *//* Compute the "height" of a tree -- the number of nodes along the longest path from the root node down to the farthest leaf node.*/int height(node* node){ if (node == NULL) return 0; else { /* compute the height of each subtree */ int lHeight = height(node->left); int rHeight = height(node->right); /* use the larger one */ return (lHeight > rHeight) ? (lHeight + 1) : (rHeight + 1); }} /* Helper function that allocates a new node with thegiven data and NULL left and right pointers. */node* newNode(int data){ node* Node = new node(); Node->data = data; Node->left = NULL; Node->right = NULL; return (Node);} /* Driver code*/int main(){ node* root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); root->right->right = newNode(8); root->right->right->left = newNode(6); root->right->right->right = newNode(7); /* Constructed binary tree is: 1 / \ 2 3 / \ \ 4 5 8 / \ 6 7 */ // Function call cout << "Maximum width is " << getMaxWidth(root) << endl; return 0;} // This code is contributed by rathbhupendra
// C program to calculate width of binary tree#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;}; /*Function prototypes*/int getWidth(struct node* root, int level);int height(struct node* node);struct node* newNode(int data); /* Function to get the maximum width of a binary tree*/int getMaxWidth(struct node* root){ int maxWidth = 0; int width; int h = height(root); int i; /* Get width of each level and compare the width with maximum width so far */ for (i = 1; i <= h; i++) { width = getWidth(root, i); if (width > maxWidth) maxWidth = width; } return maxWidth;} /* Get width of a given level */int getWidth(struct node* root, int level){ if (root == NULL) return 0; if (level == 1) return 1; else if (level > 1) return getWidth(root->left, level - 1) + getWidth(root->right, level - 1);} /* UTILITY FUNCTIONS *//* Compute the "height" of a tree -- the number of nodes along the longest path from the root node down to the farthest leaf node.*/int height(struct node* node){ if (node == NULL) return 0; else { /* compute the height of each subtree */ int lHeight = height(node->left); int rHeight = height(node->right); /* use the larger one */ return (lHeight > rHeight) ? (lHeight + 1) : (rHeight + 1); }}/* 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);}/* Driver code*/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); root->right->right = newNode(8); root->right->right->left = newNode(6); root->right->right->right = newNode(7); /* Constructed binary tree is: 1 / \ 2 3 / \ \ 4 5 8 / \ 6 7 */ // Function call printf("Maximum width is %d \n", getMaxWidth(root)); getchar(); return 0;}
// Java program to calculate width of binary tree /* A binary tree node has data, pointer to left child and a pointer to right child */class Node { int data; Node left, right; Node(int item) { data = item; left = right = null; }} class BinaryTree { Node root; /* Function to get the maximum width of a binary tree*/ int getMaxWidth(Node node) { int maxWidth = 0; int width; int h = height(node); int i; /* Get width of each level and compare the width with maximum width so far */ for (i = 1; i <= h; i++) { width = getWidth(node, i); if (width > maxWidth) maxWidth = width; } return maxWidth; } /* Get width of a given level */ int getWidth(Node node, int level) { if (node == null) return 0; if (level == 1) return 1; else if (level > 1) return getWidth(node.left, level - 1) + getWidth(node.right, level - 1); return 0; } /* UTILITY FUNCTIONS */ /* Compute the "height" of a tree -- the number of nodes along the longest path from the root node down to the farthest leaf node.*/ int height(Node node) { if (node == null) return 0; else { /* compute the height of each subtree */ int lHeight = height(node.left); int rHeight = height(node.right); /* use the larger one */ return (lHeight > rHeight) ? (lHeight + 1) : (rHeight + 1); } } /* Driver code */ public static void main(String args[]) { BinaryTree tree = new BinaryTree(); /* Constructed binary tree is: 1 / \ 2 3 / \ \ 4 5 8 / \ 6 7 */ 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); tree.root.right.right = new Node(8); tree.root.right.right.left = new Node(6); tree.root.right.right.right = new Node(7); // Function call System.out.println("Maximum width is " + tree.getMaxWidth(tree.root)); }} // This code has been contributed by Mayank Jaiswal
# Python program to find the maximum width of# binary tree using Level Order Traversal. # A binary tree node class Node: # Constructor to create a new node def __init__(self, data): self.data = data self.left = None self.right = None # Function to get the maximum width of a binary tree def getMaxWidth(root): maxWidth = 0 h = height(root) # Get width of each level and compare the # width with maximum width so far for i in range(1, h+1): width = getWidth(root, i) if (width > maxWidth): maxWidth = width return maxWidth # Get width of a given level def getWidth(root, level): if root is None: return 0 if level == 1: return 1 elif level > 1: return (getWidth(root.left, level-1) + getWidth(root.right, level-1)) # UTILITY FUNCTIONS# Compute the "height" of a tree -- the number of# nodes along the longest path from the root node# down to the farthest leaf node. def height(node): if node is None: return 0 else: # compute the height of each subtree lHeight = height(node.left) rHeight = height(node.right) # use the larger one return (lHeight+1) if (lHeight > rHeight) else (rHeight+1) # Driver coderoot = Node(1)root.left = Node(2)root.right = Node(3)root.left.left = Node(4)root.left.right = Node(5)root.right.right = Node(8)root.right.right.left = Node(6)root.right.right.right = Node(7) """Constructed binary tree is: 1 / \ 2 3 / \ \4 5 8 / \ 6 7"""# Function callprint ("Maximum width is %d" % (getMaxWidth(root))) # This code is contributed by Naveen Aili
// C# program to calculate width of binary treeusing System; /* A binary tree node has data, pointer to left childand a pointer to right child */public class Node { public int data; public Node left, right; public Node(int item) { data = item; left = right = null; }} public class BinaryTree { public Node root; /* Function to get the maximum width of a binary tree*/ public virtual int getMaxWidth(Node node) { int maxWidth = 0; int width; int h = height(node); int i; /* Get width of each level and compare the width with maximum width so far */ for (i = 1; i <= h; i++) { width = getWidth(node, i); if (width > maxWidth) { maxWidth = width; } } return maxWidth; } /* Get width of a given level */ public virtual int getWidth(Node node, int level) { if (node == null) { return 0; } if (level == 1) { return 1; } else if (level > 1) { return getWidth(node.left, level - 1) + getWidth(node.right, level - 1); } return 0; } /* UTILITY FUNCTIONS */ /* Compute the "height" of a tree -- the number of nodes along the longest path from the root node down to the farthest leaf node.*/ public virtual int height(Node node) { if (node == null) { return 0; } else { /* compute the height of each subtree */ int lHeight = height(node.left); int rHeight = height(node.right); /* use the larger one */ return (lHeight > rHeight) ? (lHeight + 1) : (rHeight + 1); } } /* Driver code */ public static void Main(string[] args) { BinaryTree tree = new BinaryTree(); /* Constructed binary tree is: 1 / \ 2 3 / \ \ 4 5 8 / \ 6 7 */ 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); tree.root.right.right = new Node(8); tree.root.right.right.left = new Node(6); tree.root.right.right.right = new Node(7); // Function call Console.WriteLine("Maximum width is " + tree.getMaxWidth(tree.root)); }} // This code is contributed by Shrikant13
<script> // JavaScript program to calculate width of binary tree /* A binary tree node has data, pointer to left child and a pointer to right child */class Node { constructor(val) { this.data = val; this.left = null; this.right = null; }} var root; /* Function to get the maximum width of a binary tree*/ function getMaxWidth(node) { var maxWidth = 0; var width; var h = height(node); var i; /* Get width of each level and compare the width with maximum width so far */ for (i = 1; i <= h; i++) { width = getWidth(node, i); if (width > maxWidth) maxWidth = width; } return maxWidth; } /* Get width of a given level */ function getWidth(node , level) { if (node == null) return 0; if (level == 1) return 1; else if (level > 1) return getWidth(node.left, level - 1) + getWidth(node.right, level - 1); return 0; } /* UTILITY FUNCTIONS */ /* Compute the "height" of a tree -- the number of nodes along the longest path from the root node down to the farthest leaf node.*/ function height(node) { if (node == null) return 0; else { /* compute the height of each subtree */ var lHeight = height(node.left); var rHeight = height(node.right); /* use the larger one */ return (lHeight > rHeight) ? (lHeight + 1) : (rHeight + 1); } } /* Driver code */ /* Constructed binary tree is: 1 / \ 2 3 / \ \ 4 5 8 / \ 6 7 */ 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); root.right.right = new Node(8); root.right.right.left = new Node(6); root.right.right.right = new Node(7); // Function call document.write("Maximum width is " + getMaxWidth(root));// This code is contributed by todaysgaurav </script>
Maximum width is 3
Time Complexity: O(n2) in the worst case.We can use Queue based level order traversal to optimize the time complexity of this method. The Queue based level order traversal will take O(n) time in worst case. Thanks to Nitish, DivyaC and tech.login.id2 for suggesting this optimization. See their comments for implementation using queue-based traversal.
Method 2 (Using Level Order Traversal with Queue) In this method, we store all the child nodes at the current level in the queue and then count the total number of nodes after the level order traversal for a particular level is completed. Since the queue now contains all the nodes of the next level, we can easily find out the total number of nodes in the next level by finding the size of queue. We then follow the same procedure for the successive levels. We store and update the maximum number of nodes found at each level.
Below is the implementation of the above idea:
C++
Java
Python3
C#
Javascript
// A queue based C++ program to find maximum width// of a Binary Tree#include <bits/stdc++.h>using namespace std; /* A binary tree node has data, pointer to left child and a pointer to right child */struct Node { int data; struct Node* left; struct Node* right;}; // Function to find the maximum width of the tree// using level order traversalint maxWidth(struct Node* root){ // Base case if (root == NULL) return 0; // Initialize result int result = 0; // Do Level order traversal keeping track of number // of nodes at every level. queue<Node*> q; q.push(root); while (!q.empty()) { // Get the size of queue when the level order // traversal for one level finishes int count = q.size(); // Update the maximum node count value result = max(count, result); // Iterate for all the nodes in the queue currently while (count--) { // Dequeue an node from queue Node* temp = q.front(); q.pop(); // Enqueue left and right children of // dequeued node if (temp->left != NULL) q.push(temp->left); if (temp->right != NULL) q.push(temp->right); } } return result;} /* 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 = new Node; node->data = data; node->left = node->right = NULL; return (node);} // Driver codeint main(){ struct Node* root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); root->right->right = newNode(8); root->right->right->left = newNode(6); root->right->right->right = newNode(7); /* Constructed Binary tree is: 1 / \ 2 3 / \ \ 4 5 8 / \ 6 7 */ // Function call cout << "Maximum width is " << maxWidth(root) << endl; return 0;} // This code is contributed by Nikhil Kumar// Singh(nickzuck_007)
// Java program to calculate maximum width// of a binary tree using queueimport java.util.LinkedList;import java.util.Queue; public class maxwidthusingqueue{ /* A binary tree node has data, pointer to left child and a pointer to right child */ static class node { int data; node left, right; public node(int data) { this.data = data; } } // Function to find the maximum width of // the tree using level order traversal static int maxwidth(node root) { // Base case if (root == null) return 0; // Initialize result int maxwidth = 0; // Do Level order traversal keeping // track of number of nodes at every level Queue<node> q = new LinkedList<>(); q.add(root); while (!q.isEmpty()) { // Get the size of queue when the level order // traversal for one level finishes int count = q.size(); // Update the maximum node count value maxwidth = Math.max(maxwidth, count); // Iterate for all the nodes in // the queue currently while (count-- > 0) { // Dequeue an node from queue node temp = q.remove(); // Enqueue left and right children // of dequeued node if (temp.left != null) { q.add(temp.left); } if (temp.right != null) { q.add(temp.right); } } } return maxwidth; } // Function call public static void main(String[] args) { node 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); root.right.right = new node(8); root.right.right.left = new node(6); root.right.right.right = new node(7); /* Constructed Binary tree is: 1 / \ 2 3 / \ \ 4 5 8 / \ 6 7 */ // Function call System.out.println("Maximum width = " + maxwidth(root)); }} // This code is contributed by Rishabh Mahrsee
# Python program to find the maximum width of binary# tree using Level Order Traversal with queue. # A binary tree node class Node: # Constructor to create a new node def __init__(self, data): self.data = data self.left = None self.right = None # Function to get the maximum width of a binary tree def getMaxWidth(root): # base case if root is None: return 0 q = [] maxWidth = 0 q.insert(0, root) while (q != []): # Get the size of queue when the level order # traversal for one level finishes count = len(q) # Update the maximum node count value maxWidth = max(count, maxWidth) while (count is not 0): count = count-1 temp = q[-1] q.pop() if temp.left is not None: q.insert(0, temp.left) if temp.right is not None: q.insert(0, temp.right) return maxWidth # Driver program to test above functionroot = Node(1)root.left = Node(2)root.right = Node(3)root.left.left = Node(4)root.left.right = Node(5)root.right.right = Node(8)root.right.right.left = Node(6)root.right.right.right = Node(7) """Constructed binary tree is: 1 / \ 2 3 / \ \ 4 5 8 / \ 6 7"""# Function callprint ("Maximum width is %d" % (getMaxWidth(root))) # This code is contributed by Naveen Aili
// C# program to calculate maximum width// of a binary tree using queueusing System;using System.Collections.Generic; public class maxwidthusingqueue{ /* A binary tree node has data, pointer to left child and a pointer to right child */ public class node { public int data; public node left, right; public node(int data) { this.data = data; } } // Function to find the maximum width of // the tree using level order traversal static int maxwidth(node root) { // Base case if (root == null) return 0; // Initialize result int maxwidth = 0; // Do Level order traversal keeping // track of number of nodes at every level Queue<node> q = new Queue<node>(); q.Enqueue(root); while (q.Count != 0) { // Get the size of queue when the level order // traversal for one level finishes int count = q.Count; // Update the maximum node count value maxwidth = Math.Max(maxwidth, count); // Iterate for all the nodes in // the queue currently while (count-- > 0) { // Dequeue an node from queue node temp = q.Dequeue(); // Enqueue left and right children // of dequeued node if (temp.left != null) { q.Enqueue(temp.left); } if (temp.right != null) { q.Enqueue(temp.right); } } } return maxwidth; } // Driver code public static void Main(String[] args) { node 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); root.right.right = new node(8); root.right.right.left = new node(6); root.right.right.right = new node(7); /* Constructed Binary tree is: 1 / \ 2 3 / \ \ 4 5 8 / \ 6 7 */ Console.WriteLine("Maximum width = " + maxwidth(root)); }} // This code is contributed by Princi Singh
<script> // JavaScript program to calculate maximum width // of a binary tree using queue class node { constructor(data) { this.left = null; this.right = null; this.data = data; } } // Function to find the maximum width of // the tree using level order traversal function maxwidth(root) { // Base case if (root == null) return 0; // Initialize result let maxwidth = 0; // Do Level order traversal keeping // track of number of nodes at every level let q = []; q.push(root); while (q.length > 0) { // Get the size of queue when the level order // traversal for one level finishes let count = q.length; // Update the maximum node count value maxwidth = Math.max(maxwidth, count); // Iterate for all the nodes in // the queue currently while (count-- > 0) { // Dequeue an node from queue let temp = q.shift(); // Enqueue left and right children // of dequeued node if (temp.left != null) { q.push(temp.left); } if (temp.right != null) { q.push(temp.right); } } } return maxwidth; } let 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); root.right.right = new node(8); root.right.right.left = new node(6); root.right.right.right = new node(7); /* Constructed Binary tree is: 1 / \ 2 3 / \ \ 4 5 8 / \ 6 7 */ // Function call document.write("Maximum width is " + maxwidth(root)); </script>
Maximum width is 3
Complexity Analysis: Time Complexity: O(N) where N is the total number of nodes in the tree. In level order traversal, every node of the tree is processed once and hence the complexity due to the level order traversal is O(N) if there are total N nodes in the tree. Therefore, the time complexity is O(N).
Auxiliary Space: O(w) where w is the maximum width of the tree.In level order traversal, a queue is maintained whose maximum size at any moment can go upto the maximum width of the binary tree.
Method 3 (Using Preorder Traversal) In this method, we create a temporary array count[] of size equal to the height of tree. We initialize all values in count as 0. We traverse the tree using preorder traversal and fill the entries in count so that the count array contains count of nodes at each level in Binary Tree.
Below is the implementation of the above idea:
C++
C
Java
Python3
C#
Javascript
// C++ program to calculate width of binary tree#include <bits/stdc++.h>using namespace std; /* A binary tree node has data, pointer to left childand a pointer to right child */class node {public: int data; node* left; node* right;}; // A utility function to get// height of a binary treeint height(node* node); // A utility function to allocate// a new node with given datanode* newNode(int data); // A utility function that returns// maximum value in arr[] of size nint getMax(int arr[], int n); // A function that fills count array// with count of nodes at every// level of given binary treevoid getMaxWidthRecur(node* root, int count[], int level); /* Function to get the maximumwidth of a binary tree*/int getMaxWidth(node* root){ int width; int h = height(root); // Create an array that will // store count of nodes at each level int* count = new int[h]; int level = 0; // Fill the count array using preorder traversal getMaxWidthRecur(root, count, level); // Return the maximum value from count array return getMax(count, h);} // A function that fills count array// with count of nodes at every// level of given binary treevoid getMaxWidthRecur(node* root, int count[], int level){ if (root) { count[level]++; getMaxWidthRecur(root->left, count, level + 1); getMaxWidthRecur(root->right, count, level + 1); }} /* UTILITY FUNCTIONS *//* Compute the "height" of a tree -- the number of nodes along the longest path from the root node down to the farthest leaf node.*/int height(node* node){ if (node == NULL) return 0; else { /* compute the height of each subtree */ int lHeight = height(node->left); int rHeight = height(node->right); /* use the larger one */ return (lHeight > rHeight) ? (lHeight + 1) : (rHeight + 1); }} /* Helper function that allocates a new node with thegiven data and NULL left and right pointers. */node* newNode(int data){ node* Node = new node(); Node->data = data; Node->left = NULL; Node->right = NULL; return (Node);} // Return the maximum value from count arrayint getMax(int arr[], int n){ int max = arr[0]; int i; for (i = 0; i < n; i++) { if (arr[i] > max) max = arr[i]; } return max;} /* Driver code*/int main(){ node* root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); root->right->right = newNode(8); root->right->right->left = newNode(6); root->right->right->right = newNode(7); cout << "Maximum width is " << getMaxWidth(root) << endl; return 0;} // This is code is contributed by rathbhupendra
// C program to calculate width of binary tree#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;}; // A utility function to get height of a binary treeint height(struct node* node); // A utility function to allocate a new node with given datastruct node* newNode(int data); // A utility function that returns maximum value in arr[] of// size nint getMax(int arr[], int n); // A function that fills count array with count of nodes at// every level of given binary treevoid getMaxWidthRecur(struct node* root, int count[], int level); /* Function to get the maximum width of a binary tree*/int getMaxWidth(struct node* root){ int width; int h = height(root); // Create an array that will store count of nodes at // each level int* count = (int*)calloc(sizeof(int), h); int level = 0; // Fill the count array using preorder traversal getMaxWidthRecur(root, count, level); // Return the maximum value from count array return getMax(count, h);} // A function that fills count array with count of nodes at// every level of given binary treevoid getMaxWidthRecur(struct node* root, int count[], int level){ if (root) { count[level]++; getMaxWidthRecur(root->left, count, level + 1); getMaxWidthRecur(root->right, count, level + 1); }} /* UTILITY FUNCTIONS *//* Compute the "height" of a tree -- the number of nodes along the longest path from the root node down to the farthest leaf node.*/int height(struct node* node){ if (node == NULL) return 0; else { /* compute the height of each subtree */ int lHeight = height(node->left); int rHeight = height(node->right); /* use the larger one */ return (lHeight > rHeight) ? (lHeight + 1) : (rHeight + 1); }}/* 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);} // Return the maximum value from count arrayint getMax(int arr[], int n){ int max = arr[0]; int i; for (i = 0; i < n; i++) { if (arr[i] > max) max = arr[i]; } return max;} /* 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); root->right->right = newNode(8); root->right->right->left = newNode(6); root->right->right->right = newNode(7); /* Constructed binary tree is: 1 / \ 2 3 / \ \ 4 5 8 / \ 6 7 */ printf("Maximum width is %d \n", getMaxWidth(root)); getchar(); return 0;}
// Java program to calculate width of binary tree /* A binary tree node has data, pointer to left child and a pointer to right child */class Node { int data; Node left, right; Node(int item) { data = item; left = right = null; }} class BinaryTree { Node root; /* Function to get the maximum width of a binary tree*/ int getMaxWidth(Node node) { int width; int h = height(node); // Create an array that will store count of nodes at // each level int count[] = new int[10]; int level = 0; // Fill the count array using preorder traversal getMaxWidthRecur(node, count, level); // Return the maximum value from count array return getMax(count, h); } // A function that fills count array with count of nodes // at every level of given binary tree void getMaxWidthRecur(Node node, int count[], int level) { if (node != null) { count[level]++; getMaxWidthRecur(node.left, count, level + 1); getMaxWidthRecur(node.right, count, level + 1); } } /* UTILITY FUNCTIONS */ /* Compute the "height" of a tree -- the number of nodes along the longest path from the root node down to the farthest leaf node.*/ int height(Node node) { if (node == null) return 0; else { /* compute the height of each subtree */ int lHeight = height(node.left); int rHeight = height(node.right); /* use the larger one */ return (lHeight > rHeight) ? (lHeight + 1) : (rHeight + 1); } } // Return the maximum value from count array int getMax(int arr[], int n) { int max = arr[0]; int i; for (i = 0; i < n; i++) { if (arr[i] > max) max = arr[i]; } return max; } /* Driver program to test above functions */ public static void main(String args[]) { BinaryTree tree = new BinaryTree(); /* Constructed binary tree is: 1 / \ 2 3 / \ \ 4 5 8 / \ 6 7 */ 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); tree.root.right.right = new Node(8); tree.root.right.right.left = new Node(6); tree.root.right.right.right = new Node(7); System.out.println("Maximum width is " + tree.getMaxWidth(tree.root)); }} // This code has been contributed by Mayank Jaiswal
# Python program to find the maximum width of# binary tree using Preorder Traversal. # A binary tree node class Node: # Constructor to create a new node def __init__(self, data): self.data = data self.left = None self.right = None # Function to get the maximum width of a binary tree def getMaxWidth(root): h = height(root) # Create an array that will store count of nodes at each level count = [0] * h level = 0 # Fill the count array using preorder traversal getMaxWidthRecur(root, count, level) # Return the maximum value from count array return getMax(count, h) # A function that fills count array with count of nodes at every# level of given binary tree def getMaxWidthRecur(root, count, level): if root is not None: count[level] += 1 getMaxWidthRecur(root.left, count, level+1) getMaxWidthRecur(root.right, count, level+1) # UTILITY FUNCTIONS# Compute the "height" of a tree -- the number of# nodes along the longest path from the root node# down to the farthest leaf node. def height(node): if node is None: return 0 else: # compute the height of each subtree lHeight = height(node.left) rHeight = height(node.right) # use the larger one return (lHeight+1) if (lHeight > rHeight) else (rHeight+1) # Return the maximum value from count array def getMax(count, n): max = count[0] for i in range(1, n): if (count[i] > max): max = count[i] return max # Driver program to test above functionroot = Node(1)root.left = Node(2)root.right = Node(3)root.left.left = Node(4)root.left.right = Node(5)root.right.right = Node(8)root.right.right.left = Node(6)root.right.right.right = Node(7) """Constructed binary tree is: 1 / \ 2 3 / \ \ 4 5 8 / \ 6 7""" print ("Maximum width is %d" % (getMaxWidth(root))) # This code is contributed by Naveen Aili
// C# program to calculate width of binary treeusing System; /* A binary tree node has data,pointer to left child anda pointer to right child */public class Node{ public int data; public Node left, right; public Node(int item) { data = item; left = right = null; }} public class BinaryTree{ Node root; /* Function to get the maximum width of a binary tree*/ int getMaxWidth(Node node) { int width; int h = height(node); // Create an array that will store // count of nodes at each level int[] count = new int[10]; int level = 0; // Fill the count array using preorder traversal getMaxWidthRecur(node, count, level); // Return the maximum value from count array return getMax(count, h); } // A function that fills count // array with count of nodes at every // level of given binary tree void getMaxWidthRecur(Node node, int[] count, int level) { if (node != null) { count[level]++; getMaxWidthRecur(node.left, count, level + 1); getMaxWidthRecur(node.right, count, level + 1); } } /* UTILITY FUNCTIONS */ /* Compute the "height" of a tree -- the number of nodes along the longest path from the root node down to the farthest leaf node.*/ int height(Node node) { if (node == null) return 0; else { /* compute the height of each subtree */ int lHeight = height(node.left); int rHeight = height(node.right); /* use the larger one */ return (lHeight > rHeight) ? (lHeight + 1) : (rHeight + 1); } } // Return the maximum value from count array int getMax(int[] arr, int n) { int max = arr[0]; int i; for (i = 0; i < n; i++) { if (arr[i] > max) max = arr[i]; } return max; } /* Driver program to test above functions */ 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); tree.root.right.right = new Node(8); tree.root.right.right.left = new Node(6); tree.root.right.right.right = new Node(7); Console.WriteLine("Maximum width is " + tree.getMaxWidth(tree.root)); }} // This code is contributed Rajput-Ji
<script>// javascript program to calculate width of binary tree /* A binary tree node has data, pointer to left child and a pointer to right child */class Node { constructor(val) { this.data = val; this.left = null; this.right = null; }}var root; /* Function to get the maximum width of a binary tree*/ function getMaxWidth(node) { var width; var h = height(node); // Create an array that will store count of nodes at // each level var count = Array(10).fill(0); var level = 0; // Fill the count array using preorder traversal getMaxWidthRecur(node, count, level); // Return the maximum value from count array return getMax(count, h); } // A function that fills count array with count of nodes // at every level of given binary tree function getMaxWidthRecur(node , count , level) { if (node != null) { count[level]++; getMaxWidthRecur(node.left, count, level + 1); getMaxWidthRecur(node.right, count, level + 1); } } /* UTILITY FUNCTIONS */ /* Compute the "height" of a tree -- the number of nodes avar the longest path from the root node down to the farthest leaf node.*/ function height(node) { if (node == null) return 0; else { /* compute the height of each subtree */ var lHeight = height(node.left); var rHeight = height(node.right); /* use the larger one */ return (lHeight > rHeight) ? (lHeight + 1) : (rHeight + 1); } } // Return the maximum value from count array function getMax(arr , n) { var max = arr[0]; var i; for (i = 0; i < n; i++) { if (arr[i] > max) max = arr[i]; } return max; } /* Driver program to test above functions */ /* Constructed binary tree is: 1 / \ 2 3 / \ \ 4 5 8 / \ 6 7 */ 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); root.right.right = new Node(8); root.right.right.left = new Node(6); root.right.right.right = new Node(7); document.write("Maximum width is " + getMaxWidth(root)); // This code is contributed by Rajput-Ji</script>
Maximum width is 3
Time Complexity: O(n)
YouTubeGeeksforGeeks506K subscribersMaximum width of a binary tree | 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:51•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=tRH8RS99wPk" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
?list=PLqM7alHXFySHCXD7r1J0ky9Zg_GBB1dbk
Thanks to Raja and jagdish for suggesting this method.Please write comments if you find the above code/algorithm incorrect, or find better ways to solve the same problem.
Ayush Jain 7398
shrikanth13
Rajput-Ji
rathbhupendra
princi singh
muskan_garg
todaysgaurav
rameshtravel07
clintra
simranarora5sos
sooda367
sagartomar9927
amartyaghoshgfg
Accolite
Amazon
Flipkart
Microsoft
VMWare
Tree
VMWare
Flipkart
Accolite
Amazon
Microsoft
Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Binary Tree | Set 3 (Types of Binary Tree)
Inorder Tree Traversal without Recursion
Binary Tree | Set 2 (Properties)
Decision Tree
Construct Tree from given Inorder and Preorder traversals
Introduction to Tree Data Structure
Complexity of different operations in Binary tree, Binary Search Tree and AVL tree
Deletion in a Binary Tree
Lowest Common Ancestor in a Binary Tree | Set 1 | [
{
"code": null,
"e": 26645,
"s": 26617,
"text": "\n10 Jan, 2022"
},
{
"code": null,
"e": 26780,
"s": 26645,
"text": "Given a binary tree, write a function to get the maximum width of the given tree. Width of a tree is maximum of widths of all levels. "
},
{
"code": null,
"e": 26822,
"s": 26780,
"text": "Let us consider the below example tree. "
},
{
"code": null,
"e": 26933,
"s": 26822,
"text": " 1\n / \\\n 2 3\n / \\ \\\n 4 5 8 \n / \\\n 6 7"
},
{
"code": null,
"e": 27083,
"s": 26933,
"text": "For the above tree, width of level 1 is 1, width of level 2 is 2, width of level 3 is 3 width of level 4 is 2. So the maximum width of the tree is 3."
},
{
"code": null,
"e": 27369,
"s": 27083,
"text": "Method 1 (Using Level Order Traversal) This method mainly involves two functions. One is to count nodes at a given level (getWidth), and other is to get the maximum width of the tree(getMaxWidth). getMaxWidth() makes use of getWidth() to get the width of all levels starting from root."
},
{
"code": null,
"e": 27570,
"s": 27369,
"text": "/*Function to print level order traversal of tree*/\ngetMaxWidth(tree)\nmaxWdth = 0\nfor i = 1 to height(tree)\n width = getWidth(tree, i);\n if(width > maxWdth) \n maxWdth = width\nreturn maxWidth"
},
{
"code": null,
"e": 27814,
"s": 27570,
"text": "/*Function to get width of a given level */\ngetWidth(tree, level)\nif tree is NULL then return 0;\nif level is 1, then return 1; \nelse if level greater than 1, then\n return getWidth(tree->left, level-1) + \n getWidth(tree->right, level-1);"
},
{
"code": null,
"e": 27861,
"s": 27814,
"text": "Below is the implementation of the above idea:"
},
{
"code": null,
"e": 27865,
"s": 27861,
"text": "C++"
},
{
"code": null,
"e": 27867,
"s": 27865,
"text": "C"
},
{
"code": null,
"e": 27872,
"s": 27867,
"text": "Java"
},
{
"code": null,
"e": 27880,
"s": 27872,
"text": "Python3"
},
{
"code": null,
"e": 27883,
"s": 27880,
"text": "C#"
},
{
"code": null,
"e": 27894,
"s": 27883,
"text": "Javascript"
},
{
"code": "// C++ program to calculate width of binary tree#include <bits/stdc++.h>using namespace std; /* A binary tree node has data, pointer to left childand a pointer to right child */class node {public: int data; node* left; node* right;}; /*Function prototypes*/int getWidth(node* root, int level);int height(node* node);node* newNode(int data); /* Function to get the maximum width of a binary tree*/int getMaxWidth(node* root){ int maxWidth = 0; int width; int h = height(root); int i; /* Get width of each level and compare the width with maximum width so far */ for (i = 1; i <= h; i++) { width = getWidth(root, i); if (width > maxWidth) maxWidth = width; } return maxWidth;} /* Get width of a given level */int getWidth(node* root, int level){ if (root == NULL) return 0; if (level == 1) return 1; else if (level > 1) return getWidth(root->left, level - 1) + getWidth(root->right, level - 1);} /* UTILITY FUNCTIONS *//* Compute the \"height\" of a tree -- the number of nodes along the longest path from the root node down to the farthest leaf node.*/int height(node* node){ if (node == NULL) return 0; else { /* compute the height of each subtree */ int lHeight = height(node->left); int rHeight = height(node->right); /* use the larger one */ return (lHeight > rHeight) ? (lHeight + 1) : (rHeight + 1); }} /* Helper function that allocates a new node with thegiven data and NULL left and right pointers. */node* newNode(int data){ node* Node = new node(); Node->data = data; Node->left = NULL; Node->right = NULL; return (Node);} /* Driver code*/int main(){ node* root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); root->right->right = newNode(8); root->right->right->left = newNode(6); root->right->right->right = newNode(7); /* Constructed binary tree is: 1 / \\ 2 3 / \\ \\ 4 5 8 / \\ 6 7 */ // Function call cout << \"Maximum width is \" << getMaxWidth(root) << endl; return 0;} // This code is contributed by rathbhupendra",
"e": 30246,
"s": 27894,
"text": null
},
{
"code": "// C program to calculate width of binary tree#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;}; /*Function prototypes*/int getWidth(struct node* root, int level);int height(struct node* node);struct node* newNode(int data); /* Function to get the maximum width of a binary tree*/int getMaxWidth(struct node* root){ int maxWidth = 0; int width; int h = height(root); int i; /* Get width of each level and compare the width with maximum width so far */ for (i = 1; i <= h; i++) { width = getWidth(root, i); if (width > maxWidth) maxWidth = width; } return maxWidth;} /* Get width of a given level */int getWidth(struct node* root, int level){ if (root == NULL) return 0; if (level == 1) return 1; else if (level > 1) return getWidth(root->left, level - 1) + getWidth(root->right, level - 1);} /* UTILITY FUNCTIONS *//* Compute the \"height\" of a tree -- the number of nodes along the longest path from the root node down to the farthest leaf node.*/int height(struct node* node){ if (node == NULL) return 0; else { /* compute the height of each subtree */ int lHeight = height(node->left); int rHeight = height(node->right); /* use the larger one */ return (lHeight > rHeight) ? (lHeight + 1) : (rHeight + 1); }}/* 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);}/* Driver code*/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); root->right->right = newNode(8); root->right->right->left = newNode(6); root->right->right->right = newNode(7); /* Constructed binary tree is: 1 / \\ 2 3 / \\ \\ 4 5 8 / \\ 6 7 */ // Function call printf(\"Maximum width is %d \\n\", getMaxWidth(root)); getchar(); return 0;}",
"e": 32671,
"s": 30246,
"text": null
},
{
"code": "// Java program to calculate width of binary tree /* A binary tree node has data, pointer to left child and a pointer to right child */class Node { int data; Node left, right; Node(int item) { data = item; left = right = null; }} class BinaryTree { Node root; /* Function to get the maximum width of a binary tree*/ int getMaxWidth(Node node) { int maxWidth = 0; int width; int h = height(node); int i; /* Get width of each level and compare the width with maximum width so far */ for (i = 1; i <= h; i++) { width = getWidth(node, i); if (width > maxWidth) maxWidth = width; } return maxWidth; } /* Get width of a given level */ int getWidth(Node node, int level) { if (node == null) return 0; if (level == 1) return 1; else if (level > 1) return getWidth(node.left, level - 1) + getWidth(node.right, level - 1); return 0; } /* UTILITY FUNCTIONS */ /* Compute the \"height\" of a tree -- the number of nodes along the longest path from the root node down to the farthest leaf node.*/ int height(Node node) { if (node == null) return 0; else { /* compute the height of each subtree */ int lHeight = height(node.left); int rHeight = height(node.right); /* use the larger one */ return (lHeight > rHeight) ? (lHeight + 1) : (rHeight + 1); } } /* Driver code */ public static void main(String args[]) { BinaryTree tree = new BinaryTree(); /* Constructed binary tree is: 1 / \\ 2 3 / \\ \\ 4 5 8 / \\ 6 7 */ 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); tree.root.right.right = new Node(8); tree.root.right.right.left = new Node(6); tree.root.right.right.right = new Node(7); // Function call System.out.println(\"Maximum width is \" + tree.getMaxWidth(tree.root)); }} // This code has been contributed by Mayank Jaiswal",
"e": 35121,
"s": 32671,
"text": null
},
{
"code": "# Python program to find the maximum width of# binary tree using Level Order Traversal. # A binary tree node class Node: # Constructor to create a new node def __init__(self, data): self.data = data self.left = None self.right = None # Function to get the maximum width of a binary tree def getMaxWidth(root): maxWidth = 0 h = height(root) # Get width of each level and compare the # width with maximum width so far for i in range(1, h+1): width = getWidth(root, i) if (width > maxWidth): maxWidth = width return maxWidth # Get width of a given level def getWidth(root, level): if root is None: return 0 if level == 1: return 1 elif level > 1: return (getWidth(root.left, level-1) + getWidth(root.right, level-1)) # UTILITY FUNCTIONS# Compute the \"height\" of a tree -- the number of# nodes along the longest path from the root node# down to the farthest leaf node. def height(node): if node is None: return 0 else: # compute the height of each subtree lHeight = height(node.left) rHeight = height(node.right) # use the larger one return (lHeight+1) if (lHeight > rHeight) else (rHeight+1) # Driver coderoot = Node(1)root.left = Node(2)root.right = Node(3)root.left.left = Node(4)root.left.right = Node(5)root.right.right = Node(8)root.right.right.left = Node(6)root.right.right.right = Node(7) \"\"\"Constructed binary tree is: 1 / \\ 2 3 / \\ \\4 5 8 / \\ 6 7\"\"\"# Function callprint (\"Maximum width is %d\" % (getMaxWidth(root))) # This code is contributed by Naveen Aili",
"e": 36787,
"s": 35121,
"text": null
},
{
"code": "// C# program to calculate width of binary treeusing System; /* A binary tree node has data, pointer to left childand a pointer to right child */public class Node { public int data; public Node left, right; public Node(int item) { data = item; left = right = null; }} public class BinaryTree { public Node root; /* Function to get the maximum width of a binary tree*/ public virtual int getMaxWidth(Node node) { int maxWidth = 0; int width; int h = height(node); int i; /* Get width of each level and compare the width with maximum width so far */ for (i = 1; i <= h; i++) { width = getWidth(node, i); if (width > maxWidth) { maxWidth = width; } } return maxWidth; } /* Get width of a given level */ public virtual int getWidth(Node node, int level) { if (node == null) { return 0; } if (level == 1) { return 1; } else if (level > 1) { return getWidth(node.left, level - 1) + getWidth(node.right, level - 1); } return 0; } /* UTILITY FUNCTIONS */ /* Compute the \"height\" of a tree -- the number of nodes along the longest path from the root node down to the farthest leaf node.*/ public virtual int height(Node node) { if (node == null) { return 0; } else { /* compute the height of each subtree */ int lHeight = height(node.left); int rHeight = height(node.right); /* use the larger one */ return (lHeight > rHeight) ? (lHeight + 1) : (rHeight + 1); } } /* Driver code */ public static void Main(string[] args) { BinaryTree tree = new BinaryTree(); /* Constructed binary tree is: 1 / \\ 2 3 / \\ \\ 4 5 8 / \\ 6 7 */ 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); tree.root.right.right = new Node(8); tree.root.right.right.left = new Node(6); tree.root.right.right.right = new Node(7); // Function call Console.WriteLine(\"Maximum width is \" + tree.getMaxWidth(tree.root)); }} // This code is contributed by Shrikant13",
"e": 39354,
"s": 36787,
"text": null
},
{
"code": "<script> // JavaScript program to calculate width of binary tree /* A binary tree node has data, pointer to left child and a pointer to right child */class Node { constructor(val) { this.data = val; this.left = null; this.right = null; }} var root; /* Function to get the maximum width of a binary tree*/ function getMaxWidth(node) { var maxWidth = 0; var width; var h = height(node); var i; /* Get width of each level and compare the width with maximum width so far */ for (i = 1; i <= h; i++) { width = getWidth(node, i); if (width > maxWidth) maxWidth = width; } return maxWidth; } /* Get width of a given level */ function getWidth(node , level) { if (node == null) return 0; if (level == 1) return 1; else if (level > 1) return getWidth(node.left, level - 1) + getWidth(node.right, level - 1); return 0; } /* UTILITY FUNCTIONS */ /* Compute the \"height\" of a tree -- the number of nodes along the longest path from the root node down to the farthest leaf node.*/ function height(node) { if (node == null) return 0; else { /* compute the height of each subtree */ var lHeight = height(node.left); var rHeight = height(node.right); /* use the larger one */ return (lHeight > rHeight) ? (lHeight + 1) : (rHeight + 1); } } /* Driver code */ /* Constructed binary tree is: 1 / \\ 2 3 / \\ \\ 4 5 8 / \\ 6 7 */ 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); root.right.right = new Node(8); root.right.right.left = new Node(6); root.right.right.right = new Node(7); // Function call document.write(\"Maximum width is \" + getMaxWidth(root));// This code is contributed by todaysgaurav </script>",
"e": 41642,
"s": 39354,
"text": null
},
{
"code": null,
"e": 41661,
"s": 41642,
"text": "Maximum width is 3"
},
{
"code": null,
"e": 42013,
"s": 41661,
"text": "Time Complexity: O(n2) in the worst case.We can use Queue based level order traversal to optimize the time complexity of this method. The Queue based level order traversal will take O(n) time in worst case. Thanks to Nitish, DivyaC and tech.login.id2 for suggesting this optimization. See their comments for implementation using queue-based traversal."
},
{
"code": null,
"e": 42541,
"s": 42013,
"text": "Method 2 (Using Level Order Traversal with Queue) In this method, we store all the child nodes at the current level in the queue and then count the total number of nodes after the level order traversal for a particular level is completed. Since the queue now contains all the nodes of the next level, we can easily find out the total number of nodes in the next level by finding the size of queue. We then follow the same procedure for the successive levels. We store and update the maximum number of nodes found at each level."
},
{
"code": null,
"e": 42589,
"s": 42541,
"text": "Below is the implementation of the above idea: "
},
{
"code": null,
"e": 42593,
"s": 42589,
"text": "C++"
},
{
"code": null,
"e": 42598,
"s": 42593,
"text": "Java"
},
{
"code": null,
"e": 42606,
"s": 42598,
"text": "Python3"
},
{
"code": null,
"e": 42609,
"s": 42606,
"text": "C#"
},
{
"code": null,
"e": 42620,
"s": 42609,
"text": "Javascript"
},
{
"code": "// A queue based C++ program to find maximum width// of a Binary Tree#include <bits/stdc++.h>using namespace std; /* A binary tree node has data, pointer to left child and a pointer to right child */struct Node { int data; struct Node* left; struct Node* right;}; // Function to find the maximum width of the tree// using level order traversalint maxWidth(struct Node* root){ // Base case if (root == NULL) return 0; // Initialize result int result = 0; // Do Level order traversal keeping track of number // of nodes at every level. queue<Node*> q; q.push(root); while (!q.empty()) { // Get the size of queue when the level order // traversal for one level finishes int count = q.size(); // Update the maximum node count value result = max(count, result); // Iterate for all the nodes in the queue currently while (count--) { // Dequeue an node from queue Node* temp = q.front(); q.pop(); // Enqueue left and right children of // dequeued node if (temp->left != NULL) q.push(temp->left); if (temp->right != NULL) q.push(temp->right); } } return result;} /* 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 = new Node; node->data = data; node->left = node->right = NULL; return (node);} // Driver codeint main(){ struct Node* root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); root->right->right = newNode(8); root->right->right->left = newNode(6); root->right->right->right = newNode(7); /* Constructed Binary tree is: 1 / \\ 2 3 / \\ \\ 4 5 8 / \\ 6 7 */ // Function call cout << \"Maximum width is \" << maxWidth(root) << endl; return 0;} // This code is contributed by Nikhil Kumar// Singh(nickzuck_007)",
"e": 44807,
"s": 42620,
"text": null
},
{
"code": "// Java program to calculate maximum width// of a binary tree using queueimport java.util.LinkedList;import java.util.Queue; public class maxwidthusingqueue{ /* A binary tree node has data, pointer to left child and a pointer to right child */ static class node { int data; node left, right; public node(int data) { this.data = data; } } // Function to find the maximum width of // the tree using level order traversal static int maxwidth(node root) { // Base case if (root == null) return 0; // Initialize result int maxwidth = 0; // Do Level order traversal keeping // track of number of nodes at every level Queue<node> q = new LinkedList<>(); q.add(root); while (!q.isEmpty()) { // Get the size of queue when the level order // traversal for one level finishes int count = q.size(); // Update the maximum node count value maxwidth = Math.max(maxwidth, count); // Iterate for all the nodes in // the queue currently while (count-- > 0) { // Dequeue an node from queue node temp = q.remove(); // Enqueue left and right children // of dequeued node if (temp.left != null) { q.add(temp.left); } if (temp.right != null) { q.add(temp.right); } } } return maxwidth; } // Function call public static void main(String[] args) { node 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); root.right.right = new node(8); root.right.right.left = new node(6); root.right.right.right = new node(7); /* Constructed Binary tree is: 1 / \\ 2 3 / \\ \\ 4 5 8 / \\ 6 7 */ // Function call System.out.println(\"Maximum width = \" + maxwidth(root)); }} // This code is contributed by Rishabh Mahrsee",
"e": 47097,
"s": 44807,
"text": null
},
{
"code": "# Python program to find the maximum width of binary# tree using Level Order Traversal with queue. # A binary tree node class Node: # Constructor to create a new node def __init__(self, data): self.data = data self.left = None self.right = None # Function to get the maximum width of a binary tree def getMaxWidth(root): # base case if root is None: return 0 q = [] maxWidth = 0 q.insert(0, root) while (q != []): # Get the size of queue when the level order # traversal for one level finishes count = len(q) # Update the maximum node count value maxWidth = max(count, maxWidth) while (count is not 0): count = count-1 temp = q[-1] q.pop() if temp.left is not None: q.insert(0, temp.left) if temp.right is not None: q.insert(0, temp.right) return maxWidth # Driver program to test above functionroot = Node(1)root.left = Node(2)root.right = Node(3)root.left.left = Node(4)root.left.right = Node(5)root.right.right = Node(8)root.right.right.left = Node(6)root.right.right.right = Node(7) \"\"\"Constructed binary tree is: 1 / \\ 2 3 / \\ \\ 4 5 8 / \\ 6 7\"\"\"# Function callprint (\"Maximum width is %d\" % (getMaxWidth(root))) # This code is contributed by Naveen Aili",
"e": 48496,
"s": 47097,
"text": null
},
{
"code": "// C# program to calculate maximum width// of a binary tree using queueusing System;using System.Collections.Generic; public class maxwidthusingqueue{ /* A binary tree node has data, pointer to left child and a pointer to right child */ public class node { public int data; public node left, right; public node(int data) { this.data = data; } } // Function to find the maximum width of // the tree using level order traversal static int maxwidth(node root) { // Base case if (root == null) return 0; // Initialize result int maxwidth = 0; // Do Level order traversal keeping // track of number of nodes at every level Queue<node> q = new Queue<node>(); q.Enqueue(root); while (q.Count != 0) { // Get the size of queue when the level order // traversal for one level finishes int count = q.Count; // Update the maximum node count value maxwidth = Math.Max(maxwidth, count); // Iterate for all the nodes in // the queue currently while (count-- > 0) { // Dequeue an node from queue node temp = q.Dequeue(); // Enqueue left and right children // of dequeued node if (temp.left != null) { q.Enqueue(temp.left); } if (temp.right != null) { q.Enqueue(temp.right); } } } return maxwidth; } // Driver code public static void Main(String[] args) { node 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); root.right.right = new node(8); root.right.right.left = new node(6); root.right.right.right = new node(7); /* Constructed Binary tree is: 1 / \\ 2 3 / \\ \\ 4 5 8 / \\ 6 7 */ Console.WriteLine(\"Maximum width = \" + maxwidth(root)); }} // This code is contributed by Princi Singh",
"e": 50752,
"s": 48496,
"text": null
},
{
"code": "<script> // JavaScript program to calculate maximum width // of a binary tree using queue class node { constructor(data) { this.left = null; this.right = null; this.data = data; } } // Function to find the maximum width of // the tree using level order traversal function maxwidth(root) { // Base case if (root == null) return 0; // Initialize result let maxwidth = 0; // Do Level order traversal keeping // track of number of nodes at every level let q = []; q.push(root); while (q.length > 0) { // Get the size of queue when the level order // traversal for one level finishes let count = q.length; // Update the maximum node count value maxwidth = Math.max(maxwidth, count); // Iterate for all the nodes in // the queue currently while (count-- > 0) { // Dequeue an node from queue let temp = q.shift(); // Enqueue left and right children // of dequeued node if (temp.left != null) { q.push(temp.left); } if (temp.right != null) { q.push(temp.right); } } } return maxwidth; } let 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); root.right.right = new node(8); root.right.right.left = new node(6); root.right.right.right = new node(7); /* Constructed Binary tree is: 1 / \\ 2 3 / \\ \\ 4 5 8 / \\ 6 7 */ // Function call document.write(\"Maximum width is \" + maxwidth(root)); </script>",
"e": 52739,
"s": 50752,
"text": null
},
{
"code": null,
"e": 52758,
"s": 52739,
"text": "Maximum width is 3"
},
{
"code": null,
"e": 53064,
"s": 52758,
"text": "Complexity Analysis: Time Complexity: O(N) where N is the total number of nodes in the tree. In level order traversal, every node of the tree is processed once and hence the complexity due to the level order traversal is O(N) if there are total N nodes in the tree. Therefore, the time complexity is O(N)."
},
{
"code": null,
"e": 53259,
"s": 53064,
"text": "Auxiliary Space: O(w) where w is the maximum width of the tree.In level order traversal, a queue is maintained whose maximum size at any moment can go upto the maximum width of the binary tree. "
},
{
"code": null,
"e": 53579,
"s": 53259,
"text": "Method 3 (Using Preorder Traversal) In this method, we create a temporary array count[] of size equal to the height of tree. We initialize all values in count as 0. We traverse the tree using preorder traversal and fill the entries in count so that the count array contains count of nodes at each level in Binary Tree. "
},
{
"code": null,
"e": 53626,
"s": 53579,
"text": "Below is the implementation of the above idea:"
},
{
"code": null,
"e": 53630,
"s": 53626,
"text": "C++"
},
{
"code": null,
"e": 53632,
"s": 53630,
"text": "C"
},
{
"code": null,
"e": 53637,
"s": 53632,
"text": "Java"
},
{
"code": null,
"e": 53645,
"s": 53637,
"text": "Python3"
},
{
"code": null,
"e": 53648,
"s": 53645,
"text": "C#"
},
{
"code": null,
"e": 53659,
"s": 53648,
"text": "Javascript"
},
{
"code": "// C++ program to calculate width of binary tree#include <bits/stdc++.h>using namespace std; /* A binary tree node has data, pointer to left childand a pointer to right child */class node {public: int data; node* left; node* right;}; // A utility function to get// height of a binary treeint height(node* node); // A utility function to allocate// a new node with given datanode* newNode(int data); // A utility function that returns// maximum value in arr[] of size nint getMax(int arr[], int n); // A function that fills count array// with count of nodes at every// level of given binary treevoid getMaxWidthRecur(node* root, int count[], int level); /* Function to get the maximumwidth of a binary tree*/int getMaxWidth(node* root){ int width; int h = height(root); // Create an array that will // store count of nodes at each level int* count = new int[h]; int level = 0; // Fill the count array using preorder traversal getMaxWidthRecur(root, count, level); // Return the maximum value from count array return getMax(count, h);} // A function that fills count array// with count of nodes at every// level of given binary treevoid getMaxWidthRecur(node* root, int count[], int level){ if (root) { count[level]++; getMaxWidthRecur(root->left, count, level + 1); getMaxWidthRecur(root->right, count, level + 1); }} /* UTILITY FUNCTIONS *//* Compute the \"height\" of a tree -- the number of nodes along the longest path from the root node down to the farthest leaf node.*/int height(node* node){ if (node == NULL) return 0; else { /* compute the height of each subtree */ int lHeight = height(node->left); int rHeight = height(node->right); /* use the larger one */ return (lHeight > rHeight) ? (lHeight + 1) : (rHeight + 1); }} /* Helper function that allocates a new node with thegiven data and NULL left and right pointers. */node* newNode(int data){ node* Node = new node(); Node->data = data; Node->left = NULL; Node->right = NULL; return (Node);} // Return the maximum value from count arrayint getMax(int arr[], int n){ int max = arr[0]; int i; for (i = 0; i < n; i++) { if (arr[i] > max) max = arr[i]; } return max;} /* Driver code*/int main(){ node* root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); root->right->right = newNode(8); root->right->right->left = newNode(6); root->right->right->right = newNode(7); cout << \"Maximum width is \" << getMaxWidth(root) << endl; return 0;} // This is code is contributed by rathbhupendra",
"e": 56429,
"s": 53659,
"text": null
},
{
"code": "// C program to calculate width of binary tree#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;}; // A utility function to get height of a binary treeint height(struct node* node); // A utility function to allocate a new node with given datastruct node* newNode(int data); // A utility function that returns maximum value in arr[] of// size nint getMax(int arr[], int n); // A function that fills count array with count of nodes at// every level of given binary treevoid getMaxWidthRecur(struct node* root, int count[], int level); /* Function to get the maximum width of a binary tree*/int getMaxWidth(struct node* root){ int width; int h = height(root); // Create an array that will store count of nodes at // each level int* count = (int*)calloc(sizeof(int), h); int level = 0; // Fill the count array using preorder traversal getMaxWidthRecur(root, count, level); // Return the maximum value from count array return getMax(count, h);} // A function that fills count array with count of nodes at// every level of given binary treevoid getMaxWidthRecur(struct node* root, int count[], int level){ if (root) { count[level]++; getMaxWidthRecur(root->left, count, level + 1); getMaxWidthRecur(root->right, count, level + 1); }} /* UTILITY FUNCTIONS *//* Compute the \"height\" of a tree -- the number of nodes along the longest path from the root node down to the farthest leaf node.*/int height(struct node* node){ if (node == NULL) return 0; else { /* compute the height of each subtree */ int lHeight = height(node->left); int rHeight = height(node->right); /* use the larger one */ return (lHeight > rHeight) ? (lHeight + 1) : (rHeight + 1); }}/* 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);} // Return the maximum value from count arrayint getMax(int arr[], int n){ int max = arr[0]; int i; for (i = 0; i < n; i++) { if (arr[i] > max) max = arr[i]; } return max;} /* 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); root->right->right = newNode(8); root->right->right->left = newNode(6); root->right->right->right = newNode(7); /* Constructed binary tree is: 1 / \\ 2 3 / \\ \\ 4 5 8 / \\ 6 7 */ printf(\"Maximum width is %d \\n\", getMaxWidth(root)); getchar(); return 0;}",
"e": 59497,
"s": 56429,
"text": null
},
{
"code": "// Java program to calculate width of binary tree /* A binary tree node has data, pointer to left child and a pointer to right child */class Node { int data; Node left, right; Node(int item) { data = item; left = right = null; }} class BinaryTree { Node root; /* Function to get the maximum width of a binary tree*/ int getMaxWidth(Node node) { int width; int h = height(node); // Create an array that will store count of nodes at // each level int count[] = new int[10]; int level = 0; // Fill the count array using preorder traversal getMaxWidthRecur(node, count, level); // Return the maximum value from count array return getMax(count, h); } // A function that fills count array with count of nodes // at every level of given binary tree void getMaxWidthRecur(Node node, int count[], int level) { if (node != null) { count[level]++; getMaxWidthRecur(node.left, count, level + 1); getMaxWidthRecur(node.right, count, level + 1); } } /* UTILITY FUNCTIONS */ /* Compute the \"height\" of a tree -- the number of nodes along the longest path from the root node down to the farthest leaf node.*/ int height(Node node) { if (node == null) return 0; else { /* compute the height of each subtree */ int lHeight = height(node.left); int rHeight = height(node.right); /* use the larger one */ return (lHeight > rHeight) ? (lHeight + 1) : (rHeight + 1); } } // Return the maximum value from count array int getMax(int arr[], int n) { int max = arr[0]; int i; for (i = 0; i < n; i++) { if (arr[i] > max) max = arr[i]; } return max; } /* Driver program to test above functions */ public static void main(String args[]) { BinaryTree tree = new BinaryTree(); /* Constructed binary tree is: 1 / \\ 2 3 / \\ \\ 4 5 8 / \\ 6 7 */ 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); tree.root.right.right = new Node(8); tree.root.right.right.left = new Node(6); tree.root.right.right.right = new Node(7); System.out.println(\"Maximum width is \" + tree.getMaxWidth(tree.root)); }} // This code has been contributed by Mayank Jaiswal",
"e": 62243,
"s": 59497,
"text": null
},
{
"code": "# Python program to find the maximum width of# binary tree using Preorder Traversal. # A binary tree node class Node: # Constructor to create a new node def __init__(self, data): self.data = data self.left = None self.right = None # Function to get the maximum width of a binary tree def getMaxWidth(root): h = height(root) # Create an array that will store count of nodes at each level count = [0] * h level = 0 # Fill the count array using preorder traversal getMaxWidthRecur(root, count, level) # Return the maximum value from count array return getMax(count, h) # A function that fills count array with count of nodes at every# level of given binary tree def getMaxWidthRecur(root, count, level): if root is not None: count[level] += 1 getMaxWidthRecur(root.left, count, level+1) getMaxWidthRecur(root.right, count, level+1) # UTILITY FUNCTIONS# Compute the \"height\" of a tree -- the number of# nodes along the longest path from the root node# down to the farthest leaf node. def height(node): if node is None: return 0 else: # compute the height of each subtree lHeight = height(node.left) rHeight = height(node.right) # use the larger one return (lHeight+1) if (lHeight > rHeight) else (rHeight+1) # Return the maximum value from count array def getMax(count, n): max = count[0] for i in range(1, n): if (count[i] > max): max = count[i] return max # Driver program to test above functionroot = Node(1)root.left = Node(2)root.right = Node(3)root.left.left = Node(4)root.left.right = Node(5)root.right.right = Node(8)root.right.right.left = Node(6)root.right.right.right = Node(7) \"\"\"Constructed binary tree is: 1 / \\ 2 3 / \\ \\ 4 5 8 / \\ 6 7\"\"\" print (\"Maximum width is %d\" % (getMaxWidth(root))) # This code is contributed by Naveen Aili",
"e": 64192,
"s": 62243,
"text": null
},
{
"code": "// C# program to calculate width of binary treeusing System; /* A binary tree node has data,pointer to left child anda pointer to right child */public class Node{ public int data; public Node left, right; public Node(int item) { data = item; left = right = null; }} public class BinaryTree{ Node root; /* Function to get the maximum width of a binary tree*/ int getMaxWidth(Node node) { int width; int h = height(node); // Create an array that will store // count of nodes at each level int[] count = new int[10]; int level = 0; // Fill the count array using preorder traversal getMaxWidthRecur(node, count, level); // Return the maximum value from count array return getMax(count, h); } // A function that fills count // array with count of nodes at every // level of given binary tree void getMaxWidthRecur(Node node, int[] count, int level) { if (node != null) { count[level]++; getMaxWidthRecur(node.left, count, level + 1); getMaxWidthRecur(node.right, count, level + 1); } } /* UTILITY FUNCTIONS */ /* Compute the \"height\" of a tree -- the number of nodes along the longest path from the root node down to the farthest leaf node.*/ int height(Node node) { if (node == null) return 0; else { /* compute the height of each subtree */ int lHeight = height(node.left); int rHeight = height(node.right); /* use the larger one */ return (lHeight > rHeight) ? (lHeight + 1) : (rHeight + 1); } } // Return the maximum value from count array int getMax(int[] arr, int n) { int max = arr[0]; int i; for (i = 0; i < n; i++) { if (arr[i] > max) max = arr[i]; } return max; } /* Driver program to test above functions */ 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); tree.root.right.right = new Node(8); tree.root.right.right.left = new Node(6); tree.root.right.right.right = new Node(7); Console.WriteLine(\"Maximum width is \" + tree.getMaxWidth(tree.root)); }} // This code is contributed Rajput-Ji",
"e": 66815,
"s": 64192,
"text": null
},
{
"code": "<script>// javascript program to calculate width of binary tree /* A binary tree node has data, pointer to left child and a pointer to right child */class Node { constructor(val) { this.data = val; this.left = null; this.right = null; }}var root; /* Function to get the maximum width of a binary tree*/ function getMaxWidth(node) { var width; var h = height(node); // Create an array that will store count of nodes at // each level var count = Array(10).fill(0); var level = 0; // Fill the count array using preorder traversal getMaxWidthRecur(node, count, level); // Return the maximum value from count array return getMax(count, h); } // A function that fills count array with count of nodes // at every level of given binary tree function getMaxWidthRecur(node , count , level) { if (node != null) { count[level]++; getMaxWidthRecur(node.left, count, level + 1); getMaxWidthRecur(node.right, count, level + 1); } } /* UTILITY FUNCTIONS */ /* Compute the \"height\" of a tree -- the number of nodes avar the longest path from the root node down to the farthest leaf node.*/ function height(node) { if (node == null) return 0; else { /* compute the height of each subtree */ var lHeight = height(node.left); var rHeight = height(node.right); /* use the larger one */ return (lHeight > rHeight) ? (lHeight + 1) : (rHeight + 1); } } // Return the maximum value from count array function getMax(arr , n) { var max = arr[0]; var i; for (i = 0; i < n; i++) { if (arr[i] > max) max = arr[i]; } return max; } /* Driver program to test above functions */ /* Constructed binary tree is: 1 / \\ 2 3 / \\ \\ 4 5 8 / \\ 6 7 */ 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); root.right.right = new Node(8); root.right.right.left = new Node(6); root.right.right.right = new Node(7); document.write(\"Maximum width is \" + getMaxWidth(root)); // This code is contributed by Rajput-Ji</script>",
"e": 69385,
"s": 66815,
"text": null
},
{
"code": null,
"e": 69404,
"s": 69385,
"text": "Maximum width is 3"
},
{
"code": null,
"e": 69426,
"s": 69404,
"text": "Time Complexity: O(n)"
},
{
"code": null,
"e": 70255,
"s": 69426,
"text": "YouTubeGeeksforGeeks506K subscribersMaximum width of a binary tree | 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:51•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=tRH8RS99wPk\" 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": 70297,
"s": 70255,
"text": "?list=PLqM7alHXFySHCXD7r1J0ky9Zg_GBB1dbk "
},
{
"code": null,
"e": 70468,
"s": 70297,
"text": "Thanks to Raja and jagdish for suggesting this method.Please write comments if you find the above code/algorithm incorrect, or find better ways to solve the same problem."
},
{
"code": null,
"e": 70486,
"s": 70470,
"text": "Ayush Jain 7398"
},
{
"code": null,
"e": 70498,
"s": 70486,
"text": "shrikanth13"
},
{
"code": null,
"e": 70508,
"s": 70498,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 70522,
"s": 70508,
"text": "rathbhupendra"
},
{
"code": null,
"e": 70535,
"s": 70522,
"text": "princi singh"
},
{
"code": null,
"e": 70547,
"s": 70535,
"text": "muskan_garg"
},
{
"code": null,
"e": 70560,
"s": 70547,
"text": "todaysgaurav"
},
{
"code": null,
"e": 70575,
"s": 70560,
"text": "rameshtravel07"
},
{
"code": null,
"e": 70583,
"s": 70575,
"text": "clintra"
},
{
"code": null,
"e": 70599,
"s": 70583,
"text": "simranarora5sos"
},
{
"code": null,
"e": 70608,
"s": 70599,
"text": "sooda367"
},
{
"code": null,
"e": 70623,
"s": 70608,
"text": "sagartomar9927"
},
{
"code": null,
"e": 70639,
"s": 70623,
"text": "amartyaghoshgfg"
},
{
"code": null,
"e": 70648,
"s": 70639,
"text": "Accolite"
},
{
"code": null,
"e": 70655,
"s": 70648,
"text": "Amazon"
},
{
"code": null,
"e": 70664,
"s": 70655,
"text": "Flipkart"
},
{
"code": null,
"e": 70674,
"s": 70664,
"text": "Microsoft"
},
{
"code": null,
"e": 70681,
"s": 70674,
"text": "VMWare"
},
{
"code": null,
"e": 70686,
"s": 70681,
"text": "Tree"
},
{
"code": null,
"e": 70693,
"s": 70686,
"text": "VMWare"
},
{
"code": null,
"e": 70702,
"s": 70693,
"text": "Flipkart"
},
{
"code": null,
"e": 70711,
"s": 70702,
"text": "Accolite"
},
{
"code": null,
"e": 70718,
"s": 70711,
"text": "Amazon"
},
{
"code": null,
"e": 70728,
"s": 70718,
"text": "Microsoft"
},
{
"code": null,
"e": 70733,
"s": 70728,
"text": "Tree"
},
{
"code": null,
"e": 70831,
"s": 70733,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 70874,
"s": 70831,
"text": "Binary Tree | Set 3 (Types of Binary Tree)"
},
{
"code": null,
"e": 70915,
"s": 70874,
"text": "Inorder Tree Traversal without Recursion"
},
{
"code": null,
"e": 70948,
"s": 70915,
"text": "Binary Tree | Set 2 (Properties)"
},
{
"code": null,
"e": 70962,
"s": 70948,
"text": "Decision Tree"
},
{
"code": null,
"e": 71020,
"s": 70962,
"text": "Construct Tree from given Inorder and Preorder traversals"
},
{
"code": null,
"e": 71056,
"s": 71020,
"text": "Introduction to Tree Data Structure"
},
{
"code": null,
"e": 71139,
"s": 71056,
"text": "Complexity of different operations in Binary tree, Binary Search Tree and AVL tree"
},
{
"code": null,
"e": 71165,
"s": 71139,
"text": "Deletion in a Binary Tree"
}
] |
Rotate a 2D array without using extra space | Practice | GeeksforGeeks | Given a N x N 2D matrix Arr representing an image. Rotate the image by 90 degrees (anti-clockwise). You need to do this in place. Note that if you end up using an additional array, you will only receive partial score.
Example 1:
Input:
N = 3
Arr[][] = {{1, 2, 3}
{4, 5, 6}
{7, 8, 9}}
Output:
3 6 9
2 5 8
1 4 7
Explanation: The given matrix is rotated
by 90 degree in anti-clockwise direction.
Example 2:
Input:
N = 4
Arr[][] = {{1, 2, 3, 4}
{5, 6, 7, 8}
{9, 10, 11, 12}
{13, 14, 15, 16}}
Output:
4 8 12 16
3 7 11 15
2 6 10 14
1 5 9 13
Explanation: The given matrix is rotated
by 90 degree in anti-clockwise direction.
Your Task:
You don't need to read input or print anything. Your task is to complete the function rotate() which takes the 2D array of integers arr and n as parameters and returns void. You need to change the array itself.
Expected Time Complexity: O(N*N)
Expected Auxiliary Space: O(1)
Constraints:
1 ≤ N ≤ 1000
1 ≤ Arr[i][j] ≤ 1000
0
siwaniagrawal2 days ago
void rotateMatrix(vector<vector<int>>& arr, int N) {
//swap along diagonal
for(int i = 0; i < N; i++)
{
for(int j = 0; j <= i; j++)
{
swap(arr[i][j],arr[j][i]);
}
}
// swap rows
for(int i=0;i<N/2;i++){
swap(arr[i],arr[N-i-1]);
}
}
+1
velspace012 weeks ago
Java Sol
void rotateMatrix(int Mat[][], int n) {
for(int i=0;i<n;i++){
for(int j=i+1;j<n;j++){
int temp=Mat[i][j];
Mat[i][j]=Mat[j][i];
Mat[j][i]=temp;
}
}
int r=n-1;
for(int i=0;i<n/2;i++){
for(int j=0;j<n;j++){
int temp=Mat[i][j];
Mat[i][j]=Mat[r][j];
Mat[r][j]=temp;
}
r--;
}
}
0
roy99mustang3 weeks ago
Easy python solution:
class Solution:
def rotateMatrix(self,arr, n):
# for better clarity
def swap(a, b, c, d):
arr[a][b], arr[c][d] = arr[c][d], arr[a][b]
# layers till the center
for l in range(n//2):
r = n-1-l
# x iterates over elements
for x in range(l+1, n-l):
# top -> right
swap(x, r, l, x)
# right -> bottom
swap(r, n-1-x, x, r)
# bottom -> left
swap(n-1-x, l, r, n-1-x)
+1
shourya26rathore3 months ago
void rotateMatrix(vector<vector<int>>& mat, int n) {
int s=0,e=n-1,i,j;
for(i = 0; i <n; i++){
for( j = 0; j <i; j++){
swap(mat[i][j],mat[j][i]);
}
}
for( i = 0; i < n; i++){
while(s<=e)
{
swap(mat[s][i],mat[e][i]);
s++;
e--;
}
}
}
0
aniketag7873 months ago
class Solution { void rotateMatrix(int arr[][], int n) { // code here for(int i = 0; i < arr.length; i++){ for(int j = i + 1; j<arr[0].length; j++){ int temp = arr[i][j]; arr[i][j] = arr[j][i]; arr[j][i] = temp; } } for(int i = 0; i < arr.length; i++){ int left = 0; int right = arr[i].length - 1; while(left < right){ int temp = arr[left][i]; arr[left][i] = arr[right][i]; arr[right][i] = temp; left++; right--; } } }}
0
forcer3 months ago
//SIMPLE APPROACH C++:-
for(int i=0;i<n;i++) { reverse(arr[i].begin(),arr[i].end()); } for(int i=0;i<n;i++) { for(int j=0;j<i;j++)swap(arr[i][j],arr[j][i]); }
+1
vivekpatel72023 months ago
void rotateMatrix(vector<vector<int>>& arr, int n) {
for (int i = 0; i < n; i++) {
for (int j = 0; j <= i ; j++) {
swap(arr[i][j] , arr[j][i]);
}
}
// If it is clock wise then just reverse
// for (int i = 0; i < n ; i++) {
// reverse(arr[i].begin(), arr[i].end());
// }
// For anti clockwise
for (int i = 0; i < n; ++i)
{
/* code */
for (int j = 0; j < n / 2; ++j)
{
swap(arr[j][i], arr[n - j - 1][i]);
}
}
}
+1
keshrishivam41144 months ago
def rotateMatrix(self,arr, n): for i in range(n): for j in range(1+i,n): arr[i][j],arr[j][i]=arr[j][i],arr[i][j] for k in range(n//2): for l in range(n): arr[k][l],arr[n-1-k][l]=arr[n-1-k][l],arr[k][l] return arr
0
shiva10904 months ago
for(int i = 0; i < n; i++) { for(int j = 0; j < n; j++) { if(i > j) swap(arr[i][j] , arr[j][i]); } } for(int i = 0; i < n/2; i++) { for(int j = 0; j < n; j++) { swap(arr[i][j] , arr[n-i-1][j]); } }
0
shiva10904 months ago
for(int i = 0; i < n; i++) { for(int j = 0; j < i; j++) { swap(arr[i][j] , arr[j][i]); } } for(int i = 0; i < n/2; i++) { for(int j = 0; j < n; j++) { swap(arr[i][j] , arr[n-i-1][j]); } }
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
want to view the editorial?
Login to access your submissions.
Problem
Contest
Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab. | [
{
"code": null,
"e": 456,
"s": 238,
"text": "Given a N x N 2D matrix Arr representing an image. Rotate the image by 90 degrees (anti-clockwise). You need to do this in place. Note that if you end up using an additional array, you will only receive partial score."
},
{
"code": null,
"e": 467,
"s": 456,
"text": "Example 1:"
},
{
"code": null,
"e": 671,
"s": 467,
"text": "Input:\nN = 3\nArr[][] = {{1, 2, 3}\n {4, 5, 6}\n {7, 8, 9}}\nOutput:\n 3 6 9 \n 2 5 8 \n 1 4 7 \nExplanation: The given matrix is rotated\nby 90 degree in anti-clockwise direction."
},
{
"code": null,
"e": 682,
"s": 671,
"text": "Example 2:"
},
{
"code": null,
"e": 948,
"s": 682,
"text": "Input:\nN = 4\nArr[][] = {{1, 2, 3, 4}\n {5, 6, 7, 8}\n {9, 10, 11, 12}\n {13, 14, 15, 16}}\nOutput:\n 4 8 12 16 \n 3 7 11 15 \n 2 6 10 14 \n 1 5 9 13\nExplanation: The given matrix is rotated\nby 90 degree in anti-clockwise direction.\n"
},
{
"code": null,
"e": 1172,
"s": 948,
"text": "Your Task: \nYou don't need to read input or print anything. Your task is to complete the function rotate() which takes the 2D array of integers arr and n as parameters and returns void. You need to change the array itself."
},
{
"code": null,
"e": 1236,
"s": 1172,
"text": "Expected Time Complexity: O(N*N)\nExpected Auxiliary Space: O(1)"
},
{
"code": null,
"e": 1283,
"s": 1236,
"text": "Constraints:\n1 ≤ N ≤ 1000\n1 ≤ Arr[i][j] ≤ 1000"
},
{
"code": null,
"e": 1285,
"s": 1283,
"text": "0"
},
{
"code": null,
"e": 1309,
"s": 1285,
"text": "siwaniagrawal2 days ago"
},
{
"code": null,
"e": 1598,
"s": 1309,
"text": "\nvoid rotateMatrix(vector<vector<int>>& arr, int N) {\n//swap along diagonal\n for(int i = 0; i < N; i++)\n {\n for(int j = 0; j <= i; j++)\n {\n swap(arr[i][j],arr[j][i]);\n }\n }\n // swap rows\n for(int i=0;i<N/2;i++){\n swap(arr[i],arr[N-i-1]);\n }\n}"
},
{
"code": null,
"e": 1603,
"s": 1600,
"text": "+1"
},
{
"code": null,
"e": 1625,
"s": 1603,
"text": "velspace012 weeks ago"
},
{
"code": null,
"e": 2107,
"s": 1625,
"text": "Java Sol\n void rotateMatrix(int Mat[][], int n) {\n for(int i=0;i<n;i++){\n for(int j=i+1;j<n;j++){\n int temp=Mat[i][j];\n Mat[i][j]=Mat[j][i];\n Mat[j][i]=temp;\n }\n }\n int r=n-1;\n for(int i=0;i<n/2;i++){\n for(int j=0;j<n;j++){\n int temp=Mat[i][j];\n Mat[i][j]=Mat[r][j];\n Mat[r][j]=temp;\n }\n r--;\n }\n }"
},
{
"code": null,
"e": 2109,
"s": 2107,
"text": "0"
},
{
"code": null,
"e": 2133,
"s": 2109,
"text": "roy99mustang3 weeks ago"
},
{
"code": null,
"e": 2155,
"s": 2133,
"text": "Easy python solution:"
},
{
"code": null,
"e": 2698,
"s": 2155,
"text": "class Solution:\n \n def rotateMatrix(self,arr, n):\n # for better clarity\n def swap(a, b, c, d):\n arr[a][b], arr[c][d] = arr[c][d], arr[a][b]\n\n # layers till the center\n for l in range(n//2):\n r = n-1-l\n # x iterates over elements\n for x in range(l+1, n-l):\n # top -> right\n swap(x, r, l, x)\n # right -> bottom\n swap(r, n-1-x, x, r)\n # bottom -> left\n swap(n-1-x, l, r, n-1-x)"
},
{
"code": null,
"e": 2701,
"s": 2698,
"text": "+1"
},
{
"code": null,
"e": 2730,
"s": 2701,
"text": "shourya26rathore3 months ago"
},
{
"code": null,
"e": 3110,
"s": 2730,
"text": "\tvoid rotateMatrix(vector<vector<int>>& mat, int n) {\n\t int s=0,e=n-1,i,j;\n\t for(i = 0; i <n; i++){\n for( j = 0; j <i; j++){\n swap(mat[i][j],mat[j][i]);\n }\n }\n for( i = 0; i < n; i++){\n while(s<=e)\n {\n swap(mat[s][i],mat[e][i]);\n s++;\n e--;\n }\n \n }\n\t}\n"
},
{
"code": null,
"e": 3112,
"s": 3110,
"text": "0"
},
{
"code": null,
"e": 3136,
"s": 3112,
"text": "aniketag7873 months ago"
},
{
"code": null,
"e": 3788,
"s": 3136,
"text": "class Solution { void rotateMatrix(int arr[][], int n) { // code here for(int i = 0; i < arr.length; i++){ for(int j = i + 1; j<arr[0].length; j++){ int temp = arr[i][j]; arr[i][j] = arr[j][i]; arr[j][i] = temp; } } for(int i = 0; i < arr.length; i++){ int left = 0; int right = arr[i].length - 1; while(left < right){ int temp = arr[left][i]; arr[left][i] = arr[right][i]; arr[right][i] = temp; left++; right--; } } }}"
},
{
"code": null,
"e": 3790,
"s": 3788,
"text": "0"
},
{
"code": null,
"e": 3809,
"s": 3790,
"text": "forcer3 months ago"
},
{
"code": null,
"e": 3835,
"s": 3811,
"text": "//SIMPLE APPROACH C++:-"
},
{
"code": null,
"e": 3999,
"s": 3835,
"text": "for(int i=0;i<n;i++) { reverse(arr[i].begin(),arr[i].end()); } for(int i=0;i<n;i++) { for(int j=0;j<i;j++)swap(arr[i][j],arr[j][i]); }"
},
{
"code": null,
"e": 4002,
"s": 3999,
"text": "+1"
},
{
"code": null,
"e": 4029,
"s": 4002,
"text": "vivekpatel72023 months ago"
},
{
"code": null,
"e": 4501,
"s": 4029,
"text": "void rotateMatrix(vector<vector<int>>& arr, int n) {\n for (int i = 0; i < n; i++) {\n for (int j = 0; j <= i ; j++) {\n swap(arr[i][j] , arr[j][i]);\n }\n }\n // If it is clock wise then just reverse\n // for (int i = 0; i < n ; i++) {\n // reverse(arr[i].begin(), arr[i].end());\n // }\n \n // For anti clockwise\n for (int i = 0; i < n; ++i)\n {\n /* code */\n for (int j = 0; j < n / 2; ++j)\n {\n swap(arr[j][i], arr[n - j - 1][i]);\n }\n }\n\n\n}"
},
{
"code": null,
"e": 4504,
"s": 4501,
"text": "+1"
},
{
"code": null,
"e": 4533,
"s": 4504,
"text": "keshrishivam41144 months ago"
},
{
"code": null,
"e": 4812,
"s": 4533,
"text": "def rotateMatrix(self,arr, n): for i in range(n): for j in range(1+i,n): arr[i][j],arr[j][i]=arr[j][i],arr[i][j] for k in range(n//2): for l in range(n): arr[k][l],arr[n-1-k][l]=arr[n-1-k][l],arr[k][l] return arr"
},
{
"code": null,
"e": 4814,
"s": 4812,
"text": "0"
},
{
"code": null,
"e": 4836,
"s": 4814,
"text": "shiva10904 months ago"
},
{
"code": null,
"e": 5136,
"s": 4836,
"text": " for(int i = 0; i < n; i++) { for(int j = 0; j < n; j++) { if(i > j) swap(arr[i][j] , arr[j][i]); } } for(int i = 0; i < n/2; i++) { for(int j = 0; j < n; j++) { swap(arr[i][j] , arr[n-i-1][j]); } } "
},
{
"code": null,
"e": 5138,
"s": 5136,
"text": "0"
},
{
"code": null,
"e": 5160,
"s": 5138,
"text": "shiva10904 months ago"
},
{
"code": null,
"e": 5440,
"s": 5160,
"text": " for(int i = 0; i < n; i++) { for(int j = 0; j < i; j++) { swap(arr[i][j] , arr[j][i]); } } for(int i = 0; i < n/2; i++) { for(int j = 0; j < n; j++) { swap(arr[i][j] , arr[n-i-1][j]); } } "
},
{
"code": null,
"e": 5586,
"s": 5440,
"text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?"
},
{
"code": null,
"e": 5622,
"s": 5586,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 5632,
"s": 5622,
"text": "\nProblem\n"
},
{
"code": null,
"e": 5642,
"s": 5632,
"text": "\nContest\n"
},
{
"code": null,
"e": 5705,
"s": 5642,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 5853,
"s": 5705,
"text": "Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values."
},
{
"code": null,
"e": 6061,
"s": 5853,
"text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints."
},
{
"code": null,
"e": 6167,
"s": 6061,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
Java Program to Implement Hash Trie | 02 Feb, 2021
A trie isn’t something CS students might have spent that much time on in college but it’s really very important for interviews. A trie is a data structure that is actually a type of tree, but it’s often used to store an associative array or a dynamic set where the keys are usually characters or strings, and its position in the tree defines the key with which it is associated. The way that it works is that every successor of a node have a common prefix of the string associated with that node which means each node might store a, just a character as its data but then if we look at the path from the root down to that node, that note is really representing a word or a part of a word, and so what allows us to do is, very quick lookups of a particular kind of word or character.
Java Code:
Importing required module:
Java
import java.io.*;import java.util.*;
Now, we will make a class TrieHash in which we will implement a HashMap, it will also contain two constructors with zero and single array argument, a function to add characters to hash trie and a function to search for the specific string in the hash trie.
Java
class TrieHash { // implementing a HashMap private HashMap<Character, HashMap> origin; // implementing a zero-argument constructor public TrieHash() { // creating a new HashMap origin = new HashMap<Character, HashMap>(); } // implementing another constructor // with an array as a parameter public TrieHash(String[] array) { origin = new HashMap<Character, HashMap>(); // attaching that array string in the trie for (String c : array) attach(c); } // attach function to add character to the trie public void attach(String str) { HashMap<Character, HashMap> node = origin; int i = 0; while (i < str.length()) { // if node already contains that key, // we will simply point that node if (node.containsKey(str.charAt(i))) { node = node.get(str.charAt(i)); } else { // else we will make a new hashmap with // that character and then point it. node.put(str.charAt(i), new HashMap<Character, HashMap>()); node = node.get(str.charAt(i)); } i++; } // putting 0 to end the string node.put('\0', new HashMap<Character, HashMap>(0)); } // function to search for the specific // string in the hash trie public boolean search(String str) { HashMap<Character, HashMap> presentNode = origin; int i = 0; while (i < str.length()) { // will search for that character if it exists if (presentNode.containsKey(str.charAt(i))) { presentNode = presentNode.get(str.charAt(i)); } else { // if the character does not exist // that simply means the whole string // will also not exists, so we will // return false if we find a character // which is not found in the hash trie return false; } i++; } // this will check for the end string, // and if the whole string is found, // it will return true else false if (presentNode.containsKey('\0')) { return true; } else { return false; } }}
Now all the required functions are coded, now we will test those functions with the user input. For this, we will again make a new class to test our hash trie which will prompt the user to enter the words for trie and the word to be searched for.
Java
public class Main { // unreported exception IOException must be caught or // declared to be thrown public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader( System.in)); // this will accepts the words // for the hash trie System.out.println( "Enter the words separated with space to be entered into trie"); // will read the line which user will // provide with space separated words String input = br.readLine(); // it will split all the words // and store them in the string array String[] c = input.split(" "); // now we will use constructor with string array as // parameter and we will pass the user entered // string in that constructor to construct the hash // trie TrieHash trie = new TrieHash(c); System.out.println( "\nEnter the word one by one to be searched in hash-trie"); String word = br.readLine(); // this will search for the word in out trie if (trie.search(word)) { System.out.println("Word Found in the trie"); } else { System.out.println( "Word NOT Found in the trie!"); } }}
Below is the implementation of the problem statement:
Java
import java.io.*;import java.util.*; class TrieHash { // implementing a HashMap private HashMap<Character, HashMap> origin; // implementing a zero-argument constructor public TrieHash() { // creating a new HashMap origin = new HashMap<Character, HashMap>(); } // implementing another constructor // with an array as a parameter public TrieHash(String[] array) { origin = new HashMap<Character, HashMap>(); // attaching that array string in the trie for (String c : array) attach(c); } // attach function to add // character to the trie public void attach(String str) { HashMap<Character, HashMap> node = origin; int i = 0; while (i < str.length()) { // if node already contains thatkey, // we will simply point that node if (node.containsKey(str.charAt(i))) { node = node.get(str.charAt(i)); } else { // else we will make a new hashmap with // that character and then point it. node.put(str.charAt(i), new HashMap<Character, HashMap>()); node = node.get(str.charAt(i)); } i++; } // putting 0 to end the string node.put('\0', new HashMap<Character, HashMap>(0)); } // function to search for the // specific string in the hash trie public boolean search(String str) { HashMap<Character, HashMap> presentNode = origin; int i = 0; while (i < str.length()) { // will search for that character // if it exists if (presentNode.containsKey(str.charAt(i))) { presentNode = presentNode.get(str.charAt(i)); } else { // if the character does notexist that // simply means the whole string will // also not exists, so we will return // false if we find a character which // is not found in the hash trie return false; } i++; } // this will check for the end string, // and if the whole string is found, // it will return true else false if (presentNode.containsKey('\0')) { return true; } else { return false; } }} public class Main { // unreported exception IOException // must be caught or declared to be thrown public static void main(String[] args) throws IOException { // this will accepts the words for the hash trie BufferedReader br = new BufferedReader( new InputStreamReader(System.in)); System.out.println( "Enter the words separated with space to be entered into trie"); // will read the line which user will // provide with space separated words String input = br.readLine(); // it will split all the words and // store them in the string array String[] c = input.split(" "); // now we will use constructor with string // array as parameter and we will pass the // user entered string in that constructor // to construct the hash trie TrieHash trie = new TrieHash(c); System.out.println( "How many words you have to search in the trie"); String count = br.readLine(); int counts = Integer.parseInt(count); for (int i = 0; i < counts; i++) { System.out.println( "\nEnter the word one by one to be searched in hash-trie "); String word = br.readLine(); // this will search for the word in out trie if (trie.search(word)) { System.out.println( "Word Found in the trie"); } else { System.out.println( "Word NOT Found in the trie!"); } } }}
Output1:
Output2:
Picked
Technical Scripter 2020
Java
Java Programs
Technical Scripter
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Introduction to Java
Constructors in Java
Exceptions in Java
Generics in Java
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
Factory method design pattern in Java
Java Program to Remove Duplicate Elements From the Array | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n02 Feb, 2021"
},
{
"code": null,
"e": 810,
"s": 28,
"text": "A trie isn’t something CS students might have spent that much time on in college but it’s really very important for interviews. A trie is a data structure that is actually a type of tree, but it’s often used to store an associative array or a dynamic set where the keys are usually characters or strings, and its position in the tree defines the key with which it is associated. The way that it works is that every successor of a node have a common prefix of the string associated with that node which means each node might store a, just a character as its data but then if we look at the path from the root down to that node, that note is really representing a word or a part of a word, and so what allows us to do is, very quick lookups of a particular kind of word or character."
},
{
"code": null,
"e": 821,
"s": 810,
"text": "Java Code:"
},
{
"code": null,
"e": 848,
"s": 821,
"text": "Importing required module:"
},
{
"code": null,
"e": 853,
"s": 848,
"text": "Java"
},
{
"code": "import java.io.*;import java.util.*;",
"e": 890,
"s": 853,
"text": null
},
{
"code": null,
"e": 1147,
"s": 890,
"text": "Now, we will make a class TrieHash in which we will implement a HashMap, it will also contain two constructors with zero and single array argument, a function to add characters to hash trie and a function to search for the specific string in the hash trie."
},
{
"code": null,
"e": 1152,
"s": 1147,
"text": "Java"
},
{
"code": "class TrieHash { // implementing a HashMap private HashMap<Character, HashMap> origin; // implementing a zero-argument constructor public TrieHash() { // creating a new HashMap origin = new HashMap<Character, HashMap>(); } // implementing another constructor // with an array as a parameter public TrieHash(String[] array) { origin = new HashMap<Character, HashMap>(); // attaching that array string in the trie for (String c : array) attach(c); } // attach function to add character to the trie public void attach(String str) { HashMap<Character, HashMap> node = origin; int i = 0; while (i < str.length()) { // if node already contains that key, // we will simply point that node if (node.containsKey(str.charAt(i))) { node = node.get(str.charAt(i)); } else { // else we will make a new hashmap with // that character and then point it. node.put(str.charAt(i), new HashMap<Character, HashMap>()); node = node.get(str.charAt(i)); } i++; } // putting 0 to end the string node.put('\\0', new HashMap<Character, HashMap>(0)); } // function to search for the specific // string in the hash trie public boolean search(String str) { HashMap<Character, HashMap> presentNode = origin; int i = 0; while (i < str.length()) { // will search for that character if it exists if (presentNode.containsKey(str.charAt(i))) { presentNode = presentNode.get(str.charAt(i)); } else { // if the character does not exist // that simply means the whole string // will also not exists, so we will // return false if we find a character // which is not found in the hash trie return false; } i++; } // this will check for the end string, // and if the whole string is found, // it will return true else false if (presentNode.containsKey('\\0')) { return true; } else { return false; } }}",
"e": 3543,
"s": 1152,
"text": null
},
{
"code": null,
"e": 3792,
"s": 3545,
"text": "Now all the required functions are coded, now we will test those functions with the user input. For this, we will again make a new class to test our hash trie which will prompt the user to enter the words for trie and the word to be searched for."
},
{
"code": null,
"e": 3797,
"s": 3792,
"text": "Java"
},
{
"code": "public class Main { // unreported exception IOException must be caught or // declared to be thrown public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader( System.in)); // this will accepts the words // for the hash trie System.out.println( \"Enter the words separated with space to be entered into trie\"); // will read the line which user will // provide with space separated words String input = br.readLine(); // it will split all the words // and store them in the string array String[] c = input.split(\" \"); // now we will use constructor with string array as // parameter and we will pass the user entered // string in that constructor to construct the hash // trie TrieHash trie = new TrieHash(c); System.out.println( \"\\nEnter the word one by one to be searched in hash-trie\"); String word = br.readLine(); // this will search for the word in out trie if (trie.search(word)) { System.out.println(\"Word Found in the trie\"); } else { System.out.println( \"Word NOT Found in the trie!\"); } }}",
"e": 5140,
"s": 3797,
"text": null
},
{
"code": null,
"e": 5196,
"s": 5142,
"text": "Below is the implementation of the problem statement:"
},
{
"code": null,
"e": 5201,
"s": 5196,
"text": "Java"
},
{
"code": "import java.io.*;import java.util.*; class TrieHash { // implementing a HashMap private HashMap<Character, HashMap> origin; // implementing a zero-argument constructor public TrieHash() { // creating a new HashMap origin = new HashMap<Character, HashMap>(); } // implementing another constructor // with an array as a parameter public TrieHash(String[] array) { origin = new HashMap<Character, HashMap>(); // attaching that array string in the trie for (String c : array) attach(c); } // attach function to add // character to the trie public void attach(String str) { HashMap<Character, HashMap> node = origin; int i = 0; while (i < str.length()) { // if node already contains thatkey, // we will simply point that node if (node.containsKey(str.charAt(i))) { node = node.get(str.charAt(i)); } else { // else we will make a new hashmap with // that character and then point it. node.put(str.charAt(i), new HashMap<Character, HashMap>()); node = node.get(str.charAt(i)); } i++; } // putting 0 to end the string node.put('\\0', new HashMap<Character, HashMap>(0)); } // function to search for the // specific string in the hash trie public boolean search(String str) { HashMap<Character, HashMap> presentNode = origin; int i = 0; while (i < str.length()) { // will search for that character // if it exists if (presentNode.containsKey(str.charAt(i))) { presentNode = presentNode.get(str.charAt(i)); } else { // if the character does notexist that // simply means the whole string will // also not exists, so we will return // false if we find a character which // is not found in the hash trie return false; } i++; } // this will check for the end string, // and if the whole string is found, // it will return true else false if (presentNode.containsKey('\\0')) { return true; } else { return false; } }} public class Main { // unreported exception IOException // must be caught or declared to be thrown public static void main(String[] args) throws IOException { // this will accepts the words for the hash trie BufferedReader br = new BufferedReader( new InputStreamReader(System.in)); System.out.println( \"Enter the words separated with space to be entered into trie\"); // will read the line which user will // provide with space separated words String input = br.readLine(); // it will split all the words and // store them in the string array String[] c = input.split(\" \"); // now we will use constructor with string // array as parameter and we will pass the // user entered string in that constructor // to construct the hash trie TrieHash trie = new TrieHash(c); System.out.println( \"How many words you have to search in the trie\"); String count = br.readLine(); int counts = Integer.parseInt(count); for (int i = 0; i < counts; i++) { System.out.println( \"\\nEnter the word one by one to be searched in hash-trie \"); String word = br.readLine(); // this will search for the word in out trie if (trie.search(word)) { System.out.println( \"Word Found in the trie\"); } else { System.out.println( \"Word NOT Found in the trie!\"); } } }}",
"e": 9234,
"s": 5201,
"text": null
},
{
"code": null,
"e": 9243,
"s": 9234,
"text": "Output1:"
},
{
"code": null,
"e": 9252,
"s": 9243,
"text": "Output2:"
},
{
"code": null,
"e": 9259,
"s": 9252,
"text": "Picked"
},
{
"code": null,
"e": 9283,
"s": 9259,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 9288,
"s": 9283,
"text": "Java"
},
{
"code": null,
"e": 9302,
"s": 9288,
"text": "Java Programs"
},
{
"code": null,
"e": 9321,
"s": 9302,
"text": "Technical Scripter"
},
{
"code": null,
"e": 9326,
"s": 9321,
"text": "Java"
},
{
"code": null,
"e": 9424,
"s": 9326,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 9439,
"s": 9424,
"text": "Stream In Java"
},
{
"code": null,
"e": 9460,
"s": 9439,
"text": "Introduction to Java"
},
{
"code": null,
"e": 9481,
"s": 9460,
"text": "Constructors in Java"
},
{
"code": null,
"e": 9500,
"s": 9481,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 9517,
"s": 9500,
"text": "Generics in Java"
},
{
"code": null,
"e": 9543,
"s": 9517,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 9577,
"s": 9543,
"text": "Convert Double to Integer in Java"
},
{
"code": null,
"e": 9624,
"s": 9577,
"text": "Implementing a Linked List in Java using Class"
},
{
"code": null,
"e": 9662,
"s": 9624,
"text": "Factory method design pattern in Java"
}
] |
CSS - Using Images | Images play an important role in any webpage. Though it is not recommended to include a lot of images, but it is still important to use good images wherever required.
CSS plays a good role to control image display. You can set the following image properties using CSS.
The border property is used to set the width of an image border.
The border property is used to set the width of an image border.
The height property is used to set the height of an image.
The height property is used to set the height of an image.
The width property is used to set the width of an image.
The width property is used to set the width of an image.
The -moz-opacity property is used to set the opacity of an image.
The -moz-opacity property is used to set the opacity of an image.
The border property of an image is used to set the width of an image border. This property can have a value in length or in %.
A width of zero pixels means no border.
Here is the example −
<html>
<head>
</head>
<body>
<img style = "border:0px;" src = "/css/images/logo.png" />
<br />
<img style = "border:3px dashed red;" src = "/css/images/logo.png" />
</body>
</html>
It will produce the following result −
The height property of an image is used to set the height of an image. This property can have a value in length or in %. While giving value in %, it applies it in respect of the box in which an image is available.
Here is an example −
<html>
<head>
</head>
<body>
<img style = "border:1px solid red; height:100px;" src = "/css/images/logo.png" />
<br />
<img style = "border:1px solid red; height:50%;" src = "/css/images/logo.png" />
</body>
</html>
It will produce the following result −
The width property of an image is used to set the width of an image. This property can have a value in length or in %. While giving value in %, it applies it in respect of the box in which an image is available.
Here is an example −
<html>
<head>
</head>
<body>
<img style = "border:1px solid red; width:150px;" src = "/css/images/logo.png" />
<br />
<img style = "border:1px solid red; width:100%;" src = "/css/images/logo.png" />
</body>
</html>
It will produce the following result −
The -moz-opacity property of an image is used to set the opacity of an image. This property is used to create a transparent image in Mozilla. IE uses filter:alpha(opacity=x) to create transparent images.
In Mozilla (-moz-opacity:x) x can be a value from 0.0 - 1.0. A lower value makes the element more transparent (The same things goes for the CSS3-valid syntax opacity:x).
In IE (filter:alpha(opacity=x)) x can be a value from 0 - 100. A lower value makes the element more transparent.
Here is an example −
<html>
<head>
</head>
<body>
<img style = "border:1px solid red; -moz-opacity:0.4; filter:alpha(opacity=40);" src = "/css/images/logo.png" />
</body>
</html>
It will produce the following result − | [
{
"code": null,
"e": 2927,
"s": 2760,
"text": "Images play an important role in any webpage. Though it is not recommended to include a lot of images, but it is still important to use good images wherever required."
},
{
"code": null,
"e": 3029,
"s": 2927,
"text": "CSS plays a good role to control image display. You can set the following image properties using CSS."
},
{
"code": null,
"e": 3094,
"s": 3029,
"text": "The border property is used to set the width of an image border."
},
{
"code": null,
"e": 3159,
"s": 3094,
"text": "The border property is used to set the width of an image border."
},
{
"code": null,
"e": 3218,
"s": 3159,
"text": "The height property is used to set the height of an image."
},
{
"code": null,
"e": 3277,
"s": 3218,
"text": "The height property is used to set the height of an image."
},
{
"code": null,
"e": 3334,
"s": 3277,
"text": "The width property is used to set the width of an image."
},
{
"code": null,
"e": 3391,
"s": 3334,
"text": "The width property is used to set the width of an image."
},
{
"code": null,
"e": 3457,
"s": 3391,
"text": "The -moz-opacity property is used to set the opacity of an image."
},
{
"code": null,
"e": 3523,
"s": 3457,
"text": "The -moz-opacity property is used to set the opacity of an image."
},
{
"code": null,
"e": 3650,
"s": 3523,
"text": "The border property of an image is used to set the width of an image border. This property can have a value in length or in %."
},
{
"code": null,
"e": 3690,
"s": 3650,
"text": "A width of zero pixels means no border."
},
{
"code": null,
"e": 3712,
"s": 3690,
"text": "Here is the example −"
},
{
"code": null,
"e": 3925,
"s": 3712,
"text": "<html>\n <head>\n </head>\n\n <body>\n <img style = \"border:0px;\" src = \"/css/images/logo.png\" />\n <br />\n <img style = \"border:3px dashed red;\" src = \"/css/images/logo.png\" />\n </body>\n</html> "
},
{
"code": null,
"e": 3964,
"s": 3925,
"text": "It will produce the following result −"
},
{
"code": null,
"e": 4178,
"s": 3964,
"text": "The height property of an image is used to set the height of an image. This property can have a value in length or in %. While giving value in %, it applies it in respect of the box in which an image is available."
},
{
"code": null,
"e": 4199,
"s": 4178,
"text": "Here is an example −"
},
{
"code": null,
"e": 4447,
"s": 4199,
"text": "<html>\n <head>\n </head>\n\n <body>\n <img style = \"border:1px solid red; height:100px;\" src = \"/css/images/logo.png\" />\n <br />\n <img style = \"border:1px solid red; height:50%;\" src = \"/css/images/logo.png\" />\n </body>\n</html> "
},
{
"code": null,
"e": 4486,
"s": 4447,
"text": "It will produce the following result −"
},
{
"code": null,
"e": 4698,
"s": 4486,
"text": "The width property of an image is used to set the width of an image. This property can have a value in length or in %. While giving value in %, it applies it in respect of the box in which an image is available."
},
{
"code": null,
"e": 4719,
"s": 4698,
"text": "Here is an example −"
},
{
"code": null,
"e": 4966,
"s": 4719,
"text": "<html>\n <head>\n </head>\n\n <body>\n <img style = \"border:1px solid red; width:150px;\" src = \"/css/images/logo.png\" />\n <br />\n <img style = \"border:1px solid red; width:100%;\" src = \"/css/images/logo.png\" />\n </body>\n</html> "
},
{
"code": null,
"e": 5005,
"s": 4966,
"text": "It will produce the following result −"
},
{
"code": null,
"e": 5209,
"s": 5005,
"text": "The -moz-opacity property of an image is used to set the opacity of an image. This property is used to create a transparent image in Mozilla. IE uses filter:alpha(opacity=x) to create transparent images."
},
{
"code": null,
"e": 5379,
"s": 5209,
"text": "In Mozilla (-moz-opacity:x) x can be a value from 0.0 - 1.0. A lower value makes the element more transparent (The same things goes for the CSS3-valid syntax opacity:x)."
},
{
"code": null,
"e": 5492,
"s": 5379,
"text": "In IE (filter:alpha(opacity=x)) x can be a value from 0 - 100. A lower value makes the element more transparent."
},
{
"code": null,
"e": 5513,
"s": 5492,
"text": "Here is an example −"
},
{
"code": null,
"e": 5691,
"s": 5513,
"text": "<html>\n <head>\n </head>\n\n <body>\n <img style = \"border:1px solid red; -moz-opacity:0.4; filter:alpha(opacity=40);\" src = \"/css/images/logo.png\" />\n </body>\n</html> "
}
] |
How to Add External Library in Android Studio? | 05 May, 2021
Android Studio is the official IDE (Integrated Development Environment) for Android app development and it is based on JetBrains’ IntelliJ IDEA software. Android Studio provides many excellent features that enhance productivity when building Android apps. In this article, we will learn how to add external libraries to our android project.
Let us have an external library that we want to use in our project i.e a jar file.
Create a new project named GFGAddLib.
Now, our project has been created.
Now click on the Android drop-down and change to Project files.
Click on Project files.
Copy the jar file to the libs folder.
Here, you can see our added jar file under the libs folder. Right-click on the jar file and select Add As Library.
Now come back to the Android tab, you can see that your library has been already declared in build.grade (Module: GFGAddLib.app)
The library is successfully added to our project.
Let us have a new project GFGAddLib2 and we want to use the same common-lang3-3.4.jar library for this project.
Create a new Android Module. Go to the File -> New -> New Module
Select Import JAR/.AAR Package and click Next.
Select the location of your JAR file and click on Finish.
Module library has been created. Next, we need to declare the dependency of the main project on the newly created module. Now go to the File and click on Project structure.
Now click on circled + sign and select Module Dependency
Click OK, a new dialogue box will appear, select the jar file and click OK.
Click OK once again and our Jar file is added. You can check your module which has been declared in build.grade (Module: GFGAddLib.app).
Android-Studio
Picked
Android
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n05 May, 2021"
},
{
"code": null,
"e": 395,
"s": 54,
"text": "Android Studio is the official IDE (Integrated Development Environment) for Android app development and it is based on JetBrains’ IntelliJ IDEA software. Android Studio provides many excellent features that enhance productivity when building Android apps. In this article, we will learn how to add external libraries to our android project."
},
{
"code": null,
"e": 478,
"s": 395,
"text": "Let us have an external library that we want to use in our project i.e a jar file."
},
{
"code": null,
"e": 516,
"s": 478,
"text": "Create a new project named GFGAddLib."
},
{
"code": null,
"e": 551,
"s": 516,
"text": "Now, our project has been created."
},
{
"code": null,
"e": 615,
"s": 551,
"text": "Now click on the Android drop-down and change to Project files."
},
{
"code": null,
"e": 639,
"s": 615,
"text": "Click on Project files."
},
{
"code": null,
"e": 677,
"s": 639,
"text": "Copy the jar file to the libs folder."
},
{
"code": null,
"e": 792,
"s": 677,
"text": "Here, you can see our added jar file under the libs folder. Right-click on the jar file and select Add As Library."
},
{
"code": null,
"e": 921,
"s": 792,
"text": "Now come back to the Android tab, you can see that your library has been already declared in build.grade (Module: GFGAddLib.app)"
},
{
"code": null,
"e": 971,
"s": 921,
"text": "The library is successfully added to our project."
},
{
"code": null,
"e": 1083,
"s": 971,
"text": "Let us have a new project GFGAddLib2 and we want to use the same common-lang3-3.4.jar library for this project."
},
{
"code": null,
"e": 1148,
"s": 1083,
"text": "Create a new Android Module. Go to the File -> New -> New Module"
},
{
"code": null,
"e": 1195,
"s": 1148,
"text": "Select Import JAR/.AAR Package and click Next."
},
{
"code": null,
"e": 1253,
"s": 1195,
"text": "Select the location of your JAR file and click on Finish."
},
{
"code": null,
"e": 1426,
"s": 1253,
"text": "Module library has been created. Next, we need to declare the dependency of the main project on the newly created module. Now go to the File and click on Project structure."
},
{
"code": null,
"e": 1483,
"s": 1426,
"text": "Now click on circled + sign and select Module Dependency"
},
{
"code": null,
"e": 1559,
"s": 1483,
"text": "Click OK, a new dialogue box will appear, select the jar file and click OK."
},
{
"code": null,
"e": 1696,
"s": 1559,
"text": "Click OK once again and our Jar file is added. You can check your module which has been declared in build.grade (Module: GFGAddLib.app)."
},
{
"code": null,
"e": 1711,
"s": 1696,
"text": "Android-Studio"
},
{
"code": null,
"e": 1718,
"s": 1711,
"text": "Picked"
},
{
"code": null,
"e": 1726,
"s": 1718,
"text": "Android"
},
{
"code": null,
"e": 1734,
"s": 1726,
"text": "Android"
}
] |
Sierpinski Triangle using Graphics | 23 Oct, 2019
Sierpinski triangle is a fractal and attractive fixed set with the overall shape of an equilateral triangle. It subdivides recursively into smaller triangles.
Approach:
In the given segment of codes, a triangle is made and then draws out three other adjacent small triangles till the terminating condition which checks out whether the height of the triangle is less than 5 pixels returns true.
We only need to verify whether a given triangle is smaller than 5 pixels since beyond that the triangles would start converging at fixed points.
A counter colorVal is defined for in response to the aesthetic need of the triangle and in all, it cycles through all the available colours by iterating every triangle set.
Using this methodology we can also further implement a fractal zoom and hypothetically provide an infinite zoom later.
Below is the implementation of the above approach:
// C++ code to implement// Sierpinski Triangle using Graphics #include <math.h>#include <stdlib.h>#include <winbgim.h> #define Y 900#define X 1600 // Defining a function to draw a triangle// with thickness 'delta'void triangle(float x, float y, float h, int colorVal){ setcolor(colorVal % 15 + 1); for (float delta = 0; delta > -5; delta -= 1) { line(x - (h + delta) / sqrt(3), y - (h + delta) / 3, x + (h + delta) / sqrt(3), y - (h + delta) / 3); line(x - (h + delta) / sqrt(3), y - (h + delta) / 3, x, y + 2 * (h + delta) / 3); line(x, y + 2 * (h + delta) / 3, x + (h + delta) / sqrt(3), y - (h + delta) / 3); }} // Defining a function to draw// an inverted triangle// with thickness 'delta'void trianglev2(float x, float y, float h, int colorVal){ setcolor(colorVal % 15 + 1); for (float delta = 0; delta > -1 + 5; delta -= 1) { line(x - (h + delta) / sqrt(3), y + (h + delta) / 3, x + (h + delta) / sqrt(3), y + (h + delta) / 3); line(x - (h + delta) / sqrt(3), y + (h + delta) / 3, x, y - 2 * (h + delta) / 3); line(x, y - 2 * (h + delta) / 3, x + (h + delta) / sqrt(3), y + (h + delta) / 3); }} // A recursive function to draw out// three adjacent smaller triangles// while the height is greater than 5 pixels.int drawTriangles(float x = X / 2, float y = 2 * Y / 3, float h = Y / 2, int colorVal = 0){ if (h < 5) { return 0; } if (x > 0 && y > 0 && x < X && y < Y) { triangle(x, y, h, colorVal); } drawTriangles(x, y - 2 * h / 3, h / 2, colorVal + 1); drawTriangles(x - h / sqrt(3), y + h / 3, h / 2, colorVal + 1); drawTriangles(x + h / sqrt(3), y + h / 3, h / 2, colorVal + 1); return 0;} // Driver codeint main(){ initwindow(X, Y); trianglev2(X / 2, 2 * Y / 3, Y, 2); drawTriangles(); getch(); closegraph(); return 0;}
Output:
computer-graphics
pattern-printing
Advanced Computer Subject
pattern-printing
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
System Design Tutorial
ML | Linear Regression
Docker - COPY Instruction
Reinforcement learning
Supervised and Unsupervised learning
Decision Tree Introduction with example
Getting started with Machine Learning
How to Run a Python Script using Docker?
ML | Monte Carlo Tree Search (MCTS)
Copying Files to and from Docker Containers | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n23 Oct, 2019"
},
{
"code": null,
"e": 187,
"s": 28,
"text": "Sierpinski triangle is a fractal and attractive fixed set with the overall shape of an equilateral triangle. It subdivides recursively into smaller triangles."
},
{
"code": null,
"e": 197,
"s": 187,
"text": "Approach:"
},
{
"code": null,
"e": 422,
"s": 197,
"text": "In the given segment of codes, a triangle is made and then draws out three other adjacent small triangles till the terminating condition which checks out whether the height of the triangle is less than 5 pixels returns true."
},
{
"code": null,
"e": 567,
"s": 422,
"text": "We only need to verify whether a given triangle is smaller than 5 pixels since beyond that the triangles would start converging at fixed points."
},
{
"code": null,
"e": 740,
"s": 567,
"text": "A counter colorVal is defined for in response to the aesthetic need of the triangle and in all, it cycles through all the available colours by iterating every triangle set."
},
{
"code": null,
"e": 859,
"s": 740,
"text": "Using this methodology we can also further implement a fractal zoom and hypothetically provide an infinite zoom later."
},
{
"code": null,
"e": 910,
"s": 859,
"text": "Below is the implementation of the above approach:"
},
{
"code": "// C++ code to implement// Sierpinski Triangle using Graphics #include <math.h>#include <stdlib.h>#include <winbgim.h> #define Y 900#define X 1600 // Defining a function to draw a triangle// with thickness 'delta'void triangle(float x, float y, float h, int colorVal){ setcolor(colorVal % 15 + 1); for (float delta = 0; delta > -5; delta -= 1) { line(x - (h + delta) / sqrt(3), y - (h + delta) / 3, x + (h + delta) / sqrt(3), y - (h + delta) / 3); line(x - (h + delta) / sqrt(3), y - (h + delta) / 3, x, y + 2 * (h + delta) / 3); line(x, y + 2 * (h + delta) / 3, x + (h + delta) / sqrt(3), y - (h + delta) / 3); }} // Defining a function to draw// an inverted triangle// with thickness 'delta'void trianglev2(float x, float y, float h, int colorVal){ setcolor(colorVal % 15 + 1); for (float delta = 0; delta > -1 + 5; delta -= 1) { line(x - (h + delta) / sqrt(3), y + (h + delta) / 3, x + (h + delta) / sqrt(3), y + (h + delta) / 3); line(x - (h + delta) / sqrt(3), y + (h + delta) / 3, x, y - 2 * (h + delta) / 3); line(x, y - 2 * (h + delta) / 3, x + (h + delta) / sqrt(3), y + (h + delta) / 3); }} // A recursive function to draw out// three adjacent smaller triangles// while the height is greater than 5 pixels.int drawTriangles(float x = X / 2, float y = 2 * Y / 3, float h = Y / 2, int colorVal = 0){ if (h < 5) { return 0; } if (x > 0 && y > 0 && x < X && y < Y) { triangle(x, y, h, colorVal); } drawTriangles(x, y - 2 * h / 3, h / 2, colorVal + 1); drawTriangles(x - h / sqrt(3), y + h / 3, h / 2, colorVal + 1); drawTriangles(x + h / sqrt(3), y + h / 3, h / 2, colorVal + 1); return 0;} // Driver codeint main(){ initwindow(X, Y); trianglev2(X / 2, 2 * Y / 3, Y, 2); drawTriangles(); getch(); closegraph(); return 0;}",
"e": 3226,
"s": 910,
"text": null
},
{
"code": null,
"e": 3234,
"s": 3226,
"text": "Output:"
},
{
"code": null,
"e": 3252,
"s": 3234,
"text": "computer-graphics"
},
{
"code": null,
"e": 3269,
"s": 3252,
"text": "pattern-printing"
},
{
"code": null,
"e": 3295,
"s": 3269,
"text": "Advanced Computer Subject"
},
{
"code": null,
"e": 3312,
"s": 3295,
"text": "pattern-printing"
},
{
"code": null,
"e": 3410,
"s": 3312,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3433,
"s": 3410,
"text": "System Design Tutorial"
},
{
"code": null,
"e": 3456,
"s": 3433,
"text": "ML | Linear Regression"
},
{
"code": null,
"e": 3482,
"s": 3456,
"text": "Docker - COPY Instruction"
},
{
"code": null,
"e": 3505,
"s": 3482,
"text": "Reinforcement learning"
},
{
"code": null,
"e": 3542,
"s": 3505,
"text": "Supervised and Unsupervised learning"
},
{
"code": null,
"e": 3582,
"s": 3542,
"text": "Decision Tree Introduction with example"
},
{
"code": null,
"e": 3620,
"s": 3582,
"text": "Getting started with Machine Learning"
},
{
"code": null,
"e": 3661,
"s": 3620,
"text": "How to Run a Python Script using Docker?"
},
{
"code": null,
"e": 3697,
"s": 3661,
"text": "ML | Monte Carlo Tree Search (MCTS)"
}
] |
Get the id after INSERT into MySQL database using Python | 11 Dec, 2020
Prerequisites: MySQL, mysql-connector for python
The task here is to draft a Python program that works with SQL support to connect data. Whenever insertion into the database takes place, the ID of the row inserted will be printed. To connect python with the database we are using MySQL connector. The work of mysql-connector is to provide access to MySQL Driver to the required language. Thus, it generates a connection between the programming language and MySQL Server.
As the name suggests, it inserts data into the database. Certain rules need to be followed while using the insert command. The data to be updated should either be in the same order as the columns of the database or names of the columns should be given to the query along with the data to be inserted.
Syntax:
INSERT INTO <tablename>(Col1,Col2, ...)
VALUES(....);
To print the ID of the last inserted row lastrowid will be used. This is a special keyword that prints the ID of the row last inserted but to do so there are certain protocols that had to be kept in mind before employing this:
ID column of the database should be a primary key
ID column should auto-incremented.
Given below is the implementation of the same:
Database In Use:
Below is the implementation:
Python3
import mysql.connector mydb = mysql.connector.connect( host = 'localhost', database = 'employee', user = 'root', password = 'Your_pass') cs = mydb.cursor()statement = "INSERT INTO geekstudent( id, name,gender, subject)\VALUES(6,'Shoit','M', 'ML')"cs.execute(statement)mydb.commit() print(cs.rowcount, " record(s) added") print(cs.lastrowid)
Output:
1 record(s) added
0
Updated Database Output:
Python-mySQL
Technical Scripter 2020
Python
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
Check if element exists in list in Python
Python | os.path.join() method
How To Convert Python Dictionary To JSON?
Python | Get unique values from a list
Defaultdict in Python | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n11 Dec, 2020"
},
{
"code": null,
"e": 78,
"s": 28,
"text": " Prerequisites: MySQL, mysql-connector for python"
},
{
"code": null,
"e": 501,
"s": 78,
"text": "The task here is to draft a Python program that works with SQL support to connect data. Whenever insertion into the database takes place, the ID of the row inserted will be printed. To connect python with the database we are using MySQL connector. The work of mysql-connector is to provide access to MySQL Driver to the required language. Thus, it generates a connection between the programming language and MySQL Server. "
},
{
"code": null,
"e": 802,
"s": 501,
"text": "As the name suggests, it inserts data into the database. Certain rules need to be followed while using the insert command. The data to be updated should either be in the same order as the columns of the database or names of the columns should be given to the query along with the data to be inserted."
},
{
"code": null,
"e": 810,
"s": 802,
"text": "Syntax:"
},
{
"code": null,
"e": 850,
"s": 810,
"text": "INSERT INTO <tablename>(Col1,Col2, ...)"
},
{
"code": null,
"e": 864,
"s": 850,
"text": "VALUES(....);"
},
{
"code": null,
"e": 1091,
"s": 864,
"text": "To print the ID of the last inserted row lastrowid will be used. This is a special keyword that prints the ID of the row last inserted but to do so there are certain protocols that had to be kept in mind before employing this:"
},
{
"code": null,
"e": 1141,
"s": 1091,
"text": "ID column of the database should be a primary key"
},
{
"code": null,
"e": 1176,
"s": 1141,
"text": "ID column should auto-incremented."
},
{
"code": null,
"e": 1223,
"s": 1176,
"text": "Given below is the implementation of the same:"
},
{
"code": null,
"e": 1240,
"s": 1223,
"text": "Database In Use:"
},
{
"code": null,
"e": 1269,
"s": 1240,
"text": "Below is the implementation:"
},
{
"code": null,
"e": 1277,
"s": 1269,
"text": "Python3"
},
{
"code": "import mysql.connector mydb = mysql.connector.connect( host = 'localhost', database = 'employee', user = 'root', password = 'Your_pass') cs = mydb.cursor()statement = \"INSERT INTO geekstudent( id, name,gender, subject)\\VALUES(6,'Shoit','M', 'ML')\"cs.execute(statement)mydb.commit() print(cs.rowcount, \" record(s) added\") print(cs.lastrowid)",
"e": 1634,
"s": 1277,
"text": null
},
{
"code": null,
"e": 1642,
"s": 1634,
"text": "Output:"
},
{
"code": null,
"e": 1663,
"s": 1642,
"text": "1 record(s) added\n0"
},
{
"code": null,
"e": 1688,
"s": 1663,
"text": "Updated Database Output:"
},
{
"code": null,
"e": 1701,
"s": 1688,
"text": "Python-mySQL"
},
{
"code": null,
"e": 1725,
"s": 1701,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 1732,
"s": 1725,
"text": "Python"
},
{
"code": null,
"e": 1751,
"s": 1732,
"text": "Technical Scripter"
},
{
"code": null,
"e": 1849,
"s": 1751,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1881,
"s": 1849,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 1908,
"s": 1881,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 1929,
"s": 1908,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 1952,
"s": 1929,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 2008,
"s": 1952,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 2050,
"s": 2008,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 2081,
"s": 2050,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 2123,
"s": 2081,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 2162,
"s": 2123,
"text": "Python | Get unique values from a list"
}
] |
Convert Nested Lists to Dataframe in R | 15 Nov, 2021
In this article, we will discuss how to Convert Nested Lists to Dataframe in R Programming Language.
It can be done with two methods:
Convert Nested lists to Data Frame by Column.
Convert Nested lists to Data Frame by Row.
First, let’s Create a nested list.
Code block
Output:
fig 1: Nested List
Method 1: To convert nested list to Data Frame by column.
Approach:
Create dataframe using data.frame function with the do.call and cbind.
cbind is used to bind the lists together by column into data frame.
do.call is used to bind the cbind and the nested list together as a single argument in the Data frame function.
Also, store the whole data frame in a variable named data_frame and print the variable.
Code:
R
# list() functions are used to create# the list and those list() functions# are put in another list() function to# make the nested listnested_list <- list(l1 = list(1:5, 5:1 ), l2 = list(100:105, 105:100 ), l3 = list(200:205, 205:200 )) # Convert nested list to data frame# by column with the help of cbind and do.calldata_frame <- as.data.frame(do.call(cbind, nested_list)) # Print data framedata_frame
Output:
l1 l2 l3
1 1, 2, 3, 4, 5 100, 101, 102, 103, 104, 105 200, 201, 202, 203, 204, 205
2 5, 4, 3, 2, 1 105, 104, 103, 102, 101, 100 205, 204, 203, 202, 201, 200
Method 2: To convert nested list to Data Frame by row.
Approach:
Create dataframe using data.frame function with the do.call and rbind.
rbind is used to bind the lists together by row into data frame.
do.call is used to bind the rbind and the nested list together as a single argument in the Data frame function.
Also, store the whole data frame in a variable named data_frame and print the variable.
Code:
R
# list() functions are used to create# the list and those list() functions# are put in another list() function to# make the nested listnested_list <- list(l1 = list(1:5, 5:1 ), l2 = list(100:105, 105:100 ), l3 = list(200:205, 205:200 ))# print the nested listnested_list # Convert nested list to data frame by row# with the help of rbind and do.calldata_frame <- as.data.frame(do.call(rbind, nested_list)) # Print data framedata_frame
Output:
V1 V2
l1 1, 2, 3, 4, 5 5, 4, 3, 2, 1
l2 100, 101, 102, 103, 104, 105 105, 104, 103, 102, 101, 100
l3 200, 201, 202, 203, 204, 205 205, 204, 203, 202, 201, 200
kashishsoda
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.
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?
Printing Output of an R Program
How to Replace specific values in column in R DataFrame ?
How to Split Column Into Multiple Columns in R DataFrame?
How to change Row Names of DataFrame in R ?
How to filter R DataFrame by values in a column?
Remove rows with NA in one column of R DataFrame | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n15 Nov, 2021"
},
{
"code": null,
"e": 129,
"s": 28,
"text": "In this article, we will discuss how to Convert Nested Lists to Dataframe in R Programming Language."
},
{
"code": null,
"e": 162,
"s": 129,
"text": "It can be done with two methods:"
},
{
"code": null,
"e": 208,
"s": 162,
"text": "Convert Nested lists to Data Frame by Column."
},
{
"code": null,
"e": 251,
"s": 208,
"text": "Convert Nested lists to Data Frame by Row."
},
{
"code": null,
"e": 286,
"s": 251,
"text": "First, let’s Create a nested list."
},
{
"code": null,
"e": 297,
"s": 286,
"text": "Code block"
},
{
"code": null,
"e": 305,
"s": 297,
"text": "Output:"
},
{
"code": null,
"e": 324,
"s": 305,
"text": "fig 1: Nested List"
},
{
"code": null,
"e": 382,
"s": 324,
"text": "Method 1: To convert nested list to Data Frame by column."
},
{
"code": null,
"e": 392,
"s": 382,
"text": "Approach:"
},
{
"code": null,
"e": 463,
"s": 392,
"text": "Create dataframe using data.frame function with the do.call and cbind."
},
{
"code": null,
"e": 531,
"s": 463,
"text": "cbind is used to bind the lists together by column into data frame."
},
{
"code": null,
"e": 643,
"s": 531,
"text": "do.call is used to bind the cbind and the nested list together as a single argument in the Data frame function."
},
{
"code": null,
"e": 731,
"s": 643,
"text": "Also, store the whole data frame in a variable named data_frame and print the variable."
},
{
"code": null,
"e": 737,
"s": 731,
"text": "Code:"
},
{
"code": null,
"e": 739,
"s": 737,
"text": "R"
},
{
"code": "# list() functions are used to create# the list and those list() functions# are put in another list() function to# make the nested listnested_list <- list(l1 = list(1:5, 5:1 ), l2 = list(100:105, 105:100 ), l3 = list(200:205, 205:200 )) # Convert nested list to data frame# by column with the help of cbind and do.calldata_frame <- as.data.frame(do.call(cbind, nested_list)) # Print data framedata_frame",
"e": 1187,
"s": 739,
"text": null
},
{
"code": null,
"e": 1195,
"s": 1187,
"text": "Output:"
},
{
"code": null,
"e": 1269,
"s": 1195,
"text": " l1 l2 l3"
},
{
"code": null,
"e": 1343,
"s": 1269,
"text": "1 1, 2, 3, 4, 5 100, 101, 102, 103, 104, 105 200, 201, 202, 203, 204, 205"
},
{
"code": null,
"e": 1417,
"s": 1343,
"text": "2 5, 4, 3, 2, 1 105, 104, 103, 102, 101, 100 205, 204, 203, 202, 201, 200"
},
{
"code": null,
"e": 1472,
"s": 1417,
"text": "Method 2: To convert nested list to Data Frame by row."
},
{
"code": null,
"e": 1482,
"s": 1472,
"text": "Approach:"
},
{
"code": null,
"e": 1553,
"s": 1482,
"text": "Create dataframe using data.frame function with the do.call and rbind."
},
{
"code": null,
"e": 1618,
"s": 1553,
"text": "rbind is used to bind the lists together by row into data frame."
},
{
"code": null,
"e": 1730,
"s": 1618,
"text": "do.call is used to bind the rbind and the nested list together as a single argument in the Data frame function."
},
{
"code": null,
"e": 1818,
"s": 1730,
"text": "Also, store the whole data frame in a variable named data_frame and print the variable."
},
{
"code": null,
"e": 1824,
"s": 1818,
"text": "Code:"
},
{
"code": null,
"e": 1826,
"s": 1824,
"text": "R"
},
{
"code": "# list() functions are used to create# the list and those list() functions# are put in another list() function to# make the nested listnested_list <- list(l1 = list(1:5, 5:1 ), l2 = list(100:105, 105:100 ), l3 = list(200:205, 205:200 ))# print the nested listnested_list # Convert nested list to data frame by row# with the help of rbind and do.calldata_frame <- as.data.frame(do.call(rbind, nested_list)) # Print data framedata_frame",
"e": 2305,
"s": 1826,
"text": null
},
{
"code": null,
"e": 2315,
"s": 2305,
"text": " Output: "
},
{
"code": null,
"e": 2376,
"s": 2315,
"text": " V1 V2"
},
{
"code": null,
"e": 2437,
"s": 2376,
"text": "l1 1, 2, 3, 4, 5 5, 4, 3, 2, 1"
},
{
"code": null,
"e": 2498,
"s": 2437,
"text": "l2 100, 101, 102, 103, 104, 105 105, 104, 103, 102, 101, 100"
},
{
"code": null,
"e": 2559,
"s": 2498,
"text": "l3 200, 201, 202, 203, 204, 205 205, 204, 203, 202, 201, 200"
},
{
"code": null,
"e": 2571,
"s": 2559,
"text": "kashishsoda"
},
{
"code": null,
"e": 2578,
"s": 2571,
"text": "Picked"
},
{
"code": null,
"e": 2599,
"s": 2578,
"text": "R DataFrame-Programs"
},
{
"code": null,
"e": 2611,
"s": 2599,
"text": "R-DataFrame"
},
{
"code": null,
"e": 2622,
"s": 2611,
"text": "R Language"
},
{
"code": null,
"e": 2633,
"s": 2622,
"text": "R Programs"
},
{
"code": null,
"e": 2731,
"s": 2633,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2783,
"s": 2731,
"text": "Filter data by multiple conditions in R using Dplyr"
},
{
"code": null,
"e": 2841,
"s": 2783,
"text": "How to Replace specific values in column in R DataFrame ?"
},
{
"code": null,
"e": 2893,
"s": 2841,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 2951,
"s": 2893,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 2983,
"s": 2951,
"text": "Printing Output of an R Program"
},
{
"code": null,
"e": 3041,
"s": 2983,
"text": "How to Replace specific values in column in R DataFrame ?"
},
{
"code": null,
"e": 3099,
"s": 3041,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 3143,
"s": 3099,
"text": "How to change Row Names of DataFrame in R ?"
},
{
"code": null,
"e": 3192,
"s": 3143,
"text": "How to filter R DataFrame by values in a column?"
}
] |
Sort an array using Bubble Sort without using loops | 22 Jun, 2021
Given an array arr[] consisting of N integers, the task is to sort the given array by using Bubble Sort without using loops.
Examples:
Input: arr[] = {1, 3, 4, 2, 5}Output: 1 2 3 4 5
Input: arr[] = {1, 3, 4, 2}Output: 1 2 3 4
Approach: The idea to implement Bubble Sort without using loops is based on the following observations:
The sorting algorithm of Bubble Sort performs the following steps:The outer loop traverses the given array (N – 1) times.The inner loop traverses the array and swaps two adjacent elements if arr[i] > arr[i + 1], for every i over the range [0, N – 1].
The outer loop traverses the given array (N – 1) times.
The inner loop traverses the array and swaps two adjacent elements if arr[i] > arr[i + 1], for every i over the range [0, N – 1].
It can be observed that in every N – 1 iteration, the largest element over the range [0, N – 1 – i] shifts to the position (N – 1 – i) for every i over the range [0, N – 1].
Therefore, the idea is to use recursion to avoid loops.
Follow the steps below to solve the problem:
Consider the following base cases: If the array contains a single element, simply print the array.If the array contains two elements, swap the pair of elements (if required) to obtain a sorted sequence of array elements. Print the sorted array.
If the array contains a single element, simply print the array.
If the array contains two elements, swap the pair of elements (if required) to obtain a sorted sequence of array elements. Print the sorted array.
Store the first two elements from the current array in variables, say a and b.
Initialize an array, say bs[], to store the remaining array elements.
Place the smaller value among a and b at the front of the current array.
Recursively repeat the above steps with a new array formed by appending bs[] to the end of the larger value among a and b.
Store the sorted list returned in a variable, say res[].
Now, recursively repeat the above steps with a new array formed by appending res[] (excluding the last element) to the end of res[res.size() – 1] ( the last element ).
After completing the above steps, print the returned list.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program for the above approach#include<bits/stdc++.h>using namespace std; // Function to implement bubble// sort without using loopsvector<int> bubble_sort(vector<int> ar){ // Base Case: If array // contains a single element if (ar.size() <= 1) return ar; // Base Case: If array // contains two elements if (ar.size() == 2){ if(ar[0] < ar[1]) return ar; else return {ar[1], ar[0]}; } // Store the first two elements // of the list in variables a and b int a = ar[0]; int b = ar[1]; // Store remaining elements // in the list bs vector<int> bs; for(int i = 2; i < ar.size(); i++) bs.push_back(ar[i]); // Store the list after // each recursive call vector<int> res; // If a < b if (a < b){ vector<int> temp1; temp1.push_back(b); for(int i = 0; i < bs.size(); i++) temp1.push_back(bs[i]); vector<int> v = bubble_sort(temp1); v.insert(v.begin(), a); res = v; } // Otherwise, if b >= a else{ vector<int> temp1; temp1.push_back(a); for(int i = 0; i < bs.size(); i++) temp1.push_back(bs[i]); vector<int> v = bubble_sort(temp1); v.insert(v.begin(), b); res = v; } // Recursively call for the list // less than the last element and // and return the newly formed list vector<int> pass; for(int i = 0; i < res.size() - 1; i++) pass.push_back(res[i]); vector<int> ans = bubble_sort(pass); ans.push_back(res[res.size() - 1]); return ans; } // Driver Codeint main(){ vector<int> arr{1, 3, 4, 5, 6, 2}; vector<int> res = bubble_sort(arr); // Print the array for(int i = 0; i < res.size(); i++) cout << res[i] << " ";} // This code is contributed by ipg2016107.
// java program for the above approachimport java.io.*;import java.lang.*;import java.util.*; class GFG { // Function to implement bubble // sort without using loops static ArrayList<Integer> bubble_sort(ArrayList<Integer> ar) { // Base Case: If array // contains a single element if (ar.size() <= 1) return ar; // Base Case: If array // contains two elements if (ar.size() == 2) { if (ar.get(0) < ar.get(1)) return ar; else return new ArrayList<Integer>( Arrays.asList(ar.get(1), ar.get(0))); } // Store the first two elements // of the list in variables a and b int a = ar.get(0); int b = ar.get(1); // Store remaining elements // in the list bs ArrayList<Integer> bs = new ArrayList<>(); for (int i = 2; i < ar.size(); i++) bs.add(ar.get(i)); // Store the list after // each recursive call ArrayList<Integer> res = new ArrayList<>(); // If a < b if (a < b) { ArrayList<Integer> temp1 = new ArrayList<>(); temp1.add(b); for (int i = 0; i < bs.size(); i++) temp1.add(bs.get(i)); ArrayList<Integer> v = bubble_sort(temp1); v.add(0, a); res = v; } // Otherwise, if b >= a else { ArrayList<Integer> temp1 = new ArrayList<>(); temp1.add(a); for (int i = 0; i < bs.size(); i++) temp1.add(bs.get(i)); ArrayList<Integer> v = bubble_sort(temp1); v.add(0, b); res = v; } // Recursively call for the list // less than the last element and // and return the newly formed list ArrayList<Integer> pass = new ArrayList<>(); for (int i = 0; i < res.size() - 1; i++) pass.add(res.get(i)); ArrayList<Integer> ans = bubble_sort(pass); ans.add(res.get(res.size() - 1)); return ans; } // Driver Code public static void main(String[] args) { ArrayList<Integer> arr = new ArrayList<Integer>( Arrays.asList(1, 3, 4, 5, 6, 2)); ArrayList<Integer> res = bubble_sort(arr); // Print the array for (int i = 0; i < res.size(); i++) System.out.print(res.get(i) + " "); }} // This code is contributed by Kingash.
# Python3 program for the above approach # Function to implement bubble# sort without using loopsdef bubble_sort(ar): # Base Case: If array # contains a single element if len(ar) <= 1: return ar # Base Case: If array # contains two elements if len(ar) == 2: return ar if ar[0] < ar[1] else [ar[1], ar[0]] # Store the first two elements # of the list in variables a and b a, b = ar[0], ar[1] # Store remaining elements # in the list bs bs = ar[2:] # Store the list after # each recursive call res = [] # If a < b if a < b: res = [a] + bubble_sort([b] + bs) # Otherwise, if b >= a else: res = [b] + bubble_sort([a] + bs) # Recursively call for the list # less than the last element and # and return the newly formed list return bubble_sort(res[:-1]) + res[-1:] # Driver Code arr = [1, 3, 4, 5, 6, 2]res = bubble_sort(arr) # Print the arrayprint(*res)
// C# program for the above approachusing System;using System.Collections.Generic; class GFG{ // Function to implement bubble// sort without using loopsstatic List<int> bubble_sort(List<int> ar){ // Base Case: If array // contains a single element List<int> temp = new List<int>(); if (ar.Count <= 1) return ar; // Base Case: If array // contains two elements if (ar.Count == 2) { if (ar[0] < ar[1]) return ar; else { temp.Add(ar[1]); temp.Add(ar[0]); return temp; } } // Store the first two elements // of the list in variables a and b int a = ar[0]; int b = ar[1]; // Store remaining elements // in the list bs List<int> bs = new List<int>(); for(int i = 2; i < ar.Count; i++) bs.Add(ar[i]); // Store the list after // each recursive call List<int> res = new List<int>(); // If a < b if (a < b) { List<int> temp1 = new List<int>(); temp1.Add(b); for(int i = 0; i < bs.Count; i++) temp1.Add(bs[i]); List<int> v = bubble_sort(temp1); v.Insert(0, a); res = v; } // Otherwise, if b >= a else { List<int> temp1 = new List<int>(); temp1.Add(a); for(int i = 0; i < bs.Count; i++) temp1.Add(bs[i]); List<int> v = bubble_sort(temp1); v.Insert(0, b); res = v; } // Recursively call for the list // less than the last element and // and return the newly formed list List<int> pass = new List<int>(); for(int i = 0; i < res.Count - 1; i++) pass.Add(res[i]); List<int> ans = bubble_sort(pass); ans.Add(res[res.Count - 1]); return ans;} // Driver Codepublic static void Main(){ List<int> arr = new List<int>{ 1, 3, 4, 5, 6, 2 }; List<int> res = bubble_sort(arr); // Print the array for(int i = 0; i < res.Count; i++) Console.Write(res[i] + " ");}} // This code is contributed by ukasp
<script> // JavaScript program for the above approach // Function to implement bubble // sort without using loopsfunction bubble_sort(ar){ // Base Case: If array // contains a single element if (ar.length <= 1) return ar; // Base Case: If array // contains two elements if (ar.length == 2) { if (ar[0] < ar[1]) return ar; else return [ar[1], ar[0]]; } // Store the first two elements // of the list in variables a and b let a = ar[0]; let b = ar[1]; // Store remaining elements // in the list bs let bs = []; for (let i = 2; i < ar.length; i++) bs.push(ar[i]); // Store the list after // each recursive call let res = []; // If a < b if (a < b) { let temp1 = []; temp1.push(b); for (let i = 0; i < bs.length; i++) temp1.push(bs[i]); let v = bubble_sort(temp1); v.unshift(a); res = v; } // Otherwise, if b >= a else { let temp1 = []; temp1.push(a); for (let i = 0; i < bs.length; i++) temp1.push(bs[i]); let v = bubble_sort(temp1); v.unshift(b); res = v; } // Recursively call for the list // less than the last element and // and return the newly formed list let pass = []; for (let i = 0; i < res.length - 1; i++) pass.push(res[i]); let ans = bubble_sort(pass); ans.push(res[res.length - 1]); return ans;} // Driver Codelet arr =[1, 3, 4, 5, 6, 2];let res = bubble_sort(arr);document.write(res.join(" ")); // This code is contributed by avanitrachhadiya2155 </script>
Output:
1 2 3 4 5 6
Time Complexity: O(N2)Auxiliary Space: O(N)
ipg2016107
ukasp
Kingash
avanitrachhadiya2155
array-rearrange
BubbleSort
Arrays
Recursion
Sorting
Arrays
Recursion
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
Multidimensional Arrays in Java
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
Introduction to Arrays
K'th Smallest/Largest Element in Unsorted Array | Set 1
Write a program to print all permutations of a given string
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
Recursion
Program for Tower of Hanoi
Backtracking | Introduction | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n22 Jun, 2021"
},
{
"code": null,
"e": 179,
"s": 54,
"text": "Given an array arr[] consisting of N integers, the task is to sort the given array by using Bubble Sort without using loops."
},
{
"code": null,
"e": 189,
"s": 179,
"text": "Examples:"
},
{
"code": null,
"e": 237,
"s": 189,
"text": "Input: arr[] = {1, 3, 4, 2, 5}Output: 1 2 3 4 5"
},
{
"code": null,
"e": 280,
"s": 237,
"text": "Input: arr[] = {1, 3, 4, 2}Output: 1 2 3 4"
},
{
"code": null,
"e": 384,
"s": 280,
"text": "Approach: The idea to implement Bubble Sort without using loops is based on the following observations:"
},
{
"code": null,
"e": 635,
"s": 384,
"text": "The sorting algorithm of Bubble Sort performs the following steps:The outer loop traverses the given array (N – 1) times.The inner loop traverses the array and swaps two adjacent elements if arr[i] > arr[i + 1], for every i over the range [0, N – 1]."
},
{
"code": null,
"e": 691,
"s": 635,
"text": "The outer loop traverses the given array (N – 1) times."
},
{
"code": null,
"e": 821,
"s": 691,
"text": "The inner loop traverses the array and swaps two adjacent elements if arr[i] > arr[i + 1], for every i over the range [0, N – 1]."
},
{
"code": null,
"e": 995,
"s": 821,
"text": "It can be observed that in every N – 1 iteration, the largest element over the range [0, N – 1 – i] shifts to the position (N – 1 – i) for every i over the range [0, N – 1]."
},
{
"code": null,
"e": 1051,
"s": 995,
"text": "Therefore, the idea is to use recursion to avoid loops."
},
{
"code": null,
"e": 1096,
"s": 1051,
"text": "Follow the steps below to solve the problem:"
},
{
"code": null,
"e": 1341,
"s": 1096,
"text": "Consider the following base cases: If the array contains a single element, simply print the array.If the array contains two elements, swap the pair of elements (if required) to obtain a sorted sequence of array elements. Print the sorted array."
},
{
"code": null,
"e": 1405,
"s": 1341,
"text": "If the array contains a single element, simply print the array."
},
{
"code": null,
"e": 1552,
"s": 1405,
"text": "If the array contains two elements, swap the pair of elements (if required) to obtain a sorted sequence of array elements. Print the sorted array."
},
{
"code": null,
"e": 1631,
"s": 1552,
"text": "Store the first two elements from the current array in variables, say a and b."
},
{
"code": null,
"e": 1701,
"s": 1631,
"text": "Initialize an array, say bs[], to store the remaining array elements."
},
{
"code": null,
"e": 1774,
"s": 1701,
"text": "Place the smaller value among a and b at the front of the current array."
},
{
"code": null,
"e": 1897,
"s": 1774,
"text": "Recursively repeat the above steps with a new array formed by appending bs[] to the end of the larger value among a and b."
},
{
"code": null,
"e": 1954,
"s": 1897,
"text": "Store the sorted list returned in a variable, say res[]."
},
{
"code": null,
"e": 2122,
"s": 1954,
"text": "Now, recursively repeat the above steps with a new array formed by appending res[] (excluding the last element) to the end of res[res.size() – 1] ( the last element )."
},
{
"code": null,
"e": 2181,
"s": 2122,
"text": "After completing the above steps, print the returned list."
},
{
"code": null,
"e": 2232,
"s": 2181,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 2236,
"s": 2232,
"text": "C++"
},
{
"code": null,
"e": 2241,
"s": 2236,
"text": "Java"
},
{
"code": null,
"e": 2249,
"s": 2241,
"text": "Python3"
},
{
"code": null,
"e": 2252,
"s": 2249,
"text": "C#"
},
{
"code": null,
"e": 2263,
"s": 2252,
"text": "Javascript"
},
{
"code": "// C++ program for the above approach#include<bits/stdc++.h>using namespace std; // Function to implement bubble// sort without using loopsvector<int> bubble_sort(vector<int> ar){ // Base Case: If array // contains a single element if (ar.size() <= 1) return ar; // Base Case: If array // contains two elements if (ar.size() == 2){ if(ar[0] < ar[1]) return ar; else return {ar[1], ar[0]}; } // Store the first two elements // of the list in variables a and b int a = ar[0]; int b = ar[1]; // Store remaining elements // in the list bs vector<int> bs; for(int i = 2; i < ar.size(); i++) bs.push_back(ar[i]); // Store the list after // each recursive call vector<int> res; // If a < b if (a < b){ vector<int> temp1; temp1.push_back(b); for(int i = 0; i < bs.size(); i++) temp1.push_back(bs[i]); vector<int> v = bubble_sort(temp1); v.insert(v.begin(), a); res = v; } // Otherwise, if b >= a else{ vector<int> temp1; temp1.push_back(a); for(int i = 0; i < bs.size(); i++) temp1.push_back(bs[i]); vector<int> v = bubble_sort(temp1); v.insert(v.begin(), b); res = v; } // Recursively call for the list // less than the last element and // and return the newly formed list vector<int> pass; for(int i = 0; i < res.size() - 1; i++) pass.push_back(res[i]); vector<int> ans = bubble_sort(pass); ans.push_back(res[res.size() - 1]); return ans; } // Driver Codeint main(){ vector<int> arr{1, 3, 4, 5, 6, 2}; vector<int> res = bubble_sort(arr); // Print the array for(int i = 0; i < res.size(); i++) cout << res[i] << \" \";} // This code is contributed by ipg2016107.",
"e": 3940,
"s": 2263,
"text": null
},
{
"code": "// java program for the above approachimport java.io.*;import java.lang.*;import java.util.*; class GFG { // Function to implement bubble // sort without using loops static ArrayList<Integer> bubble_sort(ArrayList<Integer> ar) { // Base Case: If array // contains a single element if (ar.size() <= 1) return ar; // Base Case: If array // contains two elements if (ar.size() == 2) { if (ar.get(0) < ar.get(1)) return ar; else return new ArrayList<Integer>( Arrays.asList(ar.get(1), ar.get(0))); } // Store the first two elements // of the list in variables a and b int a = ar.get(0); int b = ar.get(1); // Store remaining elements // in the list bs ArrayList<Integer> bs = new ArrayList<>(); for (int i = 2; i < ar.size(); i++) bs.add(ar.get(i)); // Store the list after // each recursive call ArrayList<Integer> res = new ArrayList<>(); // If a < b if (a < b) { ArrayList<Integer> temp1 = new ArrayList<>(); temp1.add(b); for (int i = 0; i < bs.size(); i++) temp1.add(bs.get(i)); ArrayList<Integer> v = bubble_sort(temp1); v.add(0, a); res = v; } // Otherwise, if b >= a else { ArrayList<Integer> temp1 = new ArrayList<>(); temp1.add(a); for (int i = 0; i < bs.size(); i++) temp1.add(bs.get(i)); ArrayList<Integer> v = bubble_sort(temp1); v.add(0, b); res = v; } // Recursively call for the list // less than the last element and // and return the newly formed list ArrayList<Integer> pass = new ArrayList<>(); for (int i = 0; i < res.size() - 1; i++) pass.add(res.get(i)); ArrayList<Integer> ans = bubble_sort(pass); ans.add(res.get(res.size() - 1)); return ans; } // Driver Code public static void main(String[] args) { ArrayList<Integer> arr = new ArrayList<Integer>( Arrays.asList(1, 3, 4, 5, 6, 2)); ArrayList<Integer> res = bubble_sort(arr); // Print the array for (int i = 0; i < res.size(); i++) System.out.print(res.get(i) + \" \"); }} // This code is contributed by Kingash.",
"e": 6085,
"s": 3940,
"text": null
},
{
"code": "# Python3 program for the above approach # Function to implement bubble# sort without using loopsdef bubble_sort(ar): # Base Case: If array # contains a single element if len(ar) <= 1: return ar # Base Case: If array # contains two elements if len(ar) == 2: return ar if ar[0] < ar[1] else [ar[1], ar[0]] # Store the first two elements # of the list in variables a and b a, b = ar[0], ar[1] # Store remaining elements # in the list bs bs = ar[2:] # Store the list after # each recursive call res = [] # If a < b if a < b: res = [a] + bubble_sort([b] + bs) # Otherwise, if b >= a else: res = [b] + bubble_sort([a] + bs) # Recursively call for the list # less than the last element and # and return the newly formed list return bubble_sort(res[:-1]) + res[-1:] # Driver Code arr = [1, 3, 4, 5, 6, 2]res = bubble_sort(arr) # Print the arrayprint(*res)",
"e": 7068,
"s": 6085,
"text": null
},
{
"code": "// C# program for the above approachusing System;using System.Collections.Generic; class GFG{ // Function to implement bubble// sort without using loopsstatic List<int> bubble_sort(List<int> ar){ // Base Case: If array // contains a single element List<int> temp = new List<int>(); if (ar.Count <= 1) return ar; // Base Case: If array // contains two elements if (ar.Count == 2) { if (ar[0] < ar[1]) return ar; else { temp.Add(ar[1]); temp.Add(ar[0]); return temp; } } // Store the first two elements // of the list in variables a and b int a = ar[0]; int b = ar[1]; // Store remaining elements // in the list bs List<int> bs = new List<int>(); for(int i = 2; i < ar.Count; i++) bs.Add(ar[i]); // Store the list after // each recursive call List<int> res = new List<int>(); // If a < b if (a < b) { List<int> temp1 = new List<int>(); temp1.Add(b); for(int i = 0; i < bs.Count; i++) temp1.Add(bs[i]); List<int> v = bubble_sort(temp1); v.Insert(0, a); res = v; } // Otherwise, if b >= a else { List<int> temp1 = new List<int>(); temp1.Add(a); for(int i = 0; i < bs.Count; i++) temp1.Add(bs[i]); List<int> v = bubble_sort(temp1); v.Insert(0, b); res = v; } // Recursively call for the list // less than the last element and // and return the newly formed list List<int> pass = new List<int>(); for(int i = 0; i < res.Count - 1; i++) pass.Add(res[i]); List<int> ans = bubble_sort(pass); ans.Add(res[res.Count - 1]); return ans;} // Driver Codepublic static void Main(){ List<int> arr = new List<int>{ 1, 3, 4, 5, 6, 2 }; List<int> res = bubble_sort(arr); // Print the array for(int i = 0; i < res.Count; i++) Console.Write(res[i] + \" \");}} // This code is contributed by ukasp",
"e": 9130,
"s": 7068,
"text": null
},
{
"code": "<script> // JavaScript program for the above approach // Function to implement bubble // sort without using loopsfunction bubble_sort(ar){ // Base Case: If array // contains a single element if (ar.length <= 1) return ar; // Base Case: If array // contains two elements if (ar.length == 2) { if (ar[0] < ar[1]) return ar; else return [ar[1], ar[0]]; } // Store the first two elements // of the list in variables a and b let a = ar[0]; let b = ar[1]; // Store remaining elements // in the list bs let bs = []; for (let i = 2; i < ar.length; i++) bs.push(ar[i]); // Store the list after // each recursive call let res = []; // If a < b if (a < b) { let temp1 = []; temp1.push(b); for (let i = 0; i < bs.length; i++) temp1.push(bs[i]); let v = bubble_sort(temp1); v.unshift(a); res = v; } // Otherwise, if b >= a else { let temp1 = []; temp1.push(a); for (let i = 0; i < bs.length; i++) temp1.push(bs[i]); let v = bubble_sort(temp1); v.unshift(b); res = v; } // Recursively call for the list // less than the last element and // and return the newly formed list let pass = []; for (let i = 0; i < res.length - 1; i++) pass.push(res[i]); let ans = bubble_sort(pass); ans.push(res[res.length - 1]); return ans;} // Driver Codelet arr =[1, 3, 4, 5, 6, 2];let res = bubble_sort(arr);document.write(res.join(\" \")); // This code is contributed by avanitrachhadiya2155 </script>",
"e": 10731,
"s": 9130,
"text": null
},
{
"code": null,
"e": 10739,
"s": 10731,
"text": "Output:"
},
{
"code": null,
"e": 10751,
"s": 10739,
"text": "1 2 3 4 5 6"
},
{
"code": null,
"e": 10795,
"s": 10751,
"text": "Time Complexity: O(N2)Auxiliary Space: O(N)"
},
{
"code": null,
"e": 10806,
"s": 10795,
"text": "ipg2016107"
},
{
"code": null,
"e": 10812,
"s": 10806,
"text": "ukasp"
},
{
"code": null,
"e": 10820,
"s": 10812,
"text": "Kingash"
},
{
"code": null,
"e": 10841,
"s": 10820,
"text": "avanitrachhadiya2155"
},
{
"code": null,
"e": 10857,
"s": 10841,
"text": "array-rearrange"
},
{
"code": null,
"e": 10868,
"s": 10857,
"text": "BubbleSort"
},
{
"code": null,
"e": 10875,
"s": 10868,
"text": "Arrays"
},
{
"code": null,
"e": 10885,
"s": 10875,
"text": "Recursion"
},
{
"code": null,
"e": 10893,
"s": 10885,
"text": "Sorting"
},
{
"code": null,
"e": 10900,
"s": 10893,
"text": "Arrays"
},
{
"code": null,
"e": 10910,
"s": 10900,
"text": "Recursion"
},
{
"code": null,
"e": 10918,
"s": 10910,
"text": "Sorting"
},
{
"code": null,
"e": 11016,
"s": 10918,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 11084,
"s": 11016,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 11116,
"s": 11084,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 11201,
"s": 11116,
"text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)"
},
{
"code": null,
"e": 11224,
"s": 11201,
"text": "Introduction to Arrays"
},
{
"code": null,
"e": 11280,
"s": 11224,
"text": "K'th Smallest/Largest Element in Unsorted Array | Set 1"
},
{
"code": null,
"e": 11340,
"s": 11280,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 11425,
"s": 11340,
"text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)"
},
{
"code": null,
"e": 11435,
"s": 11425,
"text": "Recursion"
},
{
"code": null,
"e": 11462,
"s": 11435,
"text": "Program for Tower of Hanoi"
}
] |
Python program to extract Keywords from a list | 01 Oct, 2020
Given List of strings, extract all the words that are keywords.
Input : test_list = [“Gfg is True”, “Its a global win”, “try Gfg”], Output : [‘is’, ‘True’, ‘global’, ‘try’] Explanation : All strings in result list is valid Python keyword.
Input : test_list = [“try Gfg”], Output : [‘try’] Explanation : try is used in try/except block, hence a keyword.
Method #1 : Using iskeyword() + split() + loop
This is one of the ways in which this task can be performed. In this, we check for keyword using iskeyword() and convert a string to words using split(). The logic of extension to all strings happens using loop.
Python3
# Python3 code to demonstrate working of# Extract Keywords from String List # Using iskeyword() + loop + split()import keyword # initializing listtest_list = ["Gfg is True", "Gfg will yield a return", "Its a global win", "try Gfg"] # printing original listprint("The original list is : " + str(test_list)) # iterating using loopres = []for sub in test_list: for word in sub.split(): # check for keyword using iskeyword() if keyword.iskeyword(word): res.append(word) # printing resultprint("Extracted Keywords : " + str(res))
Output:
The original list is : [‘Gfg is True’, ‘Gfg will yield a return’, ‘Its a global win’, ‘try Gfg’]Extracted Keywords : [‘is’, ‘True’, ‘yield’, ‘return’, ‘global’, ‘try’]
Method #2: Using list comprehension
This is yet another way in which this task can be performed. Similar to the above method but much compact on paper, use similar functionalities as the above method.
Python3
# Python3 code to demonstrate working of# Extract Keywords from String List # Using list comprehensionimport keyword # initializing listtest_list = ["Gfg is True", "Gfg will yield a return", "Its a global win", "try Gfg"] # printing original listprint("The original list is : " + str(test_list)) # One-liner using list comprehensionres = [ele for sub in test_list for ele in sub.split() if keyword.iskeyword(ele)] # printing resultprint("Extracted Keywords : " + str(res))
Output:
The original list is : [‘Gfg is True’, ‘Gfg will yield a return’, ‘Its a global win’, ‘try Gfg’]Extracted Keywords : [‘is’, ‘True’, ‘yield’, ‘return’, ‘global’, ‘try’]
Python list-programs
Python string-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Different ways to create Pandas Dataframe
Enumerate() in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary
Python Program for Fibonacci numbers | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n01 Oct, 2020"
},
{
"code": null,
"e": 92,
"s": 28,
"text": "Given List of strings, extract all the words that are keywords."
},
{
"code": null,
"e": 267,
"s": 92,
"text": "Input : test_list = [“Gfg is True”, “Its a global win”, “try Gfg”], Output : [‘is’, ‘True’, ‘global’, ‘try’] Explanation : All strings in result list is valid Python keyword."
},
{
"code": null,
"e": 382,
"s": 267,
"text": "Input : test_list = [“try Gfg”], Output : [‘try’] Explanation : try is used in try/except block, hence a keyword. "
},
{
"code": null,
"e": 429,
"s": 382,
"text": "Method #1 : Using iskeyword() + split() + loop"
},
{
"code": null,
"e": 641,
"s": 429,
"text": "This is one of the ways in which this task can be performed. In this, we check for keyword using iskeyword() and convert a string to words using split(). The logic of extension to all strings happens using loop."
},
{
"code": null,
"e": 649,
"s": 641,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate working of# Extract Keywords from String List # Using iskeyword() + loop + split()import keyword # initializing listtest_list = [\"Gfg is True\", \"Gfg will yield a return\", \"Its a global win\", \"try Gfg\"] # printing original listprint(\"The original list is : \" + str(test_list)) # iterating using loopres = []for sub in test_list: for word in sub.split(): # check for keyword using iskeyword() if keyword.iskeyword(word): res.append(word) # printing resultprint(\"Extracted Keywords : \" + str(res))",
"e": 1219,
"s": 649,
"text": null
},
{
"code": null,
"e": 1227,
"s": 1219,
"text": "Output:"
},
{
"code": null,
"e": 1395,
"s": 1227,
"text": "The original list is : [‘Gfg is True’, ‘Gfg will yield a return’, ‘Its a global win’, ‘try Gfg’]Extracted Keywords : [‘is’, ‘True’, ‘yield’, ‘return’, ‘global’, ‘try’]"
},
{
"code": null,
"e": 1431,
"s": 1395,
"text": "Method #2: Using list comprehension"
},
{
"code": null,
"e": 1596,
"s": 1431,
"text": "This is yet another way in which this task can be performed. Similar to the above method but much compact on paper, use similar functionalities as the above method."
},
{
"code": null,
"e": 1604,
"s": 1596,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate working of# Extract Keywords from String List # Using list comprehensionimport keyword # initializing listtest_list = [\"Gfg is True\", \"Gfg will yield a return\", \"Its a global win\", \"try Gfg\"] # printing original listprint(\"The original list is : \" + str(test_list)) # One-liner using list comprehensionres = [ele for sub in test_list for ele in sub.split() if keyword.iskeyword(ele)] # printing resultprint(\"Extracted Keywords : \" + str(res))",
"e": 2094,
"s": 1604,
"text": null
},
{
"code": null,
"e": 2102,
"s": 2094,
"text": "Output:"
},
{
"code": null,
"e": 2270,
"s": 2102,
"text": "The original list is : [‘Gfg is True’, ‘Gfg will yield a return’, ‘Its a global win’, ‘try Gfg’]Extracted Keywords : [‘is’, ‘True’, ‘yield’, ‘return’, ‘global’, ‘try’]"
},
{
"code": null,
"e": 2291,
"s": 2270,
"text": "Python list-programs"
},
{
"code": null,
"e": 2314,
"s": 2291,
"text": "Python string-programs"
},
{
"code": null,
"e": 2321,
"s": 2314,
"text": "Python"
},
{
"code": null,
"e": 2337,
"s": 2321,
"text": "Python Programs"
},
{
"code": null,
"e": 2435,
"s": 2337,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2477,
"s": 2435,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 2499,
"s": 2477,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 2525,
"s": 2499,
"text": "Python String | replace()"
},
{
"code": null,
"e": 2557,
"s": 2525,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2586,
"s": 2557,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 2608,
"s": 2586,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 2647,
"s": 2608,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 2685,
"s": 2647,
"text": "Python | Convert a list to dictionary"
},
{
"code": null,
"e": 2734,
"s": 2685,
"text": "Python | Convert string dictionary to dictionary"
}
] |
Iterative approach to print all permutations of an Array | 17 Jun, 2019
Given an array arr[] of size N, the task is to generate and print all permutations of the given array.
Examples:
Input: arr[] = {1, 2}Output:1 22 1
Input: {0, 1, 2}Output:0 1 21 0 20 2 12 0 11 2 02 1 0
Approach: The recursive methods to solve the above problems are discussed here and here. In this post, an iterative method to output all permutations for a given array will be discussed.The iterative method acts as a state machine. When the machine is called, it outputs a permutation and move to the next one.
To begin, we need an integer array Indexes to store all the indexes of the input array, and values in array Indexes are initialized to be 0 to n – 1. What we need to do is to permute the Indexes array.
During the iteration, we find the smallest index Increase in the Indexes array such that Indexes[Increase] < Indexes[Increase + 1], which is the first “value increase”. Then, we have Indexes[0] > Indexes[1] > Indexes[2] > ... > Indexes[Increase], which is a tract of decreasing values from index[0]. The next steps will be:
Find the index mid such that Indexes[mid] is the greatest with the constraints that 0 ≤ mid ≤ Increase and Indexes[mid] < Indexes[Increase + 1]; since array Indexes is reversely sorted from 0 to Increase, this step can use binary search.Swap Indexes[Increase + 1] and Indexes[mid].Reverse Indexes[0] to Indexes[Increase].
Find the index mid such that Indexes[mid] is the greatest with the constraints that 0 ≤ mid ≤ Increase and Indexes[mid] < Indexes[Increase + 1]; since array Indexes is reversely sorted from 0 to Increase, this step can use binary search.
Swap Indexes[Increase + 1] and Indexes[mid].
Reverse Indexes[0] to Indexes[Increase].
When the values in Indexes become n – 1 to 0, there is no “value increase”, and the algorithm terminates.
To output the combination, we loop through the index array and the values of the integer array are the indexes of the input array.
The following image illustrates the iteration in the algorithm.
Below is the implementation of the above approach:
C++
Java
C#
// C++ implementation of the approach#include <iostream>using namespace std; template <typename T>class AllPermutation {private: // The input array for permutation const T* Arr; // Length of the input array const int Length; // Index array to store indexes of input array int* Indexes; // The index of the first "increase" // in the Index array which is the smallest // i such that Indexes[i] < Indexes[i + 1] int Increase; public: // Constructor AllPermutation(T* arr, int length) : Arr(arr), Length(length) { this->Indexes = nullptr; this->Increase = -1; } // Destructor ~AllPermutation() { if (this->Indexes != nullptr) { delete[] this->Indexes; } } // Initialize and output // the first permutation void GetFirst() { // Allocate memory for Indexes array this->Indexes = new int[this->Length]; // Initialize the values in Index array // from 0 to n - 1 for (int i = 0; i < this->Length; ++i) { this->Indexes[i] = i; } // Set the Increase to 0 // since Indexes[0] = 0 < Indexes[1] = 1 this->Increase = 0; // Output the first permutation this->Output(); } // Function that returns true if it is // possible to generate the next permutation bool HasNext() { // When Increase is in the end of the array, // it is not possible to have next one return this->Increase != (this->Length - 1); } // Output the next permutation void GetNext() { // Increase is at the very beginning if (this->Increase == 0) { // Swap Index[0] and Index[1] this->Swap(this->Increase, this->Increase + 1); // Update Increase this->Increase += 1; while (this->Increase < this->Length - 1 && this->Indexes[this->Increase] > this->Indexes[this->Increase + 1]) { ++this->Increase; } } else { // Value at Indexes[Increase + 1] is greater than Indexes[0] // no need for binary search, // just swap Indexes[Increase + 1] and Indexes[0] if (this->Indexes[this->Increase + 1] > this->Indexes[0]) { this->Swap(this->Increase + 1, 0); } else { // Binary search to find the greatest value // which is less than Indexes[Increase + 1] int start = 0; int end = this->Increase; int mid = (start + end) / 2; int tVal = this->Indexes[this->Increase + 1]; while (!(this->Indexes[mid] < tVal && this->Indexes[mid - 1] > tVal)) { if (this->Indexes[mid] < tVal) { end = mid - 1; } else { start = mid + 1; } mid = (start + end) / 2; } // Swap this->Swap(this->Increase + 1, mid); } // Invert 0 to Increase for (int i = 0; i <= this->Increase / 2; ++i) { this->Swap(i, this->Increase - i); } // Reset Increase this->Increase = 0; } this->Output(); } private: // Function to output the input array void Output() { for (int i = 0; i < this->Length; ++i) { // Indexes of the input array // are at the Indexes array cout << (this->Arr[this->Indexes[i]]) << " "; } cout << endl; } // Swap two values in the Indexes array void Swap(int p, int q) { int tmp = this->Indexes[p]; this->Indexes[p] = this->Indexes[q]; this->Indexes[q] = tmp; }}; // Driver codeint main(){ int arr[] = { 0, 1, 2 }; AllPermutation<int> perm(arr, sizeof(arr) / sizeof(int)); perm.GetFirst(); while (perm.HasNext()) { perm.GetNext(); } return 0;}
// Java implementation of the approachclass AllPermutation { // The input array for permutation private final int Arr[]; // Index array to store indexes of input array private int Indexes[]; // The index of the first "increase" // in the Index array which is the smallest // i such that Indexes[i] < Indexes[i + 1] private int Increase; // Constructor public AllPermutation(int arr[]) { this.Arr = arr; this.Increase = -1; this.Indexes = new int[this.Arr.length]; } // Initialize and output // the first permutation public void GetFirst() { // Allocate memory for Indexes array this.Indexes = new int[this.Arr.length]; // Initialize the values in Index array // from 0 to n - 1 for (int i = 0; i < Indexes.length; ++i) { this.Indexes[i] = i; } // Set the Increase to 0 // since Indexes[0] = 0 < Indexes[1] = 1 this.Increase = 0; // Output the first permutation this.Output(); } // Function that returns true if it is // possible to generate the next permutation public boolean HasNext() { // When Increase is in the end of the array, // it is not possible to have next one return this.Increase != (this.Indexes.length - 1); } // Output the next permutation public void GetNext() { // Increase is at the very beginning if (this.Increase == 0) { // Swap Index[0] and Index[1] this.Swap(this.Increase, this.Increase + 1); // Update Increase this.Increase += 1; while (this.Increase < this.Indexes.length - 1 && this.Indexes[this.Increase] > this.Indexes[this.Increase + 1]) { ++this.Increase; } } else { // Value at Indexes[Increase + 1] is greater than Indexes[0] // no need for binary search, // just swap Indexes[Increase + 1] and Indexes[0] if (this.Indexes[this.Increase + 1] > this.Indexes[0]) { this.Swap(this.Increase + 1, 0); } else { // Binary search to find the greatest value // which is less than Indexes[Increase + 1] int start = 0; int end = this.Increase; int mid = (start + end) / 2; int tVal = this.Indexes[this.Increase + 1]; while (!(this.Indexes[mid]<tVal&& this.Indexes[mid - 1]> tVal)) { if (this.Indexes[mid] < tVal) { end = mid - 1; } else { start = mid + 1; } mid = (start + end) / 2; } // Swap this.Swap(this.Increase + 1, mid); } // Invert 0 to Increase for (int i = 0; i <= this.Increase / 2; ++i) { this.Swap(i, this.Increase - i); } // Reset Increase this.Increase = 0; } this.Output(); } // Function to output the input array private void Output() { for (int i = 0; i < this.Indexes.length; ++i) { // Indexes of the input array // are at the Indexes array System.out.print(this.Arr[this.Indexes[i]]); System.out.print(" "); } System.out.println(); } // Swap two values in the Indexes array private void Swap(int p, int q) { int tmp = this.Indexes[p]; this.Indexes[p] = this.Indexes[q]; this.Indexes[q] = tmp; }} // Driver codeclass AppDriver { public static void main(String args[]) { int[] arr = { 0, 1, 2 }; AllPermutation perm = new AllPermutation(arr); perm.GetFirst(); while (perm.HasNext()) { perm.GetNext(); } }} // This code is contributed by ghanshyampandey
// C# implementation of the approachusing System;namespace Permutation { class AllPermutation<T> { // The input array for permutation private readonly T[] Arr; // Index array to store indexes of input array private int[] Indexes; // The index of the first "increase" // in the Index array which is the smallest // i such that Indexes[i] < Indexes[i + 1] private int Increase; // Constructor public AllPermutation(T[] arr) { this.Arr = arr; this.Increase = -1; } // Initialize and output // the first permutation public void GetFirst() { // Allocate memory for Indexes array this.Indexes = new int[this.Arr.Length]; // Initialize the values in Index array // from 0 to n - 1 for (int i = 0; i < Indexes.Length; ++i) { this.Indexes[i] = i; } // Set the Increase to 0 // since Indexes[0] = 0 < Indexes[1] = 1 this.Increase = 0; // Output the first permutation this.Output(); } // Function that returns true if it is // possible to generate the next permutation public bool HasNext() { // When Increase is in the end of the array, // it is not possible to have next one return this.Increase != (this.Indexes.Length - 1); } // Output the next permutation public void GetNext() { // Increase is at the very beginning if (this.Increase == 0) { // Swap Index[0] and Index[1] this.Swap(this.Increase, this.Increase + 1); // Update Increase this.Increase += 1; while (this.Increase < this.Indexes.Length - 1 && this.Indexes[this.Increase] > this.Indexes[this.Increase + 1]) { ++this.Increase; } } else { // Value at Indexes[Increase + 1] is greater than Indexes[0] // no need for binary search, // just swap Indexes[Increase + 1] and Indexes[0] if (this.Indexes[this.Increase + 1] > this.Indexes[0]) { this.Swap(this.Increase + 1, 0); } else { // Binary search to find the greatest value // which is less than Indexes[Increase + 1] int start = 0; int end = this.Increase; int mid = (start + end) / 2; int tVal = this.Indexes[this.Increase + 1]; while (!(this.Indexes[mid]<tVal&& this.Indexes[mid - 1]> tVal)) { if (this.Indexes[mid] < tVal) { end = mid - 1; } else { start = mid + 1; } mid = (start + end) / 2; } // Swap this.Swap(this.Increase + 1, mid); } // Invert 0 to Increase for (int i = 0; i <= this.Increase / 2; ++i) { this.Swap(i, this.Increase - i); } // Reset Increase this.Increase = 0; } this.Output(); } // Function to output the input array private void Output() { for (int i = 0; i < this.Indexes.Length; ++i) { // Indexes of the input array // are at the Indexes array Console.Write(this.Arr[this.Indexes[i]]); Console.Write(" "); } Console.WriteLine(); } // Swap two values in the Indexes array private void Swap(int p, int q) { int tmp = this.Indexes[p]; this.Indexes[p] = this.Indexes[q]; this.Indexes[q] = tmp; }} // Driver codeclass AppDriver { static void Main() { int[] arr = { 0, 1, 2 }; AllPermutation<int> perm = new AllPermutation<int>(arr); perm.GetFirst(); while (perm.HasNext()) { perm.GetNext(); } }}}
0 1 2
1 0 2
0 2 1
2 0 1
1 2 0
2 1 0
gp6
permutation
Arrays
Combinatorial
Dynamic Programming
Arrays
Dynamic Programming
permutation
Combinatorial
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)
itertools.combinations() module in Python to print all possible combinations
Factorial of a large number
Generate all possible combinations of at most X characters from a given array
Find the K-th Permutation Sequence of first N natural numbers
Count pairs of non-overlapping palindromic sub-strings of the given string | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n17 Jun, 2019"
},
{
"code": null,
"e": 155,
"s": 52,
"text": "Given an array arr[] of size N, the task is to generate and print all permutations of the given array."
},
{
"code": null,
"e": 165,
"s": 155,
"text": "Examples:"
},
{
"code": null,
"e": 200,
"s": 165,
"text": "Input: arr[] = {1, 2}Output:1 22 1"
},
{
"code": null,
"e": 254,
"s": 200,
"text": "Input: {0, 1, 2}Output:0 1 21 0 20 2 12 0 11 2 02 1 0"
},
{
"code": null,
"e": 565,
"s": 254,
"text": "Approach: The recursive methods to solve the above problems are discussed here and here. In this post, an iterative method to output all permutations for a given array will be discussed.The iterative method acts as a state machine. When the machine is called, it outputs a permutation and move to the next one."
},
{
"code": null,
"e": 767,
"s": 565,
"text": "To begin, we need an integer array Indexes to store all the indexes of the input array, and values in array Indexes are initialized to be 0 to n – 1. What we need to do is to permute the Indexes array."
},
{
"code": null,
"e": 1091,
"s": 767,
"text": "During the iteration, we find the smallest index Increase in the Indexes array such that Indexes[Increase] < Indexes[Increase + 1], which is the first “value increase”. Then, we have Indexes[0] > Indexes[1] > Indexes[2] > ... > Indexes[Increase], which is a tract of decreasing values from index[0]. The next steps will be:"
},
{
"code": null,
"e": 1413,
"s": 1091,
"text": "Find the index mid such that Indexes[mid] is the greatest with the constraints that 0 ≤ mid ≤ Increase and Indexes[mid] < Indexes[Increase + 1]; since array Indexes is reversely sorted from 0 to Increase, this step can use binary search.Swap Indexes[Increase + 1] and Indexes[mid].Reverse Indexes[0] to Indexes[Increase]."
},
{
"code": null,
"e": 1651,
"s": 1413,
"text": "Find the index mid such that Indexes[mid] is the greatest with the constraints that 0 ≤ mid ≤ Increase and Indexes[mid] < Indexes[Increase + 1]; since array Indexes is reversely sorted from 0 to Increase, this step can use binary search."
},
{
"code": null,
"e": 1696,
"s": 1651,
"text": "Swap Indexes[Increase + 1] and Indexes[mid]."
},
{
"code": null,
"e": 1737,
"s": 1696,
"text": "Reverse Indexes[0] to Indexes[Increase]."
},
{
"code": null,
"e": 1843,
"s": 1737,
"text": "When the values in Indexes become n – 1 to 0, there is no “value increase”, and the algorithm terminates."
},
{
"code": null,
"e": 1974,
"s": 1843,
"text": "To output the combination, we loop through the index array and the values of the integer array are the indexes of the input array."
},
{
"code": null,
"e": 2038,
"s": 1974,
"text": "The following image illustrates the iteration in the algorithm."
},
{
"code": null,
"e": 2089,
"s": 2038,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 2093,
"s": 2089,
"text": "C++"
},
{
"code": null,
"e": 2098,
"s": 2093,
"text": "Java"
},
{
"code": null,
"e": 2101,
"s": 2098,
"text": "C#"
},
{
"code": "// C++ implementation of the approach#include <iostream>using namespace std; template <typename T>class AllPermutation {private: // The input array for permutation const T* Arr; // Length of the input array const int Length; // Index array to store indexes of input array int* Indexes; // The index of the first \"increase\" // in the Index array which is the smallest // i such that Indexes[i] < Indexes[i + 1] int Increase; public: // Constructor AllPermutation(T* arr, int length) : Arr(arr), Length(length) { this->Indexes = nullptr; this->Increase = -1; } // Destructor ~AllPermutation() { if (this->Indexes != nullptr) { delete[] this->Indexes; } } // Initialize and output // the first permutation void GetFirst() { // Allocate memory for Indexes array this->Indexes = new int[this->Length]; // Initialize the values in Index array // from 0 to n - 1 for (int i = 0; i < this->Length; ++i) { this->Indexes[i] = i; } // Set the Increase to 0 // since Indexes[0] = 0 < Indexes[1] = 1 this->Increase = 0; // Output the first permutation this->Output(); } // Function that returns true if it is // possible to generate the next permutation bool HasNext() { // When Increase is in the end of the array, // it is not possible to have next one return this->Increase != (this->Length - 1); } // Output the next permutation void GetNext() { // Increase is at the very beginning if (this->Increase == 0) { // Swap Index[0] and Index[1] this->Swap(this->Increase, this->Increase + 1); // Update Increase this->Increase += 1; while (this->Increase < this->Length - 1 && this->Indexes[this->Increase] > this->Indexes[this->Increase + 1]) { ++this->Increase; } } else { // Value at Indexes[Increase + 1] is greater than Indexes[0] // no need for binary search, // just swap Indexes[Increase + 1] and Indexes[0] if (this->Indexes[this->Increase + 1] > this->Indexes[0]) { this->Swap(this->Increase + 1, 0); } else { // Binary search to find the greatest value // which is less than Indexes[Increase + 1] int start = 0; int end = this->Increase; int mid = (start + end) / 2; int tVal = this->Indexes[this->Increase + 1]; while (!(this->Indexes[mid] < tVal && this->Indexes[mid - 1] > tVal)) { if (this->Indexes[mid] < tVal) { end = mid - 1; } else { start = mid + 1; } mid = (start + end) / 2; } // Swap this->Swap(this->Increase + 1, mid); } // Invert 0 to Increase for (int i = 0; i <= this->Increase / 2; ++i) { this->Swap(i, this->Increase - i); } // Reset Increase this->Increase = 0; } this->Output(); } private: // Function to output the input array void Output() { for (int i = 0; i < this->Length; ++i) { // Indexes of the input array // are at the Indexes array cout << (this->Arr[this->Indexes[i]]) << \" \"; } cout << endl; } // Swap two values in the Indexes array void Swap(int p, int q) { int tmp = this->Indexes[p]; this->Indexes[p] = this->Indexes[q]; this->Indexes[q] = tmp; }}; // Driver codeint main(){ int arr[] = { 0, 1, 2 }; AllPermutation<int> perm(arr, sizeof(arr) / sizeof(int)); perm.GetFirst(); while (perm.HasNext()) { perm.GetNext(); } return 0;}",
"e": 6233,
"s": 2101,
"text": null
},
{
"code": "// Java implementation of the approachclass AllPermutation { // The input array for permutation private final int Arr[]; // Index array to store indexes of input array private int Indexes[]; // The index of the first \"increase\" // in the Index array which is the smallest // i such that Indexes[i] < Indexes[i + 1] private int Increase; // Constructor public AllPermutation(int arr[]) { this.Arr = arr; this.Increase = -1; this.Indexes = new int[this.Arr.length]; } // Initialize and output // the first permutation public void GetFirst() { // Allocate memory for Indexes array this.Indexes = new int[this.Arr.length]; // Initialize the values in Index array // from 0 to n - 1 for (int i = 0; i < Indexes.length; ++i) { this.Indexes[i] = i; } // Set the Increase to 0 // since Indexes[0] = 0 < Indexes[1] = 1 this.Increase = 0; // Output the first permutation this.Output(); } // Function that returns true if it is // possible to generate the next permutation public boolean HasNext() { // When Increase is in the end of the array, // it is not possible to have next one return this.Increase != (this.Indexes.length - 1); } // Output the next permutation public void GetNext() { // Increase is at the very beginning if (this.Increase == 0) { // Swap Index[0] and Index[1] this.Swap(this.Increase, this.Increase + 1); // Update Increase this.Increase += 1; while (this.Increase < this.Indexes.length - 1 && this.Indexes[this.Increase] > this.Indexes[this.Increase + 1]) { ++this.Increase; } } else { // Value at Indexes[Increase + 1] is greater than Indexes[0] // no need for binary search, // just swap Indexes[Increase + 1] and Indexes[0] if (this.Indexes[this.Increase + 1] > this.Indexes[0]) { this.Swap(this.Increase + 1, 0); } else { // Binary search to find the greatest value // which is less than Indexes[Increase + 1] int start = 0; int end = this.Increase; int mid = (start + end) / 2; int tVal = this.Indexes[this.Increase + 1]; while (!(this.Indexes[mid]<tVal&& this.Indexes[mid - 1]> tVal)) { if (this.Indexes[mid] < tVal) { end = mid - 1; } else { start = mid + 1; } mid = (start + end) / 2; } // Swap this.Swap(this.Increase + 1, mid); } // Invert 0 to Increase for (int i = 0; i <= this.Increase / 2; ++i) { this.Swap(i, this.Increase - i); } // Reset Increase this.Increase = 0; } this.Output(); } // Function to output the input array private void Output() { for (int i = 0; i < this.Indexes.length; ++i) { // Indexes of the input array // are at the Indexes array System.out.print(this.Arr[this.Indexes[i]]); System.out.print(\" \"); } System.out.println(); } // Swap two values in the Indexes array private void Swap(int p, int q) { int tmp = this.Indexes[p]; this.Indexes[p] = this.Indexes[q]; this.Indexes[q] = tmp; }} // Driver codeclass AppDriver { public static void main(String args[]) { int[] arr = { 0, 1, 2 }; AllPermutation perm = new AllPermutation(arr); perm.GetFirst(); while (perm.HasNext()) { perm.GetNext(); } }} // This code is contributed by ghanshyampandey",
"e": 10413,
"s": 6233,
"text": null
},
{
"code": "// C# implementation of the approachusing System;namespace Permutation { class AllPermutation<T> { // The input array for permutation private readonly T[] Arr; // Index array to store indexes of input array private int[] Indexes; // The index of the first \"increase\" // in the Index array which is the smallest // i such that Indexes[i] < Indexes[i + 1] private int Increase; // Constructor public AllPermutation(T[] arr) { this.Arr = arr; this.Increase = -1; } // Initialize and output // the first permutation public void GetFirst() { // Allocate memory for Indexes array this.Indexes = new int[this.Arr.Length]; // Initialize the values in Index array // from 0 to n - 1 for (int i = 0; i < Indexes.Length; ++i) { this.Indexes[i] = i; } // Set the Increase to 0 // since Indexes[0] = 0 < Indexes[1] = 1 this.Increase = 0; // Output the first permutation this.Output(); } // Function that returns true if it is // possible to generate the next permutation public bool HasNext() { // When Increase is in the end of the array, // it is not possible to have next one return this.Increase != (this.Indexes.Length - 1); } // Output the next permutation public void GetNext() { // Increase is at the very beginning if (this.Increase == 0) { // Swap Index[0] and Index[1] this.Swap(this.Increase, this.Increase + 1); // Update Increase this.Increase += 1; while (this.Increase < this.Indexes.Length - 1 && this.Indexes[this.Increase] > this.Indexes[this.Increase + 1]) { ++this.Increase; } } else { // Value at Indexes[Increase + 1] is greater than Indexes[0] // no need for binary search, // just swap Indexes[Increase + 1] and Indexes[0] if (this.Indexes[this.Increase + 1] > this.Indexes[0]) { this.Swap(this.Increase + 1, 0); } else { // Binary search to find the greatest value // which is less than Indexes[Increase + 1] int start = 0; int end = this.Increase; int mid = (start + end) / 2; int tVal = this.Indexes[this.Increase + 1]; while (!(this.Indexes[mid]<tVal&& this.Indexes[mid - 1]> tVal)) { if (this.Indexes[mid] < tVal) { end = mid - 1; } else { start = mid + 1; } mid = (start + end) / 2; } // Swap this.Swap(this.Increase + 1, mid); } // Invert 0 to Increase for (int i = 0; i <= this.Increase / 2; ++i) { this.Swap(i, this.Increase - i); } // Reset Increase this.Increase = 0; } this.Output(); } // Function to output the input array private void Output() { for (int i = 0; i < this.Indexes.Length; ++i) { // Indexes of the input array // are at the Indexes array Console.Write(this.Arr[this.Indexes[i]]); Console.Write(\" \"); } Console.WriteLine(); } // Swap two values in the Indexes array private void Swap(int p, int q) { int tmp = this.Indexes[p]; this.Indexes[p] = this.Indexes[q]; this.Indexes[q] = tmp; }} // Driver codeclass AppDriver { static void Main() { int[] arr = { 0, 1, 2 }; AllPermutation<int> perm = new AllPermutation<int>(arr); perm.GetFirst(); while (perm.HasNext()) { perm.GetNext(); } }}}",
"e": 14372,
"s": 10413,
"text": null
},
{
"code": null,
"e": 14414,
"s": 14372,
"text": "0 1 2 \n1 0 2 \n0 2 1 \n2 0 1 \n1 2 0 \n2 1 0\n"
},
{
"code": null,
"e": 14418,
"s": 14414,
"text": "gp6"
},
{
"code": null,
"e": 14430,
"s": 14418,
"text": "permutation"
},
{
"code": null,
"e": 14437,
"s": 14430,
"text": "Arrays"
},
{
"code": null,
"e": 14451,
"s": 14437,
"text": "Combinatorial"
},
{
"code": null,
"e": 14471,
"s": 14451,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 14478,
"s": 14471,
"text": "Arrays"
},
{
"code": null,
"e": 14498,
"s": 14478,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 14510,
"s": 14498,
"text": "permutation"
},
{
"code": null,
"e": 14524,
"s": 14510,
"text": "Combinatorial"
},
{
"code": null,
"e": 14622,
"s": 14524,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 14690,
"s": 14622,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 14734,
"s": 14690,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 14766,
"s": 14734,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 14780,
"s": 14766,
"text": "Linear Search"
},
{
"code": null,
"e": 14865,
"s": 14780,
"text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)"
},
{
"code": null,
"e": 14942,
"s": 14865,
"text": "itertools.combinations() module in Python to print all possible combinations"
},
{
"code": null,
"e": 14970,
"s": 14942,
"text": "Factorial of a large number"
},
{
"code": null,
"e": 15048,
"s": 14970,
"text": "Generate all possible combinations of at most X characters from a given array"
},
{
"code": null,
"e": 15110,
"s": 15048,
"text": "Find the K-th Permutation Sequence of first N natural numbers"
}
] |
Download File in Selenium Using Python | 04 Jan, 2021
Prerequisite: Selenium
Selenium is a powerful tool for controlling web browsers through programs and performing browser automation. It is functional for all browsers, works on all major OS and its scripts are written in various languages i.e. Python, Java, C#, etc. We will be working with Python. Selenium Tutorial covers all topics such as– WebDriver, WebElement, Unit Testing with selenium. In this article, we are going to see to Download the File From Web Page Using Selenium in Python.
For Downloading the File, we will use the click() method. Here our automation we will download a generated text file.
Follow these steps –
Enter data
Click on generate, it will generate a text file
Click on download, it will download the text file
Here we will use id for entering and generating the text file.
When a file is generated it will give a download option, click on it, the download will start.
Approach:
Import module.
Make an object for chromedriver.
Get URL with get() methods.
Create automation text.
Create link automation for downloading.
Below is the full implementation:
Python3
# Import Modulefrom selenium import webdriverfrom selenium.webdriver.common.keys import Keys # Open Chromedriver = webdriver.Chrome( 'C:/Users/HP/Desktop/Drivers/chromedriver_win32/chromedriver.exe') # Open URLdriver.get( 'http://demo.automationtesting.in/FileDownload.html') # Enter textdriver.find_element_by_id('textbox').send_keys("Hello world") # Generate Text Filedriver.find_element_by_id('createTxt').click() # Click on Download Buttondriver.find_element_by_id('link-to-download').click()
Output:
Similarly, we can download a PDF file or any other document.
Python Selenium-Exercises
Python-selenium
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
Check if element exists in list in Python
Python | os.path.join() method
How To Convert Python Dictionary To JSON?
Python | Get unique values from a list
Defaultdict in Python | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n04 Jan, 2021"
},
{
"code": null,
"e": 75,
"s": 52,
"text": "Prerequisite: Selenium"
},
{
"code": null,
"e": 545,
"s": 75,
"text": "Selenium is a powerful tool for controlling web browsers through programs and performing browser automation. It is functional for all browsers, works on all major OS and its scripts are written in various languages i.e. Python, Java, C#, etc. We will be working with Python. Selenium Tutorial covers all topics such as– WebDriver, WebElement, Unit Testing with selenium. In this article, we are going to see to Download the File From Web Page Using Selenium in Python."
},
{
"code": null,
"e": 663,
"s": 545,
"text": "For Downloading the File, we will use the click() method. Here our automation we will download a generated text file."
},
{
"code": null,
"e": 684,
"s": 663,
"text": "Follow these steps –"
},
{
"code": null,
"e": 695,
"s": 684,
"text": "Enter data"
},
{
"code": null,
"e": 743,
"s": 695,
"text": "Click on generate, it will generate a text file"
},
{
"code": null,
"e": 793,
"s": 743,
"text": "Click on download, it will download the text file"
},
{
"code": null,
"e": 856,
"s": 793,
"text": "Here we will use id for entering and generating the text file."
},
{
"code": null,
"e": 951,
"s": 856,
"text": "When a file is generated it will give a download option, click on it, the download will start."
},
{
"code": null,
"e": 961,
"s": 951,
"text": "Approach:"
},
{
"code": null,
"e": 976,
"s": 961,
"text": "Import module."
},
{
"code": null,
"e": 1009,
"s": 976,
"text": "Make an object for chromedriver."
},
{
"code": null,
"e": 1037,
"s": 1009,
"text": "Get URL with get() methods."
},
{
"code": null,
"e": 1061,
"s": 1037,
"text": "Create automation text."
},
{
"code": null,
"e": 1101,
"s": 1061,
"text": "Create link automation for downloading."
},
{
"code": null,
"e": 1135,
"s": 1101,
"text": "Below is the full implementation:"
},
{
"code": null,
"e": 1143,
"s": 1135,
"text": "Python3"
},
{
"code": "# Import Modulefrom selenium import webdriverfrom selenium.webdriver.common.keys import Keys # Open Chromedriver = webdriver.Chrome( 'C:/Users/HP/Desktop/Drivers/chromedriver_win32/chromedriver.exe') # Open URLdriver.get( 'http://demo.automationtesting.in/FileDownload.html') # Enter textdriver.find_element_by_id('textbox').send_keys(\"Hello world\") # Generate Text Filedriver.find_element_by_id('createTxt').click() # Click on Download Buttondriver.find_element_by_id('link-to-download').click()",
"e": 1651,
"s": 1143,
"text": null
},
{
"code": null,
"e": 1659,
"s": 1651,
"text": "Output:"
},
{
"code": null,
"e": 1721,
"s": 1659,
"text": "Similarly, we can download a PDF file or any other document. "
},
{
"code": null,
"e": 1747,
"s": 1721,
"text": "Python Selenium-Exercises"
},
{
"code": null,
"e": 1763,
"s": 1747,
"text": "Python-selenium"
},
{
"code": null,
"e": 1770,
"s": 1763,
"text": "Python"
},
{
"code": null,
"e": 1868,
"s": 1770,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1900,
"s": 1868,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 1927,
"s": 1900,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 1948,
"s": 1927,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 1971,
"s": 1948,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 2027,
"s": 1971,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 2069,
"s": 2027,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 2100,
"s": 2069,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 2142,
"s": 2100,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 2181,
"s": 2142,
"text": "Python | Get unique values from a list"
}
] |
PHP | strtotime() Function | 31 Jul, 2021
The strtotime() function is a built-in function in PHP which is used to convert an English textual date-time description to a UNIX timestamp. The function accepts a string parameter in English which represents the description of date-time. For e.g., “now” refers to the current date in English date-time description. The function returns the time in seconds since the Unix Epoch. We can return the English textual date-time in date format using the date() function.
Syntax:
strtotime ($EnglishDateTime, $time_now)
Parameters: The function accepts two parameters as shown above and described below:
$EnglishDateTime – This parameter specifies the English textual date-time description, which represents the date or time to be returned. The function parses the string and returns us the time in seconds. The parameter is mandatory$time_now This parameter specifies the timestamp used to calculate the returned value. It is an optional parameter.
$EnglishDateTime – This parameter specifies the English textual date-time description, which represents the date or time to be returned. The function parses the string and returns us the time in seconds. The parameter is mandatory
$time_now This parameter specifies the timestamp used to calculate the returned value. It is an optional parameter.
Note: Since the time/date is not static, therefore the output will vary.
Below programs illustrate the strtotime() function.
Program 1: The below program demonstrates the strtotime()function when the english text is “now”.
<?php// PHP program to demonstrate the strtotime() // function when the english text is "now" // prints current time in second // since now means current echo strtotime("now"), "\n"; // prints the current time in date format echo date("Y-m-d", strtotime("now"))."\n";?>
Output:
1525378260
2018-05-03
Program 2: The below program demonstrates the strtotime()function when the english text is a date.
<?php// PHP program to demonstrate the strtotime() // function when the english text is a date // prints the converted english text in second echo strtotime("12th february 2017"), "\n"; // prints the above time in date format echo date("Y-m-d", strtotime("12th february 2017"))."\n";?>
Output:
1486857600
2017-02-12
Program 3: The below program demonstrates the strtotime()function when the english text corresponds to any day.
<?php// PHP program to demonstrate the strtotime() // function when the english text corresponds to any // day // prints the converted english text in second echo strtotime("next sunday"), "\n"; // prints the above time in date format echo date("Y-m-d", strtotime("next sunday"))."\n";?>
Output:
1525564800
2018-05-06
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.
PHP-date-time
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Insert Form Data into Database using PHP ?
How to convert array to string in PHP ?
How to receive JSON POST with PHP ?
How to get parameters from a URL string in PHP?
Split a comma delimited string into an array in PHP
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ? | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n31 Jul, 2021"
},
{
"code": null,
"e": 518,
"s": 52,
"text": "The strtotime() function is a built-in function in PHP which is used to convert an English textual date-time description to a UNIX timestamp. The function accepts a string parameter in English which represents the description of date-time. For e.g., “now” refers to the current date in English date-time description. The function returns the time in seconds since the Unix Epoch. We can return the English textual date-time in date format using the date() function."
},
{
"code": null,
"e": 526,
"s": 518,
"text": "Syntax:"
},
{
"code": null,
"e": 566,
"s": 526,
"text": "strtotime ($EnglishDateTime, $time_now)"
},
{
"code": null,
"e": 650,
"s": 566,
"text": "Parameters: The function accepts two parameters as shown above and described below:"
},
{
"code": null,
"e": 996,
"s": 650,
"text": "$EnglishDateTime – This parameter specifies the English textual date-time description, which represents the date or time to be returned. The function parses the string and returns us the time in seconds. The parameter is mandatory$time_now This parameter specifies the timestamp used to calculate the returned value. It is an optional parameter."
},
{
"code": null,
"e": 1227,
"s": 996,
"text": "$EnglishDateTime – This parameter specifies the English textual date-time description, which represents the date or time to be returned. The function parses the string and returns us the time in seconds. The parameter is mandatory"
},
{
"code": null,
"e": 1343,
"s": 1227,
"text": "$time_now This parameter specifies the timestamp used to calculate the returned value. It is an optional parameter."
},
{
"code": null,
"e": 1416,
"s": 1343,
"text": "Note: Since the time/date is not static, therefore the output will vary."
},
{
"code": null,
"e": 1468,
"s": 1416,
"text": "Below programs illustrate the strtotime() function."
},
{
"code": null,
"e": 1566,
"s": 1468,
"text": "Program 1: The below program demonstrates the strtotime()function when the english text is “now”."
},
{
"code": "<?php// PHP program to demonstrate the strtotime() // function when the english text is \"now\" // prints current time in second // since now means current echo strtotime(\"now\"), \"\\n\"; // prints the current time in date format echo date(\"Y-m-d\", strtotime(\"now\")).\"\\n\";?>",
"e": 1839,
"s": 1566,
"text": null
},
{
"code": null,
"e": 1847,
"s": 1839,
"text": "Output:"
},
{
"code": null,
"e": 1870,
"s": 1847,
"text": "1525378260\n2018-05-03\n"
},
{
"code": null,
"e": 1969,
"s": 1870,
"text": "Program 2: The below program demonstrates the strtotime()function when the english text is a date."
},
{
"code": "<?php// PHP program to demonstrate the strtotime() // function when the english text is a date // prints the converted english text in second echo strtotime(\"12th february 2017\"), \"\\n\"; // prints the above time in date format echo date(\"Y-m-d\", strtotime(\"12th february 2017\")).\"\\n\";?>",
"e": 2258,
"s": 1969,
"text": null
},
{
"code": null,
"e": 2266,
"s": 2258,
"text": "Output:"
},
{
"code": null,
"e": 2289,
"s": 2266,
"text": "1486857600\n2017-02-12\n"
},
{
"code": null,
"e": 2401,
"s": 2289,
"text": "Program 3: The below program demonstrates the strtotime()function when the english text corresponds to any day."
},
{
"code": "<?php// PHP program to demonstrate the strtotime() // function when the english text corresponds to any // day // prints the converted english text in second echo strtotime(\"next sunday\"), \"\\n\"; // prints the above time in date format echo date(\"Y-m-d\", strtotime(\"next sunday\")).\"\\n\";?>",
"e": 2693,
"s": 2401,
"text": null
},
{
"code": null,
"e": 2701,
"s": 2693,
"text": "Output:"
},
{
"code": null,
"e": 2724,
"s": 2701,
"text": "1525564800\n2018-05-06\n"
},
{
"code": null,
"e": 2893,
"s": 2724,
"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": 2907,
"s": 2893,
"text": "PHP-date-time"
},
{
"code": null,
"e": 2911,
"s": 2907,
"text": "PHP"
},
{
"code": null,
"e": 2928,
"s": 2911,
"text": "Web Technologies"
},
{
"code": null,
"e": 2932,
"s": 2928,
"text": "PHP"
},
{
"code": null,
"e": 3030,
"s": 2932,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3080,
"s": 3030,
"text": "How to Insert Form Data into Database using PHP ?"
},
{
"code": null,
"e": 3120,
"s": 3080,
"text": "How to convert array to string in PHP ?"
},
{
"code": null,
"e": 3156,
"s": 3120,
"text": "How to receive JSON POST with PHP ?"
},
{
"code": null,
"e": 3204,
"s": 3156,
"text": "How to get parameters from a URL string in PHP?"
},
{
"code": null,
"e": 3256,
"s": 3204,
"text": "Split a comma delimited string into an array in PHP"
},
{
"code": null,
"e": 3289,
"s": 3256,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 3351,
"s": 3289,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 3412,
"s": 3351,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 3462,
"s": 3412,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
Matplotlib.figure.Figure.savefig() in Python | 03 May, 2020
Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The figure module provides the top-level Artist, the Figure, which contains all the plot elements. This module is used to control the default spacing of the subplots and top level container for all plot elements.
The savefig() method figure module of matplotlib library is used to save the current figure.
Syntax: savefig(self, fname, *, transparent=None, **kwargs)
Parameters: This method accept the following parameters that are discussed below:
fname :This parameter is the file name string.
Returns: This method does not returns any value.
Below examples illustrate the matplotlib.figure.Figure.savefig() function in matplotlib.figure:
Example 1:
# Implementation of matplotlib function import numpy as npimport matplotlib.cm as cmimport matplotlib.mlab as mlabimport matplotlib.pyplot as plt fig, ax = plt.subplots()s = ax.scatter([1, 2, 3], [4, 5, 6])s.set_url('http://www.google.com') fig.savefig('scatter.svg') fig.suptitle("""matplotlib.figure.Figure.savefig()function Example\n\n""", fontweight ="bold") plt.show()
Output:
Example 2:
# Implementation of matplotlib function import numpy as npimport matplotlib.cm as cmimport matplotlib.mlab as mlabimport matplotlib.pyplot as plt fig, ax = plt.subplots()delta = 0.025x = y = np.arange(-3.0, 3.0, delta)X, Y = np.meshgrid(x, y)Z1 = np.exp(-X**2 - Y**2)Z2 = np.exp(-(X - 1)**2 - (Y - 1)**2)Z = (Z1 - Z2) * 2 im = ax.imshow(Z, interpolation ='bilinear', cmap = cm.gray, origin ='lower', extent =[-3, 3, -3, 3]) fig.savefig('image.svg') fig.suptitle("""matplotlib.figure.Figure.savefig()function Example\n\n""", fontweight ="bold") plt.show()
Output:
Matplotlib figure-class
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
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Convert integer to string in Python
Python OOPs Concepts
Python | os.path.join() method | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n03 May, 2020"
},
{
"code": null,
"e": 339,
"s": 28,
"text": "Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The figure module provides the top-level Artist, the Figure, which contains all the plot elements. This module is used to control the default spacing of the subplots and top level container for all plot elements."
},
{
"code": null,
"e": 432,
"s": 339,
"text": "The savefig() method figure module of matplotlib library is used to save the current figure."
},
{
"code": null,
"e": 492,
"s": 432,
"text": "Syntax: savefig(self, fname, *, transparent=None, **kwargs)"
},
{
"code": null,
"e": 574,
"s": 492,
"text": "Parameters: This method accept the following parameters that are discussed below:"
},
{
"code": null,
"e": 621,
"s": 574,
"text": "fname :This parameter is the file name string."
},
{
"code": null,
"e": 670,
"s": 621,
"text": "Returns: This method does not returns any value."
},
{
"code": null,
"e": 766,
"s": 670,
"text": "Below examples illustrate the matplotlib.figure.Figure.savefig() function in matplotlib.figure:"
},
{
"code": null,
"e": 777,
"s": 766,
"text": "Example 1:"
},
{
"code": "# Implementation of matplotlib function import numpy as npimport matplotlib.cm as cmimport matplotlib.mlab as mlabimport matplotlib.pyplot as plt fig, ax = plt.subplots()s = ax.scatter([1, 2, 3], [4, 5, 6])s.set_url('http://www.google.com') fig.savefig('scatter.svg') fig.suptitle(\"\"\"matplotlib.figure.Figure.savefig()function Example\\n\\n\"\"\", fontweight =\"bold\") plt.show() ",
"e": 1162,
"s": 777,
"text": null
},
{
"code": null,
"e": 1170,
"s": 1162,
"text": "Output:"
},
{
"code": null,
"e": 1181,
"s": 1170,
"text": "Example 2:"
},
{
"code": "# Implementation of matplotlib function import numpy as npimport matplotlib.cm as cmimport matplotlib.mlab as mlabimport matplotlib.pyplot as plt fig, ax = plt.subplots()delta = 0.025x = y = np.arange(-3.0, 3.0, delta)X, Y = np.meshgrid(x, y)Z1 = np.exp(-X**2 - Y**2)Z2 = np.exp(-(X - 1)**2 - (Y - 1)**2)Z = (Z1 - Z2) * 2 im = ax.imshow(Z, interpolation ='bilinear', cmap = cm.gray, origin ='lower', extent =[-3, 3, -3, 3]) fig.savefig('image.svg') fig.suptitle(\"\"\"matplotlib.figure.Figure.savefig()function Example\\n\\n\"\"\", fontweight =\"bold\") plt.show() ",
"e": 1805,
"s": 1181,
"text": null
},
{
"code": null,
"e": 1813,
"s": 1805,
"text": "Output:"
},
{
"code": null,
"e": 1837,
"s": 1813,
"text": "Matplotlib figure-class"
},
{
"code": null,
"e": 1855,
"s": 1837,
"text": "Python-matplotlib"
},
{
"code": null,
"e": 1862,
"s": 1855,
"text": "Python"
},
{
"code": null,
"e": 1960,
"s": 1862,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1978,
"s": 1960,
"text": "Python Dictionary"
},
{
"code": null,
"e": 2020,
"s": 1978,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 2042,
"s": 2020,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 2068,
"s": 2042,
"text": "Python String | replace()"
},
{
"code": null,
"e": 2100,
"s": 2068,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2129,
"s": 2100,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 2156,
"s": 2129,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2192,
"s": 2156,
"text": "Convert integer to string in Python"
},
{
"code": null,
"e": 2213,
"s": 2192,
"text": "Python OOPs Concepts"
}
] |
What is a method signature in Java? | The method signature consists of the method name and the parameter list.
Live Demo
public class MethodSignature {
public int add(int a, int b){
int c = a+b;
return c;
}
public static void main(String args[]){
MethodSignature obj = new MethodSignature();
int result = obj.add(56, 34);
System.out.println(result);
}
}
90
Method signature does not include the return type of the method. A class cannot have two methods with same signature. If we try to declare two methods with same signature you will get a compile time error.
public class MethodSignature {
public int add(int a, int b){
int c = a+b;
return c;
}
public double add(int a, int b){
double c = a+b;
return c;
}
public static void main(String args[]){
MethodSignature obj = new MethodSignature();
int result = obj.add(56, 34);
System.out.println(result);
}
}
C:\Sample>javac MethodSignature.java
MethodSignature.java:7: error: method add(int,int) is already defined in class MethodSignature
public double add(int a, int b){
^
1 error | [
{
"code": null,
"e": 1260,
"s": 1187,
"text": "The method signature consists of the method name and the parameter list."
},
{
"code": null,
"e": 1271,
"s": 1260,
"text": " Live Demo"
},
{
"code": null,
"e": 1546,
"s": 1271,
"text": "public class MethodSignature {\n public int add(int a, int b){\n int c = a+b;\n return c;\n }\n public static void main(String args[]){\n MethodSignature obj = new MethodSignature();\n int result = obj.add(56, 34);\n System.out.println(result);\n }\n}"
},
{
"code": null,
"e": 1550,
"s": 1546,
"text": "90\n"
},
{
"code": null,
"e": 1756,
"s": 1550,
"text": "Method signature does not include the return type of the method. A class cannot have two methods with same signature. If we try to declare two methods with same signature you will get a compile time error."
},
{
"code": null,
"e": 2110,
"s": 1756,
"text": "public class MethodSignature {\n public int add(int a, int b){\n int c = a+b;\n return c;\n }\n public double add(int a, int b){\n double c = a+b;\n return c;\n }\n public static void main(String args[]){\n MethodSignature obj = new MethodSignature();\n int result = obj.add(56, 34);\n System.out.println(result);\n }\n}"
},
{
"code": null,
"e": 2300,
"s": 2110,
"text": "C:\\Sample>javac MethodSignature.java\nMethodSignature.java:7: error: method add(int,int) is already defined in class MethodSignature\npublic double add(int a, int b){\n ^\n1 error\n"
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.