title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
---|---|---|
ML | BIRCH Clustering | 20 Jun, 2022
Clustering algorithms like K-means clustering do not perform clustering very efficiently and it is difficult to process large datasets with a limited amount of resources (like memory or a slower CPU). So, regular clustering algorithms do not scale well in terms of running time and quality as the size of the dataset increases. This is where BIRCH clustering comes in. Balanced Iterative Reducing and Clustering using Hierarchies (BIRCH) is a clustering algorithm that can cluster large datasets by first generating a small and compact summary of the large dataset that retains as much information as possible. This smaller summary is then clustered instead of clustering the larger dataset. BIRCH is often used to complement other clustering algorithms by creating a summary of the dataset that the other clustering algorithm can now use. However, BIRCH has one major drawback – it can only process metric attributes. A metric attribute is any attribute whose values can be represented in Euclidean space i.e., no categorical attributes should be present. Before we implement BIRCH, we must understand two important terms: Clustering Feature (CF) and CF – Tree Clustering Feature (CF): BIRCH summarizes large datasets into smaller, dense regions called Clustering Feature (CF) entries. Formally, a Clustering Feature entry is defined as an ordered triple, (N, LS, SS) where ‘N’ is the number of data points in the cluster, ‘LS’ is the linear sum of the data points and ‘SS’ is the squared sum of the data points in the cluster. It is possible for a CF entry to be composed of other CF entries. CF Tree: The CF tree is the actual compact representation that we have been speaking of so far. A CF tree is a tree where each leaf node contains a sub-cluster. Every entry in a CF tree contains a pointer to a child node and a CF entry made up of the sum of CF entries in the child nodes. There is a maximum number of entries in each leaf node. This maximum number is called the threshold. We will learn more about what this threshold value is. Parameters of BIRCH Algorithm :
threshold : threshold is the maximum number of data points a sub-cluster in the leaf node of the CF tree can hold.
branching_factor : This parameter specifies the maximum number of CF sub-clusters in each node (internal node).
n_clusters : The number of clusters to be returned after the entire BIRCH algorithm is complete i.e., number of clusters after the final clustering step. If set to None, the final clustering step is not performed and intermediate clusters are returned.
Implementation of BIRCH in Python: For the sake of this example, we will generate a dataset for clustering using scikit-learn’s make_blobs() method. To learn more about make_blobs(), you can refer to the link below: https://scikit-learn.org/stable/modules/generated/sklearn.datasets.make_blobs.html Code: To create 8 clusters with 600 randomly generated samples and then plotting the results in a scatter plot.
python3
# Import required libraries and modulesimport matplotlib.pyplot as pltfrom sklearn.datasets.samples_generator import make_blobsfrom sklearn.cluster import Birch # Generating 600 samples using make_blobsdataset, clusters = make_blobs(n_samples = 600, centers = 8, cluster_std = 0.75, random_state = 0) # Creating the BIRCH clustering modelmodel = Birch(branching_factor = 50, n_clusters = None, threshold = 1.5) # Fit the data (Training)model.fit(dataset) # Predict the same datapred = model.predict(dataset) # Creating a scatter plotplt.scatter(dataset[:, 0], dataset[:, 1], c = pred, cmap = 'rainbow', alpha = 0.7, edgecolors = 'b')plt.show()
Output Plot:
simmytarika5
Machine Learning
Python
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Decision Tree Introduction with example
Search Algorithms in AI
Getting started with Machine Learning
Introduction to Recurrent Neural Network
Support Vector Machine Algorithm
Read JSON file using Python
Python map() function
Adding new column to existing DataFrame in Pandas
Python Dictionary
How to get column names in Pandas dataframe | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n20 Jun, 2022"
},
{
"code": null,
"e": 2100,
"s": 28,
"text": "Clustering algorithms like K-means clustering do not perform clustering very efficiently and it is difficult to process large datasets with a limited amount of resources (like memory or a slower CPU). So, regular clustering algorithms do not scale well in terms of running time and quality as the size of the dataset increases. This is where BIRCH clustering comes in. Balanced Iterative Reducing and Clustering using Hierarchies (BIRCH) is a clustering algorithm that can cluster large datasets by first generating a small and compact summary of the large dataset that retains as much information as possible. This smaller summary is then clustered instead of clustering the larger dataset. BIRCH is often used to complement other clustering algorithms by creating a summary of the dataset that the other clustering algorithm can now use. However, BIRCH has one major drawback – it can only process metric attributes. A metric attribute is any attribute whose values can be represented in Euclidean space i.e., no categorical attributes should be present. Before we implement BIRCH, we must understand two important terms: Clustering Feature (CF) and CF – Tree Clustering Feature (CF): BIRCH summarizes large datasets into smaller, dense regions called Clustering Feature (CF) entries. Formally, a Clustering Feature entry is defined as an ordered triple, (N, LS, SS) where ‘N’ is the number of data points in the cluster, ‘LS’ is the linear sum of the data points and ‘SS’ is the squared sum of the data points in the cluster. It is possible for a CF entry to be composed of other CF entries. CF Tree: The CF tree is the actual compact representation that we have been speaking of so far. A CF tree is a tree where each leaf node contains a sub-cluster. Every entry in a CF tree contains a pointer to a child node and a CF entry made up of the sum of CF entries in the child nodes. There is a maximum number of entries in each leaf node. This maximum number is called the threshold. We will learn more about what this threshold value is. Parameters of BIRCH Algorithm :"
},
{
"code": null,
"e": 2216,
"s": 2100,
"text": "threshold : threshold is the maximum number of data points a sub-cluster in the leaf node of the CF tree can hold."
},
{
"code": null,
"e": 2328,
"s": 2216,
"text": "branching_factor : This parameter specifies the maximum number of CF sub-clusters in each node (internal node)."
},
{
"code": null,
"e": 2581,
"s": 2328,
"text": "n_clusters : The number of clusters to be returned after the entire BIRCH algorithm is complete i.e., number of clusters after the final clustering step. If set to None, the final clustering step is not performed and intermediate clusters are returned."
},
{
"code": null,
"e": 2993,
"s": 2581,
"text": "Implementation of BIRCH in Python: For the sake of this example, we will generate a dataset for clustering using scikit-learn’s make_blobs() method. To learn more about make_blobs(), you can refer to the link below: https://scikit-learn.org/stable/modules/generated/sklearn.datasets.make_blobs.html Code: To create 8 clusters with 600 randomly generated samples and then plotting the results in a scatter plot. "
},
{
"code": null,
"e": 3001,
"s": 2993,
"text": "python3"
},
{
"code": "# Import required libraries and modulesimport matplotlib.pyplot as pltfrom sklearn.datasets.samples_generator import make_blobsfrom sklearn.cluster import Birch # Generating 600 samples using make_blobsdataset, clusters = make_blobs(n_samples = 600, centers = 8, cluster_std = 0.75, random_state = 0) # Creating the BIRCH clustering modelmodel = Birch(branching_factor = 50, n_clusters = None, threshold = 1.5) # Fit the data (Training)model.fit(dataset) # Predict the same datapred = model.predict(dataset) # Creating a scatter plotplt.scatter(dataset[:, 0], dataset[:, 1], c = pred, cmap = 'rainbow', alpha = 0.7, edgecolors = 'b')plt.show()",
"e": 3645,
"s": 3001,
"text": null
},
{
"code": null,
"e": 3658,
"s": 3645,
"text": "Output Plot:"
},
{
"code": null,
"e": 3671,
"s": 3658,
"text": "simmytarika5"
},
{
"code": null,
"e": 3688,
"s": 3671,
"text": "Machine Learning"
},
{
"code": null,
"e": 3695,
"s": 3688,
"text": "Python"
},
{
"code": null,
"e": 3712,
"s": 3695,
"text": "Machine Learning"
},
{
"code": null,
"e": 3810,
"s": 3712,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3850,
"s": 3810,
"text": "Decision Tree Introduction with example"
},
{
"code": null,
"e": 3874,
"s": 3850,
"text": "Search Algorithms in AI"
},
{
"code": null,
"e": 3912,
"s": 3874,
"text": "Getting started with Machine Learning"
},
{
"code": null,
"e": 3953,
"s": 3912,
"text": "Introduction to Recurrent Neural Network"
},
{
"code": null,
"e": 3986,
"s": 3953,
"text": "Support Vector Machine Algorithm"
},
{
"code": null,
"e": 4014,
"s": 3986,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 4036,
"s": 4014,
"text": "Python map() function"
},
{
"code": null,
"e": 4086,
"s": 4036,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 4104,
"s": 4086,
"text": "Python Dictionary"
}
] |
Python – Pearson Correlation Test Between Two Variables | 15 Sep, 2021
What is correlation test? The strength of the association between two variables is known as correlation test. For instance, if we are interested to know whether there is a relationship between the heights of fathers and sons, a correlation coefficient can be calculated to answer this question.For know more about correlation please refer this.Methods for correlation analyses:
Parametric Correlation : It measures a linear dependence between two variables (x and y) is known as a parametric correlation test because it depends on the distribution of the data.
Non-Parametric Correlation: Kendall(tau) and Spearman(rho), which are rank-based correlation coefficients, are known as non-parametric correlation.
Note: The most commonly used method is the Parametric correlation method.Pearson Correlation formula:
x and y are two vectors of length n m, x and m, y corresponds to the means of x and y, respectively.
Note:
r takes value between -1 (negative correlation) and 1 (positive correlation).
r = 0 means no correlation.
Can not be applied to ordinal variables.
The sample size should be moderate (20-30) for good estimation.
Outliers can lead to misleading values means not robust with outliers.
To compute Pearson correlation in Python – pearsonr() function can be used. Python functions
Syntax: pearsonr(x, y)Parameters: x, y: Numeric vectors with the same length
Data: Download the csv file here.Code: Python code to find the pearson correlation
Python3
# Import those librariesimport pandas as pdfrom scipy.stats import pearsonr # Import your data into Pythondf = pd.read_csv("Auto.csv") # Convert dataframe into serieslist1 = df['weight']list2 = df['mpg'] # Apply the pearsonr()corr, _ = pearsonr(list1, list2)print('Pearsons correlation: %.3f' % corr) # This code is contributed by Amiya Rout
Output:
Pearson correlation is: -0.878
Pearson Correlation for Anscombe’s Data: Anscombe’s data also known as Anscombe’s quartet comprises of four datasets that have nearly identical simple statistical properties, yet appear very different when graphed. Each dataset consists of eleven (x, y) points. They were constructed in 1973 by the statistician Francis Anscombe to demonstrate both the importance of graphing data before analyzing it and the effect of outliers on statistical properties.Those 4 sets of 11 data-points are given here. Please download the csv file here. When we plot those points it looks like this. I am considering 3 sets of 11 data-points here.
Brief explanation of the above diagram: So, if we apply Pearson’s correlation coefficient for each of these data sets we find that it is nearly identical, it does not matter whether you actually apply into a first data set (top left) or second data set (top right) or the third data set (bottom left). So, what it seems to indicate is that if we apply the Pearson’s correlation and we find the high correlation coefficient close to one in this first data set(top left) case. The key point is here we can’t conclude immediately that if the Pearson correlation coefficient is going to be high then there is a linear relationship between them, for example in the second data set(top right) this is a non-linear relationship and still gives rise to a high value.
sweetyty
data-science
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
Convert integer to string in Python | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n15 Sep, 2021"
},
{
"code": null,
"e": 408,
"s": 28,
"text": "What is correlation test? The strength of the association between two variables is known as correlation test. For instance, if we are interested to know whether there is a relationship between the heights of fathers and sons, a correlation coefficient can be calculated to answer this question.For know more about correlation please refer this.Methods for correlation analyses: "
},
{
"code": null,
"e": 591,
"s": 408,
"text": "Parametric Correlation : It measures a linear dependence between two variables (x and y) is known as a parametric correlation test because it depends on the distribution of the data."
},
{
"code": null,
"e": 739,
"s": 591,
"text": "Non-Parametric Correlation: Kendall(tau) and Spearman(rho), which are rank-based correlation coefficients, are known as non-parametric correlation."
},
{
"code": null,
"e": 843,
"s": 739,
"text": "Note: The most commonly used method is the Parametric correlation method.Pearson Correlation formula: "
},
{
"code": null,
"e": 946,
"s": 845,
"text": "x and y are two vectors of length n m, x and m, y corresponds to the means of x and y, respectively."
},
{
"code": null,
"e": 954,
"s": 946,
"text": "Note: "
},
{
"code": null,
"e": 1032,
"s": 954,
"text": "r takes value between -1 (negative correlation) and 1 (positive correlation)."
},
{
"code": null,
"e": 1060,
"s": 1032,
"text": "r = 0 means no correlation."
},
{
"code": null,
"e": 1101,
"s": 1060,
"text": "Can not be applied to ordinal variables."
},
{
"code": null,
"e": 1165,
"s": 1101,
"text": "The sample size should be moderate (20-30) for good estimation."
},
{
"code": null,
"e": 1236,
"s": 1165,
"text": "Outliers can lead to misleading values means not robust with outliers."
},
{
"code": null,
"e": 1331,
"s": 1236,
"text": "To compute Pearson correlation in Python – pearsonr() function can be used. Python functions "
},
{
"code": null,
"e": 1410,
"s": 1331,
"text": "Syntax: pearsonr(x, y)Parameters: x, y: Numeric vectors with the same length "
},
{
"code": null,
"e": 1495,
"s": 1410,
"text": "Data: Download the csv file here.Code: Python code to find the pearson correlation "
},
{
"code": null,
"e": 1503,
"s": 1495,
"text": "Python3"
},
{
"code": "# Import those librariesimport pandas as pdfrom scipy.stats import pearsonr # Import your data into Pythondf = pd.read_csv(\"Auto.csv\") # Convert dataframe into serieslist1 = df['weight']list2 = df['mpg'] # Apply the pearsonr()corr, _ = pearsonr(list1, list2)print('Pearsons correlation: %.3f' % corr) # This code is contributed by Amiya Rout",
"e": 1845,
"s": 1503,
"text": null
},
{
"code": null,
"e": 1855,
"s": 1845,
"text": "Output: "
},
{
"code": null,
"e": 1886,
"s": 1855,
"text": "Pearson correlation is: -0.878"
},
{
"code": null,
"e": 2518,
"s": 1886,
"text": "Pearson Correlation for Anscombe’s Data: Anscombe’s data also known as Anscombe’s quartet comprises of four datasets that have nearly identical simple statistical properties, yet appear very different when graphed. Each dataset consists of eleven (x, y) points. They were constructed in 1973 by the statistician Francis Anscombe to demonstrate both the importance of graphing data before analyzing it and the effect of outliers on statistical properties.Those 4 sets of 11 data-points are given here. Please download the csv file here. When we plot those points it looks like this. I am considering 3 sets of 11 data-points here. "
},
{
"code": null,
"e": 3278,
"s": 2518,
"text": "Brief explanation of the above diagram: So, if we apply Pearson’s correlation coefficient for each of these data sets we find that it is nearly identical, it does not matter whether you actually apply into a first data set (top left) or second data set (top right) or the third data set (bottom left). So, what it seems to indicate is that if we apply the Pearson’s correlation and we find the high correlation coefficient close to one in this first data set(top left) case. The key point is here we can’t conclude immediately that if the Pearson correlation coefficient is going to be high then there is a linear relationship between them, for example in the second data set(top right) this is a non-linear relationship and still gives rise to a high value. "
},
{
"code": null,
"e": 3287,
"s": 3278,
"text": "sweetyty"
},
{
"code": null,
"e": 3300,
"s": 3287,
"text": "data-science"
},
{
"code": null,
"e": 3307,
"s": 3300,
"text": "Python"
},
{
"code": null,
"e": 3405,
"s": 3307,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3423,
"s": 3405,
"text": "Python Dictionary"
},
{
"code": null,
"e": 3465,
"s": 3423,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 3487,
"s": 3465,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 3522,
"s": 3487,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 3548,
"s": 3522,
"text": "Python String | replace()"
},
{
"code": null,
"e": 3580,
"s": 3548,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 3609,
"s": 3580,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 3636,
"s": 3609,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 3666,
"s": 3636,
"text": "Iterate over a list in Python"
}
] |
How to Print all Keys of the LinkedHashMap in Java? | 17 Dec, 2020
LinkedHashMap is a predefined class in Java that is similar to HashMap, contains a key and its respective value. Unlike HashMap, In LinkedHashMap insertion order is preserved. The task is to print all the Keys present in our LinkedHashMap in java. We have to iterate through each Key in our LinkedHashMap and print It.
Example :
Input : Key- 1 : Value-5
Key- 29 : Value-13
Key- 14 : Value-10
Key- 34 : Value-2
Key- 55 : Value-6
Output: 1, 29, 14, 34, 55
Method 1: Use for-each loop to iterate through LinkedHashMap. For each iteration, we print the respective key using getKey() method.
for(Map.Entry<Integer,Integer>ite : LHM.entrySet())
System.out.print(ite.getKey()+", ");
Example 1:
Java
// Java program to print all keys of the LinkedHashMap import java.util.*;import java.io.*; class GFG { public static void main(String[] args) { // create a linkedhashmap LinkedHashMap<Integer, Integer> LHM = new LinkedHashMap<>(); // Add mappings LHM.put(1, 5); LHM.put(29, 13); LHM.put(14, 10); LHM.put(34, 2); LHM.put(55, 6); // print keys using getKey() method for (Map.Entry<Integer, Integer> ite : LHM.entrySet()) System.out.print(ite.getKey() + ", "); }}
1, 29, 14, 34, 55,
Example 2:
Java
// Java program to print all keys of the LinkedHashMap import java.util.*;import java.io.*; class GFG { public static void main(String[] args) { // create a linkedhashmap LinkedHashMap<String, String> LHM = new LinkedHashMap<>(); // Add mappings LHM.put("Geeks", "Geeks"); LHM.put("for", "for"); LHM.put("Geeks", "Geeks"); // print keys using getKey() method for (Map.Entry<String, String> ite : LHM.entrySet()) System.out.print(ite.getKey() + ", "); }}
Geeks, for,
Method 2: (Using keySet() method)
Syntax:
hash_map.keySet()
Parameters: The method does not take any parameters.
Return Value: The method returns a set having the keys of the hash map.
Java
import java.io.*;import java.util.*; class GFG { public static void main(String[] args) { // create an instance of linked hashmap LinkedHashMap<String, String> lhm = new LinkedHashMap<String, String>(); lhm.put("One", "Geeks"); lhm.put("Two", "For"); lhm.put("Three", "Geeks"); // get all keys using the keySet method Set<String> allKeys = lhm.keySet(); // print keys System.out.println(allKeys); }}
[One, Two, Three]
Java-LinkedHashMap
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": "\n17 Dec, 2020"
},
{
"code": null,
"e": 347,
"s": 28,
"text": "LinkedHashMap is a predefined class in Java that is similar to HashMap, contains a key and its respective value. Unlike HashMap, In LinkedHashMap insertion order is preserved. The task is to print all the Keys present in our LinkedHashMap in java. We have to iterate through each Key in our LinkedHashMap and print It."
},
{
"code": null,
"e": 357,
"s": 347,
"text": "Example :"
},
{
"code": null,
"e": 500,
"s": 357,
"text": "Input : Key- 1 : Value-5\n Key- 29 : Value-13\n Key- 14 : Value-10\n Key- 34 : Value-2\n Key- 55 : Value-6\n\nOutput: 1, 29, 14, 34, 55"
},
{
"code": null,
"e": 633,
"s": 500,
"text": "Method 1: Use for-each loop to iterate through LinkedHashMap. For each iteration, we print the respective key using getKey() method."
},
{
"code": null,
"e": 726,
"s": 633,
"text": "for(Map.Entry<Integer,Integer>ite : LHM.entrySet())\n System.out.print(ite.getKey()+\", \");"
},
{
"code": null,
"e": 737,
"s": 726,
"text": "Example 1:"
},
{
"code": null,
"e": 742,
"s": 737,
"text": "Java"
},
{
"code": "// Java program to print all keys of the LinkedHashMap import java.util.*;import java.io.*; class GFG { public static void main(String[] args) { // create a linkedhashmap LinkedHashMap<Integer, Integer> LHM = new LinkedHashMap<>(); // Add mappings LHM.put(1, 5); LHM.put(29, 13); LHM.put(14, 10); LHM.put(34, 2); LHM.put(55, 6); // print keys using getKey() method for (Map.Entry<Integer, Integer> ite : LHM.entrySet()) System.out.print(ite.getKey() + \", \"); }}",
"e": 1329,
"s": 742,
"text": null
},
{
"code": null,
"e": 1348,
"s": 1329,
"text": "1, 29, 14, 34, 55,"
},
{
"code": null,
"e": 1359,
"s": 1348,
"text": "Example 2:"
},
{
"code": null,
"e": 1364,
"s": 1359,
"text": "Java"
},
{
"code": "// Java program to print all keys of the LinkedHashMap import java.util.*;import java.io.*; class GFG { public static void main(String[] args) { // create a linkedhashmap LinkedHashMap<String, String> LHM = new LinkedHashMap<>(); // Add mappings LHM.put(\"Geeks\", \"Geeks\"); LHM.put(\"for\", \"for\"); LHM.put(\"Geeks\", \"Geeks\"); // print keys using getKey() method for (Map.Entry<String, String> ite : LHM.entrySet()) System.out.print(ite.getKey() + \", \"); }}",
"e": 1911,
"s": 1364,
"text": null
},
{
"code": null,
"e": 1923,
"s": 1911,
"text": "Geeks, for,"
},
{
"code": null,
"e": 1957,
"s": 1923,
"text": "Method 2: (Using keySet() method)"
},
{
"code": null,
"e": 1965,
"s": 1957,
"text": "Syntax:"
},
{
"code": null,
"e": 1983,
"s": 1965,
"text": "hash_map.keySet()"
},
{
"code": null,
"e": 2036,
"s": 1983,
"text": "Parameters: The method does not take any parameters."
},
{
"code": null,
"e": 2108,
"s": 2036,
"text": "Return Value: The method returns a set having the keys of the hash map."
},
{
"code": null,
"e": 2113,
"s": 2108,
"text": "Java"
},
{
"code": "import java.io.*;import java.util.*; class GFG { public static void main(String[] args) { // create an instance of linked hashmap LinkedHashMap<String, String> lhm = new LinkedHashMap<String, String>(); lhm.put(\"One\", \"Geeks\"); lhm.put(\"Two\", \"For\"); lhm.put(\"Three\", \"Geeks\"); // get all keys using the keySet method Set<String> allKeys = lhm.keySet(); // print keys System.out.println(allKeys); }}",
"e": 2603,
"s": 2113,
"text": null
},
{
"code": null,
"e": 2621,
"s": 2603,
"text": "[One, Two, Three]"
},
{
"code": null,
"e": 2640,
"s": 2621,
"text": "Java-LinkedHashMap"
},
{
"code": null,
"e": 2647,
"s": 2640,
"text": "Picked"
},
{
"code": null,
"e": 2671,
"s": 2647,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 2676,
"s": 2671,
"text": "Java"
},
{
"code": null,
"e": 2690,
"s": 2676,
"text": "Java Programs"
},
{
"code": null,
"e": 2709,
"s": 2690,
"text": "Technical Scripter"
},
{
"code": null,
"e": 2714,
"s": 2709,
"text": "Java"
},
{
"code": null,
"e": 2812,
"s": 2714,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2827,
"s": 2812,
"text": "Stream In Java"
},
{
"code": null,
"e": 2848,
"s": 2827,
"text": "Introduction to Java"
},
{
"code": null,
"e": 2869,
"s": 2848,
"text": "Constructors in Java"
},
{
"code": null,
"e": 2888,
"s": 2869,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 2905,
"s": 2888,
"text": "Generics in Java"
},
{
"code": null,
"e": 2931,
"s": 2905,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 2965,
"s": 2931,
"text": "Convert Double to Integer in Java"
},
{
"code": null,
"e": 3012,
"s": 2965,
"text": "Implementing a Linked List in Java using Class"
},
{
"code": null,
"e": 3050,
"s": 3012,
"text": "Factory method design pattern in Java"
}
] |
Interact with files in Python | 12 Dec, 2019
Python too supports file handling and allows users to handle files i.e., to read, write, create, delete and move files, along with many other file handling options, to operate on files. The concept of file handling has stretched over various other languages, but the implementation is either complicated or lengthy, but alike other concepts of Python, this concept here is also easy and short.
The main focus of this article will be on the following topics.
Creating a file
Reading from file
Writing to file
Moving file
Deleting a file
The first step in using a file instance is to open a disk file. In any computer language this means establishing a communication link between your code and the external file. To create a new file I/O classes provides the member function open().
Syntax:
open(filename, mode)
Here the mode refers to the Access Mode. Access modes govern the type of operations possible in the opened file. It refers to how the file will be used once it’s opened. These modes also define the location of the File Handle in the file. File handle is like a cursor, which defines from where the data has to be read or written in the file. There are 6 access modes in python.
Read Only (‘r’): Open text file for reading. The handle is positioned at the beginning of the file. If the file does not exists, raises I/O error. This is also the default mode in which file is opened.
Read and Write (‘r+’): Open the file for reading and writing. The handle is positioned at the beginning of the file. Raises I/O error if the file does not exists.
Write Only (‘w’): Open the file for writing. For existing file, the data is truncated and over-written. The handle is positioned at the beginning of the file. Creates the file if the file does not exists.
Write and Read (‘w+’): Open the file for reading and writing. For existing file, data is truncated and over-written. The handle is positioned at the beginning of the file.
Append Only (‘a’): Open the file for writing. The file is created if it does not exist. The handle is positioned at the end of the file. The data being written will be inserted at the end, after the existing data.
Append and Read (‘a+’): Open the file for reading and writing. The file is created if it does not exist. The handle is positioned at the end of the file. The data being written will be inserted at the end, after the existing data.
Example: Suppose the folder looks like this –
# Open function to open the file "MyFile1.txt" # (same directory) in append mode and file1 = open("MyFile.txt","w+")
Output:
In the above example, open() function along with the access mode ‘w+’ is used to open a file in writing and reading mode but if the file doesn’t exist in the computer system then it creates the new file.
Note: To know more about creating a file click here.
There are three ways to read data from a text file.
read(): Returns the read bytes in form of a string. Reads n bytes, if no n specified, reads the entire file.File_object.read([n])readline(): Reads a line of the file and returns in form of a string.For specified n, reads at most n bytes. However, does not reads more than one line, even if n exceeds the length of the line.File_object.readline([n])readlines(): Reads all the lines and return them as each line a string element in a list.File_object.readlines()
read(): Returns the read bytes in form of a string. Reads n bytes, if no n specified, reads the entire file.File_object.read([n])
File_object.read([n])
readline(): Reads a line of the file and returns in form of a string.For specified n, reads at most n bytes. However, does not reads more than one line, even if n exceeds the length of the line.File_object.readline([n])
File_object.readline([n])
readlines(): Reads all the lines and return them as each line a string element in a list.File_object.readlines()
File_object.readlines()
Note: ‘\n’ is treated as a special character of two bytes.
# Program to show various ways to # read data from a file. # Creating a file file1 = open("myfile.txt", "w") L = ["This is Delhi \n", "This is Paris \n", "This is London \n"] # Writing data to a file file1.write("Hello \n") file1.writelines(L) file1.close() # to change file access modes file1 = open("myfile.txt", "r+") print("Output of Read function is ") print(file1.read()) print() # seek(n) takes the file handle to the nth # bite from the beginning. file1.seek(0) print("Output of Readline function is ") print(file1.readline()) print() file1.seek(0) # To show difference between read and readline print("Output of Read(9) function is ") print(file1.read(9)) print() file1.seek(0) print("Output of Readline(9) function is ") print(file1.readline(9)) print() file1.seek(0) # readlines function print("Output of Readlines function is ") print(file1.readlines()) print() file1.close()
Output:
Output of Read function is
Hello
This is Delhi
This is Paris
This is London
Output of Readline function is
Hello
Output of Read(9) function is
Hello
Th
Output of Readline(9) function is
Hello
Output of Readlines function is
['Hello \n', 'This is Delhi \n', 'This is Paris \n', 'This is London \n']
Note: To know more about reading from file click here.
There are two ways to write in a file.
write(): Inserts the string str1 in a single line in the text file.File_object.write(str1)writelines(): For a list of string elements, each string is inserted in the text file. Used to insert multiple strings at a single time.File_object.writelines(L) for L = [str1, str2, str3]
write(): Inserts the string str1 in a single line in the text file.File_object.write(str1)
writelines(): For a list of string elements, each string is inserted in the text file. Used to insert multiple strings at a single time.File_object.writelines(L) for L = [str1, str2, str3]
Note: ‘\n’ is treated as a special character of two bytes.
# Python program to demonstrate # writing to file # Opening a file file1 = open('myfile.txt', 'w') L = ["This is Delhi \n", "This is Paris \n", "This is London \n"] s = "Hello\n" # Writing a string to file file1.write(s) # Writing multiple strings # at a time file1.writelines(L) # Closing file file1.close() # Checking if the data is # written to file or not file1 = open('myfile.txt', 'r') print(file1.read()) file1.close()
Output:
Hello
This is Delhi
This is Paris
This is London
Note: To know more about writing to file click here.
This can be achieved using shutil.move() function from shutil module. shutil.move() method Recursively moves a file or directory (source) to another location (destination) and returns the destination. If the destination directory already exists then src is moved inside that directory. If the destination already exists but is not a directory then it may be overwritten depending on os.rename() semantics.
Example: Suppose the directory looks like this –
Inside G:
# Python program to move # files import shutil # Source path source = "D:\Pycharm projects\gfg\Test\Test4.txt" # Destination path destination = "D:\Pycharm projects\gfg\Test\G" # Move the content of # source to destination dest = shutil.move(source, destination) # print(dest) prints the # Destination of moved directory
Output:
Note: To know more about moving files click here.
os.remove() method in Python is used to remove or delete a file path. This method can not remove or delete a directory. If the specified path is a directory then OSError will be raised by the method.
Example: Suppose the file contained in the folder are:
We want to delete the file1 from the above folder. Below is the implementation.
# Python program to explain os.remove() method # importing os module import os # File name file = 'file1.txt' # File location location = "D:/Pycharm projects/GeeksforGeeks/Authors/Nikhil/" # Path path = os.path.join(location, file) # Remove the file # 'file.txt' os.remove(path)
Output:
Note: To know more about deleting files click here.
python-file-handling
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
Python | os.path.join() method
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python | Get unique values from a list
Create a directory in Python | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n12 Dec, 2019"
},
{
"code": null,
"e": 422,
"s": 28,
"text": "Python too supports file handling and allows users to handle files i.e., to read, write, create, delete and move files, along with many other file handling options, to operate on files. The concept of file handling has stretched over various other languages, but the implementation is either complicated or lengthy, but alike other concepts of Python, this concept here is also easy and short."
},
{
"code": null,
"e": 486,
"s": 422,
"text": "The main focus of this article will be on the following topics."
},
{
"code": null,
"e": 502,
"s": 486,
"text": "Creating a file"
},
{
"code": null,
"e": 520,
"s": 502,
"text": "Reading from file"
},
{
"code": null,
"e": 536,
"s": 520,
"text": "Writing to file"
},
{
"code": null,
"e": 548,
"s": 536,
"text": "Moving file"
},
{
"code": null,
"e": 564,
"s": 548,
"text": "Deleting a file"
},
{
"code": null,
"e": 809,
"s": 564,
"text": "The first step in using a file instance is to open a disk file. In any computer language this means establishing a communication link between your code and the external file. To create a new file I/O classes provides the member function open()."
},
{
"code": null,
"e": 817,
"s": 809,
"text": "Syntax:"
},
{
"code": null,
"e": 838,
"s": 817,
"text": "open(filename, mode)"
},
{
"code": null,
"e": 1216,
"s": 838,
"text": "Here the mode refers to the Access Mode. Access modes govern the type of operations possible in the opened file. It refers to how the file will be used once it’s opened. These modes also define the location of the File Handle in the file. File handle is like a cursor, which defines from where the data has to be read or written in the file. There are 6 access modes in python."
},
{
"code": null,
"e": 1418,
"s": 1216,
"text": "Read Only (‘r’): Open text file for reading. The handle is positioned at the beginning of the file. If the file does not exists, raises I/O error. This is also the default mode in which file is opened."
},
{
"code": null,
"e": 1581,
"s": 1418,
"text": "Read and Write (‘r+’): Open the file for reading and writing. The handle is positioned at the beginning of the file. Raises I/O error if the file does not exists."
},
{
"code": null,
"e": 1786,
"s": 1581,
"text": "Write Only (‘w’): Open the file for writing. For existing file, the data is truncated and over-written. The handle is positioned at the beginning of the file. Creates the file if the file does not exists."
},
{
"code": null,
"e": 1958,
"s": 1786,
"text": "Write and Read (‘w+’): Open the file for reading and writing. For existing file, data is truncated and over-written. The handle is positioned at the beginning of the file."
},
{
"code": null,
"e": 2172,
"s": 1958,
"text": "Append Only (‘a’): Open the file for writing. The file is created if it does not exist. The handle is positioned at the end of the file. The data being written will be inserted at the end, after the existing data."
},
{
"code": null,
"e": 2403,
"s": 2172,
"text": "Append and Read (‘a+’): Open the file for reading and writing. The file is created if it does not exist. The handle is positioned at the end of the file. The data being written will be inserted at the end, after the existing data."
},
{
"code": null,
"e": 2449,
"s": 2403,
"text": "Example: Suppose the folder looks like this –"
},
{
"code": "# Open function to open the file \"MyFile1.txt\" # (same directory) in append mode and file1 = open(\"MyFile.txt\",\"w+\") ",
"e": 2568,
"s": 2449,
"text": null
},
{
"code": null,
"e": 2576,
"s": 2568,
"text": "Output:"
},
{
"code": null,
"e": 2780,
"s": 2576,
"text": "In the above example, open() function along with the access mode ‘w+’ is used to open a file in writing and reading mode but if the file doesn’t exist in the computer system then it creates the new file."
},
{
"code": null,
"e": 2833,
"s": 2780,
"text": "Note: To know more about creating a file click here."
},
{
"code": null,
"e": 2885,
"s": 2833,
"text": "There are three ways to read data from a text file."
},
{
"code": null,
"e": 3346,
"s": 2885,
"text": "read(): Returns the read bytes in form of a string. Reads n bytes, if no n specified, reads the entire file.File_object.read([n])readline(): Reads a line of the file and returns in form of a string.For specified n, reads at most n bytes. However, does not reads more than one line, even if n exceeds the length of the line.File_object.readline([n])readlines(): Reads all the lines and return them as each line a string element in a list.File_object.readlines()"
},
{
"code": null,
"e": 3476,
"s": 3346,
"text": "read(): Returns the read bytes in form of a string. Reads n bytes, if no n specified, reads the entire file.File_object.read([n])"
},
{
"code": null,
"e": 3498,
"s": 3476,
"text": "File_object.read([n])"
},
{
"code": null,
"e": 3718,
"s": 3498,
"text": "readline(): Reads a line of the file and returns in form of a string.For specified n, reads at most n bytes. However, does not reads more than one line, even if n exceeds the length of the line.File_object.readline([n])"
},
{
"code": null,
"e": 3744,
"s": 3718,
"text": "File_object.readline([n])"
},
{
"code": null,
"e": 3857,
"s": 3744,
"text": "readlines(): Reads all the lines and return them as each line a string element in a list.File_object.readlines()"
},
{
"code": null,
"e": 3881,
"s": 3857,
"text": "File_object.readlines()"
},
{
"code": null,
"e": 3940,
"s": 3881,
"text": "Note: ‘\\n’ is treated as a special character of two bytes."
},
{
"code": "# Program to show various ways to # read data from a file. # Creating a file file1 = open(\"myfile.txt\", \"w\") L = [\"This is Delhi \\n\", \"This is Paris \\n\", \"This is London \\n\"] # Writing data to a file file1.write(\"Hello \\n\") file1.writelines(L) file1.close() # to change file access modes file1 = open(\"myfile.txt\", \"r+\") print(\"Output of Read function is \") print(file1.read()) print() # seek(n) takes the file handle to the nth # bite from the beginning. file1.seek(0) print(\"Output of Readline function is \") print(file1.readline()) print() file1.seek(0) # To show difference between read and readline print(\"Output of Read(9) function is \") print(file1.read(9)) print() file1.seek(0) print(\"Output of Readline(9) function is \") print(file1.readline(9)) print() file1.seek(0) # readlines function print(\"Output of Readlines function is \") print(file1.readlines()) print() file1.close() ",
"e": 4885,
"s": 3940,
"text": null
},
{
"code": null,
"e": 4893,
"s": 4885,
"text": "Output:"
},
{
"code": null,
"e": 5199,
"s": 4893,
"text": "Output of Read function is\nHello\nThis is Delhi\nThis is Paris\nThis is London\n\n\nOutput of Readline function is\nHello\n\n\nOutput of Read(9) function is\nHello\nTh\n\nOutput of Readline(9) function is\nHello\n\n\nOutput of Readlines function is\n['Hello \\n', 'This is Delhi \\n', 'This is Paris \\n', 'This is London \\n']\n"
},
{
"code": null,
"e": 5254,
"s": 5199,
"text": "Note: To know more about reading from file click here."
},
{
"code": null,
"e": 5293,
"s": 5254,
"text": "There are two ways to write in a file."
},
{
"code": null,
"e": 5572,
"s": 5293,
"text": "write(): Inserts the string str1 in a single line in the text file.File_object.write(str1)writelines(): For a list of string elements, each string is inserted in the text file. Used to insert multiple strings at a single time.File_object.writelines(L) for L = [str1, str2, str3]"
},
{
"code": null,
"e": 5663,
"s": 5572,
"text": "write(): Inserts the string str1 in a single line in the text file.File_object.write(str1)"
},
{
"code": null,
"e": 5852,
"s": 5663,
"text": "writelines(): For a list of string elements, each string is inserted in the text file. Used to insert multiple strings at a single time.File_object.writelines(L) for L = [str1, str2, str3]"
},
{
"code": null,
"e": 5911,
"s": 5852,
"text": "Note: ‘\\n’ is treated as a special character of two bytes."
},
{
"code": "# Python program to demonstrate # writing to file # Opening a file file1 = open('myfile.txt', 'w') L = [\"This is Delhi \\n\", \"This is Paris \\n\", \"This is London \\n\"] s = \"Hello\\n\" # Writing a string to file file1.write(s) # Writing multiple strings # at a time file1.writelines(L) # Closing file file1.close() # Checking if the data is # written to file or not file1 = open('myfile.txt', 'r') print(file1.read()) file1.close() ",
"e": 6357,
"s": 5911,
"text": null
},
{
"code": null,
"e": 6365,
"s": 6357,
"text": "Output:"
},
{
"code": null,
"e": 6415,
"s": 6365,
"text": "Hello\nThis is Delhi\nThis is Paris\nThis is London\n"
},
{
"code": null,
"e": 6468,
"s": 6415,
"text": "Note: To know more about writing to file click here."
},
{
"code": null,
"e": 6874,
"s": 6468,
"text": "This can be achieved using shutil.move() function from shutil module. shutil.move() method Recursively moves a file or directory (source) to another location (destination) and returns the destination. If the destination directory already exists then src is moved inside that directory. If the destination already exists but is not a directory then it may be overwritten depending on os.rename() semantics."
},
{
"code": null,
"e": 6923,
"s": 6874,
"text": "Example: Suppose the directory looks like this –"
},
{
"code": null,
"e": 6933,
"s": 6923,
"text": "Inside G:"
},
{
"code": "# Python program to move # files import shutil # Source path source = \"D:\\Pycharm projects\\gfg\\Test\\Test4.txt\" # Destination path destination = \"D:\\Pycharm projects\\gfg\\Test\\G\" # Move the content of # source to destination dest = shutil.move(source, destination) # print(dest) prints the # Destination of moved directory ",
"e": 7277,
"s": 6933,
"text": null
},
{
"code": null,
"e": 7285,
"s": 7277,
"text": "Output:"
},
{
"code": null,
"e": 7335,
"s": 7285,
"text": "Note: To know more about moving files click here."
},
{
"code": null,
"e": 7535,
"s": 7335,
"text": "os.remove() method in Python is used to remove or delete a file path. This method can not remove or delete a directory. If the specified path is a directory then OSError will be raised by the method."
},
{
"code": null,
"e": 7590,
"s": 7535,
"text": "Example: Suppose the file contained in the folder are:"
},
{
"code": null,
"e": 7670,
"s": 7590,
"text": "We want to delete the file1 from the above folder. Below is the implementation."
},
{
"code": "# Python program to explain os.remove() method # importing os module import os # File name file = 'file1.txt' # File location location = \"D:/Pycharm projects/GeeksforGeeks/Authors/Nikhil/\" # Path path = os.path.join(location, file) # Remove the file # 'file.txt' os.remove(path) ",
"e": 7992,
"s": 7670,
"text": null
},
{
"code": null,
"e": 8000,
"s": 7992,
"text": "Output:"
},
{
"code": null,
"e": 8052,
"s": 8000,
"text": "Note: To know more about deleting files click here."
},
{
"code": null,
"e": 8073,
"s": 8052,
"text": "python-file-handling"
},
{
"code": null,
"e": 8080,
"s": 8073,
"text": "Python"
},
{
"code": null,
"e": 8099,
"s": 8080,
"text": "Technical Scripter"
},
{
"code": null,
"e": 8197,
"s": 8099,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 8229,
"s": 8197,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 8256,
"s": 8229,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 8277,
"s": 8256,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 8300,
"s": 8277,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 8356,
"s": 8300,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 8387,
"s": 8356,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 8429,
"s": 8387,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 8471,
"s": 8429,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 8510,
"s": 8471,
"text": "Python | Get unique values from a list"
}
] |
SQL | Date Functions (Set-1) | 20 Jul, 2018
In SQL, dates are complicated for newbies, since while working with a database, the format of the date in the table must be matched with the input date in order to insert. In various scenarios instead of date, datetime (time is also involved with date) is used.
Some of the important date functions have been already discussed in the previous post. The basic idea of this post is to know the working or syntax of all the date functions:
Below are the date functions that are used in SQL:
ADDDATE(): It returns a date after a certain time/date interval has been added.Syntax: SELECT ADDTIME("2018-07-16 02:52:47", "2");Output: 2018-07-16 02:52:49ADDTIME(): It returns a time / date time after a certain time interval has been added.Syntax: SELECT ADDTIME("2017-06-15 09:34:21", "2");Output: 2017-06-15 09:34:23CURDATE(): It returns the current date.Syntax: SELECT CURDATE();Output: 2018-07-16CURRENT_DATE(): It returns the current date.Syntax: SELECT CURRENT_DATE();Output: 2018-07-16CURRENT_TIME(): It returns the current time.Syntax: SELECT CURRENT_TIME();Output: 02:53:15CURRENT_TIMESTAMP(): It returns the current date and time.Syntax: SELECT CURRENT_TIMESTAMP();Output: 2018-07-16 02:53:21CURTIME(): It returns the current time.Syntax: SELECT CURTIME();Output: 02:53:28DATE(): It extracts the date value from a date or date time expression.Syntax: SELECT DATE("2017-06-15");Output: 2017-06-15DATEDIFF(): It returns the difference in days between two date values.Syntax: SELECT DATEDIFF("2017-06-25", "2017-06-15");Output: 10DATE_ADD(): It returns a date after a certain time/date interval has been added.Syntax: SELECT DATE_ADD("2018-07-16", INTERVAL 10 DAY);Output: 2018-07-16DATE_FORMAT(): It formats a date as specified by a format mask.Syntax: SELECT DATE_FORMAT("2018-06-15", "%Y");Output: 2018DATE_SUB(): It returns a date after a certain time/date interval has been subtracted.Syntax: SELECT DATE_SUB("2017-06-15", INTERVAL 10 DAY);Output: 2018-07-16DAY(): It returns the day portion of a date value.Syntax: SELECT DAY("2018-07-16");Output: 16DAYNAME(): It returns the weekday name for a date.Syntax: SELECT DAYNAME('2008-05-15');Output: ThursdayDAYOFMONTH(): It returns the day portion of a date value.Syntax: SELECT DAYOFMONTH('2018-07-16');Output: 16DAYWEEK(): It returns the weekday index for a date value.Syntax: SELECT WEEKDAY("2018-07-16");Output: 0DAYOFYEAR(): It returns the day of the year for a date value.Syntax: SELECT DAYOFYEAR("2018-07-16");Output: 197EXTRACT(): It extracts parts from a date.Syntax: SELECT EXTRACT(MONTH FROM "2018-07-16");Output: 7FROM_DAYS(): It returns a date value from a numeric representation of the day.Syntax: SELECT FROM_DAYS(685467);Output: 1876-09-29HOUR(): It returns the hour portion of a date value.Syntax: SELECT HOUR("2018-07-16 09:34:00");Output: 9LAST_DAY(): It returns the last day of the month for a given date.Syntax: SELECT LAST_DAY('2018-07-16');Output: 2018-07-31LOCALTIME(): It returns the current date and time.Syntax: SELECT LOCALTIME();Output: 2018-07-16 02:56:42LOCALTIMESTAMP(): It returns the current date and time.Syntax: SELECT LOCALTIMESTAMP();Output: 2018-07-16 02:56:48MAKEDATE(): It returns the date for a certain year and day-of-year value.Syntax: SELECT MAKEDATE(2009, 138);Output: 2009-05-18MAKETIME(): It returns the time for a certain hour, minute, second combination.Syntax: SELECT MAKETIME(11, 35, 4);Output: 11:35:04
ADDDATE(): It returns a date after a certain time/date interval has been added.Syntax: SELECT ADDTIME("2018-07-16 02:52:47", "2");Output: 2018-07-16 02:52:49
Syntax: SELECT ADDTIME("2018-07-16 02:52:47", "2");
Output: 2018-07-16 02:52:49
ADDTIME(): It returns a time / date time after a certain time interval has been added.Syntax: SELECT ADDTIME("2017-06-15 09:34:21", "2");Output: 2017-06-15 09:34:23
Syntax: SELECT ADDTIME("2017-06-15 09:34:21", "2");
Output: 2017-06-15 09:34:23
CURDATE(): It returns the current date.Syntax: SELECT CURDATE();Output: 2018-07-16
Syntax: SELECT CURDATE();
Output: 2018-07-16
CURRENT_DATE(): It returns the current date.Syntax: SELECT CURRENT_DATE();Output: 2018-07-16
Syntax: SELECT CURRENT_DATE();
Output: 2018-07-16
CURRENT_TIME(): It returns the current time.Syntax: SELECT CURRENT_TIME();Output: 02:53:15
Syntax: SELECT CURRENT_TIME();
Output: 02:53:15
CURRENT_TIMESTAMP(): It returns the current date and time.Syntax: SELECT CURRENT_TIMESTAMP();Output: 2018-07-16 02:53:21
Syntax: SELECT CURRENT_TIMESTAMP();
Output: 2018-07-16 02:53:21
CURTIME(): It returns the current time.Syntax: SELECT CURTIME();Output: 02:53:28
Syntax: SELECT CURTIME();
Output: 02:53:28
DATE(): It extracts the date value from a date or date time expression.Syntax: SELECT DATE("2017-06-15");Output: 2017-06-15
Syntax: SELECT DATE("2017-06-15");
Output: 2017-06-15
DATEDIFF(): It returns the difference in days between two date values.Syntax: SELECT DATEDIFF("2017-06-25", "2017-06-15");Output: 10
Syntax: SELECT DATEDIFF("2017-06-25", "2017-06-15");
Output: 10
DATE_ADD(): It returns a date after a certain time/date interval has been added.Syntax: SELECT DATE_ADD("2018-07-16", INTERVAL 10 DAY);Output: 2018-07-16
Syntax: SELECT DATE_ADD("2018-07-16", INTERVAL 10 DAY);
Output: 2018-07-16
DATE_FORMAT(): It formats a date as specified by a format mask.Syntax: SELECT DATE_FORMAT("2018-06-15", "%Y");Output: 2018
Syntax: SELECT DATE_FORMAT("2018-06-15", "%Y");
Output: 2018
DATE_SUB(): It returns a date after a certain time/date interval has been subtracted.Syntax: SELECT DATE_SUB("2017-06-15", INTERVAL 10 DAY);Output: 2018-07-16
Syntax: SELECT DATE_SUB("2017-06-15", INTERVAL 10 DAY);
Output: 2018-07-16
DAY(): It returns the day portion of a date value.Syntax: SELECT DAY("2018-07-16");Output: 16
Syntax: SELECT DAY("2018-07-16");
Output: 16
DAYNAME(): It returns the weekday name for a date.Syntax: SELECT DAYNAME('2008-05-15');Output: Thursday
Syntax: SELECT DAYNAME('2008-05-15');
Output: Thursday
DAYOFMONTH(): It returns the day portion of a date value.Syntax: SELECT DAYOFMONTH('2018-07-16');Output: 16
Syntax: SELECT DAYOFMONTH('2018-07-16');
Output: 16
DAYWEEK(): It returns the weekday index for a date value.Syntax: SELECT WEEKDAY("2018-07-16");Output: 0
Syntax: SELECT WEEKDAY("2018-07-16");
Output: 0
DAYOFYEAR(): It returns the day of the year for a date value.Syntax: SELECT DAYOFYEAR("2018-07-16");Output: 197
Syntax: SELECT DAYOFYEAR("2018-07-16");
Output: 197
EXTRACT(): It extracts parts from a date.Syntax: SELECT EXTRACT(MONTH FROM "2018-07-16");Output: 7
Syntax: SELECT EXTRACT(MONTH FROM "2018-07-16");
Output: 7
FROM_DAYS(): It returns a date value from a numeric representation of the day.Syntax: SELECT FROM_DAYS(685467);Output: 1876-09-29
Syntax: SELECT FROM_DAYS(685467);
Output: 1876-09-29
HOUR(): It returns the hour portion of a date value.Syntax: SELECT HOUR("2018-07-16 09:34:00");Output: 9
Syntax: SELECT HOUR("2018-07-16 09:34:00");
Output: 9
LAST_DAY(): It returns the last day of the month for a given date.Syntax: SELECT LAST_DAY('2018-07-16');Output: 2018-07-31
Syntax: SELECT LAST_DAY('2018-07-16');
Output: 2018-07-31
LOCALTIME(): It returns the current date and time.Syntax: SELECT LOCALTIME();Output: 2018-07-16 02:56:42
Syntax: SELECT LOCALTIME();
Output: 2018-07-16 02:56:42
LOCALTIMESTAMP(): It returns the current date and time.Syntax: SELECT LOCALTIMESTAMP();Output: 2018-07-16 02:56:48
Syntax: SELECT LOCALTIMESTAMP();
Output: 2018-07-16 02:56:48
MAKEDATE(): It returns the date for a certain year and day-of-year value.Syntax: SELECT MAKEDATE(2009, 138);Output: 2009-05-18
Syntax: SELECT MAKEDATE(2009, 138);
Output: 2009-05-18
MAKETIME(): It returns the time for a certain hour, minute, second combination.Syntax: SELECT MAKETIME(11, 35, 4);Output: 11:35:04
Syntax: SELECT MAKETIME(11, 35, 4);
Output: 11:35:04
SQL-Functions
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
CTE in SQL
SQL Trigger | Student Database
How to Update Multiple Columns in Single Update Statement in SQL?
SQL Interview Questions
SQL | Views
Difference between DELETE, DROP and TRUNCATE
Window functions in SQL
MySQL | Group_CONCAT() Function
Difference between DELETE and TRUNCATE
Difference between DDL and DML in DBMS | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n20 Jul, 2018"
},
{
"code": null,
"e": 315,
"s": 53,
"text": "In SQL, dates are complicated for newbies, since while working with a database, the format of the date in the table must be matched with the input date in order to insert. In various scenarios instead of date, datetime (time is also involved with date) is used."
},
{
"code": null,
"e": 490,
"s": 315,
"text": "Some of the important date functions have been already discussed in the previous post. The basic idea of this post is to know the working or syntax of all the date functions:"
},
{
"code": null,
"e": 541,
"s": 490,
"text": "Below are the date functions that are used in SQL:"
},
{
"code": null,
"e": 3459,
"s": 541,
"text": "ADDDATE(): It returns a date after a certain time/date interval has been added.Syntax: SELECT ADDTIME(\"2018-07-16 02:52:47\", \"2\");Output: 2018-07-16 02:52:49ADDTIME(): It returns a time / date time after a certain time interval has been added.Syntax: SELECT ADDTIME(\"2017-06-15 09:34:21\", \"2\");Output: 2017-06-15 09:34:23CURDATE(): It returns the current date.Syntax: SELECT CURDATE();Output: 2018-07-16CURRENT_DATE(): It returns the current date.Syntax: SELECT CURRENT_DATE();Output: 2018-07-16CURRENT_TIME(): It returns the current time.Syntax: SELECT CURRENT_TIME();Output: 02:53:15CURRENT_TIMESTAMP(): It returns the current date and time.Syntax: SELECT CURRENT_TIMESTAMP();Output: 2018-07-16 02:53:21CURTIME(): It returns the current time.Syntax: SELECT CURTIME();Output: 02:53:28DATE(): It extracts the date value from a date or date time expression.Syntax: SELECT DATE(\"2017-06-15\");Output: 2017-06-15DATEDIFF(): It returns the difference in days between two date values.Syntax: SELECT DATEDIFF(\"2017-06-25\", \"2017-06-15\");Output: 10DATE_ADD(): It returns a date after a certain time/date interval has been added.Syntax: SELECT DATE_ADD(\"2018-07-16\", INTERVAL 10 DAY);Output: 2018-07-16DATE_FORMAT(): It formats a date as specified by a format mask.Syntax: SELECT DATE_FORMAT(\"2018-06-15\", \"%Y\");Output: 2018DATE_SUB(): It returns a date after a certain time/date interval has been subtracted.Syntax: SELECT DATE_SUB(\"2017-06-15\", INTERVAL 10 DAY);Output: 2018-07-16DAY(): It returns the day portion of a date value.Syntax: SELECT DAY(\"2018-07-16\");Output: 16DAYNAME(): It returns the weekday name for a date.Syntax: SELECT DAYNAME('2008-05-15');Output: ThursdayDAYOFMONTH(): It returns the day portion of a date value.Syntax: SELECT DAYOFMONTH('2018-07-16');Output: 16DAYWEEK(): It returns the weekday index for a date value.Syntax: SELECT WEEKDAY(\"2018-07-16\");Output: 0DAYOFYEAR(): It returns the day of the year for a date value.Syntax: SELECT DAYOFYEAR(\"2018-07-16\");Output: 197EXTRACT(): It extracts parts from a date.Syntax: SELECT EXTRACT(MONTH FROM \"2018-07-16\");Output: 7FROM_DAYS(): It returns a date value from a numeric representation of the day.Syntax: SELECT FROM_DAYS(685467);Output: 1876-09-29HOUR(): It returns the hour portion of a date value.Syntax: SELECT HOUR(\"2018-07-16 09:34:00\");Output: 9LAST_DAY(): It returns the last day of the month for a given date.Syntax: SELECT LAST_DAY('2018-07-16');Output: 2018-07-31LOCALTIME(): It returns the current date and time.Syntax: SELECT LOCALTIME();Output: 2018-07-16 02:56:42LOCALTIMESTAMP(): It returns the current date and time.Syntax: SELECT LOCALTIMESTAMP();Output: 2018-07-16 02:56:48MAKEDATE(): It returns the date for a certain year and day-of-year value.Syntax: SELECT MAKEDATE(2009, 138);Output: 2009-05-18MAKETIME(): It returns the time for a certain hour, minute, second combination.Syntax: SELECT MAKETIME(11, 35, 4);Output: 11:35:04"
},
{
"code": null,
"e": 3617,
"s": 3459,
"text": "ADDDATE(): It returns a date after a certain time/date interval has been added.Syntax: SELECT ADDTIME(\"2018-07-16 02:52:47\", \"2\");Output: 2018-07-16 02:52:49"
},
{
"code": null,
"e": 3669,
"s": 3617,
"text": "Syntax: SELECT ADDTIME(\"2018-07-16 02:52:47\", \"2\");"
},
{
"code": null,
"e": 3697,
"s": 3669,
"text": "Output: 2018-07-16 02:52:49"
},
{
"code": null,
"e": 3862,
"s": 3697,
"text": "ADDTIME(): It returns a time / date time after a certain time interval has been added.Syntax: SELECT ADDTIME(\"2017-06-15 09:34:21\", \"2\");Output: 2017-06-15 09:34:23"
},
{
"code": null,
"e": 3914,
"s": 3862,
"text": "Syntax: SELECT ADDTIME(\"2017-06-15 09:34:21\", \"2\");"
},
{
"code": null,
"e": 3942,
"s": 3914,
"text": "Output: 2017-06-15 09:34:23"
},
{
"code": null,
"e": 4025,
"s": 3942,
"text": "CURDATE(): It returns the current date.Syntax: SELECT CURDATE();Output: 2018-07-16"
},
{
"code": null,
"e": 4051,
"s": 4025,
"text": "Syntax: SELECT CURDATE();"
},
{
"code": null,
"e": 4070,
"s": 4051,
"text": "Output: 2018-07-16"
},
{
"code": null,
"e": 4163,
"s": 4070,
"text": "CURRENT_DATE(): It returns the current date.Syntax: SELECT CURRENT_DATE();Output: 2018-07-16"
},
{
"code": null,
"e": 4194,
"s": 4163,
"text": "Syntax: SELECT CURRENT_DATE();"
},
{
"code": null,
"e": 4213,
"s": 4194,
"text": "Output: 2018-07-16"
},
{
"code": null,
"e": 4304,
"s": 4213,
"text": "CURRENT_TIME(): It returns the current time.Syntax: SELECT CURRENT_TIME();Output: 02:53:15"
},
{
"code": null,
"e": 4335,
"s": 4304,
"text": "Syntax: SELECT CURRENT_TIME();"
},
{
"code": null,
"e": 4352,
"s": 4335,
"text": "Output: 02:53:15"
},
{
"code": null,
"e": 4473,
"s": 4352,
"text": "CURRENT_TIMESTAMP(): It returns the current date and time.Syntax: SELECT CURRENT_TIMESTAMP();Output: 2018-07-16 02:53:21"
},
{
"code": null,
"e": 4509,
"s": 4473,
"text": "Syntax: SELECT CURRENT_TIMESTAMP();"
},
{
"code": null,
"e": 4537,
"s": 4509,
"text": "Output: 2018-07-16 02:53:21"
},
{
"code": null,
"e": 4618,
"s": 4537,
"text": "CURTIME(): It returns the current time.Syntax: SELECT CURTIME();Output: 02:53:28"
},
{
"code": null,
"e": 4644,
"s": 4618,
"text": "Syntax: SELECT CURTIME();"
},
{
"code": null,
"e": 4661,
"s": 4644,
"text": "Output: 02:53:28"
},
{
"code": null,
"e": 4785,
"s": 4661,
"text": "DATE(): It extracts the date value from a date or date time expression.Syntax: SELECT DATE(\"2017-06-15\");Output: 2017-06-15"
},
{
"code": null,
"e": 4820,
"s": 4785,
"text": "Syntax: SELECT DATE(\"2017-06-15\");"
},
{
"code": null,
"e": 4839,
"s": 4820,
"text": "Output: 2017-06-15"
},
{
"code": null,
"e": 4972,
"s": 4839,
"text": "DATEDIFF(): It returns the difference in days between two date values.Syntax: SELECT DATEDIFF(\"2017-06-25\", \"2017-06-15\");Output: 10"
},
{
"code": null,
"e": 5025,
"s": 4972,
"text": "Syntax: SELECT DATEDIFF(\"2017-06-25\", \"2017-06-15\");"
},
{
"code": null,
"e": 5036,
"s": 5025,
"text": "Output: 10"
},
{
"code": null,
"e": 5190,
"s": 5036,
"text": "DATE_ADD(): It returns a date after a certain time/date interval has been added.Syntax: SELECT DATE_ADD(\"2018-07-16\", INTERVAL 10 DAY);Output: 2018-07-16"
},
{
"code": null,
"e": 5246,
"s": 5190,
"text": "Syntax: SELECT DATE_ADD(\"2018-07-16\", INTERVAL 10 DAY);"
},
{
"code": null,
"e": 5265,
"s": 5246,
"text": "Output: 2018-07-16"
},
{
"code": null,
"e": 5388,
"s": 5265,
"text": "DATE_FORMAT(): It formats a date as specified by a format mask.Syntax: SELECT DATE_FORMAT(\"2018-06-15\", \"%Y\");Output: 2018"
},
{
"code": null,
"e": 5436,
"s": 5388,
"text": "Syntax: SELECT DATE_FORMAT(\"2018-06-15\", \"%Y\");"
},
{
"code": null,
"e": 5449,
"s": 5436,
"text": "Output: 2018"
},
{
"code": null,
"e": 5608,
"s": 5449,
"text": "DATE_SUB(): It returns a date after a certain time/date interval has been subtracted.Syntax: SELECT DATE_SUB(\"2017-06-15\", INTERVAL 10 DAY);Output: 2018-07-16"
},
{
"code": null,
"e": 5664,
"s": 5608,
"text": "Syntax: SELECT DATE_SUB(\"2017-06-15\", INTERVAL 10 DAY);"
},
{
"code": null,
"e": 5683,
"s": 5664,
"text": "Output: 2018-07-16"
},
{
"code": null,
"e": 5777,
"s": 5683,
"text": "DAY(): It returns the day portion of a date value.Syntax: SELECT DAY(\"2018-07-16\");Output: 16"
},
{
"code": null,
"e": 5811,
"s": 5777,
"text": "Syntax: SELECT DAY(\"2018-07-16\");"
},
{
"code": null,
"e": 5822,
"s": 5811,
"text": "Output: 16"
},
{
"code": null,
"e": 5926,
"s": 5822,
"text": "DAYNAME(): It returns the weekday name for a date.Syntax: SELECT DAYNAME('2008-05-15');Output: Thursday"
},
{
"code": null,
"e": 5964,
"s": 5926,
"text": "Syntax: SELECT DAYNAME('2008-05-15');"
},
{
"code": null,
"e": 5981,
"s": 5964,
"text": "Output: Thursday"
},
{
"code": null,
"e": 6089,
"s": 5981,
"text": "DAYOFMONTH(): It returns the day portion of a date value.Syntax: SELECT DAYOFMONTH('2018-07-16');Output: 16"
},
{
"code": null,
"e": 6130,
"s": 6089,
"text": "Syntax: SELECT DAYOFMONTH('2018-07-16');"
},
{
"code": null,
"e": 6141,
"s": 6130,
"text": "Output: 16"
},
{
"code": null,
"e": 6245,
"s": 6141,
"text": "DAYWEEK(): It returns the weekday index for a date value.Syntax: SELECT WEEKDAY(\"2018-07-16\");Output: 0"
},
{
"code": null,
"e": 6283,
"s": 6245,
"text": "Syntax: SELECT WEEKDAY(\"2018-07-16\");"
},
{
"code": null,
"e": 6293,
"s": 6283,
"text": "Output: 0"
},
{
"code": null,
"e": 6405,
"s": 6293,
"text": "DAYOFYEAR(): It returns the day of the year for a date value.Syntax: SELECT DAYOFYEAR(\"2018-07-16\");Output: 197"
},
{
"code": null,
"e": 6445,
"s": 6405,
"text": "Syntax: SELECT DAYOFYEAR(\"2018-07-16\");"
},
{
"code": null,
"e": 6457,
"s": 6445,
"text": "Output: 197"
},
{
"code": null,
"e": 6556,
"s": 6457,
"text": "EXTRACT(): It extracts parts from a date.Syntax: SELECT EXTRACT(MONTH FROM \"2018-07-16\");Output: 7"
},
{
"code": null,
"e": 6605,
"s": 6556,
"text": "Syntax: SELECT EXTRACT(MONTH FROM \"2018-07-16\");"
},
{
"code": null,
"e": 6615,
"s": 6605,
"text": "Output: 7"
},
{
"code": null,
"e": 6745,
"s": 6615,
"text": "FROM_DAYS(): It returns a date value from a numeric representation of the day.Syntax: SELECT FROM_DAYS(685467);Output: 1876-09-29"
},
{
"code": null,
"e": 6779,
"s": 6745,
"text": "Syntax: SELECT FROM_DAYS(685467);"
},
{
"code": null,
"e": 6798,
"s": 6779,
"text": "Output: 1876-09-29"
},
{
"code": null,
"e": 6903,
"s": 6798,
"text": "HOUR(): It returns the hour portion of a date value.Syntax: SELECT HOUR(\"2018-07-16 09:34:00\");Output: 9"
},
{
"code": null,
"e": 6947,
"s": 6903,
"text": "Syntax: SELECT HOUR(\"2018-07-16 09:34:00\");"
},
{
"code": null,
"e": 6957,
"s": 6947,
"text": "Output: 9"
},
{
"code": null,
"e": 7080,
"s": 6957,
"text": "LAST_DAY(): It returns the last day of the month for a given date.Syntax: SELECT LAST_DAY('2018-07-16');Output: 2018-07-31"
},
{
"code": null,
"e": 7119,
"s": 7080,
"text": "Syntax: SELECT LAST_DAY('2018-07-16');"
},
{
"code": null,
"e": 7138,
"s": 7119,
"text": "Output: 2018-07-31"
},
{
"code": null,
"e": 7243,
"s": 7138,
"text": "LOCALTIME(): It returns the current date and time.Syntax: SELECT LOCALTIME();Output: 2018-07-16 02:56:42"
},
{
"code": null,
"e": 7271,
"s": 7243,
"text": "Syntax: SELECT LOCALTIME();"
},
{
"code": null,
"e": 7299,
"s": 7271,
"text": "Output: 2018-07-16 02:56:42"
},
{
"code": null,
"e": 7414,
"s": 7299,
"text": "LOCALTIMESTAMP(): It returns the current date and time.Syntax: SELECT LOCALTIMESTAMP();Output: 2018-07-16 02:56:48"
},
{
"code": null,
"e": 7447,
"s": 7414,
"text": "Syntax: SELECT LOCALTIMESTAMP();"
},
{
"code": null,
"e": 7475,
"s": 7447,
"text": "Output: 2018-07-16 02:56:48"
},
{
"code": null,
"e": 7602,
"s": 7475,
"text": "MAKEDATE(): It returns the date for a certain year and day-of-year value.Syntax: SELECT MAKEDATE(2009, 138);Output: 2009-05-18"
},
{
"code": null,
"e": 7638,
"s": 7602,
"text": "Syntax: SELECT MAKEDATE(2009, 138);"
},
{
"code": null,
"e": 7657,
"s": 7638,
"text": "Output: 2009-05-18"
},
{
"code": null,
"e": 7788,
"s": 7657,
"text": "MAKETIME(): It returns the time for a certain hour, minute, second combination.Syntax: SELECT MAKETIME(11, 35, 4);Output: 11:35:04"
},
{
"code": null,
"e": 7824,
"s": 7788,
"text": "Syntax: SELECT MAKETIME(11, 35, 4);"
},
{
"code": null,
"e": 7841,
"s": 7824,
"text": "Output: 11:35:04"
},
{
"code": null,
"e": 7855,
"s": 7841,
"text": "SQL-Functions"
},
{
"code": null,
"e": 7859,
"s": 7855,
"text": "SQL"
},
{
"code": null,
"e": 7863,
"s": 7859,
"text": "SQL"
},
{
"code": null,
"e": 7961,
"s": 7863,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 7972,
"s": 7961,
"text": "CTE in SQL"
},
{
"code": null,
"e": 8003,
"s": 7972,
"text": "SQL Trigger | Student Database"
},
{
"code": null,
"e": 8069,
"s": 8003,
"text": "How to Update Multiple Columns in Single Update Statement in SQL?"
},
{
"code": null,
"e": 8093,
"s": 8069,
"text": "SQL Interview Questions"
},
{
"code": null,
"e": 8105,
"s": 8093,
"text": "SQL | Views"
},
{
"code": null,
"e": 8150,
"s": 8105,
"text": "Difference between DELETE, DROP and TRUNCATE"
},
{
"code": null,
"e": 8174,
"s": 8150,
"text": "Window functions in SQL"
},
{
"code": null,
"e": 8206,
"s": 8174,
"text": "MySQL | Group_CONCAT() Function"
},
{
"code": null,
"e": 8245,
"s": 8206,
"text": "Difference between DELETE and TRUNCATE"
}
] |
Python | math.isqrt() method | 04 Dec, 2020
Math module in Python contains a number of mathematical operations, which can be performed with ease using the module. math.isqrt() method in Python is used to get the integer square root of the given non-negative integer value n. This method returns the floor value of the exact square root of n or equivalently the greatest integer a such that a2 <= n.
Note: This method is new in Python version 3.8.
Syntax: math.isqrt(n)
Parameter: n: A non-negative integer
Returns: an integer value which represents the floor of exact square root of the given non-negative integer n.
Code #1: Use of math.isqrt() method
Python3
# Python Program to explain# math.isqrt() method import math n = 10 # Get the floor value of# exact square root of nsqrt = math.isqrt(n)print(n) n = 100 # Get the floor value of# exact square root of nsqrt = math.isqrt(n)print(n)
3
10
Code #2: Use of math.isqrt() method to check whether the given integer is a perfect square.
Python3
# Python Program to explain# math.isqrt() method import math def isPerfect(n): # Get the floor value of # exact square root of n sqrt = math.isqrt(n) if sqrt * sqrt == n: print(f"{n} is perfect square") else : print(f"{n} is not a perfect square") # Driver's codeisPerfect(100)isPerfect(10)
100 is perfect square
10 is not a perfect square
Code #3: Use of math.isqrt() method to find the next perfect square of n.
Python3
# Python Program to explain# math.isqrt() method import math n = 11 def Next(n): # Get the ceiling of # exact square root of n ceil = 1 + math.isqrt(n) # print the next perfect square of n print("Next perfect square of {} is {}". format(n, ceil*ceil)) # Driver's codeNext(11)Next(37)
Next perfect square after 11 is 16
Next perfect square after 37 is 49
Akanksha_Rai
Python math-library-functions
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n04 Dec, 2020"
},
{
"code": null,
"e": 383,
"s": 28,
"text": "Math module in Python contains a number of mathematical operations, which can be performed with ease using the module. math.isqrt() method in Python is used to get the integer square root of the given non-negative integer value n. This method returns the floor value of the exact square root of n or equivalently the greatest integer a such that a2 <= n."
},
{
"code": null,
"e": 432,
"s": 383,
"text": "Note: This method is new in Python version 3.8. "
},
{
"code": null,
"e": 455,
"s": 432,
"text": "Syntax: math.isqrt(n) "
},
{
"code": null,
"e": 493,
"s": 455,
"text": "Parameter: n: A non-negative integer "
},
{
"code": null,
"e": 606,
"s": 493,
"text": "Returns: an integer value which represents the floor of exact square root of the given non-negative integer n. "
},
{
"code": null,
"e": 642,
"s": 606,
"text": "Code #1: Use of math.isqrt() method"
},
{
"code": null,
"e": 650,
"s": 642,
"text": "Python3"
},
{
"code": "# Python Program to explain# math.isqrt() method import math n = 10 # Get the floor value of# exact square root of nsqrt = math.isqrt(n)print(n) n = 100 # Get the floor value of# exact square root of nsqrt = math.isqrt(n)print(n)",
"e": 881,
"s": 650,
"text": null
},
{
"code": null,
"e": 886,
"s": 881,
"text": "3\n10"
},
{
"code": null,
"e": 980,
"s": 888,
"text": "Code #2: Use of math.isqrt() method to check whether the given integer is a perfect square."
},
{
"code": null,
"e": 988,
"s": 980,
"text": "Python3"
},
{
"code": "# Python Program to explain# math.isqrt() method import math def isPerfect(n): # Get the floor value of # exact square root of n sqrt = math.isqrt(n) if sqrt * sqrt == n: print(f\"{n} is perfect square\") else : print(f\"{n} is not a perfect square\") # Driver's codeisPerfect(100)isPerfect(10)",
"e": 1327,
"s": 988,
"text": null
},
{
"code": null,
"e": 1376,
"s": 1327,
"text": "100 is perfect square\n10 is not a perfect square"
},
{
"code": null,
"e": 1452,
"s": 1378,
"text": "Code #3: Use of math.isqrt() method to find the next perfect square of n."
},
{
"code": null,
"e": 1460,
"s": 1452,
"text": "Python3"
},
{
"code": "# Python Program to explain# math.isqrt() method import math n = 11 def Next(n): # Get the ceiling of # exact square root of n ceil = 1 + math.isqrt(n) # print the next perfect square of n print(\"Next perfect square of {} is {}\". format(n, ceil*ceil)) # Driver's codeNext(11)Next(37)",
"e": 1781,
"s": 1460,
"text": null
},
{
"code": null,
"e": 1851,
"s": 1781,
"text": "Next perfect square after 11 is 16\nNext perfect square after 37 is 49"
},
{
"code": null,
"e": 1866,
"s": 1853,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 1896,
"s": 1866,
"text": "Python math-library-functions"
},
{
"code": null,
"e": 1903,
"s": 1896,
"text": "Python"
}
] |
Lex program to find the length of the longest word | 30 Apr, 2019
Lex is a computer program that generates lexical analyzers. Lex reads an input stream specifying the lexical analyzer and outputs source code implementing the lexer in the C programming language.
The commands for executing the lex program are:
lex abc.l (abc is the file name)
cc lex.yy.c -efl
./a.out
Let’s see lex program to check valid email.
Examples:
Input: geeks for geeks
Output: 5
Input: facebook google yahoo
Output: 8
Below is the implementation:
/*lex code to find the length of the longest word*/ % { int counter = 0; %} %% [a - zA - Z] + { if (yyleng > counter) { counter = yyleng; }} %% main() { yylex(); printf("largest: %d", counter); printf("\n");}
Output:
Lex program
C Programs
Compiler Design
GBlog
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Header files in C/C++ and its uses
C Program to read contents of Whole File
How to return multiple values from a function in C or C++?
C++ Program to check Prime Number
Producer Consumer Problem in C
Issues in the design of a code generator
Three address code in Compiler
Phases of a Compiler
Peephole Optimization in Compiler Design
Code Optimization in Compiler Design | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n30 Apr, 2019"
},
{
"code": null,
"e": 249,
"s": 53,
"text": "Lex is a computer program that generates lexical analyzers. Lex reads an input stream specifying the lexical analyzer and outputs source code implementing the lexer in the C programming language."
},
{
"code": null,
"e": 297,
"s": 249,
"text": "The commands for executing the lex program are:"
},
{
"code": null,
"e": 356,
"s": 297,
"text": "lex abc.l (abc is the file name)\ncc lex.yy.c -efl\n./a.out "
},
{
"code": null,
"e": 400,
"s": 356,
"text": "Let’s see lex program to check valid email."
},
{
"code": null,
"e": 410,
"s": 400,
"text": "Examples:"
},
{
"code": null,
"e": 488,
"s": 410,
"text": "Input: geeks for geeks\nOutput: 5\n\nInput: facebook google yahoo\nOutput: 8 "
},
{
"code": null,
"e": 517,
"s": 488,
"text": "Below is the implementation:"
},
{
"code": "/*lex code to find the length of the longest word*/ % { int counter = 0; %} %% [a - zA - Z] + { if (yyleng > counter) { counter = yyleng; }} %% main() { yylex(); printf(\"largest: %d\", counter); printf(\"\\n\");}",
"e": 738,
"s": 517,
"text": null
},
{
"code": null,
"e": 746,
"s": 738,
"text": "Output:"
},
{
"code": null,
"e": 758,
"s": 746,
"text": "Lex program"
},
{
"code": null,
"e": 769,
"s": 758,
"text": "C Programs"
},
{
"code": null,
"e": 785,
"s": 769,
"text": "Compiler Design"
},
{
"code": null,
"e": 791,
"s": 785,
"text": "GBlog"
},
{
"code": null,
"e": 889,
"s": 791,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 924,
"s": 889,
"text": "Header files in C/C++ and its uses"
},
{
"code": null,
"e": 965,
"s": 924,
"text": "C Program to read contents of Whole File"
},
{
"code": null,
"e": 1024,
"s": 965,
"text": "How to return multiple values from a function in C or C++?"
},
{
"code": null,
"e": 1058,
"s": 1024,
"text": "C++ Program to check Prime Number"
},
{
"code": null,
"e": 1089,
"s": 1058,
"text": "Producer Consumer Problem in C"
},
{
"code": null,
"e": 1130,
"s": 1089,
"text": "Issues in the design of a code generator"
},
{
"code": null,
"e": 1161,
"s": 1130,
"text": "Three address code in Compiler"
},
{
"code": null,
"e": 1182,
"s": 1161,
"text": "Phases of a Compiler"
},
{
"code": null,
"e": 1223,
"s": 1182,
"text": "Peephole Optimization in Compiler Design"
}
] |
exit command in Linux with Examples | 15 May, 2019
exit command in linux is used to exit the shell where it is currently running. It takes one more parameter as [N] and exits the shell with a return of status N. If n is not provided, then it simply returns the status of last command that is executed.
Syntax:
exit [n]
Options for exit command –
exit: Exit Without ParameterAfter pressing enter, the terminal will simply close.
After pressing enter, the terminal will simply close.
exit [n] : Exit With ParameterAfter pressing enter, the terminal window will close and return a status of 110. Return status is important because sometimes they can be mapped to tell error, warnings and notifications. For example generally, return status –“0” means the program has executed successfully.“1” means the program has minnor errors.
After pressing enter, the terminal window will close and return a status of 110. Return status is important because sometimes they can be mapped to tell error, warnings and notifications. For example generally, return status –“0” means the program has executed successfully.“1” means the program has minnor errors.
exit n : Using “sudo su” we are going to the root directory and then exit the root directory with a return status of 5. After returning it will show how to display the return status code.echo $? command is used to see the last return status.
exit –help : It displays help information.
linux-command
Linux-Shell-Commands
Picked
Technical Scripter 2018
Linux-Unix
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
tar command in Linux with examples
curl command in Linux with Examples
'crontab' in Linux with Examples
Conditional Statements | Shell Script
Tail command in Linux with examples
Docker - COPY Instruction
UDP Server-Client implementation in C
scp command in Linux with Examples
diff command in Linux with examples
echo command in Linux with Examples | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n15 May, 2019"
},
{
"code": null,
"e": 279,
"s": 28,
"text": "exit command in linux is used to exit the shell where it is currently running. It takes one more parameter as [N] and exits the shell with a return of status N. If n is not provided, then it simply returns the status of last command that is executed."
},
{
"code": null,
"e": 287,
"s": 279,
"text": "Syntax:"
},
{
"code": null,
"e": 296,
"s": 287,
"text": "exit [n]"
},
{
"code": null,
"e": 323,
"s": 296,
"text": "Options for exit command –"
},
{
"code": null,
"e": 405,
"s": 323,
"text": "exit: Exit Without ParameterAfter pressing enter, the terminal will simply close."
},
{
"code": null,
"e": 459,
"s": 405,
"text": "After pressing enter, the terminal will simply close."
},
{
"code": null,
"e": 804,
"s": 459,
"text": "exit [n] : Exit With ParameterAfter pressing enter, the terminal window will close and return a status of 110. Return status is important because sometimes they can be mapped to tell error, warnings and notifications. For example generally, return status –“0” means the program has executed successfully.“1” means the program has minnor errors."
},
{
"code": null,
"e": 1119,
"s": 804,
"text": "After pressing enter, the terminal window will close and return a status of 110. Return status is important because sometimes they can be mapped to tell error, warnings and notifications. For example generally, return status –“0” means the program has executed successfully.“1” means the program has minnor errors."
},
{
"code": null,
"e": 1361,
"s": 1119,
"text": "exit n : Using “sudo su” we are going to the root directory and then exit the root directory with a return status of 5. After returning it will show how to display the return status code.echo $? command is used to see the last return status."
},
{
"code": null,
"e": 1404,
"s": 1361,
"text": "exit –help : It displays help information."
},
{
"code": null,
"e": 1418,
"s": 1404,
"text": "linux-command"
},
{
"code": null,
"e": 1439,
"s": 1418,
"text": "Linux-Shell-Commands"
},
{
"code": null,
"e": 1446,
"s": 1439,
"text": "Picked"
},
{
"code": null,
"e": 1470,
"s": 1446,
"text": "Technical Scripter 2018"
},
{
"code": null,
"e": 1481,
"s": 1470,
"text": "Linux-Unix"
},
{
"code": null,
"e": 1500,
"s": 1481,
"text": "Technical Scripter"
},
{
"code": null,
"e": 1598,
"s": 1500,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1633,
"s": 1598,
"text": "tar command in Linux with examples"
},
{
"code": null,
"e": 1669,
"s": 1633,
"text": "curl command in Linux with Examples"
},
{
"code": null,
"e": 1702,
"s": 1669,
"text": "'crontab' in Linux with Examples"
},
{
"code": null,
"e": 1740,
"s": 1702,
"text": "Conditional Statements | Shell Script"
},
{
"code": null,
"e": 1776,
"s": 1740,
"text": "Tail command in Linux with examples"
},
{
"code": null,
"e": 1802,
"s": 1776,
"text": "Docker - COPY Instruction"
},
{
"code": null,
"e": 1840,
"s": 1802,
"text": "UDP Server-Client implementation in C"
},
{
"code": null,
"e": 1875,
"s": 1840,
"text": "scp command in Linux with Examples"
},
{
"code": null,
"e": 1911,
"s": 1875,
"text": "diff command in Linux with examples"
}
] |
Minimum flips or swapping of adjacent characters required to make a string equal to another | 18 Jun, 2021
Given two binary strings A and B of length N, the task is to convert the string A to B by either flipping any character of A or swapping adjacent characters of A minimum number of times. If it is not possible to make both the strings equal, print -1.
Examples:
Input: A = “10010010”, B = “00001000” Output: 3Explanation:Operation 1: Flipping A[0] modifies A to “00010010”.Operation 2: Flipping A[6] modifies A to “00010000”.Operation 3: Swapping A[3] and A[4] modifies A to “00001000” Therefore, the total number of operations is 3.
Input: A = “11”, B = “00” Output: 3
Approach: The idea is to traverse the string A and try to make the same-indexed characters equal by first checking for the condition of swapping the adjacent characters. If the characters can not be made equal by this operation, then flip the character. Follow the steps below to solve the problem:
Initialize a variable, say ans, to store the required result.
Traverse the string A using a variable, say i, and perform the following operations:If A[i] is equal to B[i], then continue to the next iteration in the loop.Otherwise, if A[i] is equal to B[i + 1] and A[i + 1] is equal to B[i], then swap the characters and increment i and ans by 1.Otherwise, if A[i] is not equal to B[i], then flip the current bit and increment ans by 1.
If A[i] is equal to B[i], then continue to the next iteration in the loop.
Otherwise, if A[i] is equal to B[i + 1] and A[i + 1] is equal to B[i], then swap the characters and increment i and ans by 1.
Otherwise, if A[i] is not equal to B[i], then flip the current bit and increment ans by 1.
Print the value of ans as the result.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to find minimum operations// required to convert string A to Bint minimumOperation(string a, string b){ // Store the size of the string int n = a.length(); int i = 0; // Store the required result int minoperation = 0; // Traverse the string, a while (i < n) { // If a[i] is equal to b[i] if (a[i] == b[i]) { i = i + 1; continue; } // Check if swapping adjacent // characters make the same-indexed // characters equal or not else if (a[i] == b[i + 1] && a[i + 1] == b[i] && i < n - 1) { minoperation++; i = i + 2; } // Otherwise, flip the current bit else if (a[i] != b[i]) { minoperation++; i = i + 1; } else { ++i; } } // Print the minimum number of operations cout << minoperation;} // Driver Codeint main(){ // Given Input string a = "10010010", b = "00001000"; // Function Call minimumOperation(a, b); return 0;}
// Java program for the above approachpublic class GFG{ // Function to find minimum operations// required to convert string A to Bstatic void minimumOperation(String a, String b){ // Store the size of the string int n = a.length(); int i = 0; // Store the required result int minoperation = 0; // Traverse the string, a while (i < n) { // If a[i] is equal to b[i] if (a.charAt(i) == b.charAt(i)) { i = i + 1; continue; } // Check if swapping adjacent // characters make the same-indexed // characters equal or not else if (a.charAt(i) == b.charAt(i + 1) && a.charAt(i + 1) == b.charAt(i) && i < n - 1) { minoperation++; i = i + 2; } // Otherwise, flip the current bit else if (a.charAt(i) != b.charAt(i)) { minoperation++; i = i + 1; } else { ++i; } } // Print the minimum number of operations System.out.println(minoperation);} // Driver Codepublic static void main(String []args){ // Given Input String a = "10010010", b = "00001000"; // Function Call minimumOperation(a, b);}} // This code is contributed by AnkThon
# Python3 program for the above approach # Function to find minimum operations# required to convert A to Bdef minimumOperation(a, b): # Store the size of the string n = len(a) i = 0 # Store the required result minoperation = 0 # Traverse the string, a while (i < n): # If a[i] is equal to b[i] if (a[i] == b[i]): i = i + 1 continue # Check if swapping adjacent # characters make the same-indexed # characters equal or not elif (a[i] == b[i + 1] and a[i + 1] == b[i] and i < n - 1): minoperation += 1 i = i + 2 # Otherwise, flip the current bit elif (a[i] != b[i]): minoperation += 1 i = i + 1 else: i+=1 # Print the minimum number of operations print (minoperation) # Driver Codeif __name__ == '__main__': # Given Input a = "10010010" b = "00001000" # Function Call minimumOperation(a, b) # This code is contributed by mohit kumar 29
// C# program for the above approachusing System; class GFG{ // Function to find minimum operations// required to convert string A to Bstatic void minimumOperation(string a, string b){ // Store the size of the string int n = a.Length; int i = 0; // Store the required result int minoperation = 0; // Traverse the string, a while (i < n) { // If a[i] is equal to b[i] if (a[i] == b[i]) { i = i + 1; continue; } // Check if swapping adjacent // characters make the same-indexed // characters equal or not else if (a[i] == b[i + 1] && a[i + 1] == b[i] && i < n - 1) { minoperation++; i = i + 2; } // Otherwise, flip the current bit else if (a[i] != b[i]) { minoperation++; i = i + 1; } else { ++i; } } // Print the minimum number of operations Console.WriteLine(minoperation);} // Driver Codepublic static void Main(){ // Given Input string a = "10010010", b = "00001000"; // Function Call minimumOperation(a, b);}} // This code is contributed by ankThon
<script> // Javascript program for the above approach // Function to find minimum operations// required to convert string A to Bfunction minimumOperation(a, b){ // Store the size of the string var n = a.length; var i = 0; // Store the required result var minoperation = 0; // Traverse the string, a while (i < n) { // If a[i] is equal to b[i] if (a[i] == b[i]) { i = i + 1; continue; } // Check if swapping adjacent // characters make the same-indexed // characters equal or not else if (a[i] == b[i + 1] && a[i + 1] == b[i] && i < n - 1) { minoperation++; i = i + 2; } // Otherwise, flip the current bit else if (a[i] != b[i]) { minoperation++; i = i + 1; } else { ++i; } } // Print the minimum number of operations document.write(minoperation);} // Driver Code // Given Input var a = "10010010", b = "00001000"; // Function Call minimumOperation(a, b); </script>
3
Time Complexity: O(N)Auxiliary Space: O(1)
mohit kumar 29
ankthon
SURENDRA_GANGWAR
binary-string
Greedy
Strings
Strings
Greedy
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Huffman Coding | Greedy Algo-3
Coin Change | DP-7
Activity Selection Problem | Greedy Algo-1
Fractional Knapsack Problem
Job Sequencing Problem
Write a program to reverse an array or string
Reverse a string in Java
C++ Data Types
Check for Balanced Brackets in an expression (well-formedness) using Stack
Different Methods to Reverse a String in C++ | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n18 Jun, 2021"
},
{
"code": null,
"e": 279,
"s": 28,
"text": "Given two binary strings A and B of length N, the task is to convert the string A to B by either flipping any character of A or swapping adjacent characters of A minimum number of times. If it is not possible to make both the strings equal, print -1."
},
{
"code": null,
"e": 289,
"s": 279,
"text": "Examples:"
},
{
"code": null,
"e": 562,
"s": 289,
"text": "Input: A = “10010010”, B = “00001000” Output: 3Explanation:Operation 1: Flipping A[0] modifies A to “00010010”.Operation 2: Flipping A[6] modifies A to “00010000”.Operation 3: Swapping A[3] and A[4] modifies A to “00001000” Therefore, the total number of operations is 3."
},
{
"code": null,
"e": 599,
"s": 562,
"text": "Input: A = “11”, B = “00” Output: 3"
},
{
"code": null,
"e": 898,
"s": 599,
"text": "Approach: The idea is to traverse the string A and try to make the same-indexed characters equal by first checking for the condition of swapping the adjacent characters. If the characters can not be made equal by this operation, then flip the character. Follow the steps below to solve the problem:"
},
{
"code": null,
"e": 960,
"s": 898,
"text": "Initialize a variable, say ans, to store the required result."
},
{
"code": null,
"e": 1334,
"s": 960,
"text": "Traverse the string A using a variable, say i, and perform the following operations:If A[i] is equal to B[i], then continue to the next iteration in the loop.Otherwise, if A[i] is equal to B[i + 1] and A[i + 1] is equal to B[i], then swap the characters and increment i and ans by 1.Otherwise, if A[i] is not equal to B[i], then flip the current bit and increment ans by 1."
},
{
"code": null,
"e": 1409,
"s": 1334,
"text": "If A[i] is equal to B[i], then continue to the next iteration in the loop."
},
{
"code": null,
"e": 1535,
"s": 1409,
"text": "Otherwise, if A[i] is equal to B[i + 1] and A[i + 1] is equal to B[i], then swap the characters and increment i and ans by 1."
},
{
"code": null,
"e": 1626,
"s": 1535,
"text": "Otherwise, if A[i] is not equal to B[i], then flip the current bit and increment ans by 1."
},
{
"code": null,
"e": 1664,
"s": 1626,
"text": "Print the value of ans as the result."
},
{
"code": null,
"e": 1715,
"s": 1664,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 1719,
"s": 1715,
"text": "C++"
},
{
"code": null,
"e": 1724,
"s": 1719,
"text": "Java"
},
{
"code": null,
"e": 1732,
"s": 1724,
"text": "Python3"
},
{
"code": null,
"e": 1735,
"s": 1732,
"text": "C#"
},
{
"code": null,
"e": 1746,
"s": 1735,
"text": "Javascript"
},
{
"code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to find minimum operations// required to convert string A to Bint minimumOperation(string a, string b){ // Store the size of the string int n = a.length(); int i = 0; // Store the required result int minoperation = 0; // Traverse the string, a while (i < n) { // If a[i] is equal to b[i] if (a[i] == b[i]) { i = i + 1; continue; } // Check if swapping adjacent // characters make the same-indexed // characters equal or not else if (a[i] == b[i + 1] && a[i + 1] == b[i] && i < n - 1) { minoperation++; i = i + 2; } // Otherwise, flip the current bit else if (a[i] != b[i]) { minoperation++; i = i + 1; } else { ++i; } } // Print the minimum number of operations cout << minoperation;} // Driver Codeint main(){ // Given Input string a = \"10010010\", b = \"00001000\"; // Function Call minimumOperation(a, b); return 0;}",
"e": 2912,
"s": 1746,
"text": null
},
{
"code": "// Java program for the above approachpublic class GFG{ // Function to find minimum operations// required to convert string A to Bstatic void minimumOperation(String a, String b){ // Store the size of the string int n = a.length(); int i = 0; // Store the required result int minoperation = 0; // Traverse the string, a while (i < n) { // If a[i] is equal to b[i] if (a.charAt(i) == b.charAt(i)) { i = i + 1; continue; } // Check if swapping adjacent // characters make the same-indexed // characters equal or not else if (a.charAt(i) == b.charAt(i + 1) && a.charAt(i + 1) == b.charAt(i) && i < n - 1) { minoperation++; i = i + 2; } // Otherwise, flip the current bit else if (a.charAt(i) != b.charAt(i)) { minoperation++; i = i + 1; } else { ++i; } } // Print the minimum number of operations System.out.println(minoperation);} // Driver Codepublic static void main(String []args){ // Given Input String a = \"10010010\", b = \"00001000\"; // Function Call minimumOperation(a, b);}} // This code is contributed by AnkThon",
"e": 4236,
"s": 2912,
"text": null
},
{
"code": "# Python3 program for the above approach # Function to find minimum operations# required to convert A to Bdef minimumOperation(a, b): # Store the size of the string n = len(a) i = 0 # Store the required result minoperation = 0 # Traverse the string, a while (i < n): # If a[i] is equal to b[i] if (a[i] == b[i]): i = i + 1 continue # Check if swapping adjacent # characters make the same-indexed # characters equal or not elif (a[i] == b[i + 1] and a[i + 1] == b[i] and i < n - 1): minoperation += 1 i = i + 2 # Otherwise, flip the current bit elif (a[i] != b[i]): minoperation += 1 i = i + 1 else: i+=1 # Print the minimum number of operations print (minoperation) # Driver Codeif __name__ == '__main__': # Given Input a = \"10010010\" b = \"00001000\" # Function Call minimumOperation(a, b) # This code is contributed by mohit kumar 29",
"e": 5282,
"s": 4236,
"text": null
},
{
"code": "// C# program for the above approachusing System; class GFG{ // Function to find minimum operations// required to convert string A to Bstatic void minimumOperation(string a, string b){ // Store the size of the string int n = a.Length; int i = 0; // Store the required result int minoperation = 0; // Traverse the string, a while (i < n) { // If a[i] is equal to b[i] if (a[i] == b[i]) { i = i + 1; continue; } // Check if swapping adjacent // characters make the same-indexed // characters equal or not else if (a[i] == b[i + 1] && a[i + 1] == b[i] && i < n - 1) { minoperation++; i = i + 2; } // Otherwise, flip the current bit else if (a[i] != b[i]) { minoperation++; i = i + 1; } else { ++i; } } // Print the minimum number of operations Console.WriteLine(minoperation);} // Driver Codepublic static void Main(){ // Given Input string a = \"10010010\", b = \"00001000\"; // Function Call minimumOperation(a, b);}} // This code is contributed by ankThon",
"e": 6539,
"s": 5282,
"text": null
},
{
"code": "<script> // Javascript program for the above approach // Function to find minimum operations// required to convert string A to Bfunction minimumOperation(a, b){ // Store the size of the string var n = a.length; var i = 0; // Store the required result var minoperation = 0; // Traverse the string, a while (i < n) { // If a[i] is equal to b[i] if (a[i] == b[i]) { i = i + 1; continue; } // Check if swapping adjacent // characters make the same-indexed // characters equal or not else if (a[i] == b[i + 1] && a[i + 1] == b[i] && i < n - 1) { minoperation++; i = i + 2; } // Otherwise, flip the current bit else if (a[i] != b[i]) { minoperation++; i = i + 1; } else { ++i; } } // Print the minimum number of operations document.write(minoperation);} // Driver Code // Given Input var a = \"10010010\", b = \"00001000\"; // Function Call minimumOperation(a, b); </script>",
"e": 7660,
"s": 6539,
"text": null
},
{
"code": null,
"e": 7662,
"s": 7660,
"text": "3"
},
{
"code": null,
"e": 7707,
"s": 7664,
"text": "Time Complexity: O(N)Auxiliary Space: O(1)"
},
{
"code": null,
"e": 7724,
"s": 7709,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 7732,
"s": 7724,
"text": "ankthon"
},
{
"code": null,
"e": 7749,
"s": 7732,
"text": "SURENDRA_GANGWAR"
},
{
"code": null,
"e": 7763,
"s": 7749,
"text": "binary-string"
},
{
"code": null,
"e": 7770,
"s": 7763,
"text": "Greedy"
},
{
"code": null,
"e": 7778,
"s": 7770,
"text": "Strings"
},
{
"code": null,
"e": 7786,
"s": 7778,
"text": "Strings"
},
{
"code": null,
"e": 7793,
"s": 7786,
"text": "Greedy"
},
{
"code": null,
"e": 7891,
"s": 7793,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 7922,
"s": 7891,
"text": "Huffman Coding | Greedy Algo-3"
},
{
"code": null,
"e": 7941,
"s": 7922,
"text": "Coin Change | DP-7"
},
{
"code": null,
"e": 7984,
"s": 7941,
"text": "Activity Selection Problem | Greedy Algo-1"
},
{
"code": null,
"e": 8012,
"s": 7984,
"text": "Fractional Knapsack Problem"
},
{
"code": null,
"e": 8035,
"s": 8012,
"text": "Job Sequencing Problem"
},
{
"code": null,
"e": 8081,
"s": 8035,
"text": "Write a program to reverse an array or string"
},
{
"code": null,
"e": 8106,
"s": 8081,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 8121,
"s": 8106,
"text": "C++ Data Types"
},
{
"code": null,
"e": 8196,
"s": 8121,
"text": "Check for Balanced Brackets in an expression (well-formedness) using Stack"
}
] |
enchant.Dict() in Python | 03 Jun, 2020
Enchant is a module in python which is used to check the spelling of a word, gives suggestions to correct words. Also, gives antonym and synonym of words. It checks whether a word exists in dictionary or not.
enchant.Dict() is an inbuilt method of enchant module. It is used to create a Dict object, which is the most important object in the enchantt module. The Dict object represents the dictionary of a particular language.
Syntax : enchant.Dict(tag)
Parameter :tag : the code of the language dictionary(optional)
Returns : a Dict object
Example 1 :
# import the enchant moduleimport enchant # dictionary of en_USd = enchant.Dict("en_US") # the dictionary tagtag = d.tagprint("The dictionary tag is " + tag)
The dictionary tag is en_US
Example 2 : When the enchant.Dict() method is executed without passing any parameter in it, it by default takes the the code of the language of the local machine.
# import the enchant moduleimport enchant # instantiating the dictionary # without passing any parameterd = enchant.Dict() # finding the dictionary tagtag = d.tagprint("The dictionary tag is " + tag)
The dictionary tag is en_IN
Example 3 : The enchant.Dict() method may fail if the appropriate dictionary is not available. In that case the following message is printed:
enchant.Dict()
Output :
Traceback (most recent call last):File “”, line 1, inenchant.Dict()File “C:\Users\user\AppData\Local\Programs\Python\Python37-32\lib\site-packages\enchant\__init__.py”, line 541, in __init___EnchantObject.__init__(self)File “C:\Users\user\AppData\Local\Programs\Python\Python37-32\lib\site-packages\enchant\__init__.py”, line 144, in __init__self._init_this()File “C:\Users\user\AppData\Local\Programs\Python\Python37-32\lib\site-packages\enchant\__init__.py”, line 548, in _init_thisthis = self._broker._request_dict_data(self.tag)File “C:\Users\user\AppData\Local\Programs\Python\Python37-32\lib\site-packages\enchant\__init__.py”, line 286, in _request_dict_dataself._raise_error(e_str % (tag, ), DictNotFoundError)File “C:\Users\user\AppData\Local\Programs\Python\Python37-32\lib\site-packages\enchant\__init__.py”, line 233, in _raise_errorraise eclass(default)enchant.errors.DictNotFoundError: Dictionary for language ‘English_India’ could not be found
Python Enchant-module
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n03 Jun, 2020"
},
{
"code": null,
"e": 237,
"s": 28,
"text": "Enchant is a module in python which is used to check the spelling of a word, gives suggestions to correct words. Also, gives antonym and synonym of words. It checks whether a word exists in dictionary or not."
},
{
"code": null,
"e": 455,
"s": 237,
"text": "enchant.Dict() is an inbuilt method of enchant module. It is used to create a Dict object, which is the most important object in the enchantt module. The Dict object represents the dictionary of a particular language."
},
{
"code": null,
"e": 482,
"s": 455,
"text": "Syntax : enchant.Dict(tag)"
},
{
"code": null,
"e": 545,
"s": 482,
"text": "Parameter :tag : the code of the language dictionary(optional)"
},
{
"code": null,
"e": 569,
"s": 545,
"text": "Returns : a Dict object"
},
{
"code": null,
"e": 581,
"s": 569,
"text": "Example 1 :"
},
{
"code": "# import the enchant moduleimport enchant # dictionary of en_USd = enchant.Dict(\"en_US\") # the dictionary tagtag = d.tagprint(\"The dictionary tag is \" + tag)",
"e": 741,
"s": 581,
"text": null
},
{
"code": null,
"e": 770,
"s": 741,
"text": "The dictionary tag is en_US\n"
},
{
"code": null,
"e": 933,
"s": 770,
"text": "Example 2 : When the enchant.Dict() method is executed without passing any parameter in it, it by default takes the the code of the language of the local machine."
},
{
"code": "# import the enchant moduleimport enchant # instantiating the dictionary # without passing any parameterd = enchant.Dict() # finding the dictionary tagtag = d.tagprint(\"The dictionary tag is \" + tag)",
"e": 1135,
"s": 933,
"text": null
},
{
"code": null,
"e": 1164,
"s": 1135,
"text": "The dictionary tag is en_IN\n"
},
{
"code": null,
"e": 1306,
"s": 1164,
"text": "Example 3 : The enchant.Dict() method may fail if the appropriate dictionary is not available. In that case the following message is printed:"
},
{
"code": "enchant.Dict()",
"e": 1321,
"s": 1306,
"text": null
},
{
"code": null,
"e": 1330,
"s": 1321,
"text": "Output :"
},
{
"code": null,
"e": 2289,
"s": 1330,
"text": "Traceback (most recent call last):File “”, line 1, inenchant.Dict()File “C:\\Users\\user\\AppData\\Local\\Programs\\Python\\Python37-32\\lib\\site-packages\\enchant\\__init__.py”, line 541, in __init___EnchantObject.__init__(self)File “C:\\Users\\user\\AppData\\Local\\Programs\\Python\\Python37-32\\lib\\site-packages\\enchant\\__init__.py”, line 144, in __init__self._init_this()File “C:\\Users\\user\\AppData\\Local\\Programs\\Python\\Python37-32\\lib\\site-packages\\enchant\\__init__.py”, line 548, in _init_thisthis = self._broker._request_dict_data(self.tag)File “C:\\Users\\user\\AppData\\Local\\Programs\\Python\\Python37-32\\lib\\site-packages\\enchant\\__init__.py”, line 286, in _request_dict_dataself._raise_error(e_str % (tag, ), DictNotFoundError)File “C:\\Users\\user\\AppData\\Local\\Programs\\Python\\Python37-32\\lib\\site-packages\\enchant\\__init__.py”, line 233, in _raise_errorraise eclass(default)enchant.errors.DictNotFoundError: Dictionary for language ‘English_India’ could not be found"
},
{
"code": null,
"e": 2311,
"s": 2289,
"text": "Python Enchant-module"
},
{
"code": null,
"e": 2318,
"s": 2311,
"text": "Python"
}
] |
Program to find area of a Trapezoid | 22 Jun, 2022
Definition of Trapezoid : A Trapezoid is a convex quadrilateral with at least one pair of parallel sides. The parallel sides are called the bases of the trapezoid and the other two sides which are not parallel are referred to as the legs. There can also be two pairs of bases.
In the above figure CD || AB, so they form the bases and the other two sides i.e., AD and BC form the legs. The area of a trapezoid can be found by using this simple formula :
a = base b = base h = height Examples :
Input : base1 = 8, base2 = 10, height = 6
Output : Area is: 54.0
Input :base1 = 4, base2 = 20, height = 7
Output :Area is: 84.0
C++
C
Java
Python3
C#
PHP
Javascript
// C++ program to calculate// area of a trapezoid#include<bits/stdc++.h>using namespace std; // Function for the areadouble Area(int b1, int b2, int h){ return ((b1 + b2) / 2) * h;} // Driver Codeint main(){ int base1 = 8, base2 = 10, height = 6; double area = Area(base1, base2, height); cout << "Area is: " << area; return 0;} // This code is contributed by shivanisinghss2110
// CPP program to calculate// area of a trapezoid#include <stdio.h> // Function for the areadouble Area(int b1, int b2, int h){ return ((b1 + b2) / 2) * h;} // Driver Codeint main(){ int base1 = 8, base2 = 10, height = 6; double area = Area(base1, base2, height); printf("Area is: %.1lf", area); return 0;}
// Java program to calculate// area of a trapezoidimport java.io.*; class GFG{ // Function for the area static double Area(int b1, int b2, int h) { return ((b1 + b2) / 2) * h; } // Driver Code public static void main (String[] args) { int base1 = 8, base2 = 10, height = 6; double area = Area(base1, base2, height); System.out.println("Area is: " + area); }}
# Python program to calculate# area of a trapezoid # Function for the areadef Area(b1, b2, h): return ((b1 + b2) / 2) * h # Driver Codebase1 = 8; base2 = 10; height = 6area = Area(base1, base2, height)print("Area is:", area)
// C# program to calculate// area of a trapezoidusing System; class GFG{ // Function for the area static double Area(int b1, int b2, int h) { return ((b1 + b2) / 2) * h; } // Driver Code public static void Main () { int base1 = 8, base2 = 10, height = 6; double area = Area(base1, base2, height); Console.WriteLine("Area is: " + area); }} // This code is contributed by vt_m
<?php// PHP program to calculate// area of a trapezoid // Function for the areafunction Area( $b1, $b2, $h){ return (($b1 + $b2) / 2) * $h;} // Driver Code $base1 = 8; $base2 = 10; $height = 6; $area = Area($base1, $base2, $height); echo("Area is: "); echo($area); // This code is contributed by vt_m.?>
<script> // Javascript program to calculate// area of a trapezoid // Function for the areafunction Area(b1, b2, h){ return ((b1 + b2) / 2) * h;} // Driver Code let base1 = 8, base2 = 10, height = 6; let area = Area(base1, base2, height); document.write("Area is: " + area); // This code is contributed by Mayank Tyagi</script>
Output :
Area is: 54.0
Time complexity: O(1)
space complexity: O(1)
vt_m
shivanisinghss2110
mayanktyagi1709
hasani
area-volume-programs
Geometric
School Programming
Geometric
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Program for distance between two points on earth
Find if two rectangles overlap
Check whether triangle is valid or not if sides are given
Line Clipping | Set 1 (Cohen–Sutherland Algorithm)
Program for Point of Intersection of Two Lines
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 Jun, 2022"
},
{
"code": null,
"e": 307,
"s": 28,
"text": "Definition of Trapezoid : A Trapezoid is a convex quadrilateral with at least one pair of parallel sides. The parallel sides are called the bases of the trapezoid and the other two sides which are not parallel are referred to as the legs. There can also be two pairs of bases. "
},
{
"code": null,
"e": 485,
"s": 307,
"text": "In the above figure CD || AB, so they form the bases and the other two sides i.e., AD and BC form the legs. The area of a trapezoid can be found by using this simple formula : "
},
{
"code": null,
"e": 527,
"s": 485,
"text": "a = base b = base h = height Examples : "
},
{
"code": null,
"e": 656,
"s": 527,
"text": "Input : base1 = 8, base2 = 10, height = 6\nOutput : Area is: 54.0\n\nInput :base1 = 4, base2 = 20, height = 7\nOutput :Area is: 84.0"
},
{
"code": null,
"e": 664,
"s": 660,
"text": "C++"
},
{
"code": null,
"e": 666,
"s": 664,
"text": "C"
},
{
"code": null,
"e": 671,
"s": 666,
"text": "Java"
},
{
"code": null,
"e": 679,
"s": 671,
"text": "Python3"
},
{
"code": null,
"e": 682,
"s": 679,
"text": "C#"
},
{
"code": null,
"e": 686,
"s": 682,
"text": "PHP"
},
{
"code": null,
"e": 697,
"s": 686,
"text": "Javascript"
},
{
"code": "// C++ program to calculate// area of a trapezoid#include<bits/stdc++.h>using namespace std; // Function for the areadouble Area(int b1, int b2, int h){ return ((b1 + b2) / 2) * h;} // Driver Codeint main(){ int base1 = 8, base2 = 10, height = 6; double area = Area(base1, base2, height); cout << \"Area is: \" << area; return 0;} // This code is contributed by shivanisinghss2110",
"e": 1152,
"s": 697,
"text": null
},
{
"code": "// CPP program to calculate// area of a trapezoid#include <stdio.h> // Function for the areadouble Area(int b1, int b2, int h){ return ((b1 + b2) / 2) * h;} // Driver Codeint main(){ int base1 = 8, base2 = 10, height = 6; double area = Area(base1, base2, height); printf(\"Area is: %.1lf\", area); return 0;}",
"e": 1540,
"s": 1152,
"text": null
},
{
"code": "// Java program to calculate// area of a trapezoidimport java.io.*; class GFG{ // Function for the area static double Area(int b1, int b2, int h) { return ((b1 + b2) / 2) * h; } // Driver Code public static void main (String[] args) { int base1 = 8, base2 = 10, height = 6; double area = Area(base1, base2, height); System.out.println(\"Area is: \" + area); }}",
"e": 2056,
"s": 1540,
"text": null
},
{
"code": "# Python program to calculate# area of a trapezoid # Function for the areadef Area(b1, b2, h): return ((b1 + b2) / 2) * h # Driver Codebase1 = 8; base2 = 10; height = 6area = Area(base1, base2, height)print(\"Area is:\", area)",
"e": 2284,
"s": 2056,
"text": null
},
{
"code": "// C# program to calculate// area of a trapezoidusing System; class GFG{ // Function for the area static double Area(int b1, int b2, int h) { return ((b1 + b2) / 2) * h; } // Driver Code public static void Main () { int base1 = 8, base2 = 10, height = 6; double area = Area(base1, base2, height); Console.WriteLine(\"Area is: \" + area); }} // This code is contributed by vt_m",
"e": 2816,
"s": 2284,
"text": null
},
{
"code": "<?php// PHP program to calculate// area of a trapezoid // Function for the areafunction Area( $b1, $b2, $h){ return (($b1 + $b2) / 2) * $h;} // Driver Code $base1 = 8; $base2 = 10; $height = 6; $area = Area($base1, $base2, $height); echo(\"Area is: \"); echo($area); // This code is contributed by vt_m.?>",
"e": 3145,
"s": 2816,
"text": null
},
{
"code": "<script> // Javascript program to calculate// area of a trapezoid // Function for the areafunction Area(b1, b2, h){ return ((b1 + b2) / 2) * h;} // Driver Code let base1 = 8, base2 = 10, height = 6; let area = Area(base1, base2, height); document.write(\"Area is: \" + area); // This code is contributed by Mayank Tyagi</script>",
"e": 3530,
"s": 3145,
"text": null
},
{
"code": null,
"e": 3541,
"s": 3530,
"text": "Output : "
},
{
"code": null,
"e": 3555,
"s": 3541,
"text": "Area is: 54.0"
},
{
"code": null,
"e": 3578,
"s": 3555,
"text": " Time complexity: O(1)"
},
{
"code": null,
"e": 3601,
"s": 3578,
"text": "space complexity: O(1)"
},
{
"code": null,
"e": 3606,
"s": 3601,
"text": "vt_m"
},
{
"code": null,
"e": 3625,
"s": 3606,
"text": "shivanisinghss2110"
},
{
"code": null,
"e": 3641,
"s": 3625,
"text": "mayanktyagi1709"
},
{
"code": null,
"e": 3648,
"s": 3641,
"text": "hasani"
},
{
"code": null,
"e": 3669,
"s": 3648,
"text": "area-volume-programs"
},
{
"code": null,
"e": 3679,
"s": 3669,
"text": "Geometric"
},
{
"code": null,
"e": 3698,
"s": 3679,
"text": "School Programming"
},
{
"code": null,
"e": 3708,
"s": 3698,
"text": "Geometric"
},
{
"code": null,
"e": 3806,
"s": 3708,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3855,
"s": 3806,
"text": "Program for distance between two points on earth"
},
{
"code": null,
"e": 3886,
"s": 3855,
"text": "Find if two rectangles overlap"
},
{
"code": null,
"e": 3944,
"s": 3886,
"text": "Check whether triangle is valid or not if sides are given"
},
{
"code": null,
"e": 3995,
"s": 3944,
"text": "Line Clipping | Set 1 (Cohen–Sutherland Algorithm)"
},
{
"code": null,
"e": 4042,
"s": 3995,
"text": "Program for Point of Intersection of Two Lines"
},
{
"code": null,
"e": 4060,
"s": 4042,
"text": "Python Dictionary"
},
{
"code": null,
"e": 4085,
"s": 4060,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 4101,
"s": 4085,
"text": "Arrays in C/C++"
},
{
"code": null,
"e": 4124,
"s": 4101,
"text": "Introduction To PYTHON"
}
] |
Raja Software Labs Interview Experience | 06 Nov, 2020
Raja Software Labs visited our college for campus hiring. The selection process included aptitude tests, coding tests, and 3 technical interviews.
Aptitude Test: Test duration of 30 min, It consists of 20 MCQ questions. No negative marking test was taken on google forms.
Programming Test: Test duration of 60 min. It consists of 5 coding questions.
Write a function that takes an input parameter as a string and return the alternate words in it with “abc”. Words are separated by dots.Note: Avoid using inbuilt functionsInput: "i.like.this.program.very.much"
Output: "i.abc.this.abc.very.abc"Write a function that takes a number as input if the given number is a Fibonacci number, prints the number otherwise, print the sum of all even Fibonacci numbers less than the given number.Input: 20
Output: 10
Input: 21
Output: 21Write a function that takes a string as an input and you have to return the frequency of characters.Write a function that takes an array of integers as input and prints the second maximum difference between any two elements from an array.Input: arr[] = {14,12,70,95,65,22,30};
Output: 81
[1st max difference = 95-12=83
2nd max difference = 95-14 = 81]Write a function that takes an array of integers and prints the numbers that have a remainder of 4 when divided by 5.Input: [19,10,44,3,11,129]
Output: [19, 44, 129]
Input:[13,4]
Output: [4]
Write a function that takes an input parameter as a string and return the alternate words in it with “abc”. Words are separated by dots.Note: Avoid using inbuilt functionsInput: "i.like.this.program.very.much"
Output: "i.abc.this.abc.very.abc"
Write a function that takes an input parameter as a string and return the alternate words in it with “abc”. Words are separated by dots.
Note: Avoid using inbuilt functions
Input: "i.like.this.program.very.much"
Output: "i.abc.this.abc.very.abc"
Write a function that takes a number as input if the given number is a Fibonacci number, prints the number otherwise, print the sum of all even Fibonacci numbers less than the given number.Input: 20
Output: 10
Input: 21
Output: 21
Write a function that takes a number as input if the given number is a Fibonacci number, prints the number otherwise, print the sum of all even Fibonacci numbers less than the given number.
Input: 20
Output: 10
Input: 21
Output: 21
Write a function that takes a string as an input and you have to return the frequency of characters.
Write a function that takes a string as an input and you have to return the frequency of characters.
Write a function that takes an array of integers as input and prints the second maximum difference between any two elements from an array.Input: arr[] = {14,12,70,95,65,22,30};
Output: 81
[1st max difference = 95-12=83
2nd max difference = 95-14 = 81]
Write a function that takes an array of integers as input and prints the second maximum difference between any two elements from an array.
Input: arr[] = {14,12,70,95,65,22,30};
Output: 81
[1st max difference = 95-12=83
2nd max difference = 95-14 = 81]
Write a function that takes an array of integers and prints the numbers that have a remainder of 4 when divided by 5.Input: [19,10,44,3,11,129]
Output: [19, 44, 129]
Input:[13,4]
Output: [4]
Write a function that takes an array of integers and prints the numbers that have a remainder of 4 when divided by 5.
Input: [19,10,44,3,11,129]
Output: [19, 44, 129]
Input:[13,4]
Output: [4]
1st Technical Interview: 3 coding question
Write a function that takes an integer as an input and returns the nearest prime number. Input: 7
Output: 7
Input: 13
Output:11Write a function that takes two inputs, year, and n and returns n leap year after the given year.Input: year = 1, n=4
Output: 4,8,12,16Write a function that takes a string as an input and returns the first non-repeating character.
Write a function that takes an integer as an input and returns the nearest prime number. Input: 7
Output: 7
Input: 13
Output:11
Write a function that takes an integer as an input and returns the nearest prime number.
Input: 7
Output: 7
Input: 13
Output:11
Write a function that takes two inputs, year, and n and returns n leap year after the given year.Input: year = 1, n=4
Output: 4,8,12,16
Write a function that takes two inputs, year, and n and returns n leap year after the given year.
Input: year = 1, n=4
Output: 4,8,12,16
Write a function that takes a string as an input and returns the first non-repeating character.
Write a function that takes a string as an input and returns the first non-repeating character.
2nd Technical Interview: 2 coding question
Write a function that takes a string as input and replace the space with “%?”Input: "welcome to geeksforgeeks"
Output: "welcome%?to%?geeksforgeeks"You have to make changes in the given string only.Function to print a pyramid pattern.
Write a function that takes a string as input and replace the space with “%?”Input: "welcome to geeksforgeeks"
Output: "welcome%?to%?geeksforgeeks"You have to make changes in the given string only.
Write a function that takes a string as input and replace the space with “%?”
Input: "welcome to geeksforgeeks"
Output: "welcome%?to%?geeksforgeeks"
You have to make changes in the given string only.
Function to print a pyramid pattern.
Function to print a pyramid pattern.
3rd Technical Interview: 2 coding question
Given an expression string exp, write a program to examine whether the pairs and the orders of “{“, “}”, “(“, “)”, “[“, “]” are correct in exp.If the given string is balanced then return the same string.If the given string is unbalanced then balance the string and then return it.Write a function that takes a string as input and returns the output as an integer (STOI).
Given an expression string exp, write a program to examine whether the pairs and the orders of “{“, “}”, “(“, “)”, “[“, “]” are correct in exp.If the given string is balanced then return the same string.If the given string is unbalanced then balance the string and then return it.
Given an expression string exp, write a program to examine whether the pairs and the orders of “{“, “}”, “(“, “)”, “[“, “]” are correct in exp.
If the given string is balanced then return the same string.
If the given string is unbalanced then balance the string and then return it.
Write a function that takes a string as input and returns the output as an integer (STOI).
Write a function that takes a string as input and returns the output as an integer (STOI).
Marketing
On-Campus
Raja Software Labs
Interview Experiences
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Amazon Interview Experience for SDE 1
Samsung Interview Experience Research & Institute SRIB (Off-Campus) 2022
Amazon Interview Experience SDE-2 (3 Years Experienced)
Google SWE Interview Experience (Google Online Coding Challenge) 2022
Write It Up: Share Your Interview Experiences
Nagarro Interview Experience | On-Campus 2021
Amazon Interview Experience for SDE-1
Nagarro Interview Experience
TCS Ninja Interview Experience (2020 batch)
Samsung Software Competency Test (SWC) for Working professionals | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n06 Nov, 2020"
},
{
"code": null,
"e": 199,
"s": 52,
"text": "Raja Software Labs visited our college for campus hiring. The selection process included aptitude tests, coding tests, and 3 technical interviews."
},
{
"code": null,
"e": 324,
"s": 199,
"text": "Aptitude Test: Test duration of 30 min, It consists of 20 MCQ questions. No negative marking test was taken on google forms."
},
{
"code": null,
"e": 402,
"s": 324,
"text": "Programming Test: Test duration of 60 min. It consists of 5 coding questions."
},
{
"code": null,
"e": 1422,
"s": 402,
"text": "Write a function that takes an input parameter as a string and return the alternate words in it with “abc”. Words are separated by dots.Note: Avoid using inbuilt functionsInput: \"i.like.this.program.very.much\"\nOutput: \"i.abc.this.abc.very.abc\"Write a function that takes a number as input if the given number is a Fibonacci number, prints the number otherwise, print the sum of all even Fibonacci numbers less than the given number.Input: 20\nOutput: 10\nInput: 21\nOutput: 21Write a function that takes a string as an input and you have to return the frequency of characters.Write a function that takes an array of integers as input and prints the second maximum difference between any two elements from an array.Input: arr[] = {14,12,70,95,65,22,30};\nOutput: 81\n\n[1st max difference = 95-12=83 \n 2nd max difference = 95-14 = 81]Write a function that takes an array of integers and prints the numbers that have a remainder of 4 when divided by 5.Input: [19,10,44,3,11,129]\nOutput: [19, 44, 129]\nInput:[13,4]\nOutput: [4]"
},
{
"code": null,
"e": 1666,
"s": 1422,
"text": "Write a function that takes an input parameter as a string and return the alternate words in it with “abc”. Words are separated by dots.Note: Avoid using inbuilt functionsInput: \"i.like.this.program.very.much\"\nOutput: \"i.abc.this.abc.very.abc\""
},
{
"code": null,
"e": 1803,
"s": 1666,
"text": "Write a function that takes an input parameter as a string and return the alternate words in it with “abc”. Words are separated by dots."
},
{
"code": null,
"e": 1839,
"s": 1803,
"text": "Note: Avoid using inbuilt functions"
},
{
"code": null,
"e": 1912,
"s": 1839,
"text": "Input: \"i.like.this.program.very.much\"\nOutput: \"i.abc.this.abc.very.abc\""
},
{
"code": null,
"e": 2143,
"s": 1912,
"text": "Write a function that takes a number as input if the given number is a Fibonacci number, prints the number otherwise, print the sum of all even Fibonacci numbers less than the given number.Input: 20\nOutput: 10\nInput: 21\nOutput: 21"
},
{
"code": null,
"e": 2333,
"s": 2143,
"text": "Write a function that takes a number as input if the given number is a Fibonacci number, prints the number otherwise, print the sum of all even Fibonacci numbers less than the given number."
},
{
"code": null,
"e": 2375,
"s": 2333,
"text": "Input: 20\nOutput: 10\nInput: 21\nOutput: 21"
},
{
"code": null,
"e": 2476,
"s": 2375,
"text": "Write a function that takes a string as an input and you have to return the frequency of characters."
},
{
"code": null,
"e": 2577,
"s": 2476,
"text": "Write a function that takes a string as an input and you have to return the frequency of characters."
},
{
"code": null,
"e": 2834,
"s": 2577,
"text": "Write a function that takes an array of integers as input and prints the second maximum difference between any two elements from an array.Input: arr[] = {14,12,70,95,65,22,30};\nOutput: 81\n\n[1st max difference = 95-12=83 \n 2nd max difference = 95-14 = 81]"
},
{
"code": null,
"e": 2973,
"s": 2834,
"text": "Write a function that takes an array of integers as input and prints the second maximum difference between any two elements from an array."
},
{
"code": null,
"e": 3092,
"s": 2973,
"text": "Input: arr[] = {14,12,70,95,65,22,30};\nOutput: 81\n\n[1st max difference = 95-12=83 \n 2nd max difference = 95-14 = 81]"
},
{
"code": null,
"e": 3283,
"s": 3092,
"text": "Write a function that takes an array of integers and prints the numbers that have a remainder of 4 when divided by 5.Input: [19,10,44,3,11,129]\nOutput: [19, 44, 129]\nInput:[13,4]\nOutput: [4]"
},
{
"code": null,
"e": 3401,
"s": 3283,
"text": "Write a function that takes an array of integers and prints the numbers that have a remainder of 4 when divided by 5."
},
{
"code": null,
"e": 3475,
"s": 3401,
"text": "Input: [19,10,44,3,11,129]\nOutput: [19, 44, 129]\nInput:[13,4]\nOutput: [4]"
},
{
"code": null,
"e": 3518,
"s": 3475,
"text": "1st Technical Interview: 3 coding question"
},
{
"code": null,
"e": 3876,
"s": 3518,
"text": "Write a function that takes an integer as an input and returns the nearest prime number. Input: 7\nOutput: 7\nInput: 13\nOutput:11Write a function that takes two inputs, year, and n and returns n leap year after the given year.Input: year = 1, n=4\nOutput: 4,8,12,16Write a function that takes a string as an input and returns the first non-repeating character."
},
{
"code": null,
"e": 4004,
"s": 3876,
"text": "Write a function that takes an integer as an input and returns the nearest prime number. Input: 7\nOutput: 7\nInput: 13\nOutput:11"
},
{
"code": null,
"e": 4094,
"s": 4004,
"text": "Write a function that takes an integer as an input and returns the nearest prime number. "
},
{
"code": null,
"e": 4133,
"s": 4094,
"text": "Input: 7\nOutput: 7\nInput: 13\nOutput:11"
},
{
"code": null,
"e": 4269,
"s": 4133,
"text": "Write a function that takes two inputs, year, and n and returns n leap year after the given year.Input: year = 1, n=4\nOutput: 4,8,12,16"
},
{
"code": null,
"e": 4367,
"s": 4269,
"text": "Write a function that takes two inputs, year, and n and returns n leap year after the given year."
},
{
"code": null,
"e": 4406,
"s": 4367,
"text": "Input: year = 1, n=4\nOutput: 4,8,12,16"
},
{
"code": null,
"e": 4502,
"s": 4406,
"text": "Write a function that takes a string as an input and returns the first non-repeating character."
},
{
"code": null,
"e": 4598,
"s": 4502,
"text": "Write a function that takes a string as an input and returns the first non-repeating character."
},
{
"code": null,
"e": 4641,
"s": 4598,
"text": "2nd Technical Interview: 2 coding question"
},
{
"code": null,
"e": 4875,
"s": 4641,
"text": "Write a function that takes a string as input and replace the space with “%?”Input: \"welcome to geeksforgeeks\"\nOutput: \"welcome%?to%?geeksforgeeks\"You have to make changes in the given string only.Function to print a pyramid pattern."
},
{
"code": null,
"e": 5073,
"s": 4875,
"text": "Write a function that takes a string as input and replace the space with “%?”Input: \"welcome to geeksforgeeks\"\nOutput: \"welcome%?to%?geeksforgeeks\"You have to make changes in the given string only."
},
{
"code": null,
"e": 5151,
"s": 5073,
"text": "Write a function that takes a string as input and replace the space with “%?”"
},
{
"code": null,
"e": 5222,
"s": 5151,
"text": "Input: \"welcome to geeksforgeeks\"\nOutput: \"welcome%?to%?geeksforgeeks\""
},
{
"code": null,
"e": 5273,
"s": 5222,
"text": "You have to make changes in the given string only."
},
{
"code": null,
"e": 5310,
"s": 5273,
"text": "Function to print a pyramid pattern."
},
{
"code": null,
"e": 5347,
"s": 5310,
"text": "Function to print a pyramid pattern."
},
{
"code": null,
"e": 5390,
"s": 5347,
"text": "3rd Technical Interview: 2 coding question"
},
{
"code": null,
"e": 5761,
"s": 5390,
"text": "Given an expression string exp, write a program to examine whether the pairs and the orders of “{“, “}”, “(“, “)”, “[“, “]” are correct in exp.If the given string is balanced then return the same string.If the given string is unbalanced then balance the string and then return it.Write a function that takes a string as input and returns the output as an integer (STOI)."
},
{
"code": null,
"e": 6042,
"s": 5761,
"text": "Given an expression string exp, write a program to examine whether the pairs and the orders of “{“, “}”, “(“, “)”, “[“, “]” are correct in exp.If the given string is balanced then return the same string.If the given string is unbalanced then balance the string and then return it."
},
{
"code": null,
"e": 6186,
"s": 6042,
"text": "Given an expression string exp, write a program to examine whether the pairs and the orders of “{“, “}”, “(“, “)”, “[“, “]” are correct in exp."
},
{
"code": null,
"e": 6247,
"s": 6186,
"text": "If the given string is balanced then return the same string."
},
{
"code": null,
"e": 6325,
"s": 6247,
"text": "If the given string is unbalanced then balance the string and then return it."
},
{
"code": null,
"e": 6416,
"s": 6325,
"text": "Write a function that takes a string as input and returns the output as an integer (STOI)."
},
{
"code": null,
"e": 6507,
"s": 6416,
"text": "Write a function that takes a string as input and returns the output as an integer (STOI)."
},
{
"code": null,
"e": 6517,
"s": 6507,
"text": "Marketing"
},
{
"code": null,
"e": 6527,
"s": 6517,
"text": "On-Campus"
},
{
"code": null,
"e": 6546,
"s": 6527,
"text": "Raja Software Labs"
},
{
"code": null,
"e": 6568,
"s": 6546,
"text": "Interview Experiences"
},
{
"code": null,
"e": 6666,
"s": 6568,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 6704,
"s": 6666,
"text": "Amazon Interview Experience for SDE 1"
},
{
"code": null,
"e": 6777,
"s": 6704,
"text": "Samsung Interview Experience Research & Institute SRIB (Off-Campus) 2022"
},
{
"code": null,
"e": 6833,
"s": 6777,
"text": "Amazon Interview Experience SDE-2 (3 Years Experienced)"
},
{
"code": null,
"e": 6903,
"s": 6833,
"text": "Google SWE Interview Experience (Google Online Coding Challenge) 2022"
},
{
"code": null,
"e": 6949,
"s": 6903,
"text": "Write It Up: Share Your Interview Experiences"
},
{
"code": null,
"e": 6995,
"s": 6949,
"text": "Nagarro Interview Experience | On-Campus 2021"
},
{
"code": null,
"e": 7033,
"s": 6995,
"text": "Amazon Interview Experience for SDE-1"
},
{
"code": null,
"e": 7062,
"s": 7033,
"text": "Nagarro Interview Experience"
},
{
"code": null,
"e": 7106,
"s": 7062,
"text": "TCS Ninja Interview Experience (2020 batch)"
}
] |
How to display multiple images in one figure correctly in matplotlib? | To display multiple images in one figure, we can follow the steps given below −
Initialize the number of rows and cols. nrows*ncols subplot will be created in the current figure. nrows = 2 and ncols = 2, i.e., 2*2 = 4 subplots can be created.
Initialize the number of rows and cols. nrows*ncols subplot will be created in the current figure. nrows = 2 and ncols = 2, i.e., 2*2 = 4 subplots can be created.
Now add the figures at different indices from 1 to 4.
Now add the figures at different indices from 1 to 4.
Use plt.subplot(2, 2, 1) to add new images, i.e., pie at index 1.
Use plt.subplot(2, 2, 1) to add new images, i.e., pie at index 1.
To plot a pie chart, pass a list of numbers. Pie charts will be split into the size of list and %age section will depend upon the values in the list.
To plot a pie chart, pass a list of numbers. Pie charts will be split into the size of list and %age section will depend upon the values in the list.
Set the title of the subplot, i.e., “Figure 1”.
Set the title of the subplot, i.e., “Figure 1”.
Use plt.subplot(2, 2, 2) to add new images, i.e., pie at index 2.
Use plt.subplot(2, 2, 2) to add new images, i.e., pie at index 2.
Use plt.pie() to create a new pie chart.
Use plt.pie() to create a new pie chart.
Set the title of the subplot, i.e., “Figure 2”.
Set the title of the subplot, i.e., “Figure 2”.
Use plt.subplot(2, 2, 3) to add new images i.e., pie at index 3.
Use plt.subplot(2, 2, 3) to add new images i.e., pie at index 3.
Use plt.pie() to create a new pie chart.
Use plt.pie() to create a new pie chart.
Set the title of the subplot i.e., “Figure 3”.
Set the title of the subplot i.e., “Figure 3”.
Use plt.subplot(2, 2, 4) to add new images i.e., pie at index 4.
Use plt.subplot(2, 2, 4) to add new images i.e., pie at index 4.
Use plt.pie() to create a new pie chart.
Use plt.pie() to create a new pie chart.
Set the title of the subplot i.e., “Figure 4”.
Set the title of the subplot i.e., “Figure 4”.
Use plt.show(), to show the figure.
Use plt.show(), to show the figure.
import matplotlib.pyplot as plt
rows, cols = 2, 2
plt.subplot(rows, cols, 1)
plt.pie([1, 2, 3])
plt.title("Figure 1")
plt.subplot(rows, cols, 2)
plt.pie([3, 4, 5])
plt.title("Figure 2")
plt.subplot(rows, cols, 3)
plt.pie([6, 7, 8])
plt.title("Figure 3")
plt.subplot(rows, cols, 4)
plt.pie([8, 9, 10])
plt.title("Figure 4")
plt.show() | [
{
"code": null,
"e": 1267,
"s": 1187,
"text": "To display multiple images in one figure, we can follow the steps given below −"
},
{
"code": null,
"e": 1430,
"s": 1267,
"text": "Initialize the number of rows and cols. nrows*ncols subplot will be created in the current figure. nrows = 2 and ncols = 2, i.e., 2*2 = 4 subplots can be created."
},
{
"code": null,
"e": 1593,
"s": 1430,
"text": "Initialize the number of rows and cols. nrows*ncols subplot will be created in the current figure. nrows = 2 and ncols = 2, i.e., 2*2 = 4 subplots can be created."
},
{
"code": null,
"e": 1647,
"s": 1593,
"text": "Now add the figures at different indices from 1 to 4."
},
{
"code": null,
"e": 1701,
"s": 1647,
"text": "Now add the figures at different indices from 1 to 4."
},
{
"code": null,
"e": 1767,
"s": 1701,
"text": "Use plt.subplot(2, 2, 1) to add new images, i.e., pie at index 1."
},
{
"code": null,
"e": 1833,
"s": 1767,
"text": "Use plt.subplot(2, 2, 1) to add new images, i.e., pie at index 1."
},
{
"code": null,
"e": 1983,
"s": 1833,
"text": "To plot a pie chart, pass a list of numbers. Pie charts will be split into the size of list and %age section will depend upon the values in the list."
},
{
"code": null,
"e": 2133,
"s": 1983,
"text": "To plot a pie chart, pass a list of numbers. Pie charts will be split into the size of list and %age section will depend upon the values in the list."
},
{
"code": null,
"e": 2181,
"s": 2133,
"text": "Set the title of the subplot, i.e., “Figure 1”."
},
{
"code": null,
"e": 2229,
"s": 2181,
"text": "Set the title of the subplot, i.e., “Figure 1”."
},
{
"code": null,
"e": 2295,
"s": 2229,
"text": "Use plt.subplot(2, 2, 2) to add new images, i.e., pie at index 2."
},
{
"code": null,
"e": 2361,
"s": 2295,
"text": "Use plt.subplot(2, 2, 2) to add new images, i.e., pie at index 2."
},
{
"code": null,
"e": 2402,
"s": 2361,
"text": "Use plt.pie() to create a new pie chart."
},
{
"code": null,
"e": 2443,
"s": 2402,
"text": "Use plt.pie() to create a new pie chart."
},
{
"code": null,
"e": 2491,
"s": 2443,
"text": "Set the title of the subplot, i.e., “Figure 2”."
},
{
"code": null,
"e": 2539,
"s": 2491,
"text": "Set the title of the subplot, i.e., “Figure 2”."
},
{
"code": null,
"e": 2604,
"s": 2539,
"text": "Use plt.subplot(2, 2, 3) to add new images i.e., pie at index 3."
},
{
"code": null,
"e": 2669,
"s": 2604,
"text": "Use plt.subplot(2, 2, 3) to add new images i.e., pie at index 3."
},
{
"code": null,
"e": 2710,
"s": 2669,
"text": "Use plt.pie() to create a new pie chart."
},
{
"code": null,
"e": 2751,
"s": 2710,
"text": "Use plt.pie() to create a new pie chart."
},
{
"code": null,
"e": 2798,
"s": 2751,
"text": "Set the title of the subplot i.e., “Figure 3”."
},
{
"code": null,
"e": 2845,
"s": 2798,
"text": "Set the title of the subplot i.e., “Figure 3”."
},
{
"code": null,
"e": 2910,
"s": 2845,
"text": "Use plt.subplot(2, 2, 4) to add new images i.e., pie at index 4."
},
{
"code": null,
"e": 2975,
"s": 2910,
"text": "Use plt.subplot(2, 2, 4) to add new images i.e., pie at index 4."
},
{
"code": null,
"e": 3016,
"s": 2975,
"text": "Use plt.pie() to create a new pie chart."
},
{
"code": null,
"e": 3057,
"s": 3016,
"text": "Use plt.pie() to create a new pie chart."
},
{
"code": null,
"e": 3104,
"s": 3057,
"text": "Set the title of the subplot i.e., “Figure 4”."
},
{
"code": null,
"e": 3151,
"s": 3104,
"text": "Set the title of the subplot i.e., “Figure 4”."
},
{
"code": null,
"e": 3187,
"s": 3151,
"text": "Use plt.show(), to show the figure."
},
{
"code": null,
"e": 3223,
"s": 3187,
"text": "Use plt.show(), to show the figure."
},
{
"code": null,
"e": 3559,
"s": 3223,
"text": "import matplotlib.pyplot as plt\n\nrows, cols = 2, 2\nplt.subplot(rows, cols, 1)\nplt.pie([1, 2, 3])\nplt.title(\"Figure 1\")\nplt.subplot(rows, cols, 2)\nplt.pie([3, 4, 5])\nplt.title(\"Figure 2\")\nplt.subplot(rows, cols, 3)\nplt.pie([6, 7, 8])\nplt.title(\"Figure 3\")\nplt.subplot(rows, cols, 4)\nplt.pie([8, 9, 10])\nplt.title(\"Figure 4\")\n\nplt.show()"
}
] |
How to Concatenate image using Pillow in Python ? | 07 Apr, 2021
Prerequisites: Python Pillow
Concatenate image means joining of two images. We can merge any image whether it has different pixels, different image formats namely, ‘jpeg’, ‘png’, ‘gif’, ‘tiff’, etc. In python, we can join two images using the Python image library also known as the pillow library. In this article, we will see how the concatenation of images is done.
Concatenation of images can be done in two ways :
Horizontal
Vertical
Approach:
Import module
Open the images
Resize the image using Resize() function. Both the resize images should be of the same width and height so that their aspect ratio is intact and can be pasted into the new background image.
To create a new image it has a new() function which has 3 parameters (“mode”,(size),color)
Paste the image to new image using paste()
Program:
Python3
# libraryfrom PIL import Imageimport matplotlib.pyplot as plt # opening up of imagesimg = Image.open("logo.png")img1 = Image.open("logo2.png")img.sizeimg1.sizeimg_size = img.resize((250, 90))img1_size = img1.resize((250, 90)) # creating a new image and pasting # the imagesimg2 = Image.new("RGB", (500, 90), "white") # pasting the first image (image_name,# (position))img2.paste(img_size, (0, 0)) # pasting the second image (image_name,# (position))img2.paste(img1_size, (250, 0)) plt.imshow(img2)
Output :
The whole code is the same as horizontal but the only change is that in horizontal we double the width and the height is same but in vertical we make the size of width same, but we double the height.
Approach:
Import the libraries for image processing.
Use Image.open() to open the library.
Use img.size to know the size of the image.
Use img.resize((width,height)) to resize the image.
Both the images should be of same size.
Create a new image using new() and pass the 3 parameters”mode”,size,”color”).
Size in new image should be (width, 2*height).
After the creation of new image, paste the first image by using paste() and pass the parameter(img_resize,(position)) #position(0,0)
After pasting the first image, paste the second image using paste and pass the parameter(img1_reszie, (position)). In position, width would be the same but the height would be the last position of the first image’s height. . #position=(0,180)
Use plt.imshow(img2) to show the concatenate of images.
Program:
Python3
# libraryfrom PIL import Imageimport matplotlib.pyplot as plt # opening up of imagesimg = Image.open("logo.png")img1 = Image.open("logo2.png")img.sizeimg1.sizeimg_size = img.resize((250, 90))img1_size = img1.resize((250, 90)) # creating a new image and pasting the # imagesimg2 = Image.new("RGB", (250, 180), "white") # pasting the first image (image_name,# (position))img2.paste(img_size, (0, 0)) # pasting the second image (image_name,# (position))img2.paste(img1_size, (0, 90) plt.imshow(img2)
Output:
Picked
Python-pil
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n07 Apr, 2021"
},
{
"code": null,
"e": 81,
"s": 52,
"text": "Prerequisites: Python Pillow"
},
{
"code": null,
"e": 420,
"s": 81,
"text": "Concatenate image means joining of two images. We can merge any image whether it has different pixels, different image formats namely, ‘jpeg’, ‘png’, ‘gif’, ‘tiff’, etc. In python, we can join two images using the Python image library also known as the pillow library. In this article, we will see how the concatenation of images is done."
},
{
"code": null,
"e": 470,
"s": 420,
"text": "Concatenation of images can be done in two ways :"
},
{
"code": null,
"e": 481,
"s": 470,
"text": "Horizontal"
},
{
"code": null,
"e": 490,
"s": 481,
"text": "Vertical"
},
{
"code": null,
"e": 500,
"s": 490,
"text": "Approach:"
},
{
"code": null,
"e": 514,
"s": 500,
"text": "Import module"
},
{
"code": null,
"e": 530,
"s": 514,
"text": "Open the images"
},
{
"code": null,
"e": 720,
"s": 530,
"text": "Resize the image using Resize() function. Both the resize images should be of the same width and height so that their aspect ratio is intact and can be pasted into the new background image."
},
{
"code": null,
"e": 811,
"s": 720,
"text": "To create a new image it has a new() function which has 3 parameters (“mode”,(size),color)"
},
{
"code": null,
"e": 854,
"s": 811,
"text": "Paste the image to new image using paste()"
},
{
"code": null,
"e": 863,
"s": 854,
"text": "Program:"
},
{
"code": null,
"e": 871,
"s": 863,
"text": "Python3"
},
{
"code": "# libraryfrom PIL import Imageimport matplotlib.pyplot as plt # opening up of imagesimg = Image.open(\"logo.png\")img1 = Image.open(\"logo2.png\")img.sizeimg1.sizeimg_size = img.resize((250, 90))img1_size = img1.resize((250, 90)) # creating a new image and pasting # the imagesimg2 = Image.new(\"RGB\", (500, 90), \"white\") # pasting the first image (image_name,# (position))img2.paste(img_size, (0, 0)) # pasting the second image (image_name,# (position))img2.paste(img1_size, (250, 0)) plt.imshow(img2)",
"e": 1374,
"s": 871,
"text": null
},
{
"code": null,
"e": 1384,
"s": 1374,
"text": " Output :"
},
{
"code": null,
"e": 1585,
"s": 1384,
"text": "The whole code is the same as horizontal but the only change is that in horizontal we double the width and the height is same but in vertical we make the size of width same, but we double the height. "
},
{
"code": null,
"e": 1595,
"s": 1585,
"text": "Approach:"
},
{
"code": null,
"e": 1638,
"s": 1595,
"text": "Import the libraries for image processing."
},
{
"code": null,
"e": 1676,
"s": 1638,
"text": "Use Image.open() to open the library."
},
{
"code": null,
"e": 1720,
"s": 1676,
"text": "Use img.size to know the size of the image."
},
{
"code": null,
"e": 1772,
"s": 1720,
"text": "Use img.resize((width,height)) to resize the image."
},
{
"code": null,
"e": 1812,
"s": 1772,
"text": "Both the images should be of same size."
},
{
"code": null,
"e": 1890,
"s": 1812,
"text": "Create a new image using new() and pass the 3 parameters”mode”,size,”color”)."
},
{
"code": null,
"e": 1937,
"s": 1890,
"text": "Size in new image should be (width, 2*height)."
},
{
"code": null,
"e": 2070,
"s": 1937,
"text": "After the creation of new image, paste the first image by using paste() and pass the parameter(img_resize,(position)) #position(0,0)"
},
{
"code": null,
"e": 2313,
"s": 2070,
"text": "After pasting the first image, paste the second image using paste and pass the parameter(img1_reszie, (position)). In position, width would be the same but the height would be the last position of the first image’s height. . #position=(0,180)"
},
{
"code": null,
"e": 2369,
"s": 2313,
"text": "Use plt.imshow(img2) to show the concatenate of images."
},
{
"code": null,
"e": 2378,
"s": 2369,
"text": "Program:"
},
{
"code": null,
"e": 2386,
"s": 2378,
"text": "Python3"
},
{
"code": "# libraryfrom PIL import Imageimport matplotlib.pyplot as plt # opening up of imagesimg = Image.open(\"logo.png\")img1 = Image.open(\"logo2.png\")img.sizeimg1.sizeimg_size = img.resize((250, 90))img1_size = img1.resize((250, 90)) # creating a new image and pasting the # imagesimg2 = Image.new(\"RGB\", (250, 180), \"white\") # pasting the first image (image_name,# (position))img2.paste(img_size, (0, 0)) # pasting the second image (image_name,# (position))img2.paste(img1_size, (0, 90) plt.imshow(img2)",
"e": 2890,
"s": 2386,
"text": null
},
{
"code": null,
"e": 2898,
"s": 2890,
"text": "Output:"
},
{
"code": null,
"e": 2905,
"s": 2898,
"text": "Picked"
},
{
"code": null,
"e": 2916,
"s": 2905,
"text": "Python-pil"
},
{
"code": null,
"e": 2923,
"s": 2916,
"text": "Python"
}
] |
How to run a given array of promises in series in JavaScript ? | 23 Apr, 2021
Given an array of Promises, we have to run that in a series. To do this task, we can use then(), to run the next promise, after completion of a promise.
Approach: The then() method returns a Promise, which helps us to chain promises/methods. The Promise.resolve() method executes the first callback, and when this promise is fulfilled, then it passes to the next function callback1, and it goes on until all the promises are fulfilled. In this way, we can run all the Promises in series.
Syntax:
Promise.resolve( callback0 )
.then( callback1 )
.then( callback2 )
.then( callback3 )...
Example 1: In this example, we will be executing 3 promises by chaining each of them with the then() method.
HTML
<html><body> <h1 style="color: green;"> GeeksforGeeks </h1> <b>Promises</b> <script> // Define an asynchronous function, // results in returning a promise async function task(url) { console.log(url + " will be fetched now") return fetch(url); } // Declaring an array of URLs let arr = [ "https://www.google.com", "https://www.facebook.com", "https://www.twitter.com" ]; // Resolving the first task Promise.resolve(() => { return task(arr[0]); }) // Resolving the second task .then(() => { return task(arr[1]); }) // Resolving the third task .then(() => { return task(arr[2]); }); </script></body></html>
Output:
https://www.facebook.com will be fetched now
https://www.twitter.com will be fetched now
The above approach is not feasible if there are a lot more promises in the array. Chaining of the function would get very tiring and will make the code lengthy. We can use the forEach() array function to execute the promises by storing the results in a variable and updating that variable at every promise. This will automatically go through all the promises and one can prevent repeatedly writing then() statements.
Example 2: In this example, we will be executing multiple promises by using the forEach() method.
HTML
<html><body> <h1 style="color: green;"> GeeksforGeeks </h1> <b>Promises</b> <script> // Define an asynchronous function async function task(url) { return fetch(url); } // Define array that has to be processed // by the asynchronous function let arr = [ "https://www.google.com", "https://www.facebook.com", "https://www.twitter.com", "https://www.youtube.com", "https://www.netflix.com", ]; // Declare a Promise using its resolve constructor let promise = Promise.resolve(); // Use the forEach function to evaluate // the promises in series // The value of // p would be the result // of previous promise arr.forEach((url, index) => { promise = promise.then(() => { let para = document.createElement("p"); para.innerText = "The async request of " + url + " has been resolved"; document.body.appendChild(para); return task(url); }); }); </script></body></html>
Output:
JavaScript-Methods
JavaScript-Questions
Picked
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Remove elements from a JavaScript Array
Difference Between PUT and PATCH Request
Roadmap to Learn JavaScript For Beginners
JavaScript | Promises
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 Apr, 2021"
},
{
"code": null,
"e": 181,
"s": 28,
"text": "Given an array of Promises, we have to run that in a series. To do this task, we can use then(), to run the next promise, after completion of a promise."
},
{
"code": null,
"e": 516,
"s": 181,
"text": "Approach: The then() method returns a Promise, which helps us to chain promises/methods. The Promise.resolve() method executes the first callback, and when this promise is fulfilled, then it passes to the next function callback1, and it goes on until all the promises are fulfilled. In this way, we can run all the Promises in series."
},
{
"code": null,
"e": 524,
"s": 516,
"text": "Syntax:"
},
{
"code": null,
"e": 617,
"s": 524,
"text": "Promise.resolve( callback0 )\n.then( callback1 )\n.then( callback2 )\n.then( callback3 )... "
},
{
"code": null,
"e": 726,
"s": 617,
"text": "Example 1: In this example, we will be executing 3 promises by chaining each of them with the then() method."
},
{
"code": null,
"e": 731,
"s": 726,
"text": "HTML"
},
{
"code": "<html><body> <h1 style=\"color: green;\"> GeeksforGeeks </h1> <b>Promises</b> <script> // Define an asynchronous function, // results in returning a promise async function task(url) { console.log(url + \" will be fetched now\") return fetch(url); } // Declaring an array of URLs let arr = [ \"https://www.google.com\", \"https://www.facebook.com\", \"https://www.twitter.com\" ]; // Resolving the first task Promise.resolve(() => { return task(arr[0]); }) // Resolving the second task .then(() => { return task(arr[1]); }) // Resolving the third task .then(() => { return task(arr[2]); }); </script></body></html>",
"e": 1455,
"s": 731,
"text": null
},
{
"code": null,
"e": 1463,
"s": 1455,
"text": "Output:"
},
{
"code": null,
"e": 1552,
"s": 1463,
"text": "https://www.facebook.com will be fetched now\nhttps://www.twitter.com will be fetched now"
},
{
"code": null,
"e": 1969,
"s": 1552,
"text": "The above approach is not feasible if there are a lot more promises in the array. Chaining of the function would get very tiring and will make the code lengthy. We can use the forEach() array function to execute the promises by storing the results in a variable and updating that variable at every promise. This will automatically go through all the promises and one can prevent repeatedly writing then() statements."
},
{
"code": null,
"e": 2067,
"s": 1969,
"text": "Example 2: In this example, we will be executing multiple promises by using the forEach() method."
},
{
"code": null,
"e": 2072,
"s": 2067,
"text": "HTML"
},
{
"code": "<html><body> <h1 style=\"color: green;\"> GeeksforGeeks </h1> <b>Promises</b> <script> // Define an asynchronous function async function task(url) { return fetch(url); } // Define array that has to be processed // by the asynchronous function let arr = [ \"https://www.google.com\", \"https://www.facebook.com\", \"https://www.twitter.com\", \"https://www.youtube.com\", \"https://www.netflix.com\", ]; // Declare a Promise using its resolve constructor let promise = Promise.resolve(); // Use the forEach function to evaluate // the promises in series // The value of // p would be the result // of previous promise arr.forEach((url, index) => { promise = promise.then(() => { let para = document.createElement(\"p\"); para.innerText = \"The async request of \" + url + \" has been resolved\"; document.body.appendChild(para); return task(url); }); }); </script></body></html>",
"e": 3097,
"s": 2072,
"text": null
},
{
"code": null,
"e": 3105,
"s": 3097,
"text": "Output:"
},
{
"code": null,
"e": 3124,
"s": 3105,
"text": "JavaScript-Methods"
},
{
"code": null,
"e": 3145,
"s": 3124,
"text": "JavaScript-Questions"
},
{
"code": null,
"e": 3152,
"s": 3145,
"text": "Picked"
},
{
"code": null,
"e": 3163,
"s": 3152,
"text": "JavaScript"
},
{
"code": null,
"e": 3180,
"s": 3163,
"text": "Web Technologies"
},
{
"code": null,
"e": 3278,
"s": 3180,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3339,
"s": 3278,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 3379,
"s": 3339,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 3420,
"s": 3379,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 3462,
"s": 3420,
"text": "Roadmap to Learn JavaScript For Beginners"
},
{
"code": null,
"e": 3484,
"s": 3462,
"text": "JavaScript | Promises"
},
{
"code": null,
"e": 3546,
"s": 3484,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 3579,
"s": 3546,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 3640,
"s": 3579,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 3690,
"s": 3640,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
How to find all the values of particular key of MongoDB Database using Node.js ? | 12 Feb, 2021
MongoDB module: This module of Node.js is used for connecting the MongoDB database as well as used for manipulating the collections and databases in MongoDB. The mongodb.connect() is the main method that is used for connecting to the MongoDB database which is running on a particular server on your machine (Refer to this article). We can also use promises, in this method to resolve the object contains all the methods and properties required for collection manipulation and reject the error that occurs during connection.
Project() method of MongoDB module is allowed only documents that specified as a parameter in this Method. This Method takes the document’s key name and with 0 and 1 value.
0 means except this key show all other’s keys value of MongoDB Collection.
1 means show only given keys value. Of MongoDB Collection.
Installing module: You can install the mongodb module using the following command:
node install mongodb
Project Structure: The project structure will look like the following.
Running the server on Local IP: In the following command, data is the folder name.
mongod --dbpath=data --bind_ip 127.0.0.1
MongoDB Database: Our database name and collection is shown below with some dummy data.
Database:GFG
Collection:aayush
Filename: index.js
Javascript
// Requiring moduleconst MongoClient = require("mongodb"); // Connection URLconst url = 'mongodb://localhost:27017/'; // Database nameconst databasename = "GFG"; MongoClient.connect(url).then((client) => { const connect = client.db(databasename); // Connect to collection const collection = connect.collection("aayush"); // Fetching the records of name key collection.find({ }).project({name:1}) .toArray().then((values) => { // Printing the values console.log(ans); }); }).catch((err) => { // Printing the error message console.log(err.Message);})
Run the index.js file using the following command:
node index.js
Output:
mridulmanochagfg
Node.js-Misc
Technical Scripter 2020
Node.js
Technical Scripter
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n12 Feb, 2021"
},
{
"code": null,
"e": 552,
"s": 28,
"text": "MongoDB module: This module of Node.js is used for connecting the MongoDB database as well as used for manipulating the collections and databases in MongoDB. The mongodb.connect() is the main method that is used for connecting to the MongoDB database which is running on a particular server on your machine (Refer to this article). We can also use promises, in this method to resolve the object contains all the methods and properties required for collection manipulation and reject the error that occurs during connection."
},
{
"code": null,
"e": 726,
"s": 552,
"text": "Project() method of MongoDB module is allowed only documents that specified as a parameter in this Method. This Method takes the document’s key name and with 0 and 1 value. "
},
{
"code": null,
"e": 801,
"s": 726,
"text": "0 means except this key show all other’s keys value of MongoDB Collection."
},
{
"code": null,
"e": 860,
"s": 801,
"text": "1 means show only given keys value. Of MongoDB Collection."
},
{
"code": null,
"e": 943,
"s": 860,
"text": "Installing module: You can install the mongodb module using the following command:"
},
{
"code": null,
"e": 964,
"s": 943,
"text": "node install mongodb"
},
{
"code": null,
"e": 1035,
"s": 964,
"text": "Project Structure: The project structure will look like the following."
},
{
"code": null,
"e": 1118,
"s": 1035,
"text": "Running the server on Local IP: In the following command, data is the folder name."
},
{
"code": null,
"e": 1159,
"s": 1118,
"text": "mongod --dbpath=data --bind_ip 127.0.0.1"
},
{
"code": null,
"e": 1247,
"s": 1159,
"text": "MongoDB Database: Our database name and collection is shown below with some dummy data."
},
{
"code": null,
"e": 1278,
"s": 1247,
"text": "Database:GFG\nCollection:aayush"
},
{
"code": null,
"e": 1297,
"s": 1278,
"text": "Filename: index.js"
},
{
"code": null,
"e": 1308,
"s": 1297,
"text": "Javascript"
},
{
"code": "// Requiring moduleconst MongoClient = require(\"mongodb\"); // Connection URLconst url = 'mongodb://localhost:27017/'; // Database nameconst databasename = \"GFG\"; MongoClient.connect(url).then((client) => { const connect = client.db(databasename); // Connect to collection const collection = connect.collection(\"aayush\"); // Fetching the records of name key collection.find({ }).project({name:1}) .toArray().then((values) => { // Printing the values console.log(ans); }); }).catch((err) => { // Printing the error message console.log(err.Message);})",
"e": 1912,
"s": 1308,
"text": null
},
{
"code": null,
"e": 1964,
"s": 1912,
"text": " Run the index.js file using the following command:"
},
{
"code": null,
"e": 1978,
"s": 1964,
"text": "node index.js"
},
{
"code": null,
"e": 1986,
"s": 1978,
"text": "Output:"
},
{
"code": null,
"e": 2003,
"s": 1986,
"text": "mridulmanochagfg"
},
{
"code": null,
"e": 2016,
"s": 2003,
"text": "Node.js-Misc"
},
{
"code": null,
"e": 2040,
"s": 2016,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 2048,
"s": 2040,
"text": "Node.js"
},
{
"code": null,
"e": 2067,
"s": 2048,
"text": "Technical Scripter"
},
{
"code": null,
"e": 2084,
"s": 2067,
"text": "Web Technologies"
},
{
"code": null,
"e": 2111,
"s": 2084,
"text": "Web technologies Questions"
}
] |
Difference between Recursive Predictive Descent Parser and Non-Recursive Predictive Descent Parser | 14 Jul, 2021
Prerequisite – Recursive Descent Parser
1. Recursive Predictive Descent Parser : Recursive Descent Parser is a top-down method of syntax analysis in which a set of recursive procedures is used to process input. One procedure is associated with each non-terminal of a grammar. Here we consider a simple form of recursive descent parsing called Predictive Recursive Descent Parser, in which look-ahead symbol unambiguously determines flow of control through procedure body for each non-terminal. The sequence of procedure calls during analysis of an input string implicitly defines a parse tree for input and can be used to build an explicit parse tree, if desired. In recursive descent parsing, parser may have more than one production to choose from for a single instance of input there concept of backtracking comes into play.
Back-tracking – It means, if one derivation of a production fails, syntax analyzer restarts process using different rules of same production. This technique may process input string more than once to determine right production.Top- down parser start from root node (start symbol) and match input string against production rules to replace them (if matched).
To understand this, take following example of CFG :
S -> aAb | aBb
A -> cx | dx
B -> xe
For an input string – read, a top-down parser, will behave like this.
It will start with S from production rules and will match its yield to left-most letter of input, i.e. ‘a’. The very production of S (S -> aAb) matches with it. So top-down parser advances to next input letter (i.e., ‘d’). The parser tries to expand non-terminal ‘A’ and checks its production from left (A -> cx). It does not match with next input symbol. So top-down parser backtracks to obtain next production rule of A, (A -> dx).
Now parser matches all input letters in an ordered manner. The string is accepted.
2. Non-Recursive Predictive Descent Parser : A form of recursive-descent parsing that does not require any back-tracking is known as predictive parsing. It is also called as LL(1) parsing table technique since we would be building a table for string to be parsed. It has capability to predict which production is to be used to replace input string. To accomplish its tasks, predictive parser uses a look-ahead pointer, which points to next input symbols. To make parser back-tracking free, predictive parser puts some constraints on grammar and accepts only a class of grammar known as LL(k) grammar.
Predictive parsing uses a stack and a parsing table to parse input and generate a parse tree. Both stack and input contains an end symbol $ to denote that stack is empty and input is consumed. The parser refers to parsing table to take any decision on input and stack element combination. There might be instances where there is no production matching input string, making parsing procedure to fail.
Difference between Recursive Predictive Descent Parser and Non-Recursive Predictive Descent Parser :
Recursive Predictive Descent Parser
Non-Recursive Predictive Descent Parser
varshagumber28
Compiler Design
Difference Between
GATE CS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Issues in the design of a code generator
Peephole Optimization in Compiler Design
Directed Acyclic graph in Compiler Design (with examples)
Type Checking in Compiler Design
Difference between Compiler and Interpreter
Class method vs Static method in Python
Difference between BFS and DFS
Difference between var, let and const keywords in JavaScript
Difference Between Method Overloading and Method Overriding in Java
Differences between JDK, JRE and JVM | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n14 Jul, 2021"
},
{
"code": null,
"e": 95,
"s": 54,
"text": "Prerequisite – Recursive Descent Parser "
},
{
"code": null,
"e": 884,
"s": 95,
"text": "1. Recursive Predictive Descent Parser : Recursive Descent Parser is a top-down method of syntax analysis in which a set of recursive procedures is used to process input. One procedure is associated with each non-terminal of a grammar. Here we consider a simple form of recursive descent parsing called Predictive Recursive Descent Parser, in which look-ahead symbol unambiguously determines flow of control through procedure body for each non-terminal. The sequence of procedure calls during analysis of an input string implicitly defines a parse tree for input and can be used to build an explicit parse tree, if desired. In recursive descent parsing, parser may have more than one production to choose from for a single instance of input there concept of backtracking comes into play. "
},
{
"code": null,
"e": 1243,
"s": 884,
"text": "Back-tracking – It means, if one derivation of a production fails, syntax analyzer restarts process using different rules of same production. This technique may process input string more than once to determine right production.Top- down parser start from root node (start symbol) and match input string against production rules to replace them (if matched). "
},
{
"code": null,
"e": 1296,
"s": 1243,
"text": "To understand this, take following example of CFG : "
},
{
"code": null,
"e": 1333,
"s": 1296,
"text": "S -> aAb | aBb\nA -> cx | dx\nB -> xe "
},
{
"code": null,
"e": 1404,
"s": 1333,
"text": "For an input string – read, a top-down parser, will behave like this. "
},
{
"code": null,
"e": 1839,
"s": 1404,
"text": "It will start with S from production rules and will match its yield to left-most letter of input, i.e. ‘a’. The very production of S (S -> aAb) matches with it. So top-down parser advances to next input letter (i.e., ‘d’). The parser tries to expand non-terminal ‘A’ and checks its production from left (A -> cx). It does not match with next input symbol. So top-down parser backtracks to obtain next production rule of A, (A -> dx). "
},
{
"code": null,
"e": 1923,
"s": 1839,
"text": "Now parser matches all input letters in an ordered manner. The string is accepted. "
},
{
"code": null,
"e": 2526,
"s": 1923,
"text": "2. Non-Recursive Predictive Descent Parser : A form of recursive-descent parsing that does not require any back-tracking is known as predictive parsing. It is also called as LL(1) parsing table technique since we would be building a table for string to be parsed. It has capability to predict which production is to be used to replace input string. To accomplish its tasks, predictive parser uses a look-ahead pointer, which points to next input symbols. To make parser back-tracking free, predictive parser puts some constraints on grammar and accepts only a class of grammar known as LL(k) grammar. "
},
{
"code": null,
"e": 2927,
"s": 2526,
"text": "Predictive parsing uses a stack and a parsing table to parse input and generate a parse tree. Both stack and input contains an end symbol $ to denote that stack is empty and input is consumed. The parser refers to parsing table to take any decision on input and stack element combination. There might be instances where there is no production matching input string, making parsing procedure to fail. "
},
{
"code": null,
"e": 3029,
"s": 2927,
"text": "Difference between Recursive Predictive Descent Parser and Non-Recursive Predictive Descent Parser : "
},
{
"code": null,
"e": 3065,
"s": 3029,
"text": "Recursive Predictive Descent Parser"
},
{
"code": null,
"e": 3105,
"s": 3065,
"text": "Non-Recursive Predictive Descent Parser"
},
{
"code": null,
"e": 3122,
"s": 3107,
"text": "varshagumber28"
},
{
"code": null,
"e": 3138,
"s": 3122,
"text": "Compiler Design"
},
{
"code": null,
"e": 3157,
"s": 3138,
"text": "Difference Between"
},
{
"code": null,
"e": 3165,
"s": 3157,
"text": "GATE CS"
},
{
"code": null,
"e": 3263,
"s": 3165,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3304,
"s": 3263,
"text": "Issues in the design of a code generator"
},
{
"code": null,
"e": 3345,
"s": 3304,
"text": "Peephole Optimization in Compiler Design"
},
{
"code": null,
"e": 3403,
"s": 3345,
"text": "Directed Acyclic graph in Compiler Design (with examples)"
},
{
"code": null,
"e": 3436,
"s": 3403,
"text": "Type Checking in Compiler Design"
},
{
"code": null,
"e": 3480,
"s": 3436,
"text": "Difference between Compiler and Interpreter"
},
{
"code": null,
"e": 3520,
"s": 3480,
"text": "Class method vs Static method in Python"
},
{
"code": null,
"e": 3551,
"s": 3520,
"text": "Difference between BFS and DFS"
},
{
"code": null,
"e": 3612,
"s": 3551,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 3680,
"s": 3612,
"text": "Difference Between Method Overloading and Method Overriding in Java"
}
] |
Get topmost N records within each group of a Pandas DataFrame | 28 Jul, 2020
Firstly, the pandas dataframe stores data in the form of a table. In some situations we need to retrieve data from dataframe according to some conditions. Such as if we want to get top N records of each group of the dataframe. Here we will use Groupby() function of pandas to group the columns. So we can do it as follows:
Firstly, we created a pandas dataframe:
Python3
#importing pandas as pdimport pandas as pd #creating dataframedf=pd.DataFrame({ 'Variables': ['A','A','A','A','B','B', 'B','C','C','C','C'], 'Value': [2,5,0,3,1,0,9,0,7,5,4]})df
Output:
Now, we will get topmost N values of each group of the ‘Variables’ column. Here reset_index() is used to provide a new index according to the grouping of data. And head() is used to get topmost N values from the top.
Example 1: Suppose the value of N=2
Python3
# setting value of N as 2N = 2 # using groupby to group acc. to# column 'Variable'df.groupby('Variables').head(N).reset_index(drop=True)
Output:
Example 2: Now, suppose the value of N=4
Python3
# setting value of N as 2N = 4 # using groupby to group acc. # to column 'Variable'df.groupby('Variables').head(N).reset_index(drop=True)
Output:
Python pandas-groupby
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
Python | os.path.join() method
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Get unique values from a list
Python | datetime.timedelta() function | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n28 Jul, 2020"
},
{
"code": null,
"e": 351,
"s": 28,
"text": "Firstly, the pandas dataframe stores data in the form of a table. In some situations we need to retrieve data from dataframe according to some conditions. Such as if we want to get top N records of each group of the dataframe. Here we will use Groupby() function of pandas to group the columns. So we can do it as follows:"
},
{
"code": null,
"e": 391,
"s": 351,
"text": "Firstly, we created a pandas dataframe:"
},
{
"code": null,
"e": 399,
"s": 391,
"text": "Python3"
},
{
"code": "#importing pandas as pdimport pandas as pd #creating dataframedf=pd.DataFrame({ 'Variables': ['A','A','A','A','B','B', 'B','C','C','C','C'], 'Value': [2,5,0,3,1,0,9,0,7,5,4]})df",
"e": 625,
"s": 399,
"text": null
},
{
"code": null,
"e": 633,
"s": 625,
"text": "Output:"
},
{
"code": null,
"e": 850,
"s": 633,
"text": "Now, we will get topmost N values of each group of the ‘Variables’ column. Here reset_index() is used to provide a new index according to the grouping of data. And head() is used to get topmost N values from the top."
},
{
"code": null,
"e": 886,
"s": 850,
"text": "Example 1: Suppose the value of N=2"
},
{
"code": null,
"e": 894,
"s": 886,
"text": "Python3"
},
{
"code": "# setting value of N as 2N = 2 # using groupby to group acc. to# column 'Variable'df.groupby('Variables').head(N).reset_index(drop=True)",
"e": 1032,
"s": 894,
"text": null
},
{
"code": null,
"e": 1040,
"s": 1032,
"text": "Output:"
},
{
"code": null,
"e": 1081,
"s": 1040,
"text": "Example 2: Now, suppose the value of N=4"
},
{
"code": null,
"e": 1089,
"s": 1081,
"text": "Python3"
},
{
"code": "# setting value of N as 2N = 4 # using groupby to group acc. # to column 'Variable'df.groupby('Variables').head(N).reset_index(drop=True)",
"e": 1228,
"s": 1089,
"text": null
},
{
"code": null,
"e": 1236,
"s": 1228,
"text": "Output:"
},
{
"code": null,
"e": 1258,
"s": 1236,
"text": "Python pandas-groupby"
},
{
"code": null,
"e": 1272,
"s": 1258,
"text": "Python-pandas"
},
{
"code": null,
"e": 1279,
"s": 1272,
"text": "Python"
},
{
"code": null,
"e": 1377,
"s": 1279,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1409,
"s": 1377,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 1436,
"s": 1409,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 1457,
"s": 1436,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 1480,
"s": 1457,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 1511,
"s": 1480,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 1567,
"s": 1511,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 1609,
"s": 1567,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 1651,
"s": 1609,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 1690,
"s": 1651,
"text": "Python | Get unique values from a list"
}
] |
Merge Sort for Linked Lists in JavaScript | 23 Jun, 2022
Prerequisite: Merge Sort for Linked Lists Merge sort is often preferred for sorting a linked list. The slow random-access performance of a linked list makes some other algorithms (such as quicksort) perform poorly, and others (such as heapsort) completely impossible. In this post, Merge sort for linked list is implemented using JavaScript. Examples:
Input : 5 -> 4 -> 3 -> 2 -> 1 Output :1 -> 2 -> 3 -> 4 -> 5 Input : 10 -> 20 -> 3 -> 2 -> 1 Output : 1 -> 2 -> 3 -> 10 -> 20
javascript
<script> // Create Node of LinkedListfunction Node(data) { this.node = data; this.next = null;} // To initialize a linkedlistfunction LinkedList(list) { this.head = list || null} // Function to insert The new Node into the linkedListLinkedList.prototype.insert = function(data) { // Check if the linked list is empty // so insert first node and lead head // points to generic node if (this.head === null) this.head = new Node(data); else { // If linked list is not empty, insert the node // at the end of the linked list let list = this.head; while (list.next) { list = list.next; } // Now here list pointer points to last // node let’s insert out new node in it list.next = new Node(data) }} // Function to print linkedListLinkedList.prototype.iterate = function() { // First we will check whether out // linked list is empty or node if (this.head === null) return null; // If linked list is not empty we will // iterate from each Node and prints // it’s value store in “data” property let list = this.head; // we will iterate until our list variable // contains the “Next” value of the last Node // i.e-> null while (list) { document.write(list.node) if (list.next) document.write(' -> ') list = list.next }} // Function to mergesort a linked listLinkedList.prototype.mergeSort = function(list) { if (list.next === null) return list; let count = 0; let countList = list let leftPart = list; let leftPointer = list; let rightPart = null; let rightPointer = null; // Counting the nodes in the received linkedlist while (countList.next !== null) { count++; countList = countList.next; } // counting the mid of the linked list let mid = Math.floor(count / 2) let count2 = 0; // separating the left and right part with // respect to mid node in the linked list while (count2 < mid) { count2++; leftPointer = leftPointer.next; } rightPart = new LinkedList(leftPointer.next); leftPointer.next = null; // Here are two linked list which // contains the left most nodes and right // most nodes of the mid node return this._mergeSort(this.mergeSort(leftPart), this.mergeSort(rightPart.head))} // Merging both lists in a sorted mannerLinkedList.prototype._mergeSort = function(left, right) { // Create a new empty linked list let result = new LinkedList() let resultPointer = result.head; let pointerLeft = left; let pointerRight = right; // If true then add left most node value in result, // increment left pointer else do the same in // right linked list. // This loop will be executed until pointer's of // a left node or right node reached null while (pointerLeft && pointerRight) { let tempNode = null; // Check if the right node's value is greater than // left node's value if (pointerLeft.node > pointerRight.node) { tempNode = pointerRight.node pointerRight = pointerRight.next; } else { tempNode = pointerLeft.node pointerLeft = pointerLeft.next; } if (result.head == null) { result.head = new Node(tempNode) resultPointer = result.head } else { resultPointer.next = new Node(tempNode) resultPointer = resultPointer.next } } // Add the remaining elements in the last of resultant // linked list resultPointer.next = pointerLeft; while (resultPointer.next) resultPointer = resultPointer.next resultPointer.next = pointerRight // Result is the new sorted linked list return result.head;} // Initialize the objectlet l = new LinkedList();l.insert(10)l.insert(20)l.insert(3)l.insert(2)l.insert(1)// Print the linked listl.iterate() // Sort the linked listl.head = LinkedList.prototype.mergeSort(l.head) document.write('<br> After sorting : '); // Print the sorted linked listl.iterate()</script>
Output
10 -> 20 -> 3 -> 2 -> 1
After sorting : 1 -> 2 -> 3 -> 10 -> 20
Time Complexity: O(n*log(n))Auxiliary Space: O(n)
simmytarika5
amankr0211
JavaScript-DS
Linked-List-Sorting
JavaScript
Linked List
Recursion
Sorting
Linked List
Recursion
Sorting
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Remove elements from a JavaScript Array
Difference Between PUT and PATCH Request
Roadmap to Learn JavaScript For Beginners
JavaScript | Promises
Linked List | Set 1 (Introduction)
Linked List | Set 2 (Inserting a node)
Reverse a linked list
Stack Data Structure (Introduction and Program)
Linked List | Set 3 (Deleting a node) | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n23 Jun, 2022"
},
{
"code": null,
"e": 405,
"s": 52,
"text": "Prerequisite: Merge Sort for Linked Lists Merge sort is often preferred for sorting a linked list. The slow random-access performance of a linked list makes some other algorithms (such as quicksort) perform poorly, and others (such as heapsort) completely impossible. In this post, Merge sort for linked list is implemented using JavaScript. Examples:"
},
{
"code": null,
"e": 530,
"s": 405,
"text": "Input : 5 -> 4 -> 3 -> 2 -> 1 Output :1 -> 2 -> 3 -> 4 -> 5 Input : 10 -> 20 -> 3 -> 2 -> 1 Output : 1 -> 2 -> 3 -> 10 -> 20"
},
{
"code": null,
"e": 541,
"s": 530,
"text": "javascript"
},
{
"code": "<script> // Create Node of LinkedListfunction Node(data) { this.node = data; this.next = null;} // To initialize a linkedlistfunction LinkedList(list) { this.head = list || null} // Function to insert The new Node into the linkedListLinkedList.prototype.insert = function(data) { // Check if the linked list is empty // so insert first node and lead head // points to generic node if (this.head === null) this.head = new Node(data); else { // If linked list is not empty, insert the node // at the end of the linked list let list = this.head; while (list.next) { list = list.next; } // Now here list pointer points to last // node let’s insert out new node in it list.next = new Node(data) }} // Function to print linkedListLinkedList.prototype.iterate = function() { // First we will check whether out // linked list is empty or node if (this.head === null) return null; // If linked list is not empty we will // iterate from each Node and prints // it’s value store in “data” property let list = this.head; // we will iterate until our list variable // contains the “Next” value of the last Node // i.e-> null while (list) { document.write(list.node) if (list.next) document.write(' -> ') list = list.next }} // Function to mergesort a linked listLinkedList.prototype.mergeSort = function(list) { if (list.next === null) return list; let count = 0; let countList = list let leftPart = list; let leftPointer = list; let rightPart = null; let rightPointer = null; // Counting the nodes in the received linkedlist while (countList.next !== null) { count++; countList = countList.next; } // counting the mid of the linked list let mid = Math.floor(count / 2) let count2 = 0; // separating the left and right part with // respect to mid node in the linked list while (count2 < mid) { count2++; leftPointer = leftPointer.next; } rightPart = new LinkedList(leftPointer.next); leftPointer.next = null; // Here are two linked list which // contains the left most nodes and right // most nodes of the mid node return this._mergeSort(this.mergeSort(leftPart), this.mergeSort(rightPart.head))} // Merging both lists in a sorted mannerLinkedList.prototype._mergeSort = function(left, right) { // Create a new empty linked list let result = new LinkedList() let resultPointer = result.head; let pointerLeft = left; let pointerRight = right; // If true then add left most node value in result, // increment left pointer else do the same in // right linked list. // This loop will be executed until pointer's of // a left node or right node reached null while (pointerLeft && pointerRight) { let tempNode = null; // Check if the right node's value is greater than // left node's value if (pointerLeft.node > pointerRight.node) { tempNode = pointerRight.node pointerRight = pointerRight.next; } else { tempNode = pointerLeft.node pointerLeft = pointerLeft.next; } if (result.head == null) { result.head = new Node(tempNode) resultPointer = result.head } else { resultPointer.next = new Node(tempNode) resultPointer = resultPointer.next } } // Add the remaining elements in the last of resultant // linked list resultPointer.next = pointerLeft; while (resultPointer.next) resultPointer = resultPointer.next resultPointer.next = pointerRight // Result is the new sorted linked list return result.head;} // Initialize the objectlet l = new LinkedList();l.insert(10)l.insert(20)l.insert(3)l.insert(2)l.insert(1)// Print the linked listl.iterate() // Sort the linked listl.head = LinkedList.prototype.mergeSort(l.head) document.write('<br> After sorting : '); // Print the sorted linked listl.iterate()</script>",
"e": 5125,
"s": 541,
"text": null
},
{
"code": null,
"e": 5132,
"s": 5125,
"text": "Output"
},
{
"code": null,
"e": 5197,
"s": 5132,
"text": "10 -> 20 -> 3 -> 2 -> 1\nAfter sorting : 1 -> 2 -> 3 -> 10 -> 20 "
},
{
"code": null,
"e": 5247,
"s": 5197,
"text": "Time Complexity: O(n*log(n))Auxiliary Space: O(n)"
},
{
"code": null,
"e": 5260,
"s": 5247,
"text": "simmytarika5"
},
{
"code": null,
"e": 5271,
"s": 5260,
"text": "amankr0211"
},
{
"code": null,
"e": 5285,
"s": 5271,
"text": "JavaScript-DS"
},
{
"code": null,
"e": 5305,
"s": 5285,
"text": "Linked-List-Sorting"
},
{
"code": null,
"e": 5316,
"s": 5305,
"text": "JavaScript"
},
{
"code": null,
"e": 5328,
"s": 5316,
"text": "Linked List"
},
{
"code": null,
"e": 5338,
"s": 5328,
"text": "Recursion"
},
{
"code": null,
"e": 5346,
"s": 5338,
"text": "Sorting"
},
{
"code": null,
"e": 5358,
"s": 5346,
"text": "Linked List"
},
{
"code": null,
"e": 5368,
"s": 5358,
"text": "Recursion"
},
{
"code": null,
"e": 5376,
"s": 5368,
"text": "Sorting"
},
{
"code": null,
"e": 5474,
"s": 5376,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5535,
"s": 5474,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 5575,
"s": 5535,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 5616,
"s": 5575,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 5658,
"s": 5616,
"text": "Roadmap to Learn JavaScript For Beginners"
},
{
"code": null,
"e": 5680,
"s": 5658,
"text": "JavaScript | Promises"
},
{
"code": null,
"e": 5715,
"s": 5680,
"text": "Linked List | Set 1 (Introduction)"
},
{
"code": null,
"e": 5754,
"s": 5715,
"text": "Linked List | Set 2 (Inserting a node)"
},
{
"code": null,
"e": 5776,
"s": 5754,
"text": "Reverse a linked list"
},
{
"code": null,
"e": 5824,
"s": 5776,
"text": "Stack Data Structure (Introduction and Program)"
}
] |
Mathworks EDG Program Interview Experience | On-Campus | 18 Aug, 2021
Mathworks conducted an online test on 13th August, Friday in our college, out of which around 25 people were shortlisted.
Coding Test: The online coding test (90 minutes) had MCQs and 2 coding questions. We had the liberty to choose any 2 languages out of C, C++, Java, Python.
The first coding question was “Reduced Fraction Sums”.Given a string describing an arithmetic expression that sums 2 fractions in the format a/b+c/d, compute the sum and fully reduce the resulting fraction (i.e. e/f), then save the reduced fraction as a string in the form of e/f, Example:
1/2+1/6 = 4/6,
which we can reduce to the string 2/3
Input:
A vector of strings containing
the arithmetic expressions
3
722/148+360/176
978/1212+183/183
358/472+301/417
Output:
2818/407
365/202
145679/98412The second coding question was Tom and Jerry in a Maze. We had to find the shortest distance that tom has to travel to read Jerry’s position while covering all the cells that contains cheese. (BFS)
The first coding question was “Reduced Fraction Sums”.Given a string describing an arithmetic expression that sums 2 fractions in the format a/b+c/d, compute the sum and fully reduce the resulting fraction (i.e. e/f), then save the reduced fraction as a string in the form of e/f, Example:
1/2+1/6 = 4/6,
which we can reduce to the string 2/3
Input:
A vector of strings containing
the arithmetic expressions
3
722/148+360/176
978/1212+183/183
358/472+301/417
Output:
2818/407
365/202
145679/98412
Given a string describing an arithmetic expression that sums 2 fractions in the format a/b+c/d, compute the sum and fully reduce the resulting fraction (i.e. e/f), then save the reduced fraction as a string in the form of e/f,
Example:
1/2+1/6 = 4/6,
which we can reduce to the string 2/3
Input:
A vector of strings containing
the arithmetic expressions
3
722/148+360/176
978/1212+183/183
358/472+301/417
Output:
2818/407
365/202
145679/98412
The second coding question was Tom and Jerry in a Maze. We had to find the shortest distance that tom has to travel to read Jerry’s position while covering all the cells that contains cheese. (BFS)
25 people were shortlisted for fulltime role after the online test.
On 16th, there was a 30 minutes PPT session about the EDG Program, followed by Group Discussion (30 mins), and HR(40 minutes) , Managerial(40 minutes) and Technical interview(65 minutes).
These interview rounds may happen in any order depending on the availability.
Group Discussion: Topic for group discussion was “What is you understanding about the EDG program, what do you like about the EDG program, what do you think are some challenges, top 3 reasons to join EDG program”
Every round is an elimination round (We were a group of 6 members, 2 were eliminated)
HR + Managerial: HR (40 minutes) and Managerial (40 minutes) rounds were almost similar for me, the same set of questions were asked :
Tell me about yourselfTell me about your internship and your work there.Since you’re already interning, you will get a PPO there, why join Mathworks?Tell me about your projectsYour areas of interest and which domain you want to join in MathworksLocation preference – Bangalore or Hyderabad ?What are some qualities that you feel your manager should have?What are some areas of improvements? He expected both technical and personal areas of improvementWhat do you know about EDG and why do you want to join ?What factors do you consider to join a company? Why not join your current company?
Tell me about yourself
Tell me about your internship and your work there.
Since you’re already interning, you will get a PPO there, why join Mathworks?
Tell me about your projects
Your areas of interest and which domain you want to join in Mathworks
Location preference – Bangalore or Hyderabad ?
What are some qualities that you feel your manager should have?
What are some areas of improvements? He expected both technical and personal areas of improvement
What do you know about EDG and why do you want to join ?
What factors do you consider to join a company? Why not join your current company?
and more questions which I cannot recall.
Technical Interview (65 minutes): I was shared a link to hackerrank coding platform. I was again asked to introduce myself, and talk about my internship experience, my areas of interest, language I am comfortable in. I was asked how confident are you in OOPs.
He asked to design and implement an abstract class, create a child class inheriting that class, and create an object of child class by keeping the constructor as private. When I took some time to figure out how to create an object of a class with private constructor, he gave hint to use a static function.
He asked about what is the use of virtual, what is inline function and how does it help in reducing the function call overhead, what do you know about OOPs, what is the default access specifier in a class.
Then he asked me to create an array of the child objects inside the static function. He then asked me to show him runtime polymorphism using the 2 classes.
Later he asked how to get factorial of a number recursively. What is the number of negative?
He asked to dynamically create a 2D char array using malloc or new.
He asked me what are function pointers, where are they used. He then asked me what are lambdas, where are they used, write a simple lambda to get sum of 2 integers.
He then asked me to write a simple function in python (to check if I am comfortable with python)
He then asked me what are linked lists, what are trees, what are their applications.
Out of 25 students, 3 fulltimes were selected.
Marketing
MathWorks
On-Campus
Interview Experiences
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Google SWE Interview Experience (Google Online Coding Challenge) 2022
TCS Digital Interview Questions
Samsung Interview Experience Research & Institute SRIB (Off-Campus) 2022
Amazon Interview Experience for SDE 1
Google Interview Questions
Amazon Interview Experience SDE-2 (3 Years Experienced)
TCS Ninja Interview Experience (2020 batch)
Write It Up: Share Your Interview Experiences
Samsung RnD Coding Round Questions
Nagarro Interview Experience | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n18 Aug, 2021"
},
{
"code": null,
"e": 176,
"s": 54,
"text": "Mathworks conducted an online test on 13th August, Friday in our college, out of which around 25 people were shortlisted."
},
{
"code": null,
"e": 332,
"s": 176,
"text": "Coding Test: The online coding test (90 minutes) had MCQs and 2 coding questions. We had the liberty to choose any 2 languages out of C, C++, Java, Python."
},
{
"code": null,
"e": 1030,
"s": 332,
"text": "The first coding question was “Reduced Fraction Sums”.Given a string describing an arithmetic expression that sums 2 fractions in the format a/b+c/d, compute the sum and fully reduce the resulting fraction (i.e. e/f), then save the reduced fraction as a string in the form of e/f, Example:\n1/2+1/6 = 4/6, \nwhich we can reduce to the string 2/3\nInput: \nA vector of strings containing \nthe arithmetic expressions\n3\n722/148+360/176\n978/1212+183/183\n358/472+301/417\nOutput: \n2818/407\n365/202\n145679/98412The second coding question was Tom and Jerry in a Maze. We had to find the shortest distance that tom has to travel to read Jerry’s position while covering all the cells that contains cheese. (BFS)"
},
{
"code": null,
"e": 1531,
"s": 1030,
"text": "The first coding question was “Reduced Fraction Sums”.Given a string describing an arithmetic expression that sums 2 fractions in the format a/b+c/d, compute the sum and fully reduce the resulting fraction (i.e. e/f), then save the reduced fraction as a string in the form of e/f, Example:\n1/2+1/6 = 4/6, \nwhich we can reduce to the string 2/3\nInput: \nA vector of strings containing \nthe arithmetic expressions\n3\n722/148+360/176\n978/1212+183/183\n358/472+301/417\nOutput: \n2818/407\n365/202\n145679/98412"
},
{
"code": null,
"e": 1759,
"s": 1531,
"text": "Given a string describing an arithmetic expression that sums 2 fractions in the format a/b+c/d, compute the sum and fully reduce the resulting fraction (i.e. e/f), then save the reduced fraction as a string in the form of e/f, "
},
{
"code": null,
"e": 1979,
"s": 1759,
"text": "Example:\n1/2+1/6 = 4/6, \nwhich we can reduce to the string 2/3\nInput: \nA vector of strings containing \nthe arithmetic expressions\n3\n722/148+360/176\n978/1212+183/183\n358/472+301/417\nOutput: \n2818/407\n365/202\n145679/98412"
},
{
"code": null,
"e": 2177,
"s": 1979,
"text": "The second coding question was Tom and Jerry in a Maze. We had to find the shortest distance that tom has to travel to read Jerry’s position while covering all the cells that contains cheese. (BFS)"
},
{
"code": null,
"e": 2246,
"s": 2177,
"text": "25 people were shortlisted for fulltime role after the online test. "
},
{
"code": null,
"e": 2434,
"s": 2246,
"text": "On 16th, there was a 30 minutes PPT session about the EDG Program, followed by Group Discussion (30 mins), and HR(40 minutes) , Managerial(40 minutes) and Technical interview(65 minutes)."
},
{
"code": null,
"e": 2512,
"s": 2434,
"text": "These interview rounds may happen in any order depending on the availability."
},
{
"code": null,
"e": 2725,
"s": 2512,
"text": "Group Discussion: Topic for group discussion was “What is you understanding about the EDG program, what do you like about the EDG program, what do you think are some challenges, top 3 reasons to join EDG program”"
},
{
"code": null,
"e": 2811,
"s": 2725,
"text": "Every round is an elimination round (We were a group of 6 members, 2 were eliminated)"
},
{
"code": null,
"e": 2946,
"s": 2811,
"text": "HR + Managerial: HR (40 minutes) and Managerial (40 minutes) rounds were almost similar for me, the same set of questions were asked :"
},
{
"code": null,
"e": 3536,
"s": 2946,
"text": "Tell me about yourselfTell me about your internship and your work there.Since you’re already interning, you will get a PPO there, why join Mathworks?Tell me about your projectsYour areas of interest and which domain you want to join in MathworksLocation preference – Bangalore or Hyderabad ?What are some qualities that you feel your manager should have?What are some areas of improvements? He expected both technical and personal areas of improvementWhat do you know about EDG and why do you want to join ?What factors do you consider to join a company? Why not join your current company?"
},
{
"code": null,
"e": 3559,
"s": 3536,
"text": "Tell me about yourself"
},
{
"code": null,
"e": 3610,
"s": 3559,
"text": "Tell me about your internship and your work there."
},
{
"code": null,
"e": 3688,
"s": 3610,
"text": "Since you’re already interning, you will get a PPO there, why join Mathworks?"
},
{
"code": null,
"e": 3716,
"s": 3688,
"text": "Tell me about your projects"
},
{
"code": null,
"e": 3786,
"s": 3716,
"text": "Your areas of interest and which domain you want to join in Mathworks"
},
{
"code": null,
"e": 3833,
"s": 3786,
"text": "Location preference – Bangalore or Hyderabad ?"
},
{
"code": null,
"e": 3897,
"s": 3833,
"text": "What are some qualities that you feel your manager should have?"
},
{
"code": null,
"e": 3995,
"s": 3897,
"text": "What are some areas of improvements? He expected both technical and personal areas of improvement"
},
{
"code": null,
"e": 4052,
"s": 3995,
"text": "What do you know about EDG and why do you want to join ?"
},
{
"code": null,
"e": 4135,
"s": 4052,
"text": "What factors do you consider to join a company? Why not join your current company?"
},
{
"code": null,
"e": 4178,
"s": 4135,
"text": "and more questions which I cannot recall."
},
{
"code": null,
"e": 4438,
"s": 4178,
"text": "Technical Interview (65 minutes): I was shared a link to hackerrank coding platform. I was again asked to introduce myself, and talk about my internship experience, my areas of interest, language I am comfortable in. I was asked how confident are you in OOPs."
},
{
"code": null,
"e": 4746,
"s": 4438,
"text": "He asked to design and implement an abstract class, create a child class inheriting that class, and create an object of child class by keeping the constructor as private. When I took some time to figure out how to create an object of a class with private constructor, he gave hint to use a static function. "
},
{
"code": null,
"e": 4953,
"s": 4746,
"text": "He asked about what is the use of virtual, what is inline function and how does it help in reducing the function call overhead, what do you know about OOPs, what is the default access specifier in a class. "
},
{
"code": null,
"e": 5109,
"s": 4953,
"text": "Then he asked me to create an array of the child objects inside the static function. He then asked me to show him runtime polymorphism using the 2 classes."
},
{
"code": null,
"e": 5202,
"s": 5109,
"text": "Later he asked how to get factorial of a number recursively. What is the number of negative?"
},
{
"code": null,
"e": 5270,
"s": 5202,
"text": "He asked to dynamically create a 2D char array using malloc or new."
},
{
"code": null,
"e": 5435,
"s": 5270,
"text": "He asked me what are function pointers, where are they used. He then asked me what are lambdas, where are they used, write a simple lambda to get sum of 2 integers."
},
{
"code": null,
"e": 5532,
"s": 5435,
"text": "He then asked me to write a simple function in python (to check if I am comfortable with python)"
},
{
"code": null,
"e": 5617,
"s": 5532,
"text": "He then asked me what are linked lists, what are trees, what are their applications."
},
{
"code": null,
"e": 5664,
"s": 5617,
"text": "Out of 25 students, 3 fulltimes were selected."
},
{
"code": null,
"e": 5674,
"s": 5664,
"text": "Marketing"
},
{
"code": null,
"e": 5684,
"s": 5674,
"text": "MathWorks"
},
{
"code": null,
"e": 5694,
"s": 5684,
"text": "On-Campus"
},
{
"code": null,
"e": 5716,
"s": 5694,
"text": "Interview Experiences"
},
{
"code": null,
"e": 5814,
"s": 5716,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5884,
"s": 5814,
"text": "Google SWE Interview Experience (Google Online Coding Challenge) 2022"
},
{
"code": null,
"e": 5916,
"s": 5884,
"text": "TCS Digital Interview Questions"
},
{
"code": null,
"e": 5989,
"s": 5916,
"text": "Samsung Interview Experience Research & Institute SRIB (Off-Campus) 2022"
},
{
"code": null,
"e": 6027,
"s": 5989,
"text": "Amazon Interview Experience for SDE 1"
},
{
"code": null,
"e": 6054,
"s": 6027,
"text": "Google Interview Questions"
},
{
"code": null,
"e": 6110,
"s": 6054,
"text": "Amazon Interview Experience SDE-2 (3 Years Experienced)"
},
{
"code": null,
"e": 6154,
"s": 6110,
"text": "TCS Ninja Interview Experience (2020 batch)"
},
{
"code": null,
"e": 6200,
"s": 6154,
"text": "Write It Up: Share Your Interview Experiences"
},
{
"code": null,
"e": 6235,
"s": 6200,
"text": "Samsung RnD Coding Round Questions"
}
] |
How can I get the list of files in a directory using C or C++? | Let us consider the following C++ sample code to get the list of files in a directory.
Begin
Declare a poniter dr to the DIR type.
Declare another pointer en of the dirent structure.
Call opendir() function to open all file in present directory.
Initialize dr pointer as dr = opendir(".").
If(dr)
while ((en = readdir(dr)) != NULL)
print all the file name using en->d_name.
call closedir() function to close the directory.
End.
#include <iostream>
#include <dirent.h>
#include <sys/types.h>
using namespace std;
int main(void) {
DIR *dr;
struct dirent *en;
dr = opendir("."); //open all directory
if (dr) {
while ((en = readdir(dr)) != NULL) {
cout<<" \n"<<en->d_name; //print all directory name
}
closedir(dr); //close all directory
}
return(0);
}
BINSEARC.C
BINTREE (1).C
BINTREE.C
BTREE.C
BUBBLE.C
c.txt
file3.txt
HEAP.C
HEAPSORT.C
HLINKLST.C
INSERTIO.C
LINKLIST.C
LINKLST.C
LLIST1.C
players.cpp
PolarRect.cpp
QUEUE.C
#include <stdio.h>
#include <dirent.h>
int main(void) {
DIR *dr;
struct dirent *en;
dr = opendir("."); //open all or present directory
if (dr) {
while ((en = readdir(dr)) != NULL) {
printf("%s\n", en->d_name); //print all directory name
}
closedir(dr); //close all directory
}
return(0);
}
BINSEARC.C
BINTREE (1).C
BINTREE.C
BTREE.C
BUBBLE.C
c.txt
file3.txt
HEAP.C
HEAPSORT.C
HLINKLST.C
INSERTIO.C
LINKLIST.C
LINKLST.C
LLIST1.C | [
{
"code": null,
"e": 1274,
"s": 1187,
"text": "Let us consider the following C++ sample code to get the list of files in a directory."
},
{
"code": null,
"e": 1651,
"s": 1274,
"text": "Begin\n Declare a poniter dr to the DIR type.\n Declare another pointer en of the dirent structure.\n Call opendir() function to open all file in present directory.\n Initialize dr pointer as dr = opendir(\".\").\n If(dr)\n while ((en = readdir(dr)) != NULL)\n print all the file name using en->d_name.\n call closedir() function to close the directory.\nEnd."
},
{
"code": null,
"e": 2017,
"s": 1651,
"text": "#include <iostream>\n#include <dirent.h>\n#include <sys/types.h>\nusing namespace std;\nint main(void) {\n DIR *dr;\n struct dirent *en;\n dr = opendir(\".\"); //open all directory\n if (dr) {\n while ((en = readdir(dr)) != NULL) {\n cout<<\" \\n\"<<en->d_name; //print all directory name\n }\n closedir(dr); //close all directory\n }\n return(0);\n}"
},
{
"code": null,
"e": 2189,
"s": 2017,
"text": "BINSEARC.C\nBINTREE (1).C\nBINTREE.C\nBTREE.C\nBUBBLE.C\nc.txt\nfile3.txt\nHEAP.C\nHEAPSORT.C\nHLINKLST.C\nINSERTIO.C\nLINKLIST.C\nLINKLST.C\nLLIST1.C\nplayers.cpp\nPolarRect.cpp\nQUEUE.C"
},
{
"code": null,
"e": 2524,
"s": 2189,
"text": "#include <stdio.h>\n#include <dirent.h>\nint main(void) {\n DIR *dr;\n struct dirent *en;\n dr = opendir(\".\"); //open all or present directory\n if (dr) {\n while ((en = readdir(dr)) != NULL) {\n printf(\"%s\\n\", en->d_name); //print all directory name\n }\n closedir(dr); //close all directory\n }\n return(0);\n}"
},
{
"code": null,
"e": 2662,
"s": 2524,
"text": "BINSEARC.C\nBINTREE (1).C\nBINTREE.C\nBTREE.C\nBUBBLE.C\nc.txt\nfile3.txt\nHEAP.C\nHEAPSORT.C\nHLINKLST.C\nINSERTIO.C\nLINKLIST.C\nLINKLST.C\nLLIST1.C"
}
] |
ReactJS - Creating a React Application | As we learned earlier, React library can be used in both simple and complex application. Simple application normally includes the React library in its script section. In complex application, developers have to split the code into multiple files and organize the code into a standard structure. Here, React toolchain provides pre-defined structure to bootstrap the application. Also, developers are free to use their own project structure to organize the code.
Let us see how to create simple as well as complex React application −
Simple application using CDN
Simple application using CDN
Complex application using React Create App cli
Complex application using React Create App cli
Complex application using customized method
Complex application using customized method
Rollup is one of the small and fast JavaScript bundlers. Let us learn how to use rollup bundler in this chapter.
Open a terminal and go to your workspace.
cd /go/to/your/workspace
Next, create a folder, expense-manager-rollup and move to newly created folder. Also, open the folder in your favorite editor or IDE.
mkdir expense-manager-rollup
cd expense-manager-rollup
Next, create and initialize the project.
npm init -y
Next, install React libraries (react and react-dom).
npm install react@^17.0.0 react-dom@^17.0.0 --save
Next, install babel and its preset libraries as development dependency.
npm install @babel/preset-env @babel/preset-react
@babel/core @babel/plugin-proposal-class-properties -D
Next, install rollup and its plugin libraries as development dependency.
npm i -D rollup postcss@8.1 @rollup/plugin-babel
@rollup/plugin-commonjs @rollup/plugin-node-resolve
@rollup/plugin-replace rollup-plugin-livereload
rollup-plugin-postcss rollup-plugin-serve postcss@8.1
postcss-modules@4 rollup-plugin-postcss
Next, install corejs and regenerator runtime for async programming.
npm i regenerator-runtime core-js
Next, create a babel configuration file, .babelrc under the root folder to configure the babel compiler.
{
"presets": [
[
"@babel/preset-env",
{
"useBuiltIns": "usage",
"corejs": 3,
"targets": "> 0.25%, not dead"
}
],
"@babel/preset-react"
],
"plugins": [
"@babel/plugin-proposal-class-properties"
]
}
Next, create a rollup.config.js file in the root folder to configure the rollup bundler.
import babel from '@rollup/plugin-babel';
import resolve from '@rollup/plugin-node-resolve';
import commonjs from '@rollup/plugin-commonjs';
import replace from '@rollup/plugin-replace';
import serve from 'rollup-plugin-serve';
import livereload from 'rollup-plugin-livereload';
import postcss from 'rollup-plugin-postcss'
export default {
input: 'src/index.js',
output: {
file: 'public/index.js',
format: 'iife',
},
plugins: [
commonjs({
include: [
'node_modules/**',
],
exclude: [
'node_modules/process-es6/**',
],
}),
resolve(),
babel({
exclude: 'node_modules/**'
}),
replace({
'process.env.NODE_ENV': JSON.stringify('production'),
}),
postcss({
autoModules: true
}),
livereload('public'),
serve({
contentBase: 'public',
port: 3000,
open: true,
}), // index.html should be in root of project
]
}
Next, update the package.json and include our entry point (public/index.js and public/styles.css) and command to build and run the application.
...
"main": "public/index.js",
"style": "public/styles.css",
"files": [
"public"
],
"scripts": {
"start": "rollup -c -w",
"build": "rollup"
},
...
Next, create a src folder in the root directory of the application, which will hold all the source code of the application.
Next, create a folder, components under src to include our React components. The idea is to create two files, <component>.js to write the component logic and <component.css> to include the component specific styles.
The final structure of the application will be as follows −
|-- package-lock.json
|-- package.json
|-- rollup.config.js
|-- .babelrc
`-- public
|-- index.html
`-- src
|-- index.js
`-- components
| |-- mycom.js
| |-- mycom.css
Let us create a new component, HelloWorld to confirm our setup is working fine. Create a file, HelloWorld.js under components folder and write a simple component to emit Hello World message.
import React from "react";
class HelloWorld extends React.Component {
render() {
return (
<div>
<h1>Hello World!</h1>
</div>
);
}
}
export default HelloWorld;
Next, create our main file, index.js under src folder and call our newly created component.
import React from 'react';
import ReactDOM from 'react-dom';
import HelloWorld from './components/HelloWorld';
ReactDOM.render(
<React.StrictMode>
<HelloWorld />
</React.StrictMode>,
document.getElementById('root')
);
Next, create a public folder in the root directory.
Next, create a html file, index.html (under public folder*), which will be our entry point of the application.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Expense Manager :: Rollup version</title>
</head>
<body>
<div id="root"></div>
<script type="text/JavaScript" src="./index.js"></script>
</body>
</html>
Next, build and run the application.
npm start
The npm build command will execute the rollup and bundle our application into a single file, dist/index.js file and start serving the application. The dev command will recompile the code whenever the source code is changed and also reload the changes in the browser.
> expense-manager-rollup@1.0.0 build /path/to/your/workspace/expense-manager-rollup
> rollup -c
rollup v2.36.1
bundles src/index.js → dist\index.js...
LiveReload enabled
http://localhost:10001 -> /path/to/your/workspace/expense-manager-rollup/dist
created dist\index.js in 4.7s
waiting for changes...
Next, open the browser and enter http://localhost:3000 in the address bar and press enter. serve application will serve our webpage as shown below.
Parcel is fast bundler with zero configuration. It expects just the entry point of the application and it will resolve the dependency itself and bundle the application. Let us learn how to use parcel bundler in this chapter.
First, install the parcel bundler.
npm install -g parcel-bundler
Open a terminal and go to your workspace.
cd /go/to/your/workspace
Next, create a folder, expense-manager-parcel and move to newly created folder. Also, open the folder in your favorite editor or IDE.
mkdir expense-manager-parcel
cd expense-manager-parcel
Next, create and initialize the project.
npm init -y
Next, install React libraries (react and react-dom).
npm install react@^17.0.0 react-dom@^17.0.0 --save
Next, install babel and its preset libraries as development dependency.
npm install @babel/preset-env @babel/preset-react @babel/core @babel/plugin-proposal-class-properties -D
Next, create a babel configuration file, .babelrc under the root folder to configure the babel compiler.
{
"presets": [
"@babel/preset-env",
"@babel/preset-react"
],
"plugins": [
"@babel/plugin-proposal-class-properties"
]
}
Next, update the package.json and include our entry point (src/index.js) and commands to build and run the application.
...
"main": "src/index.js",
"scripts": {
"start": "parcel public/index.html",
"build": "parcel build public/index.html --out-dir dist"
},
...
Next, create a src folder in the root directory of the application, which will hold all the source code of the application.
Next, create a folder, components under src to include our React components. The idea is to create two files, <component>.js to write the component logic and <component.css> to include the component specific styles.
The final structure of the application will be as follows −
|-- package-lock.json
|-- package.json
|-- .babelrc
`-- public
|-- index.html
`-- src
|-- index.js
`-- components
| |-- mycom.js
| |-- mycom.css
Let us create a new component, HelloWorld to confirm our setup is working fine. Create a file, HelloWorld.js under components folder and write a simple component to emit Hello World message.
import React from "react";
class HelloWorld extends React.Component {
render() {
return (
<div>
<h1>Hello World!</h1>
</div>
);
}
}
export default HelloWorld;
Next, create our main file, index.js under src folder and call our newly created component.
import React from 'react';
import ReactDOM from 'react-dom';
import HelloWorld from './components/HelloWorld';
ReactDOM.render(
<React.StrictMode>
<HelloWorld />
</React.StrictMode>,
document.getElementById('root')
);
Next, create a public folder in the root directory.
Next, create a html file, index.html (in the public folder), which will be our entry point of the application.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Expense Manager :: Parcel version</title>
</head>
<body>
<div id="root"></div>
<script type="text/JavaScript" src="../src/index.js"></script>
</body>
</html>
Next, build and run the application.
npm start
The npm build command will execute the parcel command. It will bundle and serve the application on the fly. It recompiles whenever the source code is changed and also reload the changes in the browser.
> expense-manager-parcel@1.0.0 dev /go/to/your/workspace/expense-manager-parcel
> parcel index.html Server running at http://localhost:1234
√ Built in 10.41s.
Next, open the browser and enter http://localhost:1234 in the address bar and press enter.
To create the production bundle of the application to deploy it in production server, use build command. It will generate a index.js file with all the bundled source code under dist folder.
npm run build
> expense-manager-parcel@1.0.0 build /go/to/your/workspace/expense-manager-parcel
> parcel build index.html --out-dir dist
√ Built in 6.42s.
dist\src.80621d09.js.map 270.23 KB 79ms
dist\src.80621d09.js 131.49 KB 4.67s
dist\index.html 221 B 1.63s | [
{
"code": null,
"e": 2627,
"s": 2167,
"text": "As we learned earlier, React library can be used in both simple and complex application. Simple application normally includes the React library in its script section. In complex application, developers have to split the code into multiple files and organize the code into a standard structure. Here, React toolchain provides pre-defined structure to bootstrap the application. Also, developers are free to use their own project structure to organize the code."
},
{
"code": null,
"e": 2698,
"s": 2627,
"text": "Let us see how to create simple as well as complex React application −"
},
{
"code": null,
"e": 2727,
"s": 2698,
"text": "Simple application using CDN"
},
{
"code": null,
"e": 2756,
"s": 2727,
"text": "Simple application using CDN"
},
{
"code": null,
"e": 2803,
"s": 2756,
"text": "Complex application using React Create App cli"
},
{
"code": null,
"e": 2850,
"s": 2803,
"text": "Complex application using React Create App cli"
},
{
"code": null,
"e": 2894,
"s": 2850,
"text": "Complex application using customized method"
},
{
"code": null,
"e": 2938,
"s": 2894,
"text": "Complex application using customized method"
},
{
"code": null,
"e": 3051,
"s": 2938,
"text": "Rollup is one of the small and fast JavaScript bundlers. Let us learn how to use rollup bundler in this chapter."
},
{
"code": null,
"e": 3093,
"s": 3051,
"text": "Open a terminal and go to your workspace."
},
{
"code": null,
"e": 3119,
"s": 3093,
"text": "cd /go/to/your/workspace\n"
},
{
"code": null,
"e": 3253,
"s": 3119,
"text": "Next, create a folder, expense-manager-rollup and move to newly created folder. Also, open the folder in your favorite editor or IDE."
},
{
"code": null,
"e": 3310,
"s": 3253,
"text": "mkdir expense-manager-rollup \ncd expense-manager-rollup\n"
},
{
"code": null,
"e": 3351,
"s": 3310,
"text": "Next, create and initialize the project."
},
{
"code": null,
"e": 3364,
"s": 3351,
"text": "npm init -y\n"
},
{
"code": null,
"e": 3417,
"s": 3364,
"text": "Next, install React libraries (react and react-dom)."
},
{
"code": null,
"e": 3469,
"s": 3417,
"text": "npm install react@^17.0.0 react-dom@^17.0.0 --save\n"
},
{
"code": null,
"e": 3541,
"s": 3469,
"text": "Next, install babel and its preset libraries as development dependency."
},
{
"code": null,
"e": 3648,
"s": 3541,
"text": "npm install @babel/preset-env @babel/preset-react \n@babel/core @babel/plugin-proposal-class-properties -D\n"
},
{
"code": null,
"e": 3721,
"s": 3648,
"text": "Next, install rollup and its plugin libraries as development dependency."
},
{
"code": null,
"e": 3969,
"s": 3721,
"text": "npm i -D rollup postcss@8.1 @rollup/plugin-babel \n@rollup/plugin-commonjs @rollup/plugin-node-resolve \n@rollup/plugin-replace rollup-plugin-livereload \nrollup-plugin-postcss rollup-plugin-serve postcss@8.1 \npostcss-modules@4 rollup-plugin-postcss\n"
},
{
"code": null,
"e": 4037,
"s": 3969,
"text": "Next, install corejs and regenerator runtime for async programming."
},
{
"code": null,
"e": 4072,
"s": 4037,
"text": "npm i regenerator-runtime core-js\n"
},
{
"code": null,
"e": 4177,
"s": 4072,
"text": "Next, create a babel configuration file, .babelrc under the root folder to configure the babel compiler."
},
{
"code": null,
"e": 4473,
"s": 4177,
"text": "{\n \"presets\": [\n [\n \"@babel/preset-env\",\n {\n \"useBuiltIns\": \"usage\",\n \"corejs\": 3,\n \"targets\": \"> 0.25%, not dead\"\n }\n ],\n \"@babel/preset-react\"\n ],\n \"plugins\": [\n \"@babel/plugin-proposal-class-properties\"\n ]\n}"
},
{
"code": null,
"e": 4562,
"s": 4473,
"text": "Next, create a rollup.config.js file in the root folder to configure the rollup bundler."
},
{
"code": null,
"e": 5575,
"s": 4562,
"text": "import babel from '@rollup/plugin-babel';\nimport resolve from '@rollup/plugin-node-resolve';\nimport commonjs from '@rollup/plugin-commonjs';\nimport replace from '@rollup/plugin-replace';\nimport serve from 'rollup-plugin-serve';\nimport livereload from 'rollup-plugin-livereload';\nimport postcss from 'rollup-plugin-postcss'\n\nexport default {\n input: 'src/index.js',\n output: {\n file: 'public/index.js',\n format: 'iife',\n },\n plugins: [\n commonjs({\n include: [\n 'node_modules/**',\n ],\n exclude: [\n 'node_modules/process-es6/**',\n ],\n }),\n resolve(),\n babel({\n exclude: 'node_modules/**'\n }),\n replace({\n 'process.env.NODE_ENV': JSON.stringify('production'),\n }),\n postcss({\n autoModules: true\n }),\n livereload('public'),\n serve({\n contentBase: 'public',\n port: 3000,\n open: true,\n }), // index.html should be in root of project\n ]\n}"
},
{
"code": null,
"e": 5719,
"s": 5575,
"text": "Next, update the package.json and include our entry point (public/index.js and public/styles.css) and command to build and run the application."
},
{
"code": null,
"e": 5875,
"s": 5719,
"text": "...\n\"main\": \"public/index.js\",\n\"style\": \"public/styles.css\",\n\"files\": [\n \"public\"\n],\n\"scripts\": {\n \"start\": \"rollup -c -w\",\n \"build\": \"rollup\"\n},\n..."
},
{
"code": null,
"e": 5999,
"s": 5875,
"text": "Next, create a src folder in the root directory of the application, which will hold all the source code of the application."
},
{
"code": null,
"e": 6215,
"s": 5999,
"text": "Next, create a folder, components under src to include our React components. The idea is to create two files, <component>.js to write the component logic and <component.css> to include the component specific styles."
},
{
"code": null,
"e": 6275,
"s": 6215,
"text": "The final structure of the application will be as follows −"
},
{
"code": null,
"e": 6458,
"s": 6275,
"text": "|-- package-lock.json\n|-- package.json\n|-- rollup.config.js\n|-- .babelrc\n`-- public\n |-- index.html\n`-- src\n |-- index.js\n `-- components\n | |-- mycom.js\n | |-- mycom.css"
},
{
"code": null,
"e": 6649,
"s": 6458,
"text": "Let us create a new component, HelloWorld to confirm our setup is working fine. Create a file, HelloWorld.js under components folder and write a simple component to emit Hello World message."
},
{
"code": null,
"e": 6857,
"s": 6649,
"text": "import React from \"react\";\n\nclass HelloWorld extends React.Component {\n render() {\n return (\n <div>\n <h1>Hello World!</h1>\n </div>\n );\n }\n}\nexport default HelloWorld;"
},
{
"code": null,
"e": 6949,
"s": 6857,
"text": "Next, create our main file, index.js under src folder and call our newly created component."
},
{
"code": null,
"e": 7183,
"s": 6949,
"text": "import React from 'react';\nimport ReactDOM from 'react-dom';\nimport HelloWorld from './components/HelloWorld';\n\nReactDOM.render(\n <React.StrictMode>\n <HelloWorld />\n </React.StrictMode>,\n document.getElementById('root')\n);"
},
{
"code": null,
"e": 7235,
"s": 7183,
"text": "Next, create a public folder in the root directory."
},
{
"code": null,
"e": 7346,
"s": 7235,
"text": "Next, create a html file, index.html (under public folder*), which will be our entry point of the application."
},
{
"code": null,
"e": 7605,
"s": 7346,
"text": "<!DOCTYPE html>\n<html lang=\"en\">\n <head>\n <meta charset=\"utf-8\">\n <title>Expense Manager :: Rollup version</title>\n </head>\n <body>\n <div id=\"root\"></div>\n <script type=\"text/JavaScript\" src=\"./index.js\"></script>\n </body>\n</html>"
},
{
"code": null,
"e": 7642,
"s": 7605,
"text": "Next, build and run the application."
},
{
"code": null,
"e": 7653,
"s": 7642,
"text": "npm start\n"
},
{
"code": null,
"e": 7920,
"s": 7653,
"text": "The npm build command will execute the rollup and bundle our application into a single file, dist/index.js file and start serving the application. The dev command will recompile the code whenever the source code is changed and also reload the changes in the browser."
},
{
"code": null,
"e": 8229,
"s": 7920,
"text": "> expense-manager-rollup@1.0.0 build /path/to/your/workspace/expense-manager-rollup \n> rollup -c \nrollup v2.36.1 \nbundles src/index.js → dist\\index.js... \nLiveReload enabled \nhttp://localhost:10001 -> /path/to/your/workspace/expense-manager-rollup/dist \ncreated dist\\index.js in 4.7s \n\nwaiting for changes..."
},
{
"code": null,
"e": 8377,
"s": 8229,
"text": "Next, open the browser and enter http://localhost:3000 in the address bar and press enter. serve application will serve our webpage as shown below."
},
{
"code": null,
"e": 8602,
"s": 8377,
"text": "Parcel is fast bundler with zero configuration. It expects just the entry point of the application and it will resolve the dependency itself and bundle the application. Let us learn how to use parcel bundler in this chapter."
},
{
"code": null,
"e": 8637,
"s": 8602,
"text": "First, install the parcel bundler."
},
{
"code": null,
"e": 8668,
"s": 8637,
"text": "npm install -g parcel-bundler\n"
},
{
"code": null,
"e": 8710,
"s": 8668,
"text": "Open a terminal and go to your workspace."
},
{
"code": null,
"e": 8736,
"s": 8710,
"text": "cd /go/to/your/workspace\n"
},
{
"code": null,
"e": 8870,
"s": 8736,
"text": "Next, create a folder, expense-manager-parcel and move to newly created folder. Also, open the folder in your favorite editor or IDE."
},
{
"code": null,
"e": 8927,
"s": 8870,
"text": "mkdir expense-manager-parcel \ncd expense-manager-parcel\n"
},
{
"code": null,
"e": 8968,
"s": 8927,
"text": "Next, create and initialize the project."
},
{
"code": null,
"e": 8981,
"s": 8968,
"text": "npm init -y\n"
},
{
"code": null,
"e": 9034,
"s": 8981,
"text": "Next, install React libraries (react and react-dom)."
},
{
"code": null,
"e": 9086,
"s": 9034,
"text": "npm install react@^17.0.0 react-dom@^17.0.0 --save\n"
},
{
"code": null,
"e": 9158,
"s": 9086,
"text": "Next, install babel and its preset libraries as development dependency."
},
{
"code": null,
"e": 9264,
"s": 9158,
"text": "npm install @babel/preset-env @babel/preset-react @babel/core @babel/plugin-proposal-class-properties -D\n"
},
{
"code": null,
"e": 9369,
"s": 9264,
"text": "Next, create a babel configuration file, .babelrc under the root folder to configure the babel compiler."
},
{
"code": null,
"e": 9520,
"s": 9369,
"text": "{\n \"presets\": [\n \"@babel/preset-env\",\n \"@babel/preset-react\"\n ],\n \"plugins\": [\n \"@babel/plugin-proposal-class-properties\"\n ]\n}\n"
},
{
"code": null,
"e": 9640,
"s": 9520,
"text": "Next, update the package.json and include our entry point (src/index.js) and commands to build and run the application."
},
{
"code": null,
"e": 9792,
"s": 9640,
"text": "... \n\"main\": \"src/index.js\", \n\"scripts\": {\n \"start\": \"parcel public/index.html\",\n \"build\": \"parcel build public/index.html --out-dir dist\" \n},\n...\n"
},
{
"code": null,
"e": 9916,
"s": 9792,
"text": "Next, create a src folder in the root directory of the application, which will hold all the source code of the application."
},
{
"code": null,
"e": 10132,
"s": 9916,
"text": "Next, create a folder, components under src to include our React components. The idea is to create two files, <component>.js to write the component logic and <component.css> to include the component specific styles."
},
{
"code": null,
"e": 10192,
"s": 10132,
"text": "The final structure of the application will be as follows −"
},
{
"code": null,
"e": 10355,
"s": 10192,
"text": "|-- package-lock.json\n|-- package.json\n|-- .babelrc\n`-- public\n |-- index.html\n`-- src\n |-- index.js\n `-- components\n | |-- mycom.js\n | |-- mycom.css\n"
},
{
"code": null,
"e": 10546,
"s": 10355,
"text": "Let us create a new component, HelloWorld to confirm our setup is working fine. Create a file, HelloWorld.js under components folder and write a simple component to emit Hello World message."
},
{
"code": null,
"e": 10754,
"s": 10546,
"text": "import React from \"react\";\n\nclass HelloWorld extends React.Component {\n render() {\n return (\n <div>\n <h1>Hello World!</h1>\n </div>\n );\n }\n}\nexport default HelloWorld;"
},
{
"code": null,
"e": 10846,
"s": 10754,
"text": "Next, create our main file, index.js under src folder and call our newly created component."
},
{
"code": null,
"e": 11080,
"s": 10846,
"text": "import React from 'react';\nimport ReactDOM from 'react-dom';\nimport HelloWorld from './components/HelloWorld';\n\nReactDOM.render(\n <React.StrictMode>\n <HelloWorld />\n </React.StrictMode>,\n document.getElementById('root')\n);"
},
{
"code": null,
"e": 11132,
"s": 11080,
"text": "Next, create a public folder in the root directory."
},
{
"code": null,
"e": 11243,
"s": 11132,
"text": "Next, create a html file, index.html (in the public folder), which will be our entry point of the application."
},
{
"code": null,
"e": 11507,
"s": 11243,
"text": "<!DOCTYPE html>\n<html lang=\"en\">\n <head>\n <meta charset=\"utf-8\">\n <title>Expense Manager :: Parcel version</title>\n </head>\n <body>\n <div id=\"root\"></div>\n <script type=\"text/JavaScript\" src=\"../src/index.js\"></script>\n </body>\n</html>"
},
{
"code": null,
"e": 11544,
"s": 11507,
"text": "Next, build and run the application."
},
{
"code": null,
"e": 11555,
"s": 11544,
"text": "npm start\n"
},
{
"code": null,
"e": 11757,
"s": 11555,
"text": "The npm build command will execute the parcel command. It will bundle and serve the application on the fly. It recompiles whenever the source code is changed and also reload the changes in the browser."
},
{
"code": null,
"e": 11919,
"s": 11757,
"text": "> expense-manager-parcel@1.0.0 dev /go/to/your/workspace/expense-manager-parcel \n> parcel index.html Server running at http://localhost:1234 \n√ Built in 10.41s.\n"
},
{
"code": null,
"e": 12010,
"s": 11919,
"text": "Next, open the browser and enter http://localhost:1234 in the address bar and press enter."
},
{
"code": null,
"e": 12200,
"s": 12010,
"text": "To create the production bundle of the application to deploy it in production server, use build command. It will generate a index.js file with all the bundled source code under dist folder."
}
] |
PostgreSQL - LIMIT clause - GeeksforGeeks | 28 Aug, 2020
The PostgreSQL LIMIT clause is used to get a subset of rows generated by a query. It is an optional clause of the SELECT statement.
Syntax: SELECT * FROM table_name LIMIT n;
Now let’s analyze the syntax above:
The above syntax returns “n” no. of query results.
If “n” is skipped or equal to NULL it returns all the query results.
For the sake of this article we will be using the sample DVD rental database, which is explained here and can be downloaded by clicking on this link.
Now, let’s look into a few examples.
Example 1:In this example we will be using the LIMIT clause to get the first 10 films ordered by the “film_id” from the “film” table of our sample database.
SELECT
film_id,
title,
rating
FROM
film
ORDER BY
film_id
LIMIT 10;
Output:
Example 2:In this example we will be using the LIMIT clause to get the top 10 expensive films ordered by the “rental_rate” from the “film” table of our sample database.
SELECT
film_id,
title,
rental_rate
FROM
film
ORDER BY
rental_rate DESC
LIMIT 10;
Output:
postgreSQL-clauses
PostgreSQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
PostgreSQL - CREATE PROCEDURE
PostgreSQL - GROUP BY clause
PostgreSQL - DROP INDEX
PostgreSQL - REPLACE Function
PostgreSQL - CREATE SCHEMA
PostgreSQL - TIME Data Type
PostgreSQL - Copy Table
PostgreSQL - Rename Table
PostgreSQL - RENAME COLUMN
PostgreSQL - Cursor | [
{
"code": null,
"e": 24060,
"s": 24032,
"text": "\n28 Aug, 2020"
},
{
"code": null,
"e": 24192,
"s": 24060,
"text": "The PostgreSQL LIMIT clause is used to get a subset of rows generated by a query. It is an optional clause of the SELECT statement."
},
{
"code": null,
"e": 24234,
"s": 24192,
"text": "Syntax: SELECT * FROM table_name LIMIT n;"
},
{
"code": null,
"e": 24270,
"s": 24234,
"text": "Now let’s analyze the syntax above:"
},
{
"code": null,
"e": 24321,
"s": 24270,
"text": "The above syntax returns “n” no. of query results."
},
{
"code": null,
"e": 24390,
"s": 24321,
"text": "If “n” is skipped or equal to NULL it returns all the query results."
},
{
"code": null,
"e": 24540,
"s": 24390,
"text": "For the sake of this article we will be using the sample DVD rental database, which is explained here and can be downloaded by clicking on this link."
},
{
"code": null,
"e": 24577,
"s": 24540,
"text": "Now, let’s look into a few examples."
},
{
"code": null,
"e": 24734,
"s": 24577,
"text": "Example 1:In this example we will be using the LIMIT clause to get the first 10 films ordered by the “film_id” from the “film” table of our sample database."
},
{
"code": null,
"e": 24821,
"s": 24734,
"text": "SELECT\n film_id,\n title,\n rating\nFROM\n film\nORDER BY\n film_id\nLIMIT 10;"
},
{
"code": null,
"e": 24829,
"s": 24821,
"text": "Output:"
},
{
"code": null,
"e": 24998,
"s": 24829,
"text": "Example 2:In this example we will be using the LIMIT clause to get the top 10 expensive films ordered by the “rental_rate” from the “film” table of our sample database."
},
{
"code": null,
"e": 25099,
"s": 24998,
"text": "SELECT\n film_id,\n title,\n rental_rate\nFROM\n film\nORDER BY\n rental_rate DESC\nLIMIT 10;"
},
{
"code": null,
"e": 25107,
"s": 25099,
"text": "Output:"
},
{
"code": null,
"e": 25126,
"s": 25107,
"text": "postgreSQL-clauses"
},
{
"code": null,
"e": 25137,
"s": 25126,
"text": "PostgreSQL"
},
{
"code": null,
"e": 25235,
"s": 25137,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25265,
"s": 25235,
"text": "PostgreSQL - CREATE PROCEDURE"
},
{
"code": null,
"e": 25294,
"s": 25265,
"text": "PostgreSQL - GROUP BY clause"
},
{
"code": null,
"e": 25318,
"s": 25294,
"text": "PostgreSQL - DROP INDEX"
},
{
"code": null,
"e": 25348,
"s": 25318,
"text": "PostgreSQL - REPLACE Function"
},
{
"code": null,
"e": 25375,
"s": 25348,
"text": "PostgreSQL - CREATE SCHEMA"
},
{
"code": null,
"e": 25403,
"s": 25375,
"text": "PostgreSQL - TIME Data Type"
},
{
"code": null,
"e": 25427,
"s": 25403,
"text": "PostgreSQL - Copy Table"
},
{
"code": null,
"e": 25453,
"s": 25427,
"text": "PostgreSQL - Rename Table"
},
{
"code": null,
"e": 25480,
"s": 25453,
"text": "PostgreSQL - RENAME COLUMN"
}
] |
C++ Program to check if a given String is Palindrome or not - GeeksforGeeks | 21 Jul, 2021
Given a string S consisting of N characters of the English alphabet, the task is to check if the given string is a palindrome. If the given string is a palindrome, then print “Yes“. Otherwise, print “No“.
Note: A string is said to be palindrome if the reverse of the string is the same as the string.
Examples:
Input: S = “ABCDCBA”Output: YesExplanation:The reverse of the given string is equal to the (ABCDCBA) which is equal to the given string. Therefore, the given string is palindrome.
Input: S = “GeeksforGeeks”Output: NoExplanation: The reverse of the given string is equal to the (skeeGrofskeeG) which is not equal to the given string. Therefore, the given string is not a palindrome.
Naive Approach: The simplest approach to use the inbuilt reverse function in the STL. Follow the steps below to solve the problem:
Copy the string S to another string, say P, and then reverse the string S.
Now check if the string S is equal to the string P and then print “Yes“. Otherwise, print “No“.
Below is the implementation of the above approach:
C++
// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to check whether// the string is palindromestring isPalindrome(string S){ // Stores the reverse of the // string S string P = S; // Reverse the string P reverse(P.begin(), P.end()); // If S is equal to P if (S == P) { // Return "Yes" return "Yes"; } // Otherwise else { // return "No" return "No"; }} // Driver Codeint main(){ string S = "ABCDCBA"; cout << isPalindrome(S); return 0;}
Yes
Time Complexity: O(N)Auxiliary Space: O(N)
Efficient Approach: The above approach can be optimized in space complexity by traversing the string and checking whether the character at ith index is equal to the character at the (N-i-1)th index for every index in the range [0, N/2]. Follow the steps below to solve the problem:
Iterate over the range [0, N/2], using the variable i and in each iteration check if the character at index i and N-i-1 are not equal, then print “No” and break.
If none of the above cases satisfy, then print “Yes“.
Below is the implementation of the above approach:
C++
// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to check whether string// is palindromestring isPalindrome(string S){ // Iterate over the range [0, N/2] for (int i = 0; i < S.length() / 2; i++) { // If S[i] is not equal to // the S[N-i-1] if (S[i] != S[S.length() - i - 1]) { // Return No return "No"; } } // Return "Yes" return "Yes";} // Driver Codeint main(){ string S = "ABCDCBA"; cout << isPalindrome(S); return 0;}
Yes
Time Complexity: O(N)Auxiliary Space: O(1)
sooda367
palindrome
Reverse
C++ Programs
School Programming
Strings
Strings
palindrome
Reverse
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Passing a function as a parameter in C++
Const keyword in C++
cout in C++
Program to implement Singly Linked List in C++ using class
Iterative Letter Combinations of a Phone Number
Python Dictionary
Arrays in C/C++
Inheritance in C++
Reverse a string in Java
C++ Classes and Objects | [
{
"code": null,
"e": 25788,
"s": 25760,
"text": "\n21 Jul, 2021"
},
{
"code": null,
"e": 25993,
"s": 25788,
"text": "Given a string S consisting of N characters of the English alphabet, the task is to check if the given string is a palindrome. If the given string is a palindrome, then print “Yes“. Otherwise, print “No“."
},
{
"code": null,
"e": 26090,
"s": 25993,
"text": "Note: A string is said to be palindrome if the reverse of the string is the same as the string. "
},
{
"code": null,
"e": 26100,
"s": 26090,
"text": "Examples:"
},
{
"code": null,
"e": 26280,
"s": 26100,
"text": "Input: S = “ABCDCBA”Output: YesExplanation:The reverse of the given string is equal to the (ABCDCBA) which is equal to the given string. Therefore, the given string is palindrome."
},
{
"code": null,
"e": 26482,
"s": 26280,
"text": "Input: S = “GeeksforGeeks”Output: NoExplanation: The reverse of the given string is equal to the (skeeGrofskeeG) which is not equal to the given string. Therefore, the given string is not a palindrome."
},
{
"code": null,
"e": 26613,
"s": 26482,
"text": "Naive Approach: The simplest approach to use the inbuilt reverse function in the STL. Follow the steps below to solve the problem:"
},
{
"code": null,
"e": 26688,
"s": 26613,
"text": "Copy the string S to another string, say P, and then reverse the string S."
},
{
"code": null,
"e": 26784,
"s": 26688,
"text": "Now check if the string S is equal to the string P and then print “Yes“. Otherwise, print “No“."
},
{
"code": null,
"e": 26835,
"s": 26784,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 26839,
"s": 26835,
"text": "C++"
},
{
"code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to check whether// the string is palindromestring isPalindrome(string S){ // Stores the reverse of the // string S string P = S; // Reverse the string P reverse(P.begin(), P.end()); // If S is equal to P if (S == P) { // Return \"Yes\" return \"Yes\"; } // Otherwise else { // return \"No\" return \"No\"; }} // Driver Codeint main(){ string S = \"ABCDCBA\"; cout << isPalindrome(S); return 0;}",
"e": 27391,
"s": 26839,
"text": null
},
{
"code": null,
"e": 27395,
"s": 27391,
"text": "Yes"
},
{
"code": null,
"e": 27438,
"s": 27395,
"text": "Time Complexity: O(N)Auxiliary Space: O(N)"
},
{
"code": null,
"e": 27720,
"s": 27438,
"text": "Efficient Approach: The above approach can be optimized in space complexity by traversing the string and checking whether the character at ith index is equal to the character at the (N-i-1)th index for every index in the range [0, N/2]. Follow the steps below to solve the problem:"
},
{
"code": null,
"e": 27882,
"s": 27720,
"text": "Iterate over the range [0, N/2], using the variable i and in each iteration check if the character at index i and N-i-1 are not equal, then print “No” and break."
},
{
"code": null,
"e": 27936,
"s": 27882,
"text": "If none of the above cases satisfy, then print “Yes“."
},
{
"code": null,
"e": 27987,
"s": 27936,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 27991,
"s": 27987,
"text": "C++"
},
{
"code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to check whether string// is palindromestring isPalindrome(string S){ // Iterate over the range [0, N/2] for (int i = 0; i < S.length() / 2; i++) { // If S[i] is not equal to // the S[N-i-1] if (S[i] != S[S.length() - i - 1]) { // Return No return \"No\"; } } // Return \"Yes\" return \"Yes\";} // Driver Codeint main(){ string S = \"ABCDCBA\"; cout << isPalindrome(S); return 0;}",
"e": 28534,
"s": 27991,
"text": null
},
{
"code": null,
"e": 28538,
"s": 28534,
"text": "Yes"
},
{
"code": null,
"e": 28583,
"s": 28540,
"text": "Time Complexity: O(N)Auxiliary Space: O(1)"
},
{
"code": null,
"e": 28594,
"s": 28585,
"text": "sooda367"
},
{
"code": null,
"e": 28605,
"s": 28594,
"text": "palindrome"
},
{
"code": null,
"e": 28613,
"s": 28605,
"text": "Reverse"
},
{
"code": null,
"e": 28626,
"s": 28613,
"text": "C++ Programs"
},
{
"code": null,
"e": 28645,
"s": 28626,
"text": "School Programming"
},
{
"code": null,
"e": 28653,
"s": 28645,
"text": "Strings"
},
{
"code": null,
"e": 28661,
"s": 28653,
"text": "Strings"
},
{
"code": null,
"e": 28672,
"s": 28661,
"text": "palindrome"
},
{
"code": null,
"e": 28680,
"s": 28672,
"text": "Reverse"
},
{
"code": null,
"e": 28778,
"s": 28680,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28819,
"s": 28778,
"text": "Passing a function as a parameter in C++"
},
{
"code": null,
"e": 28840,
"s": 28819,
"text": "Const keyword in C++"
},
{
"code": null,
"e": 28852,
"s": 28840,
"text": "cout in C++"
},
{
"code": null,
"e": 28911,
"s": 28852,
"text": "Program to implement Singly Linked List in C++ using class"
},
{
"code": null,
"e": 28959,
"s": 28911,
"text": "Iterative Letter Combinations of a Phone Number"
},
{
"code": null,
"e": 28977,
"s": 28959,
"text": "Python Dictionary"
},
{
"code": null,
"e": 28993,
"s": 28977,
"text": "Arrays in C/C++"
},
{
"code": null,
"e": 29012,
"s": 28993,
"text": "Inheritance in C++"
},
{
"code": null,
"e": 29037,
"s": 29012,
"text": "Reverse a string in Java"
}
] |
Order of Constructor/ Destructor Call in C++ | 19 Apr, 2022
Prerequisite: Constructors Whenever we create an object of a class, the default constructor of that class is invoked automatically to initialize the members of the class.
If we inherit a class from another class and create an object of the derived class, it is clear that the default constructor of the derived class will be invoked but before that the default constructor of all of the base classes will be invoke, i.e the order of invocation is that the base class’s default constructor will be invoked first and then the derived class’s default constructor will be invoked.
Why the base class’s constructor is called on creating an object of derived class?
To understand this you will have to recall your knowledge on inheritance. What happens when a class is inherited from other? The data members and member functions of base class comes automatically in derived class based on the access specifier but the definition of these members exists in base class only. So when we create an object of derived class, all of the members of derived class must be initialized but the inherited members in derived class can only be initialized by the base class’s constructor as the definition of these members exists in base class only. This is why the constructor of base class is called first to initialize all the inherited members.
C++
// C++ program to show the order of constructor call// in single inheritance #include <iostream>using namespace std; // base classclass Parent{ public: // base class constructor Parent() { cout << "Inside base class" << endl; }}; // sub classclass Child : public Parent{ public: //sub class constructor Child() { cout << "Inside sub class" << endl; }}; // main functionint main() { // creating object of sub class Child obj; return 0;}
Output:
Inside base class
Inside sub class
Order of constructor call for Multiple Inheritance
For multiple inheritance order of constructor call is, the base class’s constructors are called in the order of inheritance and then the derived class’s constructor.
C++
// C++ program to show the order of constructor calls// in Multiple Inheritance #include <iostream>using namespace std; // first base classclass Parent1{ public: // first base class's Constructor Parent1() { cout << "Inside first base class" << endl; }}; // second base classclass Parent2{ public: // second base class's Constructor Parent2() { cout << "Inside second base class" << endl; }}; // child class inherits Parent1 and Parent2class Child : public Parent1, public Parent2{ public: // child class's Constructor Child() { cout << "Inside child class" << endl; }}; // main functionint main() { // creating object of class Child Child obj1; return 0;}
Output:
Inside first base class
Inside second base class
Inside child class
Order of constructor and Destructor call for a given order of Inheritance
How to call the parameterized constructor of base class in derived class constructor?
To call the parameterized constructor of base class when derived class’s parameterized constructor is called, you have to explicitly specify the base class’s parameterized constructor in derived class as shown in below program:
C++
// C++ program to show how to call parameterized Constructor// of base class when derived class's Constructor is called #include <iostream>using namespace std; // base classclass Parent { int x; public: // base class's parameterized constructor Parent(int i) { x = i; cout << "Inside base class's parameterized " "constructor" << endl; }}; // sub classclass Child : public Parent {public: // sub class's parameterized constructor Child(int x): Parent(x) { cout << "Inside sub class's parameterized " "constructor" << endl; }}; // main functionint main(){ // creating object of class Child Child obj1(10); return 0;}
Output:
Inside base class's parameterized constructor
Inside sub class's parameterized constructor
Important Points:
Whenever the derived class’s default constructor is called, the base class’s default constructor is called automatically.
To call the parameterized constructor of base class inside the parameterized constructor of sub class, we have to mention it explicitly.
The parameterized constructor of base class cannot be called in default constructor of sub class, it should be called in the parameterized constructor of sub class.
Destructors in C++ are called in the opposite order of that of Constructors.This article is contributed by Abhirav Kariya and Harsh Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
sunnychaudharyvlsi
simmytarika5
gairolashivansh
chhabradhanvi
rkbhola5
cpp-inheritance
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Sorting a vector in C++
Polymorphism in C++
Friend class and function in C++
Pair in C++ Standard Template Library (STL)
std::string class in C++
Queue in C++ Standard Template Library (STL)
Unordered Sets in C++ Standard Template Library
std::find in C++
List in C++ Standard Template Library (STL)
Inline Functions in C++ | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n19 Apr, 2022"
},
{
"code": null,
"e": 224,
"s": 52,
"text": "Prerequisite: Constructors Whenever we create an object of a class, the default constructor of that class is invoked automatically to initialize the members of the class. "
},
{
"code": null,
"e": 630,
"s": 224,
"text": "If we inherit a class from another class and create an object of the derived class, it is clear that the default constructor of the derived class will be invoked but before that the default constructor of all of the base classes will be invoke, i.e the order of invocation is that the base class’s default constructor will be invoked first and then the derived class’s default constructor will be invoked."
},
{
"code": null,
"e": 713,
"s": 630,
"text": "Why the base class’s constructor is called on creating an object of derived class?"
},
{
"code": null,
"e": 1383,
"s": 713,
"text": "To understand this you will have to recall your knowledge on inheritance. What happens when a class is inherited from other? The data members and member functions of base class comes automatically in derived class based on the access specifier but the definition of these members exists in base class only. So when we create an object of derived class, all of the members of derived class must be initialized but the inherited members in derived class can only be initialized by the base class’s constructor as the definition of these members exists in base class only. This is why the constructor of base class is called first to initialize all the inherited members. "
},
{
"code": null,
"e": 1387,
"s": 1383,
"text": "C++"
},
{
"code": "// C++ program to show the order of constructor call// in single inheritance #include <iostream>using namespace std; // base classclass Parent{ public: // base class constructor Parent() { cout << \"Inside base class\" << endl; }}; // sub classclass Child : public Parent{ public: //sub class constructor Child() { cout << \"Inside sub class\" << endl; }}; // main functionint main() { // creating object of sub class Child obj; return 0;}",
"e": 1898,
"s": 1387,
"text": null
},
{
"code": null,
"e": 1908,
"s": 1898,
"text": "Output: "
},
{
"code": null,
"e": 1943,
"s": 1908,
"text": "Inside base class\nInside sub class"
},
{
"code": null,
"e": 1994,
"s": 1943,
"text": "Order of constructor call for Multiple Inheritance"
},
{
"code": null,
"e": 2161,
"s": 1994,
"text": "For multiple inheritance order of constructor call is, the base class’s constructors are called in the order of inheritance and then the derived class’s constructor. "
},
{
"code": null,
"e": 2165,
"s": 2161,
"text": "C++"
},
{
"code": "// C++ program to show the order of constructor calls// in Multiple Inheritance #include <iostream>using namespace std; // first base classclass Parent1{ public: // first base class's Constructor Parent1() { cout << \"Inside first base class\" << endl; }}; // second base classclass Parent2{ public: // second base class's Constructor Parent2() { cout << \"Inside second base class\" << endl; }}; // child class inherits Parent1 and Parent2class Child : public Parent1, public Parent2{ public: // child class's Constructor Child() { cout << \"Inside child class\" << endl; }}; // main functionint main() { // creating object of class Child Child obj1; return 0;}",
"e": 2926,
"s": 2165,
"text": null
},
{
"code": null,
"e": 2936,
"s": 2926,
"text": "Output: "
},
{
"code": null,
"e": 3004,
"s": 2936,
"text": "Inside first base class\nInside second base class\nInside child class"
},
{
"code": null,
"e": 3078,
"s": 3004,
"text": "Order of constructor and Destructor call for a given order of Inheritance"
},
{
"code": null,
"e": 3165,
"s": 3078,
"text": " How to call the parameterized constructor of base class in derived class constructor?"
},
{
"code": null,
"e": 3393,
"s": 3165,
"text": "To call the parameterized constructor of base class when derived class’s parameterized constructor is called, you have to explicitly specify the base class’s parameterized constructor in derived class as shown in below program:"
},
{
"code": null,
"e": 3397,
"s": 3393,
"text": "C++"
},
{
"code": "// C++ program to show how to call parameterized Constructor// of base class when derived class's Constructor is called #include <iostream>using namespace std; // base classclass Parent { int x; public: // base class's parameterized constructor Parent(int i) { x = i; cout << \"Inside base class's parameterized \" \"constructor\" << endl; }}; // sub classclass Child : public Parent {public: // sub class's parameterized constructor Child(int x): Parent(x) { cout << \"Inside sub class's parameterized \" \"constructor\" << endl; }}; // main functionint main(){ // creating object of class Child Child obj1(10); return 0;}",
"e": 4125,
"s": 3397,
"text": null
},
{
"code": null,
"e": 4134,
"s": 4125,
"text": "Output: "
},
{
"code": null,
"e": 4225,
"s": 4134,
"text": "Inside base class's parameterized constructor\nInside sub class's parameterized constructor"
},
{
"code": null,
"e": 4244,
"s": 4225,
"text": "Important Points: "
},
{
"code": null,
"e": 4366,
"s": 4244,
"text": "Whenever the derived class’s default constructor is called, the base class’s default constructor is called automatically."
},
{
"code": null,
"e": 4503,
"s": 4366,
"text": "To call the parameterized constructor of base class inside the parameterized constructor of sub class, we have to mention it explicitly."
},
{
"code": null,
"e": 4668,
"s": 4503,
"text": "The parameterized constructor of base class cannot be called in default constructor of sub class, it should be called in the parameterized constructor of sub class."
},
{
"code": null,
"e": 5184,
"s": 4668,
"text": "Destructors in C++ are called in the opposite order of that of Constructors.This article is contributed by Abhirav Kariya and Harsh Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 5203,
"s": 5184,
"text": "sunnychaudharyvlsi"
},
{
"code": null,
"e": 5216,
"s": 5203,
"text": "simmytarika5"
},
{
"code": null,
"e": 5232,
"s": 5216,
"text": "gairolashivansh"
},
{
"code": null,
"e": 5246,
"s": 5232,
"text": "chhabradhanvi"
},
{
"code": null,
"e": 5255,
"s": 5246,
"text": "rkbhola5"
},
{
"code": null,
"e": 5271,
"s": 5255,
"text": "cpp-inheritance"
},
{
"code": null,
"e": 5275,
"s": 5271,
"text": "C++"
},
{
"code": null,
"e": 5279,
"s": 5275,
"text": "CPP"
},
{
"code": null,
"e": 5377,
"s": 5279,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5401,
"s": 5377,
"text": "Sorting a vector in C++"
},
{
"code": null,
"e": 5421,
"s": 5401,
"text": "Polymorphism in C++"
},
{
"code": null,
"e": 5454,
"s": 5421,
"text": "Friend class and function in C++"
},
{
"code": null,
"e": 5498,
"s": 5454,
"text": "Pair in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 5523,
"s": 5498,
"text": "std::string class in C++"
},
{
"code": null,
"e": 5568,
"s": 5523,
"text": "Queue in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 5616,
"s": 5568,
"text": "Unordered Sets in C++ Standard Template Library"
},
{
"code": null,
"e": 5633,
"s": 5616,
"text": "std::find in C++"
},
{
"code": null,
"e": 5677,
"s": 5633,
"text": "List in C++ Standard Template Library (STL)"
}
] |
Drop shadow for PNG image using CSS | 22 Apr, 2019
There is a basic way to add shadow effect on images but that effect will behave like the image is square, so there is another way to do the shadow which is basically applied on PNG images. The normal shadow effect will always put a square image shadow for the image which can be squared or cannot be squared but the shadow will be always square. filter:drop-shadow(); and text-shadow(); property is more eye pleasant compare to box-shadow:() property.
Syntax:
filter: drop-shadow();
Example 1: This example uses filter: drop-shadow() property to add shadow effect on pngimage.
<!DOCTYPE html><html> <head> <!-- CSS style to add shadow --> <style> img { filter: drop-shadow(5px 5px 5px #222); width:200px; height:220px; } </style></head> <body style="text-align:center;"> <h3>Drop shadow effect on png</h3> <img src="https://media.geeksforgeeks.org/wp-content/uploads/20190405213436/left90.png" /></body> </html>
Output:
Example 2: This example differentiate between filter:drop-shadow();, text-shadow(); and box-shadow:(); property.
<!DOCTYPE html> <html> <head> <style> img { width:120px; } .Box-shadow { float:left; box-shadow:2px 2px 2px gray; } .Text-shadow { float:right; text-shadow:2px 2px 2px gray; } .Drop-shadow { float:right; } .Drop-shadow img { filter:drop-shadow(2px 2px 2px gray); } </style> </head> <body> <div class = "images"> <div class="Box-shadow"> <p>Box-shadow <img src="https://media.geeksforgeeks.org/wp-content/uploads/20190405213436/left90.png" /> </p> </div> <div class="Text-shadow"> <p>Text-shadow <img src="https://media.geeksforgeeks.org/wp-content/uploads/20190405213436/left90.png" /> </p> </div> <div class="Drop-shadow"> <p>Drop-shadow <img src="https://media.geeksforgeeks.org/wp-content/uploads/20190405213436/left90.png" /> </p> </div> </div> </body> </html>
Output:
CSS-Misc
Picked
CSS
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n22 Apr, 2019"
},
{
"code": null,
"e": 480,
"s": 28,
"text": "There is a basic way to add shadow effect on images but that effect will behave like the image is square, so there is another way to do the shadow which is basically applied on PNG images. The normal shadow effect will always put a square image shadow for the image which can be squared or cannot be squared but the shadow will be always square. filter:drop-shadow(); and text-shadow(); property is more eye pleasant compare to box-shadow:() property."
},
{
"code": null,
"e": 488,
"s": 480,
"text": "Syntax:"
},
{
"code": null,
"e": 511,
"s": 488,
"text": "filter: drop-shadow();"
},
{
"code": null,
"e": 605,
"s": 511,
"text": "Example 1: This example uses filter: drop-shadow() property to add shadow effect on pngimage."
},
{
"code": "<!DOCTYPE html><html> <head> <!-- CSS style to add shadow --> <style> img { filter: drop-shadow(5px 5px 5px #222); width:200px; height:220px; } </style></head> <body style=\"text-align:center;\"> <h3>Drop shadow effect on png</h3> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/20190405213436/left90.png\" /></body> </html> ",
"e": 1045,
"s": 605,
"text": null
},
{
"code": null,
"e": 1053,
"s": 1045,
"text": "Output:"
},
{
"code": null,
"e": 1166,
"s": 1053,
"text": "Example 2: This example differentiate between filter:drop-shadow();, text-shadow(); and box-shadow:(); property."
},
{
"code": "<!DOCTYPE html> <html> <head> <style> img { width:120px; } .Box-shadow { float:left; box-shadow:2px 2px 2px gray; } .Text-shadow { float:right; text-shadow:2px 2px 2px gray; } .Drop-shadow { float:right; } .Drop-shadow img { filter:drop-shadow(2px 2px 2px gray); } </style> </head> <body> <div class = \"images\"> <div class=\"Box-shadow\"> <p>Box-shadow <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/20190405213436/left90.png\" /> </p> </div> <div class=\"Text-shadow\"> <p>Text-shadow <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/20190405213436/left90.png\" /> </p> </div> <div class=\"Drop-shadow\"> <p>Drop-shadow <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/20190405213436/left90.png\" /> </p> </div> </div> </body> </html> ",
"e": 2342,
"s": 1166,
"text": null
},
{
"code": null,
"e": 2350,
"s": 2342,
"text": "Output:"
},
{
"code": null,
"e": 2359,
"s": 2350,
"text": "CSS-Misc"
},
{
"code": null,
"e": 2366,
"s": 2359,
"text": "Picked"
},
{
"code": null,
"e": 2370,
"s": 2366,
"text": "CSS"
},
{
"code": null,
"e": 2387,
"s": 2370,
"text": "Web Technologies"
},
{
"code": null,
"e": 2414,
"s": 2387,
"text": "Web technologies Questions"
}
] |
EnvironmentError Exception in Python | 21 Aug, 2020
EnvironmentError is the base class for errors that come from outside of Python (the operating system, file system, etc.). It is the parent class for IOError and OSError exceptions.
exception IOError – It is raised when an I/O operation (when a method of a file object ) fails. e.g “File not found” or “Disk Full”.exception OSError – It is raised when a function returns a system-related error.
exception IOError – It is raised when an I/O operation (when a method of a file object ) fails. e.g “File not found” or “Disk Full”.
exception OSError – It is raised when a function returns a system-related error.
Any example of an IOError or OSError should also be an example of Environment Error.
Example 1 :
Python3
# importing the moduleimport sys try: # an invalid path file = open("GeeksforGeeks.txt", 'r')except Exception as e: print(e) print(sys.exc_info()[0])
[Errno 2] No such file or directory: 'GeeksforGeeks.txt'
<class 'FileNotFoundError'>
Example 2 :
Python3
# importing the moduleimport osimport sys try: for i in range(7): print(i) print(os.ttyname(i))except Exception as e: print(e) print(sys.exc_info()[0])
0
[Errno 25] Inappropriate ioctl for device
<class 'OSError'>
Example 3 :
Python3
# importing the moduleimport sysimport os try: # an invalid path os.rmdir('GEEKS')except Exception as e: print(e) print(sys.exc_info()[0])
[Errno 2] No such file or directory: 'GEEKS'
<class 'FileNotFoundError'>
Python-exceptions
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
Iterate over a list in Python
Python Classes and Objects
Convert integer to string in Python
Python OOPs Concepts | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n21 Aug, 2020"
},
{
"code": null,
"e": 210,
"s": 28,
"text": "EnvironmentError is the base class for errors that come from outside of Python (the operating system, file system, etc.). It is the parent class for IOError and OSError exceptions. "
},
{
"code": null,
"e": 423,
"s": 210,
"text": "exception IOError – It is raised when an I/O operation (when a method of a file object ) fails. e.g “File not found” or “Disk Full”.exception OSError – It is raised when a function returns a system-related error."
},
{
"code": null,
"e": 556,
"s": 423,
"text": "exception IOError – It is raised when an I/O operation (when a method of a file object ) fails. e.g “File not found” or “Disk Full”."
},
{
"code": null,
"e": 637,
"s": 556,
"text": "exception OSError – It is raised when a function returns a system-related error."
},
{
"code": null,
"e": 722,
"s": 637,
"text": "Any example of an IOError or OSError should also be an example of Environment Error."
},
{
"code": null,
"e": 734,
"s": 722,
"text": "Example 1 :"
},
{
"code": null,
"e": 742,
"s": 734,
"text": "Python3"
},
{
"code": "# importing the moduleimport sys try: # an invalid path file = open(\"GeeksforGeeks.txt\", 'r')except Exception as e: print(e) print(sys.exc_info()[0])",
"e": 905,
"s": 742,
"text": null
},
{
"code": null,
"e": 991,
"s": 905,
"text": "[Errno 2] No such file or directory: 'GeeksforGeeks.txt'\n<class 'FileNotFoundError'>\n"
},
{
"code": null,
"e": 1003,
"s": 991,
"text": "Example 2 :"
},
{
"code": null,
"e": 1011,
"s": 1003,
"text": "Python3"
},
{
"code": "# importing the moduleimport osimport sys try: for i in range(7): print(i) print(os.ttyname(i))except Exception as e: print(e) print(sys.exc_info()[0])",
"e": 1187,
"s": 1011,
"text": null
},
{
"code": null,
"e": 1250,
"s": 1187,
"text": "0\n[Errno 25] Inappropriate ioctl for device\n<class 'OSError'>\n"
},
{
"code": null,
"e": 1262,
"s": 1250,
"text": "Example 3 :"
},
{
"code": null,
"e": 1270,
"s": 1262,
"text": "Python3"
},
{
"code": "# importing the moduleimport sysimport os try: # an invalid path os.rmdir('GEEKS')except Exception as e: print(e) print(sys.exc_info()[0])",
"e": 1422,
"s": 1270,
"text": null
},
{
"code": null,
"e": 1496,
"s": 1422,
"text": "[Errno 2] No such file or directory: 'GEEKS'\n<class 'FileNotFoundError'>\n"
},
{
"code": null,
"e": 1514,
"s": 1496,
"text": "Python-exceptions"
},
{
"code": null,
"e": 1521,
"s": 1514,
"text": "Python"
},
{
"code": null,
"e": 1619,
"s": 1521,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1637,
"s": 1619,
"text": "Python Dictionary"
},
{
"code": null,
"e": 1679,
"s": 1637,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 1701,
"s": 1679,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 1727,
"s": 1701,
"text": "Python String | replace()"
},
{
"code": null,
"e": 1759,
"s": 1727,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 1788,
"s": 1759,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 1818,
"s": 1788,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 1845,
"s": 1818,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 1881,
"s": 1845,
"text": "Convert integer to string in Python"
}
] |
Convert list to dataframe with specific column names in R | 12 Dec, 2021
A list contains different types of objects as their components. The components may belong to different data types or different dimensions. Vector can be useful components of a list and can be easily mapped as the rows or columns of a dataframe. Each column in the dataframe is referenced using a unique name, which can be either equivalent to the lists’ components names or assigned explicitly. In this article, we will discuss how to convert a list to dataframe with specific column names in R Programming Language.
do.call() method in R constructs and executes a function call from a name or a function and a list of arguments to be passed during the function call.
Syntax: do.call (fun , args)
Arguments :
fun – The function name to be executed
args – list of arguments to the function call
The rbind() method is used as the fun during this function call, which binds the passed elements of the list as rows of the dataframe. The rows are named based on the corresponding components of the list. Therefore, the argument of the do.call() method is the list object. The column names can be modified using the colnames() method in R, which assigns the column names to the assigned vector. In case, the length of the column names vector is smaller, NA is assigned as the respective column name. The column names are preserved in the original dataframe object. The number of columns in the dataframe is equivalent to the size of each component in the list.
do.call ( rbind , list)
The as.data.frame() method is used to map the object to a dataframe consisting of rows and columns.
R
# declaring a list objectlst_obj <- list(row1 = 1 : 5, row2 = LETTERS[1 : 5], row3 = FALSE) print ("Original List")print (lst_obj) # binding columns togetherdf <- do.call(rbind, lst_obj)print ("Original dataframe") # converting to a dataframedata_frame <- as.data.frame(df)print (data_frame) print ("Modified dataframe")colnames(data_frame) <- c( "ColA", "ColB", "ColC", "ColD", "ColE") print (data_frame)
Output:
[1] "Original List"
$col1
[1] 1 2 3 4 5
$col2
[1] "A" "B" "C" "D" "E"
$col3
[1] FALSE
[1] "Original dataframe"
V1 V2 V3 V4 V5
row1 1 2 3 4 5
row2 A B C D E
row3 FALSE FALSE FALSE FALSE FALSE
[1] "Modified dataframe"
ColA ColB ColC ColD ColE
row1 1 2 3 4 5
row2 A B C D E
row3 FALSE FALSE FALSE FALSE FALSE
Column names can also be assigned to the dataframe based on the naming of elements inside the list object. The naming is assigned even if any one of the vector components is assigned names.
R
# declaring a list objectlst_obj <- list("Row 1" = c(col1 = 'a', col2 = 'b', col3 = 'c'), "Row 2" = c(col1 = 'd', col2 = 'e', col3 = 'f')) print ("Original List")print (lst_obj) # binding columns togetherdf <- do.call(rbind, lst_obj)print ("dataframe") # converting to a dataframedata_frame <- as.data.frame(df)print (data_frame)
Output:
[1] "Original List"
$`Row 1`
col1 col2 col3
"a" "b" "c"
$`Row 2`
col1 col2 col3
"d" "e" "f"
[1] "dataframe"
col1 col2 col3
Row 1 a b c
Row 2 d e f
It can be done using the cbind() and do.call() method.
do.call ( cbind , list)
The following properties are maintained :
The names assigned to the components of the list become column names, which can be modified using the colnames() method.
The total number of rows is equivalent to the length of the components.
Row names are mapped to the row numbers.
Code:
R
# declaring a list objectlst_obj <- list(col1 = 1 : 5, col2 = LETTERS[1 : 5], col3 = FALSE) print ("Original List")print (lst_obj) # binding columns togetherdf <- do.call(cbind, lst_obj)print ("dataframe") # converting to a dataframeas.data.frame(df)
Output
[1] "Original List"
$col1
[1] 1 2 3 4 5
$col2
[1] "A" "B" "C" "D" "E"
$col3
[1] FALSE
[1] "dataframe"
col1 col2 col3
1 1 A FALSE
2 2 B FALSE
3 3 C FALSE
4 4 D FALSE
5 5 E FALSE
adnanirshad158
Picked
R DataFrame-Programs
R List-Programs
R-DataFrame
R-List
R Language
R Programs
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
How to Split Column Into Multiple Columns in R DataFrame?
How to filter R DataFrame by values in a column?
Replace Specific Characters in String in R
Merge DataFrames by Column Names in R
How to Sort a DataFrame in R ? | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n12 Dec, 2021"
},
{
"code": null,
"e": 545,
"s": 28,
"text": "A list contains different types of objects as their components. The components may belong to different data types or different dimensions. Vector can be useful components of a list and can be easily mapped as the rows or columns of a dataframe. Each column in the dataframe is referenced using a unique name, which can be either equivalent to the lists’ components names or assigned explicitly. In this article, we will discuss how to convert a list to dataframe with specific column names in R Programming Language."
},
{
"code": null,
"e": 697,
"s": 545,
"text": "do.call() method in R constructs and executes a function call from a name or a function and a list of arguments to be passed during the function call. "
},
{
"code": null,
"e": 726,
"s": 697,
"text": "Syntax: do.call (fun , args)"
},
{
"code": null,
"e": 739,
"s": 726,
"text": "Arguments : "
},
{
"code": null,
"e": 778,
"s": 739,
"text": "fun – The function name to be executed"
},
{
"code": null,
"e": 824,
"s": 778,
"text": "args – list of arguments to the function call"
},
{
"code": null,
"e": 1486,
"s": 824,
"text": "The rbind() method is used as the fun during this function call, which binds the passed elements of the list as rows of the dataframe. The rows are named based on the corresponding components of the list. Therefore, the argument of the do.call() method is the list object. The column names can be modified using the colnames() method in R, which assigns the column names to the assigned vector. In case, the length of the column names vector is smaller, NA is assigned as the respective column name. The column names are preserved in the original dataframe object. The number of columns in the dataframe is equivalent to the size of each component in the list. "
},
{
"code": null,
"e": 1510,
"s": 1486,
"text": "do.call ( rbind , list)"
},
{
"code": null,
"e": 1611,
"s": 1510,
"text": "The as.data.frame() method is used to map the object to a dataframe consisting of rows and columns. "
},
{
"code": null,
"e": 1613,
"s": 1611,
"text": "R"
},
{
"code": "# declaring a list objectlst_obj <- list(row1 = 1 : 5, row2 = LETTERS[1 : 5], row3 = FALSE) print (\"Original List\")print (lst_obj) # binding columns togetherdf <- do.call(rbind, lst_obj)print (\"Original dataframe\") # converting to a dataframedata_frame <- as.data.frame(df)print (data_frame) print (\"Modified dataframe\")colnames(data_frame) <- c( \"ColA\", \"ColB\", \"ColC\", \"ColD\", \"ColE\") print (data_frame)",
"e": 2050,
"s": 1613,
"text": null
},
{
"code": null,
"e": 2058,
"s": 2050,
"text": "Output:"
},
{
"code": null,
"e": 2476,
"s": 2058,
"text": "[1] \"Original List\"\n$col1\n[1] 1 2 3 4 5\n\n$col2\n[1] \"A\" \"B\" \"C\" \"D\" \"E\"\n\n$col3\n[1] FALSE\n[1] \"Original dataframe\"\n V1 V2 V3 V4 V5\nrow1 1 2 3 4 5\nrow2 A B C D E\nrow3 FALSE FALSE FALSE FALSE FALSE\n\n[1] \"Modified dataframe\"\n ColA ColB ColC ColD ColE\nrow1 1 2 3 4 5\nrow2 A B C D E\nrow3 FALSE FALSE FALSE FALSE FALSE"
},
{
"code": null,
"e": 2667,
"s": 2476,
"text": "Column names can also be assigned to the dataframe based on the naming of elements inside the list object. The naming is assigned even if any one of the vector components is assigned names. "
},
{
"code": null,
"e": 2669,
"s": 2667,
"text": "R"
},
{
"code": "# declaring a list objectlst_obj <- list(\"Row 1\" = c(col1 = 'a', col2 = 'b', col3 = 'c'), \"Row 2\" = c(col1 = 'd', col2 = 'e', col3 = 'f')) print (\"Original List\")print (lst_obj) # binding columns togetherdf <- do.call(rbind, lst_obj)print (\"dataframe\") # converting to a dataframedata_frame <- as.data.frame(df)print (data_frame)",
"e": 3068,
"s": 2669,
"text": null
},
{
"code": null,
"e": 3076,
"s": 3068,
"text": "Output:"
},
{
"code": null,
"e": 3252,
"s": 3076,
"text": "[1] \"Original List\"\n$`Row 1`\ncol1 col2 col3\n\"a\" \"b\" \"c\"\n\n$`Row 2`\ncol1 col2 col3\n\"d\" \"e\" \"f\"\n\n[1] \"dataframe\"\n col1 col2 col3\nRow 1 a b c\nRow 2 d e f"
},
{
"code": null,
"e": 3307,
"s": 3252,
"text": "It can be done using the cbind() and do.call() method."
},
{
"code": null,
"e": 3331,
"s": 3307,
"text": "do.call ( cbind , list)"
},
{
"code": null,
"e": 3374,
"s": 3331,
"text": "The following properties are maintained : "
},
{
"code": null,
"e": 3495,
"s": 3374,
"text": "The names assigned to the components of the list become column names, which can be modified using the colnames() method."
},
{
"code": null,
"e": 3567,
"s": 3495,
"text": "The total number of rows is equivalent to the length of the components."
},
{
"code": null,
"e": 3608,
"s": 3567,
"text": "Row names are mapped to the row numbers."
},
{
"code": null,
"e": 3614,
"s": 3608,
"text": "Code:"
},
{
"code": null,
"e": 3616,
"s": 3614,
"text": "R"
},
{
"code": "# declaring a list objectlst_obj <- list(col1 = 1 : 5, col2 = LETTERS[1 : 5], col3 = FALSE) print (\"Original List\")print (lst_obj) # binding columns togetherdf <- do.call(cbind, lst_obj)print (\"dataframe\") # converting to a dataframeas.data.frame(df)",
"e": 3897,
"s": 3616,
"text": null
},
{
"code": null,
"e": 3904,
"s": 3897,
"text": "Output"
},
{
"code": null,
"e": 4117,
"s": 3904,
"text": "[1] \"Original List\"\n$col1\n[1] 1 2 3 4 5\n\n$col2\n[1] \"A\" \"B\" \"C\" \"D\" \"E\"\n\n$col3\n[1] FALSE\n\n\n[1] \"dataframe\"\n col1 col2 col3\n1 1 A FALSE\n2 2 B FALSE\n3 3 C FALSE\n4 4 D FALSE\n5 5 E FALSE"
},
{
"code": null,
"e": 4132,
"s": 4117,
"text": "adnanirshad158"
},
{
"code": null,
"e": 4139,
"s": 4132,
"text": "Picked"
},
{
"code": null,
"e": 4160,
"s": 4139,
"text": "R DataFrame-Programs"
},
{
"code": null,
"e": 4176,
"s": 4160,
"text": "R List-Programs"
},
{
"code": null,
"e": 4188,
"s": 4176,
"text": "R-DataFrame"
},
{
"code": null,
"e": 4195,
"s": 4188,
"text": "R-List"
},
{
"code": null,
"e": 4206,
"s": 4195,
"text": "R Language"
},
{
"code": null,
"e": 4217,
"s": 4206,
"text": "R Programs"
},
{
"code": null,
"e": 4315,
"s": 4217,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4367,
"s": 4315,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 4425,
"s": 4367,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 4460,
"s": 4425,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 4498,
"s": 4460,
"text": "How to Change Axis Scales in R Plots?"
},
{
"code": null,
"e": 4515,
"s": 4498,
"text": "R - if statement"
},
{
"code": null,
"e": 4573,
"s": 4515,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 4622,
"s": 4573,
"text": "How to filter R DataFrame by values in a column?"
},
{
"code": null,
"e": 4665,
"s": 4622,
"text": "Replace Specific Characters in String in R"
},
{
"code": null,
"e": 4703,
"s": 4665,
"text": "Merge DataFrames by Column Names in R"
}
] |
EasyMock - createMock | So far, we've used annotations to create mocks. EasyMock provides various methods to create mock objects. EasyMock.createMock() creates mocks without bothering about the order of method calls that the mock is going to make in due course of its action.
calcService = EasyMock.createMock(CalculatorService.class);
Step 1: Create an interface called CalculatorService to provide mathematical functions
File: CalculatorService.java
public interface CalculatorService {
public double add(double input1, double input2);
public double subtract(double input1, double input2);
public double multiply(double input1, double input2);
public double divide(double input1, double input2);
}
Step 2: Create a JAVA class to represent MathApplication
File: MathApplication.java
public class MathApplication {
private CalculatorService calcService;
public void setCalculatorService(CalculatorService calcService){
this.calcService = calcService;
}
public double add(double input1, double input2){
return calcService.add(input1, input2);
}
public double subtract(double input1, double input2){
return calcService.subtract(input1, input2);
}
public double multiply(double input1, double input2){
return calcService.multiply(input1, input2);
}
public double divide(double input1, double input2){
return calcService.divide(input1, input2);
}
}
Step 3: Test the MathApplication class
Let's test the MathApplication class, by injecting in it a mock of calculatorService. Mock will be created by EasyMock.
Here we've added two mock method calls, add() and subtract(), to the mock object via expect(). However during testing, we've called subtract() before calling add(). When we create a mock object using EasyMock.createMock(), the order of execution of the method does not matter.
File: MathApplicationTester.java
import org.easymock.EasyMock;
import org.easymock.EasyMockRunner;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
@RunWith(EasyMockRunner.class)
public class MathApplicationTester {
private MathApplication mathApplication;
private CalculatorService calcService;
@Before
public void setUp(){
mathApplication = new MathApplication();
calcService = EasyMock.createMock(CalculatorService.class);
mathApplication.setCalculatorService(calcService);
}
@Test
public void testAddAndSubtract(){
//add the behavior to add numbers
EasyMock.expect(calcService.add(20.0,10.0)).andReturn(30.0);
//subtract the behavior to subtract numbers
EasyMock.expect(calcService.subtract(20.0,10.0)).andReturn(10.0);
//activate the mock
EasyMock.replay(calcService);
//test the subtract functionality
Assert.assertEquals(mathApplication.subtract(20.0, 10.0),10.0,0);
//test the add functionality
Assert.assertEquals(mathApplication.add(20.0, 10.0),30.0,0);
//verify call to calcService is made or not
EasyMock.verify(calcService);
}
}
Step 4: Execute test cases
Create a java class file named TestRunner in C:\> EasyMock_WORKSPACE to execute Test case(s).
File: TestRunner.java
import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;
public class TestRunner {
public static void main(String[] args) {
Result result = JUnitCore.runClasses(MathApplicationTester.class);
for (Failure failure : result.getFailures()) {
System.out.println(failure.toString());
}
System.out.println(result.wasSuccessful());
}
}
Step 5: Verify the Result
Compile the classes using javac compiler as follows −
C:\EasyMock_WORKSPACE>javac MathApplicationTester.java
Now run the Test Runner to see the result −
C:\EasyMock_WORKSPACE>java TestRunner
Verify the output. | [
{
"code": null,
"e": 2295,
"s": 2043,
"text": "So far, we've used annotations to create mocks. EasyMock provides various methods to create mock objects. EasyMock.createMock() creates mocks without bothering about the order of method calls that the mock is going to make in due course of its action."
},
{
"code": null,
"e": 2356,
"s": 2295,
"text": "calcService = EasyMock.createMock(CalculatorService.class);\n"
},
{
"code": null,
"e": 2443,
"s": 2356,
"text": "Step 1: Create an interface called CalculatorService to provide mathematical functions"
},
{
"code": null,
"e": 2472,
"s": 2443,
"text": "File: CalculatorService.java"
},
{
"code": null,
"e": 2732,
"s": 2472,
"text": "public interface CalculatorService {\n public double add(double input1, double input2);\n public double subtract(double input1, double input2);\n public double multiply(double input1, double input2);\n public double divide(double input1, double input2);\n}"
},
{
"code": null,
"e": 2789,
"s": 2732,
"text": "Step 2: Create a JAVA class to represent MathApplication"
},
{
"code": null,
"e": 2816,
"s": 2789,
"text": "File: MathApplication.java"
},
{
"code": null,
"e": 3442,
"s": 2816,
"text": "public class MathApplication {\n private CalculatorService calcService;\n public void setCalculatorService(CalculatorService calcService){\n this.calcService = calcService;\n }\n public double add(double input1, double input2){\n return calcService.add(input1, input2);\t\t\n }\n public double subtract(double input1, double input2){\n return calcService.subtract(input1, input2);\n }\n public double multiply(double input1, double input2){\n return calcService.multiply(input1, input2);\n }\n public double divide(double input1, double input2){\n return calcService.divide(input1, input2);\n }\n}"
},
{
"code": null,
"e": 3481,
"s": 3442,
"text": "Step 3: Test the MathApplication class"
},
{
"code": null,
"e": 3601,
"s": 3481,
"text": "Let's test the MathApplication class, by injecting in it a mock of calculatorService. Mock will be created by EasyMock."
},
{
"code": null,
"e": 3878,
"s": 3601,
"text": "Here we've added two mock method calls, add() and subtract(), to the mock object via expect(). However during testing, we've called subtract() before calling add(). When we create a mock object using EasyMock.createMock(), the order of execution of the method does not matter."
},
{
"code": null,
"e": 3911,
"s": 3878,
"text": "File: MathApplicationTester.java"
},
{
"code": null,
"e": 5127,
"s": 3911,
"text": "import org.easymock.EasyMock;\nimport org.easymock.EasyMockRunner;\nimport org.junit.Assert;\nimport org.junit.Before;\nimport org.junit.Test;\nimport org.junit.runner.RunWith;\n\n@RunWith(EasyMockRunner.class)\npublic class MathApplicationTester {\n private MathApplication mathApplication;\n private CalculatorService calcService;\n \n @Before\n public void setUp(){\n mathApplication = new MathApplication();\n calcService = EasyMock.createMock(CalculatorService.class);\n mathApplication.setCalculatorService(calcService);\n }\n @Test\n public void testAddAndSubtract(){\n //add the behavior to add numbers\n EasyMock.expect(calcService.add(20.0,10.0)).andReturn(30.0);\n \n //subtract the behavior to subtract numbers\n EasyMock.expect(calcService.subtract(20.0,10.0)).andReturn(10.0);\n \n //activate the mock\n EasyMock.replay(calcService);\t\n\t\n //test the subtract functionality\n Assert.assertEquals(mathApplication.subtract(20.0, 10.0),10.0,0);\n \n //test the add functionality\n Assert.assertEquals(mathApplication.add(20.0, 10.0),30.0,0);\n \n //verify call to calcService is made or not\n EasyMock.verify(calcService);\n }\n}"
},
{
"code": null,
"e": 5154,
"s": 5127,
"text": "Step 4: Execute test cases"
},
{
"code": null,
"e": 5248,
"s": 5154,
"text": "Create a java class file named TestRunner in C:\\> EasyMock_WORKSPACE to execute Test case(s)."
},
{
"code": null,
"e": 5270,
"s": 5248,
"text": "File: TestRunner.java"
},
{
"code": null,
"e": 5697,
"s": 5270,
"text": "import org.junit.runner.JUnitCore;\nimport org.junit.runner.Result;\nimport org.junit.runner.notification.Failure;\n\npublic class TestRunner {\n public static void main(String[] args) {\n Result result = JUnitCore.runClasses(MathApplicationTester.class);\n for (Failure failure : result.getFailures()) {\n System.out.println(failure.toString());\n }\n System.out.println(result.wasSuccessful());\n }\n} \t"
},
{
"code": null,
"e": 5723,
"s": 5697,
"text": "Step 5: Verify the Result"
},
{
"code": null,
"e": 5777,
"s": 5723,
"text": "Compile the classes using javac compiler as follows −"
},
{
"code": null,
"e": 5833,
"s": 5777,
"text": "C:\\EasyMock_WORKSPACE>javac MathApplicationTester.java\n"
},
{
"code": null,
"e": 5877,
"s": 5833,
"text": "Now run the Test Runner to see the result −"
},
{
"code": null,
"e": 5916,
"s": 5877,
"text": "C:\\EasyMock_WORKSPACE>java TestRunner\n"
}
] |
Ways to increment Iterator from inside the For loop in Python | 12 Feb, 2021
For loops, in general, are used for sequential traversal. It falls under the category of definite iteration. Definite iterations mean the number of repetitions is specified explicitly in advance. But have you ever wondered, what happens, if you try to increment the value of the iterator from inside the for loop. Let’s see with the help of the below example.Example:
Python3
lis = [1, 2, 3, 4, 5] for i in range(len(lis)): print(lis[i]) i += 2
Output:
1
2
3
4
5
The above example shows this odd behavior of the for loop because the for loop in Python is not a convention C style for loop, i.e., for (i=0; i<n; i++) rather it is a for in loop which is similar to for each loop in other languages. However, there are few methods by which we can control the iteration in the for loop. Some of them are –
Using While loop: We can’t directly increase/decrease the iteration value inside the body of the for loop, we can use while loop for this purpose.Example:
Python
# Using while loop lis = [1, 2, 3, 4, 5]i = 0 while(i < len(lis)): print(lis[i], end = " ") # Changing the value of # i inside the loop will # change it's value at the # time of checking condition i += 2
Output:
1 3 5
Using another variable: We can use another variable for the same purpose because after every iteration the value of loop variable is re-initialized.Example:
Python
# Using for loop lis = [1, 2, 3, 4, 5] i = 0 for j in range(len(lis)): # Terminating condition for i if(i >= len(lis)): break print(lis[i], end = " ") i += 2
Output:
1 3 5
Using Range Function: We can use the range function as the third parameter of this function specifies the step.Note: For more information, refer to Python range() Function.Example:
Python3
# Using for loop lis = [1, 2, 3, 4, 5] for i in range(0, len(lis), 2): print(lis[i], end = " ")
Output:
1 3 5
arorakashish0911
python-basics
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
Convert integer to string in Python | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n12 Feb, 2021"
},
{
"code": null,
"e": 422,
"s": 53,
"text": "For loops, in general, are used for sequential traversal. It falls under the category of definite iteration. Definite iterations mean the number of repetitions is specified explicitly in advance. But have you ever wondered, what happens, if you try to increment the value of the iterator from inside the for loop. Let’s see with the help of the below example.Example: "
},
{
"code": null,
"e": 430,
"s": 422,
"text": "Python3"
},
{
"code": "lis = [1, 2, 3, 4, 5] for i in range(len(lis)): print(lis[i]) i += 2",
"e": 510,
"s": 430,
"text": null
},
{
"code": null,
"e": 519,
"s": 510,
"text": "Output: "
},
{
"code": null,
"e": 529,
"s": 519,
"text": "1\n2\n3\n4\n5"
},
{
"code": null,
"e": 869,
"s": 529,
"text": "The above example shows this odd behavior of the for loop because the for loop in Python is not a convention C style for loop, i.e., for (i=0; i<n; i++) rather it is a for in loop which is similar to for each loop in other languages. However, there are few methods by which we can control the iteration in the for loop. Some of them are – "
},
{
"code": null,
"e": 1025,
"s": 869,
"text": "Using While loop: We can’t directly increase/decrease the iteration value inside the body of the for loop, we can use while loop for this purpose.Example: "
},
{
"code": null,
"e": 1032,
"s": 1025,
"text": "Python"
},
{
"code": "# Using while loop lis = [1, 2, 3, 4, 5]i = 0 while(i < len(lis)): print(lis[i], end = \" \") # Changing the value of # i inside the loop will # change it's value at the # time of checking condition i += 2 ",
"e": 1263,
"s": 1032,
"text": null
},
{
"code": null,
"e": 1273,
"s": 1263,
"text": "Output: "
},
{
"code": null,
"e": 1279,
"s": 1273,
"text": "1 3 5"
},
{
"code": null,
"e": 1440,
"s": 1281,
"text": "Using another variable: We can use another variable for the same purpose because after every iteration the value of loop variable is re-initialized.Example: "
},
{
"code": null,
"e": 1447,
"s": 1440,
"text": "Python"
},
{
"code": "# Using for loop lis = [1, 2, 3, 4, 5] i = 0 for j in range(len(lis)): # Terminating condition for i if(i >= len(lis)): break print(lis[i], end = \" \") i += 2",
"e": 1633,
"s": 1447,
"text": null
},
{
"code": null,
"e": 1643,
"s": 1633,
"text": "Output: "
},
{
"code": null,
"e": 1649,
"s": 1643,
"text": "1 3 5"
},
{
"code": null,
"e": 1833,
"s": 1651,
"text": "Using Range Function: We can use the range function as the third parameter of this function specifies the step.Note: For more information, refer to Python range() Function.Example: "
},
{
"code": null,
"e": 1841,
"s": 1833,
"text": "Python3"
},
{
"code": "# Using for loop lis = [1, 2, 3, 4, 5] for i in range(0, len(lis), 2): print(lis[i], end = \" \") ",
"e": 1948,
"s": 1841,
"text": null
},
{
"code": null,
"e": 1957,
"s": 1948,
"text": "Output: "
},
{
"code": null,
"e": 1963,
"s": 1957,
"text": "1 3 5"
},
{
"code": null,
"e": 1984,
"s": 1967,
"text": "arorakashish0911"
},
{
"code": null,
"e": 1998,
"s": 1984,
"text": "python-basics"
},
{
"code": null,
"e": 2005,
"s": 1998,
"text": "Python"
},
{
"code": null,
"e": 2103,
"s": 2005,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2121,
"s": 2103,
"text": "Python Dictionary"
},
{
"code": null,
"e": 2163,
"s": 2121,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 2185,
"s": 2163,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 2220,
"s": 2185,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 2246,
"s": 2220,
"text": "Python String | replace()"
},
{
"code": null,
"e": 2278,
"s": 2246,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2307,
"s": 2278,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 2334,
"s": 2307,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2364,
"s": 2334,
"text": "Iterate over a list in Python"
}
] |
How to implement stack using priority queue or heap? | 08 Feb, 2018
How to Implement stack using a priority queue(using min heap)?.
Asked In: Microsoft, Adobe.
Solution:
In priority queue, we assign priority to the elements that are being pushed. A stack requires elements to be processed in Last in First Out manner. The idea is to associate a count that determines when it was pushed. This count works as a key for the priority queue.
So the implementation of stack uses a priority queue of pairs, with the first element serving as the key.
pair <int, int> (key, value)
See Below Image to understand Better
Below is C++ implementation of the idea.
// C++ program to implement a stack using// Priority queue(min heap)#include<bits/stdc++.h>using namespace std; typedef pair<int, int> pi; // User defined stack classclass Stack{ // cnt is used to keep track of the number of //elements in the stack and also serves as key //for the priority queue. int cnt; priority_queue<pair<int, int> > pq;public: Stack():cnt(0){} void push(int n); void pop(); int top(); bool isEmpty();}; // push function increases cnt by 1 and// inserts this cnt with the original value. void Stack::push(int n){ cnt++; pq.push(pi(cnt, n));} // pops element and reduces count.void Stack::pop(){ if(pq.empty()){ cout<<"Nothing to pop!!!";} cnt--; pq.pop();} // returns the top element in the stack using// cnt as key to determine top(highest priority),// default comparator for pairs works fine in this case int Stack::top(){ pi temp=pq.top(); return temp.second;} // return true if stack is emptybool Stack::isEmpty(){ return pq.empty();} // Driver codeint main(){ Stack* s=new Stack(); s->push(1); s->push(2); s->push(3); while(!s->isEmpty()){ cout<<s->top()<<endl; s->pop(); }}
Output:
3
2
1
Now, as we can see this implementation takes O(log n) time for both push and pop operations. This can be slightly optimized by using fibonacci heap implementation of priority queue which would give us O(1) time complexity for push operation, but pop still requires O(log n) time.
This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
priority-queue
Heap
Stack
Stack
Heap
priority-queue
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to Data Structures
Find k numbers with most occurrences in the given array
Difference between Min Heap and Max Heap
Priority queue of pairs in C++ (Ordered by first)
K-th Largest Sum Contiguous Subarray
Stack Data Structure (Introduction and Program)
Stack in Python
Stack Class in Java
Check for Balanced Brackets in an expression (well-formedness) using Stack
Introduction to Data Structures | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n08 Feb, 2018"
},
{
"code": null,
"e": 118,
"s": 54,
"text": "How to Implement stack using a priority queue(using min heap)?."
},
{
"code": null,
"e": 146,
"s": 118,
"text": "Asked In: Microsoft, Adobe."
},
{
"code": null,
"e": 156,
"s": 146,
"text": "Solution:"
},
{
"code": null,
"e": 423,
"s": 156,
"text": "In priority queue, we assign priority to the elements that are being pushed. A stack requires elements to be processed in Last in First Out manner. The idea is to associate a count that determines when it was pushed. This count works as a key for the priority queue."
},
{
"code": null,
"e": 529,
"s": 423,
"text": "So the implementation of stack uses a priority queue of pairs, with the first element serving as the key."
},
{
"code": "pair <int, int> (key, value)",
"e": 558,
"s": 529,
"text": null
},
{
"code": null,
"e": 595,
"s": 558,
"text": "See Below Image to understand Better"
},
{
"code": null,
"e": 636,
"s": 595,
"text": "Below is C++ implementation of the idea."
},
{
"code": "// C++ program to implement a stack using// Priority queue(min heap)#include<bits/stdc++.h>using namespace std; typedef pair<int, int> pi; // User defined stack classclass Stack{ // cnt is used to keep track of the number of //elements in the stack and also serves as key //for the priority queue. int cnt; priority_queue<pair<int, int> > pq;public: Stack():cnt(0){} void push(int n); void pop(); int top(); bool isEmpty();}; // push function increases cnt by 1 and// inserts this cnt with the original value. void Stack::push(int n){ cnt++; pq.push(pi(cnt, n));} // pops element and reduces count.void Stack::pop(){ if(pq.empty()){ cout<<\"Nothing to pop!!!\";} cnt--; pq.pop();} // returns the top element in the stack using// cnt as key to determine top(highest priority),// default comparator for pairs works fine in this case int Stack::top(){ pi temp=pq.top(); return temp.second;} // return true if stack is emptybool Stack::isEmpty(){ return pq.empty();} // Driver codeint main(){ Stack* s=new Stack(); s->push(1); s->push(2); s->push(3); while(!s->isEmpty()){ cout<<s->top()<<endl; s->pop(); }}",
"e": 1837,
"s": 636,
"text": null
},
{
"code": null,
"e": 1845,
"s": 1837,
"text": "Output:"
},
{
"code": null,
"e": 1855,
"s": 1845,
"text": " 3\n 2\n 1\n"
},
{
"code": null,
"e": 2135,
"s": 1855,
"text": "Now, as we can see this implementation takes O(log n) time for both push and pop operations. This can be slightly optimized by using fibonacci heap implementation of priority queue which would give us O(1) time complexity for push operation, but pop still requires O(log n) time."
},
{
"code": null,
"e": 2441,
"s": 2135,
"text": "This article is contributed by Mr. Somesh Awasthi. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 2566,
"s": 2441,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 2581,
"s": 2566,
"text": "priority-queue"
},
{
"code": null,
"e": 2586,
"s": 2581,
"text": "Heap"
},
{
"code": null,
"e": 2592,
"s": 2586,
"text": "Stack"
},
{
"code": null,
"e": 2598,
"s": 2592,
"text": "Stack"
},
{
"code": null,
"e": 2603,
"s": 2598,
"text": "Heap"
},
{
"code": null,
"e": 2618,
"s": 2603,
"text": "priority-queue"
},
{
"code": null,
"e": 2716,
"s": 2618,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2748,
"s": 2716,
"text": "Introduction to Data Structures"
},
{
"code": null,
"e": 2804,
"s": 2748,
"text": "Find k numbers with most occurrences in the given array"
},
{
"code": null,
"e": 2845,
"s": 2804,
"text": "Difference between Min Heap and Max Heap"
},
{
"code": null,
"e": 2895,
"s": 2845,
"text": "Priority queue of pairs in C++ (Ordered by first)"
},
{
"code": null,
"e": 2932,
"s": 2895,
"text": "K-th Largest Sum Contiguous Subarray"
},
{
"code": null,
"e": 2980,
"s": 2932,
"text": "Stack Data Structure (Introduction and Program)"
},
{
"code": null,
"e": 2996,
"s": 2980,
"text": "Stack in Python"
},
{
"code": null,
"e": 3016,
"s": 2996,
"text": "Stack Class in Java"
},
{
"code": null,
"e": 3091,
"s": 3016,
"text": "Check for Balanced Brackets in an expression (well-formedness) using Stack"
}
] |
Maximum number of Unique integers in Sub-Array of given size | 26 Oct, 2021
Given an array of N integers and a number M. The task is to find out the maximum number of unique integers among all possible contiguous subarrays of size M.
Examples:
Input : arr[] = {5, 3, 5, 2, 3, 2}, M = 3 Output : 3 Explanation: In the sample test case, there are 4 subarrays of size 3. s1 = (5, 3, 5)- Has 2 unique numbers. s2 = (3, 5, 2)- Has 3 unique numbers. s3 = (5, 2, 3)- Has 3 unique numbers. s4 = (2, 3, 2)- Has 2 unique numbers. In these subarrays, there are 2, 3, 3, 2 unique numbers, respectively. The maximum amount of unique numbers among all possible contiguous subarrays is 3.
Input : arr[] = {5, 5, 5, 5, 5, 5}, M = 3 Output : 1
Naive Approach:
Generate all subarrays of size M.Count unique number for each subarray. Check whether it is greater than the previous maximum unique number or not, if yes, replace it with the previous maximum unique number.Continue until we generate all possible subarrays.
Generate all subarrays of size M.
Count unique number for each subarray. Check whether it is greater than the previous maximum unique number or not, if yes, replace it with the previous maximum unique number.
Check whether it is greater than the previous maximum unique number or not, if yes, replace it with the previous maximum unique number.
Continue until we generate all possible subarrays.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// A C++ programme to find maximum distinct elements// in a subarray of size k#include<bits/stdc++.h>using namespace std;//Function to find maximum unique element in//a subarray of size kint maxUniqueNum(int a[],int N,int M){ int maxUnique=0; //search every subarray of size k //and find how many unique element present for(int i=0;i<=N-M;i++) { //create an empty set to store the unique elements set<int> s; for(int j=0;j<M;j++) { //insert all elements //duplicate elements are not stored in set s.insert(a[i+j]); } //update the maxUnique if(s.size()>maxUnique) { maxUnique=s.size(); } } return maxUnique;} int main(){ int arr[] = {5, 3, 5, 2, 3, 2}; int M=3,N=sizeof(arr)/sizeof(arr[0]); cout<<maxUniqueNum(arr,N,M)<<endl; }
// Java Program to find maximum number of// Unique integers in Sub-Array// of given size import java.util.*;class GFG { // Function to find maximum number of // Unique integers in Sub-Array // of given size public static int maxUniqueNum(int arr[], int N, int M) { int maxUnique = 0; // Generate all subarrays of size M for (int i = 0; i <= N - M; i++) { int currentUnique = 0; HashMap<Integer, Integer> map = new HashMap<Integer, Integer>(); for (int k = i; k < i + M; k++) { // if the key is new to the map, // push the key in map and increment // count for unique number if (!map.containsKey(arr[k])) { map.put(arr[i], 1); currentUnique++; } } if (currentUnique > maxUnique) maxUnique = currentUnique; } return maxUnique; } // Driver Code public static void main(String[] args) { int[] arr = { 5, 3, 5, 2, 3, 2 }; int N = 6; int M = 3; System.out.println(maxUniqueNum(arr, N, M)); }}
# A python3 programme to find maximum# distinct elements in a subarray of size k # Function to find maximum unique# element in a subarray of size kdef maxUniqueNum(a, N, M): maxUnique = 0 # search every subarray of size k and # find how many unique element present for i in range(N - M + 1): # create an empty set to store # the unique elements s = set() for j in range(M): # insert all elements # duplicate elements are not # stored in set s.add(a[i + j]) # update the maxUnique if(len(s) > maxUnique): maxUnique = len(s) return maxUnique # Driver Code if __name__ == '__main__': arr = [5, 3, 5, 2, 3, 2] M = 3 N = len(arr) print(maxUniqueNum(arr, N, M)) # This code is contributed by# Sanjit_Prasad
// C# Program to find maximum number of// Unique integers in Sub-Array// of given sizeusing System;using System.Collections.Generic; class GFG{ // Function to find maximum number of // Unique integers in Sub-Array // of given size public static int maxUniqueNum(int []arr, int N, int M) { int maxUnique = 0; // Generate all subarrays of size M for (int i = 0; i <= N - M; i++) { int currentUnique = 0; Dictionary<int,int> map = new Dictionary<int,int>(); for (int k = i; k < i + M; k++) { // if the key is new to the map, // push the key in map and increment // count for unique number if (!map.ContainsKey(arr[k])) { map.Remove(arr[i]); map.Add(arr[i], 1); currentUnique++; continue; } } if (currentUnique > maxUnique) maxUnique = currentUnique; } return maxUnique; } // Driver Code public static void Main(String[] args) { int[] arr = { 5, 3, 5, 2, 3, 2 }; int N = 6; int M = 3; Console.WriteLine(maxUniqueNum(arr, N, M)); }} // This code has been contributed by 29AjayKumar
<script> // JavaScript Program to find maximum number of// Unique integers in Sub-Array// of given size // Function to find maximum number of // Unique integers in Sub-Array // of given sizefunction maxUniqueNum(arr,N,M){ let maxUnique = 0; // Generate all subarrays of size M for (let i = 0; i <= N - M; i++) { let currentUnique = 0; let map = new Map(); for (let k = i; k < i + M; k++) { // if the key is new to the map, // push the key in map and increment // count for unique number if (!map.has(arr[k])) { map.set(arr[i], 1); currentUnique++; } } if (currentUnique > maxUnique) maxUnique = currentUnique; } return maxUnique;} // Driver Codelet arr=[5, 3, 5, 2, 3, 2 ];let N = 6;let M = 3;document.write(maxUniqueNum(arr, N, M)); // This code is contributed by unknown2108 </script>
3
Time Complexity : O(M * N) Auxiliary Space : O(M)
Efficient Solution An efficient solution is to use window sliding technique. We maintain a single hash table for storing unique elements of every window. 1) Store counts of first M elements in a hash map. 2) Traverse from (M+1)-th element and for every element, add it to hash map and remove first element of previous window.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// An efficient Approach to count distinct elements in// every window of size k#include<bits/stdc++.h>using namespace std;//Function to find maximum unique element in//a subarray of size kint max_U_element(int a[],int N,int M){ //map to store the unique elements and their size map<int,int> hash; //Number of unique elements in an window int dist_count=0; int res=0; //Maximum unique element in a window //store all elements till size k i.e. //storing first window for(int i=0;i<M;i++) { //found an unique element if(hash.find(a[i])==hash.end()) { hash.insert(make_pair(a[i],1)); dist_count++; } //an Duplicate element inserting else { //Update the size of that element hash[a[i]]++; } } res=dist_count; //Traverse till the end of array for(int i=M;i<N;i++) { //Remove first element from map if(hash[a[i-M]]==1) { //when element present only one time // in window so delete this hash.erase(a[i-M]); dist_count--; } else { //when multiple time element has occurred // in window so decrease size by one hash[a[i-M]]--; } //Add new element to map //If element is unique to map //increment count if(hash.find(a[i])==hash.end()) { hash.insert(make_pair(a[i],1)); dist_count++; } //Duplicate element found //update the size of that element else { hash[a[i]]++; } //Update the res res=max(res,dist_count); } return res;}//Driver codeint main(){ int arr[] = {1, 2, 1, 3, 4, 2, 3}; int M=4,N=sizeof(arr)/sizeof(arr[0]); cout<<max_U_element(arr,N,M)<<endl; }
// An efficient Java program to count distinct elements in// every window of size kimport java.util.HashMap; class maxUniqueNumWindow { static int maxUniqueNum(int arr[], int M) { // Creates an empty hashMap hM HashMap<Integer, Integer> hM = new HashMap<Integer, Integer>(); // initialize distinct element count for // current window int dist_count = 0; // Traverse the first window and store count // of every element in hash map for (int i = 0; i < M; i++) { if (hM.get(arr[i]) == null) { hM.put(arr[i], 1); dist_count++; } else { int count = hM.get(arr[i]); hM.put(arr[i], count + 1); } } int res = dist_count; // Traverse through the remaining array for (int i = M; i < arr.length; i++) { // Remove first element of previous window // If there was only one occurrence, then // reduce distinct count. if (hM.get(arr[i - M]) == 1) { hM.remove(arr[i - M]); dist_count--; } else // reduce count of the removed element { int count = hM.get(arr[i - M]); hM.put(arr[i - M], count - 1); } // Add new element of current window // If this element appears first time, // increment distinct element count if (hM.get(arr[i]) == null) { hM.put(arr[i], 1); dist_count++; } else // Increment distinct element count { int count = hM.get(arr[i]); hM.put(arr[i], count + 1); } res = Math.max(res, dist_count); } return res; } // Driver method public static void main(String arg[]) { int arr[] = { 1, 2, 1, 3, 4, 2, 3 }; int M = 4; System.out.println(maxUniqueNum(arr, M)); }}
# An efficient Approach to count distinct elements in# every window of size k# Function to find maximum unique element in# a subarray of size kdef max_U_element(a, N, M): # map to store the unique elements and their size hsh = dict() # Number of unique elements in an window dist_count = 0 res = 0 # Maximum unique element in a window # store all elements till size k i.e. # storing first window for i in range(M): # found an unique element if(arr[i] not in hsh.keys()): hsh[a[i]] = 1 dist_count += 1 # an Duplicate element inserting else: # Update the size of that element hsh[a[i]] += 1 res = dist_count # Traverse till the end of array for i in range(M, N): # Remove first element from map if(a[i - M] in hsh.keys() and hsh[a[i - M]] == 1): # when element present only one time # in window so delete this del hsh[a[i-M]] dist_count -= 1 else: # when multiple time element has occurred # in window so decrease size by one hsh[a[i - M]] -= 1 # Add new element to map # If element is unique to map # increment count if(a[i] not in hsh.keys()): hsh[a[i]] = 1 dist_count += 1 # Duplicate element found # update the size of that element else: hsh[a[i]] += 1 # Update the res res = max(res, dist_count) return res # Driver codearr = [1, 2, 1, 3, 4, 2, 3]M = 4N = len(arr)print(max_U_element(arr, N, M)) # This code is contributed by mohit kumar
// An efficient C# program to// count distinct elements in// every window of size kusing System;using System.Collections.Generic; class GFG{ static int maxUniqueNum(int []arr, int M) { // Creates an empty hashMap hM Dictionary<int, int> hM = new Dictionary<int, int>(); // initialize distinct element count // for current window int dist_count = 0; // Traverse the first window and store // count of every element in hash map for (int i = 0; i < M; i++) { if (!hM.ContainsKey(arr[i])) { hM.Add(arr[i], 1); dist_count++; } else { int count = hM[arr[i]]; hM[arr[i]] = count + 1; } } int res = dist_count; // Traverse through the remaining array for (int i = M; i < arr.Length; i++) { // Remove first element of previous window // If there was only one occurrence, then // reduce distinct count. if (hM[arr[i - M]] == 1) { hM.Remove(arr[i - M]); dist_count--; } // reduce count of the removed element else { int count = hM[arr[i - M]]; hM[arr[i - M]] = count - 1; } // Add new element of current window // If this element appears first time, // increment distinct element count if (!hM.ContainsKey(arr[i])) { hM.Add(arr[i], 1); dist_count++; } // Increment distinct element count else { int count = hM[arr[i]]; hM[arr[i]] = count + 1; } res = Math.Max(res, dist_count); } return res; } // Driver Code public static void Main(String []arg) { int []arr = { 1, 2, 1, 3, 4, 2, 3 }; int M = 4; Console.WriteLine(maxUniqueNum(arr, M)); }} // This code is contributed by 29AjayKumar
<script> // An efficient JavaScript program to// count distinct elements in// every window of size k function maxUniqueNum(arr,m){ // Creates an empty hashMap hM let hM = new Map(); // initialize distinct element count for // current window let dist_count = 0; // Traverse the first window and store count // of every element in hash map for (let i = 0; i < M; i++) { if (hM.get(arr[i]) == null) { hM.set(arr[i], 1); dist_count++; } else { let count = hM.get(arr[i]); hM.set(arr[i], count + 1); } } let res = dist_count; // Traverse through the remaining array for (let i = M; i < arr.length; i++) { // Remove first element of previous window // If there was only one occurrence, then // reduce distinct count. if (hM.get(arr[i - M]) == 1) { hM.delete(arr[i - M]); dist_count--; } else // reduce count of the removed element { let count = hM.get(arr[i - M]); hM.set(arr[i - M], count - 1); } // Add new element of current window // If this element appears first time, // increment distinct element count if (hM.get(arr[i]) == null) { hM.set(arr[i], 1); dist_count++; } else // Increment distinct element count { let count = hM.get(arr[i]); hM.set(arr[i], count + 1); } res = Math.max(res, dist_count); } return res;} // Driver methodlet arr=[1, 2, 1, 3, 4, 2, 3];let M = 4;document.write(maxUniqueNum(arr, M)); // This code is contributed by patel2127 </script>
4
Time Complexity : O(N) Auxiliary Space : O(M)
Milan1999
Sanjit_Prasad
29AjayKumar
mohit kumar 29
nidhi_biet
Snehil Sharma
patel2127
unknown2108
arorakashish0911
ashutoshsinghgeeksforgeeks
Java-Array-Programs
Java-HashMap
sliding-window
Algorithms
Java
sliding-window
Java
Algorithms
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n26 Oct, 2021"
},
{
"code": null,
"e": 212,
"s": 54,
"text": "Given an array of N integers and a number M. The task is to find out the maximum number of unique integers among all possible contiguous subarrays of size M."
},
{
"code": null,
"e": 223,
"s": 212,
"text": "Examples: "
},
{
"code": null,
"e": 653,
"s": 223,
"text": "Input : arr[] = {5, 3, 5, 2, 3, 2}, M = 3 Output : 3 Explanation: In the sample test case, there are 4 subarrays of size 3. s1 = (5, 3, 5)- Has 2 unique numbers. s2 = (3, 5, 2)- Has 3 unique numbers. s3 = (5, 2, 3)- Has 3 unique numbers. s4 = (2, 3, 2)- Has 2 unique numbers. In these subarrays, there are 2, 3, 3, 2 unique numbers, respectively. The maximum amount of unique numbers among all possible contiguous subarrays is 3."
},
{
"code": null,
"e": 708,
"s": 653,
"text": "Input : arr[] = {5, 5, 5, 5, 5, 5}, M = 3 Output : 1 "
},
{
"code": null,
"e": 725,
"s": 708,
"text": "Naive Approach: "
},
{
"code": null,
"e": 983,
"s": 725,
"text": "Generate all subarrays of size M.Count unique number for each subarray. Check whether it is greater than the previous maximum unique number or not, if yes, replace it with the previous maximum unique number.Continue until we generate all possible subarrays."
},
{
"code": null,
"e": 1017,
"s": 983,
"text": "Generate all subarrays of size M."
},
{
"code": null,
"e": 1192,
"s": 1017,
"text": "Count unique number for each subarray. Check whether it is greater than the previous maximum unique number or not, if yes, replace it with the previous maximum unique number."
},
{
"code": null,
"e": 1328,
"s": 1192,
"text": "Check whether it is greater than the previous maximum unique number or not, if yes, replace it with the previous maximum unique number."
},
{
"code": null,
"e": 1379,
"s": 1328,
"text": "Continue until we generate all possible subarrays."
},
{
"code": null,
"e": 1431,
"s": 1379,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 1435,
"s": 1431,
"text": "C++"
},
{
"code": null,
"e": 1440,
"s": 1435,
"text": "Java"
},
{
"code": null,
"e": 1448,
"s": 1440,
"text": "Python3"
},
{
"code": null,
"e": 1451,
"s": 1448,
"text": "C#"
},
{
"code": null,
"e": 1462,
"s": 1451,
"text": "Javascript"
},
{
"code": "// A C++ programme to find maximum distinct elements// in a subarray of size k#include<bits/stdc++.h>using namespace std;//Function to find maximum unique element in//a subarray of size kint maxUniqueNum(int a[],int N,int M){ int maxUnique=0; //search every subarray of size k //and find how many unique element present for(int i=0;i<=N-M;i++) { //create an empty set to store the unique elements set<int> s; for(int j=0;j<M;j++) { //insert all elements //duplicate elements are not stored in set s.insert(a[i+j]); } //update the maxUnique if(s.size()>maxUnique) { maxUnique=s.size(); } } return maxUnique;} int main(){ int arr[] = {5, 3, 5, 2, 3, 2}; int M=3,N=sizeof(arr)/sizeof(arr[0]); cout<<maxUniqueNum(arr,N,M)<<endl; }",
"e": 2334,
"s": 1462,
"text": null
},
{
"code": "// Java Program to find maximum number of// Unique integers in Sub-Array// of given size import java.util.*;class GFG { // Function to find maximum number of // Unique integers in Sub-Array // of given size public static int maxUniqueNum(int arr[], int N, int M) { int maxUnique = 0; // Generate all subarrays of size M for (int i = 0; i <= N - M; i++) { int currentUnique = 0; HashMap<Integer, Integer> map = new HashMap<Integer, Integer>(); for (int k = i; k < i + M; k++) { // if the key is new to the map, // push the key in map and increment // count for unique number if (!map.containsKey(arr[k])) { map.put(arr[i], 1); currentUnique++; } } if (currentUnique > maxUnique) maxUnique = currentUnique; } return maxUnique; } // Driver Code public static void main(String[] args) { int[] arr = { 5, 3, 5, 2, 3, 2 }; int N = 6; int M = 3; System.out.println(maxUniqueNum(arr, N, M)); }}",
"e": 3541,
"s": 2334,
"text": null
},
{
"code": "# A python3 programme to find maximum# distinct elements in a subarray of size k # Function to find maximum unique# element in a subarray of size kdef maxUniqueNum(a, N, M): maxUnique = 0 # search every subarray of size k and # find how many unique element present for i in range(N - M + 1): # create an empty set to store # the unique elements s = set() for j in range(M): # insert all elements # duplicate elements are not # stored in set s.add(a[i + j]) # update the maxUnique if(len(s) > maxUnique): maxUnique = len(s) return maxUnique # Driver Code if __name__ == '__main__': arr = [5, 3, 5, 2, 3, 2] M = 3 N = len(arr) print(maxUniqueNum(arr, N, M)) # This code is contributed by# Sanjit_Prasad",
"e": 4397,
"s": 3541,
"text": null
},
{
"code": "// C# Program to find maximum number of// Unique integers in Sub-Array// of given sizeusing System;using System.Collections.Generic; class GFG{ // Function to find maximum number of // Unique integers in Sub-Array // of given size public static int maxUniqueNum(int []arr, int N, int M) { int maxUnique = 0; // Generate all subarrays of size M for (int i = 0; i <= N - M; i++) { int currentUnique = 0; Dictionary<int,int> map = new Dictionary<int,int>(); for (int k = i; k < i + M; k++) { // if the key is new to the map, // push the key in map and increment // count for unique number if (!map.ContainsKey(arr[k])) { map.Remove(arr[i]); map.Add(arr[i], 1); currentUnique++; continue; } } if (currentUnique > maxUnique) maxUnique = currentUnique; } return maxUnique; } // Driver Code public static void Main(String[] args) { int[] arr = { 5, 3, 5, 2, 3, 2 }; int N = 6; int M = 3; Console.WriteLine(maxUniqueNum(arr, N, M)); }} // This code has been contributed by 29AjayKumar",
"e": 5758,
"s": 4397,
"text": null
},
{
"code": "<script> // JavaScript Program to find maximum number of// Unique integers in Sub-Array// of given size // Function to find maximum number of // Unique integers in Sub-Array // of given sizefunction maxUniqueNum(arr,N,M){ let maxUnique = 0; // Generate all subarrays of size M for (let i = 0; i <= N - M; i++) { let currentUnique = 0; let map = new Map(); for (let k = i; k < i + M; k++) { // if the key is new to the map, // push the key in map and increment // count for unique number if (!map.has(arr[k])) { map.set(arr[i], 1); currentUnique++; } } if (currentUnique > maxUnique) maxUnique = currentUnique; } return maxUnique;} // Driver Codelet arr=[5, 3, 5, 2, 3, 2 ];let N = 6;let M = 3;document.write(maxUniqueNum(arr, N, M)); // This code is contributed by unknown2108 </script>",
"e": 6782,
"s": 5758,
"text": null
},
{
"code": null,
"e": 6784,
"s": 6782,
"text": "3"
},
{
"code": null,
"e": 6836,
"s": 6786,
"text": "Time Complexity : O(M * N) Auxiliary Space : O(M)"
},
{
"code": null,
"e": 7162,
"s": 6836,
"text": "Efficient Solution An efficient solution is to use window sliding technique. We maintain a single hash table for storing unique elements of every window. 1) Store counts of first M elements in a hash map. 2) Traverse from (M+1)-th element and for every element, add it to hash map and remove first element of previous window."
},
{
"code": null,
"e": 7213,
"s": 7162,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 7217,
"s": 7213,
"text": "C++"
},
{
"code": null,
"e": 7222,
"s": 7217,
"text": "Java"
},
{
"code": null,
"e": 7230,
"s": 7222,
"text": "Python3"
},
{
"code": null,
"e": 7233,
"s": 7230,
"text": "C#"
},
{
"code": null,
"e": 7244,
"s": 7233,
"text": "Javascript"
},
{
"code": "// An efficient Approach to count distinct elements in// every window of size k#include<bits/stdc++.h>using namespace std;//Function to find maximum unique element in//a subarray of size kint max_U_element(int a[],int N,int M){ //map to store the unique elements and their size map<int,int> hash; //Number of unique elements in an window int dist_count=0; int res=0; //Maximum unique element in a window //store all elements till size k i.e. //storing first window for(int i=0;i<M;i++) { //found an unique element if(hash.find(a[i])==hash.end()) { hash.insert(make_pair(a[i],1)); dist_count++; } //an Duplicate element inserting else { //Update the size of that element hash[a[i]]++; } } res=dist_count; //Traverse till the end of array for(int i=M;i<N;i++) { //Remove first element from map if(hash[a[i-M]]==1) { //when element present only one time // in window so delete this hash.erase(a[i-M]); dist_count--; } else { //when multiple time element has occurred // in window so decrease size by one hash[a[i-M]]--; } //Add new element to map //If element is unique to map //increment count if(hash.find(a[i])==hash.end()) { hash.insert(make_pair(a[i],1)); dist_count++; } //Duplicate element found //update the size of that element else { hash[a[i]]++; } //Update the res res=max(res,dist_count); } return res;}//Driver codeint main(){ int arr[] = {1, 2, 1, 3, 4, 2, 3}; int M=4,N=sizeof(arr)/sizeof(arr[0]); cout<<max_U_element(arr,N,M)<<endl; }",
"e": 9108,
"s": 7244,
"text": null
},
{
"code": "// An efficient Java program to count distinct elements in// every window of size kimport java.util.HashMap; class maxUniqueNumWindow { static int maxUniqueNum(int arr[], int M) { // Creates an empty hashMap hM HashMap<Integer, Integer> hM = new HashMap<Integer, Integer>(); // initialize distinct element count for // current window int dist_count = 0; // Traverse the first window and store count // of every element in hash map for (int i = 0; i < M; i++) { if (hM.get(arr[i]) == null) { hM.put(arr[i], 1); dist_count++; } else { int count = hM.get(arr[i]); hM.put(arr[i], count + 1); } } int res = dist_count; // Traverse through the remaining array for (int i = M; i < arr.length; i++) { // Remove first element of previous window // If there was only one occurrence, then // reduce distinct count. if (hM.get(arr[i - M]) == 1) { hM.remove(arr[i - M]); dist_count--; } else // reduce count of the removed element { int count = hM.get(arr[i - M]); hM.put(arr[i - M], count - 1); } // Add new element of current window // If this element appears first time, // increment distinct element count if (hM.get(arr[i]) == null) { hM.put(arr[i], 1); dist_count++; } else // Increment distinct element count { int count = hM.get(arr[i]); hM.put(arr[i], count + 1); } res = Math.max(res, dist_count); } return res; } // Driver method public static void main(String arg[]) { int arr[] = { 1, 2, 1, 3, 4, 2, 3 }; int M = 4; System.out.println(maxUniqueNum(arr, M)); }}",
"e": 11131,
"s": 9108,
"text": null
},
{
"code": "# An efficient Approach to count distinct elements in# every window of size k# Function to find maximum unique element in# a subarray of size kdef max_U_element(a, N, M): # map to store the unique elements and their size hsh = dict() # Number of unique elements in an window dist_count = 0 res = 0 # Maximum unique element in a window # store all elements till size k i.e. # storing first window for i in range(M): # found an unique element if(arr[i] not in hsh.keys()): hsh[a[i]] = 1 dist_count += 1 # an Duplicate element inserting else: # Update the size of that element hsh[a[i]] += 1 res = dist_count # Traverse till the end of array for i in range(M, N): # Remove first element from map if(a[i - M] in hsh.keys() and hsh[a[i - M]] == 1): # when element present only one time # in window so delete this del hsh[a[i-M]] dist_count -= 1 else: # when multiple time element has occurred # in window so decrease size by one hsh[a[i - M]] -= 1 # Add new element to map # If element is unique to map # increment count if(a[i] not in hsh.keys()): hsh[a[i]] = 1 dist_count += 1 # Duplicate element found # update the size of that element else: hsh[a[i]] += 1 # Update the res res = max(res, dist_count) return res # Driver codearr = [1, 2, 1, 3, 4, 2, 3]M = 4N = len(arr)print(max_U_element(arr, N, M)) # This code is contributed by mohit kumar",
"e": 12886,
"s": 11131,
"text": null
},
{
"code": "// An efficient C# program to// count distinct elements in// every window of size kusing System;using System.Collections.Generic; class GFG{ static int maxUniqueNum(int []arr, int M) { // Creates an empty hashMap hM Dictionary<int, int> hM = new Dictionary<int, int>(); // initialize distinct element count // for current window int dist_count = 0; // Traverse the first window and store // count of every element in hash map for (int i = 0; i < M; i++) { if (!hM.ContainsKey(arr[i])) { hM.Add(arr[i], 1); dist_count++; } else { int count = hM[arr[i]]; hM[arr[i]] = count + 1; } } int res = dist_count; // Traverse through the remaining array for (int i = M; i < arr.Length; i++) { // Remove first element of previous window // If there was only one occurrence, then // reduce distinct count. if (hM[arr[i - M]] == 1) { hM.Remove(arr[i - M]); dist_count--; } // reduce count of the removed element else { int count = hM[arr[i - M]]; hM[arr[i - M]] = count - 1; } // Add new element of current window // If this element appears first time, // increment distinct element count if (!hM.ContainsKey(arr[i])) { hM.Add(arr[i], 1); dist_count++; } // Increment distinct element count else { int count = hM[arr[i]]; hM[arr[i]] = count + 1; } res = Math.Max(res, dist_count); } return res; } // Driver Code public static void Main(String []arg) { int []arr = { 1, 2, 1, 3, 4, 2, 3 }; int M = 4; Console.WriteLine(maxUniqueNum(arr, M)); }} // This code is contributed by 29AjayKumar",
"e": 15072,
"s": 12886,
"text": null
},
{
"code": "<script> // An efficient JavaScript program to// count distinct elements in// every window of size k function maxUniqueNum(arr,m){ // Creates an empty hashMap hM let hM = new Map(); // initialize distinct element count for // current window let dist_count = 0; // Traverse the first window and store count // of every element in hash map for (let i = 0; i < M; i++) { if (hM.get(arr[i]) == null) { hM.set(arr[i], 1); dist_count++; } else { let count = hM.get(arr[i]); hM.set(arr[i], count + 1); } } let res = dist_count; // Traverse through the remaining array for (let i = M; i < arr.length; i++) { // Remove first element of previous window // If there was only one occurrence, then // reduce distinct count. if (hM.get(arr[i - M]) == 1) { hM.delete(arr[i - M]); dist_count--; } else // reduce count of the removed element { let count = hM.get(arr[i - M]); hM.set(arr[i - M], count - 1); } // Add new element of current window // If this element appears first time, // increment distinct element count if (hM.get(arr[i]) == null) { hM.set(arr[i], 1); dist_count++; } else // Increment distinct element count { let count = hM.get(arr[i]); hM.set(arr[i], count + 1); } res = Math.max(res, dist_count); } return res;} // Driver methodlet arr=[1, 2, 1, 3, 4, 2, 3];let M = 4;document.write(maxUniqueNum(arr, M)); // This code is contributed by patel2127 </script>",
"e": 16959,
"s": 15072,
"text": null
},
{
"code": null,
"e": 16961,
"s": 16959,
"text": "4"
},
{
"code": null,
"e": 17010,
"s": 16963,
"text": "Time Complexity : O(N) Auxiliary Space : O(M) "
},
{
"code": null,
"e": 17020,
"s": 17010,
"text": "Milan1999"
},
{
"code": null,
"e": 17034,
"s": 17020,
"text": "Sanjit_Prasad"
},
{
"code": null,
"e": 17046,
"s": 17034,
"text": "29AjayKumar"
},
{
"code": null,
"e": 17061,
"s": 17046,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 17072,
"s": 17061,
"text": "nidhi_biet"
},
{
"code": null,
"e": 17086,
"s": 17072,
"text": "Snehil Sharma"
},
{
"code": null,
"e": 17096,
"s": 17086,
"text": "patel2127"
},
{
"code": null,
"e": 17108,
"s": 17096,
"text": "unknown2108"
},
{
"code": null,
"e": 17125,
"s": 17108,
"text": "arorakashish0911"
},
{
"code": null,
"e": 17152,
"s": 17125,
"text": "ashutoshsinghgeeksforgeeks"
},
{
"code": null,
"e": 17172,
"s": 17152,
"text": "Java-Array-Programs"
},
{
"code": null,
"e": 17185,
"s": 17172,
"text": "Java-HashMap"
},
{
"code": null,
"e": 17200,
"s": 17185,
"text": "sliding-window"
},
{
"code": null,
"e": 17211,
"s": 17200,
"text": "Algorithms"
},
{
"code": null,
"e": 17216,
"s": 17211,
"text": "Java"
},
{
"code": null,
"e": 17231,
"s": 17216,
"text": "sliding-window"
},
{
"code": null,
"e": 17236,
"s": 17231,
"text": "Java"
},
{
"code": null,
"e": 17247,
"s": 17236,
"text": "Algorithms"
}
] |
Externalizable interface in Java | 11 Jan, 2022
Externalization serves the purpose of custom Serialization, where we can decide what to store in stream.Externalizable interface present in java.io, is used for Externalization which extends Serializable interface. It consist of two methods which we have to override to write/read object into/from stream which are-
// to read object from stream
void readExternal(ObjectInput in)
// to write object into stream
void writeExternal(ObjectOutput out)
Key differences between Serializable and Externalizable
Implementation : Unlike Serializable interface which will serialize the variables in object with just by implementing interface, here we have to explicitly mention what fields or variables you want to serialize.
Methods : Serializable is marker interface without any methods. Externalizable interface contains two methods: writeExternal() and readExternal().
Process: Default Serialization process will take place for classes implementing Serializable interface. Programmer defined Serialization process for classes implementing Externalizable interface.
Backward Compatibility and Control: If you have to support multiple versions, you can have full control with Externalizable interface. You can support different versions of your object. If you implement Externalizable, it’s your responsibility to serialize super class.
public No-arg constructor: Serializable uses reflection to construct object and does not require no arg constructor. But Externalizable requires public no-arg constructor.
Below is the example for Externalization-
Java
// Java program to demonstrate working of Externalization// interfaceimport java.io.*;class Car implements Externalizable { static int age; String name; int year; public Car() { System.out.println("Default Constructor called"); } Car(String n, int y) { this.name = n; this.year = y; age = 10; } @Override public void writeExternal(ObjectOutput out) throws IOException { out.writeObject(name); out.writeInt(age); out.writeInt(year); } @Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { name = (String)in.readObject(); year = in.readInt(); age = in.readInt(); } @Override public String toString() { return ("Name: " + name + "\n" + "Year: " + year + "\n" + "Age: " + age); }} public class ExternExample { public static void main(String[] args) { Car car = new Car("Shubham", 1995); Car newcar = null; // Serialize the car try { FileOutputStream fo = new FileOutputStream("gfg.txt"); ObjectOutputStream so = new ObjectOutputStream(fo); so.writeObject(car); so.flush(); } catch (Exception e) { System.out.println(e); } // Deserialization the car try { FileInputStream fi = new FileInputStream("gfg.txt"); ObjectInputStream si = new ObjectInputStream(fi); newcar = (Car)si.readObject(); } catch (Exception e) { System.out.println(e); } System.out.println("The original car is:\n" + car); System.out.println("The new car is:\n" + newcar); }}
Output:
Default Constructor called
The original car is:
Name: Shubham
Year: 1995
Age: 10
The new car is:
Name: Shubham
Year: 1995
Age: 10
In the example, the class Car has two methods- writeExternal and readExternal. So, when we write “Car” object to OutputStream, writeExternal method is called to persist the data. The same applies to the readExternal method. When an Externalizable object is reconstructed, an instance is created first using the public no-argument constructor, then the readExternal method is called. So, it is mandatory to provide a no-argument constructor. When an object implements Serializable interface, is serialized or deserialized, no constructor of object is called and hence any initialization which is implemented in constructor can’t be done.
This article is contributed by Shubham Juneja. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Rishav Shandilya 2
vineethmaller
adnanirshad158
java-interfaces
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
How to iterate any Map in Java
Interfaces in Java
HashMap in Java with Examples
ArrayList in Java
Collections in Java
Singleton Class in Java
Multidimensional Arrays in Java
Stack Class in Java
Set in Java | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n11 Jan, 2022"
},
{
"code": null,
"e": 370,
"s": 52,
"text": "Externalization serves the purpose of custom Serialization, where we can decide what to store in stream.Externalizable interface present in java.io, is used for Externalization which extends Serializable interface. It consist of two methods which we have to override to write/read object into/from stream which are- "
},
{
"code": null,
"e": 505,
"s": 370,
"text": "// to read object from stream\nvoid readExternal(ObjectInput in) \n\n// to write object into stream\nvoid writeExternal(ObjectOutput out) "
},
{
"code": null,
"e": 563,
"s": 505,
"text": "Key differences between Serializable and Externalizable "
},
{
"code": null,
"e": 775,
"s": 563,
"text": "Implementation : Unlike Serializable interface which will serialize the variables in object with just by implementing interface, here we have to explicitly mention what fields or variables you want to serialize."
},
{
"code": null,
"e": 922,
"s": 775,
"text": "Methods : Serializable is marker interface without any methods. Externalizable interface contains two methods: writeExternal() and readExternal()."
},
{
"code": null,
"e": 1118,
"s": 922,
"text": "Process: Default Serialization process will take place for classes implementing Serializable interface. Programmer defined Serialization process for classes implementing Externalizable interface."
},
{
"code": null,
"e": 1388,
"s": 1118,
"text": "Backward Compatibility and Control: If you have to support multiple versions, you can have full control with Externalizable interface. You can support different versions of your object. If you implement Externalizable, it’s your responsibility to serialize super class."
},
{
"code": null,
"e": 1560,
"s": 1388,
"text": "public No-arg constructor: Serializable uses reflection to construct object and does not require no arg constructor. But Externalizable requires public no-arg constructor."
},
{
"code": null,
"e": 1603,
"s": 1560,
"text": "Below is the example for Externalization- "
},
{
"code": null,
"e": 1608,
"s": 1603,
"text": "Java"
},
{
"code": "// Java program to demonstrate working of Externalization// interfaceimport java.io.*;class Car implements Externalizable { static int age; String name; int year; public Car() { System.out.println(\"Default Constructor called\"); } Car(String n, int y) { this.name = n; this.year = y; age = 10; } @Override public void writeExternal(ObjectOutput out) throws IOException { out.writeObject(name); out.writeInt(age); out.writeInt(year); } @Override public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { name = (String)in.readObject(); year = in.readInt(); age = in.readInt(); } @Override public String toString() { return (\"Name: \" + name + \"\\n\" + \"Year: \" + year + \"\\n\" + \"Age: \" + age); }} public class ExternExample { public static void main(String[] args) { Car car = new Car(\"Shubham\", 1995); Car newcar = null; // Serialize the car try { FileOutputStream fo = new FileOutputStream(\"gfg.txt\"); ObjectOutputStream so = new ObjectOutputStream(fo); so.writeObject(car); so.flush(); } catch (Exception e) { System.out.println(e); } // Deserialization the car try { FileInputStream fi = new FileInputStream(\"gfg.txt\"); ObjectInputStream si = new ObjectInputStream(fi); newcar = (Car)si.readObject(); } catch (Exception e) { System.out.println(e); } System.out.println(\"The original car is:\\n\" + car); System.out.println(\"The new car is:\\n\" + newcar); }}",
"e": 3444,
"s": 1608,
"text": null
},
{
"code": null,
"e": 3454,
"s": 3444,
"text": "Output: "
},
{
"code": null,
"e": 3584,
"s": 3454,
"text": "Default Constructor called\nThe original car is:\nName: Shubham\nYear: 1995\nAge: 10\nThe new car is:\nName: Shubham\nYear: 1995\nAge: 10"
},
{
"code": null,
"e": 4222,
"s": 3584,
"text": "In the example, the class Car has two methods- writeExternal and readExternal. So, when we write “Car” object to OutputStream, writeExternal method is called to persist the data. The same applies to the readExternal method. When an Externalizable object is reconstructed, an instance is created first using the public no-argument constructor, then the readExternal method is called. So, it is mandatory to provide a no-argument constructor. When an object implements Serializable interface, is serialized or deserialized, no constructor of object is called and hence any initialization which is implemented in constructor can’t be done. "
},
{
"code": null,
"e": 4645,
"s": 4222,
"text": "This article is contributed by Shubham Juneja. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 4664,
"s": 4645,
"text": "Rishav Shandilya 2"
},
{
"code": null,
"e": 4678,
"s": 4664,
"text": "vineethmaller"
},
{
"code": null,
"e": 4693,
"s": 4678,
"text": "adnanirshad158"
},
{
"code": null,
"e": 4709,
"s": 4693,
"text": "java-interfaces"
},
{
"code": null,
"e": 4714,
"s": 4709,
"text": "Java"
},
{
"code": null,
"e": 4719,
"s": 4714,
"text": "Java"
},
{
"code": null,
"e": 4817,
"s": 4719,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4868,
"s": 4817,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 4899,
"s": 4868,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 4918,
"s": 4899,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 4948,
"s": 4918,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 4966,
"s": 4948,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 4986,
"s": 4966,
"text": "Collections in Java"
},
{
"code": null,
"e": 5010,
"s": 4986,
"text": "Singleton Class in Java"
},
{
"code": null,
"e": 5042,
"s": 5010,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 5062,
"s": 5042,
"text": "Stack Class in Java"
}
] |
How to select the Date Picker In Selenium WebDriver? | We can select the date picker in Selenium. It is slightly difficult to handle calendar controls as the day, month and year selection can be represented via different UI.
Sometimes they are represented by the dropdown or by forward and backward controls. Let us select the date picker as shown below.
From Date −
To Date −
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 org.openqa.selenium.support.ui.Select;
public class DatePicker{
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver",
"C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
String frdate = "20";
String todate = "26";
driver.get("https://jqueryui.com/datepicker/#date−range");
// wait of 4 seconds
driver.manage().timeouts().implicitlyWait(4, TimeUnit.SECONDS);
// maximize browser
driver.manage().window().maximize();
// identify frame and switch to it
WebElement e = driver.findElement(By.xpath("//*[@id='content']/iframe"));
driver.switchTo().frame(e);
// choose from date
driver.findElement(By.xpath("//input[@id='from']")).click();
Thread.sleep(1000);
// choose month from dropdown
WebElement m = driver
.findElement(By.xpath("//div/select[@class='ui− datepicker−month']"));
Select s = new Select(m);
s.selectByVisibleText("Jan");
Thread.sleep(1000);
// select day
driver.findElement(By.xpath("//td[not(contains(@class,'ui−datepicker− month'))]/a[text()='"+frdate+"']")).click();
Thread.sleep(1000);
// choose to date
driver.findElement(By.xpath("//input[@id='to']")).click();
Thread.sleep(1000);
// choose month from dropdown
WebElement n = driver
.findElement(By.xpath("//div/select[@class='ui− datepicker−month']"));
Select sel = new Select(n);
sel.selectByVisibleText("Feb");
Thread.sleep(1000);
// select day
driver.findElement(By.xpath("//td[not(contains(@class,'ui−datepicker− month'))]/a[text()='"+todate+"']")).click();
Thread.sleep(1000);
}
} | [
{
"code": null,
"e": 1357,
"s": 1187,
"text": "We can select the date picker in Selenium. It is slightly difficult to handle calendar controls as the day, month and year selection can be represented via different UI."
},
{
"code": null,
"e": 1487,
"s": 1357,
"text": "Sometimes they are represented by the dropdown or by forward and backward controls. Let us select the date picker as shown below."
},
{
"code": null,
"e": 1499,
"s": 1487,
"text": "From Date −"
},
{
"code": null,
"e": 1509,
"s": 1499,
"text": "To Date −"
},
{
"code": null,
"e": 3468,
"s": 1509,
"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 org.openqa.selenium.support.ui.Select;\npublic class DatePicker{\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 String frdate = \"20\";\n String todate = \"26\";\n driver.get(\"https://jqueryui.com/datepicker/#date−range\");\n // wait of 4 seconds\n driver.manage().timeouts().implicitlyWait(4, TimeUnit.SECONDS);\n // maximize browser\n driver.manage().window().maximize();\n // identify frame and switch to it\n WebElement e = driver.findElement(By.xpath(\"//*[@id='content']/iframe\"));\n driver.switchTo().frame(e);\n // choose from date\n driver.findElement(By.xpath(\"//input[@id='from']\")).click();\n Thread.sleep(1000);\n // choose month from dropdown\n WebElement m = driver\n .findElement(By.xpath(\"//div/select[@class='ui− datepicker−month']\"));\n Select s = new Select(m);\n s.selectByVisibleText(\"Jan\");\n Thread.sleep(1000);\n // select day\n driver.findElement(By.xpath(\"//td[not(contains(@class,'ui−datepicker− month'))]/a[text()='\"+frdate+\"']\")).click();\n Thread.sleep(1000);\n // choose to date\n driver.findElement(By.xpath(\"//input[@id='to']\")).click();\n Thread.sleep(1000);\n // choose month from dropdown\n WebElement n = driver\n .findElement(By.xpath(\"//div/select[@class='ui− datepicker−month']\"));\n Select sel = new Select(n);\n sel.selectByVisibleText(\"Feb\");\n Thread.sleep(1000);\n // select day\n driver.findElement(By.xpath(\"//td[not(contains(@class,'ui−datepicker− month'))]/a[text()='\"+todate+\"']\")).click();\n Thread.sleep(1000);\n }\n}"
}
] |
Compute the minimum or maximum of two integers without branching | 12 Jun, 2022
On some rare machines where branching is expensive, the below obvious approach to find minimum can be slow as it uses branching.
C++
C
Java
Python3
C#
Javascript
/* The obvious approach to find minimum (involves branching) */int min(int x, int y){ return (x < y) ? x : y} //This code is contributed by Shubham Singh
/* The obvious approach to find minimum (involves branching) */int min(int x, int y){ return (x < y) ? x : y}
/* The obvious approach to find minimum (involves branching) */static int min(int x, int y){ return (x < y) ? x : y;} // This code is contributed by rishavmahato348.
# The obvious approach to find minimum (involves branching)def min(x, y): return x if x < y else y # This code is contributed by subham348.
/* The obvious approach to find minimum (involves branching) */static int min(int x, int y){ return (x < y) ? x : y;} // This code is contributed by rishavmahato348.
<script> /* The obvious approach to find minimum (involves branching) */function min(x, y){ return (x < y) ? x : y;} // This code is contributed by subham348.</script>
Below are the methods to get minimum(or maximum) without using branching. Typically, the obvious approach is best, though.
Method 1(Use XOR and comparison operator)Minimum of x and y will be
y ^ ((x ^ y) & -(x < y))
It works because if x < y, then -(x < y) will be -1 which is all ones(11111....), so r = y ^ ((x ^ y) & (111111...)) = y ^ x ^ y = x.
And if x>y, then-(x<y) will be -(0) i.e -(zero) which is zero, so r = y^((x^y) & 0) = y^0 = y.
On some machines, evaluating (x < y) as 0 or 1 requires a branch instruction, so there may be no advantage.To find the maximum, use
x ^ ((x ^ y) & -(x < y));
C++
C
Java
Python3
C#
PHP
Javascript
// C++ program to Compute the minimum// or maximum of two integers without// branching#include<iostream>using namespace std; class gfg{ /*Function to find minimum of x and y*/ public: int min(int x, int y) { return y ^ ((x ^ y) & -(x < y)); } /*Function to find maximum of x and y*/ int max(int x, int y) { return x ^ ((x ^ y) & -(x < y)); } }; /* Driver code */ int main() { gfg g; int x = 15; int y = 6; cout << "Minimum of " << x << " and " << y << " is "; cout << g. min(x, y); cout << "\nMaximum of " << x << " and " << y << " is "; cout << g.max(x, y); getchar(); } // This code is contributed by SoM15242
// C program to Compute the minimum// or maximum of two integers without// branching#include<stdio.h> /*Function to find minimum of x and y*/int min(int x, int y){return y ^ ((x ^ y) & -(x < y));} /*Function to find maximum of x and y*/int max(int x, int y){return x ^ ((x ^ y) & -(x < y));} /* Driver program to test above functions */int main(){int x = 15;int y = 6;printf("Minimum of %d and %d is ", x, y);printf("%d", min(x, y));printf("\nMaximum of %d and %d is ", x, y);printf("%d", max(x, y));getchar();}
// Java program to Compute the minimum// or maximum of two integers without// branchingpublic class AWS { /*Function to find minimum of x and y*/ static int min(int x, int y) { return y ^ ((x ^ y) & -(x << y)); } /*Function to find maximum of x and y*/ static int max(int x, int y) { return x ^ ((x ^ y) & -(x << y)); } /* Driver program to test above functions */ public static void main(String[] args) { int x = 15; int y = 6; System.out.print("Minimum of "+x+" and "+y+" is "); System.out.println(min(x, y)); System.out.print("Maximum of "+x+" and "+y+" is "); System.out.println( max(x, y)); } }
# Python3 program to Compute the minimum# or maximum of two integers without# branching # Function to find minimum of x and y def min(x, y): return y ^ ((x ^ y) & -(x < y)) # Function to find maximum of x and ydef max(x, y): return x ^ ((x ^ y) & -(x < y)) # Driver program to test above functionsx = 15y = 6print("Minimum of", x, "and", y, "is", end=" ")print(min(x, y))print("Maximum of", x, "and", y, "is", end=" ")print(max(x, y)) # This code is contributed# by Smitha Dinesh Semwal
using System; // C# program to Compute the minimum// or maximum of two integers without // branchingpublic class AWS{ /*Function to find minimum of x and y*/ public static int min(int x, int y) { return y ^ ((x ^ y) & -(x << y)); } /*Function to find maximum of x and y*/ public static int max(int x, int y) { return x ^ ((x ^ y) & -(x << y)); } /* Driver program to test above functions */ public static void Main(string[] args) { int x = 15; int y = 6; Console.Write("Minimum of " + x + " and " + y + " is "); Console.WriteLine(min(x, y)); Console.Write("Maximum of " + x + " and " + y + " is "); Console.WriteLine(max(x, y)); } } // This code is contributed by Shrikant13
<?php// PHP program to Compute the minimum// or maximum of two integers without// branching // Function to find minimum// of x and yfunction m_in($x, $y){ return $y ^ (($x ^ $y) & - ($x < $y));} // Function to find maximum// of x and yfunction m_ax($x, $y){ return $x ^ (($x ^ $y) & - ($x < $y));} // Driver Code$x = 15;$y = 6;echo"Minimum of"," ", $x," ","and", " ",$y," "," is "," "; echo m_in($x, $y); echo "\nMaximum of"," ",$x," ", "and"," ",$y," ", " is "; echo m_ax($x, $y); // This code is contributed by anuj_67.?>
<script>// Javascript program to Compute the minimum// or maximum of two integers without// branching /*Function to find minimum of x and y*/ function min(x,y) { return y ^ ((x ^ y) & -(x << y)); } /*Function to find maximum of x and y*/ function max(x,y) { return x ^ ((x ^ y) & -(x << y)); } /* Driver program to test above functions */ let x = 15 let y = 6 document.write("Minimum of "+ x + " and " + y + " is "); document.write(min(x, y) + "<br>"); document.write("Maximum of " + x + " and " + y + " is "); document.write(max(x, y) + "\n"); // This code is contributed by avanitrachhadiya2155</script>
Output:
Minimum of 15 and 6 is 6
Maximum of 15 and 6 is 15
Time Complexity: O(1)
Auxiliary Space: O(1)
Method 2(Use subtraction and shift) If we know that
INT_MIN <= (x - y) <= INT_MAX
, then we can use the following, which are faster because (x – y) only needs to be evaluated once. Minimum of x and y will be
y + ((x - y) & ((x - y) >>(sizeof(int) * CHAR_BIT - 1)))
This method shifts the subtraction of x and y by 31 (if size of integer is 32). If (x-y) is smaller than 0, then (x -y)>>31 will be 1. If (x-y) is greater than or equal to 0, then (x -y)>>31 will be 0. So if x >= y, we get minimum as y + (x-y)&0 which is y. If x < y, we get minimum as y + (x-y)&1 which is x.Similarly, to find the maximum use
x - ((x - y) & ((x - y) >> (sizeof(int) * CHAR_BIT - 1)))
C++
C
Java
Python3
C#
Javascript
#include <bits/stdc++.h>using namespace std;#define CHARBIT 8 /*Function to find minimum of x and y*/int min(int x, int y){ return y + ((x - y) & ((x - y) >> (sizeof(int) * CHARBIT - 1)));} /*Function to find maximum of x and y*/int max(int x, int y){ return x - ((x - y) & ((x - y) >> (sizeof(int) * CHARBIT - 1)));} /* Driver code */int main(){ int x = 15; int y = 6; cout<<"Minimum of "<<x<<" and "<<y<<" is "; cout<<min(x, y); cout<<"\nMaximum of"<<x<<" and "<<y<<" is "; cout<<max(x, y);} // This code is contributed by rathbhupendra
#include<stdio.h>#define CHAR_BIT 8 /*Function to find minimum of x and y*/int min(int x, int y){ return y + ((x - y) & ((x - y) >> (sizeof(int) * CHAR_BIT - 1)));} /*Function to find maximum of x and y*/int max(int x, int y){ return x - ((x - y) & ((x - y) >> (sizeof(int) * CHAR_BIT - 1)));} /* Driver program to test above functions */int main(){ int x = 15; int y = 6; printf("Minimum of %d and %d is ", x, y); printf("%d", min(x, y)); printf("\nMaximum of %d and %d is ", x, y); printf("%d", max(x, y)); getchar();}
// JAVA implementation of above approachclass GFG{ static int CHAR_BIT = 4;static int INT_BIT = 8;/*Function to find minimum of x and y*/static int min(int x, int y){ return y + ((x - y) & ((x - y) >> (INT_BIT * CHAR_BIT - 1)));} /*Function to find maximum of x and y*/static int max(int x, int y){ return x - ((x - y) & ((x - y) >> (INT_BIT * CHAR_BIT - 1)));} /* Driver code */public static void main(String[] args){ int x = 15; int y = 6; System.out.println("Minimum of "+x+" and "+y+" is "+min(x, y)); System.out.println("Maximum of "+x+" and "+y+" is "+max(x, y));}} // This code is contributed by 29AjayKumar
# Python3 implementation of the approachimport sys; CHAR_BIT = 8;INT_BIT = sys.getsizeof(int()); #Function to find minimum of x and ydef Min(x, y): return y + ((x - y) & ((x - y) >> (INT_BIT * CHAR_BIT - 1))); #Function to find maximum of x and ydef Max(x, y): return x - ((x - y) & ((x - y) >> (INT_BIT * CHAR_BIT - 1))); # Driver codex = 15;y = 6;print("Minimum of", x, "and", y, "is", Min(x, y));print("Maximum of", x, "and", y, "is", Max(x, y)); # This code is contributed by PrinciRaj1992
// C# implementation of above approachusing System; class GFG{ static int CHAR_BIT = 8; /*Function to find minimum of x and y*/static int min(int x, int y){ return y + ((x - y) & ((x - y) >> (sizeof(int) * CHAR_BIT - 1)));} /*Function to find maximum of x and y*/static int max(int x, int y){ return x - ((x - y) & ((x - y) >> (sizeof(int) * CHAR_BIT - 1)));} /* Driver code */static void Main(){ int x = 15; int y = 6; Console.WriteLine("Minimum of "+x+" and "+y+" is "+min(x, y)); Console.WriteLine("Maximum of "+x+" and "+y+" is "+max(x, y));}} // This code is contributed by mits
<script>// javascript implementation of above approach var CHAR_BIT = 4; var INT_BIT = 8; /* Function to find minimum of x and y */ function min(x , y) { return y + ((x - y) & ((x - y) >> (INT_BIT * CHAR_BIT - 1))); } /* Function to find maximum of x and y */ function max(x , y) { return x - ((x - y) & ((x - y) >> (INT_BIT * CHAR_BIT - 1))); } /* Driver code */ var x = 15; var y = 6; document.write("Minimum of " + x + " and " + y + " is " + min(x, y)+"<br/>"); document.write("Maximum of " + x + " and " + y + " is " + max(x, y)); // This code is contributed by shikhasingrajput</script>
Time Complexity: O(1)
Auxiliary Space: O(1)
Note that the 1989 ANSI C specification doesn’t specify the result of signed right-shift, so above method is not portable. If exceptions are thrown on overflows, then the values of x and y should be unsigned or cast to unsigned for the subtractions to avoid unnecessarily throwing an exception, however the right-shift needs a signed operand to produce all one bits when negative, so cast to signed there.
Method 3 (Use absolute value)
A generalized formula to find the max/min number with absolute value is :
(x + y + ABS(x-y) )/2
Find the min number is:
(x + y - ABS(x-y) )/2
So, if we can use the bitwise operation to find the absolute value, we can find the max/min number without using if conditions. The way to find the absolute way with bitwise operation can be found here:
Step1) Set the mask as right shift of integer by 31 (assuming integers are stored as two’s-complement 32-bit values and that the right-shift operator does sign extension).
mask = n>>31
Step2) XOR the mask with number
mask ^ n
Step3) Subtract mask from result of step 2 and return the result.
(mask^n) - mask
Therefore, we can conclude the solution as follows:
C++
Java
Python3
C#
Javascript
// C++ program for the above approach#include <bits/stdc++.h>using namespace std; int absbit32(int x, int y){ int sub = x - y; int mask = (sub >> 31); return (sub ^ mask) - mask; } int max(int x, int y){ int abs = absbit32(x, y); return (x + y + abs) / 2; } int min(int x, int y){ int abs = absbit32(x, y); return (x + y - abs) / 2;} // Driver Codeint main(){ cout << max(2, 3) << endl; //3 cout << max(2, -3) << endl; //2 cout << max(-2, -3) << endl; //-2 cout << min(2, 3) << endl; //2 cout << min(2, -3) << endl; //-3 cout << min(-2, -3) << endl; //-3 return 0;} // This code is contributed by avijitmondal1998
// Java program for the above approach import java.io.*; class GFG { public static void main(String []args){ System.out.println( max(2,3) ); //3 System.out.println( max(2,-3) ); //2 System.out.println( max(-2,-3) ); //-2 System.out.println( min(2,3) ); //2 System.out.println( min(2,-3) ); //-3 System.out.println( min(-2,-3) ); //-3 } public static int max(int x, int y){ int abs = absbit32(x,y); return (x + y + abs)/2; } public static int min(int x, int y){ int abs = absbit32(x,y); return (x + y - abs)/2; } public static int absbit32(int x, int y){ int sub = x - y; int mask = (sub >> 31); return (sub ^ mask) - mask; }}
# Python3 program for the above approachdef max(x, y): abs = absbit32(x,y) return (x + y + abs)//2 def min(x, y): abs = absbit32(x,y) return (x + y - abs)//2 def absbit32( x, y): sub = x - y mask = (sub >> 31) return (sub ^ mask) - mask # Driver codeprint( max(2,3) ) #3print( max(2,-3) ) #2print( max(-2,-3) ) #-2print( min(2,3) ) #2print( min(2,-3) ) #-3print( min(-2,-3) ) #-3 # This code is contributed by rohitsingh07052.
// C# program for the above approachusing System; class GFG{ public static void Main(String []args){ Console.WriteLine(max(2, 3)); //3 Console.WriteLine(max(2, -3)); //2 Console.WriteLine(max(-2, -3)); //-2 Console.WriteLine(min(2, 3)); //2 Console.WriteLine(min(2, -3)); //-3 Console.WriteLine(min(-2, -3)); //-3} public static int max(int x, int y){ int abs = absbit32(x, y); return (x + y + abs) / 2; } public static int min(int x, int y){ int abs = absbit32(x, y); return (x + y - abs) / 2;} public static int absbit32(int x, int y){ int sub = x - y; int mask = (sub >> 31); return (sub ^ mask) - mask; }} // This code is contributed by Amit Katiyar
<script> // Javascript program for the above approach function max(x , y){ var abs = absbit32(x,y); return (x + y + abs)/2; } function min(x , y){ var abs = absbit32(x,y); return (x + y - abs)/2; } function absbit32(x , y){ var sub = x - y; var mask = (sub >> 31); return (sub ^ mask) - mask; } // Drive code document.write( max(2,3)+"<br>" ); //3 document.write( max(2,-3)+"<br>" ); //2 document.write( max(-2,-3)+"<br>" ); //-2 document.write( min(2,3)+"<br>" ); //2 document.write( min(2,-3)+"<br>" ); //-3 document.write( min(-2,-3) ); //-3 // This code is contributed by 29AjayKumar </script>
Time Complexity: O(1)
Auxiliary Space: O(1)Source: http://graphics.stanford.edu/~seander/bithacks.html#IntegerMinOrMax
vt_m
ukasp
shrikanth13
SoumikMondal
Mithun Kumar
rathbhupendra
29AjayKumar
princiraj1992
mrytseng
contactgaurav27
avanitrachhadiya2155
shikhasingrajput
amit143katiyar
rohitsingh07052
avijitmondal1998
rishavmahato348
subham348
shubhamsingh84100
ranjanrohit840
Bitwise-XOR
Bit Magic
Bit Magic
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Program to find whether a given number is power of 2
Bits manipulation (Important tactics)
Little and Big Endian Mystery
Binary representation of a given number
Divide two integers without using multiplication, division and mod operator
Josephus problem | Set 1 (A O(n) Solution)
Bit Fields in C
Add two numbers without using arithmetic operators
Find the element that appears once
C++ bitset and its application | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n12 Jun, 2022"
},
{
"code": null,
"e": 181,
"s": 52,
"text": "On some rare machines where branching is expensive, the below obvious approach to find minimum can be slow as it uses branching."
},
{
"code": null,
"e": 185,
"s": 181,
"text": "C++"
},
{
"code": null,
"e": 187,
"s": 185,
"text": "C"
},
{
"code": null,
"e": 192,
"s": 187,
"text": "Java"
},
{
"code": null,
"e": 200,
"s": 192,
"text": "Python3"
},
{
"code": null,
"e": 203,
"s": 200,
"text": "C#"
},
{
"code": null,
"e": 214,
"s": 203,
"text": "Javascript"
},
{
"code": "/* The obvious approach to find minimum (involves branching) */int min(int x, int y){ return (x < y) ? x : y} //This code is contributed by Shubham Singh",
"e": 369,
"s": 214,
"text": null
},
{
"code": "/* The obvious approach to find minimum (involves branching) */int min(int x, int y){ return (x < y) ? x : y}",
"e": 480,
"s": 369,
"text": null
},
{
"code": "/* The obvious approach to find minimum (involves branching) */static int min(int x, int y){ return (x < y) ? x : y;} // This code is contributed by rishavmahato348.",
"e": 647,
"s": 480,
"text": null
},
{
"code": "# The obvious approach to find minimum (involves branching)def min(x, y): return x if x < y else y # This code is contributed by subham348.",
"e": 792,
"s": 647,
"text": null
},
{
"code": "/* The obvious approach to find minimum (involves branching) */static int min(int x, int y){ return (x < y) ? x : y;} // This code is contributed by rishavmahato348.",
"e": 959,
"s": 792,
"text": null
},
{
"code": "<script> /* The obvious approach to find minimum (involves branching) */function min(x, y){ return (x < y) ? x : y;} // This code is contributed by subham348.</script>",
"e": 1128,
"s": 959,
"text": null
},
{
"code": null,
"e": 1251,
"s": 1128,
"text": "Below are the methods to get minimum(or maximum) without using branching. Typically, the obvious approach is best, though."
},
{
"code": null,
"e": 1320,
"s": 1251,
"text": "Method 1(Use XOR and comparison operator)Minimum of x and y will be "
},
{
"code": null,
"e": 1345,
"s": 1320,
"text": "y ^ ((x ^ y) & -(x < y))"
},
{
"code": null,
"e": 1480,
"s": 1345,
"text": "It works because if x < y, then -(x < y) will be -1 which is all ones(11111....), so r = y ^ ((x ^ y) & (111111...)) = y ^ x ^ y = x. "
},
{
"code": null,
"e": 1575,
"s": 1480,
"text": "And if x>y, then-(x<y) will be -(0) i.e -(zero) which is zero, so r = y^((x^y) & 0) = y^0 = y."
},
{
"code": null,
"e": 1708,
"s": 1575,
"text": "On some machines, evaluating (x < y) as 0 or 1 requires a branch instruction, so there may be no advantage.To find the maximum, use "
},
{
"code": null,
"e": 1734,
"s": 1708,
"text": "x ^ ((x ^ y) & -(x < y));"
},
{
"code": null,
"e": 1738,
"s": 1734,
"text": "C++"
},
{
"code": null,
"e": 1740,
"s": 1738,
"text": "C"
},
{
"code": null,
"e": 1745,
"s": 1740,
"text": "Java"
},
{
"code": null,
"e": 1753,
"s": 1745,
"text": "Python3"
},
{
"code": null,
"e": 1756,
"s": 1753,
"text": "C#"
},
{
"code": null,
"e": 1760,
"s": 1756,
"text": "PHP"
},
{
"code": null,
"e": 1771,
"s": 1760,
"text": "Javascript"
},
{
"code": "// C++ program to Compute the minimum// or maximum of two integers without// branching#include<iostream>using namespace std; class gfg{ /*Function to find minimum of x and y*/ public: int min(int x, int y) { return y ^ ((x ^ y) & -(x < y)); } /*Function to find maximum of x and y*/ int max(int x, int y) { return x ^ ((x ^ y) & -(x < y)); } }; /* Driver code */ int main() { gfg g; int x = 15; int y = 6; cout << \"Minimum of \" << x << \" and \" << y << \" is \"; cout << g. min(x, y); cout << \"\\nMaximum of \" << x << \" and \" << y << \" is \"; cout << g.max(x, y); getchar(); } // This code is contributed by SoM15242",
"e": 2533,
"s": 1771,
"text": null
},
{
"code": "// C program to Compute the minimum// or maximum of two integers without// branching#include<stdio.h> /*Function to find minimum of x and y*/int min(int x, int y){return y ^ ((x ^ y) & -(x < y));} /*Function to find maximum of x and y*/int max(int x, int y){return x ^ ((x ^ y) & -(x < y));} /* Driver program to test above functions */int main(){int x = 15;int y = 6;printf(\"Minimum of %d and %d is \", x, y);printf(\"%d\", min(x, y));printf(\"\\nMaximum of %d and %d is \", x, y);printf(\"%d\", max(x, y));getchar();}",
"e": 3045,
"s": 2533,
"text": null
},
{
"code": "// Java program to Compute the minimum// or maximum of two integers without// branchingpublic class AWS { /*Function to find minimum of x and y*/ static int min(int x, int y) { return y ^ ((x ^ y) & -(x << y)); } /*Function to find maximum of x and y*/ static int max(int x, int y) { return x ^ ((x ^ y) & -(x << y)); } /* Driver program to test above functions */ public static void main(String[] args) { int x = 15; int y = 6; System.out.print(\"Minimum of \"+x+\" and \"+y+\" is \"); System.out.println(min(x, y)); System.out.print(\"Maximum of \"+x+\" and \"+y+\" is \"); System.out.println( max(x, y)); } }",
"e": 3746,
"s": 3045,
"text": null
},
{
"code": "# Python3 program to Compute the minimum# or maximum of two integers without# branching # Function to find minimum of x and y def min(x, y): return y ^ ((x ^ y) & -(x < y)) # Function to find maximum of x and ydef max(x, y): return x ^ ((x ^ y) & -(x < y)) # Driver program to test above functionsx = 15y = 6print(\"Minimum of\", x, \"and\", y, \"is\", end=\" \")print(min(x, y))print(\"Maximum of\", x, \"and\", y, \"is\", end=\" \")print(max(x, y)) # This code is contributed# by Smitha Dinesh Semwal",
"e": 4243,
"s": 3746,
"text": null
},
{
"code": "using System; // C# program to Compute the minimum// or maximum of two integers without // branchingpublic class AWS{ /*Function to find minimum of x and y*/ public static int min(int x, int y) { return y ^ ((x ^ y) & -(x << y)); } /*Function to find maximum of x and y*/ public static int max(int x, int y) { return x ^ ((x ^ y) & -(x << y)); } /* Driver program to test above functions */ public static void Main(string[] args) { int x = 15; int y = 6; Console.Write(\"Minimum of \" + x + \" and \" + y + \" is \"); Console.WriteLine(min(x, y)); Console.Write(\"Maximum of \" + x + \" and \" + y + \" is \"); Console.WriteLine(max(x, y)); } } // This code is contributed by Shrikant13",
"e": 5010,
"s": 4243,
"text": null
},
{
"code": "<?php// PHP program to Compute the minimum// or maximum of two integers without// branching // Function to find minimum// of x and yfunction m_in($x, $y){ return $y ^ (($x ^ $y) & - ($x < $y));} // Function to find maximum// of x and yfunction m_ax($x, $y){ return $x ^ (($x ^ $y) & - ($x < $y));} // Driver Code$x = 15;$y = 6;echo\"Minimum of\",\" \", $x,\" \",\"and\", \" \",$y,\" \",\" is \",\" \"; echo m_in($x, $y); echo \"\\nMaximum of\",\" \",$x,\" \", \"and\",\" \",$y,\" \", \" is \"; echo m_ax($x, $y); // This code is contributed by anuj_67.?>",
"e": 5576,
"s": 5010,
"text": null
},
{
"code": "<script>// Javascript program to Compute the minimum// or maximum of two integers without// branching /*Function to find minimum of x and y*/ function min(x,y) { return y ^ ((x ^ y) & -(x << y)); } /*Function to find maximum of x and y*/ function max(x,y) { return x ^ ((x ^ y) & -(x << y)); } /* Driver program to test above functions */ let x = 15 let y = 6 document.write(\"Minimum of \"+ x + \" and \" + y + \" is \"); document.write(min(x, y) + \"<br>\"); document.write(\"Maximum of \" + x + \" and \" + y + \" is \"); document.write(max(x, y) + \"\\n\"); // This code is contributed by avanitrachhadiya2155</script>",
"e": 6261,
"s": 5576,
"text": null
},
{
"code": null,
"e": 6270,
"s": 6261,
"text": "Output: "
},
{
"code": null,
"e": 6321,
"s": 6270,
"text": "Minimum of 15 and 6 is 6\nMaximum of 15 and 6 is 15"
},
{
"code": null,
"e": 6343,
"s": 6321,
"text": "Time Complexity: O(1)"
},
{
"code": null,
"e": 6365,
"s": 6343,
"text": "Auxiliary Space: O(1)"
},
{
"code": null,
"e": 6418,
"s": 6365,
"text": "Method 2(Use subtraction and shift) If we know that "
},
{
"code": null,
"e": 6448,
"s": 6418,
"text": "INT_MIN <= (x - y) <= INT_MAX"
},
{
"code": null,
"e": 6575,
"s": 6448,
"text": ", then we can use the following, which are faster because (x – y) only needs to be evaluated once. Minimum of x and y will be "
},
{
"code": null,
"e": 6632,
"s": 6575,
"text": "y + ((x - y) & ((x - y) >>(sizeof(int) * CHAR_BIT - 1)))"
},
{
"code": null,
"e": 6977,
"s": 6632,
"text": "This method shifts the subtraction of x and y by 31 (if size of integer is 32). If (x-y) is smaller than 0, then (x -y)>>31 will be 1. If (x-y) is greater than or equal to 0, then (x -y)>>31 will be 0. So if x >= y, we get minimum as y + (x-y)&0 which is y. If x < y, we get minimum as y + (x-y)&1 which is x.Similarly, to find the maximum use "
},
{
"code": null,
"e": 7035,
"s": 6977,
"text": "x - ((x - y) & ((x - y) >> (sizeof(int) * CHAR_BIT - 1)))"
},
{
"code": null,
"e": 7039,
"s": 7035,
"text": "C++"
},
{
"code": null,
"e": 7041,
"s": 7039,
"text": "C"
},
{
"code": null,
"e": 7046,
"s": 7041,
"text": "Java"
},
{
"code": null,
"e": 7054,
"s": 7046,
"text": "Python3"
},
{
"code": null,
"e": 7057,
"s": 7054,
"text": "C#"
},
{
"code": null,
"e": 7068,
"s": 7057,
"text": "Javascript"
},
{
"code": "#include <bits/stdc++.h>using namespace std;#define CHARBIT 8 /*Function to find minimum of x and y*/int min(int x, int y){ return y + ((x - y) & ((x - y) >> (sizeof(int) * CHARBIT - 1)));} /*Function to find maximum of x and y*/int max(int x, int y){ return x - ((x - y) & ((x - y) >> (sizeof(int) * CHARBIT - 1)));} /* Driver code */int main(){ int x = 15; int y = 6; cout<<\"Minimum of \"<<x<<\" and \"<<y<<\" is \"; cout<<min(x, y); cout<<\"\\nMaximum of\"<<x<<\" and \"<<y<<\" is \"; cout<<max(x, y);} // This code is contributed by rathbhupendra",
"e": 7653,
"s": 7068,
"text": null
},
{
"code": "#include<stdio.h>#define CHAR_BIT 8 /*Function to find minimum of x and y*/int min(int x, int y){ return y + ((x - y) & ((x - y) >> (sizeof(int) * CHAR_BIT - 1)));} /*Function to find maximum of x and y*/int max(int x, int y){ return x - ((x - y) & ((x - y) >> (sizeof(int) * CHAR_BIT - 1)));} /* Driver program to test above functions */int main(){ int x = 15; int y = 6; printf(\"Minimum of %d and %d is \", x, y); printf(\"%d\", min(x, y)); printf(\"\\nMaximum of %d and %d is \", x, y); printf(\"%d\", max(x, y)); getchar();}",
"e": 8206,
"s": 7653,
"text": null
},
{
"code": "// JAVA implementation of above approachclass GFG{ static int CHAR_BIT = 4;static int INT_BIT = 8;/*Function to find minimum of x and y*/static int min(int x, int y){ return y + ((x - y) & ((x - y) >> (INT_BIT * CHAR_BIT - 1)));} /*Function to find maximum of x and y*/static int max(int x, int y){ return x - ((x - y) & ((x - y) >> (INT_BIT * CHAR_BIT - 1)));} /* Driver code */public static void main(String[] args){ int x = 15; int y = 6; System.out.println(\"Minimum of \"+x+\" and \"+y+\" is \"+min(x, y)); System.out.println(\"Maximum of \"+x+\" and \"+y+\" is \"+max(x, y));}} // This code is contributed by 29AjayKumar",
"e": 8869,
"s": 8206,
"text": null
},
{
"code": "# Python3 implementation of the approachimport sys; CHAR_BIT = 8;INT_BIT = sys.getsizeof(int()); #Function to find minimum of x and ydef Min(x, y): return y + ((x - y) & ((x - y) >> (INT_BIT * CHAR_BIT - 1))); #Function to find maximum of x and ydef Max(x, y): return x - ((x - y) & ((x - y) >> (INT_BIT * CHAR_BIT - 1))); # Driver codex = 15;y = 6;print(\"Minimum of\", x, \"and\", y, \"is\", Min(x, y));print(\"Maximum of\", x, \"and\", y, \"is\", Max(x, y)); # This code is contributed by PrinciRaj1992",
"e": 9441,
"s": 8869,
"text": null
},
{
"code": "// C# implementation of above approachusing System; class GFG{ static int CHAR_BIT = 8; /*Function to find minimum of x and y*/static int min(int x, int y){ return y + ((x - y) & ((x - y) >> (sizeof(int) * CHAR_BIT - 1)));} /*Function to find maximum of x and y*/static int max(int x, int y){ return x - ((x - y) & ((x - y) >> (sizeof(int) * CHAR_BIT - 1)));} /* Driver code */static void Main(){ int x = 15; int y = 6; Console.WriteLine(\"Minimum of \"+x+\" and \"+y+\" is \"+min(x, y)); Console.WriteLine(\"Maximum of \"+x+\" and \"+y+\" is \"+max(x, y));}} // This code is contributed by mits",
"e": 10073,
"s": 9441,
"text": null
},
{
"code": "<script>// javascript implementation of above approach var CHAR_BIT = 4; var INT_BIT = 8; /* Function to find minimum of x and y */ function min(x , y) { return y + ((x - y) & ((x - y) >> (INT_BIT * CHAR_BIT - 1))); } /* Function to find maximum of x and y */ function max(x , y) { return x - ((x - y) & ((x - y) >> (INT_BIT * CHAR_BIT - 1))); } /* Driver code */ var x = 15; var y = 6; document.write(\"Minimum of \" + x + \" and \" + y + \" is \" + min(x, y)+\"<br/>\"); document.write(\"Maximum of \" + x + \" and \" + y + \" is \" + max(x, y)); // This code is contributed by shikhasingrajput</script>",
"e": 10736,
"s": 10073,
"text": null
},
{
"code": null,
"e": 10758,
"s": 10736,
"text": "Time Complexity: O(1)"
},
{
"code": null,
"e": 10780,
"s": 10758,
"text": "Auxiliary Space: O(1)"
},
{
"code": null,
"e": 11187,
"s": 10780,
"text": "Note that the 1989 ANSI C specification doesn’t specify the result of signed right-shift, so above method is not portable. If exceptions are thrown on overflows, then the values of x and y should be unsigned or cast to unsigned for the subtractions to avoid unnecessarily throwing an exception, however the right-shift needs a signed operand to produce all one bits when negative, so cast to signed there. "
},
{
"code": null,
"e": 11218,
"s": 11187,
"text": "Method 3 (Use absolute value) "
},
{
"code": null,
"e": 11293,
"s": 11218,
"text": "A generalized formula to find the max/min number with absolute value is : "
},
{
"code": null,
"e": 11315,
"s": 11293,
"text": "(x + y + ABS(x-y) )/2"
},
{
"code": null,
"e": 11340,
"s": 11315,
"text": "Find the min number is: "
},
{
"code": null,
"e": 11362,
"s": 11340,
"text": "(x + y - ABS(x-y) )/2"
},
{
"code": null,
"e": 11565,
"s": 11362,
"text": "So, if we can use the bitwise operation to find the absolute value, we can find the max/min number without using if conditions. The way to find the absolute way with bitwise operation can be found here:"
},
{
"code": null,
"e": 11737,
"s": 11565,
"text": "Step1) Set the mask as right shift of integer by 31 (assuming integers are stored as two’s-complement 32-bit values and that the right-shift operator does sign extension)."
},
{
"code": null,
"e": 11750,
"s": 11737,
"text": "mask = n>>31"
},
{
"code": null,
"e": 11782,
"s": 11750,
"text": "Step2) XOR the mask with number"
},
{
"code": null,
"e": 11791,
"s": 11782,
"text": "mask ^ n"
},
{
"code": null,
"e": 11857,
"s": 11791,
"text": "Step3) Subtract mask from result of step 2 and return the result."
},
{
"code": null,
"e": 11874,
"s": 11857,
"text": "(mask^n) - mask "
},
{
"code": null,
"e": 11926,
"s": 11874,
"text": "Therefore, we can conclude the solution as follows:"
},
{
"code": null,
"e": 11930,
"s": 11926,
"text": "C++"
},
{
"code": null,
"e": 11935,
"s": 11930,
"text": "Java"
},
{
"code": null,
"e": 11943,
"s": 11935,
"text": "Python3"
},
{
"code": null,
"e": 11946,
"s": 11943,
"text": "C#"
},
{
"code": null,
"e": 11957,
"s": 11946,
"text": "Javascript"
},
{
"code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; int absbit32(int x, int y){ int sub = x - y; int mask = (sub >> 31); return (sub ^ mask) - mask; } int max(int x, int y){ int abs = absbit32(x, y); return (x + y + abs) / 2; } int min(int x, int y){ int abs = absbit32(x, y); return (x + y - abs) / 2;} // Driver Codeint main(){ cout << max(2, 3) << endl; //3 cout << max(2, -3) << endl; //2 cout << max(-2, -3) << endl; //-2 cout << min(2, 3) << endl; //2 cout << min(2, -3) << endl; //-3 cout << min(-2, -3) << endl; //-3 return 0;} // This code is contributed by avijitmondal1998",
"e": 12650,
"s": 11957,
"text": null
},
{
"code": "// Java program for the above approach import java.io.*; class GFG { public static void main(String []args){ System.out.println( max(2,3) ); //3 System.out.println( max(2,-3) ); //2 System.out.println( max(-2,-3) ); //-2 System.out.println( min(2,3) ); //2 System.out.println( min(2,-3) ); //-3 System.out.println( min(-2,-3) ); //-3 } public static int max(int x, int y){ int abs = absbit32(x,y); return (x + y + abs)/2; } public static int min(int x, int y){ int abs = absbit32(x,y); return (x + y - abs)/2; } public static int absbit32(int x, int y){ int sub = x - y; int mask = (sub >> 31); return (sub ^ mask) - mask; }}",
"e": 13456,
"s": 12650,
"text": null
},
{
"code": "# Python3 program for the above approachdef max(x, y): abs = absbit32(x,y) return (x + y + abs)//2 def min(x, y): abs = absbit32(x,y) return (x + y - abs)//2 def absbit32( x, y): sub = x - y mask = (sub >> 31) return (sub ^ mask) - mask # Driver codeprint( max(2,3) ) #3print( max(2,-3) ) #2print( max(-2,-3) ) #-2print( min(2,3) ) #2print( min(2,-3) ) #-3print( min(-2,-3) ) #-3 # This code is contributed by rohitsingh07052.",
"e": 13911,
"s": 13456,
"text": null
},
{
"code": "// C# program for the above approachusing System; class GFG{ public static void Main(String []args){ Console.WriteLine(max(2, 3)); //3 Console.WriteLine(max(2, -3)); //2 Console.WriteLine(max(-2, -3)); //-2 Console.WriteLine(min(2, 3)); //2 Console.WriteLine(min(2, -3)); //-3 Console.WriteLine(min(-2, -3)); //-3} public static int max(int x, int y){ int abs = absbit32(x, y); return (x + y + abs) / 2; } public static int min(int x, int y){ int abs = absbit32(x, y); return (x + y - abs) / 2;} public static int absbit32(int x, int y){ int sub = x - y; int mask = (sub >> 31); return (sub ^ mask) - mask; }} // This code is contributed by Amit Katiyar",
"e": 14639,
"s": 13911,
"text": null
},
{
"code": "<script> // Javascript program for the above approach function max(x , y){ var abs = absbit32(x,y); return (x + y + abs)/2; } function min(x , y){ var abs = absbit32(x,y); return (x + y - abs)/2; } function absbit32(x , y){ var sub = x - y; var mask = (sub >> 31); return (sub ^ mask) - mask; } // Drive code document.write( max(2,3)+\"<br>\" ); //3 document.write( max(2,-3)+\"<br>\" ); //2 document.write( max(-2,-3)+\"<br>\" ); //-2 document.write( min(2,3)+\"<br>\" ); //2 document.write( min(2,-3)+\"<br>\" ); //-3 document.write( min(-2,-3) ); //-3 // This code is contributed by 29AjayKumar </script>",
"e": 15302,
"s": 14639,
"text": null
},
{
"code": null,
"e": 15324,
"s": 15302,
"text": "Time Complexity: O(1)"
},
{
"code": null,
"e": 15422,
"s": 15324,
"text": "Auxiliary Space: O(1)Source: http://graphics.stanford.edu/~seander/bithacks.html#IntegerMinOrMax "
},
{
"code": null,
"e": 15427,
"s": 15422,
"text": "vt_m"
},
{
"code": null,
"e": 15433,
"s": 15427,
"text": "ukasp"
},
{
"code": null,
"e": 15445,
"s": 15433,
"text": "shrikanth13"
},
{
"code": null,
"e": 15458,
"s": 15445,
"text": "SoumikMondal"
},
{
"code": null,
"e": 15471,
"s": 15458,
"text": "Mithun Kumar"
},
{
"code": null,
"e": 15485,
"s": 15471,
"text": "rathbhupendra"
},
{
"code": null,
"e": 15497,
"s": 15485,
"text": "29AjayKumar"
},
{
"code": null,
"e": 15511,
"s": 15497,
"text": "princiraj1992"
},
{
"code": null,
"e": 15520,
"s": 15511,
"text": "mrytseng"
},
{
"code": null,
"e": 15536,
"s": 15520,
"text": "contactgaurav27"
},
{
"code": null,
"e": 15557,
"s": 15536,
"text": "avanitrachhadiya2155"
},
{
"code": null,
"e": 15574,
"s": 15557,
"text": "shikhasingrajput"
},
{
"code": null,
"e": 15589,
"s": 15574,
"text": "amit143katiyar"
},
{
"code": null,
"e": 15605,
"s": 15589,
"text": "rohitsingh07052"
},
{
"code": null,
"e": 15622,
"s": 15605,
"text": "avijitmondal1998"
},
{
"code": null,
"e": 15638,
"s": 15622,
"text": "rishavmahato348"
},
{
"code": null,
"e": 15648,
"s": 15638,
"text": "subham348"
},
{
"code": null,
"e": 15666,
"s": 15648,
"text": "shubhamsingh84100"
},
{
"code": null,
"e": 15681,
"s": 15666,
"text": "ranjanrohit840"
},
{
"code": null,
"e": 15693,
"s": 15681,
"text": "Bitwise-XOR"
},
{
"code": null,
"e": 15703,
"s": 15693,
"text": "Bit Magic"
},
{
"code": null,
"e": 15713,
"s": 15703,
"text": "Bit Magic"
},
{
"code": null,
"e": 15811,
"s": 15713,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 15864,
"s": 15811,
"text": "Program to find whether a given number is power of 2"
},
{
"code": null,
"e": 15902,
"s": 15864,
"text": "Bits manipulation (Important tactics)"
},
{
"code": null,
"e": 15932,
"s": 15902,
"text": "Little and Big Endian Mystery"
},
{
"code": null,
"e": 15972,
"s": 15932,
"text": "Binary representation of a given number"
},
{
"code": null,
"e": 16048,
"s": 15972,
"text": "Divide two integers without using multiplication, division and mod operator"
},
{
"code": null,
"e": 16091,
"s": 16048,
"text": "Josephus problem | Set 1 (A O(n) Solution)"
},
{
"code": null,
"e": 16107,
"s": 16091,
"text": "Bit Fields in C"
},
{
"code": null,
"e": 16158,
"s": 16107,
"text": "Add two numbers without using arithmetic operators"
},
{
"code": null,
"e": 16193,
"s": 16158,
"text": "Find the element that appears once"
}
] |
Text Split Effect using CSS | 18 Feb, 2022
In this article, we will see how we can create a text split effect using CSS. HTML code is used to create the basic structure of the sections and CSS code is used to set the style.
Approach:
Create an HTML div element with the class “container”.
Inside the “container”, create an HTML div with class “box”.
Create two p tags with text.
To split the text we are going to provide the text shape using clip-path and then use transform property on hover to translate it.
Example:
HTML
<!DOCTYPE html><html> <head> <style type="text/css"> /* Aligning container in center*/ .container { position: absolute; transform: translate(-50%, -50%); top: 35%; left: 35%; color: green; } /* General styling to text and transition of 2s*/ .text { position: absolute; text-transform: uppercase; font-size: 3rem; transition: 2s ease; } /* Giving shapes to text using clip-path*/ .text1 { clip-path: polygon(0 0, 100% 0, 100% 100%, 50% 0, 0 100%); } .text2 { clip-path: polygon(0 100%, 50% 0, 100% 100%, 100% 100%, 0 100%); } /* transforming box 1 position on hover */ .box:hover .text1 { transform: translateY(-10px); } /* transforming box 2 position on hover */ .box:hover .text2 { transform: translateY(10px); } </style></head> <body> <!-- Create container --> <div class="container"> <!-- create div with class box --> <div class="box"> <!-- write the text to be splitted into two p tags --> <p class="text text1">geeksforgeeks</p> <p class="text text2">geeksforgeeks</p> </div> </div></body> </html>
Output:
Reference: https://www.geeksforgeeks.org/how-to-split-text-horizontally-on-mouse-move-over-using-css/
sagar0719kumar
CSS-Properties
CSS-Questions
HTML-Questions
CSS
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n18 Feb, 2022"
},
{
"code": null,
"e": 210,
"s": 28,
"text": "In this article, we will see how we can create a text split effect using CSS. HTML code is used to create the basic structure of the sections and CSS code is used to set the style."
},
{
"code": null,
"e": 220,
"s": 210,
"text": "Approach:"
},
{
"code": null,
"e": 275,
"s": 220,
"text": "Create an HTML div element with the class “container”."
},
{
"code": null,
"e": 337,
"s": 275,
"text": "Inside the “container”, create an HTML div with class “box”."
},
{
"code": null,
"e": 366,
"s": 337,
"text": "Create two p tags with text."
},
{
"code": null,
"e": 497,
"s": 366,
"text": "To split the text we are going to provide the text shape using clip-path and then use transform property on hover to translate it."
},
{
"code": null,
"e": 506,
"s": 497,
"text": "Example:"
},
{
"code": null,
"e": 511,
"s": 506,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <style type=\"text/css\"> /* Aligning container in center*/ .container { position: absolute; transform: translate(-50%, -50%); top: 35%; left: 35%; color: green; } /* General styling to text and transition of 2s*/ .text { position: absolute; text-transform: uppercase; font-size: 3rem; transition: 2s ease; } /* Giving shapes to text using clip-path*/ .text1 { clip-path: polygon(0 0, 100% 0, 100% 100%, 50% 0, 0 100%); } .text2 { clip-path: polygon(0 100%, 50% 0, 100% 100%, 100% 100%, 0 100%); } /* transforming box 1 position on hover */ .box:hover .text1 { transform: translateY(-10px); } /* transforming box 2 position on hover */ .box:hover .text2 { transform: translateY(10px); } </style></head> <body> <!-- Create container --> <div class=\"container\"> <!-- create div with class box --> <div class=\"box\"> <!-- write the text to be splitted into two p tags --> <p class=\"text text1\">geeksforgeeks</p> <p class=\"text text2\">geeksforgeeks</p> </div> </div></body> </html>",
"e": 1816,
"s": 511,
"text": null
},
{
"code": null,
"e": 1824,
"s": 1816,
"text": "Output:"
},
{
"code": null,
"e": 1926,
"s": 1824,
"text": "Reference: https://www.geeksforgeeks.org/how-to-split-text-horizontally-on-mouse-move-over-using-css/"
},
{
"code": null,
"e": 1941,
"s": 1926,
"text": "sagar0719kumar"
},
{
"code": null,
"e": 1956,
"s": 1941,
"text": "CSS-Properties"
},
{
"code": null,
"e": 1970,
"s": 1956,
"text": "CSS-Questions"
},
{
"code": null,
"e": 1985,
"s": 1970,
"text": "HTML-Questions"
},
{
"code": null,
"e": 1989,
"s": 1985,
"text": "CSS"
},
{
"code": null,
"e": 1994,
"s": 1989,
"text": "HTML"
},
{
"code": null,
"e": 2011,
"s": 1994,
"text": "Web Technologies"
},
{
"code": null,
"e": 2016,
"s": 2011,
"text": "HTML"
}
] |
Button in Android | 17 Aug, 2021
In Android applications, a Button is a user interface that is used to perform some action when clicked or tapped. It is a very common widget in Android and developers often use it. This article demonstrates how to create a button in Android Studio.
XML Attributes
Description
In this example step by step demonstration of creating a Button will be covered. The application will consist of a button that displays a toast message when the user taps on it.
Note: Following steps are performed on Android Studio version 4.0
Step 1: Create a new project
Click on File, then New => New Project.Choose “Empty Activity” for the project template.Select language as Kotlin.Select the minimum SDK as per your need.
Click on File, then New => New Project.
Choose “Empty Activity” for the project template.
Select language as Kotlin.
Select the minimum SDK as per your need.
Step 2: Modify the strings.xml file
Navigate to the strings.xml file under the “values” directory of the resource folder. This file will contain all strings that are used in the Application. Below is the appropriate code.
XML
<resources> <string name="app_name">GfG | Button In Kotlin</string> <string name="btn">Button</string> <string name="message">Hello Geeks!! This is a Button.</string></resources>
Step 3: Modify the activity_main.xml file
Add a button widget in the layout of the activity. Below is the code of the activity_main.xml file which does the same.
XML
<?xml version="1.0" encoding="utf-8"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#168BC34A" tools:context=".MainActivity"> <!-- Button added in the activity --> <Button android:id="@+id/button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="#4CAF50" android:paddingStart="10dp" android:paddingEnd="10dp" android:text="@string/btn" android:textColor="@android:color/background_light" android:textSize="24sp" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" /> </androidx.constraintlayout.widget.ConstraintLayout>
Step 4: Accessing the button in the MainActivity file
Add functionality of button in the MainActivity file. Here describe the operation to display a Toast message when the user taps on the button. Below is the code to carry out this task.
Java
Kotlin
import androidx.appcompat.app.AppCompatActivity;import android.content.Context;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.Toast; public class MainActivity extends AppCompatActivity { @Override protected void onCreate( Bundle savedInstanceState ) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // storing ID of the button // in a variable Button button = (Button)findViewById(R.id.button); // operations to be performed // when user tap on the button if (button != null) { button.setOnClickListener((View.OnClickListener)(new View.OnClickListener() { public final void onClick(View it) { // displaying a toast message Toast.makeText((Context)MainActivity.this, R.string.message, Toast.LENGTH_LONG).show(); } })); } }}
import androidx.appcompat.app.AppCompatActivityimport android.os.Bundleimport android.widget.Buttonimport android.widget.Toast class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // storing ID of the button // in a variable val button = findViewById<Button>(R.id.button) // operations to be performed // when user tap on the button button?.setOnClickListener() { // displaying a toast message Toast.makeText(this@MainActivity, R.string.message, Toast.LENGTH_LONG).show() } }}
Output:
RISHU_MISHRA
anikaseth98
Android-Button
Kotlin Android
Picked
Android
Kotlin
Technical Scripter
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n17 Aug, 2021"
},
{
"code": null,
"e": 303,
"s": 54,
"text": "In Android applications, a Button is a user interface that is used to perform some action when clicked or tapped. It is a very common widget in Android and developers often use it. This article demonstrates how to create a button in Android Studio."
},
{
"code": null,
"e": 318,
"s": 303,
"text": "XML Attributes"
},
{
"code": null,
"e": 330,
"s": 318,
"text": "Description"
},
{
"code": null,
"e": 508,
"s": 330,
"text": "In this example step by step demonstration of creating a Button will be covered. The application will consist of a button that displays a toast message when the user taps on it."
},
{
"code": null,
"e": 574,
"s": 508,
"text": "Note: Following steps are performed on Android Studio version 4.0"
},
{
"code": null,
"e": 603,
"s": 574,
"text": "Step 1: Create a new project"
},
{
"code": null,
"e": 758,
"s": 603,
"text": "Click on File, then New => New Project.Choose “Empty Activity” for the project template.Select language as Kotlin.Select the minimum SDK as per your need."
},
{
"code": null,
"e": 798,
"s": 758,
"text": "Click on File, then New => New Project."
},
{
"code": null,
"e": 848,
"s": 798,
"text": "Choose “Empty Activity” for the project template."
},
{
"code": null,
"e": 875,
"s": 848,
"text": "Select language as Kotlin."
},
{
"code": null,
"e": 916,
"s": 875,
"text": "Select the minimum SDK as per your need."
},
{
"code": null,
"e": 952,
"s": 916,
"text": "Step 2: Modify the strings.xml file"
},
{
"code": null,
"e": 1138,
"s": 952,
"text": "Navigate to the strings.xml file under the “values” directory of the resource folder. This file will contain all strings that are used in the Application. Below is the appropriate code."
},
{
"code": null,
"e": 1142,
"s": 1138,
"text": "XML"
},
{
"code": "<resources> <string name=\"app_name\">GfG | Button In Kotlin</string> <string name=\"btn\">Button</string> <string name=\"message\">Hello Geeks!! This is a Button.</string></resources>",
"e": 1330,
"s": 1142,
"text": null
},
{
"code": null,
"e": 1373,
"s": 1330,
"text": " Step 3: Modify the activity_main.xml file"
},
{
"code": null,
"e": 1495,
"s": 1373,
"text": "Add a button widget in the layout of the activity. Below is the code of the activity_main.xml file which does the same. "
},
{
"code": null,
"e": 1499,
"s": 1495,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:background=\"#168BC34A\" tools:context=\".MainActivity\"> <!-- Button added in the activity --> <Button android:id=\"@+id/button\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:background=\"#4CAF50\" android:paddingStart=\"10dp\" android:paddingEnd=\"10dp\" android:text=\"@string/btn\" android:textColor=\"@android:color/background_light\" android:textSize=\"24sp\" app:layout_constraintBottom_toBottomOf=\"parent\" app:layout_constraintEnd_toEndOf=\"parent\" app:layout_constraintStart_toStartOf=\"parent\" app:layout_constraintTop_toTopOf=\"parent\" /> </androidx.constraintlayout.widget.ConstraintLayout>",
"e": 2564,
"s": 1499,
"text": null
},
{
"code": null,
"e": 2619,
"s": 2564,
"text": " Step 4: Accessing the button in the MainActivity file"
},
{
"code": null,
"e": 2805,
"s": 2619,
"text": "Add functionality of button in the MainActivity file. Here describe the operation to display a Toast message when the user taps on the button. Below is the code to carry out this task. "
},
{
"code": null,
"e": 2810,
"s": 2805,
"text": "Java"
},
{
"code": null,
"e": 2817,
"s": 2810,
"text": "Kotlin"
},
{
"code": "import androidx.appcompat.app.AppCompatActivity;import android.content.Context;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.Toast; public class MainActivity extends AppCompatActivity { @Override protected void onCreate( Bundle savedInstanceState ) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // storing ID of the button // in a variable Button button = (Button)findViewById(R.id.button); // operations to be performed // when user tap on the button if (button != null) { button.setOnClickListener((View.OnClickListener)(new View.OnClickListener() { public final void onClick(View it) { // displaying a toast message Toast.makeText((Context)MainActivity.this, R.string.message, Toast.LENGTH_LONG).show(); } })); } }}",
"e": 3793,
"s": 2817,
"text": null
},
{
"code": "import androidx.appcompat.app.AppCompatActivityimport android.os.Bundleimport android.widget.Buttonimport android.widget.Toast class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // storing ID of the button // in a variable val button = findViewById<Button>(R.id.button) // operations to be performed // when user tap on the button button?.setOnClickListener() { // displaying a toast message Toast.makeText(this@MainActivity, R.string.message, Toast.LENGTH_LONG).show() } }}",
"e": 4481,
"s": 3793,
"text": null
},
{
"code": null,
"e": 4489,
"s": 4481,
"text": "Output:"
},
{
"code": null,
"e": 4504,
"s": 4491,
"text": "RISHU_MISHRA"
},
{
"code": null,
"e": 4516,
"s": 4504,
"text": "anikaseth98"
},
{
"code": null,
"e": 4531,
"s": 4516,
"text": "Android-Button"
},
{
"code": null,
"e": 4546,
"s": 4531,
"text": "Kotlin Android"
},
{
"code": null,
"e": 4553,
"s": 4546,
"text": "Picked"
},
{
"code": null,
"e": 4561,
"s": 4553,
"text": "Android"
},
{
"code": null,
"e": 4568,
"s": 4561,
"text": "Kotlin"
},
{
"code": null,
"e": 4587,
"s": 4568,
"text": "Technical Scripter"
},
{
"code": null,
"e": 4595,
"s": 4587,
"text": "Android"
}
] |
Python: Iterating With Python Lambda | 19 Dec, 2021
In Python, the lambda function is an anonymous function. This one expression is evaluated and returned. Thus, We can use lambda functions as a function object. In this article, we will learn how to iterate with lambda in python.
Syntax:
lambda variable : expression
Where,
variable is used in the expressionexpression can be an mathematical expression
variable is used in the expression
expression can be an mathematical expression
Example 1:
In the below code, We make for loop to iterate over a list of numbers and find the square of each number and save it in the list. And then, print a list of square numbers.
Python3
# Iterating With Python Lambdas # list of numbersl1 = [4, 2, 13, 21, 5] l2 = [] # run for loop to iterate over listfor i in l1: # lambda function to make square # of number temp=lambda i:i**2 # save in list2 l2.append(temp(i)) # print listprint(l2)
Output:
[16, 4, 169, 441, 25]
Example 2:
We first iterate over the list using lambda and then find the square of each number. Here map function is used to iterate over list 1. And it passes each number in a single iterate. We then save it to a list using the list function.
Python3
# Iterating With Python Lambdas # list of numbersl1 = [4, 2, 13, 21, 5] # list of square of numbers# lambda function is used to iterate # over list l1l2 = list(map(lambda v: v ** 2, l1)) # print listprint(l2)
Output:
[16, 4, 169, 441, 25]
Example 3:
In the below code, we use map, filter, and lambda functions. We first find odd numbers from the list using filter and lambda functions. Then, we do to the square of it using map and lambda functions as we did in example 2.
Python3
# Iterating With Python Lambdas # list of numbersl1 = [4, 2, 13, 21, 5] # list of square of odd numbers# lambda function is used to iterate over list l1# filter is used to find odd numbersl2 = list(map(lambda v: v ** 2, filter(lambda u: u % 2, l1))) # print listprint(l2)
Output:
[169, 441, 25]
Picked
python-lambda
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n19 Dec, 2021"
},
{
"code": null,
"e": 282,
"s": 53,
"text": "In Python, the lambda function is an anonymous function. This one expression is evaluated and returned. Thus, We can use lambda functions as a function object. In this article, we will learn how to iterate with lambda in python."
},
{
"code": null,
"e": 290,
"s": 282,
"text": "Syntax:"
},
{
"code": null,
"e": 319,
"s": 290,
"text": "lambda variable : expression"
},
{
"code": null,
"e": 326,
"s": 319,
"text": "Where,"
},
{
"code": null,
"e": 405,
"s": 326,
"text": "variable is used in the expressionexpression can be an mathematical expression"
},
{
"code": null,
"e": 440,
"s": 405,
"text": "variable is used in the expression"
},
{
"code": null,
"e": 485,
"s": 440,
"text": "expression can be an mathematical expression"
},
{
"code": null,
"e": 496,
"s": 485,
"text": "Example 1:"
},
{
"code": null,
"e": 669,
"s": 496,
"text": " In the below code, We make for loop to iterate over a list of numbers and find the square of each number and save it in the list. And then, print a list of square numbers."
},
{
"code": null,
"e": 677,
"s": 669,
"text": "Python3"
},
{
"code": "# Iterating With Python Lambdas # list of numbersl1 = [4, 2, 13, 21, 5] l2 = [] # run for loop to iterate over listfor i in l1: # lambda function to make square # of number temp=lambda i:i**2 # save in list2 l2.append(temp(i)) # print listprint(l2)",
"e": 954,
"s": 677,
"text": null
},
{
"code": null,
"e": 962,
"s": 954,
"text": "Output:"
},
{
"code": null,
"e": 984,
"s": 962,
"text": "[16, 4, 169, 441, 25]"
},
{
"code": null,
"e": 995,
"s": 984,
"text": "Example 2:"
},
{
"code": null,
"e": 1229,
"s": 995,
"text": "We first iterate over the list using lambda and then find the square of each number. Here map function is used to iterate over list 1. And it passes each number in a single iterate. We then save it to a list using the list function. "
},
{
"code": null,
"e": 1237,
"s": 1229,
"text": "Python3"
},
{
"code": "# Iterating With Python Lambdas # list of numbersl1 = [4, 2, 13, 21, 5] # list of square of numbers# lambda function is used to iterate # over list l1l2 = list(map(lambda v: v ** 2, l1)) # print listprint(l2)",
"e": 1449,
"s": 1237,
"text": null
},
{
"code": null,
"e": 1457,
"s": 1449,
"text": "Output:"
},
{
"code": null,
"e": 1479,
"s": 1457,
"text": "[16, 4, 169, 441, 25]"
},
{
"code": null,
"e": 1490,
"s": 1479,
"text": "Example 3:"
},
{
"code": null,
"e": 1713,
"s": 1490,
"text": "In the below code, we use map, filter, and lambda functions. We first find odd numbers from the list using filter and lambda functions. Then, we do to the square of it using map and lambda functions as we did in example 2."
},
{
"code": null,
"e": 1721,
"s": 1713,
"text": "Python3"
},
{
"code": "# Iterating With Python Lambdas # list of numbersl1 = [4, 2, 13, 21, 5] # list of square of odd numbers# lambda function is used to iterate over list l1# filter is used to find odd numbersl2 = list(map(lambda v: v ** 2, filter(lambda u: u % 2, l1))) # print listprint(l2)",
"e": 1996,
"s": 1721,
"text": null
},
{
"code": null,
"e": 2004,
"s": 1996,
"text": "Output:"
},
{
"code": null,
"e": 2019,
"s": 2004,
"text": "[169, 441, 25]"
},
{
"code": null,
"e": 2026,
"s": 2019,
"text": "Picked"
},
{
"code": null,
"e": 2040,
"s": 2026,
"text": "python-lambda"
},
{
"code": null,
"e": 2047,
"s": 2040,
"text": "Python"
}
] |
Scala Map transform() method with example | 13 Aug, 2019
The transform() method is utilized to transform the elements of the map into a mutable map.
Method Definition: def transform(f: (K, V) => V): Map.this.type
Return Type: It transforms all the elements of the map and returns them into a mutable map.
Example #1:
// Scala program of transform()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Creating a map val m1 = Map(3 -> "geeks", 4 -> "for", 2 -> "cs") // Applying transform method val result = m1.transform((key,value) => value.toUpperCase) // Displays output println(result) }}
Map(3 -> GEEKS, 4 -> FOR, 2 -> CS)
Example #2:
// Scala program of transform()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Creating a map val m1 = Map(3 -> "geeks", 4 -> "for", 4 -> "for") // Applying transform method val result = m1.transform((key,value) => value.toUpperCase) // Displays output println(result) }}
Map(3 -> GEEKS, 4 -> FOR)
Scala
Scala-Map
Scala-Method
Scala
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Class and Object in Scala
Type Casting in Scala
Scala Tutorial – Learn Scala with Step By Step Guide
Scala Lists
Operators in Scala
Scala | Arrays
Scala Constructors
Scala String substring() method with example
Lambda Expression in Scala
Scala Singleton and Companion Objects | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n13 Aug, 2019"
},
{
"code": null,
"e": 120,
"s": 28,
"text": "The transform() method is utilized to transform the elements of the map into a mutable map."
},
{
"code": null,
"e": 184,
"s": 120,
"text": "Method Definition: def transform(f: (K, V) => V): Map.this.type"
},
{
"code": null,
"e": 276,
"s": 184,
"text": "Return Type: It transforms all the elements of the map and returns them into a mutable map."
},
{
"code": null,
"e": 288,
"s": 276,
"text": "Example #1:"
},
{
"code": "// Scala program of transform()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Creating a map val m1 = Map(3 -> \"geeks\", 4 -> \"for\", 2 -> \"cs\") // Applying transform method val result = m1.transform((key,value) => value.toUpperCase) // Displays output println(result) }}",
"e": 690,
"s": 288,
"text": null
},
{
"code": null,
"e": 726,
"s": 690,
"text": "Map(3 -> GEEKS, 4 -> FOR, 2 -> CS)\n"
},
{
"code": null,
"e": 738,
"s": 726,
"text": "Example #2:"
},
{
"code": "// Scala program of transform()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Creating a map val m1 = Map(3 -> \"geeks\", 4 -> \"for\", 4 -> \"for\") // Applying transform method val result = m1.transform((key,value) => value.toUpperCase) // Displays output println(result) }}",
"e": 1141,
"s": 738,
"text": null
},
{
"code": null,
"e": 1168,
"s": 1141,
"text": "Map(3 -> GEEKS, 4 -> FOR)\n"
},
{
"code": null,
"e": 1174,
"s": 1168,
"text": "Scala"
},
{
"code": null,
"e": 1184,
"s": 1174,
"text": "Scala-Map"
},
{
"code": null,
"e": 1197,
"s": 1184,
"text": "Scala-Method"
},
{
"code": null,
"e": 1203,
"s": 1197,
"text": "Scala"
},
{
"code": null,
"e": 1301,
"s": 1203,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1327,
"s": 1301,
"text": "Class and Object in Scala"
},
{
"code": null,
"e": 1349,
"s": 1327,
"text": "Type Casting in Scala"
},
{
"code": null,
"e": 1402,
"s": 1349,
"text": "Scala Tutorial – Learn Scala with Step By Step Guide"
},
{
"code": null,
"e": 1414,
"s": 1402,
"text": "Scala Lists"
},
{
"code": null,
"e": 1433,
"s": 1414,
"text": "Operators in Scala"
},
{
"code": null,
"e": 1448,
"s": 1433,
"text": "Scala | Arrays"
},
{
"code": null,
"e": 1467,
"s": 1448,
"text": "Scala Constructors"
},
{
"code": null,
"e": 1512,
"s": 1467,
"text": "Scala String substring() method with example"
},
{
"code": null,
"e": 1539,
"s": 1512,
"text": "Lambda Expression in Scala"
}
] |
How to implement HorizontalScrollView like Gallery in Android? | Before getting into an example, we should know what is Horizontal Scroll View. Horizontal Scrollview provides by android.widget.HorizontalScrollView class. It is used to scroll child views in a horizontal direction.
This example demonstrates how to use horizontal Scroll view.
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"
android:layout_width="match_parent"
android:id="@+id/layout"
android:layout_height="match_parent">
<HorizontalScrollView
android:layout_width="match_parent"
android:layout_height="300dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:layout_width="300dp"
android:background="#c1c1c1"
android:layout_height="match_parent"
android:src="@drawable/a"/>
<ImageView
android:layout_width="300dp"
android:background="#c1c1c1"
android:layout_height="match_parent"
android:layout_marginLeft="30dp"
android:src="@drawable/b"/>
<ImageView
android:layout_width="300dp"
android:background="#c1c1c1"
android:layout_height="match_parent"
android:layout_marginLeft="30dp"
android:src="@drawable/c"/>
<ImageView
android:layout_width="300dp"
android:background="#c1c1c1"
android:layout_height="match_parent"
android:layout_marginLeft="30dp"
android:src="@drawable/d"/>
<ImageView
android:layout_width="300dp"
android:background="#c1c1c1"
android:layout_height="match_parent"
android:layout_marginLeft="30dp"
android:src="@drawable/e"/>
</LinearLayout>
</HorizontalScrollView>
</LinearLayout>
In this above code we have declare Linear layout as parent and added Horizontal Scroll view. Horizontal scroll view going to scroll its child view in horizontal direction so we have created Linear layout as a child for horizontal scroll view and added child for linear layout. We have given five child images views to scroll.
Step 3 − No need to change manifest.xml and activities.
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 −
In the above result is initial screen when you scroll horizontally it will scroll as shown below image-
In the above result, we are scrolling image views horizontally.
At finally it will reach to the last position of horizontal scroll view as show above.
Click here to download the project code | [
{
"code": null,
"e": 1278,
"s": 1062,
"text": "Before getting into an example, we should know what is Horizontal Scroll View. Horizontal Scrollview provides by android.widget.HorizontalScrollView class. It is used to scroll child views in a horizontal direction."
},
{
"code": null,
"e": 1339,
"s": 1278,
"text": "This example demonstrates how to use horizontal Scroll view."
},
{
"code": null,
"e": 1468,
"s": 1339,
"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": 1533,
"s": 1468,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 3169,
"s": 1533,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n android:layout_width=\"match_parent\"\n android:id=\"@+id/layout\"\n android:layout_height=\"match_parent\">\n <HorizontalScrollView\n android:layout_width=\"match_parent\"\n android:layout_height=\"300dp\">\n <LinearLayout\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\">\n <ImageView\n android:layout_width=\"300dp\"\n android:background=\"#c1c1c1\"\n android:layout_height=\"match_parent\"\n android:src=\"@drawable/a\"/>\n <ImageView\n android:layout_width=\"300dp\"\n android:background=\"#c1c1c1\"\n android:layout_height=\"match_parent\"\n android:layout_marginLeft=\"30dp\"\n android:src=\"@drawable/b\"/>\n <ImageView\n android:layout_width=\"300dp\"\n android:background=\"#c1c1c1\"\n android:layout_height=\"match_parent\"\n android:layout_marginLeft=\"30dp\"\n android:src=\"@drawable/c\"/>\n <ImageView\n android:layout_width=\"300dp\"\n android:background=\"#c1c1c1\"\n android:layout_height=\"match_parent\"\n android:layout_marginLeft=\"30dp\"\n android:src=\"@drawable/d\"/>\n <ImageView\n android:layout_width=\"300dp\"\n android:background=\"#c1c1c1\"\n android:layout_height=\"match_parent\"\n android:layout_marginLeft=\"30dp\"\n android:src=\"@drawable/e\"/>\n </LinearLayout>\n </HorizontalScrollView>\n</LinearLayout>"
},
{
"code": null,
"e": 3495,
"s": 3169,
"text": "In this above code we have declare Linear layout as parent and added Horizontal Scroll view. Horizontal scroll view going to scroll its child view in horizontal direction so we have created Linear layout as a child for horizontal scroll view and added child for linear layout. We have given five child images views to scroll."
},
{
"code": null,
"e": 3551,
"s": 3495,
"text": "Step 3 − No need to change manifest.xml and activities."
},
{
"code": null,
"e": 3898,
"s": 3551,
"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": 4002,
"s": 3898,
"text": "In the above result is initial screen when you scroll horizontally it will scroll as shown below image-"
},
{
"code": null,
"e": 4066,
"s": 4002,
"text": "In the above result, we are scrolling image views horizontally."
},
{
"code": null,
"e": 4153,
"s": 4066,
"text": "At finally it will reach to the last position of horizontal scroll view as show above."
},
{
"code": null,
"e": 4193,
"s": 4153,
"text": "Click here to download the project code"
}
] |
2 Easy Ways to Get Tables From a Website with Pandas | by Byron Dolon | Towards Data Science | The pandas library is well known for its easy-to-use data analysis capabilities. It’s equipped with advanced indexing, DataFrame joining and data aggregation features. Pandas also has a comprehensive I/O API that you can use to input data from various sources and output data to various formats.
There are many occasions when you just need to get a table from a website to use in your analysis. Here’s a look at how you can use the pandas read_html and read_clipboard to get tables from websites with just a couple lines of code.
Note, before trying any of the code below, don’t forget to import pandas.
import pandas as pd
Let’s try getting this table with key Tesla executives for this example:
The read_html function has this description:
Read HTML tables into a list of DataFrame objects.
The function searches for HTML <table> related tags on the input (URL) you provide. It always returns a list, even if the site only has one table. To use the function, all you need to do is put the URL of the site you want as the first argument of the function. Running the function for the Yahoo Finance site looks like this:
pd.read_html('https://finance.yahoo.com/quote/TSLA/profile?p=TSLA')
To get a DataFrame from this list, you only need to make one addition:
pd.read_html('https://finance.yahoo.com/quote/TSLA/profile?p=TSLA')[0]
Adding the ‘[0]’ selects the first element in the list. There is only one element in our list, and it is a DataFrame object. Running this code gives you this output:
Now, let’s try getting this table with summary statistics for the Tesla stock:
We’ll try the same code as before:
pd.read_html('https://finance.yahoo.com/quote/TSLA?p=TSLA')
It looks like we got all the data we need, but there are two elements in the list now. This is because the table we see in the screenshot above is separated into two different tables in the HTML source code. We could do the same index trick as before, but if you want to combine both tables into one, all you need to do is concatenate the two list elements like this:
separate = pd.read_html('https://finance.yahoo.com/quote/TSLA?p=TSLA')pd.concat([separate[0],separate[1]])
There’s plenty more you could do to process this data for analysis- just renaming the column headers would be a great start. But getting this far took about 12 seconds, which is great if you just need test data from a static site.
Here’s a table with S&P 500 company information we can try to get:
The data is distributed under an ODC license, which means it’s free to share, create, and adapt the data on the site. I was initially going to use this site for my read_html example, but after I ran the function for the third time, I was greeted with an error.
pd.read_html('https://datahub.io/core/s-and-p-500-companies')
The HTTP 403 error happens when you try to access a webpage and the site successfully understands your request, but will not authorize it. This can occur when you try to access a site that you don’t have access to.
In this case, you can access the site from your browser, but the site won’t let you access it from a script. Many sites have rules about scraping on their “robots.txt” file, which you can find by appending “/robots.txt” after the top-level domain of the site’s URL. For example, Facebook’s would be “https://facebook.com/robots.txt”.
To avoid an error like this, you might be tempted to copy the data onto an Excel sheet, then load that file with the pd.read_excel function.
Instead, pandas offers a feature that allows you to copy data directly from your clipboard! The read_clipboard function has this description:
Read text from clipboard and pass to read_csv
If you’ve used pandas before, you’ve probably used pd.read_csv to get a local file for use in data analysis. The read_clipboard function just takes the text you have copied and treats it as if it were a csv. It will return a DataFrame based on the text you copied.
To get the S&P 500 table from datahub.io, select and copy the table from your browser, then enter the code below.
pd.read_clipboard()
Perfect! We’ve got a ready to use DataFrame, exactly as seen from the website!
You can check out the read_html and read_clipboard documentation for more information. There, you’ll find that there’s a lot more you can do with these functions to customize exactly how you want to input data from websites.
Good luck with your I/O! | [
{
"code": null,
"e": 468,
"s": 172,
"text": "The pandas library is well known for its easy-to-use data analysis capabilities. It’s equipped with advanced indexing, DataFrame joining and data aggregation features. Pandas also has a comprehensive I/O API that you can use to input data from various sources and output data to various formats."
},
{
"code": null,
"e": 702,
"s": 468,
"text": "There are many occasions when you just need to get a table from a website to use in your analysis. Here’s a look at how you can use the pandas read_html and read_clipboard to get tables from websites with just a couple lines of code."
},
{
"code": null,
"e": 776,
"s": 702,
"text": "Note, before trying any of the code below, don’t forget to import pandas."
},
{
"code": null,
"e": 796,
"s": 776,
"text": "import pandas as pd"
},
{
"code": null,
"e": 869,
"s": 796,
"text": "Let’s try getting this table with key Tesla executives for this example:"
},
{
"code": null,
"e": 914,
"s": 869,
"text": "The read_html function has this description:"
},
{
"code": null,
"e": 965,
"s": 914,
"text": "Read HTML tables into a list of DataFrame objects."
},
{
"code": null,
"e": 1292,
"s": 965,
"text": "The function searches for HTML <table> related tags on the input (URL) you provide. It always returns a list, even if the site only has one table. To use the function, all you need to do is put the URL of the site you want as the first argument of the function. Running the function for the Yahoo Finance site looks like this:"
},
{
"code": null,
"e": 1360,
"s": 1292,
"text": "pd.read_html('https://finance.yahoo.com/quote/TSLA/profile?p=TSLA')"
},
{
"code": null,
"e": 1431,
"s": 1360,
"text": "To get a DataFrame from this list, you only need to make one addition:"
},
{
"code": null,
"e": 1502,
"s": 1431,
"text": "pd.read_html('https://finance.yahoo.com/quote/TSLA/profile?p=TSLA')[0]"
},
{
"code": null,
"e": 1668,
"s": 1502,
"text": "Adding the ‘[0]’ selects the first element in the list. There is only one element in our list, and it is a DataFrame object. Running this code gives you this output:"
},
{
"code": null,
"e": 1747,
"s": 1668,
"text": "Now, let’s try getting this table with summary statistics for the Tesla stock:"
},
{
"code": null,
"e": 1782,
"s": 1747,
"text": "We’ll try the same code as before:"
},
{
"code": null,
"e": 1842,
"s": 1782,
"text": "pd.read_html('https://finance.yahoo.com/quote/TSLA?p=TSLA')"
},
{
"code": null,
"e": 2210,
"s": 1842,
"text": "It looks like we got all the data we need, but there are two elements in the list now. This is because the table we see in the screenshot above is separated into two different tables in the HTML source code. We could do the same index trick as before, but if you want to combine both tables into one, all you need to do is concatenate the two list elements like this:"
},
{
"code": null,
"e": 2317,
"s": 2210,
"text": "separate = pd.read_html('https://finance.yahoo.com/quote/TSLA?p=TSLA')pd.concat([separate[0],separate[1]])"
},
{
"code": null,
"e": 2548,
"s": 2317,
"text": "There’s plenty more you could do to process this data for analysis- just renaming the column headers would be a great start. But getting this far took about 12 seconds, which is great if you just need test data from a static site."
},
{
"code": null,
"e": 2615,
"s": 2548,
"text": "Here’s a table with S&P 500 company information we can try to get:"
},
{
"code": null,
"e": 2876,
"s": 2615,
"text": "The data is distributed under an ODC license, which means it’s free to share, create, and adapt the data on the site. I was initially going to use this site for my read_html example, but after I ran the function for the third time, I was greeted with an error."
},
{
"code": null,
"e": 2938,
"s": 2876,
"text": "pd.read_html('https://datahub.io/core/s-and-p-500-companies')"
},
{
"code": null,
"e": 3153,
"s": 2938,
"text": "The HTTP 403 error happens when you try to access a webpage and the site successfully understands your request, but will not authorize it. This can occur when you try to access a site that you don’t have access to."
},
{
"code": null,
"e": 3487,
"s": 3153,
"text": "In this case, you can access the site from your browser, but the site won’t let you access it from a script. Many sites have rules about scraping on their “robots.txt” file, which you can find by appending “/robots.txt” after the top-level domain of the site’s URL. For example, Facebook’s would be “https://facebook.com/robots.txt”."
},
{
"code": null,
"e": 3628,
"s": 3487,
"text": "To avoid an error like this, you might be tempted to copy the data onto an Excel sheet, then load that file with the pd.read_excel function."
},
{
"code": null,
"e": 3770,
"s": 3628,
"text": "Instead, pandas offers a feature that allows you to copy data directly from your clipboard! The read_clipboard function has this description:"
},
{
"code": null,
"e": 3816,
"s": 3770,
"text": "Read text from clipboard and pass to read_csv"
},
{
"code": null,
"e": 4081,
"s": 3816,
"text": "If you’ve used pandas before, you’ve probably used pd.read_csv to get a local file for use in data analysis. The read_clipboard function just takes the text you have copied and treats it as if it were a csv. It will return a DataFrame based on the text you copied."
},
{
"code": null,
"e": 4195,
"s": 4081,
"text": "To get the S&P 500 table from datahub.io, select and copy the table from your browser, then enter the code below."
},
{
"code": null,
"e": 4215,
"s": 4195,
"text": "pd.read_clipboard()"
},
{
"code": null,
"e": 4294,
"s": 4215,
"text": "Perfect! We’ve got a ready to use DataFrame, exactly as seen from the website!"
},
{
"code": null,
"e": 4519,
"s": 4294,
"text": "You can check out the read_html and read_clipboard documentation for more information. There, you’ll find that there’s a lot more you can do with these functions to customize exactly how you want to input data from websites."
}
] |
Python Program for n-th Fibonacci number | In this article, we will compute the nth Fibonacci number.
A Fibonacci number is defined by the recurrence relation given below −
Fn = Fn-1 + Fn-2
With F0= 0 and F1 = 1.
First, few Fibonacci numbers are
0,1,1,2,3,5,8,13,..................
We can compute the Fibonacci numbers using the method of recursion and dynamic programming.
Now let’s see the implementation in the form of Python script
Live Demo
#recursive approach
def Fibonacci(n):
if n<0:
print("Fibbonacci can't be computed")
# First Fibonacci number
elif n==1:
return 0
# Second Fibonacci number
elif n==2:
return 1
else:
return Fibonacci(n-1)+Fibonacci(n-2)
# main
n=10
print(Fibonacci(n))
34
The scope of all the variables declared is shown below.
Live Demo
#dynamic approach
Fib_Array = [0,1]
def fibonacci(n):
if n<0:
print("Fibbonacci can't be computed")
elif n<=len(Fib_Array):
return Fib_Array[n-1]
else:
temp = fibonacci(n-1)+fibonacci(n-2)
Fib_Array.append(temp)
return temp
# Driver Program
n=10
print(fibonacci(n))
34
The scope of all the variables declared is shown below
In this article, we learned about the computation of nth Fibonacci number using recursion and dynamic programming approach. | [
{
"code": null,
"e": 1121,
"s": 1062,
"text": "In this article, we will compute the nth Fibonacci number."
},
{
"code": null,
"e": 1192,
"s": 1121,
"text": "A Fibonacci number is defined by the recurrence relation given below −"
},
{
"code": null,
"e": 1209,
"s": 1192,
"text": "Fn = Fn-1 + Fn-2"
},
{
"code": null,
"e": 1232,
"s": 1209,
"text": "With F0= 0 and F1 = 1."
},
{
"code": null,
"e": 1265,
"s": 1232,
"text": "First, few Fibonacci numbers are"
},
{
"code": null,
"e": 1301,
"s": 1265,
"text": "0,1,1,2,3,5,8,13,.................."
},
{
"code": null,
"e": 1393,
"s": 1301,
"text": "We can compute the Fibonacci numbers using the method of recursion and dynamic programming."
},
{
"code": null,
"e": 1455,
"s": 1393,
"text": "Now let’s see the implementation in the form of Python script"
},
{
"code": null,
"e": 1466,
"s": 1455,
"text": " Live Demo"
},
{
"code": null,
"e": 1758,
"s": 1466,
"text": "#recursive approach\ndef Fibonacci(n):\n if n<0:\n print(\"Fibbonacci can't be computed\")\n # First Fibonacci number\n elif n==1:\n return 0\n # Second Fibonacci number\n elif n==2:\n return 1\n else:\n return Fibonacci(n-1)+Fibonacci(n-2)\n# main\nn=10\nprint(Fibonacci(n))"
},
{
"code": null,
"e": 1761,
"s": 1758,
"text": "34"
},
{
"code": null,
"e": 1817,
"s": 1761,
"text": "The scope of all the variables declared is shown below."
},
{
"code": null,
"e": 1828,
"s": 1817,
"text": " Live Demo"
},
{
"code": null,
"e": 2133,
"s": 1828,
"text": "#dynamic approach\nFib_Array = [0,1]\ndef fibonacci(n):\n if n<0:\n print(\"Fibbonacci can't be computed\")\n elif n<=len(Fib_Array):\n return Fib_Array[n-1]\n else:\n temp = fibonacci(n-1)+fibonacci(n-2)\n Fib_Array.append(temp)\n return temp\n# Driver Program\nn=10\nprint(fibonacci(n))"
},
{
"code": null,
"e": 2136,
"s": 2133,
"text": "34"
},
{
"code": null,
"e": 2191,
"s": 2136,
"text": "The scope of all the variables declared is shown below"
},
{
"code": null,
"e": 2315,
"s": 2191,
"text": "In this article, we learned about the computation of nth Fibonacci number using recursion and dynamic programming approach."
}
] |
C++ String Library - push_back | It appends character c to the end of the string, increasing its length by one.
Following is the declaration for std::string::push_back.
void push_back (char c);
void push_back (char c);
void push_back (char c);
c − It is a character object.
none
if an exception is thrown, there are no changes in the string.
In below example for std::string::push_back.
#include <iostream>
#include <fstream>
#include <string>
int main () {
std::string str;
std::ifstream file ("sample.txt",std::ios::in);
if (file) {
while (!file.eof()) str.push_back(file.get());
}
std::cout << str << '\n';
return 0;
}
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2682,
"s": 2603,
"text": "It appends character c to the end of the string, increasing its length by one."
},
{
"code": null,
"e": 2739,
"s": 2682,
"text": "Following is the declaration for std::string::push_back."
},
{
"code": null,
"e": 2764,
"s": 2739,
"text": "void push_back (char c);"
},
{
"code": null,
"e": 2789,
"s": 2764,
"text": "void push_back (char c);"
},
{
"code": null,
"e": 2814,
"s": 2789,
"text": "void push_back (char c);"
},
{
"code": null,
"e": 2844,
"s": 2814,
"text": "c − It is a character object."
},
{
"code": null,
"e": 2849,
"s": 2844,
"text": "none"
},
{
"code": null,
"e": 2912,
"s": 2849,
"text": "if an exception is thrown, there are no changes in the string."
},
{
"code": null,
"e": 2957,
"s": 2912,
"text": "In below example for std::string::push_back."
},
{
"code": null,
"e": 3217,
"s": 2957,
"text": "#include <iostream>\n#include <fstream>\n#include <string>\n\nint main () {\n std::string str;\n std::ifstream file (\"sample.txt\",std::ios::in);\n if (file) {\n while (!file.eof()) str.push_back(file.get());\n }\n std::cout << str << '\\n';\n return 0;\n}"
},
{
"code": null,
"e": 3224,
"s": 3217,
"text": " Print"
},
{
"code": null,
"e": 3235,
"s": 3224,
"text": " Add Notes"
}
] |
Centering x-tick labels between tick marks in Matplotlib | To place labels between two ticks, we can take the following steps−
Load some sample data, r.
Create a copy of the array, cast to a specified type.
Create a figure and a set of subplots using subplots() method.
Plot date and r sample data.
Set the locator of the major/minor ticker using set_major_locator() and set_minor_locator() methods.
Set the locator of the major/minor formatter using set_major_locator() and set_minor_formatter() methods.
Now, place the ticklabel at the center.
To display the figure, use show() method.
import numpy as np
import matplotlib.cbook as cbook
import matplotlib.dates as dates
import matplotlib.ticker as ticker
import matplotlib.pyplot as plt
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
with cbook.get_sample_data('aapl.npz') as fh:
r = np.load(fh)['price_data'].view(np.recarray)
r = r[-250:]
date = r.date.astype('O')
fig, ax = plt.subplots()
ax.plot(date, r.adj_close)
ax.xaxis.set_major_locator(dates.MonthLocator())
ax.xaxis.set_minor_locator(dates.MonthLocator(bymonthday=15))
ax.xaxis.set_major_formatter(ticker.NullFormatter())
ax.xaxis.set_minor_formatter(dates.DateFormatter('%b'))
for tick in ax.xaxis.get_minor_ticks():
tick.tick1line.set_markersize(0)
tick.tick2line.set_markersize(0)
tick.label1.set_horizontalalignment('center')
imid = len(r) // 2
ax.set_xlabel(str(date[imid].year))
plt.show() | [
{
"code": null,
"e": 1130,
"s": 1062,
"text": "To place labels between two ticks, we can take the following steps−"
},
{
"code": null,
"e": 1156,
"s": 1130,
"text": "Load some sample data, r."
},
{
"code": null,
"e": 1210,
"s": 1156,
"text": "Create a copy of the array, cast to a specified type."
},
{
"code": null,
"e": 1273,
"s": 1210,
"text": "Create a figure and a set of subplots using subplots() method."
},
{
"code": null,
"e": 1302,
"s": 1273,
"text": "Plot date and r sample data."
},
{
"code": null,
"e": 1403,
"s": 1302,
"text": "Set the locator of the major/minor ticker using set_major_locator() and set_minor_locator() methods."
},
{
"code": null,
"e": 1509,
"s": 1403,
"text": "Set the locator of the major/minor formatter using set_major_locator() and set_minor_formatter() methods."
},
{
"code": null,
"e": 1549,
"s": 1509,
"text": "Now, place the ticklabel at the center."
},
{
"code": null,
"e": 1591,
"s": 1549,
"text": "To display the figure, use show() method."
},
{
"code": null,
"e": 2465,
"s": 1591,
"text": "import numpy as np\nimport matplotlib.cbook as cbook\nimport matplotlib.dates as dates\nimport matplotlib.ticker as ticker\nimport matplotlib.pyplot as plt\nplt.rcParams[\"figure.figsize\"] = [7.00, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\nwith cbook.get_sample_data('aapl.npz') as fh:\n r = np.load(fh)['price_data'].view(np.recarray)\nr = r[-250:]\ndate = r.date.astype('O')\nfig, ax = plt.subplots()\nax.plot(date, r.adj_close)\nax.xaxis.set_major_locator(dates.MonthLocator())\nax.xaxis.set_minor_locator(dates.MonthLocator(bymonthday=15))\nax.xaxis.set_major_formatter(ticker.NullFormatter())\nax.xaxis.set_minor_formatter(dates.DateFormatter('%b'))\nfor tick in ax.xaxis.get_minor_ticks():\n tick.tick1line.set_markersize(0)\n tick.tick2line.set_markersize(0)\n tick.label1.set_horizontalalignment('center')\nimid = len(r) // 2\nax.set_xlabel(str(date[imid].year))\nplt.show()"
}
] |
Data Cleaning, Merging, and Wrangling in R | by Michael Grogan | Towards Data Science | One of the big issues when it comes to working with data in any context is the issue of data cleaning and merging of datasets, since it is often the case that you will find yourself having to collate data across multiple files, and will need to rely on R to carry out functions that you would normally carry out using commands like VLOOKUP in Excel.
Here are some useful examples of how R can be used for data manipulation. While Python’s pandas library has traditionally been regarded as the winner in this area, the data manipulation techniques frequently used with R can actually be quite powerful.
Let’s take a look at some of them.
For examples 1–7, we have two datasets:
sales: This file contains the variables Date, ID (which is Product ID), and Sales. We load this into R under the name mydata.
customers: This file contains the variables ID, Age, and Country. We load this into R under the name mydata2.
These datasets are available at the following GitHub repository.
The following are examples of popular techniques employed in R to clean a dataset, along with how to format variables effectively to facilitate analysis. The below functions work particularly well with panel datasets, where we have a mixture of cross-sectional and time series data.
To start off with a simple example, let us choose the customers dataset. Suppose that we only wish to include the variables ID and Age in our data. To do this, we define our data frame as follows:
dataframe<-data.frame(ID,Age)
Often times, it is necessary to combine two variables from different datasets similar to how VLOOKUP is used in Excel to join two variables based on certain criteria. If you are unfamiliar with the VLOOKUP function, then you might find this guide from Spreadsheeto particularly helpful.
In R, this can be done using the merge function.
For instance, suppose that we wish to link the Date variable in the sales dataset with the Age and Country variables in the customers dataset — with the ID variable being the common link.
Therefore, we do as follows:
mergeinfo<-merge(mydata[, c("ID", "Sales")],mydata2[, c("ID", "Age", "Country")])
Upon doing this, we see that a new dataset is formed in R joining our chosen variables:
3. Using as.date to format dates and calculate duration
Suppose that we now wish to calculate the number of days between the current date and the date of sale as listed in the sales file. In order to accomplish this, we can use as.date as follows:
currentdate=as.Date('2016-12-15')dateinfile=as.Date(Date)Duration=currentdate-dateinfile
Going back to the example above, suppose that we now wish to combine this duration variable with the rest of our data.
Hence, we can now combine our new Duration variable with the merge function as above, and can do this as follows:
durationasdouble=as.double.difftime(Duration, units='days')updateddataframe=data.frame(ID,Sales,Date,durationasdouble)updateddataframe
4. Using as.POSIXct and format to calculate differences between seconds
While it is not the case in the above example, a situation can often occur where we have dates which include the time, e.g. “2016–10–13 19:30:55”.
There may be times where we wish to find differences between seconds of two dates. In this regard, as.POSIXct is a more suitable option than as.Date. For instance, we can first format our date as follows:
date_converted<-format(Date, format="%Y-%m-%d %H:%M:%S")new_date_variable<-as.POSIXct(date_converted)seconds<-diff(new_date_variable,1)
When we define our seconds variable, it will now give us the difference between two dates in seconds. Then, it is a matter of simple arithmetic to obtain the difference in minutes and seconds.
minutes<-seconds/60hours<-minutes/60
5. grepl: Remove instances of a string from a variables
Let us look to the Country variable. Suppose that we wish to remove all instances of “Greenland” from our variable. This is accomplished using the grepl command:
countryremoved<-mydata2[!grepl("Greenland", mydata2$Country),]
6. Delete observations using head and tail functions
The head and tail functions can be used if we wish to delete certain observations from a variable, e.g. Sales. The head function allows us to delete the first 30 rows, while the tail function allows us to delete the last 30 rows.
When it comes to using a variable edited in this way for calculation purposes, e.g. a regression, the as.matrix function is also used to convert the variable into matrix format:
Salesminus30days←head(Sales,-30)X1=as.matrix(Salesminus30days)X1 Salesplus30days<-tail(Sales,-30)X2=as.matrix(Salesplus30days)X2
7. Replicate SUMIF using the “aggregate” function
names <- c("John", "Elizabeth", "Michael", "John", "Elizabeth", "Michael")webvisitsframe <- cbind("24","32","40","71","65","63")webvisits=as.numeric(webvisitsframe)minutesspentframe <- cbind("20", "41", "5", "6", "48", "97")minutesspent=as.numeric(minutesspentframe)
Let us suppose that we have created the following table as below, and want to obtain the sum of web visits and minutes spent on a website in any particular period:
In this instance, we can replicate the SUMIF function in Excel (where the values associated with a specific identifier are summed up) by using the aggregate function in R. This can be done as follows (where raw_table is the table specified as above):
sumif_table<-aggregate(. ~ names, data=raw_table, sum)sumif_table
Thus, the values associated with identifiers (in this case, names) are summed up as follows:
As per the examples at Stack Overflow, the plyr and data.table libraries can also be used to accomplish the same result as follows:
library(plyr)ddply(nametable, .(names), summarise, Sum_webvisits = sum(webvisits), Sum_minutesspent = sum(minutesspent)) library(data.table)DT <- as.data.table(nametable)DT[ , lapply(.SD, sum), by = "names"]
8. Calculate lags using the diff() function
When it comes to doing time series analysis, often times it is necessary to calculate lags for a specific variable. To do this in R, we use the diff() function.
For the purposes of this example, we create a matrix with price data for the column names, along with years as our row names:
pricedata <- matrix(c(102, 90, 84, 130, 45), ncol=1)colnames(pricedata) <- c('Price')rownames(pricedata) <- c('2012', '2013', '2014', '2015', '2016')pricedata.table <- as.table(pricedata)pricedata.tableYear Price2012 1022013 902014 842015 1302016 452. Lag = 1diff(pricedata.table,1)Year Price2013 -122014 -62015 462016 -853. Lag = 2diff(pricedata.table,2)Year Price2014 -182015 402016 -394. Differences = 2diff(pricedata.table,differences=2)Year Price2014 62015 522016 131
9. Separating by list (useful for panel datasets)
Suppose we have a dataset that needs to be separated, e.g. by ID. Doing this manually would make for quite a messy process. Instead, we can do so using the unique and split functions to form a list. Here is an example of how this would be done.
Using a data frame of dates, names, and IDs:
> Date<-c("20/02/2017","21/02/2017","22/02/2017","20/02/2017","21/02/2017","22/02/2017")> ID<-c("20","20","20","40","40","40")> Name<-c("Brian","Brian","Brian","Adam","Adam","Adam")> df<-data.frame(Date,ID,Name)> df Date ID Name1 20/02/2017 20 Brian2 21/02/2017 20 Brian3 22/02/2017 20 Brian4 20/02/2017 40 Adam5 21/02/2017 40 Adam6 22/02/2017 40 Adam
However, we would like to separate the observations into two separate lists by filtering by ID. We would do this as below:
> listofids=as.character(unique(df$ID))> mylist <- split(df, df$ID)> mylist $`20` Date ID Name1 20/02/2017 20 Brian2 21/02/2017 20 Brian3 22/02/2017 20 Brian$`40` Date ID Name4 20/02/2017 40 Adam5 21/02/2017 40 Adam6 22/02/2017 40 Adam
This is the list in its entirety. If we wished to call one at a time (by ID as our unique identifier, we can do so as follows:
> mylist[1]$`20` Date ID Name1 20/02/2017 20 Brian2 21/02/2017 20 Brian3 22/02/2017 20 Brian> mylist[2]$`40` Date ID Name4 20/02/2017 40 Adam5 21/02/2017 40 Adam6 22/02/2017 40 Adam
The above examples have illustrated various ways in which we can conduct data manipulation procedures in R, and techniques for replicating common Excel functions such as VLOOKUP. Many thanks for your time, and once again the associated GitHub repository for the above examples is available here.
You can also find more of my data science content at michael-grogan.com.
Disclaimer: This article is written on an “as is” basis and without warranty. It was written with the intention of providing an overview of data science concepts, and should not be interpreted as professional advice in any way. | [
{
"code": null,
"e": 521,
"s": 171,
"text": "One of the big issues when it comes to working with data in any context is the issue of data cleaning and merging of datasets, since it is often the case that you will find yourself having to collate data across multiple files, and will need to rely on R to carry out functions that you would normally carry out using commands like VLOOKUP in Excel."
},
{
"code": null,
"e": 773,
"s": 521,
"text": "Here are some useful examples of how R can be used for data manipulation. While Python’s pandas library has traditionally been regarded as the winner in this area, the data manipulation techniques frequently used with R can actually be quite powerful."
},
{
"code": null,
"e": 808,
"s": 773,
"text": "Let’s take a look at some of them."
},
{
"code": null,
"e": 848,
"s": 808,
"text": "For examples 1–7, we have two datasets:"
},
{
"code": null,
"e": 974,
"s": 848,
"text": "sales: This file contains the variables Date, ID (which is Product ID), and Sales. We load this into R under the name mydata."
},
{
"code": null,
"e": 1084,
"s": 974,
"text": "customers: This file contains the variables ID, Age, and Country. We load this into R under the name mydata2."
},
{
"code": null,
"e": 1149,
"s": 1084,
"text": "These datasets are available at the following GitHub repository."
},
{
"code": null,
"e": 1432,
"s": 1149,
"text": "The following are examples of popular techniques employed in R to clean a dataset, along with how to format variables effectively to facilitate analysis. The below functions work particularly well with panel datasets, where we have a mixture of cross-sectional and time series data."
},
{
"code": null,
"e": 1629,
"s": 1432,
"text": "To start off with a simple example, let us choose the customers dataset. Suppose that we only wish to include the variables ID and Age in our data. To do this, we define our data frame as follows:"
},
{
"code": null,
"e": 1659,
"s": 1629,
"text": "dataframe<-data.frame(ID,Age)"
},
{
"code": null,
"e": 1946,
"s": 1659,
"text": "Often times, it is necessary to combine two variables from different datasets similar to how VLOOKUP is used in Excel to join two variables based on certain criteria. If you are unfamiliar with the VLOOKUP function, then you might find this guide from Spreadsheeto particularly helpful."
},
{
"code": null,
"e": 1995,
"s": 1946,
"text": "In R, this can be done using the merge function."
},
{
"code": null,
"e": 2183,
"s": 1995,
"text": "For instance, suppose that we wish to link the Date variable in the sales dataset with the Age and Country variables in the customers dataset — with the ID variable being the common link."
},
{
"code": null,
"e": 2212,
"s": 2183,
"text": "Therefore, we do as follows:"
},
{
"code": null,
"e": 2294,
"s": 2212,
"text": "mergeinfo<-merge(mydata[, c(\"ID\", \"Sales\")],mydata2[, c(\"ID\", \"Age\", \"Country\")])"
},
{
"code": null,
"e": 2382,
"s": 2294,
"text": "Upon doing this, we see that a new dataset is formed in R joining our chosen variables:"
},
{
"code": null,
"e": 2438,
"s": 2382,
"text": "3. Using as.date to format dates and calculate duration"
},
{
"code": null,
"e": 2630,
"s": 2438,
"text": "Suppose that we now wish to calculate the number of days between the current date and the date of sale as listed in the sales file. In order to accomplish this, we can use as.date as follows:"
},
{
"code": null,
"e": 2719,
"s": 2630,
"text": "currentdate=as.Date('2016-12-15')dateinfile=as.Date(Date)Duration=currentdate-dateinfile"
},
{
"code": null,
"e": 2838,
"s": 2719,
"text": "Going back to the example above, suppose that we now wish to combine this duration variable with the rest of our data."
},
{
"code": null,
"e": 2952,
"s": 2838,
"text": "Hence, we can now combine our new Duration variable with the merge function as above, and can do this as follows:"
},
{
"code": null,
"e": 3087,
"s": 2952,
"text": "durationasdouble=as.double.difftime(Duration, units='days')updateddataframe=data.frame(ID,Sales,Date,durationasdouble)updateddataframe"
},
{
"code": null,
"e": 3159,
"s": 3087,
"text": "4. Using as.POSIXct and format to calculate differences between seconds"
},
{
"code": null,
"e": 3306,
"s": 3159,
"text": "While it is not the case in the above example, a situation can often occur where we have dates which include the time, e.g. “2016–10–13 19:30:55”."
},
{
"code": null,
"e": 3511,
"s": 3306,
"text": "There may be times where we wish to find differences between seconds of two dates. In this regard, as.POSIXct is a more suitable option than as.Date. For instance, we can first format our date as follows:"
},
{
"code": null,
"e": 3647,
"s": 3511,
"text": "date_converted<-format(Date, format=\"%Y-%m-%d %H:%M:%S\")new_date_variable<-as.POSIXct(date_converted)seconds<-diff(new_date_variable,1)"
},
{
"code": null,
"e": 3840,
"s": 3647,
"text": "When we define our seconds variable, it will now give us the difference between two dates in seconds. Then, it is a matter of simple arithmetic to obtain the difference in minutes and seconds."
},
{
"code": null,
"e": 3877,
"s": 3840,
"text": "minutes<-seconds/60hours<-minutes/60"
},
{
"code": null,
"e": 3933,
"s": 3877,
"text": "5. grepl: Remove instances of a string from a variables"
},
{
"code": null,
"e": 4095,
"s": 3933,
"text": "Let us look to the Country variable. Suppose that we wish to remove all instances of “Greenland” from our variable. This is accomplished using the grepl command:"
},
{
"code": null,
"e": 4158,
"s": 4095,
"text": "countryremoved<-mydata2[!grepl(\"Greenland\", mydata2$Country),]"
},
{
"code": null,
"e": 4211,
"s": 4158,
"text": "6. Delete observations using head and tail functions"
},
{
"code": null,
"e": 4441,
"s": 4211,
"text": "The head and tail functions can be used if we wish to delete certain observations from a variable, e.g. Sales. The head function allows us to delete the first 30 rows, while the tail function allows us to delete the last 30 rows."
},
{
"code": null,
"e": 4619,
"s": 4441,
"text": "When it comes to using a variable edited in this way for calculation purposes, e.g. a regression, the as.matrix function is also used to convert the variable into matrix format:"
},
{
"code": null,
"e": 4748,
"s": 4619,
"text": "Salesminus30days←head(Sales,-30)X1=as.matrix(Salesminus30days)X1 Salesplus30days<-tail(Sales,-30)X2=as.matrix(Salesplus30days)X2"
},
{
"code": null,
"e": 4798,
"s": 4748,
"text": "7. Replicate SUMIF using the “aggregate” function"
},
{
"code": null,
"e": 5065,
"s": 4798,
"text": "names <- c(\"John\", \"Elizabeth\", \"Michael\", \"John\", \"Elizabeth\", \"Michael\")webvisitsframe <- cbind(\"24\",\"32\",\"40\",\"71\",\"65\",\"63\")webvisits=as.numeric(webvisitsframe)minutesspentframe <- cbind(\"20\", \"41\", \"5\", \"6\", \"48\", \"97\")minutesspent=as.numeric(minutesspentframe)"
},
{
"code": null,
"e": 5229,
"s": 5065,
"text": "Let us suppose that we have created the following table as below, and want to obtain the sum of web visits and minutes spent on a website in any particular period:"
},
{
"code": null,
"e": 5480,
"s": 5229,
"text": "In this instance, we can replicate the SUMIF function in Excel (where the values associated with a specific identifier are summed up) by using the aggregate function in R. This can be done as follows (where raw_table is the table specified as above):"
},
{
"code": null,
"e": 5546,
"s": 5480,
"text": "sumif_table<-aggregate(. ~ names, data=raw_table, sum)sumif_table"
},
{
"code": null,
"e": 5639,
"s": 5546,
"text": "Thus, the values associated with identifiers (in this case, names) are summed up as follows:"
},
{
"code": null,
"e": 5771,
"s": 5639,
"text": "As per the examples at Stack Overflow, the plyr and data.table libraries can also be used to accomplish the same result as follows:"
},
{
"code": null,
"e": 5979,
"s": 5771,
"text": "library(plyr)ddply(nametable, .(names), summarise, Sum_webvisits = sum(webvisits), Sum_minutesspent = sum(minutesspent)) library(data.table)DT <- as.data.table(nametable)DT[ , lapply(.SD, sum), by = \"names\"]"
},
{
"code": null,
"e": 6023,
"s": 5979,
"text": "8. Calculate lags using the diff() function"
},
{
"code": null,
"e": 6184,
"s": 6023,
"text": "When it comes to doing time series analysis, often times it is necessary to calculate lags for a specific variable. To do this in R, we use the diff() function."
},
{
"code": null,
"e": 6310,
"s": 6184,
"text": "For the purposes of this example, we create a matrix with price data for the column names, along with years as our row names:"
},
{
"code": null,
"e": 6783,
"s": 6310,
"text": "pricedata <- matrix(c(102, 90, 84, 130, 45), ncol=1)colnames(pricedata) <- c('Price')rownames(pricedata) <- c('2012', '2013', '2014', '2015', '2016')pricedata.table <- as.table(pricedata)pricedata.tableYear\tPrice2012\t1022013\t902014\t842015\t1302016\t452. Lag = 1diff(pricedata.table,1)Year\tPrice2013\t-122014\t-62015\t462016\t-853. Lag = 2diff(pricedata.table,2)Year\tPrice2014\t-182015\t402016\t-394. Differences = 2diff(pricedata.table,differences=2)Year\tPrice2014\t62015\t522016\t131"
},
{
"code": null,
"e": 6833,
"s": 6783,
"text": "9. Separating by list (useful for panel datasets)"
},
{
"code": null,
"e": 7078,
"s": 6833,
"text": "Suppose we have a dataset that needs to be separated, e.g. by ID. Doing this manually would make for quite a messy process. Instead, we can do so using the unique and split functions to form a list. Here is an example of how this would be done."
},
{
"code": null,
"e": 7123,
"s": 7078,
"text": "Using a data frame of dates, names, and IDs:"
},
{
"code": null,
"e": 7486,
"s": 7123,
"text": "> Date<-c(\"20/02/2017\",\"21/02/2017\",\"22/02/2017\",\"20/02/2017\",\"21/02/2017\",\"22/02/2017\")> ID<-c(\"20\",\"20\",\"20\",\"40\",\"40\",\"40\")> Name<-c(\"Brian\",\"Brian\",\"Brian\",\"Adam\",\"Adam\",\"Adam\")> df<-data.frame(Date,ID,Name)> df Date ID Name1 20/02/2017 20 Brian2 21/02/2017 20 Brian3 22/02/2017 20 Brian4 20/02/2017 40 Adam5 21/02/2017 40 Adam6 22/02/2017 40 Adam"
},
{
"code": null,
"e": 7609,
"s": 7486,
"text": "However, we would like to separate the observations into two separate lists by filtering by ID. We would do this as below:"
},
{
"code": null,
"e": 7860,
"s": 7609,
"text": "> listofids=as.character(unique(df$ID))> mylist <- split(df, df$ID)> mylist $`20` Date ID Name1 20/02/2017 20 Brian2 21/02/2017 20 Brian3 22/02/2017 20 Brian$`40` Date ID Name4 20/02/2017 40 Adam5 21/02/2017 40 Adam6 22/02/2017 40 Adam"
},
{
"code": null,
"e": 7987,
"s": 7860,
"text": "This is the list in its entirety. If we wished to call one at a time (by ID as our unique identifier, we can do so as follows:"
},
{
"code": null,
"e": 8184,
"s": 7987,
"text": "> mylist[1]$`20` Date ID Name1 20/02/2017 20 Brian2 21/02/2017 20 Brian3 22/02/2017 20 Brian> mylist[2]$`40` Date ID Name4 20/02/2017 40 Adam5 21/02/2017 40 Adam6 22/02/2017 40 Adam"
},
{
"code": null,
"e": 8480,
"s": 8184,
"text": "The above examples have illustrated various ways in which we can conduct data manipulation procedures in R, and techniques for replicating common Excel functions such as VLOOKUP. Many thanks for your time, and once again the associated GitHub repository for the above examples is available here."
},
{
"code": null,
"e": 8553,
"s": 8480,
"text": "You can also find more of my data science content at michael-grogan.com."
}
] |
Abstract Classes in Java | A class which contains the abstract keyword in its declaration is known as an abstract class.
Abstract classes may or may not contain abstract methods, i.e., methods without a body ( public void get(); )
Abstract classes may or may not contain abstract methods, i.e., methods without a body ( public void get(); )
But, if a class has at least one abstract method, then the class must be declared abstract.
But, if a class has at least one abstract method, then the class must be declared abstract.
If a class is declared abstract, it cannot be instantiated.
If a class is declared abstract, it cannot be instantiated.
To use an abstract class, you have to inherit it from another class, provide implementations for the abstract methods in it.
To use an abstract class, you have to inherit it from another class, provide implementations for the abstract methods in it.
If you inherit an abstract class, you have to provide implementations to all the abstract methods in it.
If you inherit an abstract class, you have to provide implementations to all the abstract methods in it.
This section provides you an example of the abstract class. To create an abstract class, just use the abstract keyword before the class keyword, in the class declaration.
/* File name : Employee.java */
public abstract class Employee {
private String name;
private String address;
private int number;
public Employee(String name, String address, int number) {
System.out.println("Constructing an Employee");
this.name = name;
this.address = address;
this.number = number;
}
public double computePay() {
System.out.println("Inside Employee computePay");
return 0.0;
}
public void mailCheck() {
System.out.println("Mailing a check to " + this.name + " " + this.address);
}
public String toString() {
return name + " " + address + " " + number;
}
public String getName() {
return name;
}
public String getAddress() {
return address;
}
public void setAddress(String newAddress) {
address = newAddress;
}
public int getNumber() {
return number;
}
}
You can observe that except abstract methods the Employee class is the same as the normal class in Java. The class is now abstract, but it still has three fields, seven methods, and one constructor.
Now you can try to instantiate the Employee class in the following way −
/* File name : AbstractDemo.java */
public class AbstractDemo {
public static void main(String [] args) {
/* Following is not allowed and would raise error */
Employee e = new Employee("George W.", "Houston, TX", 43);
System.out.println("\n Call mailCheck using Employee reference--");
e.mailCheck();
}
}
When you compile the above class, it gives you the following error −
Employee.java:46: Employee is abstract; cannot be instantiated
Employee e = new Employee("George W.", "Houston, TX", 43);
^
1 error
We can inherit the properties of Employee class just like a concrete class in the following way −
/* File name : Salary.java */
public class Salary extends Employee {
private double salary; // Annual salary
public Salary(String name, String address, int number, double salary) {
super(name, address, number);
setSalary(salary);
}
public void mailCheck() {
System.out.println("Within mailCheck of Salary class ");
System.out.println("Mailing check to " + getName() + " with salary " + salary);
}
public double getSalary() {
return salary;
}
public void setSalary(double newSalary) {
if(newSalary >= 0.0) {
salary = newSalary;
}
}
public double computePay() {
System.out.println("Computing salary pay for " + getName());
return salary/52;
}
}
Here, you cannot instantiate the Employee class, but you can instantiate the Salary Class, and using this instance you can access all the three fields and seven methods of Employee class as shown below.
/* File name : AbstractDemo.java */
public class AbstractDemo {
public static void main(String [] args) {
Salary s = new Salary("Mohd Mohtashim", "Ambehta, UP", 3, 3600.00);
Employee e = new Salary("John Adams", "Boston, MA", 2, 2400.00);
System.out.println("Call mailCheck using Salary reference --");
s.mailCheck();
System.out.println("\n Call mailCheck using Employee reference--");
e.mailCheck();
}
}
This produces the following result −
Constructing an Employee
Constructing an Employee
Call mailCheck using Salary reference --
Within mailCheck of Salary class
Mailing check to Mohd Mohtashim with salary 3600.0
Call mailCheck using Employee reference--
Within mailCheck of Salary class
Mailing check to John Adams with salary 2400.0 | [
{
"code": null,
"e": 1156,
"s": 1062,
"text": "A class which contains the abstract keyword in its declaration is known as an abstract class."
},
{
"code": null,
"e": 1266,
"s": 1156,
"text": "Abstract classes may or may not contain abstract methods, i.e., methods without a body ( public void get(); )"
},
{
"code": null,
"e": 1376,
"s": 1266,
"text": "Abstract classes may or may not contain abstract methods, i.e., methods without a body ( public void get(); )"
},
{
"code": null,
"e": 1468,
"s": 1376,
"text": "But, if a class has at least one abstract method, then the class must be declared abstract."
},
{
"code": null,
"e": 1560,
"s": 1468,
"text": "But, if a class has at least one abstract method, then the class must be declared abstract."
},
{
"code": null,
"e": 1620,
"s": 1560,
"text": "If a class is declared abstract, it cannot be instantiated."
},
{
"code": null,
"e": 1680,
"s": 1620,
"text": "If a class is declared abstract, it cannot be instantiated."
},
{
"code": null,
"e": 1805,
"s": 1680,
"text": "To use an abstract class, you have to inherit it from another class, provide implementations for the abstract methods in it."
},
{
"code": null,
"e": 1930,
"s": 1805,
"text": "To use an abstract class, you have to inherit it from another class, provide implementations for the abstract methods in it."
},
{
"code": null,
"e": 2035,
"s": 1930,
"text": "If you inherit an abstract class, you have to provide implementations to all the abstract methods in it."
},
{
"code": null,
"e": 2140,
"s": 2035,
"text": "If you inherit an abstract class, you have to provide implementations to all the abstract methods in it."
},
{
"code": null,
"e": 2311,
"s": 2140,
"text": "This section provides you an example of the abstract class. To create an abstract class, just use the abstract keyword before the class keyword, in the class declaration."
},
{
"code": null,
"e": 3214,
"s": 2311,
"text": "/* File name : Employee.java */\npublic abstract class Employee {\n private String name;\n private String address;\n private int number;\n\n public Employee(String name, String address, int number) {\n System.out.println(\"Constructing an Employee\");\n this.name = name;\n this.address = address;\n this.number = number;\n }\n public double computePay() {\n System.out.println(\"Inside Employee computePay\");\n return 0.0;\n }\n public void mailCheck() {\n System.out.println(\"Mailing a check to \" + this.name + \" \" + this.address);\n }\n public String toString() {\n return name + \" \" + address + \" \" + number;\n }\n public String getName() {\n return name;\n }\n public String getAddress() {\n return address;\n }\n public void setAddress(String newAddress) {\n address = newAddress;\n }\n public int getNumber() {\n return number;\n }\n}"
},
{
"code": null,
"e": 3413,
"s": 3214,
"text": "You can observe that except abstract methods the Employee class is the same as the normal class in Java. The class is now abstract, but it still has three fields, seven methods, and one constructor."
},
{
"code": null,
"e": 3486,
"s": 3413,
"text": "Now you can try to instantiate the Employee class in the following way −"
},
{
"code": null,
"e": 3822,
"s": 3486,
"text": "/* File name : AbstractDemo.java */\npublic class AbstractDemo {\n\n public static void main(String [] args) {\n /* Following is not allowed and would raise error */\n Employee e = new Employee(\"George W.\", \"Houston, TX\", 43);\n System.out.println(\"\\n Call mailCheck using Employee reference--\");\n e.mailCheck();\n }\n}"
},
{
"code": null,
"e": 3891,
"s": 3822,
"text": "When you compile the above class, it gives you the following error −"
},
{
"code": null,
"e": 4058,
"s": 3891,
"text": "Employee.java:46: Employee is abstract; cannot be instantiated \n Employee e = new Employee(\"George W.\", \"Houston, TX\", 43); \n ^\n1 error"
},
{
"code": null,
"e": 4156,
"s": 4058,
"text": "We can inherit the properties of Employee class just like a concrete class in the following way −"
},
{
"code": null,
"e": 4898,
"s": 4156,
"text": "/* File name : Salary.java */\npublic class Salary extends Employee {\n private double salary; // Annual salary\n\n public Salary(String name, String address, int number, double salary) {\n super(name, address, number);\n setSalary(salary);\n }\n public void mailCheck() {\n System.out.println(\"Within mailCheck of Salary class \");\n System.out.println(\"Mailing check to \" + getName() + \" with salary \" + salary);\n }\n public double getSalary() {\n return salary;\n }\n public void setSalary(double newSalary) {\n if(newSalary >= 0.0) {\n salary = newSalary;\n }\n }\n public double computePay() {\n System.out.println(\"Computing salary pay for \" + getName());\n return salary/52;\n }\n}"
},
{
"code": null,
"e": 5101,
"s": 4898,
"text": "Here, you cannot instantiate the Employee class, but you can instantiate the Salary Class, and using this instance you can access all the three fields and seven methods of Employee class as shown below."
},
{
"code": null,
"e": 5549,
"s": 5101,
"text": "/* File name : AbstractDemo.java */\npublic class AbstractDemo {\n\n public static void main(String [] args) {\n Salary s = new Salary(\"Mohd Mohtashim\", \"Ambehta, UP\", 3, 3600.00);\n Employee e = new Salary(\"John Adams\", \"Boston, MA\", 2, 2400.00);\n System.out.println(\"Call mailCheck using Salary reference --\");\n s.mailCheck();\n System.out.println(\"\\n Call mailCheck using Employee reference--\");\n e.mailCheck();\n }\n}"
},
{
"code": null,
"e": 5586,
"s": 5549,
"text": "This produces the following result −"
},
{
"code": null,
"e": 5888,
"s": 5586,
"text": "Constructing an Employee\nConstructing an Employee\nCall mailCheck using Salary reference --\nWithin mailCheck of Salary class \nMailing check to Mohd Mohtashim with salary 3600.0\n\nCall mailCheck using Employee reference--\nWithin mailCheck of Salary class \nMailing check to John Adams with salary 2400.0"
}
] |
Building a sonar sensor array with Arduino and Python | by Alberto Naranjo | Towards Data Science | In this article we are going to build from scratch a sonar array based on the cheap and popular HC-SR04 sensor. We will use an Arduino microcontroller to drive and read the sensors and to communicate to a host computer using serial communication. Here is the working code for the full project however I recommend you to follow the steps in the article to understand how it works and to customize it for your needs.
The HC-SR04 is a very popular ultrasound sensor usually used in hobby electronics to build cheap distance sensors for obstacle avoidance or object detection. It has an ultrasound transmitter and receptor used to measure the time-of-flight of an ultrasonic wave signal bouncing against a solid object.
If the speed of sound is roughly 343 m/s at a room temperature of 20 celsius degrees. The distance to an object would the half of the time it takes the ultrasound wave from the transmitter to the receptor:
distance = 343 / ( time/2 )
However the HC-SR04 sensor is very inaccurate and will give you a very rough and noisy distance estimate. There are environmental factors like temperature and humidity that will affect the ultrasonic wave speed and the solid object material and angle of incidence will as well deteriorate the distance estimation. There are ways to improve the raw readings as we will learn later but in general terms ultrasound sensors should be used only as the last resort to avoid a close collision or to detect a solid object with a low distance resolution. But they are not good navigational or distance estimation sensors. For that we could use more expensive sensors as LiDar or a laser rangefinder.
I want to use this sonar array to detect nearby obstacles in front of my Raspberry Pi robot Rover4Wd (this project will be covered in another article). The sensor’s effective angle of detection is around 15 degrees so in order to cover a bigger area in front of the robot I want to use 5 sensors in total using an arc shape:
The benefit of this setup is that we can not only estimate the distance of the obstacle in front of the robot but also the position (roughly) of the object relative to the robot.
The HC-SR04 sensor has only four pins. Two for ground and +5v, and Echo and Trigger pins. To use the sensor we need to trigger the signal using the Trigger pin and measure the time until is received via the Echo pin. As we don’t use the Echo and Trigger pins at the same time they can share the same cable to connect to an Arduino digital pin.
For this project we are going to use an Arduino Nano which is small and broadly available. There are tons of non-official compatible clones for under $3 per unit as well.
For this breadboard setup we have connected both Trig and Echo pins to a single digital pin in Arduino. We are going to use D12, D11, D10, D9 and D8 pins for sending and receiving signals. This hardware setup is only limited by the microcontroller’s available digital pins but it can be expanded further using multiplexing where one pin can be shared by multiple sensors but only one sensor at the time.
Traditionally this will be the sequential workflow we would need to manage to poll sensors one by one:
Trigger one sensorReceive the echoCalculate distance using the duration of the previous stepsCommunicate measurement using the serial portProcess next sensor
Trigger one sensor
Receive the echo
Calculate distance using the duration of the previous steps
Communicate measurement using the serial port
Process next sensor
However we are going to use a ready available Arduino library called NewPing that allows you to ping multiple sensors minimizing the delay between sensors. This will help us to measure the distance from all 5 sensors several times per second at the same time (almost). The resulting workflow would look like this:
Trigger and echo all sensors async (but sequentially)When a sensor is done calculate distanceWhen all sensors are done for the current cycle, communicate readings from all sensors using the serial portStart a new sensor reading cycle
Trigger and echo all sensors async (but sequentially)
When a sensor is done calculate distance
When all sensors are done for the current cycle, communicate readings from all sensors using the serial port
Start a new sensor reading cycle
The implementation is very straightforward and heavily commented in the code. Feel free to take a look at the full code here.
I want to put special focus on the serial communication part when all the sensors are done with the distance measurement:
void oneSensorCycle() { // Sensor ping cycle complete, do something with the results. for (uint8_t i = 0; i < SONAR_NUM; i++) { // Sending bytes byte reading_high = highByte(cm[i]); byte reading_low = lowByte(cm[i]); byte packet[]={0x59,0x59,i,reading_high,reading_low}; Serial.write(packet, sizeof(packet)); }}
Originally I wanted to send sensor readings via serial using strings however I realized the message will be big and harder to parse on the host side of the project. In order to improve speed and lower delay in the readings I decided to switch to a simple format using a message of 5 bytes:
Byte 1: Character ‘Y’Byte 2: Character ‘Y’Byte 3: Sensor index [0–255]Byte 4: High-order byte of the measured distance (as an unsigned integer)Byte 5: Low-order byte of the measured distance (as an unsigned integer)
Byte 1 and 2 will be just the message header to decide where a new message starts when we will be reading the incoming serial bytes. This approach is very similar to what the TF-Luna LiDar sensor is doing to communicate to the host computer.
In the host side we will use Python 3 to connect to the Arduino micro-controller via serial port and read the incoming bytes as fast as we can. The ideal setup will be to use a UART port in the host computer but just serial USB will do the job. The full code of the Python script is here.
There are several interesting things to note, first we need to read the serial on a different thread so we won’t miss any incoming messages while we are processing the sensor reading or doing different stuff:
def read_serial(serial, sensors): while True: # Read by bytes counter = serial.in_waiting # count the number of bytes of the serial port bytes_to_read = 5 if counter > bytes_to_read - 1: bytes_serial = serial.read(bytes_to_read) # ser.reset_input_buffer() # reset buffer sensor_index, sensor_reading = read_sensor_package(bytes_serial) if sensor_index >= 0: if sensor_index not in sensors: sensors[sensor_index] = SMA(2) if sensor_reading > 0: sensors[sensor_index].append(sensor_reading)
Secondly, we need to find the start of the message with the header ‘YY’ to start reading the sensors. As the Arduino controller doesn’t wait a host to connect to the serial port we may connect and read a partial message that will be discarded. It may take and additional second or two to get in sync with the micro-controller messages.
Thirdly, we are smoothing the measurements with a simple moving average to avoid some noise. In this case we are just using a window of two measurements because we need the distance to be updated very fast to avoid hitting a close obstacle with the robot Rover4WD. But you can adjust it to a bigger window depending on you requirements. Bigger window cleaner but slow changing, smaller window noisier but fast changing.
What are the next steps? This project is ready to be integrated in a robotic/electronic project. In my case I’m using a Ubuntu 20.10 with ROS2 in a Raspberry Pi 4 to control my robot Rover4WD. The next step for me would be to build a ROS package to process the measurements into detected obstacles and to publish transform messages that will be incorporated into the bigger navigation framework using sensor fusion.
As always let me know if you have any question or comment to improve the quality of this article. Thank you and keep enjoying your projects! | [
{
"code": null,
"e": 587,
"s": 172,
"text": "In this article we are going to build from scratch a sonar array based on the cheap and popular HC-SR04 sensor. We will use an Arduino microcontroller to drive and read the sensors and to communicate to a host computer using serial communication. Here is the working code for the full project however I recommend you to follow the steps in the article to understand how it works and to customize it for your needs."
},
{
"code": null,
"e": 888,
"s": 587,
"text": "The HC-SR04 is a very popular ultrasound sensor usually used in hobby electronics to build cheap distance sensors for obstacle avoidance or object detection. It has an ultrasound transmitter and receptor used to measure the time-of-flight of an ultrasonic wave signal bouncing against a solid object."
},
{
"code": null,
"e": 1094,
"s": 888,
"text": "If the speed of sound is roughly 343 m/s at a room temperature of 20 celsius degrees. The distance to an object would the half of the time it takes the ultrasound wave from the transmitter to the receptor:"
},
{
"code": null,
"e": 1122,
"s": 1094,
"text": "distance = 343 / ( time/2 )"
},
{
"code": null,
"e": 1813,
"s": 1122,
"text": "However the HC-SR04 sensor is very inaccurate and will give you a very rough and noisy distance estimate. There are environmental factors like temperature and humidity that will affect the ultrasonic wave speed and the solid object material and angle of incidence will as well deteriorate the distance estimation. There are ways to improve the raw readings as we will learn later but in general terms ultrasound sensors should be used only as the last resort to avoid a close collision or to detect a solid object with a low distance resolution. But they are not good navigational or distance estimation sensors. For that we could use more expensive sensors as LiDar or a laser rangefinder."
},
{
"code": null,
"e": 2138,
"s": 1813,
"text": "I want to use this sonar array to detect nearby obstacles in front of my Raspberry Pi robot Rover4Wd (this project will be covered in another article). The sensor’s effective angle of detection is around 15 degrees so in order to cover a bigger area in front of the robot I want to use 5 sensors in total using an arc shape:"
},
{
"code": null,
"e": 2317,
"s": 2138,
"text": "The benefit of this setup is that we can not only estimate the distance of the obstacle in front of the robot but also the position (roughly) of the object relative to the robot."
},
{
"code": null,
"e": 2661,
"s": 2317,
"text": "The HC-SR04 sensor has only four pins. Two for ground and +5v, and Echo and Trigger pins. To use the sensor we need to trigger the signal using the Trigger pin and measure the time until is received via the Echo pin. As we don’t use the Echo and Trigger pins at the same time they can share the same cable to connect to an Arduino digital pin."
},
{
"code": null,
"e": 2832,
"s": 2661,
"text": "For this project we are going to use an Arduino Nano which is small and broadly available. There are tons of non-official compatible clones for under $3 per unit as well."
},
{
"code": null,
"e": 3236,
"s": 2832,
"text": "For this breadboard setup we have connected both Trig and Echo pins to a single digital pin in Arduino. We are going to use D12, D11, D10, D9 and D8 pins for sending and receiving signals. This hardware setup is only limited by the microcontroller’s available digital pins but it can be expanded further using multiplexing where one pin can be shared by multiple sensors but only one sensor at the time."
},
{
"code": null,
"e": 3339,
"s": 3236,
"text": "Traditionally this will be the sequential workflow we would need to manage to poll sensors one by one:"
},
{
"code": null,
"e": 3497,
"s": 3339,
"text": "Trigger one sensorReceive the echoCalculate distance using the duration of the previous stepsCommunicate measurement using the serial portProcess next sensor"
},
{
"code": null,
"e": 3516,
"s": 3497,
"text": "Trigger one sensor"
},
{
"code": null,
"e": 3533,
"s": 3516,
"text": "Receive the echo"
},
{
"code": null,
"e": 3593,
"s": 3533,
"text": "Calculate distance using the duration of the previous steps"
},
{
"code": null,
"e": 3639,
"s": 3593,
"text": "Communicate measurement using the serial port"
},
{
"code": null,
"e": 3659,
"s": 3639,
"text": "Process next sensor"
},
{
"code": null,
"e": 3973,
"s": 3659,
"text": "However we are going to use a ready available Arduino library called NewPing that allows you to ping multiple sensors minimizing the delay between sensors. This will help us to measure the distance from all 5 sensors several times per second at the same time (almost). The resulting workflow would look like this:"
},
{
"code": null,
"e": 4207,
"s": 3973,
"text": "Trigger and echo all sensors async (but sequentially)When a sensor is done calculate distanceWhen all sensors are done for the current cycle, communicate readings from all sensors using the serial portStart a new sensor reading cycle"
},
{
"code": null,
"e": 4261,
"s": 4207,
"text": "Trigger and echo all sensors async (but sequentially)"
},
{
"code": null,
"e": 4302,
"s": 4261,
"text": "When a sensor is done calculate distance"
},
{
"code": null,
"e": 4411,
"s": 4302,
"text": "When all sensors are done for the current cycle, communicate readings from all sensors using the serial port"
},
{
"code": null,
"e": 4444,
"s": 4411,
"text": "Start a new sensor reading cycle"
},
{
"code": null,
"e": 4570,
"s": 4444,
"text": "The implementation is very straightforward and heavily commented in the code. Feel free to take a look at the full code here."
},
{
"code": null,
"e": 4692,
"s": 4570,
"text": "I want to put special focus on the serial communication part when all the sensors are done with the distance measurement:"
},
{
"code": null,
"e": 5040,
"s": 4692,
"text": "void oneSensorCycle() { // Sensor ping cycle complete, do something with the results. for (uint8_t i = 0; i < SONAR_NUM; i++) { // Sending bytes byte reading_high = highByte(cm[i]); byte reading_low = lowByte(cm[i]); byte packet[]={0x59,0x59,i,reading_high,reading_low}; Serial.write(packet, sizeof(packet)); }}"
},
{
"code": null,
"e": 5330,
"s": 5040,
"text": "Originally I wanted to send sensor readings via serial using strings however I realized the message will be big and harder to parse on the host side of the project. In order to improve speed and lower delay in the readings I decided to switch to a simple format using a message of 5 bytes:"
},
{
"code": null,
"e": 5546,
"s": 5330,
"text": "Byte 1: Character ‘Y’Byte 2: Character ‘Y’Byte 3: Sensor index [0–255]Byte 4: High-order byte of the measured distance (as an unsigned integer)Byte 5: Low-order byte of the measured distance (as an unsigned integer)"
},
{
"code": null,
"e": 5788,
"s": 5546,
"text": "Byte 1 and 2 will be just the message header to decide where a new message starts when we will be reading the incoming serial bytes. This approach is very similar to what the TF-Luna LiDar sensor is doing to communicate to the host computer."
},
{
"code": null,
"e": 6077,
"s": 5788,
"text": "In the host side we will use Python 3 to connect to the Arduino micro-controller via serial port and read the incoming bytes as fast as we can. The ideal setup will be to use a UART port in the host computer but just serial USB will do the job. The full code of the Python script is here."
},
{
"code": null,
"e": 6286,
"s": 6077,
"text": "There are several interesting things to note, first we need to read the serial on a different thread so we won’t miss any incoming messages while we are processing the sensor reading or doing different stuff:"
},
{
"code": null,
"e": 6920,
"s": 6286,
"text": "def read_serial(serial, sensors): while True: # Read by bytes counter = serial.in_waiting # count the number of bytes of the serial port bytes_to_read = 5 if counter > bytes_to_read - 1: bytes_serial = serial.read(bytes_to_read) # ser.reset_input_buffer() # reset buffer sensor_index, sensor_reading = read_sensor_package(bytes_serial) if sensor_index >= 0: if sensor_index not in sensors: sensors[sensor_index] = SMA(2) if sensor_reading > 0: sensors[sensor_index].append(sensor_reading)"
},
{
"code": null,
"e": 7256,
"s": 6920,
"text": "Secondly, we need to find the start of the message with the header ‘YY’ to start reading the sensors. As the Arduino controller doesn’t wait a host to connect to the serial port we may connect and read a partial message that will be discarded. It may take and additional second or two to get in sync with the micro-controller messages."
},
{
"code": null,
"e": 7676,
"s": 7256,
"text": "Thirdly, we are smoothing the measurements with a simple moving average to avoid some noise. In this case we are just using a window of two measurements because we need the distance to be updated very fast to avoid hitting a close obstacle with the robot Rover4WD. But you can adjust it to a bigger window depending on you requirements. Bigger window cleaner but slow changing, smaller window noisier but fast changing."
},
{
"code": null,
"e": 8092,
"s": 7676,
"text": "What are the next steps? This project is ready to be integrated in a robotic/electronic project. In my case I’m using a Ubuntu 20.10 with ROS2 in a Raspberry Pi 4 to control my robot Rover4WD. The next step for me would be to build a ROS package to process the measurements into detected obstacles and to publish transform messages that will be incorporated into the bigger navigation framework using sensor fusion."
}
] |
Plotting Various Sounds on Graphs using Python and Matplotlib - GeeksforGeeks | 27 Jan, 2022
In this article, we will explore the way of visualizing sounds waves using Python and Matplotlib.
1. Matplotlib: Install Matplotlib using the below command:
pip install matplotlib
2. Numpy: Numpy gets installed automatically installed with Matplotlib. Although, if you face any import error, use the below command to install Numpy
pip install numpy
Note: If you are on Linux like me, then you might need to use pip3 instead of pip or you might create a virtual environment and run the above command.
Import matplotlib, Numpy, wave, and sys module.
Open the audio file using the wave.open() method.
Read all frames of the opened sound wave using readframes() function.
Store the frame rate in a variable using the getframrate() function.
Finally, plot the x-axis in seconds using frame rate.
Use the matplotlib.figure() function to plot the derived graph
Use labels as per the requirement.
Below is the implementation.
Python3
# importsimport matplotlib.pyplot as pltimport numpy as npimport wave, sys # shows the sound wavesdef visualize(path: str): # reading the audio file raw = wave.open(path) # reads all the frames # -1 indicates all or max frames signal = raw.readframes(-1) signal = np.frombuffer(signal, dtype ="int16") # gets the frame rate f_rate = raw.getframerate() # to Plot the x-axis in seconds # you need get the frame rate # and divide by size of your signal # to create a Time Vector # spaced linearly with the size # of the audio file time = np.linspace( 0, # start len(signal) / f_rate, num = len(signal) ) # using matplotlib to plot # creates a new figure plt.figure(1) # title of the plot plt.title("Sound Wave") # label of x-axis plt.xlabel("Time") # actual plotting plt.plot(time, signal) # shows the plot # in new window plt.show() # you can also save # the plot using # plt.savefig('filename') if __name__ == "__main__": # gets the command line Value path = sys.argv[1] visualize(path)
Output:
So, we are done with coding, now it’s the moment of truth. Let’s check if it actually works or not. You can try out any audio file but make sure that it has to be a wav file. If you have some other file type then you can use ffmpeg to convert it to wav file. If you want then feel free to download the audio file we will be using. You can download it using this link, but do try out other files too.To run the code, you need to pass the path of the audio file in the command line. To do that type the following in your terminal:
python soundwave.py sample_audio.wav
It is important to note that name of the Python file is soundwave.py and the name of the audio file is sample_audio.wav. You need to change these according to your system. Now, a new window should have popped up and should be seeing a sound wave plot. If you have used my audio, then your plot should look something like this.
varshagumber28
adnanirshad158
Data Visualization
Python-matplotlib
Python
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
How to Install PIP on Windows ?
Read a file line by line in Python
Enumerate() in Python
Different ways to create Pandas Dataframe | [
{
"code": null,
"e": 31572,
"s": 31544,
"text": "\n27 Jan, 2022"
},
{
"code": null,
"e": 31670,
"s": 31572,
"text": "In this article, we will explore the way of visualizing sounds waves using Python and Matplotlib."
},
{
"code": null,
"e": 31730,
"s": 31670,
"text": " 1. Matplotlib: Install Matplotlib using the below command:"
},
{
"code": null,
"e": 31753,
"s": 31730,
"text": "pip install matplotlib"
},
{
"code": null,
"e": 31904,
"s": 31753,
"text": "2. Numpy: Numpy gets installed automatically installed with Matplotlib. Although, if you face any import error, use the below command to install Numpy"
},
{
"code": null,
"e": 31922,
"s": 31904,
"text": "pip install numpy"
},
{
"code": null,
"e": 32073,
"s": 31922,
"text": "Note: If you are on Linux like me, then you might need to use pip3 instead of pip or you might create a virtual environment and run the above command."
},
{
"code": null,
"e": 32121,
"s": 32073,
"text": "Import matplotlib, Numpy, wave, and sys module."
},
{
"code": null,
"e": 32171,
"s": 32121,
"text": "Open the audio file using the wave.open() method."
},
{
"code": null,
"e": 32241,
"s": 32171,
"text": "Read all frames of the opened sound wave using readframes() function."
},
{
"code": null,
"e": 32310,
"s": 32241,
"text": "Store the frame rate in a variable using the getframrate() function."
},
{
"code": null,
"e": 32364,
"s": 32310,
"text": "Finally, plot the x-axis in seconds using frame rate."
},
{
"code": null,
"e": 32427,
"s": 32364,
"text": "Use the matplotlib.figure() function to plot the derived graph"
},
{
"code": null,
"e": 32462,
"s": 32427,
"text": "Use labels as per the requirement."
},
{
"code": null,
"e": 32492,
"s": 32462,
"text": "Below is the implementation. "
},
{
"code": null,
"e": 32500,
"s": 32492,
"text": "Python3"
},
{
"code": "# importsimport matplotlib.pyplot as pltimport numpy as npimport wave, sys # shows the sound wavesdef visualize(path: str): # reading the audio file raw = wave.open(path) # reads all the frames # -1 indicates all or max frames signal = raw.readframes(-1) signal = np.frombuffer(signal, dtype =\"int16\") # gets the frame rate f_rate = raw.getframerate() # to Plot the x-axis in seconds # you need get the frame rate # and divide by size of your signal # to create a Time Vector # spaced linearly with the size # of the audio file time = np.linspace( 0, # start len(signal) / f_rate, num = len(signal) ) # using matplotlib to plot # creates a new figure plt.figure(1) # title of the plot plt.title(\"Sound Wave\") # label of x-axis plt.xlabel(\"Time\") # actual plotting plt.plot(time, signal) # shows the plot # in new window plt.show() # you can also save # the plot using # plt.savefig('filename') if __name__ == \"__main__\": # gets the command line Value path = sys.argv[1] visualize(path)",
"e": 33649,
"s": 32500,
"text": null
},
{
"code": null,
"e": 33657,
"s": 33649,
"text": "Output:"
},
{
"code": null,
"e": 34186,
"s": 33657,
"text": "So, we are done with coding, now it’s the moment of truth. Let’s check if it actually works or not. You can try out any audio file but make sure that it has to be a wav file. If you have some other file type then you can use ffmpeg to convert it to wav file. If you want then feel free to download the audio file we will be using. You can download it using this link, but do try out other files too.To run the code, you need to pass the path of the audio file in the command line. To do that type the following in your terminal:"
},
{
"code": null,
"e": 34223,
"s": 34186,
"text": "python soundwave.py sample_audio.wav"
},
{
"code": null,
"e": 34550,
"s": 34223,
"text": "It is important to note that name of the Python file is soundwave.py and the name of the audio file is sample_audio.wav. You need to change these according to your system. Now, a new window should have popped up and should be seeing a sound wave plot. If you have used my audio, then your plot should look something like this."
},
{
"code": null,
"e": 34565,
"s": 34550,
"text": "varshagumber28"
},
{
"code": null,
"e": 34580,
"s": 34565,
"text": "adnanirshad158"
},
{
"code": null,
"e": 34599,
"s": 34580,
"text": "Data Visualization"
},
{
"code": null,
"e": 34617,
"s": 34599,
"text": "Python-matplotlib"
},
{
"code": null,
"e": 34624,
"s": 34617,
"text": "Python"
},
{
"code": null,
"e": 34722,
"s": 34624,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 34750,
"s": 34722,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 34800,
"s": 34750,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 34822,
"s": 34800,
"text": "Python map() function"
},
{
"code": null,
"e": 34866,
"s": 34822,
"text": "How to get column names in Pandas dataframe"
},
{
"code": null,
"e": 34884,
"s": 34866,
"text": "Python Dictionary"
},
{
"code": null,
"e": 34907,
"s": 34884,
"text": "Taking input in Python"
},
{
"code": null,
"e": 34939,
"s": 34907,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 34974,
"s": 34939,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 34996,
"s": 34974,
"text": "Enumerate() in Python"
}
] |
Image Resizing in Matlab - GeeksforGeeks | 22 May, 2019
Prerequisite : RGB image representation
MATLAB stores most images as two-dimensional matrices, in which each element of the matrix corresponds to a single discrete pixel in the displayed image. Some images, such as truecolor images, represent images using a three-dimensional array. In truecolor images, the first plane in the third dimension represents the red pixel intensities, the second plane represents the green pixel intensities, and the third plane represents the blue pixel intensities.
Image resize changes the size of an image. There are two ways of using the imresize column. if the input image has more than two dimensions imresize only resizes the first two dimensions.
J = imresize(I, scale) : The method takes the input image I as input and a scaling factor and scales the input image with that factor. For eg. if we choose 0.5 as the scaling factor every two pixels in the original image is mapped to one pixel value in the output image for both the dimensions.
J = imresize(I, [numrows numcols]) : The methods takes the number of rows and columns and fits the original input image to an output image having the specified number of rows and columns.
Code #1: Read the image from file
% read image fileI = imread('image.jpg'); %display image sizesize(I) %display the imagefigure, imshow(I);
Output :
ans = 371 660 3
Code #2: Resize by scaling
% compress the image and save % in another variableI1 = imresize(I, 0.5); %display image sizesize(I1) %display the imagefigure, imshow(I1);
Output :
ans = 186 330 3
Code #3: Resize with specified rows and columns
% resize by specifying rows % and columnsI2 = imresize(I, [100, 200]); %display image sizesize(I2) %display the imagefigure, imshow(I2);
Output :
ans = 100 200 3
Kaustav kumar Chanda
Image-Processing
MATLAB
Advanced Computer Subject
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ML | Linear Regression
System Design Tutorial
Decision Tree Introduction with example
Python | Decision tree implementation
Copying Files to and from Docker Containers
ML | Underfitting and Overfitting
Clustering in Machine Learning
KDD Process in Data Mining
Docker - COPY Instruction
Getting started with Machine Learning | [
{
"code": null,
"e": 26211,
"s": 26183,
"text": "\n22 May, 2019"
},
{
"code": null,
"e": 26251,
"s": 26211,
"text": "Prerequisite : RGB image representation"
},
{
"code": null,
"e": 26708,
"s": 26251,
"text": "MATLAB stores most images as two-dimensional matrices, in which each element of the matrix corresponds to a single discrete pixel in the displayed image. Some images, such as truecolor images, represent images using a three-dimensional array. In truecolor images, the first plane in the third dimension represents the red pixel intensities, the second plane represents the green pixel intensities, and the third plane represents the blue pixel intensities."
},
{
"code": null,
"e": 26896,
"s": 26708,
"text": "Image resize changes the size of an image. There are two ways of using the imresize column. if the input image has more than two dimensions imresize only resizes the first two dimensions."
},
{
"code": null,
"e": 27191,
"s": 26896,
"text": "J = imresize(I, scale) : The method takes the input image I as input and a scaling factor and scales the input image with that factor. For eg. if we choose 0.5 as the scaling factor every two pixels in the original image is mapped to one pixel value in the output image for both the dimensions."
},
{
"code": null,
"e": 27379,
"s": 27191,
"text": "J = imresize(I, [numrows numcols]) : The methods takes the number of rows and columns and fits the original input image to an output image having the specified number of rows and columns."
},
{
"code": null,
"e": 27413,
"s": 27379,
"text": "Code #1: Read the image from file"
},
{
"code": "% read image fileI = imread('image.jpg'); %display image sizesize(I) %display the imagefigure, imshow(I);",
"e": 27521,
"s": 27413,
"text": null
},
{
"code": null,
"e": 27530,
"s": 27521,
"text": "Output :"
},
{
"code": null,
"e": 27553,
"s": 27530,
"text": "ans = 371 660 3\n"
},
{
"code": null,
"e": 27581,
"s": 27553,
"text": " Code #2: Resize by scaling"
},
{
"code": "% compress the image and save % in another variableI1 = imresize(I, 0.5); %display image sizesize(I1) %display the imagefigure, imshow(I1);",
"e": 27723,
"s": 27581,
"text": null
},
{
"code": null,
"e": 27732,
"s": 27723,
"text": "Output :"
},
{
"code": null,
"e": 27755,
"s": 27732,
"text": "ans = 186 330 3\n"
},
{
"code": null,
"e": 27804,
"s": 27755,
"text": " Code #3: Resize with specified rows and columns"
},
{
"code": "% resize by specifying rows % and columnsI2 = imresize(I, [100, 200]); %display image sizesize(I2) %display the imagefigure, imshow(I2);",
"e": 27943,
"s": 27804,
"text": null
},
{
"code": null,
"e": 27952,
"s": 27943,
"text": "Output :"
},
{
"code": null,
"e": 27975,
"s": 27952,
"text": "ans = 100 200 3\n"
},
{
"code": null,
"e": 27996,
"s": 27975,
"text": "Kaustav kumar Chanda"
},
{
"code": null,
"e": 28013,
"s": 27996,
"text": "Image-Processing"
},
{
"code": null,
"e": 28020,
"s": 28013,
"text": "MATLAB"
},
{
"code": null,
"e": 28046,
"s": 28020,
"text": "Advanced Computer Subject"
},
{
"code": null,
"e": 28144,
"s": 28046,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28167,
"s": 28144,
"text": "ML | Linear Regression"
},
{
"code": null,
"e": 28190,
"s": 28167,
"text": "System Design Tutorial"
},
{
"code": null,
"e": 28230,
"s": 28190,
"text": "Decision Tree Introduction with example"
},
{
"code": null,
"e": 28268,
"s": 28230,
"text": "Python | Decision tree implementation"
},
{
"code": null,
"e": 28312,
"s": 28268,
"text": "Copying Files to and from Docker Containers"
},
{
"code": null,
"e": 28346,
"s": 28312,
"text": "ML | Underfitting and Overfitting"
},
{
"code": null,
"e": 28377,
"s": 28346,
"text": "Clustering in Machine Learning"
},
{
"code": null,
"e": 28404,
"s": 28377,
"text": "KDD Process in Data Mining"
},
{
"code": null,
"e": 28430,
"s": 28404,
"text": "Docker - COPY Instruction"
}
] |
How to create Skewed Background with hover effect using HTML and CSS? - GeeksforGeeks | 10 May, 2020
The skewed background or you can say an angel color shade background can be created by using HTML and CSS. This background can be used as a cover pic of your website that will be attractive. In this article, we will create a simple skewed background. We will divide the article into two sections in the first section we will create the structure and in the second section, we decorate the structure.
Creating structure: In this section, we will create the structure by using only simple HTML codes.
HTML Code: By using the HTML <section> tag we will create the section for our skewed background which will have a HTML <div> tag inside of it.<!DOCTYPE html><html> <head> <meta> <title> Skewed Background using HTML and CSS </title></head> <body> <section> <div class="content"> <h2>GeeksforGeeks</h2> </div> </section> </body> </html>
<!DOCTYPE html><html> <head> <meta> <title> Skewed Background using HTML and CSS </title></head> <body> <section> <div class="content"> <h2>GeeksforGeeks</h2> </div> </section> </body> </html>
Designing structure: In this section we will decorate the pre-created structure with the help of CSS.
CSS Code: In this section first we will use some CSS properties to design the background and then we will use the skew property of the CSS which skews an element along the x and Y axis by the given angles.<style> body { margin: 0; padding: 0; font-family: serif; } section:hover { background: linear-gradient( green , yellow); } section { display: flex; background: green; height: 350px; justify-content: center; align-items: center; transform: skew(0deg, -10deg) translateY(-120px); } .content { margin: 0; padding: 0; position: relative; max-width: 900px; transform: skew(0deg, 10deg); text-align: center; } .content h2 { color: #fff; font-size: 80px; }</style>
<style> body { margin: 0; padding: 0; font-family: serif; } section:hover { background: linear-gradient( green , yellow); } section { display: flex; background: green; height: 350px; justify-content: center; align-items: center; transform: skew(0deg, -10deg) translateY(-120px); } .content { margin: 0; padding: 0; position: relative; max-width: 900px; transform: skew(0deg, 10deg); text-align: center; } .content h2 { color: #fff; font-size: 80px; }</style>
Final Code: It is the combination of the above two code sections by combining the above two sections we can achieve the skewed background.
Program:<!DOCTYPE html><html> <head> <meta> <title> Skewed Background using HTML and CSS </title></head><style> body { margin: 0; padding: 0; font-family: serif; } section:hover { background-image: linear-gradient(to left, green , yellow); transition-time: 5s; } section { display: flex; background: green; height: 350px; justify-content: center; align-items: center; transform: skew(0deg, -10deg) translateY(-120px); } .content { margin: 0; padding: 0; position: relative; max-width: 900px; transform: skew(0deg, 10deg); text-align: center; } .content h2 { color: #fff; font-size: 80px; }</style> <body> <section> <div class="content"> <h2>GeeksforGeeks</h2> </div> </section> </body> </html>
<!DOCTYPE html><html> <head> <meta> <title> Skewed Background using HTML and CSS </title></head><style> body { margin: 0; padding: 0; font-family: serif; } section:hover { background-image: linear-gradient(to left, green , yellow); transition-time: 5s; } section { display: flex; background: green; height: 350px; justify-content: center; align-items: center; transform: skew(0deg, -10deg) translateY(-120px); } .content { margin: 0; padding: 0; position: relative; max-width: 900px; transform: skew(0deg, 10deg); text-align: center; } .content h2 { color: #fff; font-size: 80px; }</style> <body> <section> <div class="content"> <h2>GeeksforGeeks</h2> </div> </section> </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
Web technologies Questions
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to apply style to parent if it has child with CSS?
Types of CSS (Cascading Style Sheet)
How to position a div at the bottom of its container using CSS?
Design a web page using HTML and CSS
How to set space between the flexbox ?
How to set the default value for an HTML <select> element ?
Hide or show elements in HTML using display property
How to set input type date in dd-mm-yyyy format using HTML ?
REST API (Introduction)
How to Insert Form Data into Database using PHP ? | [
{
"code": null,
"e": 25775,
"s": 25747,
"text": "\n10 May, 2020"
},
{
"code": null,
"e": 26175,
"s": 25775,
"text": "The skewed background or you can say an angel color shade background can be created by using HTML and CSS. This background can be used as a cover pic of your website that will be attractive. In this article, we will create a simple skewed background. We will divide the article into two sections in the first section we will create the structure and in the second section, we decorate the structure."
},
{
"code": null,
"e": 26274,
"s": 26175,
"text": "Creating structure: In this section, we will create the structure by using only simple HTML codes."
},
{
"code": null,
"e": 26680,
"s": 26274,
"text": "HTML Code: By using the HTML <section> tag we will create the section for our skewed background which will have a HTML <div> tag inside of it.<!DOCTYPE html><html> <head> <meta> <title> Skewed Background using HTML and CSS </title></head> <body> <section> <div class=\"content\"> <h2>GeeksforGeeks</h2> </div> </section> </body> </html> "
},
{
"code": "<!DOCTYPE html><html> <head> <meta> <title> Skewed Background using HTML and CSS </title></head> <body> <section> <div class=\"content\"> <h2>GeeksforGeeks</h2> </div> </section> </body> </html> ",
"e": 26944,
"s": 26680,
"text": null
},
{
"code": null,
"e": 27046,
"s": 26944,
"text": "Designing structure: In this section we will decorate the pre-created structure with the help of CSS."
},
{
"code": null,
"e": 27892,
"s": 27046,
"text": "CSS Code: In this section first we will use some CSS properties to design the background and then we will use the skew property of the CSS which skews an element along the x and Y axis by the given angles.<style> body { margin: 0; padding: 0; font-family: serif; } section:hover { background: linear-gradient( green , yellow); } section { display: flex; background: green; height: 350px; justify-content: center; align-items: center; transform: skew(0deg, -10deg) translateY(-120px); } .content { margin: 0; padding: 0; position: relative; max-width: 900px; transform: skew(0deg, 10deg); text-align: center; } .content h2 { color: #fff; font-size: 80px; }</style>"
},
{
"code": "<style> body { margin: 0; padding: 0; font-family: serif; } section:hover { background: linear-gradient( green , yellow); } section { display: flex; background: green; height: 350px; justify-content: center; align-items: center; transform: skew(0deg, -10deg) translateY(-120px); } .content { margin: 0; padding: 0; position: relative; max-width: 900px; transform: skew(0deg, 10deg); text-align: center; } .content h2 { color: #fff; font-size: 80px; }</style>",
"e": 28533,
"s": 27892,
"text": null
},
{
"code": null,
"e": 28672,
"s": 28533,
"text": "Final Code: It is the combination of the above two code sections by combining the above two sections we can achieve the skewed background."
},
{
"code": null,
"e": 29605,
"s": 28672,
"text": "Program:<!DOCTYPE html><html> <head> <meta> <title> Skewed Background using HTML and CSS </title></head><style> body { margin: 0; padding: 0; font-family: serif; } section:hover { background-image: linear-gradient(to left, green , yellow); transition-time: 5s; } section { display: flex; background: green; height: 350px; justify-content: center; align-items: center; transform: skew(0deg, -10deg) translateY(-120px); } .content { margin: 0; padding: 0; position: relative; max-width: 900px; transform: skew(0deg, 10deg); text-align: center; } .content h2 { color: #fff; font-size: 80px; }</style> <body> <section> <div class=\"content\"> <h2>GeeksforGeeks</h2> </div> </section> </body> </html> "
},
{
"code": "<!DOCTYPE html><html> <head> <meta> <title> Skewed Background using HTML and CSS </title></head><style> body { margin: 0; padding: 0; font-family: serif; } section:hover { background-image: linear-gradient(to left, green , yellow); transition-time: 5s; } section { display: flex; background: green; height: 350px; justify-content: center; align-items: center; transform: skew(0deg, -10deg) translateY(-120px); } .content { margin: 0; padding: 0; position: relative; max-width: 900px; transform: skew(0deg, 10deg); text-align: center; } .content h2 { color: #fff; font-size: 80px; }</style> <body> <section> <div class=\"content\"> <h2>GeeksforGeeks</h2> </div> </section> </body> </html> ",
"e": 30530,
"s": 29605,
"text": null
},
{
"code": null,
"e": 30538,
"s": 30530,
"text": "Output:"
},
{
"code": null,
"e": 30675,
"s": 30538,
"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": 30684,
"s": 30675,
"text": "CSS-Misc"
},
{
"code": null,
"e": 30694,
"s": 30684,
"text": "HTML-Misc"
},
{
"code": null,
"e": 30698,
"s": 30694,
"text": "CSS"
},
{
"code": null,
"e": 30703,
"s": 30698,
"text": "HTML"
},
{
"code": null,
"e": 30720,
"s": 30703,
"text": "Web Technologies"
},
{
"code": null,
"e": 30747,
"s": 30720,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 30752,
"s": 30747,
"text": "HTML"
},
{
"code": null,
"e": 30850,
"s": 30752,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30905,
"s": 30850,
"text": "How to apply style to parent if it has child with CSS?"
},
{
"code": null,
"e": 30942,
"s": 30905,
"text": "Types of CSS (Cascading Style Sheet)"
},
{
"code": null,
"e": 31006,
"s": 30942,
"text": "How to position a div at the bottom of its container using CSS?"
},
{
"code": null,
"e": 31043,
"s": 31006,
"text": "Design a web page using HTML and CSS"
},
{
"code": null,
"e": 31082,
"s": 31043,
"text": "How to set space between the flexbox ?"
},
{
"code": null,
"e": 31142,
"s": 31082,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 31195,
"s": 31142,
"text": "Hide or show elements in HTML using display property"
},
{
"code": null,
"e": 31256,
"s": 31195,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
},
{
"code": null,
"e": 31280,
"s": 31256,
"text": "REST API (Introduction)"
}
] |
Python | Get first N key:value pairs in given dictionary - GeeksforGeeks | 02 Aug, 2019
Given a dictionary, the task is to get N key:value pairs from given dictionary. This type of problem can be useful while some cases, like fetching first N values in web development.
Note that the given dictionary is unordered, the first N pairs will not be same here all the time. In case, you need to maintain order in your problem, you can use ordered dictionary.
Code #1: Using itertools.islice() method
# Python program to get N key:value pairs in given dictionary# using itertools.islice() method import itertools # Initialize dictionarytest_dict = {'Geeks' : 1, 'For':2, 'is' : 3, 'best' : 4, 'for' : 5, 'CS' : 6} # printing original dictionary print("The original dictionary : " + str(test_dict)) # Initialize limit N = 3 # Using islice() + items() # Get first N items in dictionary out = dict(itertools.islice(test_dict.items(), N)) # printing result print("Dictionary limited by K is : " + str(out))
Output:
The original dictionary : {‘for’: 5, ‘best’: 4, ‘CS’: 6, ‘is’: 3, ‘Geeks’: 1, ‘For’: 2}Dictionary limited by K is : {‘for’: 5, ‘best’: 4, ‘CS’: 6}
Code #2: Using slicing on dictionary item list
# Python program to get N key:value pairs in given dictionary# using list slicing # Initialize dictionarytest_dict = {'Geeks' : 1, 'For':2, 'is' : 3, 'best' : 4, 'for' : 5, 'CS' : 6} # printing original dictionary print("The original dictionary : " + str(test_dict)) # Initialize limit N = 3 # Using items() + list slicing # Get first K items in dictionary out = dict(list(test_dict.items())[0: N]) # printing result print("Dictionary limited by K is : " + str(out))
Output:
The original dictionary : {‘best’: 3, ‘gfg’: 1, ‘is’: 2, ‘CS’: 5, ‘for’: 4}Dictionary limited by K is : {‘best’: 3, ‘gfg’: 1, ‘is’: 2}
Python dictionary-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Python program to convert a list to string
Defaultdict in Python
Python | Split string into list of characters
Python | Convert a list to dictionary
How to print without newline in Python? | [
{
"code": null,
"e": 25885,
"s": 25857,
"text": "\n02 Aug, 2019"
},
{
"code": null,
"e": 26067,
"s": 25885,
"text": "Given a dictionary, the task is to get N key:value pairs from given dictionary. This type of problem can be useful while some cases, like fetching first N values in web development."
},
{
"code": null,
"e": 26251,
"s": 26067,
"text": "Note that the given dictionary is unordered, the first N pairs will not be same here all the time. In case, you need to maintain order in your problem, you can use ordered dictionary."
},
{
"code": null,
"e": 26292,
"s": 26251,
"text": "Code #1: Using itertools.islice() method"
},
{
"code": "# Python program to get N key:value pairs in given dictionary# using itertools.islice() method import itertools # Initialize dictionarytest_dict = {'Geeks' : 1, 'For':2, 'is' : 3, 'best' : 4, 'for' : 5, 'CS' : 6} # printing original dictionary print(\"The original dictionary : \" + str(test_dict)) # Initialize limit N = 3 # Using islice() + items() # Get first N items in dictionary out = dict(itertools.islice(test_dict.items(), N)) # printing result print(\"Dictionary limited by K is : \" + str(out)) ",
"e": 26822,
"s": 26292,
"text": null
},
{
"code": null,
"e": 26830,
"s": 26822,
"text": "Output:"
},
{
"code": null,
"e": 26977,
"s": 26830,
"text": "The original dictionary : {‘for’: 5, ‘best’: 4, ‘CS’: 6, ‘is’: 3, ‘Geeks’: 1, ‘For’: 2}Dictionary limited by K is : {‘for’: 5, ‘best’: 4, ‘CS’: 6}"
},
{
"code": null,
"e": 27026,
"s": 26979,
"text": "Code #2: Using slicing on dictionary item list"
},
{
"code": "# Python program to get N key:value pairs in given dictionary# using list slicing # Initialize dictionarytest_dict = {'Geeks' : 1, 'For':2, 'is' : 3, 'best' : 4, 'for' : 5, 'CS' : 6} # printing original dictionary print(\"The original dictionary : \" + str(test_dict)) # Initialize limit N = 3 # Using items() + list slicing # Get first K items in dictionary out = dict(list(test_dict.items())[0: N]) # printing result print(\"Dictionary limited by K is : \" + str(out)) ",
"e": 27519,
"s": 27026,
"text": null
},
{
"code": null,
"e": 27527,
"s": 27519,
"text": "Output:"
},
{
"code": null,
"e": 27662,
"s": 27527,
"text": "The original dictionary : {‘best’: 3, ‘gfg’: 1, ‘is’: 2, ‘CS’: 5, ‘for’: 4}Dictionary limited by K is : {‘best’: 3, ‘gfg’: 1, ‘is’: 2}"
},
{
"code": null,
"e": 27689,
"s": 27662,
"text": "Python dictionary-programs"
},
{
"code": null,
"e": 27696,
"s": 27689,
"text": "Python"
},
{
"code": null,
"e": 27712,
"s": 27696,
"text": "Python Programs"
},
{
"code": null,
"e": 27810,
"s": 27712,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27828,
"s": 27810,
"text": "Python Dictionary"
},
{
"code": null,
"e": 27863,
"s": 27828,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 27895,
"s": 27863,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27917,
"s": 27895,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 27959,
"s": 27917,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 28002,
"s": 27959,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 28024,
"s": 28002,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 28070,
"s": 28024,
"text": "Python | Split string into list of characters"
},
{
"code": null,
"e": 28108,
"s": 28070,
"text": "Python | Convert a list to dictionary"
}
] |
Check if a number is palindrome or not without using any extra space | Set 2 - GeeksforGeeks | 20 Dec, 2021
Given a number ‘n’ and our goal is to find out it is palindrome or not without using any extra space. We can’t make a new copy of number.
Examples:
Input: n = 2332Output: Yes it is Palindrome.Explanation:original number = 2332reversed number = 2332Both are same hence the number is palindrome.
Input: n=1111Output: Yes it is Palindrome.
Input: n = 1234Output: No not Palindrome.
Other Approach: The other recursive approaches and the approach to compare the digits are discussed in Set-1 of this article. Here, we are discussing the other approaches.
Approach: This approach depends upon 3 major steps, find the number of digits in the number. Partition the number into 2 parts from the middle. Take care of the case when the length is odd, in which we will have to use the middle element twice. Check whether the number in both numbers are the same or not. Follow the steps below to solve the problem:
Initialize the variable K as the length of the number n.
Initialize the variable ans as 0.
Iterate over the range [0, K/2) using the variable i and perform the following tasks:Put the value of n%10 in the variable ans and divide n by 10.
Put the value of n%10 in the variable ans and divide n by 10.
If K%2 equals 1 then put the value of n%10 in the variable ans.
After performing the above steps, if ans equals n then it’s a pallindrome otherwise not.
Below is the implementation of the above approach.
C++
Java
Python3
C#
Javascript
// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to find if the number is a// pallindrome or notbool isPalindrome(int n){ if (n < 0) return false; if (n < 10) return true; // Find the length of the number int K = ceil(log(n) / log(10)); int ans = 0; // Partition the number into 2 halves for (int i = 0; i < K / 2; i++) { ans = ans * 10 + n % 10; n = n / 10; } if (K % 2 == 1) ans = ans * 10 + n % 10; // Equality Condition return (ans == n);} // Driver Codeint main(){ isPalindrome(1001) ? cout << "Yes, it is Palindrome" : cout << "No, not Palindrome"; return 0;}
// Java program for the above approachimport java.util.*; class GFG{ // Function to find if the number is a// pallindrome or notstatic boolean isPalindrome(int n){ if (n < 0) return false; if (n < 10) return true; // Find the length of the number int K = (int) Math.ceil(Math.log(n) / Math.log(10)); int ans = 0; // Partition the number into 2 halves for (int i = 0; i < K / 2; i++) { ans = ans * 10 + n % 10; n = n / 10; } if (K % 2 == 1) ans = ans * 10 + n % 10; // Equality Condition return (ans == n);} // Driver Codepublic static void main(String[] args){ System.out.print(isPalindrome(1001) ? "Yes, it is Palindrome" : "No, not Palindrome");}} // This code is contributed by 29AjayKumar
# Python code for the above approachimport math as Math # Function to find if the number is a# pallindrome or notdef isPalindrome(n): if (n < 0): return False if (n < 10): return True # Find the length of the number K = Math.ceil(Math.log(n) / Math.log(10)) ans = 0 # Partition the number into 2 halves for i in range(0, K // 2): ans = ans * 10 + n % 10 n = Math.floor(n / 10) if (K % 2 == 1): ans = ans * 10 + n % 10 # Equality Condition return (ans == n) # Driver Codeprint("Yes, it is Palindrome") if isPalindrome( 1001) else print("No, not Palindrome") # This code is contributed by Saurabh jaiswal
// C# program for the above approachusing System; class GFG{ // Function to find if the number is a // pallindrome or not static bool isPalindrome(int n) { if (n < 0) return false; if (n < 10) return true; // Find the length of the number int K = (int)Math.Ceiling(Math.Log(n) / Math.Log(10)); int ans = 0; // Partition the number into 2 halves for (int i = 0; i < K / 2; i++) { ans = ans * 10 + n % 10; n = n / 10; } if (K % 2 == 1) ans = ans * 10 + n % 10; // Equality Condition return (ans == n); } // Driver Code public static void Main() { Console.Write(isPalindrome(1001) ? "Yes, it is Palindrome" : "No, not Palindrome"); }} // This code is contributed by Saurabh Jaiswal
<script> // JavaScript code for the above approach // Function to find if the number is a // pallindrome or not function isPalindrome(n) { if (n < 0) return false; if (n < 10) return true; // Find the length of the number let K = Math.ceil(Math.log(n) / Math.log(10)); let ans = 0; // Partition the number into 2 halves for (let i = 0; i < K / 2; i++) { ans = ans * 10 + n % 10; n = Math.floor(n / 10); } if (K % 2 == 1) ans = ans * 10 + n % 10; // Equality Condition return (ans == n); } // Driver Code isPalindrome(1001) ? document.write("Yes, it is Palindrome") : document.write("No, not Palindrome"); // This code is contributed by Potta Lokesh </script>
Yes, it is Palindrome
Time Complexity: O(K), where K is the number of digitsAuxiliary Approach: O(1)
lokeshpotta20
29AjayKumar
_saurabh_jaiswal
number-digits
palindrome
Divide and Conquer
Mathematical
Mathematical
Divide and Conquer
palindrome
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Binary Search In JavaScript
Find a Fixed Point (Value equal to index) in a given array
Binary Search (bisect) in Python
K-th Element of Two Sorted Arrays
Convex Hull using Divide and Conquer Algorithm
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": 26135,
"s": 26107,
"text": "\n20 Dec, 2021"
},
{
"code": null,
"e": 26273,
"s": 26135,
"text": "Given a number ‘n’ and our goal is to find out it is palindrome or not without using any extra space. We can’t make a new copy of number."
},
{
"code": null,
"e": 26283,
"s": 26273,
"text": "Examples:"
},
{
"code": null,
"e": 26429,
"s": 26283,
"text": "Input: n = 2332Output: Yes it is Palindrome.Explanation:original number = 2332reversed number = 2332Both are same hence the number is palindrome."
},
{
"code": null,
"e": 26472,
"s": 26429,
"text": "Input: n=1111Output: Yes it is Palindrome."
},
{
"code": null,
"e": 26514,
"s": 26472,
"text": "Input: n = 1234Output: No not Palindrome."
},
{
"code": null,
"e": 26686,
"s": 26514,
"text": "Other Approach: The other recursive approaches and the approach to compare the digits are discussed in Set-1 of this article. Here, we are discussing the other approaches."
},
{
"code": null,
"e": 27038,
"s": 26686,
"text": "Approach: This approach depends upon 3 major steps, find the number of digits in the number. Partition the number into 2 parts from the middle. Take care of the case when the length is odd, in which we will have to use the middle element twice. Check whether the number in both numbers are the same or not. Follow the steps below to solve the problem:"
},
{
"code": null,
"e": 27095,
"s": 27038,
"text": "Initialize the variable K as the length of the number n."
},
{
"code": null,
"e": 27129,
"s": 27095,
"text": "Initialize the variable ans as 0."
},
{
"code": null,
"e": 27276,
"s": 27129,
"text": "Iterate over the range [0, K/2) using the variable i and perform the following tasks:Put the value of n%10 in the variable ans and divide n by 10."
},
{
"code": null,
"e": 27338,
"s": 27276,
"text": "Put the value of n%10 in the variable ans and divide n by 10."
},
{
"code": null,
"e": 27402,
"s": 27338,
"text": "If K%2 equals 1 then put the value of n%10 in the variable ans."
},
{
"code": null,
"e": 27491,
"s": 27402,
"text": "After performing the above steps, if ans equals n then it’s a pallindrome otherwise not."
},
{
"code": null,
"e": 27542,
"s": 27491,
"text": "Below is the implementation of the above approach."
},
{
"code": null,
"e": 27546,
"s": 27542,
"text": "C++"
},
{
"code": null,
"e": 27551,
"s": 27546,
"text": "Java"
},
{
"code": null,
"e": 27559,
"s": 27551,
"text": "Python3"
},
{
"code": null,
"e": 27562,
"s": 27559,
"text": "C#"
},
{
"code": null,
"e": 27573,
"s": 27562,
"text": "Javascript"
},
{
"code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to find if the number is a// pallindrome or notbool isPalindrome(int n){ if (n < 0) return false; if (n < 10) return true; // Find the length of the number int K = ceil(log(n) / log(10)); int ans = 0; // Partition the number into 2 halves for (int i = 0; i < K / 2; i++) { ans = ans * 10 + n % 10; n = n / 10; } if (K % 2 == 1) ans = ans * 10 + n % 10; // Equality Condition return (ans == n);} // Driver Codeint main(){ isPalindrome(1001) ? cout << \"Yes, it is Palindrome\" : cout << \"No, not Palindrome\"; return 0;}",
"e": 28284,
"s": 27573,
"text": null
},
{
"code": "// Java program for the above approachimport java.util.*; class GFG{ // Function to find if the number is a// pallindrome or notstatic boolean isPalindrome(int n){ if (n < 0) return false; if (n < 10) return true; // Find the length of the number int K = (int) Math.ceil(Math.log(n) / Math.log(10)); int ans = 0; // Partition the number into 2 halves for (int i = 0; i < K / 2; i++) { ans = ans * 10 + n % 10; n = n / 10; } if (K % 2 == 1) ans = ans * 10 + n % 10; // Equality Condition return (ans == n);} // Driver Codepublic static void main(String[] args){ System.out.print(isPalindrome(1001) ? \"Yes, it is Palindrome\" : \"No, not Palindrome\");}} // This code is contributed by 29AjayKumar",
"e": 29074,
"s": 28284,
"text": null
},
{
"code": "# Python code for the above approachimport math as Math # Function to find if the number is a# pallindrome or notdef isPalindrome(n): if (n < 0): return False if (n < 10): return True # Find the length of the number K = Math.ceil(Math.log(n) / Math.log(10)) ans = 0 # Partition the number into 2 halves for i in range(0, K // 2): ans = ans * 10 + n % 10 n = Math.floor(n / 10) if (K % 2 == 1): ans = ans * 10 + n % 10 # Equality Condition return (ans == n) # Driver Codeprint(\"Yes, it is Palindrome\") if isPalindrome( 1001) else print(\"No, not Palindrome\") # This code is contributed by Saurabh jaiswal",
"e": 29749,
"s": 29074,
"text": null
},
{
"code": "// C# program for the above approachusing System; class GFG{ // Function to find if the number is a // pallindrome or not static bool isPalindrome(int n) { if (n < 0) return false; if (n < 10) return true; // Find the length of the number int K = (int)Math.Ceiling(Math.Log(n) / Math.Log(10)); int ans = 0; // Partition the number into 2 halves for (int i = 0; i < K / 2; i++) { ans = ans * 10 + n % 10; n = n / 10; } if (K % 2 == 1) ans = ans * 10 + n % 10; // Equality Condition return (ans == n); } // Driver Code public static void Main() { Console.Write(isPalindrome(1001) ? \"Yes, it is Palindrome\" : \"No, not Palindrome\"); }} // This code is contributed by Saurabh Jaiswal",
"e": 30507,
"s": 29749,
"text": null
},
{
"code": "<script> // JavaScript code for the above approach // Function to find if the number is a // pallindrome or not function isPalindrome(n) { if (n < 0) return false; if (n < 10) return true; // Find the length of the number let K = Math.ceil(Math.log(n) / Math.log(10)); let ans = 0; // Partition the number into 2 halves for (let i = 0; i < K / 2; i++) { ans = ans * 10 + n % 10; n = Math.floor(n / 10); } if (K % 2 == 1) ans = ans * 10 + n % 10; // Equality Condition return (ans == n); } // Driver Code isPalindrome(1001) ? document.write(\"Yes, it is Palindrome\") : document.write(\"No, not Palindrome\"); // This code is contributed by Potta Lokesh </script>",
"e": 31407,
"s": 30507,
"text": null
},
{
"code": null,
"e": 31432,
"s": 31410,
"text": "Yes, it is Palindrome"
},
{
"code": null,
"e": 31513,
"s": 31434,
"text": "Time Complexity: O(K), where K is the number of digitsAuxiliary Approach: O(1)"
},
{
"code": null,
"e": 31529,
"s": 31515,
"text": "lokeshpotta20"
},
{
"code": null,
"e": 31541,
"s": 31529,
"text": "29AjayKumar"
},
{
"code": null,
"e": 31558,
"s": 31541,
"text": "_saurabh_jaiswal"
},
{
"code": null,
"e": 31572,
"s": 31558,
"text": "number-digits"
},
{
"code": null,
"e": 31583,
"s": 31572,
"text": "palindrome"
},
{
"code": null,
"e": 31602,
"s": 31583,
"text": "Divide and Conquer"
},
{
"code": null,
"e": 31615,
"s": 31602,
"text": "Mathematical"
},
{
"code": null,
"e": 31628,
"s": 31615,
"text": "Mathematical"
},
{
"code": null,
"e": 31647,
"s": 31628,
"text": "Divide and Conquer"
},
{
"code": null,
"e": 31658,
"s": 31647,
"text": "palindrome"
},
{
"code": null,
"e": 31756,
"s": 31658,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31784,
"s": 31756,
"text": "Binary Search In JavaScript"
},
{
"code": null,
"e": 31843,
"s": 31784,
"text": "Find a Fixed Point (Value equal to index) in a given array"
},
{
"code": null,
"e": 31876,
"s": 31843,
"text": "Binary Search (bisect) in Python"
},
{
"code": null,
"e": 31910,
"s": 31876,
"text": "K-th Element of Two Sorted Arrays"
},
{
"code": null,
"e": 31957,
"s": 31910,
"text": "Convex Hull using Divide and Conquer Algorithm"
},
{
"code": null,
"e": 31987,
"s": 31957,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 32047,
"s": 31987,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 32062,
"s": 32047,
"text": "C++ Data Types"
},
{
"code": null,
"e": 32105,
"s": 32062,
"text": "Set in C++ Standard Template Library (STL)"
}
] |
How to change the value of a global variable inside of a function using JavaScript ? - GeeksforGeeks | 15 Apr, 2020
Pre-requisite: Global and Local variables in JavaScript
Local Scope: Variables which are declared inside a function is called local variables and these are accessed only inside the function. Local variables are deleted when the function is completed.
Global Scope: Global variables can be accessed from inside and outside the function. They are deleted when the browser window is closed but is available to other pages loaded on the same window. There are two ways to declare a variable globally:
Declare a variable outside the functions.
Assign value to a variable inside a function without declaring it using “var” keyword.
<!DOCTYPE html><html> <head> <title> How to change the value of a global variable inside of a function using JavaScript? </title> <script> // Declare global variables var globalFirstNum1 = 9; var globalSecondNum1 = 8; function add() { // Access and change globalFirstNum1 and globalSecondNum1 globalFirstNum1 = Number(document.getElementById("fNum").value); globalSecondNum1 = Number(document.getElementById("sNum").value); // Add local variables var result = globalFirstNum1 + globalSecondNum1; var output = "Sum of 2 numbers is " + result; // Display result document.getElementById("result").innerHTML = output; } // Declare global variables globalFirstNum2 = 8; globalSecondNum2 = 9; function subtract() { // Access and change globalFirstNum2 // and globalSecondNum2 globalFirstNum2 = Number(document.getElementById("fNum").value); globalSecondNum2 = Number(document.getElementById("sNum").value); // Use global variables to subtract numbers var result = globalFirstNum2-globalSecondNum2; var output = "Difference of 2 numbers is " + result; document.getElementById("result").innerHTML = output; } </script></head> <body style="text-align:center;"> <h1 style="color:green"> GeeksForGeeks </h1> <b>Enter first number :- </b> <input type="number" id="fNum"> <br><br> <b>Enter second number :- </b> <input type="number" id="sNum"> <br><br> <button onclick="add()">Add</button> <button onclick="subtract()">Subtract</button> <p id="result" style = "color:green; font-weight:bold;"> </p></body> </html>
Output:
Before clicking the button:
After clicking add button:
After clicking subtract button:
nehasharmatechnians
javascript-basics
javascript-functions
Picked
JavaScript
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to calculate the number of days between two dates in javascript?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS? | [
{
"code": null,
"e": 39215,
"s": 39187,
"text": "\n15 Apr, 2020"
},
{
"code": null,
"e": 39271,
"s": 39215,
"text": "Pre-requisite: Global and Local variables in JavaScript"
},
{
"code": null,
"e": 39466,
"s": 39271,
"text": "Local Scope: Variables which are declared inside a function is called local variables and these are accessed only inside the function. Local variables are deleted when the function is completed."
},
{
"code": null,
"e": 39712,
"s": 39466,
"text": "Global Scope: Global variables can be accessed from inside and outside the function. They are deleted when the browser window is closed but is available to other pages loaded on the same window. There are two ways to declare a variable globally:"
},
{
"code": null,
"e": 39754,
"s": 39712,
"text": "Declare a variable outside the functions."
},
{
"code": null,
"e": 39841,
"s": 39754,
"text": "Assign value to a variable inside a function without declaring it using “var” keyword."
},
{
"code": "<!DOCTYPE html><html> <head> <title> How to change the value of a global variable inside of a function using JavaScript? </title> <script> // Declare global variables var globalFirstNum1 = 9; var globalSecondNum1 = 8; function add() { // Access and change globalFirstNum1 and globalSecondNum1 globalFirstNum1 = Number(document.getElementById(\"fNum\").value); globalSecondNum1 = Number(document.getElementById(\"sNum\").value); // Add local variables var result = globalFirstNum1 + globalSecondNum1; var output = \"Sum of 2 numbers is \" + result; // Display result document.getElementById(\"result\").innerHTML = output; } // Declare global variables globalFirstNum2 = 8; globalSecondNum2 = 9; function subtract() { // Access and change globalFirstNum2 // and globalSecondNum2 globalFirstNum2 = Number(document.getElementById(\"fNum\").value); globalSecondNum2 = Number(document.getElementById(\"sNum\").value); // Use global variables to subtract numbers var result = globalFirstNum2-globalSecondNum2; var output = \"Difference of 2 numbers is \" + result; document.getElementById(\"result\").innerHTML = output; } </script></head> <body style=\"text-align:center;\"> <h1 style=\"color:green\"> GeeksForGeeks </h1> <b>Enter first number :- </b> <input type=\"number\" id=\"fNum\"> <br><br> <b>Enter second number :- </b> <input type=\"number\" id=\"sNum\"> <br><br> <button onclick=\"add()\">Add</button> <button onclick=\"subtract()\">Subtract</button> <p id=\"result\" style = \"color:green; font-weight:bold;\"> </p></body> </html>",
"e": 41869,
"s": 39841,
"text": null
},
{
"code": null,
"e": 41877,
"s": 41869,
"text": "Output:"
},
{
"code": null,
"e": 41905,
"s": 41877,
"text": "Before clicking the button:"
},
{
"code": null,
"e": 41932,
"s": 41905,
"text": "After clicking add button:"
},
{
"code": null,
"e": 41964,
"s": 41932,
"text": "After clicking subtract button:"
},
{
"code": null,
"e": 41984,
"s": 41964,
"text": "nehasharmatechnians"
},
{
"code": null,
"e": 42002,
"s": 41984,
"text": "javascript-basics"
},
{
"code": null,
"e": 42023,
"s": 42002,
"text": "javascript-functions"
},
{
"code": null,
"e": 42030,
"s": 42023,
"text": "Picked"
},
{
"code": null,
"e": 42041,
"s": 42030,
"text": "JavaScript"
},
{
"code": null,
"e": 42058,
"s": 42041,
"text": "Web Technologies"
},
{
"code": null,
"e": 42085,
"s": 42058,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 42183,
"s": 42085,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 42223,
"s": 42183,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 42268,
"s": 42223,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 42329,
"s": 42268,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 42401,
"s": 42329,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 42470,
"s": 42401,
"text": "How to calculate the number of days between two dates in javascript?"
},
{
"code": null,
"e": 42510,
"s": 42470,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 42543,
"s": 42510,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 42588,
"s": 42543,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 42631,
"s": 42588,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
Check if a Binary Tree is univalued or not - GeeksforGeeks | 19 Jan, 2022
Given a binary tree, the task is to check if the binary tree is univalued or not. If found to be true, then print “YES”. Otherwise, print “NO”.
A binary tree is univalued if every node in the tree has the same value.
Example:
Input:
1
/ \
1 1
/ \ \
1 1 1
Output: YES Explanation: The value of all the nodes in the binary tree is equal to 1. Therefore, the required output is YES.
Input:
9
/ \
2 4
/ \ \
-1 3 0
Output: NO
DFS-based Approach: The idea is to traverse the tree using DFS and check if every node of the binary tree have the same value as the root node of the binary tree or not. If found to be true, then print “YES”. Otherwise, print “NO”.
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; // Structure of a tree nodestruct Node { int data; Node* left; Node* right;}; // Function to insert a new node// in a binary treeNode* newNode(int data){ Node* temp = new Node; temp->data = data; temp->left = temp->right = NULL; return (temp);} // Function to check If the tree// is uni-valued or notbool isUnivalTree(Node* root){ // If tree is an empty tree if (!root) { return true; } // If all the nodes on the left subtree // have not value equal to root node if (root->left != NULL && root->data != root->left->data) return false; // If all the nodes on the left subtree // have not value equal to root node if (root->right != NULL && root->data != root->right->data) return false; // Recurse on left and right subtree return isUnivalTree(root->left) && isUnivalTree(root->right);} // Driver Codeint main(){ /* 1 / \ 1 1 / \ \ 1 1 1 */ Node* root = newNode(1); root->left = newNode(1); root->right = newNode(1); root->left->left = newNode(1); root->left->right = newNode(1); root->right->right = newNode(1); if (isUnivalTree(root) == 1) { cout << "YES"; } else { cout << "NO"; } return 0;}
// Java Program for the above approachimport java.util.*;class GFG{ // Structure of a tree nodestatic class Node{ int data; Node left; Node right;}; // Function to insert a new node// in a binary treestatic Node newNode(int data){ Node temp = new Node(); temp.data = data; temp.left = temp.right = null; return (temp);} // Function to check If the tree// is uni-valued or notstatic boolean isUnivalTree(Node root){ // If tree is an empty tree if (root == null) { return true; } // If all the nodes on the left subtree // have not value equal to root node if (root.left != null && root.data != root.left.data) return false; // If all the nodes on the left subtree // have not value equal to root node if (root.right != null && root.data != root.right.data) return false; // Recurse on left and right subtree return isUnivalTree(root.left) && isUnivalTree(root.right);} // Driver Codepublic static void main(String[] args){ /* 1 / \ 1 1 / \ \ 1 1 1 */ Node root = newNode(1); root.left = newNode(1); root.right = newNode(1); root.left.left = newNode(1); root.left.right = newNode(1); root.right.right = newNode(1); if (isUnivalTree(root)) { System.out.print("YES"); } else { System.out.print("NO"); }}} // This code is contributed by 29AjayKumar
# python3 Program for the above approach # Structure of a tree nodeclass Node: def __init__(self, x): self.data = x self.left = None self.right = None # Function to check If the tree# is uni-valued or notdef isUnivalTree(root): # If tree is an empty tree if (not root): return True # If all the nodes on the left subtree # have not value equal to root node if (root.left != None and root.data != root.left.data): return False # If all the nodes on the left subtree # have not value equal to root node if (root.right != None and root.data != root.right.data): return False # Recurse on left and right subtree return isUnivalTree(root.left) and isUnivalTree(root.right) # Driver Codeif __name__ == '__main__': # /* # 1 # / \ # 1 1 # / \ \ # 1 1 1 # */ root = Node(1) root.left = Node(1) root.right = Node(1) root.left.left = Node(1) root.left.right = Node(1) root.right.right = Node(1) if (isUnivalTree(root) == 1): print("YES") else: print("NO") # This code is contribute by mohit kumar 29
// C# Program for the above approachusing System;class GFG{ // Structure of a tree nodeclass Node{ public int data; public Node left; public Node right;}; // Function to insert a new node// in a binary treestatic Node newNode(int data){ Node temp = new Node(); temp.data = data; temp.left = temp.right = null; return (temp);} // Function to check If the tree// is uni-valued or notstatic bool isUnivalTree(Node root){ // If tree is an empty tree if (root == null) { return true; } // If all the nodes on the left subtree // have not value equal to root node if (root.left != null && root.data != root.left.data) return false; // If all the nodes on the left subtree // have not value equal to root node if (root.right != null && root.data != root.right.data) return false; // Recurse on left and right subtree return isUnivalTree(root.left) && isUnivalTree(root.right);} // Driver Codepublic static void Main(String[] args){ /* 1 / \ 1 1 / \ \ 1 1 1 */ Node root = newNode(1); root.left = newNode(1); root.right = newNode(1); root.left.left = newNode(1); root.left.right = newNode(1); root.right.right = newNode(1); if (isUnivalTree(root)) { Console.Write("YES"); } else { Console.Write("NO"); }}} // This code is contributed by 29AjayKumar
<script> // JavaScript Program for the above approach // Structure of a tree nodeclass Node{ constructor(data) { this.data=data; this.left=this.right=null; }} // Function to check If the tree// is uni-valued or notfunction isUnivalTree(root){ // If tree is an empty tree if (root == null) { return true; } // If all the nodes on the left subtree // have not value equal to root node if (root.left != null && root.data != root.left.data) return false; // If all the nodes on the left subtree // have not value equal to root node if (root.right != null && root.data != root.right.data) return false; // Recurse on left and right subtree return isUnivalTree(root.left) && isUnivalTree(root.right);} // Driver Code/* 1 / \ 1 1 / \ \ 1 1 1 */let root = new Node(1);root.left = new Node(1);root.right = new Node(1);root.left.left = new Node(1);root.left.right = new Node(1);root.right.right = new Node(1); if (isUnivalTree(root)){ document.write("YES");}else{ document.write("NO");} // This code is contributed by unknown2108 </script>
YES
Time complexity: O(N) Auxiliary Space: O(1)
BFS-based Approach: The idea is to traverse the tree using BFS and check if every node of the binary tree have a value equal to the root node of the binary tree or not. If found to be true, then print “YES”. Otherwise, print “NO”. Follow the steps below to solve the problem:
Initialize a queue to traverse the binary tree using BFS.
Insert the root node of the binary tree into the queue.
Insert the left subtree of the tree into queue and check if value of front element of the queue equal to the value of current traversed node of the tree or not. If found to be false, then print “NO”.
Insert the right subtree of the tree into queue and check if value of front element of the queue equal to the value of current traversed node of the tree or not. If found to be false, then print “NO”.
Otherwise, If all the nodes of the tree are traversed and value of each node equal to the value of root node, then print “YES”.
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; // Structure of a tree nodestruct Node { int data; Node* left; Node* right;}; // Function to insert a new node// in a binary treeNode* newNode(int data){ Node* temp = new Node; temp->data = data; temp->left = temp->right = NULL; return (temp);} // Function to check If the tree// is univalued or notbool isUnivalTree(Node* root){ // If tree is an empty tree if (!root) { return true; } // Store nodes at each level // of the tree queue<Node*> q; // Insert root node q.push(root); // Stores value of root node int rootVal = root->data; // Traverse the tree using BFS while (!q.empty()) { // Stores front element // of the queue Node* currRoot = q.front(); // If value of traversed node // not equal to value of root node if (currRoot->data != rootVal) { return false; } // If left subtree is not NULL if (currRoot->left) { // Insert left subtree q.push(currRoot->left); } // If right subtree is not NULL if (currRoot->right) { // Insert right subtree q.push(currRoot->right); } // Remove front element // of the queue q.pop(); } return true;} // Driver Codeint main(){ /* 1 / \ 1 1 / \ \ 1 1 1 */ Node* root = newNode(1); root->left = newNode(1); root->right = newNode(1); root->left->left = newNode(1); root->left->right = newNode(1); root->right->right = newNode(1); if (isUnivalTree(root) == 1) { cout << "YES"; } else { cout << "NO"; } return 0;}
// Java program for the above approachimport java.io.*;import java.util.*; class GFG { // Structure of a tree node static class Node { int data; Node left; Node right; }; // Function to insert a new node // in a binary tree static Node newNode(int data) { Node temp = new Node(); temp.data = data; temp.left = temp.right = null; return (temp); } // Function to check If the tree // is univalued or not static boolean isUnivalTree(Node root) { // If tree is an empty tree if (root == null) { return true; } // Store nodes at each level // of the tree Queue<Node> q = new LinkedList<>(); // Insert root node q.add(root); // Stores value of root node int rootVal = root.data; // Traverse the tree using BFS while (!q.isEmpty()) { // Stores front element // of the queue Node currRoot = q.peek(); // If value of traversed node // not equal to value of root node if (currRoot.data != rootVal) { return false; } // If left subtree is not NULL if (currRoot.left != null) { // Insert left subtree q.add(currRoot.left); } // If right subtree is not NULL if (currRoot.right != null) { // Insert right subtree q.add(currRoot.right); } // Remove front element // of the queue q.remove(); } return true; } // Driver Code public static void main(String[] args) { /* 1 / \ 1 1 / \ \ 1 1 1 */ Node root = newNode(1); root.left = newNode(1); root.right = newNode(1); root.left.left = newNode(1); root.left.right = newNode(1); root.right.right = newNode(1); if (isUnivalTree(root)) { System.out.print("YES"); } else { System.out.print("NO"); } }} // This code is contributed by Dharanendra L V.
# Python program for the above approach # Structure of a tree nodeclass node: # Function to insert a new node # in a binary tree def __init__(self, x): self.data = x self.left = None self.right = None # Function to check If the tree# is univalued or notdef isUnivalTree(root): # If tree is an empty tree if(root == None): return True # Store nodes at each level # of the tree q = [] # Insert root node q.append(root) # Stores value of root node rootVal = root.data # Traverse the tree using BFS while(len(q) != 0): # Stores front element # of the queue currRoot = q[0] # If value of traversed node # not equal to value of root node if (currRoot.data != rootVal): return False # If left subtree is not NULL if (currRoot.left != None): # Insert left subtree q.append(currRoot.left) # If right subtree is not NULL if(currRoot.right != None): # Insert right subtree q.append(currRoot.right) # Remove front element # of the queue q.pop(0) return True # Driver Codeif __name__ == '__main__': # # 1 # / \ # 1 1 # / \ \ # 1 1 1 root=node(1) root.left= node(1) root.right = node(1) root.left.left = node(1) root.left.right = node(1) root.right.right = node(1) if(isUnivalTree(root)): print("YES") else: print("NO") # This code is contributed by avanitrachhadiya2155
// C# program for the above approachusing System;using System.Collections.Generic;public class GFG{ // Structure of a tree node class Node { public int data; public Node left; public Node right; }; // Function to insert a new node // in a binary tree static Node newNode(int data) { Node temp = new Node(); temp.data = data; temp.left = temp.right = null; return (temp); } // Function to check If the tree // is univalued or not static bool isUnivalTree(Node root) { // If tree is an empty tree if (root == null) { return true; } // Store nodes at each level // of the tree Queue<Node> q = new Queue<Node>(); // Insert root node q.Enqueue(root); // Stores value of root node int rootVal = root.data; // Traverse the tree using BFS while (q.Count != 0) { // Stores front element // of the queue Node currRoot = q.Peek(); // If value of traversed node // not equal to value of root node if (currRoot.data != rootVal) { return false; } // If left subtree is not NULL if (currRoot.left != null) { // Insert left subtree q.Enqueue(currRoot.left); } // If right subtree is not NULL if (currRoot.right != null) { // Insert right subtree q.Enqueue(currRoot.right); } // Remove front element // of the queue q.Dequeue(); } return true; } // Driver Code public static void Main(String[] args) { /* 1 / \ 1 1 / \ \ 1 1 1 */ Node root = newNode(1); root.left = newNode(1); root.right = newNode(1); root.left.left = newNode(1); root.left.right = newNode(1); root.right.right = newNode(1); if (isUnivalTree(root)) { Console.Write("YES"); } else { Console.Write("NO"); } }} // This code is contributed by 29AjayKumar
<script>// Javascript program for the above approach // Structure of a tree nodeclass Node{ // Function to insert a new node // in a binary tree constructor(data) { this.data=data; this.left=this.right=null; }} // Function to check If the tree // is univalued or notfunction isUnivalTree(root){ // If tree is an empty tree if (root == null) { return true; } // Store nodes at each level // of the tree let q = []; // Insert root node q.push(root); // Stores value of root node let rootVal = root.data; // Traverse the tree using BFS while (q.length!=0) { // Stores front element // of the queue let currRoot = q[0]; // If value of traversed node // not equal to value of root node if (currRoot.data != rootVal) { return false; } // If left subtree is not NULL if (currRoot.left != null) { // Insert left subtree q.push(currRoot.left); } // If right subtree is not NULL if (currRoot.right != null) { // Insert right subtree q.push(currRoot.right); } // Remove front element // of the queue q.shift(); } return true;} // Driver Code /* 1 / \ 1 1 / \ \ 1 1 1 */ let root = new Node(1); root.left = new Node(1); root.right = new Node(1); root.left.left = new Node(1); root.left.right = new Node(1); root.right.right = new Node(1); if (isUnivalTree(root)) { document.write("YES"); } else { document.write("NO"); } // This code is contributed by patel2127</script>
YES
Time complexity: O(N) Auxiliary Space: O(N)
mohit kumar 29
29AjayKumar
dharanendralv23
avanitrachhadiya2155
unknown2108
patel2127
sumitgumber28
Misc
Misc
Misc
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Activation Functions
Characteristics of Internet of Things
Advantages and Disadvantages of OOP
Sensors in Internet of Things(IoT)
Challenges in Internet of things (IoT)
Election algorithm and distributed processing
Introduction to Internet of Things (IoT) | Set 1
Introduction to Electronic Mail
Communication Models in IoT (Internet of Things )
Introduction to Parallel Computing | [
{
"code": null,
"e": 25918,
"s": 25890,
"text": "\n19 Jan, 2022"
},
{
"code": null,
"e": 26062,
"s": 25918,
"text": "Given a binary tree, the task is to check if the binary tree is univalued or not. If found to be true, then print “YES”. Otherwise, print “NO”."
},
{
"code": null,
"e": 26135,
"s": 26062,
"text": "A binary tree is univalued if every node in the tree has the same value."
},
{
"code": null,
"e": 26144,
"s": 26135,
"text": "Example:"
},
{
"code": null,
"e": 26153,
"s": 26144,
"text": "Input: "
},
{
"code": null,
"e": 26273,
"s": 26153,
"text": " 1\n / \\\n 1 1 \n / \\ \\\n 1 1 1"
},
{
"code": null,
"e": 26398,
"s": 26273,
"text": "Output: YES Explanation: The value of all the nodes in the binary tree is equal to 1. Therefore, the required output is YES."
},
{
"code": null,
"e": 26407,
"s": 26398,
"text": "Input: "
},
{
"code": null,
"e": 26520,
"s": 26407,
"text": " 9\n / \\\n 2 4 \n / \\ \\\n -1 3 0"
},
{
"code": null,
"e": 26531,
"s": 26520,
"text": "Output: NO"
},
{
"code": null,
"e": 26766,
"s": 26534,
"text": "DFS-based Approach: The idea is to traverse the tree using DFS and check if every node of the binary tree have the same value as the root node of the binary tree or not. If found to be true, then print “YES”. Otherwise, print “NO”."
},
{
"code": null,
"e": 26817,
"s": 26766,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 26821,
"s": 26817,
"text": "C++"
},
{
"code": null,
"e": 26826,
"s": 26821,
"text": "Java"
},
{
"code": null,
"e": 26834,
"s": 26826,
"text": "Python3"
},
{
"code": null,
"e": 26837,
"s": 26834,
"text": "C#"
},
{
"code": null,
"e": 26848,
"s": 26837,
"text": "Javascript"
},
{
"code": "// C++ Program for the above approach #include <bits/stdc++.h>using namespace std; // Structure of a tree nodestruct Node { int data; Node* left; Node* right;}; // Function to insert a new node// in a binary treeNode* newNode(int data){ Node* temp = new Node; temp->data = data; temp->left = temp->right = NULL; return (temp);} // Function to check If the tree// is uni-valued or notbool isUnivalTree(Node* root){ // If tree is an empty tree if (!root) { return true; } // If all the nodes on the left subtree // have not value equal to root node if (root->left != NULL && root->data != root->left->data) return false; // If all the nodes on the left subtree // have not value equal to root node if (root->right != NULL && root->data != root->right->data) return false; // Recurse on left and right subtree return isUnivalTree(root->left) && isUnivalTree(root->right);} // Driver Codeint main(){ /* 1 / \\ 1 1 / \\ \\ 1 1 1 */ Node* root = newNode(1); root->left = newNode(1); root->right = newNode(1); root->left->left = newNode(1); root->left->right = newNode(1); root->right->right = newNode(1); if (isUnivalTree(root) == 1) { cout << \"YES\"; } else { cout << \"NO\"; } return 0;}",
"e": 28263,
"s": 26848,
"text": null
},
{
"code": "// Java Program for the above approachimport java.util.*;class GFG{ // Structure of a tree nodestatic class Node{ int data; Node left; Node right;}; // Function to insert a new node// in a binary treestatic Node newNode(int data){ Node temp = new Node(); temp.data = data; temp.left = temp.right = null; return (temp);} // Function to check If the tree// is uni-valued or notstatic boolean isUnivalTree(Node root){ // If tree is an empty tree if (root == null) { return true; } // If all the nodes on the left subtree // have not value equal to root node if (root.left != null && root.data != root.left.data) return false; // If all the nodes on the left subtree // have not value equal to root node if (root.right != null && root.data != root.right.data) return false; // Recurse on left and right subtree return isUnivalTree(root.left) && isUnivalTree(root.right);} // Driver Codepublic static void main(String[] args){ /* 1 / \\ 1 1 / \\ \\ 1 1 1 */ Node root = newNode(1); root.left = newNode(1); root.right = newNode(1); root.left.left = newNode(1); root.left.right = newNode(1); root.right.right = newNode(1); if (isUnivalTree(root)) { System.out.print(\"YES\"); } else { System.out.print(\"NO\"); }}} // This code is contributed by 29AjayKumar",
"e": 29748,
"s": 28263,
"text": null
},
{
"code": "# python3 Program for the above approach # Structure of a tree nodeclass Node: def __init__(self, x): self.data = x self.left = None self.right = None # Function to check If the tree# is uni-valued or notdef isUnivalTree(root): # If tree is an empty tree if (not root): return True # If all the nodes on the left subtree # have not value equal to root node if (root.left != None and root.data != root.left.data): return False # If all the nodes on the left subtree # have not value equal to root node if (root.right != None and root.data != root.right.data): return False # Recurse on left and right subtree return isUnivalTree(root.left) and isUnivalTree(root.right) # Driver Codeif __name__ == '__main__': # /* # 1 # / \\ # 1 1 # / \\ \\ # 1 1 1 # */ root = Node(1) root.left = Node(1) root.right = Node(1) root.left.left = Node(1) root.left.right = Node(1) root.right.right = Node(1) if (isUnivalTree(root) == 1): print(\"YES\") else: print(\"NO\") # This code is contribute by mohit kumar 29",
"e": 30947,
"s": 29748,
"text": null
},
{
"code": "// C# Program for the above approachusing System;class GFG{ // Structure of a tree nodeclass Node{ public int data; public Node left; public Node right;}; // Function to insert a new node// in a binary treestatic Node newNode(int data){ Node temp = new Node(); temp.data = data; temp.left = temp.right = null; return (temp);} // Function to check If the tree// is uni-valued or notstatic bool isUnivalTree(Node root){ // If tree is an empty tree if (root == null) { return true; } // If all the nodes on the left subtree // have not value equal to root node if (root.left != null && root.data != root.left.data) return false; // If all the nodes on the left subtree // have not value equal to root node if (root.right != null && root.data != root.right.data) return false; // Recurse on left and right subtree return isUnivalTree(root.left) && isUnivalTree(root.right);} // Driver Codepublic static void Main(String[] args){ /* 1 / \\ 1 1 / \\ \\ 1 1 1 */ Node root = newNode(1); root.left = newNode(1); root.right = newNode(1); root.left.left = newNode(1); root.left.right = newNode(1); root.right.right = newNode(1); if (isUnivalTree(root)) { Console.Write(\"YES\"); } else { Console.Write(\"NO\"); }}} // This code is contributed by 29AjayKumar",
"e": 32429,
"s": 30947,
"text": null
},
{
"code": "<script> // JavaScript Program for the above approach // Structure of a tree nodeclass Node{ constructor(data) { this.data=data; this.left=this.right=null; }} // Function to check If the tree// is uni-valued or notfunction isUnivalTree(root){ // If tree is an empty tree if (root == null) { return true; } // If all the nodes on the left subtree // have not value equal to root node if (root.left != null && root.data != root.left.data) return false; // If all the nodes on the left subtree // have not value equal to root node if (root.right != null && root.data != root.right.data) return false; // Recurse on left and right subtree return isUnivalTree(root.left) && isUnivalTree(root.right);} // Driver Code/* 1 / \\ 1 1 / \\ \\ 1 1 1 */let root = new Node(1);root.left = new Node(1);root.right = new Node(1);root.left.left = new Node(1);root.left.right = new Node(1);root.right.right = new Node(1); if (isUnivalTree(root)){ document.write(\"YES\");}else{ document.write(\"NO\");} // This code is contributed by unknown2108 </script>",
"e": 33656,
"s": 32429,
"text": null
},
{
"code": null,
"e": 33660,
"s": 33656,
"text": "YES"
},
{
"code": null,
"e": 33706,
"s": 33662,
"text": "Time complexity: O(N) Auxiliary Space: O(1)"
},
{
"code": null,
"e": 33982,
"s": 33706,
"text": "BFS-based Approach: The idea is to traverse the tree using BFS and check if every node of the binary tree have a value equal to the root node of the binary tree or not. If found to be true, then print “YES”. Otherwise, print “NO”. Follow the steps below to solve the problem:"
},
{
"code": null,
"e": 34040,
"s": 33982,
"text": "Initialize a queue to traverse the binary tree using BFS."
},
{
"code": null,
"e": 34096,
"s": 34040,
"text": "Insert the root node of the binary tree into the queue."
},
{
"code": null,
"e": 34296,
"s": 34096,
"text": "Insert the left subtree of the tree into queue and check if value of front element of the queue equal to the value of current traversed node of the tree or not. If found to be false, then print “NO”."
},
{
"code": null,
"e": 34497,
"s": 34296,
"text": "Insert the right subtree of the tree into queue and check if value of front element of the queue equal to the value of current traversed node of the tree or not. If found to be false, then print “NO”."
},
{
"code": null,
"e": 34625,
"s": 34497,
"text": "Otherwise, If all the nodes of the tree are traversed and value of each node equal to the value of root node, then print “YES”."
},
{
"code": null,
"e": 34676,
"s": 34625,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 34680,
"s": 34676,
"text": "C++"
},
{
"code": null,
"e": 34685,
"s": 34680,
"text": "Java"
},
{
"code": null,
"e": 34693,
"s": 34685,
"text": "Python3"
},
{
"code": null,
"e": 34696,
"s": 34693,
"text": "C#"
},
{
"code": null,
"e": 34707,
"s": 34696,
"text": "Javascript"
},
{
"code": "// C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Structure of a tree nodestruct Node { int data; Node* left; Node* right;}; // Function to insert a new node// in a binary treeNode* newNode(int data){ Node* temp = new Node; temp->data = data; temp->left = temp->right = NULL; return (temp);} // Function to check If the tree// is univalued or notbool isUnivalTree(Node* root){ // If tree is an empty tree if (!root) { return true; } // Store nodes at each level // of the tree queue<Node*> q; // Insert root node q.push(root); // Stores value of root node int rootVal = root->data; // Traverse the tree using BFS while (!q.empty()) { // Stores front element // of the queue Node* currRoot = q.front(); // If value of traversed node // not equal to value of root node if (currRoot->data != rootVal) { return false; } // If left subtree is not NULL if (currRoot->left) { // Insert left subtree q.push(currRoot->left); } // If right subtree is not NULL if (currRoot->right) { // Insert right subtree q.push(currRoot->right); } // Remove front element // of the queue q.pop(); } return true;} // Driver Codeint main(){ /* 1 / \\ 1 1 / \\ \\ 1 1 1 */ Node* root = newNode(1); root->left = newNode(1); root->right = newNode(1); root->left->left = newNode(1); root->left->right = newNode(1); root->right->right = newNode(1); if (isUnivalTree(root) == 1) { cout << \"YES\"; } else { cout << \"NO\"; } return 0;}",
"e": 36526,
"s": 34707,
"text": null
},
{
"code": "// Java program for the above approachimport java.io.*;import java.util.*; class GFG { // Structure of a tree node static class Node { int data; Node left; Node right; }; // Function to insert a new node // in a binary tree static Node newNode(int data) { Node temp = new Node(); temp.data = data; temp.left = temp.right = null; return (temp); } // Function to check If the tree // is univalued or not static boolean isUnivalTree(Node root) { // If tree is an empty tree if (root == null) { return true; } // Store nodes at each level // of the tree Queue<Node> q = new LinkedList<>(); // Insert root node q.add(root); // Stores value of root node int rootVal = root.data; // Traverse the tree using BFS while (!q.isEmpty()) { // Stores front element // of the queue Node currRoot = q.peek(); // If value of traversed node // not equal to value of root node if (currRoot.data != rootVal) { return false; } // If left subtree is not NULL if (currRoot.left != null) { // Insert left subtree q.add(currRoot.left); } // If right subtree is not NULL if (currRoot.right != null) { // Insert right subtree q.add(currRoot.right); } // Remove front element // of the queue q.remove(); } return true; } // Driver Code public static void main(String[] args) { /* 1 / \\ 1 1 / \\ \\ 1 1 1 */ Node root = newNode(1); root.left = newNode(1); root.right = newNode(1); root.left.left = newNode(1); root.left.right = newNode(1); root.right.right = newNode(1); if (isUnivalTree(root)) { System.out.print(\"YES\"); } else { System.out.print(\"NO\"); } }} // This code is contributed by Dharanendra L V.",
"e": 38786,
"s": 36526,
"text": null
},
{
"code": "# Python program for the above approach # Structure of a tree nodeclass node: # Function to insert a new node # in a binary tree def __init__(self, x): self.data = x self.left = None self.right = None # Function to check If the tree# is univalued or notdef isUnivalTree(root): # If tree is an empty tree if(root == None): return True # Store nodes at each level # of the tree q = [] # Insert root node q.append(root) # Stores value of root node rootVal = root.data # Traverse the tree using BFS while(len(q) != 0): # Stores front element # of the queue currRoot = q[0] # If value of traversed node # not equal to value of root node if (currRoot.data != rootVal): return False # If left subtree is not NULL if (currRoot.left != None): # Insert left subtree q.append(currRoot.left) # If right subtree is not NULL if(currRoot.right != None): # Insert right subtree q.append(currRoot.right) # Remove front element # of the queue q.pop(0) return True # Driver Codeif __name__ == '__main__': # # 1 # / \\ # 1 1 # / \\ \\ # 1 1 1 root=node(1) root.left= node(1) root.right = node(1) root.left.left = node(1) root.left.right = node(1) root.right.right = node(1) if(isUnivalTree(root)): print(\"YES\") else: print(\"NO\") # This code is contributed by avanitrachhadiya2155",
"e": 40529,
"s": 38786,
"text": null
},
{
"code": "// C# program for the above approachusing System;using System.Collections.Generic;public class GFG{ // Structure of a tree node class Node { public int data; public Node left; public Node right; }; // Function to insert a new node // in a binary tree static Node newNode(int data) { Node temp = new Node(); temp.data = data; temp.left = temp.right = null; return (temp); } // Function to check If the tree // is univalued or not static bool isUnivalTree(Node root) { // If tree is an empty tree if (root == null) { return true; } // Store nodes at each level // of the tree Queue<Node> q = new Queue<Node>(); // Insert root node q.Enqueue(root); // Stores value of root node int rootVal = root.data; // Traverse the tree using BFS while (q.Count != 0) { // Stores front element // of the queue Node currRoot = q.Peek(); // If value of traversed node // not equal to value of root node if (currRoot.data != rootVal) { return false; } // If left subtree is not NULL if (currRoot.left != null) { // Insert left subtree q.Enqueue(currRoot.left); } // If right subtree is not NULL if (currRoot.right != null) { // Insert right subtree q.Enqueue(currRoot.right); } // Remove front element // of the queue q.Dequeue(); } return true; } // Driver Code public static void Main(String[] args) { /* 1 / \\ 1 1 / \\ \\ 1 1 1 */ Node root = newNode(1); root.left = newNode(1); root.right = newNode(1); root.left.left = newNode(1); root.left.right = newNode(1); root.right.right = newNode(1); if (isUnivalTree(root)) { Console.Write(\"YES\"); } else { Console.Write(\"NO\"); } }} // This code is contributed by 29AjayKumar",
"e": 42526,
"s": 40529,
"text": null
},
{
"code": "<script>// Javascript program for the above approach // Structure of a tree nodeclass Node{ // Function to insert a new node // in a binary tree constructor(data) { this.data=data; this.left=this.right=null; }} // Function to check If the tree // is univalued or notfunction isUnivalTree(root){ // If tree is an empty tree if (root == null) { return true; } // Store nodes at each level // of the tree let q = []; // Insert root node q.push(root); // Stores value of root node let rootVal = root.data; // Traverse the tree using BFS while (q.length!=0) { // Stores front element // of the queue let currRoot = q[0]; // If value of traversed node // not equal to value of root node if (currRoot.data != rootVal) { return false; } // If left subtree is not NULL if (currRoot.left != null) { // Insert left subtree q.push(currRoot.left); } // If right subtree is not NULL if (currRoot.right != null) { // Insert right subtree q.push(currRoot.right); } // Remove front element // of the queue q.shift(); } return true;} // Driver Code /* 1 / \\ 1 1 / \\ \\ 1 1 1 */ let root = new Node(1); root.left = new Node(1); root.right = new Node(1); root.left.left = new Node(1); root.left.right = new Node(1); root.right.right = new Node(1); if (isUnivalTree(root)) { document.write(\"YES\"); } else { document.write(\"NO\"); } // This code is contributed by patel2127</script>",
"e": 44503,
"s": 42526,
"text": null
},
{
"code": null,
"e": 44507,
"s": 44503,
"text": "YES"
},
{
"code": null,
"e": 44553,
"s": 44509,
"text": "Time complexity: O(N) Auxiliary Space: O(N)"
},
{
"code": null,
"e": 44568,
"s": 44553,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 44580,
"s": 44568,
"text": "29AjayKumar"
},
{
"code": null,
"e": 44596,
"s": 44580,
"text": "dharanendralv23"
},
{
"code": null,
"e": 44617,
"s": 44596,
"text": "avanitrachhadiya2155"
},
{
"code": null,
"e": 44629,
"s": 44617,
"text": "unknown2108"
},
{
"code": null,
"e": 44639,
"s": 44629,
"text": "patel2127"
},
{
"code": null,
"e": 44653,
"s": 44639,
"text": "sumitgumber28"
},
{
"code": null,
"e": 44658,
"s": 44653,
"text": "Misc"
},
{
"code": null,
"e": 44663,
"s": 44658,
"text": "Misc"
},
{
"code": null,
"e": 44668,
"s": 44663,
"text": "Misc"
},
{
"code": null,
"e": 44766,
"s": 44668,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 44787,
"s": 44766,
"text": "Activation Functions"
},
{
"code": null,
"e": 44825,
"s": 44787,
"text": "Characteristics of Internet of Things"
},
{
"code": null,
"e": 44861,
"s": 44825,
"text": "Advantages and Disadvantages of OOP"
},
{
"code": null,
"e": 44896,
"s": 44861,
"text": "Sensors in Internet of Things(IoT)"
},
{
"code": null,
"e": 44935,
"s": 44896,
"text": "Challenges in Internet of things (IoT)"
},
{
"code": null,
"e": 44981,
"s": 44935,
"text": "Election algorithm and distributed processing"
},
{
"code": null,
"e": 45030,
"s": 44981,
"text": "Introduction to Internet of Things (IoT) | Set 1"
},
{
"code": null,
"e": 45062,
"s": 45030,
"text": "Introduction to Electronic Mail"
},
{
"code": null,
"e": 45112,
"s": 45062,
"text": "Communication Models in IoT (Internet of Things )"
}
] |
Tailwind CSS Background Image - GeeksforGeeks | 23 Mar, 2022
This class accepts more than one value in tailwind CSS. All the properties are covered in class form. It is the alternative to the CSS background-image property. This class is used to set one or more background images to an element. By default, it places the image on the top left corner. To specify two or more images, separate the URLs with a comma.
Background Image classes:
bg-none: This class is used not to set any linear-gradient.
bg-gradient-to-t: This class is used to set the linear-gradient to the top.
bg-gradient-to-tr: This class is used to set the linear-gradient to the top right.
bg-gradient-to-r: This class is used to set the linear-gradient to right.
bg-gradient-to-br: This class is used to set the linear-gradient to the bottom right.
bg-gradient-to-b: This class is used to set the linear-gradient to the bottom.
bg-gradient-to-bl: This class is used to set the linear-gradient to the bottom left.
bg-gradient-to-l: This class is used to set the linear-gradient to left.
bg-gradient-to-tl: This class is used to set the linear-gradient to the top left.
Syntax:
<element class="bg-gradient-to-{direction}">...</element>
Example:
HTML
<!DOCTYPE html> <html> <head> <link href="https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css" rel="stylesheet"> </head> <body class="text-center"> <h1 class="text-green-600 text-5xl font-bold"> GeeksforGeeks </h1> <b>Tailwind CSS Background Image Class</b> <div class="mx-4 grid grid-cols-3 gap-2"> <div class="h-12 w-full bg-gradient-to-r rounded-lg from-yellow-400 via-green-500 to-blue-500"> </div> <div class="h-12 w-full bg-gradient-to-tr rounded-lg from-yellow-400 via-green-500 to-blue-500"> </div> <div class="h-12 w-full bg-gradient-to-br rounded-lg from-yellow-400 via-green-500 to-blue-500"> </div> <div class="h-12 w-full bg-gradient-to-b rounded-lg from-yellow-400 via-green-500 to-blue-500"> </div> <div class="h-12 w-full bg-gradient-to-bl rounded-lg from-yellow-400 via-green-500 to-blue-500"> </div> <div class="h-12 w-full bg-gradient-to-tl rounded-lg from-yellow-400 via-green-500 to-blue-500"> </div> <div class="h-12 w-full bg-gradient-to-l rounded-lg from-yellow-400 via-green-500 to-blue-500"> </div></body> </html>
Output:
Tailwind CSS background image
Tailwind CSS
Tailwind-Background
CSS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to insert spaces/tabs in text using HTML/CSS?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to update Node.js and NPM to next version ?
How to create footer to stay at the bottom of a Web page?
How to apply style to parent if it has child with 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 ?
How to insert spaces/tabs in text using HTML/CSS? | [
{
"code": null,
"e": 37385,
"s": 37357,
"text": "\n23 Mar, 2022"
},
{
"code": null,
"e": 37737,
"s": 37385,
"text": "This class accepts more than one value in tailwind CSS. All the properties are covered in class form. It is the alternative to the CSS background-image property. This class is used to set one or more background images to an element. By default, it places the image on the top left corner. To specify two or more images, separate the URLs with a comma."
},
{
"code": null,
"e": 37763,
"s": 37737,
"text": "Background Image classes:"
},
{
"code": null,
"e": 37823,
"s": 37763,
"text": "bg-none: This class is used not to set any linear-gradient."
},
{
"code": null,
"e": 37899,
"s": 37823,
"text": "bg-gradient-to-t: This class is used to set the linear-gradient to the top."
},
{
"code": null,
"e": 37982,
"s": 37899,
"text": "bg-gradient-to-tr: This class is used to set the linear-gradient to the top right."
},
{
"code": null,
"e": 38056,
"s": 37982,
"text": "bg-gradient-to-r: This class is used to set the linear-gradient to right."
},
{
"code": null,
"e": 38142,
"s": 38056,
"text": "bg-gradient-to-br: This class is used to set the linear-gradient to the bottom right."
},
{
"code": null,
"e": 38221,
"s": 38142,
"text": "bg-gradient-to-b: This class is used to set the linear-gradient to the bottom."
},
{
"code": null,
"e": 38306,
"s": 38221,
"text": "bg-gradient-to-bl: This class is used to set the linear-gradient to the bottom left."
},
{
"code": null,
"e": 38379,
"s": 38306,
"text": "bg-gradient-to-l: This class is used to set the linear-gradient to left."
},
{
"code": null,
"e": 38461,
"s": 38379,
"text": "bg-gradient-to-tl: This class is used to set the linear-gradient to the top left."
},
{
"code": null,
"e": 38469,
"s": 38461,
"text": "Syntax:"
},
{
"code": null,
"e": 38527,
"s": 38469,
"text": "<element class=\"bg-gradient-to-{direction}\">...</element>"
},
{
"code": null,
"e": 38536,
"s": 38527,
"text": "Example:"
},
{
"code": null,
"e": 38541,
"s": 38536,
"text": "HTML"
},
{
"code": "<!DOCTYPE html> <html> <head> <link href=\"https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css\" rel=\"stylesheet\"> </head> <body class=\"text-center\"> <h1 class=\"text-green-600 text-5xl font-bold\"> GeeksforGeeks </h1> <b>Tailwind CSS Background Image Class</b> <div class=\"mx-4 grid grid-cols-3 gap-2\"> <div class=\"h-12 w-full bg-gradient-to-r rounded-lg from-yellow-400 via-green-500 to-blue-500\"> </div> <div class=\"h-12 w-full bg-gradient-to-tr rounded-lg from-yellow-400 via-green-500 to-blue-500\"> </div> <div class=\"h-12 w-full bg-gradient-to-br rounded-lg from-yellow-400 via-green-500 to-blue-500\"> </div> <div class=\"h-12 w-full bg-gradient-to-b rounded-lg from-yellow-400 via-green-500 to-blue-500\"> </div> <div class=\"h-12 w-full bg-gradient-to-bl rounded-lg from-yellow-400 via-green-500 to-blue-500\"> </div> <div class=\"h-12 w-full bg-gradient-to-tl rounded-lg from-yellow-400 via-green-500 to-blue-500\"> </div> <div class=\"h-12 w-full bg-gradient-to-l rounded-lg from-yellow-400 via-green-500 to-blue-500\"> </div></body> </html>",
"e": 39762,
"s": 38541,
"text": null
},
{
"code": null,
"e": 39770,
"s": 39762,
"text": "Output:"
},
{
"code": null,
"e": 39800,
"s": 39770,
"text": "Tailwind CSS background image"
},
{
"code": null,
"e": 39813,
"s": 39800,
"text": "Tailwind CSS"
},
{
"code": null,
"e": 39833,
"s": 39813,
"text": "Tailwind-Background"
},
{
"code": null,
"e": 39837,
"s": 39833,
"text": "CSS"
},
{
"code": null,
"e": 39854,
"s": 39837,
"text": "Web Technologies"
},
{
"code": null,
"e": 39952,
"s": 39854,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 40002,
"s": 39952,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 40064,
"s": 40002,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 40112,
"s": 40064,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 40170,
"s": 40112,
"text": "How to create footer to stay at the bottom of a Web page?"
},
{
"code": null,
"e": 40225,
"s": 40170,
"text": "How to apply style to parent if it has child with CSS?"
},
{
"code": null,
"e": 40265,
"s": 40225,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 40298,
"s": 40265,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 40343,
"s": 40298,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 40386,
"s": 40343,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
Maximum sum path in a Matrix - GeeksforGeeks | 28 Feb, 2022
Given an n*m matrix, the task is to find the maximum sum of elements of cells starting from the cell (0, 0) to cell (n-1, m-1). However, the allowed moves are right, downwards or diagonally right, i.e, from location (i, j) next move can be (i+1, j), or, (i, j+1), or (i+1, j+1). Find the maximum sum of elements satisfying the allowed moves.Examples:
Input:
mat[][] = {{100, -350, -200},
{-100, -300, 700}}
Output: 500
Explanation:
Path followed is 100 -> -300 -> 700
Input:
mat[][] = {{500, 100, 230},
{1000, 300, 100},
{200, 1000, 200}}
Explanation:
Path followed is 500 -> 1000 -> 300 -> 1000 -> 200
Naive Approach: Recursion
Going through the Naive approach by traversing every possible path. But, this is costly. So, use Dynamic Programming here in order to reduce the time complexity.
C++
Javascript
#include <bits/stdc++.h>using namespace std;#define N 100 // No of rows and columnsint n, m; // Declaring the matrix of maximum// 100 rows and 100 columnsint a[N][N]; // For storing current sumint current_sum = 0; // For continuous update of// maximum sum requiredint total_sum = 0; // Function to Input the matrix of size n*mvoid inputMatrix(){ n = 3; m = 3; a[0][0] = 500; a[0][1] = 100; a[0][2] = 230; a[1][0] = 1000; a[1][1] = 300; a[1][2] = 100; a[2][0] = 200; a[2][1] = 1000; a[2][2] = 200;} // Function to calculate maximum sum of pathint maximum_sum_path(int i, int j){ // Checking boundary condition if (i == n - 1 && j == m - 1) return a[i][j]; // Checking whether the position hasn't // visited the last row or the last column. // Making recursive call for all the possible // moves from the current cell and then adding the // maximum returned by the calls and updating it. if (i < n - 1 & j < m - 1) { int current_sum = max(maximum_sum_path(i, j + 1), max( maximum_sum_path(i + 1, j + 1), maximum_sum_path(i + 1, j))); total_sum = a[i][j] + current_sum; } // Checking whether // position has reached last row else if (i == n - 1) total_sum = a[i][j] + maximum_sum_path(i, j + 1); // If the position is in the last column else total_sum = a[i][j] + maximum_sum_path(i + 1, j); // Returning the updated maximum value return total_sum;} // Driver Codeint main(){ inputMatrix(); // Calling the implemented function int maximum_sum = maximum_sum_path(0, 0); cout << maximum_sum; return 0;}
<script> const N = 100 // No of rows and columnslet n, m; // Declaring the matrix of maximum// 100 rows and 100 columnslet a = new Array(N);for(let i=0;i<N;i++){ a[i] = new Array(N);} // For storing current sumlet current_sum = 0; // For continuous update of// maximum sum requiredlet total_sum = 0; // Function to Input the matrix of size n*mfunction inputMatrix(){ n = 3; m = 3; a[0][0] = 500; a[0][1] = 100; a[0][2] = 230; a[1][0] = 1000; a[1][1] = 300; a[1][2] = 100; a[2][0] = 200; a[2][1] = 1000; a[2][2] = 200;} // Function to calculate maximum sum of pathfunction maximum_sum_path(i, j){ // Checking boundary condition if (i == n - 1 && j == m - 1) return a[i][j]; // Checking whether the position hasn't // visited the last row or the last column. // Making recursive call for all the possible // moves from the current cell and then adding the // maximum returned by the calls and updating it. if (i < n - 1 & j < m - 1) { let current_sum = Math.max(maximum_sum_path(i, j + 1), Math.max( maximum_sum_path(i + 1, j + 1), maximum_sum_path(i + 1, j))); total_sum = a[i][j] + current_sum; } // Checking whether // position has reached last row else if (i == n - 1) total_sum = a[i][j] + maximum_sum_path(i, j + 1); // If the position is in the last column else total_sum = a[i][j] + maximum_sum_path(i + 1, j); // Returning the updated maximum value return total_sum;} // Driver CodeinputMatrix(); // Calling the implemented functionlet maximum_sum = maximum_sum_path(0, 0); document.write(maximum_sum,"</br>"); // This code is contributed by shinjanpatra </script>
3000
Time Complexity: O(2N*M)
Auxiliary Space: O(N*M)
Efficient Approach : Dynamic programming is used to solve the above problem in a recursive way.
Allot a position at the beginning of the matrix at (0, 0).Check each next allowed position from the current position and select the path with maximum sum.Take care of the boundaries of the matrix, i.e, if the position reaches the last row or last column then the only possible choice will be right or downwards respectively.Use a map to store track of all the visiting positions and before visiting any (i, j), check whether or not the position is visited before.Update the maximum of all possible paths returned by each recursive calls made.Go till the position reaches the destination cell, i.e, (n-1.m-1).
Allot a position at the beginning of the matrix at (0, 0).
Check each next allowed position from the current position and select the path with maximum sum.
Take care of the boundaries of the matrix, i.e, if the position reaches the last row or last column then the only possible choice will be right or downwards respectively.
Use a map to store track of all the visiting positions and before visiting any (i, j), check whether or not the position is visited before.
Update the maximum of all possible paths returned by each recursive calls made.
Go till the position reaches the destination cell, i.e, (n-1.m-1).
Below is the implementation of the above approach:
C++
Java
C#
Javascript
Python3
#include <bits/stdc++.h>using namespace std;#define N 100 // No of rows and columnsint n, m; // Declaring the matrix of maximum// 100 rows and 100 columnsint a[N][N]; // Variable visited is used to keep// track of all the visited positions// Variable dp is used to store// maximum sum till current positionvector<vector<int> > dp(N, vector<int>(N)), visited(N, vector<int>(N)); // For storing current sumint current_sum = 0; // For continuous update of// maximum sum requiredint total_sum = 0; // Function to Input the matrix of size n*mvoid inputMatrix(){ n = 3; m = 3; a[0][0] = 500; a[0][1] = 100; a[0][2] = 230; a[1][0] = 1000; a[1][1] = 300; a[1][2] = 100; a[2][0] = 200; a[2][1] = 1000; a[2][2] = 200;} // Function to calculate maximum sum of pathint maximum_sum_path(int i, int j){ // Checking boundary condition if (i == n - 1 && j == m - 1) return a[i][j]; // Checking whether or not (i, j) is visited if (visited[i][j]) return dp[i][j]; // Marking (i, j) is visited visited[i][j] = 1; // Updating the maximum sum till // the current position in the dp int& total_sum = dp[i][j]; // Checking whether the position hasn't // visited the last row or the last column. // Making recursive call for all the possible // moves from the current cell and then adding the // maximum returned by the calls and updating it. if (i < n - 1 & j < m - 1) { int current_sum = max(maximum_sum_path(i, j + 1), max( maximum_sum_path(i + 1, j + 1), maximum_sum_path(i + 1, j))); total_sum = a[i][j] + current_sum; } // Checking whether // position has reached last row else if (i == n - 1) total_sum = a[i][j] + maximum_sum_path(i, j + 1); // If the position is in the last column else total_sum = a[i][j] + maximum_sum_path(i + 1, j); // Returning the updated maximum value return dp[i][j] = total_sum;} // Driver Codeint main(){ inputMatrix(); // Calling the implemented function int maximum_sum = maximum_sum_path(0, 0); cout << maximum_sum; return 0;}
class GFG{ static final int N = 100; // No of rows and columnsstatic int n, m; // Declaring the matrix of maximum// 100 rows and 100 columnsstatic int a[][] = new int[N][N]; // Variable visited is used to keep// track of all the visited positions// Variable dp is used to store// maximum sum till current positionstatic int dp[][] = new int[N][N];static int visited[][] = new int[N][N]; // For storing current sumstatic int current_sum = 0; // For continuous update of// maximum sum requiredstatic int total_sum = 0; // Function to Input the matrix// of size n*mstatic void inputMatrix(){ n = 3; m = 3; a[0][0] = 500; a[0][1] = 100; a[0][2] = 230; a[1][0] = 1000; a[1][1] = 300; a[1][2] = 100; a[2][0] = 200; a[2][1] = 1000; a[2][2] = 200;} // Function to calculate maximum sum of pathstatic int maximum_sum_path(int i, int j){ // Checking boundary condition if (i == n - 1 && j == m - 1) return a[i][j]; // Checking whether or not // (i, j) is visited if (visited[i][j] != 0) return dp[i][j]; // Marking (i, j) is visited visited[i][j] = 1; int total_sum = 0; // Checking whether the position hasn't // visited the last row or the last column. // Making recursive call for all the possible // moves from the current cell and then adding the // maximum returned by the calls and updating it. if (i < n - 1 & j < m - 1) { int current_sum = Math.max( maximum_sum_path(i, j + 1), Math.max( maximum_sum_path(i + 1, j + 1), maximum_sum_path(i + 1, j))); total_sum = a[i][j] + current_sum; } // Checking whether position // has reached last row else if (i == n - 1) total_sum = a[i][j] + maximum_sum_path(i, j + 1); // If the position is in the last column else total_sum = a[i][j] + maximum_sum_path(i + 1, j); // Updating the maximum sum till // the current position in the dp dp[i][j] = total_sum; // Returning the updated maximum value return total_sum;} // Driver Codepublic static void main(String[] args){ inputMatrix(); // Calling the implemented function int maximum_sum = maximum_sum_path(0, 0); System.out.println(maximum_sum);}} // This code is contributed by jrishabh99
// C# program to implement// the above approachusing System;class GFG{ static readonly int N = 100; // No of rows and columnsstatic int n, m; // Declaring the matrix of maximum// 100 rows and 100 columnsstatic int[,]a = new int[N, N]; // Variable visited is used to keep// track of all the visited positions// Variable dp is used to store// maximum sum till current positionstatic int [,]dp = new int[N, N];static int [,]visited = new int[N, N]; // For storing current sumstatic int current_sum = 0; // For continuous update of// maximum sum requiredstatic int total_sum = 0; // Function to Input the matrix// of size n*mstatic void inputMatrix(){ n = 3; m = 3; a[0, 0] = 500; a[0, 1] = 100; a[0, 2] = 230; a[1, 0] = 1000; a[1, 1] = 300; a[1, 2] = 100; a[2, 0] = 200; a[2, 1] = 1000; a[2, 2] = 200;} // Function to calculate maximum// sum of pathstatic int maximum_sum_path(int i, int j){ // Checking boundary condition if (i == n - 1 && j == m - 1) return a[i, j]; // Checking whether or not // (i, j) is visited if (visited[i, j] != 0) return dp[i, j]; // Marking (i, j) is visited visited[i, j] = 1; int total_sum = 0; // Checking whether the position // hasn't visited the last row // or the last column. // Making recursive call for all // the possible moves from the // current cell and then adding the // maximum returned by the calls // and updating it. if (i < n - 1 & j < m - 1) { int current_sum = Math.Max(maximum_sum_path(i, j + 1), Math.Max(maximum_sum_path(i + 1, j + 1), maximum_sum_path(i + 1, j))); total_sum = a[i, j] + current_sum; } // Checking whether position // has reached last row else if (i == n - 1) total_sum = a[i, j] + maximum_sum_path(i, j + 1); // If the position is // in the last column else total_sum = a[i, j] + maximum_sum_path(i + 1, j); // Updating the maximum // sum till the current // position in the dp dp[i, j] = total_sum; // Returning the updated // maximum value return total_sum;} // Driver Codepublic static void Main(String[] args){ inputMatrix(); // Calling the implemented function int maximum_sum = maximum_sum_path(0, 0); Console.WriteLine(maximum_sum);}} // This code is contributed by shikhasingrajput
<script> // Javascript program to implement the above approach let N = 100; // No of rows and columns let n, m; // Declaring the matrix of maximum // 100 rows and 100 columns let a = new Array(N); // Variable visited is used to keep // track of all the visited positions // Variable dp is used to store // maximum sum till current position let dp = new Array(N); let visited = new Array(N); for(let i = 0; i < N; i++) { a[i] = new Array(N); dp[i] = new Array(N); visited[i] = new Array(N); for(let j = 0; j < N; j++) { a[i][j] = 0; dp[i][j] = 0; visited[i][j] = 0; } } // For storing current sum let current_sum = 0; // For continuous update of // maximum sum required let total_sum = 0; // Function to Input the matrix // of size n*m function inputMatrix() { n = 3; m = 3; a[0][0] = 500; a[0][1] = 100; a[0][2] = 230; a[1][0] = 1000; a[1][1] = 300; a[1][2] = 100; a[2][0] = 200; a[2][1] = 1000; a[2][2] = 200; } // Function to calculate maximum sum of path function maximum_sum_path(i, j) { // Checking boundary condition if (i == n - 1 && j == m - 1) return a[i][j]; // Checking whether or not // (i, j) is visited if (visited[i][j] != 0) return dp[i][j]; // Marking (i, j) is visited visited[i][j] = 1; let total_sum = 0; // Checking whether the position hasn't // visited the last row or the last column. // Making recursive call for all the possible // moves from the current cell and then adding the // maximum returned by the calls and updating it. if (i < n - 1 & j < m - 1) { let current_sum = Math.max( maximum_sum_path(i, j + 1), Math.max( maximum_sum_path(i + 1, j + 1), maximum_sum_path(i + 1, j))); total_sum = a[i][j] + current_sum; } // Checking whether position // has reached last row else if (i == n - 1) total_sum = a[i][j] + maximum_sum_path(i, j + 1); // If the position is in the last column else total_sum = a[i][j] + maximum_sum_path(i + 1, j); // Updating the maximum sum till // the current position in the dp dp[i][j] = total_sum; // Returning the updated maximum value return total_sum; } inputMatrix(); // Calling the implemented function let maximum_sum = maximum_sum_path(0, 0); document.write(maximum_sum); // This code is contributed by suresh07.</script>
N=100 # No of rows and columnsn, m=-1,-1 # Declaring the matrix of maximum# 100 rows and 100 columnsa=[[-1]*N for _ in range(N)] # Variable visited is used to keep# track of all the visited positions# Variable dp is used to store# maximum sum till current positiondp,visited=[[-1]*N for _ in range(N)],[[False]*N for _ in range(N)] # For storing current sumcurrent_sum = 0 # For continuous update of# maximum sum requiredtotal_sum = 0 # Function to Input the matrix of size n*mdef inputMatrix(): global n, m n = 3 m = 3 a[0][0] = 500 a[0][1] = 100 a[0][2] = 230 a[1][0] = 1000 a[1][1] = 300 a[1][2] = 100 a[2][0] = 200 a[2][1] = 1000 a[2][2] = 200 # Function to calculate maximum sum of pathdef maximum_sum_path(i, j): global total_sum # Checking boundary condition if (i == n - 1 and j == m - 1): return a[i][j] # Checking whether or not (i, j) is visited if (visited[i][j]): return dp[i][j] # Marking (i, j) is visited visited[i][j] = True # Updating the maximum sum till # the current position in the dp total_sum = dp[i][j] # Checking whether the position hasn't # visited the last row or the last column. # Making recursive call for all the possible # moves from the current cell and then adding the # maximum returned by the calls and updating it. if (i < n - 1 and j < m - 1) : current_sum = max(maximum_sum_path(i, j + 1), max( maximum_sum_path(i + 1, j + 1), maximum_sum_path(i + 1, j))) total_sum = a[i][j] + current_sum # Checking whether # position has reached last row elif (i == n - 1): total_sum = a[i][j] + maximum_sum_path(i, j + 1) # If the position is in the last column else: total_sum = a[i][j] + maximum_sum_path(i + 1, j) # Returning the updated maximum value dp[i][j] = total_sum return total_sum # Driver Codeif __name__ == '__main__': inputMatrix() # Calling the implemented function maximum_sum = maximum_sum_path(0, 0) print(maximum_sum)
3000
Time Complexity: O(N*M)Auxiliary Space: O(N*M)
jrishabh99
silentRanger
shikhasingrajput
pikachuthedecipher
suresh07
amartyaghoshgfg
prasanna1995
shinjanpatra
Algorithms
Data Structures
Dynamic Programming
Matrix
Recursion
Data Structures
Dynamic Programming
Recursion
Matrix
Algorithms
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
SDE SHEET - A Complete Guide for SDE Preparation
DSA Sheet by Love Babbar
How to write a Pseudo Code?
Understanding Time Complexity with Simple Examples
Introduction to Algorithms
SDE SHEET - A Complete Guide for SDE Preparation
DSA Sheet by Love Babbar
Doubly Linked List | Set 1 (Introduction and Insertion)
Introduction to Algorithms
How to Start Learning DSA? | [
{
"code": null,
"e": 26345,
"s": 26317,
"text": "\n28 Feb, 2022"
},
{
"code": null,
"e": 26697,
"s": 26345,
"text": "Given an n*m matrix, the task is to find the maximum sum of elements of cells starting from the cell (0, 0) to cell (n-1, m-1). However, the allowed moves are right, downwards or diagonally right, i.e, from location (i, j) next move can be (i+1, j), or, (i, j+1), or (i+1, j+1). Find the maximum sum of elements satisfying the allowed moves.Examples: "
},
{
"code": null,
"e": 26984,
"s": 26697,
"text": "Input:\nmat[][] = {{100, -350, -200},\n {-100, -300, 700}}\nOutput: 500\nExplanation: \nPath followed is 100 -> -300 -> 700\n\nInput:\nmat[][] = {{500, 100, 230},\n {1000, 300, 100},\n {200, 1000, 200}}\nExplanation:\nPath followed is 500 -> 1000 -> 300 -> 1000 -> 200"
},
{
"code": null,
"e": 27010,
"s": 26984,
"text": "Naive Approach: Recursion"
},
{
"code": null,
"e": 27172,
"s": 27010,
"text": "Going through the Naive approach by traversing every possible path. But, this is costly. So, use Dynamic Programming here in order to reduce the time complexity."
},
{
"code": null,
"e": 27176,
"s": 27172,
"text": "C++"
},
{
"code": null,
"e": 27187,
"s": 27176,
"text": "Javascript"
},
{
"code": "#include <bits/stdc++.h>using namespace std;#define N 100 // No of rows and columnsint n, m; // Declaring the matrix of maximum// 100 rows and 100 columnsint a[N][N]; // For storing current sumint current_sum = 0; // For continuous update of// maximum sum requiredint total_sum = 0; // Function to Input the matrix of size n*mvoid inputMatrix(){ n = 3; m = 3; a[0][0] = 500; a[0][1] = 100; a[0][2] = 230; a[1][0] = 1000; a[1][1] = 300; a[1][2] = 100; a[2][0] = 200; a[2][1] = 1000; a[2][2] = 200;} // Function to calculate maximum sum of pathint maximum_sum_path(int i, int j){ // Checking boundary condition if (i == n - 1 && j == m - 1) return a[i][j]; // Checking whether the position hasn't // visited the last row or the last column. // Making recursive call for all the possible // moves from the current cell and then adding the // maximum returned by the calls and updating it. if (i < n - 1 & j < m - 1) { int current_sum = max(maximum_sum_path(i, j + 1), max( maximum_sum_path(i + 1, j + 1), maximum_sum_path(i + 1, j))); total_sum = a[i][j] + current_sum; } // Checking whether // position has reached last row else if (i == n - 1) total_sum = a[i][j] + maximum_sum_path(i, j + 1); // If the position is in the last column else total_sum = a[i][j] + maximum_sum_path(i + 1, j); // Returning the updated maximum value return total_sum;} // Driver Codeint main(){ inputMatrix(); // Calling the implemented function int maximum_sum = maximum_sum_path(0, 0); cout << maximum_sum; return 0;}",
"e": 28957,
"s": 27187,
"text": null
},
{
"code": "<script> const N = 100 // No of rows and columnslet n, m; // Declaring the matrix of maximum// 100 rows and 100 columnslet a = new Array(N);for(let i=0;i<N;i++){ a[i] = new Array(N);} // For storing current sumlet current_sum = 0; // For continuous update of// maximum sum requiredlet total_sum = 0; // Function to Input the matrix of size n*mfunction inputMatrix(){ n = 3; m = 3; a[0][0] = 500; a[0][1] = 100; a[0][2] = 230; a[1][0] = 1000; a[1][1] = 300; a[1][2] = 100; a[2][0] = 200; a[2][1] = 1000; a[2][2] = 200;} // Function to calculate maximum sum of pathfunction maximum_sum_path(i, j){ // Checking boundary condition if (i == n - 1 && j == m - 1) return a[i][j]; // Checking whether the position hasn't // visited the last row or the last column. // Making recursive call for all the possible // moves from the current cell and then adding the // maximum returned by the calls and updating it. if (i < n - 1 & j < m - 1) { let current_sum = Math.max(maximum_sum_path(i, j + 1), Math.max( maximum_sum_path(i + 1, j + 1), maximum_sum_path(i + 1, j))); total_sum = a[i][j] + current_sum; } // Checking whether // position has reached last row else if (i == n - 1) total_sum = a[i][j] + maximum_sum_path(i, j + 1); // If the position is in the last column else total_sum = a[i][j] + maximum_sum_path(i + 1, j); // Returning the updated maximum value return total_sum;} // Driver CodeinputMatrix(); // Calling the implemented functionlet maximum_sum = maximum_sum_path(0, 0); document.write(maximum_sum,\"</br>\"); // This code is contributed by shinjanpatra </script>",
"e": 30780,
"s": 28957,
"text": null
},
{
"code": null,
"e": 30785,
"s": 30780,
"text": "3000"
},
{
"code": null,
"e": 30811,
"s": 30785,
"text": "Time Complexity: O(2N*M) "
},
{
"code": null,
"e": 30835,
"s": 30811,
"text": "Auxiliary Space: O(N*M)"
},
{
"code": null,
"e": 30933,
"s": 30835,
"text": "Efficient Approach : Dynamic programming is used to solve the above problem in a recursive way. "
},
{
"code": null,
"e": 31542,
"s": 30933,
"text": "Allot a position at the beginning of the matrix at (0, 0).Check each next allowed position from the current position and select the path with maximum sum.Take care of the boundaries of the matrix, i.e, if the position reaches the last row or last column then the only possible choice will be right or downwards respectively.Use a map to store track of all the visiting positions and before visiting any (i, j), check whether or not the position is visited before.Update the maximum of all possible paths returned by each recursive calls made.Go till the position reaches the destination cell, i.e, (n-1.m-1)."
},
{
"code": null,
"e": 31601,
"s": 31542,
"text": "Allot a position at the beginning of the matrix at (0, 0)."
},
{
"code": null,
"e": 31698,
"s": 31601,
"text": "Check each next allowed position from the current position and select the path with maximum sum."
},
{
"code": null,
"e": 31869,
"s": 31698,
"text": "Take care of the boundaries of the matrix, i.e, if the position reaches the last row or last column then the only possible choice will be right or downwards respectively."
},
{
"code": null,
"e": 32009,
"s": 31869,
"text": "Use a map to store track of all the visiting positions and before visiting any (i, j), check whether or not the position is visited before."
},
{
"code": null,
"e": 32089,
"s": 32009,
"text": "Update the maximum of all possible paths returned by each recursive calls made."
},
{
"code": null,
"e": 32156,
"s": 32089,
"text": "Go till the position reaches the destination cell, i.e, (n-1.m-1)."
},
{
"code": null,
"e": 32208,
"s": 32156,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 32212,
"s": 32208,
"text": "C++"
},
{
"code": null,
"e": 32217,
"s": 32212,
"text": "Java"
},
{
"code": null,
"e": 32220,
"s": 32217,
"text": "C#"
},
{
"code": null,
"e": 32231,
"s": 32220,
"text": "Javascript"
},
{
"code": null,
"e": 32239,
"s": 32231,
"text": "Python3"
},
{
"code": "#include <bits/stdc++.h>using namespace std;#define N 100 // No of rows and columnsint n, m; // Declaring the matrix of maximum// 100 rows and 100 columnsint a[N][N]; // Variable visited is used to keep// track of all the visited positions// Variable dp is used to store// maximum sum till current positionvector<vector<int> > dp(N, vector<int>(N)), visited(N, vector<int>(N)); // For storing current sumint current_sum = 0; // For continuous update of// maximum sum requiredint total_sum = 0; // Function to Input the matrix of size n*mvoid inputMatrix(){ n = 3; m = 3; a[0][0] = 500; a[0][1] = 100; a[0][2] = 230; a[1][0] = 1000; a[1][1] = 300; a[1][2] = 100; a[2][0] = 200; a[2][1] = 1000; a[2][2] = 200;} // Function to calculate maximum sum of pathint maximum_sum_path(int i, int j){ // Checking boundary condition if (i == n - 1 && j == m - 1) return a[i][j]; // Checking whether or not (i, j) is visited if (visited[i][j]) return dp[i][j]; // Marking (i, j) is visited visited[i][j] = 1; // Updating the maximum sum till // the current position in the dp int& total_sum = dp[i][j]; // Checking whether the position hasn't // visited the last row or the last column. // Making recursive call for all the possible // moves from the current cell and then adding the // maximum returned by the calls and updating it. if (i < n - 1 & j < m - 1) { int current_sum = max(maximum_sum_path(i, j + 1), max( maximum_sum_path(i + 1, j + 1), maximum_sum_path(i + 1, j))); total_sum = a[i][j] + current_sum; } // Checking whether // position has reached last row else if (i == n - 1) total_sum = a[i][j] + maximum_sum_path(i, j + 1); // If the position is in the last column else total_sum = a[i][j] + maximum_sum_path(i + 1, j); // Returning the updated maximum value return dp[i][j] = total_sum;} // Driver Codeint main(){ inputMatrix(); // Calling the implemented function int maximum_sum = maximum_sum_path(0, 0); cout << maximum_sum; return 0;}",
"e": 34486,
"s": 32239,
"text": null
},
{
"code": "class GFG{ static final int N = 100; // No of rows and columnsstatic int n, m; // Declaring the matrix of maximum// 100 rows and 100 columnsstatic int a[][] = new int[N][N]; // Variable visited is used to keep// track of all the visited positions// Variable dp is used to store// maximum sum till current positionstatic int dp[][] = new int[N][N];static int visited[][] = new int[N][N]; // For storing current sumstatic int current_sum = 0; // For continuous update of// maximum sum requiredstatic int total_sum = 0; // Function to Input the matrix// of size n*mstatic void inputMatrix(){ n = 3; m = 3; a[0][0] = 500; a[0][1] = 100; a[0][2] = 230; a[1][0] = 1000; a[1][1] = 300; a[1][2] = 100; a[2][0] = 200; a[2][1] = 1000; a[2][2] = 200;} // Function to calculate maximum sum of pathstatic int maximum_sum_path(int i, int j){ // Checking boundary condition if (i == n - 1 && j == m - 1) return a[i][j]; // Checking whether or not // (i, j) is visited if (visited[i][j] != 0) return dp[i][j]; // Marking (i, j) is visited visited[i][j] = 1; int total_sum = 0; // Checking whether the position hasn't // visited the last row or the last column. // Making recursive call for all the possible // moves from the current cell and then adding the // maximum returned by the calls and updating it. if (i < n - 1 & j < m - 1) { int current_sum = Math.max( maximum_sum_path(i, j + 1), Math.max( maximum_sum_path(i + 1, j + 1), maximum_sum_path(i + 1, j))); total_sum = a[i][j] + current_sum; } // Checking whether position // has reached last row else if (i == n - 1) total_sum = a[i][j] + maximum_sum_path(i, j + 1); // If the position is in the last column else total_sum = a[i][j] + maximum_sum_path(i + 1, j); // Updating the maximum sum till // the current position in the dp dp[i][j] = total_sum; // Returning the updated maximum value return total_sum;} // Driver Codepublic static void main(String[] args){ inputMatrix(); // Calling the implemented function int maximum_sum = maximum_sum_path(0, 0); System.out.println(maximum_sum);}} // This code is contributed by jrishabh99",
"e": 36885,
"s": 34486,
"text": null
},
{
"code": "// C# program to implement// the above approachusing System;class GFG{ static readonly int N = 100; // No of rows and columnsstatic int n, m; // Declaring the matrix of maximum// 100 rows and 100 columnsstatic int[,]a = new int[N, N]; // Variable visited is used to keep// track of all the visited positions// Variable dp is used to store// maximum sum till current positionstatic int [,]dp = new int[N, N];static int [,]visited = new int[N, N]; // For storing current sumstatic int current_sum = 0; // For continuous update of// maximum sum requiredstatic int total_sum = 0; // Function to Input the matrix// of size n*mstatic void inputMatrix(){ n = 3; m = 3; a[0, 0] = 500; a[0, 1] = 100; a[0, 2] = 230; a[1, 0] = 1000; a[1, 1] = 300; a[1, 2] = 100; a[2, 0] = 200; a[2, 1] = 1000; a[2, 2] = 200;} // Function to calculate maximum// sum of pathstatic int maximum_sum_path(int i, int j){ // Checking boundary condition if (i == n - 1 && j == m - 1) return a[i, j]; // Checking whether or not // (i, j) is visited if (visited[i, j] != 0) return dp[i, j]; // Marking (i, j) is visited visited[i, j] = 1; int total_sum = 0; // Checking whether the position // hasn't visited the last row // or the last column. // Making recursive call for all // the possible moves from the // current cell and then adding the // maximum returned by the calls // and updating it. if (i < n - 1 & j < m - 1) { int current_sum = Math.Max(maximum_sum_path(i, j + 1), Math.Max(maximum_sum_path(i + 1, j + 1), maximum_sum_path(i + 1, j))); total_sum = a[i, j] + current_sum; } // Checking whether position // has reached last row else if (i == n - 1) total_sum = a[i, j] + maximum_sum_path(i, j + 1); // If the position is // in the last column else total_sum = a[i, j] + maximum_sum_path(i + 1, j); // Updating the maximum // sum till the current // position in the dp dp[i, j] = total_sum; // Returning the updated // maximum value return total_sum;} // Driver Codepublic static void Main(String[] args){ inputMatrix(); // Calling the implemented function int maximum_sum = maximum_sum_path(0, 0); Console.WriteLine(maximum_sum);}} // This code is contributed by shikhasingrajput",
"e": 39274,
"s": 36885,
"text": null
},
{
"code": "<script> // Javascript program to implement the above approach let N = 100; // No of rows and columns let n, m; // Declaring the matrix of maximum // 100 rows and 100 columns let a = new Array(N); // Variable visited is used to keep // track of all the visited positions // Variable dp is used to store // maximum sum till current position let dp = new Array(N); let visited = new Array(N); for(let i = 0; i < N; i++) { a[i] = new Array(N); dp[i] = new Array(N); visited[i] = new Array(N); for(let j = 0; j < N; j++) { a[i][j] = 0; dp[i][j] = 0; visited[i][j] = 0; } } // For storing current sum let current_sum = 0; // For continuous update of // maximum sum required let total_sum = 0; // Function to Input the matrix // of size n*m function inputMatrix() { n = 3; m = 3; a[0][0] = 500; a[0][1] = 100; a[0][2] = 230; a[1][0] = 1000; a[1][1] = 300; a[1][2] = 100; a[2][0] = 200; a[2][1] = 1000; a[2][2] = 200; } // Function to calculate maximum sum of path function maximum_sum_path(i, j) { // Checking boundary condition if (i == n - 1 && j == m - 1) return a[i][j]; // Checking whether or not // (i, j) is visited if (visited[i][j] != 0) return dp[i][j]; // Marking (i, j) is visited visited[i][j] = 1; let total_sum = 0; // Checking whether the position hasn't // visited the last row or the last column. // Making recursive call for all the possible // moves from the current cell and then adding the // maximum returned by the calls and updating it. if (i < n - 1 & j < m - 1) { let current_sum = Math.max( maximum_sum_path(i, j + 1), Math.max( maximum_sum_path(i + 1, j + 1), maximum_sum_path(i + 1, j))); total_sum = a[i][j] + current_sum; } // Checking whether position // has reached last row else if (i == n - 1) total_sum = a[i][j] + maximum_sum_path(i, j + 1); // If the position is in the last column else total_sum = a[i][j] + maximum_sum_path(i + 1, j); // Updating the maximum sum till // the current position in the dp dp[i][j] = total_sum; // Returning the updated maximum value return total_sum; } inputMatrix(); // Calling the implemented function let maximum_sum = maximum_sum_path(0, 0); document.write(maximum_sum); // This code is contributed by suresh07.</script>",
"e": 42113,
"s": 39274,
"text": null
},
{
"code": "N=100 # No of rows and columnsn, m=-1,-1 # Declaring the matrix of maximum# 100 rows and 100 columnsa=[[-1]*N for _ in range(N)] # Variable visited is used to keep# track of all the visited positions# Variable dp is used to store# maximum sum till current positiondp,visited=[[-1]*N for _ in range(N)],[[False]*N for _ in range(N)] # For storing current sumcurrent_sum = 0 # For continuous update of# maximum sum requiredtotal_sum = 0 # Function to Input the matrix of size n*mdef inputMatrix(): global n, m n = 3 m = 3 a[0][0] = 500 a[0][1] = 100 a[0][2] = 230 a[1][0] = 1000 a[1][1] = 300 a[1][2] = 100 a[2][0] = 200 a[2][1] = 1000 a[2][2] = 200 # Function to calculate maximum sum of pathdef maximum_sum_path(i, j): global total_sum # Checking boundary condition if (i == n - 1 and j == m - 1): return a[i][j] # Checking whether or not (i, j) is visited if (visited[i][j]): return dp[i][j] # Marking (i, j) is visited visited[i][j] = True # Updating the maximum sum till # the current position in the dp total_sum = dp[i][j] # Checking whether the position hasn't # visited the last row or the last column. # Making recursive call for all the possible # moves from the current cell and then adding the # maximum returned by the calls and updating it. if (i < n - 1 and j < m - 1) : current_sum = max(maximum_sum_path(i, j + 1), max( maximum_sum_path(i + 1, j + 1), maximum_sum_path(i + 1, j))) total_sum = a[i][j] + current_sum # Checking whether # position has reached last row elif (i == n - 1): total_sum = a[i][j] + maximum_sum_path(i, j + 1) # If the position is in the last column else: total_sum = a[i][j] + maximum_sum_path(i + 1, j) # Returning the updated maximum value dp[i][j] = total_sum return total_sum # Driver Codeif __name__ == '__main__': inputMatrix() # Calling the implemented function maximum_sum = maximum_sum_path(0, 0) print(maximum_sum)",
"e": 44252,
"s": 42113,
"text": null
},
{
"code": null,
"e": 44257,
"s": 44252,
"text": "3000"
},
{
"code": null,
"e": 44304,
"s": 44257,
"text": "Time Complexity: O(N*M)Auxiliary Space: O(N*M)"
},
{
"code": null,
"e": 44315,
"s": 44304,
"text": "jrishabh99"
},
{
"code": null,
"e": 44328,
"s": 44315,
"text": "silentRanger"
},
{
"code": null,
"e": 44345,
"s": 44328,
"text": "shikhasingrajput"
},
{
"code": null,
"e": 44364,
"s": 44345,
"text": "pikachuthedecipher"
},
{
"code": null,
"e": 44373,
"s": 44364,
"text": "suresh07"
},
{
"code": null,
"e": 44389,
"s": 44373,
"text": "amartyaghoshgfg"
},
{
"code": null,
"e": 44402,
"s": 44389,
"text": "prasanna1995"
},
{
"code": null,
"e": 44415,
"s": 44402,
"text": "shinjanpatra"
},
{
"code": null,
"e": 44426,
"s": 44415,
"text": "Algorithms"
},
{
"code": null,
"e": 44442,
"s": 44426,
"text": "Data Structures"
},
{
"code": null,
"e": 44462,
"s": 44442,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 44469,
"s": 44462,
"text": "Matrix"
},
{
"code": null,
"e": 44479,
"s": 44469,
"text": "Recursion"
},
{
"code": null,
"e": 44495,
"s": 44479,
"text": "Data Structures"
},
{
"code": null,
"e": 44515,
"s": 44495,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 44525,
"s": 44515,
"text": "Recursion"
},
{
"code": null,
"e": 44532,
"s": 44525,
"text": "Matrix"
},
{
"code": null,
"e": 44543,
"s": 44532,
"text": "Algorithms"
},
{
"code": null,
"e": 44641,
"s": 44543,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 44690,
"s": 44641,
"text": "SDE SHEET - A Complete Guide for SDE Preparation"
},
{
"code": null,
"e": 44715,
"s": 44690,
"text": "DSA Sheet by Love Babbar"
},
{
"code": null,
"e": 44743,
"s": 44715,
"text": "How to write a Pseudo Code?"
},
{
"code": null,
"e": 44794,
"s": 44743,
"text": "Understanding Time Complexity with Simple Examples"
},
{
"code": null,
"e": 44821,
"s": 44794,
"text": "Introduction to Algorithms"
},
{
"code": null,
"e": 44870,
"s": 44821,
"text": "SDE SHEET - A Complete Guide for SDE Preparation"
},
{
"code": null,
"e": 44895,
"s": 44870,
"text": "DSA Sheet by Love Babbar"
},
{
"code": null,
"e": 44951,
"s": 44895,
"text": "Doubly Linked List | Set 1 (Introduction and Insertion)"
},
{
"code": null,
"e": 44978,
"s": 44951,
"text": "Introduction to Algorithms"
}
] |
LocalTime isSupported() method in Java with Examples - GeeksforGeeks | 26 Jul, 2021
In LocalTime class, there are two types of isSupported() method depending upon the parameters passed to it.
isSupported() method of a LocalTime class used to Check if the specified field is supported by LocalTime class or not means using this method we can check if this LocalTime can be queried for the specified field.The supported fields of ChronoField are:
NANO_OF_SECOND
MICRO_OF_SECOND
MILLI_OF_SECOND
INSTANT_SECONDS
SECOND_OF_MINUTE
NANO_OF_DAY
MICRO_OF_DAY
MILLI_OF_DAY
SECOND_OF_DAY
MINUTE_OF_HOUR
MINUTE_OF_DAY
HOUR_OF_AMPM
CLOCK_HOUR_OF_AMPM
HOUR_OF_DAY
CLOCK_HOUR_OF_DAY
AMPM_OF_DAY
All other ChronoField instances will return false.Syntax:
public boolean isSupported(TemporalField field)
Parameters: This method accepts one single parameter field which is the field to check.Return value: This method returns boolean value true if the field is supported on this LocalTime, false if not.Below programs illustrate the isSupported() method:Program 1:
Java
// Java program to demonstrate// LocalTime.isSupported() method import java.time.*;import java.time.temporal.ChronoField; public class GFG { public static void main(String[] args) { // create a LocalTime object LocalTime lt = LocalTime.parse("19:34:50.63"); // check Milli of Second is supported in LocalTime boolean value = lt.isSupported(ChronoField.MILLI_OF_SECOND); // print result System.out.println("MilliSecond Field is supported: " + value); }}
MilliSecond Field is supported: true
isSupported() method of a LocalTime class used to Check if the specified unit is supported by LocalTime class or not means using this method we can check if this LocalTime can be queried for the specified unit.The supported fields of ChronoUnit are:
NANOS
MICROS
MILLIS
SECONDS
MINUTES
HOURS
HALF_DAYS
All other ChronoUnit instances will return false.Syntax:
public boolean isSupported(TemporalUnit unit)
Parameters: This method accepts one single parameter unit which is the unit to check.Return value: This method returns boolean value true if the field is supported on this LocalTime, false if not.Below programs illustrate the isSupported() method:Program 1:
Java
// Java program to demonstrate// LocalTime.isSupported() method import java.time.*;import java.time.temporal.ChronoUnit; public class GFG { public static void main(String[] args) { // create a LocalTime object LocalTime lt = LocalTime.parse("19:34:50.63"); // check MILLIS ChronoUnit supported in LocalTime boolean value = lt.isSupported(ChronoUnit.MILLIS); // print result System.out.println("ChronoUnit MILLIS is supported: " + value); }}
ChronoUnit MILLIS is supported: true
Reference:
https://docs.oracle.com/javase/10/docs/api/java/time/LocalTime.html#isSupported(java.time.temporal.TemporalField)
https://docs.oracle.com/javase/10/docs/api/java/time/LocalTime.html#isSupported(java.time.temporal.TemporalUnit)
arorakashish0911
Java-Functions
Java-LocalTime
Java-time package
Java
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
Generics in Java
Introduction to Java
Comparator Interface in Java with Examples
Internal Working of HashMap in Java
Strings in Java | [
{
"code": null,
"e": 25225,
"s": 25197,
"text": "\n26 Jul, 2021"
},
{
"code": null,
"e": 25333,
"s": 25225,
"text": "In LocalTime class, there are two types of isSupported() method depending upon the parameters passed to it."
},
{
"code": null,
"e": 25588,
"s": 25333,
"text": "isSupported() method of a LocalTime class used to Check if the specified field is supported by LocalTime class or not means using this method we can check if this LocalTime can be queried for the specified field.The supported fields of ChronoField are: "
},
{
"code": null,
"e": 25603,
"s": 25588,
"text": "NANO_OF_SECOND"
},
{
"code": null,
"e": 25619,
"s": 25603,
"text": "MICRO_OF_SECOND"
},
{
"code": null,
"e": 25635,
"s": 25619,
"text": "MILLI_OF_SECOND"
},
{
"code": null,
"e": 25651,
"s": 25635,
"text": "INSTANT_SECONDS"
},
{
"code": null,
"e": 25668,
"s": 25651,
"text": "SECOND_OF_MINUTE"
},
{
"code": null,
"e": 25680,
"s": 25668,
"text": "NANO_OF_DAY"
},
{
"code": null,
"e": 25693,
"s": 25680,
"text": "MICRO_OF_DAY"
},
{
"code": null,
"e": 25706,
"s": 25693,
"text": "MILLI_OF_DAY"
},
{
"code": null,
"e": 25720,
"s": 25706,
"text": "SECOND_OF_DAY"
},
{
"code": null,
"e": 25735,
"s": 25720,
"text": "MINUTE_OF_HOUR"
},
{
"code": null,
"e": 25749,
"s": 25735,
"text": "MINUTE_OF_DAY"
},
{
"code": null,
"e": 25762,
"s": 25749,
"text": "HOUR_OF_AMPM"
},
{
"code": null,
"e": 25781,
"s": 25762,
"text": "CLOCK_HOUR_OF_AMPM"
},
{
"code": null,
"e": 25793,
"s": 25781,
"text": "HOUR_OF_DAY"
},
{
"code": null,
"e": 25811,
"s": 25793,
"text": "CLOCK_HOUR_OF_DAY"
},
{
"code": null,
"e": 25823,
"s": 25811,
"text": "AMPM_OF_DAY"
},
{
"code": null,
"e": 25882,
"s": 25823,
"text": "All other ChronoField instances will return false.Syntax: "
},
{
"code": null,
"e": 25930,
"s": 25882,
"text": "public boolean isSupported(TemporalField field)"
},
{
"code": null,
"e": 26192,
"s": 25930,
"text": "Parameters: This method accepts one single parameter field which is the field to check.Return value: This method returns boolean value true if the field is supported on this LocalTime, false if not.Below programs illustrate the isSupported() method:Program 1: "
},
{
"code": null,
"e": 26197,
"s": 26192,
"text": "Java"
},
{
"code": "// Java program to demonstrate// LocalTime.isSupported() method import java.time.*;import java.time.temporal.ChronoField; public class GFG { public static void main(String[] args) { // create a LocalTime object LocalTime lt = LocalTime.parse(\"19:34:50.63\"); // check Milli of Second is supported in LocalTime boolean value = lt.isSupported(ChronoField.MILLI_OF_SECOND); // print result System.out.println(\"MilliSecond Field is supported: \" + value); }}",
"e": 26752,
"s": 26197,
"text": null
},
{
"code": null,
"e": 26789,
"s": 26752,
"text": "MilliSecond Field is supported: true"
},
{
"code": null,
"e": 27041,
"s": 26789,
"text": "isSupported() method of a LocalTime class used to Check if the specified unit is supported by LocalTime class or not means using this method we can check if this LocalTime can be queried for the specified unit.The supported fields of ChronoUnit are: "
},
{
"code": null,
"e": 27047,
"s": 27041,
"text": "NANOS"
},
{
"code": null,
"e": 27054,
"s": 27047,
"text": "MICROS"
},
{
"code": null,
"e": 27061,
"s": 27054,
"text": "MILLIS"
},
{
"code": null,
"e": 27069,
"s": 27061,
"text": "SECONDS"
},
{
"code": null,
"e": 27077,
"s": 27069,
"text": "MINUTES"
},
{
"code": null,
"e": 27083,
"s": 27077,
"text": "HOURS"
},
{
"code": null,
"e": 27093,
"s": 27083,
"text": "HALF_DAYS"
},
{
"code": null,
"e": 27151,
"s": 27093,
"text": "All other ChronoUnit instances will return false.Syntax: "
},
{
"code": null,
"e": 27197,
"s": 27151,
"text": "public boolean isSupported(TemporalUnit unit)"
},
{
"code": null,
"e": 27457,
"s": 27197,
"text": "Parameters: This method accepts one single parameter unit which is the unit to check.Return value: This method returns boolean value true if the field is supported on this LocalTime, false if not.Below programs illustrate the isSupported() method:Program 1: "
},
{
"code": null,
"e": 27462,
"s": 27457,
"text": "Java"
},
{
"code": "// Java program to demonstrate// LocalTime.isSupported() method import java.time.*;import java.time.temporal.ChronoUnit; public class GFG { public static void main(String[] args) { // create a LocalTime object LocalTime lt = LocalTime.parse(\"19:34:50.63\"); // check MILLIS ChronoUnit supported in LocalTime boolean value = lt.isSupported(ChronoUnit.MILLIS); // print result System.out.println(\"ChronoUnit MILLIS is supported: \" + value); }}",
"e": 28006,
"s": 27462,
"text": null
},
{
"code": null,
"e": 28044,
"s": 28006,
"text": "ChronoUnit MILLIS is supported: true"
},
{
"code": null,
"e": 28058,
"s": 28046,
"text": "Reference: "
},
{
"code": null,
"e": 28172,
"s": 28058,
"text": "https://docs.oracle.com/javase/10/docs/api/java/time/LocalTime.html#isSupported(java.time.temporal.TemporalField)"
},
{
"code": null,
"e": 28285,
"s": 28172,
"text": "https://docs.oracle.com/javase/10/docs/api/java/time/LocalTime.html#isSupported(java.time.temporal.TemporalUnit)"
},
{
"code": null,
"e": 28304,
"s": 28287,
"text": "arorakashish0911"
},
{
"code": null,
"e": 28319,
"s": 28304,
"text": "Java-Functions"
},
{
"code": null,
"e": 28334,
"s": 28319,
"text": "Java-LocalTime"
},
{
"code": null,
"e": 28352,
"s": 28334,
"text": "Java-time package"
},
{
"code": null,
"e": 28357,
"s": 28352,
"text": "Java"
},
{
"code": null,
"e": 28362,
"s": 28357,
"text": "Java"
},
{
"code": null,
"e": 28460,
"s": 28362,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28475,
"s": 28460,
"text": "Stream In Java"
},
{
"code": null,
"e": 28496,
"s": 28475,
"text": "Constructors in Java"
},
{
"code": null,
"e": 28515,
"s": 28496,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 28545,
"s": 28515,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 28591,
"s": 28545,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 28608,
"s": 28591,
"text": "Generics in Java"
},
{
"code": null,
"e": 28629,
"s": 28608,
"text": "Introduction to Java"
},
{
"code": null,
"e": 28672,
"s": 28629,
"text": "Comparator Interface in Java with Examples"
},
{
"code": null,
"e": 28708,
"s": 28672,
"text": "Internal Working of HashMap in Java"
}
] |
Count number of words | Practice | GeeksforGeeks | Given a string consisting of spaces,\t,\n and lower case alphabets.Your task is to count the number of words where spaces,\t and \n work as separators.
Example 1:
Input: S = "abc def"
Output: 2
Explanation: There is a space at 4th
position which works as a seperator
between "abc" and "def"
Example 2:
Input: S = "a\nyo\n"
Output: 2
Explanation: There are two words "a"
and "yo" which are seperated by "\n".
Your Task:
You don't need to read input or print anything. Your task is to complete the function countWords() which accepts a string as input and returns number of words present in it.
Expected Time Complexity: O(N)
Expected Auxiliary Space: O(1)
where N is length of given String.
Constraints:
2 <= Length of String <= 106
+1
mayank20212 weeks ago
C++ : 0.06/1.5int countWords(string s){ int count=0, flag=0; for(int i=0; i<s.size(); i++) { if( (s[i]==' ' || s[i]=='\\' ) ) { if(s[i]=='\\' && (s[i+1]=='t' || s[i+1]=='n') ) i++; if(flag) count++; flag=0; } else { flag=1; } } if (flag) count++; return count; }
0
premranjan88046
This comment was deleted.
0
triple2double18 months ago
int countWords(string s){ int count = 0; int n = s.length(); int seenletter =false; int i=0; while(i<n) { seenletter =false; while (i<n&&isalpha(s[i])) { seenletter=true; i++; } if(s[i]=='\\') i+=2; else i++; if(seenletter==true) count++; } return count;}
0
martial8 months ago
martial
what is isalpha?
0
shahzdor9 months ago
shahzdor
Python solution showing error
class Solution: def countWords(self, s): count=0 strx=0 for i in s: if i==' ' or i=='\n' or i=='\t' and strx>0: count+=1 strx=0 else: strx+=1 if strx>0: count+=1 return count
###################
from re import split
class Solution: def countWords(self, s): words = s.split() return len(words)
Both are giving error
0
ANAS MALVAT9 months ago
ANAS MALVAT
for(int i = 0 ; i < s.length() ; i ++) { if(isalpha(s[i])) { if(!flag) { flag = 1; ret++; } } else if(s[i] ==' ') { flag = 0; } else if(!isalpha(s[i]) and s[i + 1] == 'n') { i++; flag = 0; } else if(!isalpha(s[i]) and s[i + 1] =='t') { i++; flag = 0; } } return ret;
0
dhanraj kalantri10 months ago
dhanraj kalantri
int countWords(string s){int count = 0, i;string x = "";for (i = 0; i < s.length(); i++){if (isalpha(s[i])){x += s[i];continue;}else if (s[i] == ' '){if (x != ""){count++;x = "";}}else{if (x != ""){count++;x = "";}i++;}}if (x != "")count++;return count;}
0
Debojyoti Sinha10 months ago
Debojyoti Sinha
Total Time Taken: 0.1/1.4 ✅
int countWords(string s){ int res = 0; for(int i = 0; i < s.size(); i++) { if(isalpha(s[i])) { res++; } while(i < s.size() and isalpha(s[i])) { i++; } if(i < s.size() and s[i] == '\\') { i++; } } return res;}
0
Bharat Gupta1 year ago
Bharat Gupta
Refer to the hint if getting an error while comparing '\'.
int countWords(string s){ int words = 0, len = s.length(); for(int i = 0; i < len; i++){ if(isalpha(s[i])) words++; while(i < len and isalpha(s[i])) i++; if(s[i] == '\\') i++; } return words;}
-4
Babita Kumari1 year ago
Babita Kumari
int countWords(string str){
int wc = 1;
for(int i=0;str[i]!='\0';i++) {
if (str[i] == '\n' || str[i] == ' ' || str[i] == '\t') wc+=1; }
return wc; //code here
}
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": 393,
"s": 238,
"text": "Given a string consisting of spaces,\\t,\\n and lower case alphabets.Your task is to count the number of words where spaces,\\t and \\n work as separators.\n "
},
{
"code": null,
"e": 404,
"s": 393,
"text": "Example 1:"
},
{
"code": null,
"e": 533,
"s": 404,
"text": "Input: S = \"abc def\"\nOutput: 2\nExplanation: There is a space at 4th\nposition which works as a seperator\nbetween \"abc\" and \"def\"\n"
},
{
"code": null,
"e": 546,
"s": 535,
"text": "Example 2:"
},
{
"code": null,
"e": 652,
"s": 546,
"text": "Input: S = \"a\\nyo\\n\"\nOutput: 2\nExplanation: There are two words \"a\"\nand \"yo\" which are seperated by \"\\n\"."
},
{
"code": null,
"e": 983,
"s": 652,
"text": "\nYour Task: \nYou don't need to read input or print anything. Your task is to complete the function countWords() which accepts a string as input and returns number of words present in it.\n\nExpected Time Complexity: O(N)\nExpected Auxiliary Space: O(1)\nwhere N is length of given String.\n\nConstraints:\n2 <= Length of String <= 106\n "
},
{
"code": null,
"e": 986,
"s": 983,
"text": "+1"
},
{
"code": null,
"e": 1008,
"s": 986,
"text": "mayank20212 weeks ago"
},
{
"code": null,
"e": 1399,
"s": 1008,
"text": "C++ : 0.06/1.5int countWords(string s){ int count=0, flag=0; for(int i=0; i<s.size(); i++) { if( (s[i]==' ' || s[i]=='\\\\' ) ) { if(s[i]=='\\\\' && (s[i+1]=='t' || s[i+1]=='n') ) i++; if(flag) count++; flag=0; } else { flag=1; } } if (flag) count++; return count; }"
},
{
"code": null,
"e": 1401,
"s": 1399,
"text": "0"
},
{
"code": null,
"e": 1417,
"s": 1401,
"text": "premranjan88046"
},
{
"code": null,
"e": 1443,
"s": 1417,
"text": "This comment was deleted."
},
{
"code": null,
"e": 1445,
"s": 1443,
"text": "0"
},
{
"code": null,
"e": 1472,
"s": 1445,
"text": "triple2double18 months ago"
},
{
"code": null,
"e": 1858,
"s": 1472,
"text": "int countWords(string s){ int count = 0; int n = s.length(); int seenletter =false; int i=0; while(i<n) { seenletter =false; while (i<n&&isalpha(s[i])) { seenletter=true; i++; } if(s[i]=='\\\\') i+=2; else i++; if(seenletter==true) count++; } return count;}"
},
{
"code": null,
"e": 1862,
"s": 1860,
"text": "0"
},
{
"code": null,
"e": 1882,
"s": 1862,
"text": "martial8 months ago"
},
{
"code": null,
"e": 1890,
"s": 1882,
"text": "martial"
},
{
"code": null,
"e": 1907,
"s": 1890,
"text": "what is isalpha?"
},
{
"code": null,
"e": 1909,
"s": 1907,
"text": "0"
},
{
"code": null,
"e": 1930,
"s": 1909,
"text": "shahzdor9 months ago"
},
{
"code": null,
"e": 1939,
"s": 1930,
"text": "shahzdor"
},
{
"code": null,
"e": 1969,
"s": 1939,
"text": "Python solution showing error"
},
{
"code": null,
"e": 2196,
"s": 1969,
"text": "class Solution: def countWords(self, s): count=0 strx=0 for i in s: if i==' ' or i=='\\n' or i=='\\t' and strx>0: count+=1 strx=0 else: strx+=1 if strx>0: count+=1 return count"
},
{
"code": null,
"e": 2216,
"s": 2196,
"text": "###################"
},
{
"code": null,
"e": 2237,
"s": 2216,
"text": "from re import split"
},
{
"code": null,
"e": 2321,
"s": 2237,
"text": "class Solution: def countWords(self, s): words = s.split() return len(words)"
},
{
"code": null,
"e": 2343,
"s": 2321,
"text": "Both are giving error"
},
{
"code": null,
"e": 2345,
"s": 2343,
"text": "0"
},
{
"code": null,
"e": 2369,
"s": 2345,
"text": "ANAS MALVAT9 months ago"
},
{
"code": null,
"e": 2381,
"s": 2369,
"text": "ANAS MALVAT"
},
{
"code": null,
"e": 2860,
"s": 2381,
"text": "for(int i = 0 ; i < s.length() ; i ++) { if(isalpha(s[i])) { if(!flag) { flag = 1; ret++; } } else if(s[i] ==' ') { flag = 0; } else if(!isalpha(s[i]) and s[i + 1] == 'n') { i++; flag = 0; } else if(!isalpha(s[i]) and s[i + 1] =='t') { i++; flag = 0; } } return ret;"
},
{
"code": null,
"e": 2862,
"s": 2860,
"text": "0"
},
{
"code": null,
"e": 2892,
"s": 2862,
"text": "dhanraj kalantri10 months ago"
},
{
"code": null,
"e": 2909,
"s": 2892,
"text": "dhanraj kalantri"
},
{
"code": null,
"e": 3164,
"s": 2909,
"text": "int countWords(string s){int count = 0, i;string x = \"\";for (i = 0; i < s.length(); i++){if (isalpha(s[i])){x += s[i];continue;}else if (s[i] == ' '){if (x != \"\"){count++;x = \"\";}}else{if (x != \"\"){count++;x = \"\";}i++;}}if (x != \"\")count++;return count;}"
},
{
"code": null,
"e": 3166,
"s": 3164,
"text": "0"
},
{
"code": null,
"e": 3195,
"s": 3166,
"text": "Debojyoti Sinha10 months ago"
},
{
"code": null,
"e": 3211,
"s": 3195,
"text": "Debojyoti Sinha"
},
{
"code": null,
"e": 3239,
"s": 3211,
"text": "Total Time Taken: 0.1/1.4 ✅"
},
{
"code": null,
"e": 3583,
"s": 3239,
"text": "int countWords(string s){ int res = 0; for(int i = 0; i < s.size(); i++) { if(isalpha(s[i])) { res++; } while(i < s.size() and isalpha(s[i])) { i++; } if(i < s.size() and s[i] == '\\\\') { i++; } } return res;}"
},
{
"code": null,
"e": 3585,
"s": 3583,
"text": "0"
},
{
"code": null,
"e": 3608,
"s": 3585,
"text": "Bharat Gupta1 year ago"
},
{
"code": null,
"e": 3621,
"s": 3608,
"text": "Bharat Gupta"
},
{
"code": null,
"e": 3680,
"s": 3621,
"text": "Refer to the hint if getting an error while comparing '\\'."
},
{
"code": null,
"e": 3929,
"s": 3680,
"text": "int countWords(string s){ int words = 0, len = s.length(); for(int i = 0; i < len; i++){ if(isalpha(s[i])) words++; while(i < len and isalpha(s[i])) i++; if(s[i] == '\\\\') i++; } return words;}"
},
{
"code": null,
"e": 3932,
"s": 3929,
"text": "-4"
},
{
"code": null,
"e": 3956,
"s": 3932,
"text": "Babita Kumari1 year ago"
},
{
"code": null,
"e": 3970,
"s": 3956,
"text": "Babita Kumari"
},
{
"code": null,
"e": 3998,
"s": 3970,
"text": "int countWords(string str){"
},
{
"code": null,
"e": 4014,
"s": 3998,
"text": " int wc = 1;"
},
{
"code": null,
"e": 4053,
"s": 4014,
"text": " for(int i=0;str[i]!='\\0';i++) {"
},
{
"code": null,
"e": 4140,
"s": 4053,
"text": " if (str[i] == '\\n' || str[i] == ' ' || str[i] == '\\t') wc+=1; }"
},
{
"code": null,
"e": 4171,
"s": 4140,
"text": " return wc; //code here"
},
{
"code": null,
"e": 4173,
"s": 4171,
"text": "}"
},
{
"code": null,
"e": 4319,
"s": 4173,
"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": 4355,
"s": 4319,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 4365,
"s": 4355,
"text": "\nProblem\n"
},
{
"code": null,
"e": 4375,
"s": 4365,
"text": "\nContest\n"
},
{
"code": null,
"e": 4438,
"s": 4375,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 4586,
"s": 4438,
"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": 4794,
"s": 4586,
"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": 4900,
"s": 4794,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
Program for SSTF disk scheduling algorithm - GeeksforGeeks | 24 Jan, 2022
Prerequisite – Disk scheduling algorithms Given an array of disk track numbers and initial head position, our task is to find the total number of seek operations done to access all the requested tracks if Shortest Seek Time First (SSTF) is a disk scheduling algorithm is used.
Shortest Seek Time First (SSTF) – Basic idea is the tracks which are closer to current disk head position should be serviced first in order to minimise the seek operations.
Advantages of Shortest Seek Time First (SSTF) –
Better performance than FCFS scheduling algorithm.It provides better throughput.This algorithm is used in Batch Processing system where throughput is more important.It has less average response and waiting time.
Better performance than FCFS scheduling algorithm.
It provides better throughput.
This algorithm is used in Batch Processing system where throughput is more important.
It has less average response and waiting time.
Disadvantages of Shortest Seek Time First (SSTF) –
Starvation is possible for some requests as it favours easy to reach request and ignores the far away processes.Their is lack of predictability because of high variance of response time.Switching direction slows things down.
Starvation is possible for some requests as it favours easy to reach request and ignores the far away processes.
Their is lack of predictability because of high variance of response time.
Switching direction slows things down.
Algorithm –
Let Request array represents an array storing indexes of tracks that have been requested. ‘head’ is the position of disk head.Find the positive distance of all tracks in the request array from head.Find a track from requested array which has not been accessed/serviced yet and has minimum distance from head.Increment the total seek count with this distance.Currently serviced track position now becomes the new head position.Go to step 2 until all tracks in request array have not been serviced.
Let Request array represents an array storing indexes of tracks that have been requested. ‘head’ is the position of disk head.
Find the positive distance of all tracks in the request array from head.
Find a track from requested array which has not been accessed/serviced yet and has minimum distance from head.
Increment the total seek count with this distance.
Currently serviced track position now becomes the new head position.
Go to step 2 until all tracks in request array have not been serviced.
Example – Request sequence = {176, 79, 34, 60, 92, 11, 41, 114} Initial head position = 50
The following chart shows the sequence in which requested tracks are serviced using SSTF.
Therefore, total seek count is calculated as:
= (50-41)+(41-34)+(34-11)+(60-11)+(79-60)+(92-79)+(114-92)+(176-114)
= 204
Which can also be directly calculated as: (50-11)+(176-11)Implementation – Implementation of SSTF is given below. Note that we have made a node class having 2 members. ‘distance’ is used to store the distance between head and the track position. ‘accessed’ is a boolean variable which tells whether the track has been accessed/serviced before by disk head or not.
C++
Java
Python3
C#
// C++ program for implementation of// SSTF disk scheduling#include <bits/stdc++.h>using namespace std; // Calculates difference of each // track number with the head positionvoid calculatedifference(int request[], int head, int diff[][2], int n){ for(int i = 0; i < n; i++) { diff[i][0] = abs(head - request[i]); }} // Find unaccessed track which is// at minimum distance from headint findMIN(int diff[][2], int n){ int index = -1; int minimum = 1e9; for(int i = 0; i < n; i++) { if (!diff[i][1] && minimum > diff[i][0]) { minimum = diff[i][0]; index = i; } } return index;} void shortestSeekTimeFirst(int request[], int head, int n){ if (n == 0) { return; } // Create array of objects of class node int diff[n][2] = { { 0, 0 } }; // Count total number of seek operation int seekcount = 0; // Stores sequence in which disk access is done int seeksequence[n + 1] = {0}; for(int i = 0; i < n; i++) { seeksequence[i] = head; calculatedifference(request, head, diff, n); int index = findMIN(diff, n); diff[index][1] = 1; // Increase the total count seekcount += diff[index][0]; // Accessed track is now new head head = request[index]; } seeksequence[n] = head; cout << "Total number of seek operations = " << seekcount << endl; cout << "Seek sequence is : " << "\n"; // Print the sequence for(int i = 0; i <= n; i++) { cout << seeksequence[i] << "\n"; }} // Driver codeint main(){ int n = 8; int proc[n] = { 176, 79, 34, 60, 92, 11, 41, 114 }; shortestSeekTimeFirst(proc, 50, n); return 0;} // This code is contributed by manish19je0495
// Java program for implementation of// SSTF disk schedulingclass node { // represent difference between // head position and track number int distance = 0; // true if track has been accessed boolean accessed = false;} public class SSTF { // Calculates difference of each // track number with the head position public static void calculateDifference(int queue[], int head, node diff[]) { for (int i = 0; i < diff.length; i++) diff[i].distance = Math.abs(queue[i] - head); } // find unaccessed track // which is at minimum distance from head public static int findMin(node diff[]) { int index = -1, minimum = Integer.MAX_VALUE; for (int i = 0; i < diff.length; i++) { if (!diff[i].accessed && minimum > diff[i].distance) { minimum = diff[i].distance; index = i; } } return index; } public static void shortestSeekTimeFirst(int request[], int head) { if (request.length == 0) return; // create array of objects of class node node diff[] = new node[request.length]; // initialize array for (int i = 0; i < diff.length; i++) diff[i] = new node(); // count total number of seek operation int seek_count = 0; // stores sequence in which disk access is done int[] seek_sequence = new int[request.length + 1]; for (int i = 0; i < request.length; i++) { seek_sequence[i] = head; calculateDifference(request, head, diff); int index = findMin(diff); diff[index].accessed = true; // increase the total count seek_count += diff[index].distance; // accessed track is now new head head = request[index]; } // for last accessed track seek_sequence[seek_sequence.length - 1] = head; System.out.println("Total number of seek operations = " + seek_count); System.out.println("Seek Sequence is"); // print the sequence for (int i = 0; i < seek_sequence.length; i++) System.out.println(seek_sequence[i]); } public static void main(String[] args) { // request array int arr[] = { 176, 79, 34, 60, 92, 11, 41, 114 }; shortestSeekTimeFirst(arr, 50); }}
# Python3 program for implementation of# SSTF disk scheduling # Calculates difference of each# track number with the head positiondef calculateDifference(queue, head, diff): for i in range(len(diff)): diff[i][0] = abs(queue[i] - head) # find unaccessed track which is# at minimum distance from headdef findMin(diff): index = -1 minimum = 999999999 for i in range(len(diff)): if (not diff[i][1] and minimum > diff[i][0]): minimum = diff[i][0] index = i return index def shortestSeekTimeFirst(request, head): if (len(request) == 0): return l = len(request) diff = [0] * l # initialize array for i in range(l): diff[i] = [0, 0] # count total number of seek operation seek_count = 0 # stores sequence in which disk # access is done seek_sequence = [0] * (l + 1) for i in range(l): seek_sequence[i] = head calculateDifference(request, head, diff) index = findMin(diff) diff[index][1] = True # increase the total count seek_count += diff[index][0] # accessed track is now new head head = request[index] # for last accessed track seek_sequence[len(seek_sequence) - 1] = head print("Total number of seek operations =", seek_count) print("Seek Sequence is") # print the sequence for i in range(l + 1): print(seek_sequence[i]) # Driver codeif __name__ =="__main__": # request array proc = [176, 79, 34, 60, 92, 11, 41, 114] shortestSeekTimeFirst(proc, 50) # This code is contributed by# Shubham Singh(SHUBHAMSINGH10)
// C# program for implementation of// SSTF disk schedulingusing System; public class node{ // represent difference between // head position and track number public int distance = 0; // true if track has been accessed public Boolean accessed = false;} public class SSTF{ // Calculates difference of each // track number with the head position public static void calculateDifference(int []queue, int head, node []diff) { for (int i = 0; i < diff.Length; i++) diff[i].distance = Math.Abs(queue[i] - head); } // find unaccessed track // which is at minimum distance from head public static int findMin(node []diff) { int index = -1, minimum = int.MaxValue; for (int i = 0; i < diff.Length; i++) { if (!diff[i].accessed && minimum > diff[i].distance) { minimum = diff[i].distance; index = i; } } return index; } public static void shortestSeekTimeFirst(int []request, int head) { if (request.Length == 0) return; // create array of objects of class node node []diff = new node[request.Length]; // initialize array for (int i = 0; i < diff.Length; i++) diff[i] = new node(); // count total number of seek operation int seek_count = 0; // stores sequence in which disk access is done int[] seek_sequence = new int[request.Length + 1]; for (int i = 0; i < request.Length; i++) { seek_sequence[i] = head; calculateDifference(request, head, diff); int index = findMin(diff); diff[index].accessed = true; // increase the total count seek_count += diff[index].distance; // accessed track is now new head head = request[index]; } // for last accessed track seek_sequence[seek_sequence.Length - 1] = head; Console.WriteLine("Total number of seek operations = " + seek_count); Console.WriteLine("Seek Sequence is"); // print the sequence for (int i = 0; i < seek_sequence.Length; i++) Console.WriteLine(seek_sequence[i]); } // Driver code public static void Main(String[] args) { // request array int []arr = { 176, 79, 34, 60, 92, 11, 41, 114 }; shortestSeekTimeFirst(arr, 50); }} // This code contributed by Rajput-Ji
Output:
Total number of seek operations = 204
Seek Sequence is
50
41
34
11
60
79
92
114
176
Time Complexity: O(N^2)Auxiliary Space: O(N)
sonuyadavaffriya
SHUBHAMSINGH10
Rajput-Ji
itskawal2000
manish19je0495
pankajsharmagfg
arrynn
kk773572498
Algorithms
GATE CS
Operating Systems
Operating Systems
Algorithms
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
SDE SHEET - A Complete Guide for SDE Preparation
Top 50 Array Coding Problems for Interviews
DSA Sheet by Love Babbar
Difference between BFS and DFS
How to write a Pseudo Code?
Layers of OSI Model
ACID Properties in DBMS
TCP/IP Model
Normal Forms in DBMS
Differences between TCP and UDP | [
{
"code": null,
"e": 29507,
"s": 29479,
"text": "\n24 Jan, 2022"
},
{
"code": null,
"e": 29784,
"s": 29507,
"text": "Prerequisite – Disk scheduling algorithms Given an array of disk track numbers and initial head position, our task is to find the total number of seek operations done to access all the requested tracks if Shortest Seek Time First (SSTF) is a disk scheduling algorithm is used."
},
{
"code": null,
"e": 29957,
"s": 29784,
"text": "Shortest Seek Time First (SSTF) – Basic idea is the tracks which are closer to current disk head position should be serviced first in order to minimise the seek operations."
},
{
"code": null,
"e": 30006,
"s": 29957,
"text": "Advantages of Shortest Seek Time First (SSTF) – "
},
{
"code": null,
"e": 30218,
"s": 30006,
"text": "Better performance than FCFS scheduling algorithm.It provides better throughput.This algorithm is used in Batch Processing system where throughput is more important.It has less average response and waiting time."
},
{
"code": null,
"e": 30269,
"s": 30218,
"text": "Better performance than FCFS scheduling algorithm."
},
{
"code": null,
"e": 30300,
"s": 30269,
"text": "It provides better throughput."
},
{
"code": null,
"e": 30386,
"s": 30300,
"text": "This algorithm is used in Batch Processing system where throughput is more important."
},
{
"code": null,
"e": 30433,
"s": 30386,
"text": "It has less average response and waiting time."
},
{
"code": null,
"e": 30485,
"s": 30433,
"text": "Disadvantages of Shortest Seek Time First (SSTF) – "
},
{
"code": null,
"e": 30710,
"s": 30485,
"text": "Starvation is possible for some requests as it favours easy to reach request and ignores the far away processes.Their is lack of predictability because of high variance of response time.Switching direction slows things down."
},
{
"code": null,
"e": 30823,
"s": 30710,
"text": "Starvation is possible for some requests as it favours easy to reach request and ignores the far away processes."
},
{
"code": null,
"e": 30898,
"s": 30823,
"text": "Their is lack of predictability because of high variance of response time."
},
{
"code": null,
"e": 30937,
"s": 30898,
"text": "Switching direction slows things down."
},
{
"code": null,
"e": 30950,
"s": 30937,
"text": "Algorithm – "
},
{
"code": null,
"e": 31449,
"s": 30950,
"text": "Let Request array represents an array storing indexes of tracks that have been requested. ‘head’ is the position of disk head.Find the positive distance of all tracks in the request array from head.Find a track from requested array which has not been accessed/serviced yet and has minimum distance from head.Increment the total seek count with this distance.Currently serviced track position now becomes the new head position.Go to step 2 until all tracks in request array have not been serviced. "
},
{
"code": null,
"e": 31576,
"s": 31449,
"text": "Let Request array represents an array storing indexes of tracks that have been requested. ‘head’ is the position of disk head."
},
{
"code": null,
"e": 31649,
"s": 31576,
"text": "Find the positive distance of all tracks in the request array from head."
},
{
"code": null,
"e": 31760,
"s": 31649,
"text": "Find a track from requested array which has not been accessed/serviced yet and has minimum distance from head."
},
{
"code": null,
"e": 31811,
"s": 31760,
"text": "Increment the total seek count with this distance."
},
{
"code": null,
"e": 31880,
"s": 31811,
"text": "Currently serviced track position now becomes the new head position."
},
{
"code": null,
"e": 31953,
"s": 31880,
"text": "Go to step 2 until all tracks in request array have not been serviced. "
},
{
"code": null,
"e": 32045,
"s": 31953,
"text": "Example – Request sequence = {176, 79, 34, 60, 92, 11, 41, 114} Initial head position = 50 "
},
{
"code": null,
"e": 32136,
"s": 32045,
"text": "The following chart shows the sequence in which requested tracks are serviced using SSTF. "
},
{
"code": null,
"e": 32183,
"s": 32136,
"text": "Therefore, total seek count is calculated as: "
},
{
"code": null,
"e": 32259,
"s": 32183,
"text": "= (50-41)+(41-34)+(34-11)+(60-11)+(79-60)+(92-79)+(114-92)+(176-114)\n= 204 "
},
{
"code": null,
"e": 32624,
"s": 32259,
"text": "Which can also be directly calculated as: (50-11)+(176-11)Implementation – Implementation of SSTF is given below. Note that we have made a node class having 2 members. ‘distance’ is used to store the distance between head and the track position. ‘accessed’ is a boolean variable which tells whether the track has been accessed/serviced before by disk head or not. "
},
{
"code": null,
"e": 32628,
"s": 32624,
"text": "C++"
},
{
"code": null,
"e": 32633,
"s": 32628,
"text": "Java"
},
{
"code": null,
"e": 32641,
"s": 32633,
"text": "Python3"
},
{
"code": null,
"e": 32644,
"s": 32641,
"text": "C#"
},
{
"code": "// C++ program for implementation of// SSTF disk scheduling#include <bits/stdc++.h>using namespace std; // Calculates difference of each // track number with the head positionvoid calculatedifference(int request[], int head, int diff[][2], int n){ for(int i = 0; i < n; i++) { diff[i][0] = abs(head - request[i]); }} // Find unaccessed track which is// at minimum distance from headint findMIN(int diff[][2], int n){ int index = -1; int minimum = 1e9; for(int i = 0; i < n; i++) { if (!diff[i][1] && minimum > diff[i][0]) { minimum = diff[i][0]; index = i; } } return index;} void shortestSeekTimeFirst(int request[], int head, int n){ if (n == 0) { return; } // Create array of objects of class node int diff[n][2] = { { 0, 0 } }; // Count total number of seek operation int seekcount = 0; // Stores sequence in which disk access is done int seeksequence[n + 1] = {0}; for(int i = 0; i < n; i++) { seeksequence[i] = head; calculatedifference(request, head, diff, n); int index = findMIN(diff, n); diff[index][1] = 1; // Increase the total count seekcount += diff[index][0]; // Accessed track is now new head head = request[index]; } seeksequence[n] = head; cout << \"Total number of seek operations = \" << seekcount << endl; cout << \"Seek sequence is : \" << \"\\n\"; // Print the sequence for(int i = 0; i <= n; i++) { cout << seeksequence[i] << \"\\n\"; }} // Driver codeint main(){ int n = 8; int proc[n] = { 176, 79, 34, 60, 92, 11, 41, 114 }; shortestSeekTimeFirst(proc, 50, n); return 0;} // This code is contributed by manish19je0495",
"e": 34518,
"s": 32644,
"text": null
},
{
"code": "// Java program for implementation of// SSTF disk schedulingclass node { // represent difference between // head position and track number int distance = 0; // true if track has been accessed boolean accessed = false;} public class SSTF { // Calculates difference of each // track number with the head position public static void calculateDifference(int queue[], int head, node diff[]) { for (int i = 0; i < diff.length; i++) diff[i].distance = Math.abs(queue[i] - head); } // find unaccessed track // which is at minimum distance from head public static int findMin(node diff[]) { int index = -1, minimum = Integer.MAX_VALUE; for (int i = 0; i < diff.length; i++) { if (!diff[i].accessed && minimum > diff[i].distance) { minimum = diff[i].distance; index = i; } } return index; } public static void shortestSeekTimeFirst(int request[], int head) { if (request.length == 0) return; // create array of objects of class node node diff[] = new node[request.length]; // initialize array for (int i = 0; i < diff.length; i++) diff[i] = new node(); // count total number of seek operation int seek_count = 0; // stores sequence in which disk access is done int[] seek_sequence = new int[request.length + 1]; for (int i = 0; i < request.length; i++) { seek_sequence[i] = head; calculateDifference(request, head, diff); int index = findMin(diff); diff[index].accessed = true; // increase the total count seek_count += diff[index].distance; // accessed track is now new head head = request[index]; } // for last accessed track seek_sequence[seek_sequence.length - 1] = head; System.out.println(\"Total number of seek operations = \" + seek_count); System.out.println(\"Seek Sequence is\"); // print the sequence for (int i = 0; i < seek_sequence.length; i++) System.out.println(seek_sequence[i]); } public static void main(String[] args) { // request array int arr[] = { 176, 79, 34, 60, 92, 11, 41, 114 }; shortestSeekTimeFirst(arr, 50); }}",
"e": 37353,
"s": 34518,
"text": null
},
{
"code": "# Python3 program for implementation of# SSTF disk scheduling # Calculates difference of each# track number with the head positiondef calculateDifference(queue, head, diff): for i in range(len(diff)): diff[i][0] = abs(queue[i] - head) # find unaccessed track which is# at minimum distance from headdef findMin(diff): index = -1 minimum = 999999999 for i in range(len(diff)): if (not diff[i][1] and minimum > diff[i][0]): minimum = diff[i][0] index = i return index def shortestSeekTimeFirst(request, head): if (len(request) == 0): return l = len(request) diff = [0] * l # initialize array for i in range(l): diff[i] = [0, 0] # count total number of seek operation seek_count = 0 # stores sequence in which disk # access is done seek_sequence = [0] * (l + 1) for i in range(l): seek_sequence[i] = head calculateDifference(request, head, diff) index = findMin(diff) diff[index][1] = True # increase the total count seek_count += diff[index][0] # accessed track is now new head head = request[index] # for last accessed track seek_sequence[len(seek_sequence) - 1] = head print(\"Total number of seek operations =\", seek_count) print(\"Seek Sequence is\") # print the sequence for i in range(l + 1): print(seek_sequence[i]) # Driver codeif __name__ ==\"__main__\": # request array proc = [176, 79, 34, 60, 92, 11, 41, 114] shortestSeekTimeFirst(proc, 50) # This code is contributed by# Shubham Singh(SHUBHAMSINGH10)",
"e": 39327,
"s": 37353,
"text": null
},
{
"code": "// C# program for implementation of// SSTF disk schedulingusing System; public class node{ // represent difference between // head position and track number public int distance = 0; // true if track has been accessed public Boolean accessed = false;} public class SSTF{ // Calculates difference of each // track number with the head position public static void calculateDifference(int []queue, int head, node []diff) { for (int i = 0; i < diff.Length; i++) diff[i].distance = Math.Abs(queue[i] - head); } // find unaccessed track // which is at minimum distance from head public static int findMin(node []diff) { int index = -1, minimum = int.MaxValue; for (int i = 0; i < diff.Length; i++) { if (!diff[i].accessed && minimum > diff[i].distance) { minimum = diff[i].distance; index = i; } } return index; } public static void shortestSeekTimeFirst(int []request, int head) { if (request.Length == 0) return; // create array of objects of class node node []diff = new node[request.Length]; // initialize array for (int i = 0; i < diff.Length; i++) diff[i] = new node(); // count total number of seek operation int seek_count = 0; // stores sequence in which disk access is done int[] seek_sequence = new int[request.Length + 1]; for (int i = 0; i < request.Length; i++) { seek_sequence[i] = head; calculateDifference(request, head, diff); int index = findMin(diff); diff[index].accessed = true; // increase the total count seek_count += diff[index].distance; // accessed track is now new head head = request[index]; } // for last accessed track seek_sequence[seek_sequence.Length - 1] = head; Console.WriteLine(\"Total number of seek operations = \" + seek_count); Console.WriteLine(\"Seek Sequence is\"); // print the sequence for (int i = 0; i < seek_sequence.Length; i++) Console.WriteLine(seek_sequence[i]); } // Driver code public static void Main(String[] args) { // request array int []arr = { 176, 79, 34, 60, 92, 11, 41, 114 }; shortestSeekTimeFirst(arr, 50); }} // This code contributed by Rajput-Ji",
"e": 42207,
"s": 39327,
"text": null
},
{
"code": null,
"e": 42216,
"s": 42207,
"text": "Output: "
},
{
"code": null,
"e": 42301,
"s": 42216,
"text": "Total number of seek operations = 204\nSeek Sequence is\n50\n41\n34\n11\n60\n79\n92\n114\n176 "
},
{
"code": null,
"e": 42348,
"s": 42301,
"text": "Time Complexity: O(N^2)Auxiliary Space: O(N) "
},
{
"code": null,
"e": 42365,
"s": 42348,
"text": "sonuyadavaffriya"
},
{
"code": null,
"e": 42380,
"s": 42365,
"text": "SHUBHAMSINGH10"
},
{
"code": null,
"e": 42390,
"s": 42380,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 42403,
"s": 42390,
"text": "itskawal2000"
},
{
"code": null,
"e": 42418,
"s": 42403,
"text": "manish19je0495"
},
{
"code": null,
"e": 42434,
"s": 42418,
"text": "pankajsharmagfg"
},
{
"code": null,
"e": 42441,
"s": 42434,
"text": "arrynn"
},
{
"code": null,
"e": 42453,
"s": 42441,
"text": "kk773572498"
},
{
"code": null,
"e": 42464,
"s": 42453,
"text": "Algorithms"
},
{
"code": null,
"e": 42472,
"s": 42464,
"text": "GATE CS"
},
{
"code": null,
"e": 42490,
"s": 42472,
"text": "Operating Systems"
},
{
"code": null,
"e": 42508,
"s": 42490,
"text": "Operating Systems"
},
{
"code": null,
"e": 42519,
"s": 42508,
"text": "Algorithms"
},
{
"code": null,
"e": 42617,
"s": 42519,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 42666,
"s": 42617,
"text": "SDE SHEET - A Complete Guide for SDE Preparation"
},
{
"code": null,
"e": 42710,
"s": 42666,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 42735,
"s": 42710,
"text": "DSA Sheet by Love Babbar"
},
{
"code": null,
"e": 42766,
"s": 42735,
"text": "Difference between BFS and DFS"
},
{
"code": null,
"e": 42794,
"s": 42766,
"text": "How to write a Pseudo Code?"
},
{
"code": null,
"e": 42814,
"s": 42794,
"text": "Layers of OSI Model"
},
{
"code": null,
"e": 42838,
"s": 42814,
"text": "ACID Properties in DBMS"
},
{
"code": null,
"e": 42851,
"s": 42838,
"text": "TCP/IP Model"
},
{
"code": null,
"e": 42872,
"s": 42851,
"text": "Normal Forms in DBMS"
}
] |
How to Pass Image as a parameter in JavaScript function ? - GeeksforGeeks | 01 Sep, 2020
We all are familiar with functions and its parameters and we often use strings, integers, objects, arrays as a parameter in JavaScript functions but now will see how to pass an image as a parameter in JavaScript function. We will use vanilla JavaScript here.
First, create a function that receives a parameter then calls that function. The parameter should be a string that refers to the location of the image.
Syntax:
function displayImage (picUrl) {
...
}
displayImage('/assets/myPicture.jpg')
Example: In this example, we will display an image inside a DIV whose id is “imgDiv”.
<div id="imgDiv">
<!-- Here we show the picture -->
</div>
Steps:
First, create a markup that has an h1 and a div tag whose id is imgDiv in which we are going to insert the image.Create a script tag in which we all are going to make all our logics.Create a variable named divLocation and assign the DOM element of that div into the variable.Now create an img element with document.createElement() and assign it into variable imgElement.Then assign the URL of the image to its href attribute by using imgElement.href = /image location/.Now append the img Element to the div element by append() method.
First, create a markup that has an h1 and a div tag whose id is imgDiv in which we are going to insert the image.
Create a script tag in which we all are going to make all our logics.
Create a variable named divLocation and assign the DOM element of that div into the variable.
Now create an img element with document.createElement() and assign it into variable imgElement.
Then assign the URL of the image to its href attribute by using imgElement.href = /image location/.
Now append the img Element to the div element by append() method.
<!DOCTYPE html><html> <body> <center> <h1>Hello GFG</h1> <div id="imgDiv"></div> </center> <script> var Pic = "" function displayImage(pic) { let divLocation = document.getElementById("imgDiv"); let imgElement = document.createElement("img"); imgElement.src = pic divLocation.append(imgElement); } Pic = "https://write.geeksforgeeks.org/static/media/Group%20210.08204759.svg"; displayImage(Pic); </script></body> </html>
Output:
HTML-Misc
JavaScript-Misc
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to 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": 26117,
"s": 26089,
"text": "\n01 Sep, 2020"
},
{
"code": null,
"e": 26376,
"s": 26117,
"text": "We all are familiar with functions and its parameters and we often use strings, integers, objects, arrays as a parameter in JavaScript functions but now will see how to pass an image as a parameter in JavaScript function. We will use vanilla JavaScript here."
},
{
"code": null,
"e": 26528,
"s": 26376,
"text": "First, create a function that receives a parameter then calls that function. The parameter should be a string that refers to the location of the image."
},
{
"code": null,
"e": 26536,
"s": 26528,
"text": "Syntax:"
},
{
"code": null,
"e": 26619,
"s": 26536,
"text": "function displayImage (picUrl) {\n ...\n}\n\ndisplayImage('/assets/myPicture.jpg')\n"
},
{
"code": null,
"e": 26705,
"s": 26619,
"text": "Example: In this example, we will display an image inside a DIV whose id is “imgDiv”."
},
{
"code": null,
"e": 26769,
"s": 26705,
"text": "<div id=\"imgDiv\">\n <!-- Here we show the picture -->\n</div>\n"
},
{
"code": null,
"e": 26776,
"s": 26769,
"text": "Steps:"
},
{
"code": null,
"e": 27311,
"s": 26776,
"text": "First, create a markup that has an h1 and a div tag whose id is imgDiv in which we are going to insert the image.Create a script tag in which we all are going to make all our logics.Create a variable named divLocation and assign the DOM element of that div into the variable.Now create an img element with document.createElement() and assign it into variable imgElement.Then assign the URL of the image to its href attribute by using imgElement.href = /image location/.Now append the img Element to the div element by append() method."
},
{
"code": null,
"e": 27425,
"s": 27311,
"text": "First, create a markup that has an h1 and a div tag whose id is imgDiv in which we are going to insert the image."
},
{
"code": null,
"e": 27495,
"s": 27425,
"text": "Create a script tag in which we all are going to make all our logics."
},
{
"code": null,
"e": 27589,
"s": 27495,
"text": "Create a variable named divLocation and assign the DOM element of that div into the variable."
},
{
"code": null,
"e": 27685,
"s": 27589,
"text": "Now create an img element with document.createElement() and assign it into variable imgElement."
},
{
"code": null,
"e": 27785,
"s": 27685,
"text": "Then assign the URL of the image to its href attribute by using imgElement.href = /image location/."
},
{
"code": null,
"e": 27851,
"s": 27785,
"text": "Now append the img Element to the div element by append() method."
},
{
"code": "<!DOCTYPE html><html> <body> <center> <h1>Hello GFG</h1> <div id=\"imgDiv\"></div> </center> <script> var Pic = \"\" function displayImage(pic) { let divLocation = document.getElementById(\"imgDiv\"); let imgElement = document.createElement(\"img\"); imgElement.src = pic divLocation.append(imgElement); } Pic = \"https://write.geeksforgeeks.org/static/media/Group%20210.08204759.svg\"; displayImage(Pic); </script></body> </html>",
"e": 28387,
"s": 27851,
"text": null
},
{
"code": null,
"e": 28395,
"s": 28387,
"text": "Output:"
},
{
"code": null,
"e": 28405,
"s": 28395,
"text": "HTML-Misc"
},
{
"code": null,
"e": 28421,
"s": 28405,
"text": "JavaScript-Misc"
},
{
"code": null,
"e": 28432,
"s": 28421,
"text": "JavaScript"
},
{
"code": null,
"e": 28449,
"s": 28432,
"text": "Web Technologies"
},
{
"code": null,
"e": 28547,
"s": 28449,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28587,
"s": 28547,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 28632,
"s": 28587,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 28693,
"s": 28632,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 28765,
"s": 28693,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 28817,
"s": 28765,
"text": "How to append HTML code to a div using JavaScript ?"
},
{
"code": null,
"e": 28857,
"s": 28817,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 28890,
"s": 28857,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 28935,
"s": 28890,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 28978,
"s": 28935,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
How to Download All Images from a Web Page in Python? - GeeksforGeeks | 16 Oct, 2021
Prerequisite:
Requests
BeautifulSoup
os
File Handling
Web scraping is a technique to fetch data from websites. While surfing on the web, many websites don’t allow the user to save data for personal use. One way is to manually copy-paste the data, which both tedious and time-consuming. Web Scraping is the automation of the data extraction process from websites. In this article we will discuss how we can download all images from a web page using python.
bs4: Beautiful Soup(bs4) is a Python library for pulling data out of HTML and XML files. This module does not come built-in with Python.
requests: Requests allows you to send HTTP/1.1 requests extremely easily. This module also does not come built-in with Python.
os: The OS module in python provides functions for interacting with the operating system. OS, comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality.
Import module
Get HTML Code
Get list of img tags from HTML Code using findAll method in Beautiful Soup.
images = soup.findAll('img')
Create separate folder for downloading images using mkdir method in os.
os.mkdir(folder_name)
Iterate through all images and get the source URL of that image.
After getting the source URL, last step is download the image
Fetch Content of Image
r = requests.get(Source URL).content
Download image using File Handling
# Enter File Name with Extension like jpg, png etc..
with open("File Name","wb+") as f:
f.write(r)
Program:
Python3
from bs4 import *import requestsimport os # CREATE FOLDERdef folder_create(images): try: folder_name = input("Enter Folder Name:- ") # folder creation os.mkdir(folder_name) # if folder exists with that name, ask another name except: print("Folder Exist with that name!") folder_create() # image downloading start download_images(images, folder_name) # DOWNLOAD ALL IMAGES FROM THAT URLdef download_images(images, folder_name): # initial count is zero count = 0 # print total images found in URL print(f"Total {len(images)} Image Found!") # checking if images is not zero if len(images) != 0: for i, image in enumerate(images): # From image tag ,Fetch image Source URL # 1.data-srcset # 2.data-src # 3.data-fallback-src # 4.src # Here we will use exception handling # first we will search for "data-srcset" in img tag try: # In image tag ,searching for "data-srcset" image_link = image["data-srcset"] # then we will search for "data-src" in img # tag and so on.. except: try: # In image tag ,searching for "data-src" image_link = image["data-src"] except: try: # In image tag ,searching for "data-fallback-src" image_link = image["data-fallback-src"] except: try: # In image tag ,searching for "src" image_link = image["src"] # if no Source URL found except: pass # After getting Image Source URL # We will try to get the content of image try: r = requests.get(image_link).content try: # possibility of decode r = str(r, 'utf-8') except UnicodeDecodeError: # After checking above condition, Image Download start with open(f"{folder_name}/images{i+1}.jpg", "wb+") as f: f.write(r) # counting number of image downloaded count += 1 except: pass # There might be possible, that all # images not download # if all images download if count == len(images): print("All Images Downloaded!") # if all images not download else: print(f"Total {count} Images Downloaded Out of {len(images)}") # MAIN FUNCTION STARTdef main(url): # content of URL r = requests.get(url) # Parse HTML Code soup = BeautifulSoup(r.text, 'html.parser') # find all images in URL images = soup.findAll('img') # Call folder create function folder_create(images) # take urlurl = input("Enter URL:- ") # CALL MAIN FUNCTIONmain(url)
Output:
ruhelaa48
Picked
Python BeautifulSoup
Python web-scraping-exercises
Python-requests
Web-scraping
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Python | Get unique values from a list
Defaultdict in Python
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby() | [
{
"code": null,
"e": 25537,
"s": 25509,
"text": "\n16 Oct, 2021"
},
{
"code": null,
"e": 25551,
"s": 25537,
"text": "Prerequisite:"
},
{
"code": null,
"e": 25561,
"s": 25551,
"text": "Requests "
},
{
"code": null,
"e": 25575,
"s": 25561,
"text": "BeautifulSoup"
},
{
"code": null,
"e": 25578,
"s": 25575,
"text": "os"
},
{
"code": null,
"e": 25592,
"s": 25578,
"text": "File Handling"
},
{
"code": null,
"e": 25994,
"s": 25592,
"text": "Web scraping is a technique to fetch data from websites. While surfing on the web, many websites don’t allow the user to save data for personal use. One way is to manually copy-paste the data, which both tedious and time-consuming. Web Scraping is the automation of the data extraction process from websites. In this article we will discuss how we can download all images from a web page using python."
},
{
"code": null,
"e": 26131,
"s": 25994,
"text": "bs4: Beautiful Soup(bs4) is a Python library for pulling data out of HTML and XML files. This module does not come built-in with Python."
},
{
"code": null,
"e": 26259,
"s": 26131,
"text": "requests: Requests allows you to send HTTP/1.1 requests extremely easily. This module also does not come built-in with Python."
},
{
"code": null,
"e": 26487,
"s": 26259,
"text": "os: The OS module in python provides functions for interacting with the operating system. OS, comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality."
},
{
"code": null,
"e": 26501,
"s": 26487,
"text": "Import module"
},
{
"code": null,
"e": 26515,
"s": 26501,
"text": "Get HTML Code"
},
{
"code": null,
"e": 26591,
"s": 26515,
"text": "Get list of img tags from HTML Code using findAll method in Beautiful Soup."
},
{
"code": null,
"e": 26620,
"s": 26591,
"text": "images = soup.findAll('img')"
},
{
"code": null,
"e": 26692,
"s": 26620,
"text": "Create separate folder for downloading images using mkdir method in os."
},
{
"code": null,
"e": 26714,
"s": 26692,
"text": "os.mkdir(folder_name)"
},
{
"code": null,
"e": 26779,
"s": 26714,
"text": "Iterate through all images and get the source URL of that image."
},
{
"code": null,
"e": 26841,
"s": 26779,
"text": "After getting the source URL, last step is download the image"
},
{
"code": null,
"e": 26864,
"s": 26841,
"text": "Fetch Content of Image"
},
{
"code": null,
"e": 26901,
"s": 26864,
"text": "r = requests.get(Source URL).content"
},
{
"code": null,
"e": 26936,
"s": 26901,
"text": "Download image using File Handling"
},
{
"code": null,
"e": 27041,
"s": 26936,
"text": "# Enter File Name with Extension like jpg, png etc..\nwith open(\"File Name\",\"wb+\") as f:\n f.write(r)"
},
{
"code": null,
"e": 27050,
"s": 27041,
"text": "Program:"
},
{
"code": null,
"e": 27058,
"s": 27050,
"text": "Python3"
},
{
"code": "from bs4 import *import requestsimport os # CREATE FOLDERdef folder_create(images): try: folder_name = input(\"Enter Folder Name:- \") # folder creation os.mkdir(folder_name) # if folder exists with that name, ask another name except: print(\"Folder Exist with that name!\") folder_create() # image downloading start download_images(images, folder_name) # DOWNLOAD ALL IMAGES FROM THAT URLdef download_images(images, folder_name): # initial count is zero count = 0 # print total images found in URL print(f\"Total {len(images)} Image Found!\") # checking if images is not zero if len(images) != 0: for i, image in enumerate(images): # From image tag ,Fetch image Source URL # 1.data-srcset # 2.data-src # 3.data-fallback-src # 4.src # Here we will use exception handling # first we will search for \"data-srcset\" in img tag try: # In image tag ,searching for \"data-srcset\" image_link = image[\"data-srcset\"] # then we will search for \"data-src\" in img # tag and so on.. except: try: # In image tag ,searching for \"data-src\" image_link = image[\"data-src\"] except: try: # In image tag ,searching for \"data-fallback-src\" image_link = image[\"data-fallback-src\"] except: try: # In image tag ,searching for \"src\" image_link = image[\"src\"] # if no Source URL found except: pass # After getting Image Source URL # We will try to get the content of image try: r = requests.get(image_link).content try: # possibility of decode r = str(r, 'utf-8') except UnicodeDecodeError: # After checking above condition, Image Download start with open(f\"{folder_name}/images{i+1}.jpg\", \"wb+\") as f: f.write(r) # counting number of image downloaded count += 1 except: pass # There might be possible, that all # images not download # if all images download if count == len(images): print(\"All Images Downloaded!\") # if all images not download else: print(f\"Total {count} Images Downloaded Out of {len(images)}\") # MAIN FUNCTION STARTdef main(url): # content of URL r = requests.get(url) # Parse HTML Code soup = BeautifulSoup(r.text, 'html.parser') # find all images in URL images = soup.findAll('img') # Call folder create function folder_create(images) # take urlurl = input(\"Enter URL:- \") # CALL MAIN FUNCTIONmain(url)",
"e": 30208,
"s": 27058,
"text": null
},
{
"code": null,
"e": 30216,
"s": 30208,
"text": "Output:"
},
{
"code": null,
"e": 30226,
"s": 30216,
"text": "ruhelaa48"
},
{
"code": null,
"e": 30233,
"s": 30226,
"text": "Picked"
},
{
"code": null,
"e": 30254,
"s": 30233,
"text": "Python BeautifulSoup"
},
{
"code": null,
"e": 30284,
"s": 30254,
"text": "Python web-scraping-exercises"
},
{
"code": null,
"e": 30300,
"s": 30284,
"text": "Python-requests"
},
{
"code": null,
"e": 30313,
"s": 30300,
"text": "Web-scraping"
},
{
"code": null,
"e": 30320,
"s": 30313,
"text": "Python"
},
{
"code": null,
"e": 30418,
"s": 30320,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30450,
"s": 30418,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 30492,
"s": 30450,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 30534,
"s": 30492,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 30561,
"s": 30534,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 30617,
"s": 30561,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 30656,
"s": 30617,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 30678,
"s": 30656,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 30709,
"s": 30678,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 30738,
"s": 30709,
"text": "Create a directory in Python"
}
] |
Python | PageLayout in Kivy - GeeksforGeeks | 19 Oct, 2021
Kivy is a platform independent GUI tool in Python. As it can be run on Android, IOS, linux, and Windows, etc. It is basically used to develop the Android application, but it does not mean that it can not be used on Desktops applications.
Kivy Tutorial – Learn Kivy with Examples.
The PageLayout works in a different manner from other layouts. It is a dynamic layout, in the sense that it allows flipping through pages using its borders. The idea is that its components are stacked in front of each other, and we can just see the one that is on top. The PageLayout class is used to create a simple multi-page layout, in a way that allows easy flipping from one page to another using border.
To use PageLayout you have to import it by the below command:
from kivy.uix.pagelayout import PageLayout
Note: PageLayout does not currently honor the size_hint, size_hint_min, size_hint_max, or pos_hint properties.That means we can not use all these in a page layout.
Basic Approach to create PageLayout:
1) import kivy
2) import kivyApp
3) import Pagelayout
4) import button
5) Set minimum version(optional)
6) create App class:
- define build() function
7) return Layout/widget/Class(according to requirement)
8) Run an instance of the class
Implementation of the Approach:
Python3
# Sample Python application demonstrating # How to create PageLayout in Kivy import kivy # base Class of your App inherits from the App class. # app:always refers to the instance of your application from kivy.app import App # The PageLayout class is used to create# a simple multi-page layout,# in a way that allows easy flipping from# one page to another using borders.from kivy.uix.pagelayout import PageLayout # creates the button in kivy # if not imported shows the error from kivy.uix.button import Button class PageLayout(PageLayout): """ Define class PageLayout here """ def __init__(self): # The super function in Python can be # used to gain access to inherited methods # which is either from a parent or sibling class. super(PageLayout, self).__init__() # creating buttons on different pages btn1 = Button(text ='Page 1') btn2 = Button(text ='Page 2') btn3 = Button(text ='Page 3') # adding button on the screen # by add widget method self.add_widget(btn1) self.add_widget(btn2) self.add_widget(btn3) # creating the App classclass Page_LayoutApp(App): """ App class here """ def build(self): """ build function here """ return PageLayout() # Run the Appif __name__ == '__main__': Page_LayoutApp().run()
Output:Page 1 image
Page 2 image
Page 3 image
In PageLayout You can add some features on every page. We can add image, create canvas, add color, add multiple widgets, multiple layouts This is how we can use the PageLayout in an efficient way. One of the best example Our gallery Contains multiple pages.Below is the code in which i am adding the different color to every page with the help of get_color_from_hex
Implementation of the PageLayout with features
Python3
# Sample Python application demonstrating the# working of PageLayout in Kivy with some features import kivy # base Class of your App inherits from the App class. # app:always refers to the instance of your application from kivy.app import App # The PageLayout class is used to create# a simple multi-page layout,# in a way that allows easy flipping from# one page to another using borders.from kivy.uix.pagelayout import PageLayout # creates the button in kivy # if not imported shows the error from kivy.uix.button import Button # The Utils module provides a selection of general utility# functions and classes that may be useful for various applications.# These include maths, color, algebraic and platform functions.# Here we are using color from the module# By get_color_from_hex# Transform a hex string color to a kivy Color.from kivy.utils import get_color_from_hex class PageLayout(PageLayout): """ Define class PageLayout here """ def __init__(self): # The super function in Python can be # used to gain access to inherited methods # which is either from a parent or sibling class. super(PageLayout, self).__init__() # creating buttons on different pages # Button 1 or Page 1 btn1 = Button(text ='Page 1') # Adding Colour to page # Here we are using colour from btn1.background_color = get_color_from_hex('# FF0000') btn2 = Button(text ='Page 2') btn2.background_color = get_color_from_hex('# 00FF00') btn3 = Button(text ='Page 3') btn3.background_color = get_color_from_hex('# 0000FF') # adding button on the screen # by add widget method self.add_widget(btn1) self.add_widget(btn2) self.add_widget(btn3) # creating the App classclass Page_LayoutApp(App): """ App class here """ def build(self): """ build function here """ return PageLayout() # Run the Appif __name__ == '__main__': Page_LayoutApp().run()
Output:Page 1
Page 2
Page 3
Video Output:
Note: More effective when works on Android, Ios, any other touch supported Laptops. Reference: https://kivy.org/doc/stable/api-kivy.uix.pagelayout.html
sweetyty
ruhelaa48
Python-gui
Python-kivy
Python
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
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace() | [
{
"code": null,
"e": 42675,
"s": 42647,
"text": "\n19 Oct, 2021"
},
{
"code": null,
"e": 42913,
"s": 42675,
"text": "Kivy is a platform independent GUI tool in Python. As it can be run on Android, IOS, linux, and Windows, etc. It is basically used to develop the Android application, but it does not mean that it can not be used on Desktops applications."
},
{
"code": null,
"e": 42956,
"s": 42913,
"text": "Kivy Tutorial – Learn Kivy with Examples. "
},
{
"code": null,
"e": 43366,
"s": 42956,
"text": "The PageLayout works in a different manner from other layouts. It is a dynamic layout, in the sense that it allows flipping through pages using its borders. The idea is that its components are stacked in front of each other, and we can just see the one that is on top. The PageLayout class is used to create a simple multi-page layout, in a way that allows easy flipping from one page to another using border."
},
{
"code": null,
"e": 43430,
"s": 43366,
"text": "To use PageLayout you have to import it by the below command: "
},
{
"code": null,
"e": 43473,
"s": 43430,
"text": "from kivy.uix.pagelayout import PageLayout"
},
{
"code": null,
"e": 43637,
"s": 43473,
"text": "Note: PageLayout does not currently honor the size_hint, size_hint_min, size_hint_max, or pos_hint properties.That means we can not use all these in a page layout."
},
{
"code": null,
"e": 43676,
"s": 43637,
"text": "Basic Approach to create PageLayout: "
},
{
"code": null,
"e": 43923,
"s": 43676,
"text": "1) import kivy\n2) import kivyApp\n3) import Pagelayout\n4) import button\n5) Set minimum version(optional)\n6) create App class:\n - define build() function\n7) return Layout/widget/Class(according to requirement)\n8) Run an instance of the class"
},
{
"code": null,
"e": 43956,
"s": 43923,
"text": "Implementation of the Approach: "
},
{
"code": null,
"e": 43964,
"s": 43956,
"text": "Python3"
},
{
"code": "# Sample Python application demonstrating # How to create PageLayout in Kivy import kivy # base Class of your App inherits from the App class. # app:always refers to the instance of your application from kivy.app import App # The PageLayout class is used to create# a simple multi-page layout,# in a way that allows easy flipping from# one page to another using borders.from kivy.uix.pagelayout import PageLayout # creates the button in kivy # if not imported shows the error from kivy.uix.button import Button class PageLayout(PageLayout): \"\"\" Define class PageLayout here \"\"\" def __init__(self): # The super function in Python can be # used to gain access to inherited methods # which is either from a parent or sibling class. super(PageLayout, self).__init__() # creating buttons on different pages btn1 = Button(text ='Page 1') btn2 = Button(text ='Page 2') btn3 = Button(text ='Page 3') # adding button on the screen # by add widget method self.add_widget(btn1) self.add_widget(btn2) self.add_widget(btn3) # creating the App classclass Page_LayoutApp(App): \"\"\" App class here \"\"\" def build(self): \"\"\" build function here \"\"\" return PageLayout() # Run the Appif __name__ == '__main__': Page_LayoutApp().run()",
"e": 45363,
"s": 43964,
"text": null
},
{
"code": null,
"e": 45384,
"s": 45363,
"text": "Output:Page 1 image "
},
{
"code": null,
"e": 45398,
"s": 45384,
"text": "Page 2 image "
},
{
"code": null,
"e": 45412,
"s": 45398,
"text": "Page 3 image "
},
{
"code": null,
"e": 45778,
"s": 45412,
"text": "In PageLayout You can add some features on every page. We can add image, create canvas, add color, add multiple widgets, multiple layouts This is how we can use the PageLayout in an efficient way. One of the best example Our gallery Contains multiple pages.Below is the code in which i am adding the different color to every page with the help of get_color_from_hex"
},
{
"code": null,
"e": 45826,
"s": 45778,
"text": "Implementation of the PageLayout with features "
},
{
"code": null,
"e": 45834,
"s": 45826,
"text": "Python3"
},
{
"code": "# Sample Python application demonstrating the# working of PageLayout in Kivy with some features import kivy # base Class of your App inherits from the App class. # app:always refers to the instance of your application from kivy.app import App # The PageLayout class is used to create# a simple multi-page layout,# in a way that allows easy flipping from# one page to another using borders.from kivy.uix.pagelayout import PageLayout # creates the button in kivy # if not imported shows the error from kivy.uix.button import Button # The Utils module provides a selection of general utility# functions and classes that may be useful for various applications.# These include maths, color, algebraic and platform functions.# Here we are using color from the module# By get_color_from_hex# Transform a hex string color to a kivy Color.from kivy.utils import get_color_from_hex class PageLayout(PageLayout): \"\"\" Define class PageLayout here \"\"\" def __init__(self): # The super function in Python can be # used to gain access to inherited methods # which is either from a parent or sibling class. super(PageLayout, self).__init__() # creating buttons on different pages # Button 1 or Page 1 btn1 = Button(text ='Page 1') # Adding Colour to page # Here we are using colour from btn1.background_color = get_color_from_hex('# FF0000') btn2 = Button(text ='Page 2') btn2.background_color = get_color_from_hex('# 00FF00') btn3 = Button(text ='Page 3') btn3.background_color = get_color_from_hex('# 0000FF') # adding button on the screen # by add widget method self.add_widget(btn1) self.add_widget(btn2) self.add_widget(btn3) # creating the App classclass Page_LayoutApp(App): \"\"\" App class here \"\"\" def build(self): \"\"\" build function here \"\"\" return PageLayout() # Run the Appif __name__ == '__main__': Page_LayoutApp().run()",
"e": 47880,
"s": 45834,
"text": null
},
{
"code": null,
"e": 47895,
"s": 47880,
"text": "Output:Page 1 "
},
{
"code": null,
"e": 47903,
"s": 47895,
"text": "Page 2 "
},
{
"code": null,
"e": 47911,
"s": 47903,
"text": "Page 3 "
},
{
"code": null,
"e": 47927,
"s": 47911,
"text": "Video Output: "
},
{
"code": null,
"e": 48080,
"s": 47927,
"text": "Note: More effective when works on Android, Ios, any other touch supported Laptops. Reference: https://kivy.org/doc/stable/api-kivy.uix.pagelayout.html "
},
{
"code": null,
"e": 48089,
"s": 48080,
"text": "sweetyty"
},
{
"code": null,
"e": 48099,
"s": 48089,
"text": "ruhelaa48"
},
{
"code": null,
"e": 48110,
"s": 48099,
"text": "Python-gui"
},
{
"code": null,
"e": 48122,
"s": 48110,
"text": "Python-kivy"
},
{
"code": null,
"e": 48129,
"s": 48122,
"text": "Python"
},
{
"code": null,
"e": 48227,
"s": 48129,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 48255,
"s": 48227,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 48305,
"s": 48255,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 48327,
"s": 48305,
"text": "Python map() function"
},
{
"code": null,
"e": 48371,
"s": 48327,
"text": "How to get column names in Pandas dataframe"
},
{
"code": null,
"e": 48406,
"s": 48371,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 48438,
"s": 48406,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 48460,
"s": 48438,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 48502,
"s": 48460,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 48532,
"s": 48502,
"text": "Iterate over a list in Python"
}
] |
ASP Redirect Method - GeeksforGeeks | 19 Aug, 2020
The ASP Redirect Method is used to redirect the client to a different URL. It is a predefined method of the Response Object.
Syntax:
Response.Redirect URL
Parameter Values: This method accepts a single parameter as mentioned above and described below:
URL: It defines a Uniform resource locator which represents the browser is redirected to.
Return value: This method does not return any value.
Example: Below code redirects the user to geeksforgeeks website.
<%
Response.Redirect "https://www.GeelsforGeeks.org.in"
%>
ASP-Properties
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
Difference between var, let and const keywords in JavaScript
How to create footer to stay at the bottom of a Web page?
Differences between Functional Components and Class Components in React
How to set the default value for an HTML <select> element ?
File uploading in React.js
How to set input type date in dd-mm-yyyy format using HTML ?
How to apply style to parent if it has child with CSS? | [
{
"code": null,
"e": 25649,
"s": 25621,
"text": "\n19 Aug, 2020"
},
{
"code": null,
"e": 25774,
"s": 25649,
"text": "The ASP Redirect Method is used to redirect the client to a different URL. It is a predefined method of the Response Object."
},
{
"code": null,
"e": 25782,
"s": 25774,
"text": "Syntax:"
},
{
"code": null,
"e": 25809,
"s": 25782,
"text": "Response.Redirect URL\n\n\n\n\n"
},
{
"code": null,
"e": 25906,
"s": 25809,
"text": "Parameter Values: This method accepts a single parameter as mentioned above and described below:"
},
{
"code": null,
"e": 25996,
"s": 25906,
"text": "URL: It defines a Uniform resource locator which represents the browser is redirected to."
},
{
"code": null,
"e": 26050,
"s": 25996,
"text": "Return value: This method does not return any value. "
},
{
"code": null,
"e": 26115,
"s": 26050,
"text": "Example: Below code redirects the user to geeksforgeeks website."
},
{
"code": null,
"e": 26176,
"s": 26115,
"text": "<%\nResponse.Redirect \"https://www.GeelsforGeeks.org.in\"\n%>\n\n"
},
{
"code": null,
"e": 26191,
"s": 26176,
"text": "ASP-Properties"
},
{
"code": null,
"e": 26208,
"s": 26191,
"text": "Web Technologies"
},
{
"code": null,
"e": 26306,
"s": 26208,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26346,
"s": 26306,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 26391,
"s": 26346,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 26434,
"s": 26391,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 26495,
"s": 26434,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 26553,
"s": 26495,
"text": "How to create footer to stay at the bottom of a Web page?"
},
{
"code": null,
"e": 26625,
"s": 26553,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 26685,
"s": 26625,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 26712,
"s": 26685,
"text": "File uploading in React.js"
},
{
"code": null,
"e": 26773,
"s": 26712,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
}
] |
Overriding methods from different packages in Java - GeeksforGeeks | 22 Jun, 2020
Prerequisite : Overriding in Java, Packages in JavaPackages provide more layer of encapsulation for classes. Thus, visibility of a method in different packages is different from that in the same package.
How JVM find which method to call?When we run a java program,
JVM checks the runtime class of the object.
JVM checks whether the object’s runtime class has overridden the method of the declared class.
If so, that’s the method called. Otherwise, declared class’s method is called.
Thus, the key point is visible check the visibility of method in different packages.
Following are the cases where we will see method overriding in different packages
1. Private method overriding : In this, access modifier of method we want to override is private.
// Filename: Hello.javapackage a;public class Hello { private void printMessage() { System.out.println("Hello"); } public void fun() { printMessage(); }} // Filename: World.javapackage b;import a.Hello;public class World extends Hello { private void printMessage() { System.out.println("World"); } public static void main(String[] args) { Hello gfg = new World(); gfg.fun(); }}
Output:
Hello
As private method of parent class is not visible in child class. Thus no overriding takes place here.If you don’t know how to run this program from terminal then, create Hello.java file and World.java file as specified above and run these commands.
2. Public method overriding : In this, access modifier of method we want to override is public.
// Hello.javapackage a;public class Hello { public void printMessage() { System.out.println("Hello"); }} // World.javapackage b;import a.Hello;public class World extends Hello { public void printMessage() { System.out.println("World"); } public static void main(String[] args) { Hello gfg = new World(); gfg.printMessage(); }}
Output:
World
Public method is accessible everywhere, hence when printMessage() is called, jvm can find the overridden method and thus call it.Thus overriding takes place here.
3. Default method overriding
// Hello.javapackage a;public class Hello { void printMessage() { System.out.println("Hello"); }} // World.javapackage b;import a.Hello;public class World extends Hello { void printMessage() { System.out.println("World"); } public static void main(String[] args) { Hello gfg = new World(); gfg.printMessage(); }}
error: printMessage() is not public in Hello; cannot be accessed from outside package
Visibility of a default method is within its package only. Hence it can’t be access outside the package.Thus, no overriding in this case.
Predict the output of the following program
/* Hello.java */package a;public class Hello { public void doIt() { printMessage(); } void printMessage() { System.out.println("Hello"); }} /* World.java */package b;import a.Hello;public class World { private static class GFG extends Hello { void printMessage() { System.out.println("World"); } } public static void main(String[] args) { GFG gfg = new GFG(); gfg.doIt(); }}
Output:
Hello
ExplanationVisibility of printMessage() is default in package a. Thus, no overriding takes place here.
This article is contributed by Shubham Juneja. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Akanksha_Rai
java-inheritance
java-overriding
Java-Packages
Java
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
Generics in Java
Introduction to Java
Comparator Interface in Java with Examples
Internal Working of HashMap in Java
Strings in Java | [
{
"code": null,
"e": 25225,
"s": 25197,
"text": "\n22 Jun, 2020"
},
{
"code": null,
"e": 25429,
"s": 25225,
"text": "Prerequisite : Overriding in Java, Packages in JavaPackages provide more layer of encapsulation for classes. Thus, visibility of a method in different packages is different from that in the same package."
},
{
"code": null,
"e": 25491,
"s": 25429,
"text": "How JVM find which method to call?When we run a java program,"
},
{
"code": null,
"e": 25535,
"s": 25491,
"text": "JVM checks the runtime class of the object."
},
{
"code": null,
"e": 25630,
"s": 25535,
"text": "JVM checks whether the object’s runtime class has overridden the method of the declared class."
},
{
"code": null,
"e": 25709,
"s": 25630,
"text": "If so, that’s the method called. Otherwise, declared class’s method is called."
},
{
"code": null,
"e": 25794,
"s": 25709,
"text": "Thus, the key point is visible check the visibility of method in different packages."
},
{
"code": null,
"e": 25876,
"s": 25794,
"text": "Following are the cases where we will see method overriding in different packages"
},
{
"code": null,
"e": 25974,
"s": 25876,
"text": "1. Private method overriding : In this, access modifier of method we want to override is private."
},
{
"code": "// Filename: Hello.javapackage a;public class Hello { private void printMessage() { System.out.println(\"Hello\"); } public void fun() { printMessage(); }} // Filename: World.javapackage b;import a.Hello;public class World extends Hello { private void printMessage() { System.out.println(\"World\"); } public static void main(String[] args) { Hello gfg = new World(); gfg.fun(); }}",
"e": 26426,
"s": 25974,
"text": null
},
{
"code": null,
"e": 26434,
"s": 26426,
"text": "Output:"
},
{
"code": null,
"e": 26440,
"s": 26434,
"text": "Hello"
},
{
"code": null,
"e": 26689,
"s": 26440,
"text": "As private method of parent class is not visible in child class. Thus no overriding takes place here.If you don’t know how to run this program from terminal then, create Hello.java file and World.java file as specified above and run these commands."
},
{
"code": null,
"e": 26785,
"s": 26689,
"text": "2. Public method overriding : In this, access modifier of method we want to override is public."
},
{
"code": "// Hello.javapackage a;public class Hello { public void printMessage() { System.out.println(\"Hello\"); }} // World.javapackage b;import a.Hello;public class World extends Hello { public void printMessage() { System.out.println(\"World\"); } public static void main(String[] args) { Hello gfg = new World(); gfg.printMessage(); }}",
"e": 27170,
"s": 26785,
"text": null
},
{
"code": null,
"e": 27178,
"s": 27170,
"text": "Output:"
},
{
"code": null,
"e": 27185,
"s": 27178,
"text": "World\n"
},
{
"code": null,
"e": 27348,
"s": 27185,
"text": "Public method is accessible everywhere, hence when printMessage() is called, jvm can find the overridden method and thus call it.Thus overriding takes place here."
},
{
"code": null,
"e": 27377,
"s": 27348,
"text": "3. Default method overriding"
},
{
"code": "// Hello.javapackage a;public class Hello { void printMessage() { System.out.println(\"Hello\"); }} // World.javapackage b;import a.Hello;public class World extends Hello { void printMessage() { System.out.println(\"World\"); } public static void main(String[] args) { Hello gfg = new World(); gfg.printMessage(); }}",
"e": 27746,
"s": 27377,
"text": null
},
{
"code": null,
"e": 27832,
"s": 27746,
"text": "error: printMessage() is not public in Hello; cannot be accessed from outside package"
},
{
"code": null,
"e": 27970,
"s": 27832,
"text": "Visibility of a default method is within its package only. Hence it can’t be access outside the package.Thus, no overriding in this case."
},
{
"code": null,
"e": 28014,
"s": 27970,
"text": "Predict the output of the following program"
},
{
"code": "/* Hello.java */package a;public class Hello { public void doIt() { printMessage(); } void printMessage() { System.out.println(\"Hello\"); }} /* World.java */package b;import a.Hello;public class World { private static class GFG extends Hello { void printMessage() { System.out.println(\"World\"); } } public static void main(String[] args) { GFG gfg = new GFG(); gfg.doIt(); }}",
"e": 28484,
"s": 28014,
"text": null
},
{
"code": null,
"e": 28492,
"s": 28484,
"text": "Output:"
},
{
"code": null,
"e": 28499,
"s": 28492,
"text": "Hello\n"
},
{
"code": null,
"e": 28602,
"s": 28499,
"text": "ExplanationVisibility of printMessage() is default in package a. Thus, no overriding takes place here."
},
{
"code": null,
"e": 28904,
"s": 28602,
"text": "This article is contributed by Shubham Juneja. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 29029,
"s": 28904,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 29042,
"s": 29029,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 29059,
"s": 29042,
"text": "java-inheritance"
},
{
"code": null,
"e": 29075,
"s": 29059,
"text": "java-overriding"
},
{
"code": null,
"e": 29089,
"s": 29075,
"text": "Java-Packages"
},
{
"code": null,
"e": 29094,
"s": 29089,
"text": "Java"
},
{
"code": null,
"e": 29099,
"s": 29094,
"text": "Java"
},
{
"code": null,
"e": 29197,
"s": 29099,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29212,
"s": 29197,
"text": "Stream In Java"
},
{
"code": null,
"e": 29233,
"s": 29212,
"text": "Constructors in Java"
},
{
"code": null,
"e": 29252,
"s": 29233,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 29282,
"s": 29252,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 29328,
"s": 29282,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 29345,
"s": 29328,
"text": "Generics in Java"
},
{
"code": null,
"e": 29366,
"s": 29345,
"text": "Introduction to Java"
},
{
"code": null,
"e": 29409,
"s": 29366,
"text": "Comparator Interface in Java with Examples"
},
{
"code": null,
"e": 29445,
"s": 29409,
"text": "Internal Working of HashMap in Java"
}
] |
BigInteger equals() Method in Java - GeeksforGeeks | 04 Dec, 2018
The java.math.BigInteger.equals(Object x) method compares this BigInteger with the object passed as the parameter and returns true in both are equal in value else it returns false.
Syntax:
public boolean equals(Object x)
Parameter: This method accepts a single mandatory parameter x which is the Object to which BigInteger Object is to be compared.
Returns: This method returns boolean true if and only if the Object passed as parameter is a BigInteger whose value is equal to the BigInteger Object on which the method is applied. Otherwise it will return false.
Examples:
Input: BigInteger1=2345, BigInteger2=7456
Output: false
Explanation: BigInteger1.equals(BigInteger2)=false.
Input: BigInteger1=7356, BigInteger2=7456
Output: true
Explanation: BigInteger1.equals(BigInteger2)=true.
Below programs illustrate equals() method of BigInteger class:
Example 1: When both are equal in value.
// Java program to demonstrate equals() method of BigInteger import java.math.BigInteger; public class GFG { public static void main(String[] args) { // Creating 2 BigInteger objects BigInteger b1, b2; b1 = new BigInteger("321456"); b2 = new BigInteger("321456"); // apply equals() method boolean response = b1.equals(b2); // print result if (response) { System.out.println("BigInteger1 " + b1 + " and BigInteger2 " + b2 + " are equal"); } else { System.out.println("BigInteger1 " + b1 + " and BigInteger2 " + b2 + " are not equal"); } }}
BigInteger1 321456 and BigInteger2 321456 are equal
Example 2: When both are not equal in value.
// Java program to demonstrate equals() method of BigInteger import java.math.BigInteger; public class GFG { public static void main(String[] args) { // Creating 2 BigInteger objects BigInteger b1, b2; b1 = new BigInteger("321456"); b2 = new BigInteger("456782"); // apply equals() method boolean response = b1.equals(b2); // print result if (response) { System.out.println("BigInteger1 " + b1 + " and BigInteger2 " + b2 + " are equal"); } else { System.out.println("BigInteger1 " + b1 + " and BigInteger2 " + b2 + " are not equal"); } }}
BigInteger1 321456 and BigInteger2 456782 are not equal
Example 3: When object passed as parameter is other than BigInteger.
// Java program to demonstrate equals() method of BigInteger import java.math.BigInteger; public class Main6 { public static void main(String[] args) { // Creating BigInteger object BigInteger b1; b1 = new BigInteger("321456"); String object = "321456"; // apply equals() method boolean response = b1.equals(object); // print result if (response) { System.out.println("BigInteger1 " + b1 + " and String Object " + object + " are equal"); } else { System.out.println("BigInteger1 " + b1 + " and String Object " + object + " are not equal"); } }}
BigInteger1 321456 and String Object 321456 are not equal
Reference: https://docs.oracle.com/javase/7/docs/api/java/math/BigInteger.html#equals(java.lang.Object)
java-basics
Java-BigInteger
Java-Functions
java-math
Java-math-package
Java
Java-BigInteger
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
HashMap in Java with Examples
Interfaces in Java
Stream In Java
How to iterate any Map in Java
ArrayList in Java
Initialize an ArrayList in Java
Stack Class in Java
Multidimensional Arrays in Java
Singleton Class in Java | [
{
"code": null,
"e": 25619,
"s": 25591,
"text": "\n04 Dec, 2018"
},
{
"code": null,
"e": 25800,
"s": 25619,
"text": "The java.math.BigInteger.equals(Object x) method compares this BigInteger with the object passed as the parameter and returns true in both are equal in value else it returns false."
},
{
"code": null,
"e": 25808,
"s": 25800,
"text": "Syntax:"
},
{
"code": null,
"e": 25840,
"s": 25808,
"text": "public boolean equals(Object x)"
},
{
"code": null,
"e": 25968,
"s": 25840,
"text": "Parameter: This method accepts a single mandatory parameter x which is the Object to which BigInteger Object is to be compared."
},
{
"code": null,
"e": 26182,
"s": 25968,
"text": "Returns: This method returns boolean true if and only if the Object passed as parameter is a BigInteger whose value is equal to the BigInteger Object on which the method is applied. Otherwise it will return false."
},
{
"code": null,
"e": 26192,
"s": 26182,
"text": "Examples:"
},
{
"code": null,
"e": 26408,
"s": 26192,
"text": "Input: BigInteger1=2345, BigInteger2=7456\nOutput: false\nExplanation: BigInteger1.equals(BigInteger2)=false.\n\nInput: BigInteger1=7356, BigInteger2=7456\nOutput: true\nExplanation: BigInteger1.equals(BigInteger2)=true.\n"
},
{
"code": null,
"e": 26471,
"s": 26408,
"text": "Below programs illustrate equals() method of BigInteger class:"
},
{
"code": null,
"e": 26512,
"s": 26471,
"text": "Example 1: When both are equal in value."
},
{
"code": "// Java program to demonstrate equals() method of BigInteger import java.math.BigInteger; public class GFG { public static void main(String[] args) { // Creating 2 BigInteger objects BigInteger b1, b2; b1 = new BigInteger(\"321456\"); b2 = new BigInteger(\"321456\"); // apply equals() method boolean response = b1.equals(b2); // print result if (response) { System.out.println(\"BigInteger1 \" + b1 + \" and BigInteger2 \" + b2 + \" are equal\"); } else { System.out.println(\"BigInteger1 \" + b1 + \" and BigInteger2 \" + b2 + \" are not equal\"); } }}",
"e": 27295,
"s": 26512,
"text": null
},
{
"code": null,
"e": 27348,
"s": 27295,
"text": "BigInteger1 321456 and BigInteger2 321456 are equal\n"
},
{
"code": null,
"e": 27393,
"s": 27348,
"text": "Example 2: When both are not equal in value."
},
{
"code": "// Java program to demonstrate equals() method of BigInteger import java.math.BigInteger; public class GFG { public static void main(String[] args) { // Creating 2 BigInteger objects BigInteger b1, b2; b1 = new BigInteger(\"321456\"); b2 = new BigInteger(\"456782\"); // apply equals() method boolean response = b1.equals(b2); // print result if (response) { System.out.println(\"BigInteger1 \" + b1 + \" and BigInteger2 \" + b2 + \" are equal\"); } else { System.out.println(\"BigInteger1 \" + b1 + \" and BigInteger2 \" + b2 + \" are not equal\"); } }}",
"e": 28146,
"s": 27393,
"text": null
},
{
"code": null,
"e": 28203,
"s": 28146,
"text": "BigInteger1 321456 and BigInteger2 456782 are not equal\n"
},
{
"code": null,
"e": 28272,
"s": 28203,
"text": "Example 3: When object passed as parameter is other than BigInteger."
},
{
"code": "// Java program to demonstrate equals() method of BigInteger import java.math.BigInteger; public class Main6 { public static void main(String[] args) { // Creating BigInteger object BigInteger b1; b1 = new BigInteger(\"321456\"); String object = \"321456\"; // apply equals() method boolean response = b1.equals(object); // print result if (response) { System.out.println(\"BigInteger1 \" + b1 + \" and String Object \" + object + \" are equal\"); } else { System.out.println(\"BigInteger1 \" + b1 + \" and String Object \" + object + \" are not equal\"); } }}",
"e": 29062,
"s": 28272,
"text": null
},
{
"code": null,
"e": 29121,
"s": 29062,
"text": "BigInteger1 321456 and String Object 321456 are not equal\n"
},
{
"code": null,
"e": 29225,
"s": 29121,
"text": "Reference: https://docs.oracle.com/javase/7/docs/api/java/math/BigInteger.html#equals(java.lang.Object)"
},
{
"code": null,
"e": 29237,
"s": 29225,
"text": "java-basics"
},
{
"code": null,
"e": 29253,
"s": 29237,
"text": "Java-BigInteger"
},
{
"code": null,
"e": 29268,
"s": 29253,
"text": "Java-Functions"
},
{
"code": null,
"e": 29278,
"s": 29268,
"text": "java-math"
},
{
"code": null,
"e": 29296,
"s": 29278,
"text": "Java-math-package"
},
{
"code": null,
"e": 29301,
"s": 29296,
"text": "Java"
},
{
"code": null,
"e": 29317,
"s": 29301,
"text": "Java-BigInteger"
},
{
"code": null,
"e": 29322,
"s": 29317,
"text": "Java"
},
{
"code": null,
"e": 29420,
"s": 29322,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29471,
"s": 29420,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 29501,
"s": 29471,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 29520,
"s": 29501,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 29535,
"s": 29520,
"text": "Stream In Java"
},
{
"code": null,
"e": 29566,
"s": 29535,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 29584,
"s": 29566,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 29616,
"s": 29584,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 29636,
"s": 29616,
"text": "Stack Class in Java"
},
{
"code": null,
"e": 29668,
"s": 29636,
"text": "Multidimensional Arrays in Java"
}
] |
Check if an array is sorted and rotated using Binary Search - GeeksforGeeks | 21 Aug, 2021
Pre-requisite: Check if an array is sorted and rotated using Linear SearchGiven an array arr[] of N distinct integers, the task is to check if this array is sorted when rotated counter-clockwise. A sorted array is not considered sorted and rotated, i.e., there should at least one rotation.
Examples:
Input: arr[] = { 3, 4, 5, 1, 2 } Output: true Explanation: Sorted array: {1, 2, 3, 4, 5}. Rotating this sorted array clockwise by 3 positions, we get: { 3, 4, 5, 1, 2}
Input: arr[] = {7, 9, 11, 12, 5} Output: true
Input: arr[] = {1, 2, 3} Output: false
Approach: One approach to solving this problem using Linear Search has already been discussed in this article. In this article, an approach using Binary Search concept is mentioned.
To apply a binary search, the array needs to follow some order by which at every iteration, one-half of the array can be eliminated.
Therefore, the order followed by an array which is sorted and rotated array is that all the elements to the left of the pivot(the point at which the array is rotated) are in descending order and all the elements to the right of the pivot would be in ascending order. This can be visualized from the illustration below:
Therefore, the pivot can be found using Binary Search and recursion in the following way: Base Cases: The base case will be either when the pivot has been found or if the pivot cannot be found in the given array. The pivot cannot be found when the right index is less than the left index. -1 is returned in these cases. And when high and low are pointing to the same element, then the element at low is the pivot and that element is returned.
Base Cases: The base case will be either when the pivot has been found or if the pivot cannot be found in the given array. The pivot cannot be found when the right index is less than the left index. -1 is returned in these cases. And when high and low are pointing to the same element, then the element at low is the pivot and that element is returned.
if (high < low)
return -1;
if (high == low)
return low;
Apart from this, another base case is when mid((low + high) / 2) is a pivot. The element at mid is considered when that element is less than the next element or greater than the previous element.
if (mid < high && arr[mid + 1] < arr[mid])
return mid;
if (mid > low && arr[mid] < arr[mid - 1])
return mid - 1;
Recursive Case: When none of the base cases satisfies, then a decision has to be made whether to ignore the first half or second half. This decision is taken by checking if the element at the first index (low) is greater than the element at the middle index or not. If it is, then the pivot for sure lies in the first half. Else, the pivot lies in the second half.
if (arr[low] > arr[mid])
return findPivot(arr, low, mid - 1);
else
return findPivot(arr, mid + 1, high);
Once the pivot is found, then either traverse to the left of the array from the pivot and check if all the elements are in descending order, or traverse to the right of the array and check if all the elements are in ascending order or not.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
#include <bits/stdc++.h> using namespace std; // Function to return the// index of the pivotint findPivot(int arr[], int low, int high){ // Base cases if (high < low) return -1; if (high == low) return low; int mid = (low + high) / 2; if (mid < high && arr[mid + 1] < arr[mid]) { return mid; } // Check if element at (mid - 1) is pivot // Consider the cases like {4, 5, 1, 2, 3} if (mid > low && arr[mid] < arr[mid - 1]) { return mid - 1; } // Decide whether we need to go to // the left half or the right half if (arr[low] > arr[mid]) { return findPivot(arr, low, mid - 1); } else { return findPivot(arr, mid + 1, high); }} // Function to check if a given array// is sorted rotated or notbool isRotated(int arr[], int n){ int l = 0; int r = n - 1; int pivot = -1; if (arr[l] > arr[r]) { pivot = findPivot(arr, l, r); int temp=pivot; // To check if the elements to the left // of the pivot are in descending or not if (l < pivot) { while (pivot > l) { if (arr[pivot] < arr[pivot - 1]) { return false; } pivot--; } } // To check if the elements to the right // of the pivot are in ascending or not pivot=temp; if(pivot < r) { pivot++; while (pivot < r) { if (arr[pivot] > arr[pivot + 1]) { return false; } pivot++; } } // If both of the above if is true // Then the array is sorted rotated return true; } // Else the array is not sorted rotated else { return false; }} // Driver codeint main(){ int arr[] = { 4, 5, 1, 3, 2 }; if (isRotated(arr, 5)) cout<<"true"; else cout<<"false"; return 0;} // This code is contributed by mohit kumar 29
// Java implementation of the above approach class GFG { // Function to return the // index of the pivot static int findPivot(int arr[], int low, int high) { // Base cases if (high < low) return -1; if (high == low) return low; int mid = (low + high) / 2; if (mid < high && arr[mid + 1] < arr[mid]) { return mid; } // Check if element at (mid - 1) is pivot // Consider the cases like {4, 5, 1, 2, 3} if (mid > low && arr[mid] < arr[mid - 1]) { return mid - 1; } // Decide whether we need to go to // the left half or the right half if (arr[low] > arr[mid]) { return findPivot(arr, low, mid - 1); } else { return findPivot(arr, mid + 1, high); } } // Function to check if a given array // is sorted rotated or not public static boolean isRotated(int arr[], int n) { int l = 0; int r = n - 1; int pivot = -1; if (arr[l] > arr[r]) { pivot = findPivot(arr, l, r); int temp=pivot; // To check if the elements to the left // of the pivot are in descending or not if (l < pivot) { while (pivot > l) { if (arr[pivot] < arr[pivot - 1]) { return false; } pivot--; } } // To check if the elements to the right // of the pivot are in ascending or not pivot=temp; else { pivot++; while (pivot < r) { if (arr[pivot] > arr[pivot + 1]) { return false; } pivot++; } } // If any of the above if or else is true // Then the array is sorted rotated return true; } // Else the array is not sorted rotated else { return false; } } // Driver code public static void main(String[] args) { int arr[] = { 4, 5, 1, 3, 2 }; System.out.println(isRotated(arr, 5)); }}
# Python3 implementation of the above approach # Function to return the# index of the pivotdef findPivot(arr, low, high) : # Base cases if (high < low) : return -1; if (high == low) : return low; mid = (low + high) // 2; if (mid < high and arr[mid + 1] < arr[mid]) : return mid; # Check if element at (mid - 1) is pivot # Consider the cases like {4, 5, 1, 2, 3} if (mid > low and arr[mid] < arr[mid - 1]) : return mid - 1; # Decide whether we need to go to # the left half or the right half if (arr[low] > arr[mid]) : return findPivot(arr, low, mid - 1); else : return findPivot(arr, mid + 1, high); # Function to check if a given array# is sorted rotated or notdef isRotated(arr, n) : l = 0; r = n - 1; pivot = -1; if (arr[l] > arr[r]) : pivot = findPivot(arr, l, r); temp = pivot # To check if the elements to the left # of the pivot are in descending or not if (l < pivot) : while (pivot > l) : if (arr[pivot] < arr[pivot - 1]) : return False; pivot -= 1; # To check if the elements to the right # of the pivot are in ascending or not else : pivot=temp pivot += 1; while (pivot < r) : if (arr[pivot] > arr[pivot + 1]) : return False; pivot ++ 1; # If any of the above if or else is true # Then the array is sorted rotated return True; # Else the array is not sorted rotated else : return False; # Driver codeif __name__ == "__main__" : arr = [ 3, 4, 5, 1, 2 ]; if (isRotated(arr, 5)) : print("True"); else : print("False"); # This code is contributed by Yash_R
// C# implementation of the above approachusing System; class GFG { // Function to return the // index of the pivot static int findPivot(int []arr, int low, int high) { // Base cases if (high < low) return -1; if (high == low) return low; int mid = (low + high) / 2; if (mid < high && arr[mid + 1] < arr[mid]) { return mid; } // Check if element at (mid - 1) is pivot // Consider the cases like {4, 5, 1, 2, 3} if (mid > low && arr[mid] < arr[mid - 1]) { return mid - 1; } // Decide whether we need to go to // the left half or the right half if (arr[low] > arr[mid]) { return findPivot(arr, low, mid - 1); } else { return findPivot(arr, mid + 1, high); } } // Function to check if a given array // is sorted rotated or not public static bool isRotated(int []arr, int n) { int l = 0; int r = n - 1; int pivot = -1; if (arr[l] > arr[r]) { pivot = findPivot(arr, l, r); int temp = pivot; // To check if the elements to the left // of the pivot are in descending or not if (l < pivot) { while (pivot > l) { if (arr[pivot] < arr[pivot - 1]) { return false; } pivot--; } } // To check if the elements to the right // of the pivot are in ascending or not pivot=temp; else { pivot++; while (pivot < r) { if (arr[pivot] > arr[pivot + 1]) { return false; } pivot++; } } // If any of the above if or else is true // Then the array is sorted rotated return true; } // Else the array is not sorted rotated else { return false; } } // Driver code public static void Main(String[] args) { int []arr = { 3, 4, 5, 1, 2 }; Console.WriteLine(isRotated(arr, 5)); }} // This code contributed by Rajput-Ji
<script> // Function to return the// index of the pivotfunction findPivot(arr, low, high){ // Base cases if (high < low) return -1; if (high == low) return low; var mid = parseInt((low + high) / 2); if (mid < high && arr[mid + 1] < arr[mid]) { return mid; } // Check if element at (mid - 1) is pivot // Consider the cases like {4, 5, 1, 2, 3} if (mid > low && arr[mid] < arr[mid - 1]) { return mid - 1; } // Decide whether we need to go to // the left half or the right half if (arr[low] > arr[mid]) { return findPivot(arr, low, mid - 1); } else { return findPivot(arr, mid + 1, high); }} // Function to check if a given array// is sorted rotated or notfunction isRotated(arr, n){ var l = 0; var r = n - 1; var pivot = -1; if (arr[l] > arr[r]) { pivot = findPivot(arr, l, r); var temp=pivot; // To check if the elements to the left // of the pivot are in descending or not if (l < pivot) { while (pivot > l) { if (arr[pivot] < arr[pivot - 1]) { return false; } pivot--; } } // To check if the elements to the right // of the pivot are in ascending or not else { pivot=temp; pivot++; while (pivot < r) { if (arr[pivot] > arr[pivot + 1]) { return false; } pivot++; } } // If both of the above if is true // Then the array is sorted rotated return true; } // Else the array is not sorted rotated else { return false; }} // Driver codevar arr = [4, 5, 1, 3, 2];if (isRotated(arr, 5)) document.write("true");else document.write("false"); </script>
true
Time Complexity: O(N) as:
The pivot element is being found using Binary Search in O(log N)
But in order to check if the left part or right part is in descending or ascending order, O(N) time is needed in worst case scenario.
Therefore the overall time complexity is O(N)
mohit kumar 29
Rajput-Ji
Yash_R
anushka128
rrrtnx
sumitgumber28
Binary Search
Arrays
Recursion
Searching
Arrays
Searching
Recursion
Binary Search
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Maximum and minimum of an array using minimum number of comparisons
Top 50 Array Coding Problems for Interviews
Stack Data Structure (Introduction and Program)
Introduction to Arrays
Multidimensional Arrays in Java
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": 26779,
"s": 26751,
"text": "\n21 Aug, 2021"
},
{
"code": null,
"e": 27070,
"s": 26779,
"text": "Pre-requisite: Check if an array is sorted and rotated using Linear SearchGiven an array arr[] of N distinct integers, the task is to check if this array is sorted when rotated counter-clockwise. A sorted array is not considered sorted and rotated, i.e., there should at least one rotation."
},
{
"code": null,
"e": 27081,
"s": 27070,
"text": "Examples: "
},
{
"code": null,
"e": 27249,
"s": 27081,
"text": "Input: arr[] = { 3, 4, 5, 1, 2 } Output: true Explanation: Sorted array: {1, 2, 3, 4, 5}. Rotating this sorted array clockwise by 3 positions, we get: { 3, 4, 5, 1, 2}"
},
{
"code": null,
"e": 27295,
"s": 27249,
"text": "Input: arr[] = {7, 9, 11, 12, 5} Output: true"
},
{
"code": null,
"e": 27335,
"s": 27295,
"text": "Input: arr[] = {1, 2, 3} Output: false "
},
{
"code": null,
"e": 27518,
"s": 27335,
"text": "Approach: One approach to solving this problem using Linear Search has already been discussed in this article. In this article, an approach using Binary Search concept is mentioned. "
},
{
"code": null,
"e": 27651,
"s": 27518,
"text": "To apply a binary search, the array needs to follow some order by which at every iteration, one-half of the array can be eliminated."
},
{
"code": null,
"e": 27971,
"s": 27651,
"text": "Therefore, the order followed by an array which is sorted and rotated array is that all the elements to the left of the pivot(the point at which the array is rotated) are in descending order and all the elements to the right of the pivot would be in ascending order. This can be visualized from the illustration below: "
},
{
"code": null,
"e": 28414,
"s": 27971,
"text": "Therefore, the pivot can be found using Binary Search and recursion in the following way: Base Cases: The base case will be either when the pivot has been found or if the pivot cannot be found in the given array. The pivot cannot be found when the right index is less than the left index. -1 is returned in these cases. And when high and low are pointing to the same element, then the element at low is the pivot and that element is returned."
},
{
"code": null,
"e": 28767,
"s": 28414,
"text": "Base Cases: The base case will be either when the pivot has been found or if the pivot cannot be found in the given array. The pivot cannot be found when the right index is less than the left index. -1 is returned in these cases. And when high and low are pointing to the same element, then the element at low is the pivot and that element is returned."
},
{
"code": null,
"e": 28833,
"s": 28767,
"text": "if (high < low)\n return -1;\nif (high == low)\n return low;"
},
{
"code": null,
"e": 29029,
"s": 28833,
"text": "Apart from this, another base case is when mid((low + high) / 2) is a pivot. The element at mid is considered when that element is less than the next element or greater than the previous element."
},
{
"code": null,
"e": 29150,
"s": 29029,
"text": "if (mid < high && arr[mid + 1] < arr[mid])\n return mid;\nif (mid > low && arr[mid] < arr[mid - 1])\n return mid - 1;"
},
{
"code": null,
"e": 29515,
"s": 29150,
"text": "Recursive Case: When none of the base cases satisfies, then a decision has to be made whether to ignore the first half or second half. This decision is taken by checking if the element at the first index (low) is greater than the element at the middle index or not. If it is, then the pivot for sure lies in the first half. Else, the pivot lies in the second half."
},
{
"code": null,
"e": 29634,
"s": 29515,
"text": "if (arr[low] > arr[mid]) \n return findPivot(arr, low, mid - 1); \nelse \n return findPivot(arr, mid + 1, high);"
},
{
"code": null,
"e": 29874,
"s": 29634,
"text": "Once the pivot is found, then either traverse to the left of the array from the pivot and check if all the elements are in descending order, or traverse to the right of the array and check if all the elements are in ascending order or not."
},
{
"code": null,
"e": 29926,
"s": 29874,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 29930,
"s": 29926,
"text": "C++"
},
{
"code": null,
"e": 29935,
"s": 29930,
"text": "Java"
},
{
"code": null,
"e": 29943,
"s": 29935,
"text": "Python3"
},
{
"code": null,
"e": 29946,
"s": 29943,
"text": "C#"
},
{
"code": null,
"e": 29957,
"s": 29946,
"text": "Javascript"
},
{
"code": "#include <bits/stdc++.h> using namespace std; // Function to return the// index of the pivotint findPivot(int arr[], int low, int high){ // Base cases if (high < low) return -1; if (high == low) return low; int mid = (low + high) / 2; if (mid < high && arr[mid + 1] < arr[mid]) { return mid; } // Check if element at (mid - 1) is pivot // Consider the cases like {4, 5, 1, 2, 3} if (mid > low && arr[mid] < arr[mid - 1]) { return mid - 1; } // Decide whether we need to go to // the left half or the right half if (arr[low] > arr[mid]) { return findPivot(arr, low, mid - 1); } else { return findPivot(arr, mid + 1, high); }} // Function to check if a given array// is sorted rotated or notbool isRotated(int arr[], int n){ int l = 0; int r = n - 1; int pivot = -1; if (arr[l] > arr[r]) { pivot = findPivot(arr, l, r); int temp=pivot; // To check if the elements to the left // of the pivot are in descending or not if (l < pivot) { while (pivot > l) { if (arr[pivot] < arr[pivot - 1]) { return false; } pivot--; } } // To check if the elements to the right // of the pivot are in ascending or not pivot=temp; if(pivot < r) { pivot++; while (pivot < r) { if (arr[pivot] > arr[pivot + 1]) { return false; } pivot++; } } // If both of the above if is true // Then the array is sorted rotated return true; } // Else the array is not sorted rotated else { return false; }} // Driver codeint main(){ int arr[] = { 4, 5, 1, 3, 2 }; if (isRotated(arr, 5)) cout<<\"true\"; else cout<<\"false\"; return 0;} // This code is contributed by mohit kumar 29",
"e": 31967,
"s": 29957,
"text": null
},
{
"code": "// Java implementation of the above approach class GFG { // Function to return the // index of the pivot static int findPivot(int arr[], int low, int high) { // Base cases if (high < low) return -1; if (high == low) return low; int mid = (low + high) / 2; if (mid < high && arr[mid + 1] < arr[mid]) { return mid; } // Check if element at (mid - 1) is pivot // Consider the cases like {4, 5, 1, 2, 3} if (mid > low && arr[mid] < arr[mid - 1]) { return mid - 1; } // Decide whether we need to go to // the left half or the right half if (arr[low] > arr[mid]) { return findPivot(arr, low, mid - 1); } else { return findPivot(arr, mid + 1, high); } } // Function to check if a given array // is sorted rotated or not public static boolean isRotated(int arr[], int n) { int l = 0; int r = n - 1; int pivot = -1; if (arr[l] > arr[r]) { pivot = findPivot(arr, l, r); int temp=pivot; // To check if the elements to the left // of the pivot are in descending or not if (l < pivot) { while (pivot > l) { if (arr[pivot] < arr[pivot - 1]) { return false; } pivot--; } } // To check if the elements to the right // of the pivot are in ascending or not pivot=temp; else { pivot++; while (pivot < r) { if (arr[pivot] > arr[pivot + 1]) { return false; } pivot++; } } // If any of the above if or else is true // Then the array is sorted rotated return true; } // Else the array is not sorted rotated else { return false; } } // Driver code public static void main(String[] args) { int arr[] = { 4, 5, 1, 3, 2 }; System.out.println(isRotated(arr, 5)); }}",
"e": 34216,
"s": 31967,
"text": null
},
{
"code": "# Python3 implementation of the above approach # Function to return the# index of the pivotdef findPivot(arr, low, high) : # Base cases if (high < low) : return -1; if (high == low) : return low; mid = (low + high) // 2; if (mid < high and arr[mid + 1] < arr[mid]) : return mid; # Check if element at (mid - 1) is pivot # Consider the cases like {4, 5, 1, 2, 3} if (mid > low and arr[mid] < arr[mid - 1]) : return mid - 1; # Decide whether we need to go to # the left half or the right half if (arr[low] > arr[mid]) : return findPivot(arr, low, mid - 1); else : return findPivot(arr, mid + 1, high); # Function to check if a given array# is sorted rotated or notdef isRotated(arr, n) : l = 0; r = n - 1; pivot = -1; if (arr[l] > arr[r]) : pivot = findPivot(arr, l, r); temp = pivot # To check if the elements to the left # of the pivot are in descending or not if (l < pivot) : while (pivot > l) : if (arr[pivot] < arr[pivot - 1]) : return False; pivot -= 1; # To check if the elements to the right # of the pivot are in ascending or not else : pivot=temp pivot += 1; while (pivot < r) : if (arr[pivot] > arr[pivot + 1]) : return False; pivot ++ 1; # If any of the above if or else is true # Then the array is sorted rotated return True; # Else the array is not sorted rotated else : return False; # Driver codeif __name__ == \"__main__\" : arr = [ 3, 4, 5, 1, 2 ]; if (isRotated(arr, 5)) : print(\"True\"); else : print(\"False\"); # This code is contributed by Yash_R",
"e": 36177,
"s": 34216,
"text": null
},
{
"code": "// C# implementation of the above approachusing System; class GFG { // Function to return the // index of the pivot static int findPivot(int []arr, int low, int high) { // Base cases if (high < low) return -1; if (high == low) return low; int mid = (low + high) / 2; if (mid < high && arr[mid + 1] < arr[mid]) { return mid; } // Check if element at (mid - 1) is pivot // Consider the cases like {4, 5, 1, 2, 3} if (mid > low && arr[mid] < arr[mid - 1]) { return mid - 1; } // Decide whether we need to go to // the left half or the right half if (arr[low] > arr[mid]) { return findPivot(arr, low, mid - 1); } else { return findPivot(arr, mid + 1, high); } } // Function to check if a given array // is sorted rotated or not public static bool isRotated(int []arr, int n) { int l = 0; int r = n - 1; int pivot = -1; if (arr[l] > arr[r]) { pivot = findPivot(arr, l, r); int temp = pivot; // To check if the elements to the left // of the pivot are in descending or not if (l < pivot) { while (pivot > l) { if (arr[pivot] < arr[pivot - 1]) { return false; } pivot--; } } // To check if the elements to the right // of the pivot are in ascending or not pivot=temp; else { pivot++; while (pivot < r) { if (arr[pivot] > arr[pivot + 1]) { return false; } pivot++; } } // If any of the above if or else is true // Then the array is sorted rotated return true; } // Else the array is not sorted rotated else { return false; } } // Driver code public static void Main(String[] args) { int []arr = { 3, 4, 5, 1, 2 }; Console.WriteLine(isRotated(arr, 5)); }} // This code contributed by Rajput-Ji",
"e": 38470,
"s": 36177,
"text": null
},
{
"code": "<script> // Function to return the// index of the pivotfunction findPivot(arr, low, high){ // Base cases if (high < low) return -1; if (high == low) return low; var mid = parseInt((low + high) / 2); if (mid < high && arr[mid + 1] < arr[mid]) { return mid; } // Check if element at (mid - 1) is pivot // Consider the cases like {4, 5, 1, 2, 3} if (mid > low && arr[mid] < arr[mid - 1]) { return mid - 1; } // Decide whether we need to go to // the left half or the right half if (arr[low] > arr[mid]) { return findPivot(arr, low, mid - 1); } else { return findPivot(arr, mid + 1, high); }} // Function to check if a given array// is sorted rotated or notfunction isRotated(arr, n){ var l = 0; var r = n - 1; var pivot = -1; if (arr[l] > arr[r]) { pivot = findPivot(arr, l, r); var temp=pivot; // To check if the elements to the left // of the pivot are in descending or not if (l < pivot) { while (pivot > l) { if (arr[pivot] < arr[pivot - 1]) { return false; } pivot--; } } // To check if the elements to the right // of the pivot are in ascending or not else { pivot=temp; pivot++; while (pivot < r) { if (arr[pivot] > arr[pivot + 1]) { return false; } pivot++; } } // If both of the above if is true // Then the array is sorted rotated return true; } // Else the array is not sorted rotated else { return false; }} // Driver codevar arr = [4, 5, 1, 3, 2];if (isRotated(arr, 5)) document.write(\"true\");else document.write(\"false\"); </script>",
"e": 40395,
"s": 38470,
"text": null
},
{
"code": null,
"e": 40400,
"s": 40395,
"text": "true"
},
{
"code": null,
"e": 40429,
"s": 40402,
"text": "Time Complexity: O(N) as: "
},
{
"code": null,
"e": 40494,
"s": 40429,
"text": "The pivot element is being found using Binary Search in O(log N)"
},
{
"code": null,
"e": 40628,
"s": 40494,
"text": "But in order to check if the left part or right part is in descending or ascending order, O(N) time is needed in worst case scenario."
},
{
"code": null,
"e": 40674,
"s": 40628,
"text": "Therefore the overall time complexity is O(N)"
},
{
"code": null,
"e": 40691,
"s": 40676,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 40701,
"s": 40691,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 40708,
"s": 40701,
"text": "Yash_R"
},
{
"code": null,
"e": 40719,
"s": 40708,
"text": "anushka128"
},
{
"code": null,
"e": 40726,
"s": 40719,
"text": "rrrtnx"
},
{
"code": null,
"e": 40740,
"s": 40726,
"text": "sumitgumber28"
},
{
"code": null,
"e": 40754,
"s": 40740,
"text": "Binary Search"
},
{
"code": null,
"e": 40761,
"s": 40754,
"text": "Arrays"
},
{
"code": null,
"e": 40771,
"s": 40761,
"text": "Recursion"
},
{
"code": null,
"e": 40781,
"s": 40771,
"text": "Searching"
},
{
"code": null,
"e": 40788,
"s": 40781,
"text": "Arrays"
},
{
"code": null,
"e": 40798,
"s": 40788,
"text": "Searching"
},
{
"code": null,
"e": 40808,
"s": 40798,
"text": "Recursion"
},
{
"code": null,
"e": 40822,
"s": 40808,
"text": "Binary Search"
},
{
"code": null,
"e": 40920,
"s": 40822,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 40988,
"s": 40920,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 41032,
"s": 40988,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 41080,
"s": 41032,
"text": "Stack Data Structure (Introduction and Program)"
},
{
"code": null,
"e": 41103,
"s": 41080,
"text": "Introduction to Arrays"
},
{
"code": null,
"e": 41135,
"s": 41103,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 41195,
"s": 41135,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 41280,
"s": 41195,
"text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)"
},
{
"code": null,
"e": 41290,
"s": 41280,
"text": "Recursion"
},
{
"code": null,
"e": 41317,
"s": 41290,
"text": "Program for Tower of Hanoi"
}
] |
Node.js fs.readdirSync() Method - GeeksforGeeks | 11 Oct, 2021
The fs.readdirSync() method is used to synchronously read the contents of a given directory. The method returns an array with all the file names or objects in the directory. The options argument can be used to change the format in which the files are returned from the method.
Syntax:
fs.readdirSync( path, options )
Parameters: This method accept two parameters as mentioned above and described below:
path: It holds the path of the directory from where the contents have to be read. It can be a String, Buffer or URL.
options: It is an object that can be used to specify optional parameters that will affect the method. It has two optional parameters:encoding: It is a string value which specifies which encoding would be used for the filenames given to the callback argument. The default value is ‘utf8’.withFileTypes: It is a boolean value which specifies whether the files would be returned as fs.Dirent objects. The default value is ‘false’.
encoding: It is a string value which specifies which encoding would be used for the filenames given to the callback argument. The default value is ‘utf8’.
withFileTypes: It is a boolean value which specifies whether the files would be returned as fs.Dirent objects. The default value is ‘false’.
Returns: It returns an array of String, Buffer or fs.Dirent objects that contain the files in the directory.
Below examples illustrate the fs.readdirSync() method in Node.js:
Example 1: This example uses fs.readdirSync() method to return the file names or file objects in the directory.
// Node.js program to demonstrate the// fs.readdirSync() method // Import the filesystem moduleconst fs = require('fs'); // Function to get current filenames// in directoryfilenames = fs.readdirSync(__dirname); console.log("\nCurrent directory filenames:");filenames.forEach(file => { console.log(file);}); // Function to get current filenames// in directory with "withFileTypes"// set to "true" fileObjs = fs.readdirSync(__dirname, { withFileTypes: true }); console.log("\nCurrent directory files:");fileObjs.forEach(file => { console.log(file);});
Output:
Current directory filenames:
CONTRUBUTIONS.txt
index.html
index.js
package.json
README.md
Current directory files:
Dirent { name: 'CONTRUBUTIONS.txt', [Symbol(type)]: 1 }
Dirent { name: 'index.html', [Symbol(type)]: 1 }
Dirent { name: 'index.js', [Symbol(type)]: 1 }
Dirent { name: 'package.json', [Symbol(type)]: 1 }
Dirent { name: 'README.md', [Symbol(type)]: 1 }
Example 2: This example uses fs.readdirSync() method to return only the filenames with the “.md” extension.
// Node.js program to demonstrate the// fs.readdirSync() method // Import the filesystem moduleconst fs = require('fs');const path = require('path'); // Function to get current filenames// in directory with specific extensionfiles = fs.readdirSync(__dirname); console.log("\Filenames with the .md extension:");files.forEach(file => { if (path.extname(file) == ".md") console.log(file);})
Output:
Filenames with the .md extension:
README.md
Reference: https://nodejs.org/api/fs.html#fs_fs_readdirsync_path_options
Node.js-fs-module
Picked
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
How to use an ES6 import in Node.js?
Mongoose | findByIdAndUpdate() Function
Express.js res.render() Function
Remove elements from a JavaScript Array
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?
Difference between var, let and const keywords in JavaScript | [
{
"code": null,
"e": 25795,
"s": 25767,
"text": "\n11 Oct, 2021"
},
{
"code": null,
"e": 26072,
"s": 25795,
"text": "The fs.readdirSync() method is used to synchronously read the contents of a given directory. The method returns an array with all the file names or objects in the directory. The options argument can be used to change the format in which the files are returned from the method."
},
{
"code": null,
"e": 26080,
"s": 26072,
"text": "Syntax:"
},
{
"code": null,
"e": 26112,
"s": 26080,
"text": "fs.readdirSync( path, options )"
},
{
"code": null,
"e": 26198,
"s": 26112,
"text": "Parameters: This method accept two parameters as mentioned above and described below:"
},
{
"code": null,
"e": 26315,
"s": 26198,
"text": "path: It holds the path of the directory from where the contents have to be read. It can be a String, Buffer or URL."
},
{
"code": null,
"e": 26743,
"s": 26315,
"text": "options: It is an object that can be used to specify optional parameters that will affect the method. It has two optional parameters:encoding: It is a string value which specifies which encoding would be used for the filenames given to the callback argument. The default value is ‘utf8’.withFileTypes: It is a boolean value which specifies whether the files would be returned as fs.Dirent objects. The default value is ‘false’."
},
{
"code": null,
"e": 26898,
"s": 26743,
"text": "encoding: It is a string value which specifies which encoding would be used for the filenames given to the callback argument. The default value is ‘utf8’."
},
{
"code": null,
"e": 27039,
"s": 26898,
"text": "withFileTypes: It is a boolean value which specifies whether the files would be returned as fs.Dirent objects. The default value is ‘false’."
},
{
"code": null,
"e": 27148,
"s": 27039,
"text": "Returns: It returns an array of String, Buffer or fs.Dirent objects that contain the files in the directory."
},
{
"code": null,
"e": 27214,
"s": 27148,
"text": "Below examples illustrate the fs.readdirSync() method in Node.js:"
},
{
"code": null,
"e": 27326,
"s": 27214,
"text": "Example 1: This example uses fs.readdirSync() method to return the file names or file objects in the directory."
},
{
"code": "// Node.js program to demonstrate the// fs.readdirSync() method // Import the filesystem moduleconst fs = require('fs'); // Function to get current filenames// in directoryfilenames = fs.readdirSync(__dirname); console.log(\"\\nCurrent directory filenames:\");filenames.forEach(file => { console.log(file);}); // Function to get current filenames// in directory with \"withFileTypes\"// set to \"true\" fileObjs = fs.readdirSync(__dirname, { withFileTypes: true }); console.log(\"\\nCurrent directory files:\");fileObjs.forEach(file => { console.log(file);});",
"e": 27885,
"s": 27326,
"text": null
},
{
"code": null,
"e": 27893,
"s": 27885,
"text": "Output:"
},
{
"code": null,
"e": 28260,
"s": 27893,
"text": "Current directory filenames:\nCONTRUBUTIONS.txt\nindex.html\nindex.js\npackage.json\nREADME.md\n\nCurrent directory files:\nDirent { name: 'CONTRUBUTIONS.txt', [Symbol(type)]: 1 }\nDirent { name: 'index.html', [Symbol(type)]: 1 }\nDirent { name: 'index.js', [Symbol(type)]: 1 }\nDirent { name: 'package.json', [Symbol(type)]: 1 }\nDirent { name: 'README.md', [Symbol(type)]: 1 }"
},
{
"code": null,
"e": 28368,
"s": 28260,
"text": "Example 2: This example uses fs.readdirSync() method to return only the filenames with the “.md” extension."
},
{
"code": "// Node.js program to demonstrate the// fs.readdirSync() method // Import the filesystem moduleconst fs = require('fs');const path = require('path'); // Function to get current filenames// in directory with specific extensionfiles = fs.readdirSync(__dirname); console.log(\"\\Filenames with the .md extension:\");files.forEach(file => { if (path.extname(file) == \".md\") console.log(file);})",
"e": 28763,
"s": 28368,
"text": null
},
{
"code": null,
"e": 28771,
"s": 28763,
"text": "Output:"
},
{
"code": null,
"e": 28815,
"s": 28771,
"text": "Filenames with the .md extension:\nREADME.md"
},
{
"code": null,
"e": 28888,
"s": 28815,
"text": "Reference: https://nodejs.org/api/fs.html#fs_fs_readdirsync_path_options"
},
{
"code": null,
"e": 28906,
"s": 28888,
"text": "Node.js-fs-module"
},
{
"code": null,
"e": 28913,
"s": 28906,
"text": "Picked"
},
{
"code": null,
"e": 28921,
"s": 28913,
"text": "Node.js"
},
{
"code": null,
"e": 28938,
"s": 28921,
"text": "Web Technologies"
},
{
"code": null,
"e": 29036,
"s": 28938,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29093,
"s": 29036,
"text": "How to install the previous version of node.js and npm ?"
},
{
"code": null,
"e": 29147,
"s": 29093,
"text": "Difference between promise and async await in Node.js"
},
{
"code": null,
"e": 29184,
"s": 29147,
"text": "How to use an ES6 import in Node.js?"
},
{
"code": null,
"e": 29224,
"s": 29184,
"text": "Mongoose | findByIdAndUpdate() Function"
},
{
"code": null,
"e": 29257,
"s": 29224,
"text": "Express.js res.render() Function"
},
{
"code": null,
"e": 29297,
"s": 29257,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 29342,
"s": 29297,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 29385,
"s": 29342,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 29435,
"s": 29385,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
What is favicon and what is the size of it in HTML? - GeeksforGeeks | 11 Oct, 2019
A favicon is something that all of us see daily while browsing the web, but many of us don’t observe it or pay any need to it. A favicon goes by many other names as well, some of them being the favorite icon (hence the acronym favicon), shortcut icon, tab icon, website icon, or bookmark icon. It is the little image we see on a tab, or while making a bookmark of a page.
The small GeeksforGeeks image shown in the tab is the favicon we are talking about.
Types of favicons: Favicons can have different dimensions like 16×16, 32×32, 48×48, or 64×64 pixels in size. Additionally, they can have 8-bit, 24-bit, or 32-bit colour depth.
How to use a favicon?There are two ways to implement a favicon:
If the favicon is in .ico format:Copy the correctly formatted favicon.ico file to the host directory of the server where the website files are located. Generally this is public_html, but may change depending upon the configuration or hosting provider.The browser automatically detects the favicon and shows it.
Copy the correctly formatted favicon.ico file to the host directory of the server where the website files are located. Generally this is public_html, but may change depending upon the configuration or hosting provider.The browser automatically detects the favicon and shows it.
Copy the correctly formatted favicon.ico file to the host directory of the server where the website files are located. Generally this is public_html, but may change depending upon the configuration or hosting provider.
The browser automatically detects the favicon and shows it.
If the favicon is of some other format (for example jpg, BMP, gif, png):Copy the file to the host directory of the server where the website files are located. Generally this is public_html, but may change depending upon the configuration or hosting provider.Now we need to specify the image we would like to use as a favicon for our website. To do so, we need to add the following line inside the tags below the <taitle> in our website code:<link rel="shortcut icon" type="image/png" href="/favicon.png"/>For formats other than png, replace the “image/png” with the format of the file, and the “favicon.png” with the name and extension of your file.
Copy the file to the host directory of the server where the website files are located. Generally this is public_html, but may change depending upon the configuration or hosting provider.Now we need to specify the image we would like to use as a favicon for our website. To do so, we need to add the following line inside the tags below the <taitle> in our website code:<link rel="shortcut icon" type="image/png" href="/favicon.png"/>For formats other than png, replace the “image/png” with the format of the file, and the “favicon.png” with the name and extension of your file.
Copy the file to the host directory of the server where the website files are located. Generally this is public_html, but may change depending upon the configuration or hosting provider.
Now we need to specify the image we would like to use as a favicon for our website. To do so, we need to add the following line inside the tags below the <taitle> in our website code:<link rel="shortcut icon" type="image/png" href="/favicon.png"/>For formats other than png, replace the “image/png” with the format of the file, and the “favicon.png” with the name and extension of your file.
<link rel="shortcut icon" type="image/png" href="/favicon.png"/>
For formats other than png, replace the “image/png” with the format of the file, and the “favicon.png” with the name and extension of your file.
Example:
<!DOCTYPE html> <html> <head> <meta charset = "utf-8" /> <title> GeeksforGeeks icon </title> <!-- add icon link --> <link rel = "icon" href = "https://media.geeksforgeeks.org/wp-content/cdn-uploads/gfg_200X200.png" type = "image/x-icon"> </head> <body> <h1 style = "color:green;"> GeeksforGeeks </h1> <p> GeeksforGeeks icon added in the title bar </p> </body> </html>
Output:
Favicon sizes:
Note: major browsers are not supported by the sizing property of the favicon.Vulnerabilities: Many web browsers display the favicons on the left side of the address bar, so they are often used as a part of a phishing attack on HTTPS pages. The attacker changes the favicon of the site to the familiar padlock sign (notifying an encrypted connection) to fool the users. To circumvent this, many popular and modern web browsers display the favicon in the tab only and display the security status of the protocol used to access the website beside the URL.
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.
Picked
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
REST API (Introduction)
HTML Cheat Sheet - A Basic Guide to HTML
Design a web page using HTML and CSS
Form validation using jQuery
Angular File Upload
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": 26139,
"s": 26111,
"text": "\n11 Oct, 2019"
},
{
"code": null,
"e": 26511,
"s": 26139,
"text": "A favicon is something that all of us see daily while browsing the web, but many of us don’t observe it or pay any need to it. A favicon goes by many other names as well, some of them being the favorite icon (hence the acronym favicon), shortcut icon, tab icon, website icon, or bookmark icon. It is the little image we see on a tab, or while making a bookmark of a page."
},
{
"code": null,
"e": 26595,
"s": 26511,
"text": "The small GeeksforGeeks image shown in the tab is the favicon we are talking about."
},
{
"code": null,
"e": 26771,
"s": 26595,
"text": "Types of favicons: Favicons can have different dimensions like 16×16, 32×32, 48×48, or 64×64 pixels in size. Additionally, they can have 8-bit, 24-bit, or 32-bit colour depth."
},
{
"code": null,
"e": 26835,
"s": 26771,
"text": "How to use a favicon?There are two ways to implement a favicon:"
},
{
"code": null,
"e": 27146,
"s": 26835,
"text": "If the favicon is in .ico format:Copy the correctly formatted favicon.ico file to the host directory of the server where the website files are located. Generally this is public_html, but may change depending upon the configuration or hosting provider.The browser automatically detects the favicon and shows it."
},
{
"code": null,
"e": 27424,
"s": 27146,
"text": "Copy the correctly formatted favicon.ico file to the host directory of the server where the website files are located. Generally this is public_html, but may change depending upon the configuration or hosting provider.The browser automatically detects the favicon and shows it."
},
{
"code": null,
"e": 27643,
"s": 27424,
"text": "Copy the correctly formatted favicon.ico file to the host directory of the server where the website files are located. Generally this is public_html, but may change depending upon the configuration or hosting provider."
},
{
"code": null,
"e": 27703,
"s": 27643,
"text": "The browser automatically detects the favicon and shows it."
},
{
"code": null,
"e": 28353,
"s": 27703,
"text": "If the favicon is of some other format (for example jpg, BMP, gif, png):Copy the file to the host directory of the server where the website files are located. Generally this is public_html, but may change depending upon the configuration or hosting provider.Now we need to specify the image we would like to use as a favicon for our website. To do so, we need to add the following line inside the tags below the <taitle> in our website code:<link rel=\"shortcut icon\" type=\"image/png\" href=\"/favicon.png\"/>For formats other than png, replace the “image/png” with the format of the file, and the “favicon.png” with the name and extension of your file."
},
{
"code": null,
"e": 28931,
"s": 28353,
"text": "Copy the file to the host directory of the server where the website files are located. Generally this is public_html, but may change depending upon the configuration or hosting provider.Now we need to specify the image we would like to use as a favicon for our website. To do so, we need to add the following line inside the tags below the <taitle> in our website code:<link rel=\"shortcut icon\" type=\"image/png\" href=\"/favicon.png\"/>For formats other than png, replace the “image/png” with the format of the file, and the “favicon.png” with the name and extension of your file."
},
{
"code": null,
"e": 29118,
"s": 28931,
"text": "Copy the file to the host directory of the server where the website files are located. Generally this is public_html, but may change depending upon the configuration or hosting provider."
},
{
"code": null,
"e": 29510,
"s": 29118,
"text": "Now we need to specify the image we would like to use as a favicon for our website. To do so, we need to add the following line inside the tags below the <taitle> in our website code:<link rel=\"shortcut icon\" type=\"image/png\" href=\"/favicon.png\"/>For formats other than png, replace the “image/png” with the format of the file, and the “favicon.png” with the name and extension of your file."
},
{
"code": null,
"e": 29575,
"s": 29510,
"text": "<link rel=\"shortcut icon\" type=\"image/png\" href=\"/favicon.png\"/>"
},
{
"code": null,
"e": 29720,
"s": 29575,
"text": "For formats other than png, replace the “image/png” with the format of the file, and the “favicon.png” with the name and extension of your file."
},
{
"code": null,
"e": 29729,
"s": 29720,
"text": "Example:"
},
{
"code": "<!DOCTYPE html> <html> <head> <meta charset = \"utf-8\" /> <title> GeeksforGeeks icon </title> <!-- add icon link --> <link rel = \"icon\" href = \"https://media.geeksforgeeks.org/wp-content/cdn-uploads/gfg_200X200.png\" type = \"image/x-icon\"> </head> <body> <h1 style = \"color:green;\"> GeeksforGeeks </h1> <p> GeeksforGeeks icon added in the title bar </p> </body> </html> ",
"e": 30294,
"s": 29729,
"text": null
},
{
"code": null,
"e": 30302,
"s": 30294,
"text": "Output:"
},
{
"code": null,
"e": 30317,
"s": 30302,
"text": "Favicon sizes:"
},
{
"code": null,
"e": 30870,
"s": 30317,
"text": "Note: major browsers are not supported by the sizing property of the favicon.Vulnerabilities: Many web browsers display the favicons on the left side of the address bar, so they are often used as a part of a phishing attack on HTTPS pages. The attacker changes the favicon of the site to the familiar padlock sign (notifying an encrypted connection) to fool the users. To circumvent this, many popular and modern web browsers display the favicon in the tab only and display the security status of the protocol used to access the website beside the URL."
},
{
"code": null,
"e": 31007,
"s": 30870,
"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": 31014,
"s": 31007,
"text": "Picked"
},
{
"code": null,
"e": 31019,
"s": 31014,
"text": "HTML"
},
{
"code": null,
"e": 31036,
"s": 31019,
"text": "Web Technologies"
},
{
"code": null,
"e": 31041,
"s": 31036,
"text": "HTML"
},
{
"code": null,
"e": 31139,
"s": 31041,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31163,
"s": 31139,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 31204,
"s": 31163,
"text": "HTML Cheat Sheet - A Basic Guide to HTML"
},
{
"code": null,
"e": 31241,
"s": 31204,
"text": "Design a web page using HTML and CSS"
},
{
"code": null,
"e": 31270,
"s": 31241,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 31290,
"s": 31270,
"text": "Angular File Upload"
},
{
"code": null,
"e": 31330,
"s": 31290,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 31363,
"s": 31330,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 31408,
"s": 31363,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 31451,
"s": 31408,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
C++ Program to Illustrate Trigonometric functions - GeeksforGeeks | 18 May, 2020
The math.h header contains methods for performing basic numeric operations such as the elementary exponential, logarithm, square root, and trigonometric functions. In order to use these functions you need to include header file math.h.Note: All the functions take input in radians and not degrees
Below are the various trigonometric functions that can be used from the math.h header:
sin: This function takes angle (in radians) as an argument and returns its sine value that could be verified using a sine curve.Example:// C++ program to illustrate// sin trigonometric function #include <iostream>#include <math.h>using namespace std; int main(){ double x = 2.3; cout << "Sine value of x = 2.3: " << sin(x) << endl; return 0;}Output:Sine value of x = 2.3: 0.745705
cos: This function takes angle (in radians) as an argument and return its cosine value that could be verified using cosine curve.Example:// C++ program to illustrate// cos trigonometric function #include <iostream>#include <math.h>using namespace std; int main(){ double x = 2.3; cout << "Cosine value of x = 2.3: " << cos(x) << endl; return 0;}Output:Cosine value of x = 2.3: -0.666276
tan: This function takes angle (in radians) as an argument and return its tangent value. This could also be verified using Trigonometry as Tan(x) = Sin(x)/Cos(x).Example:// C++ program to illustrate// tan trigonometric function #include <iostream>#include <math.h>using namespace std; int main(){ double x = 2.3; cout << "Tangent value of x = 2.3: " << tan(x) << endl; return 0;}Output:Tangent value of x = 2.3: -1.11921
acos: This function returns the arc cosine of argument. The argument to acos must be in the range -1 to 1; otherwise, a domain error occurs.Example:// C++ program to illustrate// acos trigonometric function #include <iostream>#include <math.h>using namespace std; int main(){ double x = 1.0; cout << "Arc Cosine value of x = 1.0: " << acos(x) << endl; return 0;}Output:Arc Cosine value of x = 1.0: 0
asin: This function returns the arcsine of argument. The argument to asin must be in the range -1 to 1; otherwise, a domain error occurs.Example:// C++ program to illustrate// asin trigonometric function #include <iostream>#include <math.h>using namespace std; int main(){ double x = 1.0; cout << "Arc Sine value of x = 1.0: " << asin(x) << endl; return 0;}Output:Arc Sine value of x = 1.0: 1.5708
atan: This function returns the arc tangent of arg.Example:// C++ program to illustrate// atan trigonometric function #include <iostream>#include <math.h>using namespace std; int main(){ double x = 1.0; cout << "Arc Tangent value of x = 1.0: " << atan(x) << endl; return 0;}Output:Arc Tangent value of x = 1.0: 0.785398
atan2: This function returns the arc tangent of (a)/(b).Example:// C++ program to illustrate// atan2 trigonometric function #include <iostream>#include <math.h>using namespace std; int main(){ double x = 2.3, y = 1.0; cout << "Arc Tangent 2 value of x = 2.3 and y = 1.0: " << atan2(x, y) << endl; return 0;}Output:Arc Tangent 2 value of x = 2.3 and y = 1.0: 1.16067
cosh: This function returns the hyperbolic cosine of argument provided. The value of the argument provided must be in radians.Example:// C++ program to illustrate// cosh trigonometric function #include <iostream>#include <math.h>using namespace std; int main(){ double x = 57.3; // in degrees cout << "Hyperbolic Cosine of x=57.3: " << cosh(x) << endl; return 0;}Output:Hyperbolic Cosine of x=57.3: 3.83746e+24
tanh: This function returns the hyperbolic tangent of argument provided. The value of argument provided must be in radians.Example:// C++ program to illustrate// tanh trigonometric function #include <iostream>#include <math.h>using namespace std; int main(){ double x = 57.3; // in degrees cout << "Hyperbolic Tangent of x=57.3: " << tanh(x) << endl; return 0;}Output:Hyperbolic Tangent of x=57.3: 1
sin: This function takes angle (in radians) as an argument and returns its sine value that could be verified using a sine curve.Example:// C++ program to illustrate// sin trigonometric function #include <iostream>#include <math.h>using namespace std; int main(){ double x = 2.3; cout << "Sine value of x = 2.3: " << sin(x) << endl; return 0;}Output:Sine value of x = 2.3: 0.745705
Example:
// C++ program to illustrate// sin trigonometric function #include <iostream>#include <math.h>using namespace std; int main(){ double x = 2.3; cout << "Sine value of x = 2.3: " << sin(x) << endl; return 0;}
Sine value of x = 2.3: 0.745705
cos: This function takes angle (in radians) as an argument and return its cosine value that could be verified using cosine curve.Example:// C++ program to illustrate// cos trigonometric function #include <iostream>#include <math.h>using namespace std; int main(){ double x = 2.3; cout << "Cosine value of x = 2.3: " << cos(x) << endl; return 0;}Output:Cosine value of x = 2.3: -0.666276
Example:
// C++ program to illustrate// cos trigonometric function #include <iostream>#include <math.h>using namespace std; int main(){ double x = 2.3; cout << "Cosine value of x = 2.3: " << cos(x) << endl; return 0;}
Cosine value of x = 2.3: -0.666276
tan: This function takes angle (in radians) as an argument and return its tangent value. This could also be verified using Trigonometry as Tan(x) = Sin(x)/Cos(x).Example:// C++ program to illustrate// tan trigonometric function #include <iostream>#include <math.h>using namespace std; int main(){ double x = 2.3; cout << "Tangent value of x = 2.3: " << tan(x) << endl; return 0;}Output:Tangent value of x = 2.3: -1.11921
Example:
// C++ program to illustrate// tan trigonometric function #include <iostream>#include <math.h>using namespace std; int main(){ double x = 2.3; cout << "Tangent value of x = 2.3: " << tan(x) << endl; return 0;}
Tangent value of x = 2.3: -1.11921
acos: This function returns the arc cosine of argument. The argument to acos must be in the range -1 to 1; otherwise, a domain error occurs.Example:// C++ program to illustrate// acos trigonometric function #include <iostream>#include <math.h>using namespace std; int main(){ double x = 1.0; cout << "Arc Cosine value of x = 1.0: " << acos(x) << endl; return 0;}Output:Arc Cosine value of x = 1.0: 0
Example:
// C++ program to illustrate// acos trigonometric function #include <iostream>#include <math.h>using namespace std; int main(){ double x = 1.0; cout << "Arc Cosine value of x = 1.0: " << acos(x) << endl; return 0;}
Arc Cosine value of x = 1.0: 0
asin: This function returns the arcsine of argument. The argument to asin must be in the range -1 to 1; otherwise, a domain error occurs.Example:// C++ program to illustrate// asin trigonometric function #include <iostream>#include <math.h>using namespace std; int main(){ double x = 1.0; cout << "Arc Sine value of x = 1.0: " << asin(x) << endl; return 0;}Output:Arc Sine value of x = 1.0: 1.5708
Example:
// C++ program to illustrate// asin trigonometric function #include <iostream>#include <math.h>using namespace std; int main(){ double x = 1.0; cout << "Arc Sine value of x = 1.0: " << asin(x) << endl; return 0;}
Arc Sine value of x = 1.0: 1.5708
atan: This function returns the arc tangent of arg.Example:// C++ program to illustrate// atan trigonometric function #include <iostream>#include <math.h>using namespace std; int main(){ double x = 1.0; cout << "Arc Tangent value of x = 1.0: " << atan(x) << endl; return 0;}Output:Arc Tangent value of x = 1.0: 0.785398
Example:
// C++ program to illustrate// atan trigonometric function #include <iostream>#include <math.h>using namespace std; int main(){ double x = 1.0; cout << "Arc Tangent value of x = 1.0: " << atan(x) << endl; return 0;}
Arc Tangent value of x = 1.0: 0.785398
atan2: This function returns the arc tangent of (a)/(b).Example:// C++ program to illustrate// atan2 trigonometric function #include <iostream>#include <math.h>using namespace std; int main(){ double x = 2.3, y = 1.0; cout << "Arc Tangent 2 value of x = 2.3 and y = 1.0: " << atan2(x, y) << endl; return 0;}Output:Arc Tangent 2 value of x = 2.3 and y = 1.0: 1.16067
Example:
// C++ program to illustrate// atan2 trigonometric function #include <iostream>#include <math.h>using namespace std; int main(){ double x = 2.3, y = 1.0; cout << "Arc Tangent 2 value of x = 2.3 and y = 1.0: " << atan2(x, y) << endl; return 0;}
Arc Tangent 2 value of x = 2.3 and y = 1.0: 1.16067
cosh: This function returns the hyperbolic cosine of argument provided. The value of the argument provided must be in radians.Example:// C++ program to illustrate// cosh trigonometric function #include <iostream>#include <math.h>using namespace std; int main(){ double x = 57.3; // in degrees cout << "Hyperbolic Cosine of x=57.3: " << cosh(x) << endl; return 0;}Output:Hyperbolic Cosine of x=57.3: 3.83746e+24
Example:
// C++ program to illustrate// cosh trigonometric function #include <iostream>#include <math.h>using namespace std; int main(){ double x = 57.3; // in degrees cout << "Hyperbolic Cosine of x=57.3: " << cosh(x) << endl; return 0;}
Hyperbolic Cosine of x=57.3: 3.83746e+24
tanh: This function returns the hyperbolic tangent of argument provided. The value of argument provided must be in radians.Example:// C++ program to illustrate// tanh trigonometric function #include <iostream>#include <math.h>using namespace std; int main(){ double x = 57.3; // in degrees cout << "Hyperbolic Tangent of x=57.3: " << tanh(x) << endl; return 0;}Output:Hyperbolic Tangent of x=57.3: 1
Example:
// C++ program to illustrate// tanh trigonometric function #include <iostream>#include <math.h>using namespace std; int main(){ double x = 57.3; // in degrees cout << "Hyperbolic Tangent of x=57.3: " << tanh(x) << endl; return 0;}
Hyperbolic Tangent of x=57.3: 1
Below are the trigonometric functions all together:
// C++ program to illustrate some of the// above mentioned trigonometric functions #include <iostream>#include <math.h>using namespace std; int main(){ double x = 2.3; cout << "Sine value of x = 2.3: " << sin(x) << endl; cout << "Cosine value of x = 2.3: " << cos(x) << endl; cout << "Tangent value of x = 2.3: " << tan(x) << endl; x = 1.0; cout << "Arc Cosine value of x = 1.0: " << acos(x) << endl; cout << "Arc Sine value of x = 1.0: " << asin(x) << endl; cout << "Arc Tangent value of x = 1.0: " << atan(x) << endl; x = 57.3; // in degrees cout << "Hyperbolic Cosine of x=57.3: " << cosh(x) << endl; cout << "Hyperbolic tangent of x=57.3: " << tanh(x) << endl; return 0;}
Sine value of x = 2.3: 0.745705
Cosine value of x = 2.3: -0.666276
Tangent value of x = 2.3: -1.11921
Arc Cosine value of x = 1.0: 0
Arc Sine value of x = 1.0: 1.5708
Arc Tangent value of x = 1.0: 0.785398
Hyperbolic Cosine of x=57.3: 3.83746e+24
Hyperbolic tangent of x=57.3: 1
f20170200
CPP-Functions
C++ Programs
Geometric
Geometric
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C++ Program for QuickSort
Shallow Copy and Deep Copy in C++
delete keyword in C++
Passing a function as a parameter in C++
cin in C++
Closest Pair of Points using Divide and Conquer algorithm
How to check if a given point lies inside or outside a polygon?
Program for distance between two points on earth
How to check if two given line segments intersect?
Convex Hull | Set 1 (Jarvis's Algorithm or Wrapping) | [
{
"code": null,
"e": 26075,
"s": 26047,
"text": "\n18 May, 2020"
},
{
"code": null,
"e": 26372,
"s": 26075,
"text": "The math.h header contains methods for performing basic numeric operations such as the elementary exponential, logarithm, square root, and trigonometric functions. In order to use these functions you need to include header file math.h.Note: All the functions take input in radians and not degrees"
},
{
"code": null,
"e": 26459,
"s": 26372,
"text": "Below are the various trigonometric functions that can be used from the math.h header:"
},
{
"code": null,
"e": 30135,
"s": 26459,
"text": "sin: This function takes angle (in radians) as an argument and returns its sine value that could be verified using a sine curve.Example:// C++ program to illustrate// sin trigonometric function #include <iostream>#include <math.h>using namespace std; int main(){ double x = 2.3; cout << \"Sine value of x = 2.3: \" << sin(x) << endl; return 0;}Output:Sine value of x = 2.3: 0.745705\ncos: This function takes angle (in radians) as an argument and return its cosine value that could be verified using cosine curve.Example:// C++ program to illustrate// cos trigonometric function #include <iostream>#include <math.h>using namespace std; int main(){ double x = 2.3; cout << \"Cosine value of x = 2.3: \" << cos(x) << endl; return 0;}Output:Cosine value of x = 2.3: -0.666276\ntan: This function takes angle (in radians) as an argument and return its tangent value. This could also be verified using Trigonometry as Tan(x) = Sin(x)/Cos(x).Example:// C++ program to illustrate// tan trigonometric function #include <iostream>#include <math.h>using namespace std; int main(){ double x = 2.3; cout << \"Tangent value of x = 2.3: \" << tan(x) << endl; return 0;}Output:Tangent value of x = 2.3: -1.11921\nacos: This function returns the arc cosine of argument. The argument to acos must be in the range -1 to 1; otherwise, a domain error occurs.Example:// C++ program to illustrate// acos trigonometric function #include <iostream>#include <math.h>using namespace std; int main(){ double x = 1.0; cout << \"Arc Cosine value of x = 1.0: \" << acos(x) << endl; return 0;}Output:Arc Cosine value of x = 1.0: 0\nasin: This function returns the arcsine of argument. The argument to asin must be in the range -1 to 1; otherwise, a domain error occurs.Example:// C++ program to illustrate// asin trigonometric function #include <iostream>#include <math.h>using namespace std; int main(){ double x = 1.0; cout << \"Arc Sine value of x = 1.0: \" << asin(x) << endl; return 0;}Output:Arc Sine value of x = 1.0: 1.5708\natan: This function returns the arc tangent of arg.Example:// C++ program to illustrate// atan trigonometric function #include <iostream>#include <math.h>using namespace std; int main(){ double x = 1.0; cout << \"Arc Tangent value of x = 1.0: \" << atan(x) << endl; return 0;}Output:Arc Tangent value of x = 1.0: 0.785398\natan2: This function returns the arc tangent of (a)/(b).Example:// C++ program to illustrate// atan2 trigonometric function #include <iostream>#include <math.h>using namespace std; int main(){ double x = 2.3, y = 1.0; cout << \"Arc Tangent 2 value of x = 2.3 and y = 1.0: \" << atan2(x, y) << endl; return 0;}Output:Arc Tangent 2 value of x = 2.3 and y = 1.0: 1.16067\ncosh: This function returns the hyperbolic cosine of argument provided. The value of the argument provided must be in radians.Example:// C++ program to illustrate// cosh trigonometric function #include <iostream>#include <math.h>using namespace std; int main(){ double x = 57.3; // in degrees cout << \"Hyperbolic Cosine of x=57.3: \" << cosh(x) << endl; return 0;}Output:Hyperbolic Cosine of x=57.3: 3.83746e+24\ntanh: This function returns the hyperbolic tangent of argument provided. The value of argument provided must be in radians.Example:// C++ program to illustrate// tanh trigonometric function #include <iostream>#include <math.h>using namespace std; int main(){ double x = 57.3; // in degrees cout << \"Hyperbolic Tangent of x=57.3: \" << tanh(x) << endl; return 0;}Output:Hyperbolic Tangent of x=57.3: 1\n"
},
{
"code": null,
"e": 30538,
"s": 30135,
"text": "sin: This function takes angle (in radians) as an argument and returns its sine value that could be verified using a sine curve.Example:// C++ program to illustrate// sin trigonometric function #include <iostream>#include <math.h>using namespace std; int main(){ double x = 2.3; cout << \"Sine value of x = 2.3: \" << sin(x) << endl; return 0;}Output:Sine value of x = 2.3: 0.745705\n"
},
{
"code": null,
"e": 30547,
"s": 30538,
"text": "Example:"
},
{
"code": "// C++ program to illustrate// sin trigonometric function #include <iostream>#include <math.h>using namespace std; int main(){ double x = 2.3; cout << \"Sine value of x = 2.3: \" << sin(x) << endl; return 0;}",
"e": 30775,
"s": 30547,
"text": null
},
{
"code": null,
"e": 30808,
"s": 30775,
"text": "Sine value of x = 2.3: 0.745705\n"
},
{
"code": null,
"e": 31219,
"s": 30808,
"text": "cos: This function takes angle (in radians) as an argument and return its cosine value that could be verified using cosine curve.Example:// C++ program to illustrate// cos trigonometric function #include <iostream>#include <math.h>using namespace std; int main(){ double x = 2.3; cout << \"Cosine value of x = 2.3: \" << cos(x) << endl; return 0;}Output:Cosine value of x = 2.3: -0.666276\n"
},
{
"code": null,
"e": 31228,
"s": 31219,
"text": "Example:"
},
{
"code": "// C++ program to illustrate// cos trigonometric function #include <iostream>#include <math.h>using namespace std; int main(){ double x = 2.3; cout << \"Cosine value of x = 2.3: \" << cos(x) << endl; return 0;}",
"e": 31460,
"s": 31228,
"text": null
},
{
"code": null,
"e": 31496,
"s": 31460,
"text": "Cosine value of x = 2.3: -0.666276\n"
},
{
"code": null,
"e": 31939,
"s": 31496,
"text": "tan: This function takes angle (in radians) as an argument and return its tangent value. This could also be verified using Trigonometry as Tan(x) = Sin(x)/Cos(x).Example:// C++ program to illustrate// tan trigonometric function #include <iostream>#include <math.h>using namespace std; int main(){ double x = 2.3; cout << \"Tangent value of x = 2.3: \" << tan(x) << endl; return 0;}Output:Tangent value of x = 2.3: -1.11921\n"
},
{
"code": null,
"e": 31948,
"s": 31939,
"text": "Example:"
},
{
"code": "// C++ program to illustrate// tan trigonometric function #include <iostream>#include <math.h>using namespace std; int main(){ double x = 2.3; cout << \"Tangent value of x = 2.3: \" << tan(x) << endl; return 0;}",
"e": 32179,
"s": 31948,
"text": null
},
{
"code": null,
"e": 32215,
"s": 32179,
"text": "Tangent value of x = 2.3: -1.11921\n"
},
{
"code": null,
"e": 32637,
"s": 32215,
"text": "acos: This function returns the arc cosine of argument. The argument to acos must be in the range -1 to 1; otherwise, a domain error occurs.Example:// C++ program to illustrate// acos trigonometric function #include <iostream>#include <math.h>using namespace std; int main(){ double x = 1.0; cout << \"Arc Cosine value of x = 1.0: \" << acos(x) << endl; return 0;}Output:Arc Cosine value of x = 1.0: 0\n"
},
{
"code": null,
"e": 32646,
"s": 32637,
"text": "Example:"
},
{
"code": "// C++ program to illustrate// acos trigonometric function #include <iostream>#include <math.h>using namespace std; int main(){ double x = 1.0; cout << \"Arc Cosine value of x = 1.0: \" << acos(x) << endl; return 0;}",
"e": 32882,
"s": 32646,
"text": null
},
{
"code": null,
"e": 32914,
"s": 32882,
"text": "Arc Cosine value of x = 1.0: 0\n"
},
{
"code": null,
"e": 33334,
"s": 32914,
"text": "asin: This function returns the arcsine of argument. The argument to asin must be in the range -1 to 1; otherwise, a domain error occurs.Example:// C++ program to illustrate// asin trigonometric function #include <iostream>#include <math.h>using namespace std; int main(){ double x = 1.0; cout << \"Arc Sine value of x = 1.0: \" << asin(x) << endl; return 0;}Output:Arc Sine value of x = 1.0: 1.5708\n"
},
{
"code": null,
"e": 33343,
"s": 33334,
"text": "Example:"
},
{
"code": "// C++ program to illustrate// asin trigonometric function #include <iostream>#include <math.h>using namespace std; int main(){ double x = 1.0; cout << \"Arc Sine value of x = 1.0: \" << asin(x) << endl; return 0;}",
"e": 33577,
"s": 33343,
"text": null
},
{
"code": null,
"e": 33612,
"s": 33577,
"text": "Arc Sine value of x = 1.0: 1.5708\n"
},
{
"code": null,
"e": 33954,
"s": 33612,
"text": "atan: This function returns the arc tangent of arg.Example:// C++ program to illustrate// atan trigonometric function #include <iostream>#include <math.h>using namespace std; int main(){ double x = 1.0; cout << \"Arc Tangent value of x = 1.0: \" << atan(x) << endl; return 0;}Output:Arc Tangent value of x = 1.0: 0.785398\n"
},
{
"code": null,
"e": 33963,
"s": 33954,
"text": "Example:"
},
{
"code": "// C++ program to illustrate// atan trigonometric function #include <iostream>#include <math.h>using namespace std; int main(){ double x = 1.0; cout << \"Arc Tangent value of x = 1.0: \" << atan(x) << endl; return 0;}",
"e": 34200,
"s": 33963,
"text": null
},
{
"code": null,
"e": 34240,
"s": 34200,
"text": "Arc Tangent value of x = 1.0: 0.785398\n"
},
{
"code": null,
"e": 34628,
"s": 34240,
"text": "atan2: This function returns the arc tangent of (a)/(b).Example:// C++ program to illustrate// atan2 trigonometric function #include <iostream>#include <math.h>using namespace std; int main(){ double x = 2.3, y = 1.0; cout << \"Arc Tangent 2 value of x = 2.3 and y = 1.0: \" << atan2(x, y) << endl; return 0;}Output:Arc Tangent 2 value of x = 2.3 and y = 1.0: 1.16067\n"
},
{
"code": null,
"e": 34637,
"s": 34628,
"text": "Example:"
},
{
"code": "// C++ program to illustrate// atan2 trigonometric function #include <iostream>#include <math.h>using namespace std; int main(){ double x = 2.3, y = 1.0; cout << \"Arc Tangent 2 value of x = 2.3 and y = 1.0: \" << atan2(x, y) << endl; return 0;}",
"e": 34902,
"s": 34637,
"text": null
},
{
"code": null,
"e": 34955,
"s": 34902,
"text": "Arc Tangent 2 value of x = 2.3 and y = 1.0: 1.16067\n"
},
{
"code": null,
"e": 35388,
"s": 34955,
"text": "cosh: This function returns the hyperbolic cosine of argument provided. The value of the argument provided must be in radians.Example:// C++ program to illustrate// cosh trigonometric function #include <iostream>#include <math.h>using namespace std; int main(){ double x = 57.3; // in degrees cout << \"Hyperbolic Cosine of x=57.3: \" << cosh(x) << endl; return 0;}Output:Hyperbolic Cosine of x=57.3: 3.83746e+24\n"
},
{
"code": null,
"e": 35397,
"s": 35388,
"text": "Example:"
},
{
"code": "// C++ program to illustrate// cosh trigonometric function #include <iostream>#include <math.h>using namespace std; int main(){ double x = 57.3; // in degrees cout << \"Hyperbolic Cosine of x=57.3: \" << cosh(x) << endl; return 0;}",
"e": 35648,
"s": 35397,
"text": null
},
{
"code": null,
"e": 35690,
"s": 35648,
"text": "Hyperbolic Cosine of x=57.3: 3.83746e+24\n"
},
{
"code": null,
"e": 36112,
"s": 35690,
"text": "tanh: This function returns the hyperbolic tangent of argument provided. The value of argument provided must be in radians.Example:// C++ program to illustrate// tanh trigonometric function #include <iostream>#include <math.h>using namespace std; int main(){ double x = 57.3; // in degrees cout << \"Hyperbolic Tangent of x=57.3: \" << tanh(x) << endl; return 0;}Output:Hyperbolic Tangent of x=57.3: 1\n"
},
{
"code": null,
"e": 36121,
"s": 36112,
"text": "Example:"
},
{
"code": "// C++ program to illustrate// tanh trigonometric function #include <iostream>#include <math.h>using namespace std; int main(){ double x = 57.3; // in degrees cout << \"Hyperbolic Tangent of x=57.3: \" << tanh(x) << endl; return 0;}",
"e": 36373,
"s": 36121,
"text": null
},
{
"code": null,
"e": 36406,
"s": 36373,
"text": "Hyperbolic Tangent of x=57.3: 1\n"
},
{
"code": null,
"e": 36458,
"s": 36406,
"text": "Below are the trigonometric functions all together:"
},
{
"code": "// C++ program to illustrate some of the// above mentioned trigonometric functions #include <iostream>#include <math.h>using namespace std; int main(){ double x = 2.3; cout << \"Sine value of x = 2.3: \" << sin(x) << endl; cout << \"Cosine value of x = 2.3: \" << cos(x) << endl; cout << \"Tangent value of x = 2.3: \" << tan(x) << endl; x = 1.0; cout << \"Arc Cosine value of x = 1.0: \" << acos(x) << endl; cout << \"Arc Sine value of x = 1.0: \" << asin(x) << endl; cout << \"Arc Tangent value of x = 1.0: \" << atan(x) << endl; x = 57.3; // in degrees cout << \"Hyperbolic Cosine of x=57.3: \" << cosh(x) << endl; cout << \"Hyperbolic tangent of x=57.3: \" << tanh(x) << endl; return 0;}",
"e": 37242,
"s": 36458,
"text": null
},
{
"code": null,
"e": 37522,
"s": 37242,
"text": "Sine value of x = 2.3: 0.745705\nCosine value of x = 2.3: -0.666276\nTangent value of x = 2.3: -1.11921\nArc Cosine value of x = 1.0: 0\nArc Sine value of x = 1.0: 1.5708\nArc Tangent value of x = 1.0: 0.785398\nHyperbolic Cosine of x=57.3: 3.83746e+24\nHyperbolic tangent of x=57.3: 1\n"
},
{
"code": null,
"e": 37532,
"s": 37522,
"text": "f20170200"
},
{
"code": null,
"e": 37546,
"s": 37532,
"text": "CPP-Functions"
},
{
"code": null,
"e": 37559,
"s": 37546,
"text": "C++ Programs"
},
{
"code": null,
"e": 37569,
"s": 37559,
"text": "Geometric"
},
{
"code": null,
"e": 37579,
"s": 37569,
"text": "Geometric"
},
{
"code": null,
"e": 37677,
"s": 37579,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 37703,
"s": 37677,
"text": "C++ Program for QuickSort"
},
{
"code": null,
"e": 37737,
"s": 37703,
"text": "Shallow Copy and Deep Copy in C++"
},
{
"code": null,
"e": 37759,
"s": 37737,
"text": "delete keyword in C++"
},
{
"code": null,
"e": 37800,
"s": 37759,
"text": "Passing a function as a parameter in C++"
},
{
"code": null,
"e": 37811,
"s": 37800,
"text": "cin in C++"
},
{
"code": null,
"e": 37869,
"s": 37811,
"text": "Closest Pair of Points using Divide and Conquer algorithm"
},
{
"code": null,
"e": 37933,
"s": 37869,
"text": "How to check if a given point lies inside or outside a polygon?"
},
{
"code": null,
"e": 37982,
"s": 37933,
"text": "Program for distance between two points on earth"
},
{
"code": null,
"e": 38033,
"s": 37982,
"text": "How to check if two given line segments intersect?"
}
] |
Angular PrimeNG Badge Component - GeeksforGeeks | 24 Aug, 2021
Angular PrimeNG is an open-source framework with a rich set of native Angular UI components that are used for great styling and this framework is used to make responsive websites with very much ease. In this article, we will know how to use the Badge component in Angular PrimeNG.
Badge component: It is used to represent the text as a status indicator or number as a badge.
Properties:
value: It is used to define the value to display inside the badge. It is of string data type, the default value is null.
severity: It is used to set the severity type of the badge. It is of string data type, the default value is null.
size: It is used to define the size of the badge, valid options are “large” and “xlarge”. It is of string data type, the default value is null.
style: It is used to set the Inline style of the component. It is of object data type, the default value is null.
styleClass: It is used to define the style class of the component. It is of string data type, the default value is null.
Styling:
p-badge: It is a badge element.
p-overlay-badge: It is a wrapper badge and its target.
p-badge-dot: It is a badge element with no value.
p-badge-success: It is a badge element with success severity.
p-badge-info: It is a badge element with info severity.
p-badge-warning: It is a badge element with warning severity.
p-badge-danger: It is a badge element with danger severity.
p-badge-lg: It is a large badge element.
p-badge-xl: It is extra-large badge element.
Creating Angular application & module installation:
Step 1: Create an Angular application using the following command.ng new appname
Step 1: Create an Angular application using the following command.
ng new appname
Step 2: After creating your project folder i.e. appname, move to it using the following command.cd appname
Step 2: After creating your project folder i.e. appname, move to it using the following command.
cd appname
Step 3: Install PrimeNG in your given directory.npm install primeng --save
npm install primeicons --save
Step 3: Install PrimeNG in your given directory.
npm install primeng --save
npm install primeicons --save
Project Structure: It will look like the following.
Example 1: This is the basic example that shows how to use the badge component.
app.component.html
<h2>GeeksforGeeks</h2><h5>PrimeNG Badge Component</h5><div class="badges"> <p-badge [value]="89" styleClass="p-mr-2" severity="success"></p-badge> <p-badge [value]="26" styleClass="p-mr-2" severity="info"></p-badge> <p-badge [value]="65" styleClass="p-mr-2"></p-badge> <p-badge [value]="33" styleClass="p-mr-2" severity="danger"></p-badge> <p-badge [value]="12" styleClass="p-mr-2" severity="warning"></p-badge></div>
app.module.ts
import { NgModule } from "@angular/core";import { BrowserModule } from "@angular/platform-browser";import { BrowserAnimationsModule } from "@angular/platform-browser/animations";import { AppComponent } from "./app.component";import { BadgeModule } from "primeng/badge"; @NgModule({ imports: [BrowserModule, BrowserAnimationsModule, BadgeModule], declarations: [AppComponent], bootstrap: [AppComponent],})export class AppModule {}
app.component.ts
import { Component } from "@angular/core"; @Component({ selector: "my-app", templateUrl: "./app.component.html",})export class AppComponent {}
Output:
Example 2: In this example, we will know how to insert an icon in the message component.
app.component.html
<h2>GeeksforGeeks</h2><h5>PrimeNG Badge Component</h5><i class="pi pi-bars p-mr-3" pBadge style="font-size: 2rem" value="10" styleClass="p-mr-5"></i><i class="pi pi-chevron-left p-mr-3" pBadge severity="danger" style="font-size: 2rem" value="34"></i><i class="pi pi-chevron-right" pBadge severity="success" style="font-size: 2rem" value="47"></i>
app.module.ts
import { NgModule } from "@angular/core";import { BrowserModule } from "@angular/platform-browser";import { BrowserAnimationsModule } from "@angular/platform-browser/animations";import { AppComponent } from "./app.component";import { ButtonModule } from "primeng/button";import { BadgeModule } from "primeng/badge"; @NgModule({ imports: [ BrowserModule, BrowserAnimationsModule, BadgeModule, ButtonModule, BadgeModule, ], declarations: [AppComponent], bootstrap: [AppComponent],})export class AppModule {}
app.compnent.ts
import { Component } from '@angular/core'; @Component({ selector: 'my-app', templateUrl: './app.component.html'})export class AppComponent {}
Output:
Reference: https://primefaces.org/primeng/showcase/#/badge
Angular-PrimeNG
AngularJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Angular PrimeNG Dropdown Component
Angular PrimeNG Calendar Component
Angular 10 (blur) Event
How to make a Bootstrap Modal Popup in Angular 9/8 ?
Angular PrimeNG Messages Component
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills | [
{
"code": null,
"e": 26354,
"s": 26326,
"text": "\n24 Aug, 2021"
},
{
"code": null,
"e": 26635,
"s": 26354,
"text": "Angular PrimeNG is an open-source framework with a rich set of native Angular UI components that are used for great styling and this framework is used to make responsive websites with very much ease. In this article, we will know how to use the Badge component in Angular PrimeNG."
},
{
"code": null,
"e": 26729,
"s": 26635,
"text": "Badge component: It is used to represent the text as a status indicator or number as a badge."
},
{
"code": null,
"e": 26741,
"s": 26729,
"text": "Properties:"
},
{
"code": null,
"e": 26862,
"s": 26741,
"text": "value: It is used to define the value to display inside the badge. It is of string data type, the default value is null."
},
{
"code": null,
"e": 26976,
"s": 26862,
"text": "severity: It is used to set the severity type of the badge. It is of string data type, the default value is null."
},
{
"code": null,
"e": 27120,
"s": 26976,
"text": "size: It is used to define the size of the badge, valid options are “large” and “xlarge”. It is of string data type, the default value is null."
},
{
"code": null,
"e": 27234,
"s": 27120,
"text": "style: It is used to set the Inline style of the component. It is of object data type, the default value is null."
},
{
"code": null,
"e": 27355,
"s": 27234,
"text": "styleClass: It is used to define the style class of the component. It is of string data type, the default value is null."
},
{
"code": null,
"e": 27364,
"s": 27355,
"text": "Styling:"
},
{
"code": null,
"e": 27396,
"s": 27364,
"text": "p-badge: It is a badge element."
},
{
"code": null,
"e": 27451,
"s": 27396,
"text": "p-overlay-badge: It is a wrapper badge and its target."
},
{
"code": null,
"e": 27501,
"s": 27451,
"text": "p-badge-dot: It is a badge element with no value."
},
{
"code": null,
"e": 27563,
"s": 27501,
"text": "p-badge-success: It is a badge element with success severity."
},
{
"code": null,
"e": 27619,
"s": 27563,
"text": "p-badge-info: It is a badge element with info severity."
},
{
"code": null,
"e": 27681,
"s": 27619,
"text": "p-badge-warning: It is a badge element with warning severity."
},
{
"code": null,
"e": 27741,
"s": 27681,
"text": "p-badge-danger: It is a badge element with danger severity."
},
{
"code": null,
"e": 27782,
"s": 27741,
"text": "p-badge-lg: It is a large badge element."
},
{
"code": null,
"e": 27827,
"s": 27782,
"text": "p-badge-xl: It is extra-large badge element."
},
{
"code": null,
"e": 27881,
"s": 27829,
"text": "Creating Angular application & module installation:"
},
{
"code": null,
"e": 27962,
"s": 27881,
"text": "Step 1: Create an Angular application using the following command.ng new appname"
},
{
"code": null,
"e": 28029,
"s": 27962,
"text": "Step 1: Create an Angular application using the following command."
},
{
"code": null,
"e": 28044,
"s": 28029,
"text": "ng new appname"
},
{
"code": null,
"e": 28151,
"s": 28044,
"text": "Step 2: After creating your project folder i.e. appname, move to it using the following command.cd appname"
},
{
"code": null,
"e": 28248,
"s": 28151,
"text": "Step 2: After creating your project folder i.e. appname, move to it using the following command."
},
{
"code": null,
"e": 28259,
"s": 28248,
"text": "cd appname"
},
{
"code": null,
"e": 28364,
"s": 28259,
"text": "Step 3: Install PrimeNG in your given directory.npm install primeng --save\nnpm install primeicons --save"
},
{
"code": null,
"e": 28413,
"s": 28364,
"text": "Step 3: Install PrimeNG in your given directory."
},
{
"code": null,
"e": 28470,
"s": 28413,
"text": "npm install primeng --save\nnpm install primeicons --save"
},
{
"code": null,
"e": 28522,
"s": 28470,
"text": "Project Structure: It will look like the following."
},
{
"code": null,
"e": 28604,
"s": 28524,
"text": "Example 1: This is the basic example that shows how to use the badge component."
},
{
"code": null,
"e": 28623,
"s": 28604,
"text": "app.component.html"
},
{
"code": "<h2>GeeksforGeeks</h2><h5>PrimeNG Badge Component</h5><div class=\"badges\"> <p-badge [value]=\"89\" styleClass=\"p-mr-2\" severity=\"success\"></p-badge> <p-badge [value]=\"26\" styleClass=\"p-mr-2\" severity=\"info\"></p-badge> <p-badge [value]=\"65\" styleClass=\"p-mr-2\"></p-badge> <p-badge [value]=\"33\" styleClass=\"p-mr-2\" severity=\"danger\"></p-badge> <p-badge [value]=\"12\" styleClass=\"p-mr-2\" severity=\"warning\"></p-badge></div>",
"e": 29046,
"s": 28623,
"text": null
},
{
"code": null,
"e": 29060,
"s": 29046,
"text": "app.module.ts"
},
{
"code": "import { NgModule } from \"@angular/core\";import { BrowserModule } from \"@angular/platform-browser\";import { BrowserAnimationsModule } from \"@angular/platform-browser/animations\";import { AppComponent } from \"./app.component\";import { BadgeModule } from \"primeng/badge\"; @NgModule({ imports: [BrowserModule, BrowserAnimationsModule, BadgeModule], declarations: [AppComponent], bootstrap: [AppComponent],})export class AppModule {}",
"e": 29524,
"s": 29060,
"text": null
},
{
"code": null,
"e": 29541,
"s": 29524,
"text": "app.component.ts"
},
{
"code": "import { Component } from \"@angular/core\"; @Component({ selector: \"my-app\", templateUrl: \"./app.component.html\",})export class AppComponent {}",
"e": 29687,
"s": 29541,
"text": null
},
{
"code": null,
"e": 29695,
"s": 29687,
"text": "Output:"
},
{
"code": null,
"e": 29784,
"s": 29695,
"text": "Example 2: In this example, we will know how to insert an icon in the message component."
},
{
"code": null,
"e": 29803,
"s": 29784,
"text": "app.component.html"
},
{
"code": "<h2>GeeksforGeeks</h2><h5>PrimeNG Badge Component</h5><i class=\"pi pi-bars p-mr-3\" pBadge style=\"font-size: 2rem\" value=\"10\" styleClass=\"p-mr-5\"></i><i class=\"pi pi-chevron-left p-mr-3\" pBadge severity=\"danger\" style=\"font-size: 2rem\" value=\"34\"></i><i class=\"pi pi-chevron-right\" pBadge severity=\"success\" style=\"font-size: 2rem\" value=\"47\"></i>",
"e": 30165,
"s": 29803,
"text": null
},
{
"code": null,
"e": 30179,
"s": 30165,
"text": "app.module.ts"
},
{
"code": "import { NgModule } from \"@angular/core\";import { BrowserModule } from \"@angular/platform-browser\";import { BrowserAnimationsModule } from \"@angular/platform-browser/animations\";import { AppComponent } from \"./app.component\";import { ButtonModule } from \"primeng/button\";import { BadgeModule } from \"primeng/badge\"; @NgModule({ imports: [ BrowserModule, BrowserAnimationsModule, BadgeModule, ButtonModule, BadgeModule, ], declarations: [AppComponent], bootstrap: [AppComponent],})export class AppModule {}",
"e": 30709,
"s": 30179,
"text": null
},
{
"code": null,
"e": 30725,
"s": 30709,
"text": "app.compnent.ts"
},
{
"code": "import { Component } from '@angular/core'; @Component({ selector: 'my-app', templateUrl: './app.component.html'})export class AppComponent {}",
"e": 30870,
"s": 30725,
"text": null
},
{
"code": null,
"e": 30878,
"s": 30870,
"text": "Output:"
},
{
"code": null,
"e": 30937,
"s": 30878,
"text": "Reference: https://primefaces.org/primeng/showcase/#/badge"
},
{
"code": null,
"e": 30953,
"s": 30937,
"text": "Angular-PrimeNG"
},
{
"code": null,
"e": 30963,
"s": 30953,
"text": "AngularJS"
},
{
"code": null,
"e": 30980,
"s": 30963,
"text": "Web Technologies"
},
{
"code": null,
"e": 31078,
"s": 30980,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31113,
"s": 31078,
"text": "Angular PrimeNG Dropdown Component"
},
{
"code": null,
"e": 31148,
"s": 31113,
"text": "Angular PrimeNG Calendar Component"
},
{
"code": null,
"e": 31172,
"s": 31148,
"text": "Angular 10 (blur) Event"
},
{
"code": null,
"e": 31225,
"s": 31172,
"text": "How to make a Bootstrap Modal Popup in Angular 9/8 ?"
},
{
"code": null,
"e": 31260,
"s": 31225,
"text": "Angular PrimeNG Messages Component"
},
{
"code": null,
"e": 31300,
"s": 31260,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 31333,
"s": 31300,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 31378,
"s": 31333,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 31421,
"s": 31378,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
Count of numbers in range [L, R] having sum of digits of its square equal to square of sum of digits - GeeksforGeeks | 16 Sep, 2021
Given two integers L and R, the task is to find the count of numbers in range [L, R] such that the sum of digits of its square is equal to the square of sum of its digits,
Example:
Input: L = 22, R = 22Output: 1Explanation: 22 is only valid number in this range as sum of digits of its square = S(22*22) = S(484) = 16 and square of sum of its digits = S(22)*S(22) = 16
Input: L = 1, R = 58Output: 12Explanation: Total valid numbers are {1, 2, 3, 10, 11, 12, 13, 20, 21, 22, 30, 31}
Naive Approach: Run a loop from L to R and for each number calculate the sum of digits and check whether the current number satisfies the given condition or not.
Follow the steps below to solve the problem:
Iterate from L to R and for each number calculate its sum of digits.
Square the current number and find its sum of digits.
If they are equal, increment the answer otherwise continue for the next element.
Time Complexity: O((R-L)*log(R))
Efficient Approach: From example 2, we can observe that all the valid numbers have digits from 0 to 3 only. Therefore there are only 4 choices for each digit present in a number. Use recursion to calculate all the valid numbers till R and check whether it satisfies the given condition or not.
Follow the steps below to solve the problem:
Notice that all valid numbers have digits from [0,3].
Numbers between [4,9] when squared carries a carry over them.S(4)*S(4) = 16 and S(16) = 7, 16 != 7.S(5)*S(5) = 25 and S(25) = 7, 25 != 7.
S(4)*S(4) = 16 and S(16) = 7, 16 != 7.
S(5)*S(5) = 25 and S(25) = 7, 25 != 7.
So, generate all possible numbers up to the R.
For each generated number there are a total of possible 4 choices between [0,3].
Calculate each possible choice and check the condition for each of them.
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 check if the number is validbool check(int num){ // Sum of digits of num int sm = 0; // Squared number int num2 = num * num; while (num) { sm += num % 10; num /= 10; } // Sum of digits of (num * num) int sm2 = 0; while (num2) { sm2 += num2 % 10; num2 /= 10; } return ((sm * sm) == sm2);} // Function to convert a string to an integerint convert(string s){ int val = 0; reverse(s.begin(), s.end()); int cur = 1; for (int i = 0; i < s.size(); i++) { val += (s[i] - '0') * cur; cur *= 10; } return val;} // Function to generate all possible// strings of length lenvoid generate(string s, int len, set<int>& uniq){ // Desired string if (s.size() == len) { // Take only valid numbers if (check(convert(s))) { uniq.insert(convert(s)); } return; } // Recurse for all possible digits for (int i = 0; i <= 3; i++) { generate(s + char(i + '0'), len, uniq); }} // Function to calculate unique numbers// in range [L, R]int totalNumbers(int L, int R){ // Initialize a variable // to store the answer int ans = 0; // Calculate the maximum // possible length int max_len = log10(R) + 1; // Set to store distinct // valid numbers set<int> uniq; for (int i = 1; i <= max_len; i++) { // Generate all possible strings // of length i generate("", i, uniq); } // Iterate the set to get the count // of valid numbers in the range [L,R] for (auto x : uniq) { if (x >= L && x <= R) { ans++; } } return ans;} // Driver Codeint main(){ int L = 22, R = 22; cout << totalNumbers(L, R);}
// Java program for the above approachimport java.util.*; class GFG{ // Function to check if the number is validstatic boolean check(int num){ // Sum of digits of num int sm = 0; // Squared number int num2 = num * num; while (num > 0) { sm += num % 10; num /= 10; } // Sum of digits of (num * num) int sm2 = 0; while (num2>0) { sm2 += num2 % 10; num2 /= 10; } return ((sm * sm) == sm2);} // Function to convert a String to an integerstatic int convert(String s){ int val = 0; s = reverse(s); int cur = 1; for (int i = 0; i < s.length(); i++) { val += (s.charAt(i) - '0') * cur; cur *= 10; } return val;} // Function to generate all possible// Strings of length lenstatic void generate(String s, int len, HashSet<Integer> uniq){ // Desired String if (s.length() == len) { // Take only valid numbers if (check(convert(s))) { uniq.add(convert(s)); } return; } // Recurse for all possible digits for (int i = 0; i <= 3; i++) { generate(s + (char)(i + '0'), len, uniq); }}static String reverse(String input) { char[] a = input.toCharArray(); int l, r = a.length - 1; for (l = 0; l < r; l++, r--) { char temp = a[l]; a[l] = a[r]; a[r] = temp; } return String.valueOf(a);} // Function to calculate unique numbers// in range [L, R]static int totalNumbers(int L, int R){ // Initialize a variable // to store the answer int ans = 0; // Calculate the maximum // possible length int max_len = (int) (Math.log10(R) + 1); // Set to store distinct // valid numbers HashSet<Integer> uniq = new HashSet<Integer>(); for (int i = 1; i <= max_len; i++) { // Generate all possible Strings // of length i generate("", i, uniq); } // Iterate the set to get the count // of valid numbers in the range [L,R] for (int x : uniq) { if (x >= L && x <= R) { ans++; } } return ans;} // Driver Codepublic static void main(String[] args){ int L = 22, R = 22; System.out.print(totalNumbers(L, R));}} // This code is contributed by Princi Singh
# python 3 program for the above approach from math import log10# Function to check if the number is validdef check(num): # Sum of digits of num sm = 0 # Squared number num2 = num * num while (num): sm += num % 10 num //= 10 # Sum of digits of (num * num) sm2 = 0 while (num2): sm2 += num2 % 10 num2 //= 10 return ((sm * sm) == sm2) # Function to convert a string to an integerdef convert(s): val = 0 s = s[::-1] cur = 1 for i in range(len(s)): val += (ord(s[i]) - ord('0')) * cur cur *= 10 return val # Function to generate all possible# strings of length lendef generate(s, len1, uniq): # Desired string if (len(s) == len1): # Take only valid numbers if(check(convert(s))): uniq.add(convert(s)) return # Recurse for all possible digits for i in range(4): generate(s + chr(i + ord('0')), len1, uniq) # Function to calculate unique numbers# in range [L, R]def totalNumbers(L, R): # Initialize a variable # to store the answer ans = 0 # Calculate the maximum # possible length max_len = int(log10(R)) + 1 # Set to store distinct # valid numbers uniq = set() for i in range(1,max_len+1,1): # Generate all possible strings # of length i generate("", i, uniq) # Iterate the set to get the count # of valid numbers in the range [L,R] for x in uniq: if (x >= L and x <= R): ans += 1 return ans # Driver Codeif __name__ == '__main__': L = 22 R = 22 print(totalNumbers(L, R)) # This code is contributed by ipg2016107.
// C# program for the above approachusing System;using System.Collections.Generic; class GFG{ // Function to check if the number is validstatic bool check(int num){ // Sum of digits of num int sm = 0; // Squared number int num2 = num * num; while (num>0) { sm += num % 10; num /= 10; } // Sum of digits of (num * num) int sm2 = 0; while (num2>0) { sm2 += num2 % 10; num2 /= 10; } return ((sm * sm) == sm2);} // Function to convert a string to an integerstatic int convert(string s){ int val = 0; char[] charArray = s.ToCharArray(); Array.Reverse( charArray ); s = new string( charArray ); int cur = 1; for (int i = 0; i < s.Length; i++) { val += ((int)s[i] - (int)'0') * cur; cur *= 10; } return val;} // Function to generate all possible// strings of length lenstatic void generate(string s, int len, HashSet<int> uniq){ // Desired string if (s.Length == len) { // Take only valid numbers if (check(convert(s))) { uniq.Add(convert(s)); } return; } // Recurse for all possible digits for (int i = 0; i <= 3; i++) { generate(s + Convert.ToChar(i + (int)'0'), len, uniq); }} // Function to calculate unique numbers// in range [L, R]static int totalNumbers(int L, int R){ // Initialize a variable // to store the answer int ans = 0; // Calculate the maximum // possible length int max_len = (int)Math.Log10(R) + 1; // Set to store distinct // valid numbers HashSet<int> uniq = new HashSet<int>(); for (int i = 1; i <= max_len; i++) { // Generate all possible strings // of length i generate("", i, uniq); } // Iterate the set to get the count // of valid numbers in the range [L,R] foreach (int x in uniq) { if (x >= L && x <= R) { ans++; } } return ans;} // Driver Codepublic static void Main(){ int L = 22, R = 22; Console.Write(totalNumbers(L, R));} } // This code is contributed by SURENDRA_GANGWAR.
<script>// Javascript program for the above approach // Function to check if the number is validfunction check(num){ // Sum of digits of num let sm = 0; // Squared number let num2 = num * num; while (num) { sm += num % 10; num = Math.floor(num / 10); } // Sum of digits of (num * num) let sm2 = 0; while (num2) { sm2 += num2 % 10; num2 = Math.floor(num2 / 10); } return sm * sm == sm2;} // Function to convert a string to an integerfunction convert(s) { let val = 0; s = s.split("").reverse().join(""); let cur = 1; for (let i = 0; i < s.length; i++) { val += (s[i].charCodeAt(0) - "0".charCodeAt(0)) * cur; cur *= 10; } return val;} // Function to generate all possible// strings of length lenfunction generate(s, len, uniq) { // Desired string if (s.length == len) { // Take only valid numbers if (check(convert(s))) { uniq.add(convert(s)); } return; } // Recurse for all possible digits for (let i = 0; i <= 3; i++) { generate(s + String.fromCharCode(i + "0".charCodeAt(0)), len, uniq); }} // Function to calculate unique numbers// in range [L, R]function totalNumbers(L, R) { // Initialize a variable // to store the answer let ans = 0; // Calculate the maximum // possible length let max_len = Math.log10(R) + 1; // Set to store distinct // valid numbers let uniq = new Set(); for (let i = 1; i <= max_len; i++) { // Generate all possible strings // of length i generate("", i, uniq); } // Iterate the set to get the count // of valid numbers in the range [L,R] for (let x of uniq) { if (x >= L && x <= R) { ans++; } } return ans;} // Driver Codelet L = 22, R = 22;document.write(totalNumbers(L, R)); // This code is contributed by _saurabh_jaiswal.</script>
Output:
1
Time Complexity: (, since there are 4 choices for each of the digits till the length of R i.e log10(R) + 1, therefore the time complexity would be exponential.
Auxiliary Space: (Recursive Stack space)
ipg2016107
SURENDRA_GANGWAR
singghakshay
princi singh
_saurabh_jaiswal
simmytarika5
surinderdawra388
number-theory
Greedy
Mathematical
Strings
number-theory
Strings
Greedy
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Optimal Page Replacement Algorithm
Program for Best Fit algorithm in Memory Management
Program for First Fit algorithm in Memory Management
Bin Packing Problem (Minimize number of used Bins)
Max Flow Problem Introduction
Program for Fibonacci numbers
C++ Data Types
Set in C++ Standard Template Library (STL)
Merge two sorted arrays
Modulo Operator (%) in C/C++ with Examples | [
{
"code": null,
"e": 26563,
"s": 26535,
"text": "\n16 Sep, 2021"
},
{
"code": null,
"e": 26736,
"s": 26563,
"text": "Given two integers L and R, the task is to find the count of numbers in range [L, R] such that the sum of digits of its square is equal to the square of sum of its digits, "
},
{
"code": null,
"e": 26745,
"s": 26736,
"text": "Example:"
},
{
"code": null,
"e": 26933,
"s": 26745,
"text": "Input: L = 22, R = 22Output: 1Explanation: 22 is only valid number in this range as sum of digits of its square = S(22*22) = S(484) = 16 and square of sum of its digits = S(22)*S(22) = 16"
},
{
"code": null,
"e": 27046,
"s": 26933,
"text": "Input: L = 1, R = 58Output: 12Explanation: Total valid numbers are {1, 2, 3, 10, 11, 12, 13, 20, 21, 22, 30, 31}"
},
{
"code": null,
"e": 27210,
"s": 27046,
"text": "Naive Approach: Run a loop from L to R and for each number calculate the sum of digits and check whether the current number satisfies the given condition or not. "
},
{
"code": null,
"e": 27256,
"s": 27210,
"text": "Follow the steps below to solve the problem:"
},
{
"code": null,
"e": 27325,
"s": 27256,
"text": "Iterate from L to R and for each number calculate its sum of digits."
},
{
"code": null,
"e": 27379,
"s": 27325,
"text": "Square the current number and find its sum of digits."
},
{
"code": null,
"e": 27460,
"s": 27379,
"text": "If they are equal, increment the answer otherwise continue for the next element."
},
{
"code": null,
"e": 27493,
"s": 27460,
"text": "Time Complexity: O((R-L)*log(R))"
},
{
"code": null,
"e": 27787,
"s": 27493,
"text": "Efficient Approach: From example 2, we can observe that all the valid numbers have digits from 0 to 3 only. Therefore there are only 4 choices for each digit present in a number. Use recursion to calculate all the valid numbers till R and check whether it satisfies the given condition or not."
},
{
"code": null,
"e": 27832,
"s": 27787,
"text": "Follow the steps below to solve the problem:"
},
{
"code": null,
"e": 27886,
"s": 27832,
"text": "Notice that all valid numbers have digits from [0,3]."
},
{
"code": null,
"e": 28024,
"s": 27886,
"text": "Numbers between [4,9] when squared carries a carry over them.S(4)*S(4) = 16 and S(16) = 7, 16 != 7.S(5)*S(5) = 25 and S(25) = 7, 25 != 7."
},
{
"code": null,
"e": 28063,
"s": 28024,
"text": "S(4)*S(4) = 16 and S(16) = 7, 16 != 7."
},
{
"code": null,
"e": 28102,
"s": 28063,
"text": "S(5)*S(5) = 25 and S(25) = 7, 25 != 7."
},
{
"code": null,
"e": 28149,
"s": 28102,
"text": "So, generate all possible numbers up to the R."
},
{
"code": null,
"e": 28230,
"s": 28149,
"text": "For each generated number there are a total of possible 4 choices between [0,3]."
},
{
"code": null,
"e": 28303,
"s": 28230,
"text": "Calculate each possible choice and check the condition for each of them."
},
{
"code": null,
"e": 28355,
"s": 28303,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 28359,
"s": 28355,
"text": "C++"
},
{
"code": null,
"e": 28364,
"s": 28359,
"text": "Java"
},
{
"code": null,
"e": 28372,
"s": 28364,
"text": "Python3"
},
{
"code": null,
"e": 28375,
"s": 28372,
"text": "C#"
},
{
"code": null,
"e": 28386,
"s": 28375,
"text": "Javascript"
},
{
"code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to check if the number is validbool check(int num){ // Sum of digits of num int sm = 0; // Squared number int num2 = num * num; while (num) { sm += num % 10; num /= 10; } // Sum of digits of (num * num) int sm2 = 0; while (num2) { sm2 += num2 % 10; num2 /= 10; } return ((sm * sm) == sm2);} // Function to convert a string to an integerint convert(string s){ int val = 0; reverse(s.begin(), s.end()); int cur = 1; for (int i = 0; i < s.size(); i++) { val += (s[i] - '0') * cur; cur *= 10; } return val;} // Function to generate all possible// strings of length lenvoid generate(string s, int len, set<int>& uniq){ // Desired string if (s.size() == len) { // Take only valid numbers if (check(convert(s))) { uniq.insert(convert(s)); } return; } // Recurse for all possible digits for (int i = 0; i <= 3; i++) { generate(s + char(i + '0'), len, uniq); }} // Function to calculate unique numbers// in range [L, R]int totalNumbers(int L, int R){ // Initialize a variable // to store the answer int ans = 0; // Calculate the maximum // possible length int max_len = log10(R) + 1; // Set to store distinct // valid numbers set<int> uniq; for (int i = 1; i <= max_len; i++) { // Generate all possible strings // of length i generate(\"\", i, uniq); } // Iterate the set to get the count // of valid numbers in the range [L,R] for (auto x : uniq) { if (x >= L && x <= R) { ans++; } } return ans;} // Driver Codeint main(){ int L = 22, R = 22; cout << totalNumbers(L, R);}",
"e": 30208,
"s": 28386,
"text": null
},
{
"code": "// Java program for the above approachimport java.util.*; class GFG{ // Function to check if the number is validstatic boolean check(int num){ // Sum of digits of num int sm = 0; // Squared number int num2 = num * num; while (num > 0) { sm += num % 10; num /= 10; } // Sum of digits of (num * num) int sm2 = 0; while (num2>0) { sm2 += num2 % 10; num2 /= 10; } return ((sm * sm) == sm2);} // Function to convert a String to an integerstatic int convert(String s){ int val = 0; s = reverse(s); int cur = 1; for (int i = 0; i < s.length(); i++) { val += (s.charAt(i) - '0') * cur; cur *= 10; } return val;} // Function to generate all possible// Strings of length lenstatic void generate(String s, int len, HashSet<Integer> uniq){ // Desired String if (s.length() == len) { // Take only valid numbers if (check(convert(s))) { uniq.add(convert(s)); } return; } // Recurse for all possible digits for (int i = 0; i <= 3; i++) { generate(s + (char)(i + '0'), len, uniq); }}static String reverse(String input) { char[] a = input.toCharArray(); int l, r = a.length - 1; for (l = 0; l < r; l++, r--) { char temp = a[l]; a[l] = a[r]; a[r] = temp; } return String.valueOf(a);} // Function to calculate unique numbers// in range [L, R]static int totalNumbers(int L, int R){ // Initialize a variable // to store the answer int ans = 0; // Calculate the maximum // possible length int max_len = (int) (Math.log10(R) + 1); // Set to store distinct // valid numbers HashSet<Integer> uniq = new HashSet<Integer>(); for (int i = 1; i <= max_len; i++) { // Generate all possible Strings // of length i generate(\"\", i, uniq); } // Iterate the set to get the count // of valid numbers in the range [L,R] for (int x : uniq) { if (x >= L && x <= R) { ans++; } } return ans;} // Driver Codepublic static void main(String[] args){ int L = 22, R = 22; System.out.print(totalNumbers(L, R));}} // This code is contributed by Princi Singh",
"e": 32428,
"s": 30208,
"text": null
},
{
"code": "# python 3 program for the above approach from math import log10# Function to check if the number is validdef check(num): # Sum of digits of num sm = 0 # Squared number num2 = num * num while (num): sm += num % 10 num //= 10 # Sum of digits of (num * num) sm2 = 0 while (num2): sm2 += num2 % 10 num2 //= 10 return ((sm * sm) == sm2) # Function to convert a string to an integerdef convert(s): val = 0 s = s[::-1] cur = 1 for i in range(len(s)): val += (ord(s[i]) - ord('0')) * cur cur *= 10 return val # Function to generate all possible# strings of length lendef generate(s, len1, uniq): # Desired string if (len(s) == len1): # Take only valid numbers if(check(convert(s))): uniq.add(convert(s)) return # Recurse for all possible digits for i in range(4): generate(s + chr(i + ord('0')), len1, uniq) # Function to calculate unique numbers# in range [L, R]def totalNumbers(L, R): # Initialize a variable # to store the answer ans = 0 # Calculate the maximum # possible length max_len = int(log10(R)) + 1 # Set to store distinct # valid numbers uniq = set() for i in range(1,max_len+1,1): # Generate all possible strings # of length i generate(\"\", i, uniq) # Iterate the set to get the count # of valid numbers in the range [L,R] for x in uniq: if (x >= L and x <= R): ans += 1 return ans # Driver Codeif __name__ == '__main__': L = 22 R = 22 print(totalNumbers(L, R)) # This code is contributed by ipg2016107.",
"e": 34080,
"s": 32428,
"text": null
},
{
"code": "// C# program for the above approachusing System;using System.Collections.Generic; class GFG{ // Function to check if the number is validstatic bool check(int num){ // Sum of digits of num int sm = 0; // Squared number int num2 = num * num; while (num>0) { sm += num % 10; num /= 10; } // Sum of digits of (num * num) int sm2 = 0; while (num2>0) { sm2 += num2 % 10; num2 /= 10; } return ((sm * sm) == sm2);} // Function to convert a string to an integerstatic int convert(string s){ int val = 0; char[] charArray = s.ToCharArray(); Array.Reverse( charArray ); s = new string( charArray ); int cur = 1; for (int i = 0; i < s.Length; i++) { val += ((int)s[i] - (int)'0') * cur; cur *= 10; } return val;} // Function to generate all possible// strings of length lenstatic void generate(string s, int len, HashSet<int> uniq){ // Desired string if (s.Length == len) { // Take only valid numbers if (check(convert(s))) { uniq.Add(convert(s)); } return; } // Recurse for all possible digits for (int i = 0; i <= 3; i++) { generate(s + Convert.ToChar(i + (int)'0'), len, uniq); }} // Function to calculate unique numbers// in range [L, R]static int totalNumbers(int L, int R){ // Initialize a variable // to store the answer int ans = 0; // Calculate the maximum // possible length int max_len = (int)Math.Log10(R) + 1; // Set to store distinct // valid numbers HashSet<int> uniq = new HashSet<int>(); for (int i = 1; i <= max_len; i++) { // Generate all possible strings // of length i generate(\"\", i, uniq); } // Iterate the set to get the count // of valid numbers in the range [L,R] foreach (int x in uniq) { if (x >= L && x <= R) { ans++; } } return ans;} // Driver Codepublic static void Main(){ int L = 22, R = 22; Console.Write(totalNumbers(L, R));} } // This code is contributed by SURENDRA_GANGWAR.",
"e": 36153,
"s": 34080,
"text": null
},
{
"code": "<script>// Javascript program for the above approach // Function to check if the number is validfunction check(num){ // Sum of digits of num let sm = 0; // Squared number let num2 = num * num; while (num) { sm += num % 10; num = Math.floor(num / 10); } // Sum of digits of (num * num) let sm2 = 0; while (num2) { sm2 += num2 % 10; num2 = Math.floor(num2 / 10); } return sm * sm == sm2;} // Function to convert a string to an integerfunction convert(s) { let val = 0; s = s.split(\"\").reverse().join(\"\"); let cur = 1; for (let i = 0; i < s.length; i++) { val += (s[i].charCodeAt(0) - \"0\".charCodeAt(0)) * cur; cur *= 10; } return val;} // Function to generate all possible// strings of length lenfunction generate(s, len, uniq) { // Desired string if (s.length == len) { // Take only valid numbers if (check(convert(s))) { uniq.add(convert(s)); } return; } // Recurse for all possible digits for (let i = 0; i <= 3; i++) { generate(s + String.fromCharCode(i + \"0\".charCodeAt(0)), len, uniq); }} // Function to calculate unique numbers// in range [L, R]function totalNumbers(L, R) { // Initialize a variable // to store the answer let ans = 0; // Calculate the maximum // possible length let max_len = Math.log10(R) + 1; // Set to store distinct // valid numbers let uniq = new Set(); for (let i = 1; i <= max_len; i++) { // Generate all possible strings // of length i generate(\"\", i, uniq); } // Iterate the set to get the count // of valid numbers in the range [L,R] for (let x of uniq) { if (x >= L && x <= R) { ans++; } } return ans;} // Driver Codelet L = 22, R = 22;document.write(totalNumbers(L, R)); // This code is contributed by _saurabh_jaiswal.</script>",
"e": 37925,
"s": 36153,
"text": null
},
{
"code": null,
"e": 37933,
"s": 37925,
"text": "Output:"
},
{
"code": null,
"e": 37935,
"s": 37933,
"text": "1"
},
{
"code": null,
"e": 38095,
"s": 37935,
"text": "Time Complexity: (, since there are 4 choices for each of the digits till the length of R i.e log10(R) + 1, therefore the time complexity would be exponential."
},
{
"code": null,
"e": 38138,
"s": 38095,
"text": "Auxiliary Space: (Recursive Stack space)"
},
{
"code": null,
"e": 38151,
"s": 38140,
"text": "ipg2016107"
},
{
"code": null,
"e": 38168,
"s": 38151,
"text": "SURENDRA_GANGWAR"
},
{
"code": null,
"e": 38181,
"s": 38168,
"text": "singghakshay"
},
{
"code": null,
"e": 38194,
"s": 38181,
"text": "princi singh"
},
{
"code": null,
"e": 38211,
"s": 38194,
"text": "_saurabh_jaiswal"
},
{
"code": null,
"e": 38224,
"s": 38211,
"text": "simmytarika5"
},
{
"code": null,
"e": 38241,
"s": 38224,
"text": "surinderdawra388"
},
{
"code": null,
"e": 38255,
"s": 38241,
"text": "number-theory"
},
{
"code": null,
"e": 38262,
"s": 38255,
"text": "Greedy"
},
{
"code": null,
"e": 38275,
"s": 38262,
"text": "Mathematical"
},
{
"code": null,
"e": 38283,
"s": 38275,
"text": "Strings"
},
{
"code": null,
"e": 38297,
"s": 38283,
"text": "number-theory"
},
{
"code": null,
"e": 38305,
"s": 38297,
"text": "Strings"
},
{
"code": null,
"e": 38312,
"s": 38305,
"text": "Greedy"
},
{
"code": null,
"e": 38325,
"s": 38312,
"text": "Mathematical"
},
{
"code": null,
"e": 38423,
"s": 38325,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 38458,
"s": 38423,
"text": "Optimal Page Replacement Algorithm"
},
{
"code": null,
"e": 38510,
"s": 38458,
"text": "Program for Best Fit algorithm in Memory Management"
},
{
"code": null,
"e": 38563,
"s": 38510,
"text": "Program for First Fit algorithm in Memory Management"
},
{
"code": null,
"e": 38614,
"s": 38563,
"text": "Bin Packing Problem (Minimize number of used Bins)"
},
{
"code": null,
"e": 38644,
"s": 38614,
"text": "Max Flow Problem Introduction"
},
{
"code": null,
"e": 38674,
"s": 38644,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 38689,
"s": 38674,
"text": "C++ Data Types"
},
{
"code": null,
"e": 38732,
"s": 38689,
"text": "Set in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 38756,
"s": 38732,
"text": "Merge two sorted arrays"
}
] |
GATE | GATE-CS-2015 (Set 2) | Question 55 - GeeksforGeeks | 28 Jun, 2021
Suppose you are provided with the following function declaration in the C programming language.
int partition (int a[], int n);
The function treats the first element of a[] as a pivot, and rearranges the array so that all elements less than or equal to the pivot is in the left part of the array, and all elements greater than the pivot is in the right part. In addition, it moves the pivot so that the pivot is the last element of the left part. The return value is the number of elements in the left part. The following partially given function in the C programming language is used to find the kth smallest element in an array a[ ] of size n using the partition function. We assume k ≤ n
int kth_smallest (int a[], int n, int k){ int left_end = partition (a, n); if (left_end+1==k) { return a [left_end]; } if (left_end+1 > k) { return kth_smallest (____________________); } else { return kth_smallest (____________________); }}
The missing argument lists are respectively(A) (a, left_end, k) and (a+left_end+1, n–left_end–1, k–left_end–1)(B) (a, left_end, k) and (a, n–left_end–1, k–left_end–1)(C) (a, left_end+1, N–left_end–1, K–left_end–1) and(a, left_end, k)(D) (a, n–left_end–1, k–left_end–1) and (a, left_end, k)Answer: (A)Explanation: See method 4 of https://www.geeksforgeeks.org/kth-smallestlargest-element-unsorted-array/Quiz of this Question
GATE-CS-2015 (Set 2)
GATE-GATE-CS-2015 (Set 2)
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | Gate IT 2007 | Question 25
GATE | GATE-CS-2001 | Question 39
GATE | GATE-CS-2000 | Question 41
GATE | GATE-CS-2005 | Question 6
GATE | GATE MOCK 2017 | Question 21
GATE | GATE-CS-2006 | Question 47
GATE | GATE MOCK 2017 | Question 24
GATE | Gate IT 2008 | Question 43
GATE | GATE-CS-2009 | Question 38
GATE | GATE-CS-2003 | Question 90 | [
{
"code": null,
"e": 25649,
"s": 25621,
"text": "\n28 Jun, 2021"
},
{
"code": null,
"e": 25745,
"s": 25649,
"text": "Suppose you are provided with the following function declaration in the C programming language."
},
{
"code": null,
"e": 25781,
"s": 25745,
"text": " int partition (int a[], int n); "
},
{
"code": null,
"e": 26344,
"s": 25781,
"text": "The function treats the first element of a[] as a pivot, and rearranges the array so that all elements less than or equal to the pivot is in the left part of the array, and all elements greater than the pivot is in the right part. In addition, it moves the pivot so that the pivot is the last element of the left part. The return value is the number of elements in the left part. The following partially given function in the C programming language is used to find the kth smallest element in an array a[ ] of size n using the partition function. We assume k ≤ n"
},
{
"code": "int kth_smallest (int a[], int n, int k){ int left_end = partition (a, n); if (left_end+1==k) { return a [left_end]; } if (left_end+1 > k) { return kth_smallest (____________________); } else { return kth_smallest (____________________); }}",
"e": 26622,
"s": 26344,
"text": null
},
{
"code": null,
"e": 27046,
"s": 26622,
"text": "The missing argument lists are respectively(A) (a, left_end, k) and (a+left_end+1, n–left_end–1, k–left_end–1)(B) (a, left_end, k) and (a, n–left_end–1, k–left_end–1)(C) (a, left_end+1, N–left_end–1, K–left_end–1) and(a, left_end, k)(D) (a, n–left_end–1, k–left_end–1) and (a, left_end, k)Answer: (A)Explanation: See method 4 of https://www.geeksforgeeks.org/kth-smallestlargest-element-unsorted-array/Quiz of this Question"
},
{
"code": null,
"e": 27067,
"s": 27046,
"text": "GATE-CS-2015 (Set 2)"
},
{
"code": null,
"e": 27093,
"s": 27067,
"text": "GATE-GATE-CS-2015 (Set 2)"
},
{
"code": null,
"e": 27098,
"s": 27093,
"text": "GATE"
},
{
"code": null,
"e": 27196,
"s": 27098,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27230,
"s": 27196,
"text": "GATE | Gate IT 2007 | Question 25"
},
{
"code": null,
"e": 27264,
"s": 27230,
"text": "GATE | GATE-CS-2001 | Question 39"
},
{
"code": null,
"e": 27298,
"s": 27264,
"text": "GATE | GATE-CS-2000 | Question 41"
},
{
"code": null,
"e": 27331,
"s": 27298,
"text": "GATE | GATE-CS-2005 | Question 6"
},
{
"code": null,
"e": 27367,
"s": 27331,
"text": "GATE | GATE MOCK 2017 | Question 21"
},
{
"code": null,
"e": 27401,
"s": 27367,
"text": "GATE | GATE-CS-2006 | Question 47"
},
{
"code": null,
"e": 27437,
"s": 27401,
"text": "GATE | GATE MOCK 2017 | Question 24"
},
{
"code": null,
"e": 27471,
"s": 27437,
"text": "GATE | Gate IT 2008 | Question 43"
},
{
"code": null,
"e": 27505,
"s": 27471,
"text": "GATE | GATE-CS-2009 | Question 38"
}
] |
JavaScript Quiz | Set-2 - GeeksforGeeks | 11 Oct, 2021
Prerequisite: Basic understanding of JavaScript concepts1. What is the syntax for creating a function in JavaScript named as Geekfunc? A) function = Geekfunc() B) function Geekfunc() C) function := Geekfunc() D) function : Geekfunc()Ans: Option B Explanation: In JavaScript, function is defined as ‘function x()’. 2. How is the function called in JavaScript?A) call Geekfunc(); B) call function GeekFunc(); C) Geekfunc(); D) function Geekfunc();Ans: C Explanation: In JavaScript, functions are called directly like x().
3. How to write an ‘if’ statement for executing some code. If “i” is NOT equal to 5?A) if(i<>5) B) if i<>5 C) if(i!=5) D) if i!=5Ans: C Explanation: JavaScript does not accept <> operator as not equal to.
4. What is the correct syntax for adding comments in JavaScript?A) <!–This is a comment–> B) //This is a comment C) –This is a comment D) **This is a comment**Ans: B Explanation: Correct Syntax for comments in JavaScript is //comment. 5. How to insert a multi-line comment in JavaScript?A) <!–This is comment line 1 This is comment line 2–> B) //This is comment line 1 This is comment line 2// C) /*This is comment line 1 This is comment line 2*/ D) **This is comment line 1 This is comment line 2**Ans: C Explanation: Correct Syntax for multi-line comments in JavaScript is /*comment*/.
6. What is the JavaScript syntax for printing values in Console?A) print(5) B) console.log(5); C) console.print(5); D) print.console(5);Ans: Option B Explanation: The action which is built into the console object is the .log() method. Whenever we write console.log() in the JavaScript code, what we put inside the parentheses will get printed, or logged, to the console.
7. How to initialize an array in JavaScript?A) var Geeks= “Geek1”, “Geek2”, “Geek3” B) var Geeks=(1:Geek1, 2:Geek2, 3:Geek3) C) var Geeks=(1=Geek1, 2=Geek2, 3=Geek3) D) var Geeks=[“Geek1”, “Geek2”, “Geek3”]Ans: D Explanation: In JavaScript, functions are called directly like x(). 8. What will be the output of the following code?
javascript
<script>document.write(typeof(24.49));</script>
A) float B) number C) integer D) doubleAns: B Explanation: There are seven fundamental data types in JavaScript. They are number, string, boolean, null, undefined, symbol, and object. We do not have data types like float, integer, and double in JavaScript. 9. What will be the command to print the number of characters in the string “GeeksforGeeks”? A) document.write(“GeeksforGeeks”.len); B) document.write(sizeof(“GeeksforGeeks”)); C) document.write(“GeeksforGeeks”.length); D) document.write(lenof(“GeeksforGeeks”));Ans: C Explanation: The .length property of JavaScript is used to evaluate the number of characters in any string. 10. What is the method in JavaScript used to remove the whitespace at the beginning and end of any string?A) strip() B) trim() C) stripped() D) trimmed()Ans: B Explanation: The trim() method in JavaScript is used to remove the whitespaces at the beginning and end of the string. 11. Which of the following is the pop() method does?
A) Display the first element B) Decrements length by 1C) Increments length by 1D) None of the mentioned
Answer: Option BExplanation: The pop() method in JavaScript is used the remove the last element of the array. Hence the answer is option B.
12.Which of the following option is correct if reverse() and join() are used together?
A) Reverses and stores B) Reverses and concatenates C) Only ReversesD) None of the mentioned
Answer: Option AExplanation: The reverse() and join() method in javascript is used to reverse the arrays and later on the store the result.
13. Which of the following option is correct when a function with no return type is called?
A) Dynamic functionB) ProceduresC) Static functionD) Method
Answer: Option BExplanation: The correct definition of the procedure is the function with no return type Hence the correct option is Procedures.
14 . Which of the following scope is used by the JavaScript?
A) SegmentalB) LexicalC) LiteralD) Sequential
Answer: LexicalExplanation: In the lexical scope the function are executed between the given variable scope
15.Which of the following in reduce operation called?
A) filter and foldB) inject and foldC) finger and foldD) fold
Answer: Option BExplanation: The reduced operation in javaScript is the callback function that is injected and fold, Hence the option is to inject and bold.
BhagyaRana
nishantsinghgfg
anikakapoor
JavaScript
Quizzes
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 ?
SDE SHEET - A Complete Guide for SDE Preparation
time.h localtime() function in C with Examples
Length of race track based on the final distance between participants
TCS DIGITAL PUZZLE | Lateral Thinking
Find index after traversing a permutation Array of 1 to N by K steps | [
{
"code": null,
"e": 26236,
"s": 26208,
"text": "\n11 Oct, 2021"
},
{
"code": null,
"e": 26757,
"s": 26236,
"text": "Prerequisite: Basic understanding of JavaScript concepts1. What is the syntax for creating a function in JavaScript named as Geekfunc? A) function = Geekfunc() B) function Geekfunc() C) function := Geekfunc() D) function : Geekfunc()Ans: Option B Explanation: In JavaScript, function is defined as ‘function x()’. 2. How is the function called in JavaScript?A) call Geekfunc(); B) call function GeekFunc(); C) Geekfunc(); D) function Geekfunc();Ans: C Explanation: In JavaScript, functions are called directly like x(). "
},
{
"code": null,
"e": 26963,
"s": 26757,
"text": "3. How to write an ‘if’ statement for executing some code. If “i” is NOT equal to 5?A) if(i<>5) B) if i<>5 C) if(i!=5) D) if i!=5Ans: C Explanation: JavaScript does not accept <> operator as not equal to. "
},
{
"code": null,
"e": 27553,
"s": 26963,
"text": "4. What is the correct syntax for adding comments in JavaScript?A) <!–This is a comment–> B) //This is a comment C) –This is a comment D) **This is a comment**Ans: B Explanation: Correct Syntax for comments in JavaScript is //comment. 5. How to insert a multi-line comment in JavaScript?A) <!–This is comment line 1 This is comment line 2–> B) //This is comment line 1 This is comment line 2// C) /*This is comment line 1 This is comment line 2*/ D) **This is comment line 1 This is comment line 2**Ans: C Explanation: Correct Syntax for multi-line comments in JavaScript is /*comment*/. "
},
{
"code": null,
"e": 27925,
"s": 27553,
"text": "6. What is the JavaScript syntax for printing values in Console?A) print(5) B) console.log(5); C) console.print(5); D) print.console(5);Ans: Option B Explanation: The action which is built into the console object is the .log() method. Whenever we write console.log() in the JavaScript code, what we put inside the parentheses will get printed, or logged, to the console. "
},
{
"code": null,
"e": 28256,
"s": 27925,
"text": "7. How to initialize an array in JavaScript?A) var Geeks= “Geek1”, “Geek2”, “Geek3” B) var Geeks=(1:Geek1, 2:Geek2, 3:Geek3) C) var Geeks=(1=Geek1, 2=Geek2, 3=Geek3) D) var Geeks=[“Geek1”, “Geek2”, “Geek3”]Ans: D Explanation: In JavaScript, functions are called directly like x(). 8. What will be the output of the following code?"
},
{
"code": null,
"e": 28267,
"s": 28256,
"text": "javascript"
},
{
"code": "<script>document.write(typeof(24.49));</script>",
"e": 28315,
"s": 28267,
"text": null
},
{
"code": null,
"e": 29283,
"s": 28315,
"text": "A) float B) number C) integer D) doubleAns: B Explanation: There are seven fundamental data types in JavaScript. They are number, string, boolean, null, undefined, symbol, and object. We do not have data types like float, integer, and double in JavaScript. 9. What will be the command to print the number of characters in the string “GeeksforGeeks”? A) document.write(“GeeksforGeeks”.len); B) document.write(sizeof(“GeeksforGeeks”)); C) document.write(“GeeksforGeeks”.length); D) document.write(lenof(“GeeksforGeeks”));Ans: C Explanation: The .length property of JavaScript is used to evaluate the number of characters in any string. 10. What is the method in JavaScript used to remove the whitespace at the beginning and end of any string?A) strip() B) trim() C) stripped() D) trimmed()Ans: B Explanation: The trim() method in JavaScript is used to remove the whitespaces at the beginning and end of the string. 11. Which of the following is the pop() method does?"
},
{
"code": null,
"e": 29387,
"s": 29283,
"text": "A) Display the first element B) Decrements length by 1C) Increments length by 1D) None of the mentioned"
},
{
"code": null,
"e": 29527,
"s": 29387,
"text": "Answer: Option BExplanation: The pop() method in JavaScript is used the remove the last element of the array. Hence the answer is option B."
},
{
"code": null,
"e": 29614,
"s": 29527,
"text": "12.Which of the following option is correct if reverse() and join() are used together?"
},
{
"code": null,
"e": 29708,
"s": 29614,
"text": "A) Reverses and stores B) Reverses and concatenates C) Only ReversesD) None of the mentioned"
},
{
"code": null,
"e": 29848,
"s": 29708,
"text": "Answer: Option AExplanation: The reverse() and join() method in javascript is used to reverse the arrays and later on the store the result."
},
{
"code": null,
"e": 29940,
"s": 29848,
"text": "13. Which of the following option is correct when a function with no return type is called?"
},
{
"code": null,
"e": 30000,
"s": 29940,
"text": "A) Dynamic functionB) ProceduresC) Static functionD) Method"
},
{
"code": null,
"e": 30145,
"s": 30000,
"text": "Answer: Option BExplanation: The correct definition of the procedure is the function with no return type Hence the correct option is Procedures."
},
{
"code": null,
"e": 30206,
"s": 30145,
"text": "14 . Which of the following scope is used by the JavaScript?"
},
{
"code": null,
"e": 30252,
"s": 30206,
"text": "A) SegmentalB) LexicalC) LiteralD) Sequential"
},
{
"code": null,
"e": 30360,
"s": 30252,
"text": "Answer: LexicalExplanation: In the lexical scope the function are executed between the given variable scope"
},
{
"code": null,
"e": 30414,
"s": 30360,
"text": "15.Which of the following in reduce operation called?"
},
{
"code": null,
"e": 30477,
"s": 30414,
"text": "A) filter and foldB) inject and foldC) finger and foldD) fold "
},
{
"code": null,
"e": 30634,
"s": 30477,
"text": "Answer: Option BExplanation: The reduced operation in javaScript is the callback function that is injected and fold, Hence the option is to inject and bold."
},
{
"code": null,
"e": 30645,
"s": 30634,
"text": "BhagyaRana"
},
{
"code": null,
"e": 30661,
"s": 30645,
"text": "nishantsinghgfg"
},
{
"code": null,
"e": 30673,
"s": 30661,
"text": "anikakapoor"
},
{
"code": null,
"e": 30684,
"s": 30673,
"text": "JavaScript"
},
{
"code": null,
"e": 30692,
"s": 30684,
"text": "Quizzes"
},
{
"code": null,
"e": 30790,
"s": 30692,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30830,
"s": 30790,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 30875,
"s": 30830,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 30936,
"s": 30875,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 31008,
"s": 30936,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 31060,
"s": 31008,
"text": "How to append HTML code to a div using JavaScript ?"
},
{
"code": null,
"e": 31109,
"s": 31060,
"text": "SDE SHEET - A Complete Guide for SDE Preparation"
},
{
"code": null,
"e": 31156,
"s": 31109,
"text": "time.h localtime() function in C with Examples"
},
{
"code": null,
"e": 31226,
"s": 31156,
"text": "Length of race track based on the final distance between participants"
},
{
"code": null,
"e": 31264,
"s": 31226,
"text": "TCS DIGITAL PUZZLE | Lateral Thinking"
}
] |
Underscore.js _.functions() Function - GeeksforGeeks | 25 Nov, 2021
The _.functions() function is used to return the sorted list of all methods that present in an object.
Syntax:
_.functions(object)
Parameters: This function accepts single parameter as mentioned above and described below:
object: It contains the object element that holds the elements [key, value] pair.
Return Value: It returns the sorted list of all methods that present in an object.
Example:
<!DOCTYPE html><html> <head> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js"> </script></head> <body> <script type="text/javascript"> console.log(_.functions(_)); </script></body> </html>
Output:
JavaScript - Underscore.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
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
How to calculate the number of days between two dates in javascript?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS? | [
{
"code": null,
"e": 34847,
"s": 34819,
"text": "\n25 Nov, 2021"
},
{
"code": null,
"e": 34950,
"s": 34847,
"text": "The _.functions() function is used to return the sorted list of all methods that present in an object."
},
{
"code": null,
"e": 34958,
"s": 34950,
"text": "Syntax:"
},
{
"code": null,
"e": 34978,
"s": 34958,
"text": "_.functions(object)"
},
{
"code": null,
"e": 35069,
"s": 34978,
"text": "Parameters: This function accepts single parameter as mentioned above and described below:"
},
{
"code": null,
"e": 35151,
"s": 35069,
"text": "object: It contains the object element that holds the elements [key, value] pair."
},
{
"code": null,
"e": 35234,
"s": 35151,
"text": "Return Value: It returns the sorted list of all methods that present in an object."
},
{
"code": null,
"e": 35243,
"s": 35234,
"text": "Example:"
},
{
"code": "<!DOCTYPE html><html> <head> <script type=\"text/javascript\" src=\"https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js\"> </script></head> <body> <script type=\"text/javascript\"> console.log(_.functions(_)); </script></body> </html>",
"e": 35521,
"s": 35243,
"text": null
},
{
"code": null,
"e": 35529,
"s": 35521,
"text": "Output:"
},
{
"code": null,
"e": 35556,
"s": 35529,
"text": "JavaScript - Underscore.js"
},
{
"code": null,
"e": 35567,
"s": 35556,
"text": "JavaScript"
},
{
"code": null,
"e": 35584,
"s": 35567,
"text": "Web Technologies"
},
{
"code": null,
"e": 35682,
"s": 35584,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 35722,
"s": 35682,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 35767,
"s": 35722,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 35828,
"s": 35767,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 35900,
"s": 35828,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 35969,
"s": 35900,
"text": "How to calculate the number of days between two dates in javascript?"
},
{
"code": null,
"e": 36009,
"s": 35969,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 36042,
"s": 36009,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 36087,
"s": 36042,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 36130,
"s": 36087,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
Ternary representation of Cantor set - GeeksforGeeks | 01 Feb, 2022
Given three integers A, B and L, the task is to print the ternary cantor set from range [A, B] upto L levels. Ternary Cantor Set: A ternary Cantor set is a set built by removing the middle part of a line segment when divided into 3 parts and repeating this process with the remaining shorter segments. Below is an illustration of a cantor set.
An illustration of a Ternary Cantor Set
Examples:
Input: A = 0, B = 1, L = 2 Output: Level 0: [0.000000] — [1.000000] Level 1: [0.000000] — [0.333333] [0.666667] — [1.000000] Level 2: [0.000000] — [0.111111] [0.222222] — [0.333333] [0.666667] — [0.777778] [0.888889] — [1.000000] Explanation: For the given range [0, 1], in level 1, it is divided into three parts ([0, 0.33], [0.33, 0.67], [0.67, 1]). From the three parts, the middle part is ignored. This process is continued for every part in the subsequent executions.Input: A = 0, B = 9, L = 3 Output: Level_0: [0.000000] — [9.000000] Level_1: [0.000000] — [3.000000] [6.000000] — [9.000000] Level_2: [0.000000] — [1.000000] [2.000000] — [3.000000] [6.000000] — [7.000000] [8.000000] — [9.000000] Level_3: [0.000000] — [0.333333] [0.666667] — [1.000000] [2.000000] — [2.333333] [2.666667] — [3.000000] [6.000000] — [6.333333] [6.666667] — [7.000000] [8.000000] — [8.333333] [8.666667] — [9.000000]
Approach:
Create a linked list data structure for each node of the Set, having the start value, end value and a pointer to the next node.Initialize the list with the start and end value given as the input.For the next level: Create a new node where the difference between the start and end values is of the initial, i.e. start value is less than the initial end value.Further, modify the original node, such that the end value is more of the initial start value.Place the pointer to the new node after the original one accordingly
Create a linked list data structure for each node of the Set, having the start value, end value and a pointer to the next node.
Initialize the list with the start and end value given as the input.
For the next level: Create a new node where the difference between the start and end values is of the initial, i.e. start value is less than the initial end value.Further, modify the original node, such that the end value is more of the initial start value.Place the pointer to the new node after the original one accordingly
Create a new node where the difference between the start and end values is of the initial, i.e. start value is less than the initial end value.
Further, modify the original node, such that the end value is more of the initial start value.
Place the pointer to the new node after the original one accordingly
Below is the implementation of the above approach:
C++
C
Java
C#
Javascript
// C++ implementation to find the cantor set// for n levels and// for a given start_num and end_num#include <bits/stdc++.h>using namespace std; // The Linked List Structure for the Cantor Settypedef struct cantor { double start, end; struct cantor* next;} Cantor; // Function to initialize the Cantor Set ListCantor* startList(Cantor* head, double start_num, double end_num){ if (head == NULL) { head = new Cantor; head->start = start_num; head->end = end_num; head->next = NULL; } return head;} // Function to propagate the list// by adding new nodes for the next levelsCantor* propagate(Cantor* head){ Cantor* temp = head; if (temp != NULL) { Cantor* newNode = new Cantor; double diff = (((temp->end) - (temp->start)) / 3); // Modifying the start and end values // for the next level newNode->end = temp->end; temp->end = ((temp->start) + diff); newNode->start = (newNode->end) - diff; // Changing the pointers // to the next node newNode->next = temp->next; temp->next = newNode; // Recursively call the function // to generate the Cantor Set // for the entire level propagate(temp->next->next); } return head;} // Function to print a level of the Setvoid print(Cantor* temp){ while (temp != NULL) { printf("[%lf] -- [%lf]\t", temp->start, temp->end); temp = temp->next; } cout << endl;} // Function to build and display// the Cantor Set for each levelvoid buildCantorSet(int A, int B, int L){ Cantor* head = NULL; head = startList(head, A, B); for (int i = 0; i < L; i++) { cout <<"Level_"<< i<<" : "; print(head); propagate(head); } cout <<"Level_"<< L<<" : "; print(head);} // Driver codeint main(){ int A = 0; int B = 9; int L = 2; buildCantorSet(A, B, L); return 0;} // This code is contributed by shivanisingh
// C implementation to find the cantor set// for n levels and// for a given start_num and end_num #include <stdio.h>#include <stdlib.h>#include <string.h> // The Linked List Structure for the Cantor Settypedef struct cantor { double start, end; struct cantor* next;} Cantor; // Function to initialize the Cantor Set ListCantor* startList(Cantor* head, double start_num, double end_num){ if (head == NULL) { head = (Cantor*)malloc(sizeof(Cantor)); head->start = start_num; head->end = end_num; head->next = NULL; } return head;} // Function to propagate the list// by adding new nodes for the next levelsCantor* propagate(Cantor* head){ Cantor* temp = head; if (temp != NULL) { Cantor* newNode = (Cantor*)malloc(sizeof(Cantor)); double diff = (((temp->end) - (temp->start)) / 3); // Modifying the start and end values // for the next level newNode->end = temp->end; temp->end = ((temp->start) + diff); newNode->start = (newNode->end) - diff; // Changing the pointers // to the next node newNode->next = temp->next; temp->next = newNode; // Recursively call the function // to generate the Cantor Set // for the entire level propagate(temp->next->next); } return head;} // Function to print a level of the Setvoid print(Cantor* temp){ while (temp != NULL) { printf("[%lf] -- [%lf]\t", temp->start, temp->end); temp = temp->next; } printf("\n");} // Function to build and display// the Cantor Set for each levelvoid buildCantorSet(int A, int B, int L){ Cantor* head = NULL; head = startList(head, A, B); for (int i = 0; i < L; i++) { printf("Level_%d : ", i); print(head); propagate(head); } printf("Level_%d : ", L); print(head);} // Driver codeint main(){ int A = 0; int B = 9; int L = 2; buildCantorSet(A, B, L); return 0;}
// Java implementation to find the cantor set// for n levels and// for a given start_num and end_num class GFG{ // The Linked List Structure for the Cantor Set static class Cantor { double start, end; Cantor next; }; static Cantor Cantor; // Function to initialize the Cantor Set List static Cantor startList(Cantor head, double start_num, double end_num) { if (head == null) { head = new Cantor(); head.start = start_num; head.end = end_num; head.next = null; } return head; } // Function to propagate the list // by adding new nodes for the next levels static Cantor propagate(Cantor head) { Cantor temp = head; if (temp != null) { Cantor newNode = new Cantor(); double diff = (((temp.end) - (temp.start)) / 3); // Modifying the start and end values // for the next level newNode.end = temp.end; temp.end = ((temp.start) + diff); newNode.start = (newNode.end) - diff; // Changing the pointers // to the next node newNode.next = temp.next; temp.next = newNode; // Recursively call the function // to generate the Cantor Set // for the entire level propagate(temp.next.next); } return head; } // Function to print a level of the Set static void print(Cantor temp) { while (temp != null) { System.out.printf("[%f] -- [%f]", temp.start, temp.end); temp = temp.next; } System.out.printf("\n"); } // Function to build and display // the Cantor Set for each level static void buildCantorSet(int A, int B, int L) { Cantor head = null; head = startList(head, A, B); for (int i = 0; i < L; i++) { System.out.printf("Level_%d : ", i); print(head); propagate(head); } System.out.printf("Level_%d : ", L); print(head); } // Driver code public static void main(String[] args) { int A = 0; int B = 9; int L = 2; buildCantorSet(A, B, L); }} // This code is contributed by Rajput-Ji
// C# implementation to find the cantor set// for n levels and// for a given start_num and end_numusing System; class GFG{ // The Linked List Structure for the Cantor Set class Cantor { public double start, end; public Cantor next; }; static Cantor cantor; // Function to initialize the Cantor Set List static Cantor startList(Cantor head, double start_num, double end_num) { if (head == null) { head = new Cantor(); head.start = start_num; head.end = end_num; head.next = null; } return head; } // Function to propagate the list // by adding new nodes for the next levels static Cantor propagate(Cantor head) { Cantor temp = head; if (temp != null) { Cantor newNode = new Cantor(); double diff = (((temp.end) - (temp.start)) / 3); // Modifying the start and end values // for the next level newNode.end = temp.end; temp.end = ((temp.start) + diff); newNode.start = (newNode.end) - diff; // Changing the pointers // to the next node newNode.next = temp.next; temp.next = newNode; // Recursively call the function // to generate the Cantor Set // for the entire level propagate(temp.next.next); } return head; } // Function to print a level of the Set static void print(Cantor temp) { while (temp != null) { Console.Write("[{0:F6}] -- [{1:F6}]", temp.start, temp.end); temp = temp.next; } Console.Write("\n"); } // Function to build and display // the Cantor Set for each level static void buildCantorSet(int A, int B, int L) { Cantor head = null; head = startList(head, A, B); for (int i = 0; i < L; i++) { Console.Write("Level_{0} : ", i); print(head); propagate(head); } Console.Write("Level_{0} : ", L); print(head); } // Driver code public static void Main(String[] args) { int A = 0; int B = 9; int L = 2; buildCantorSet(A, B, L); }} // This code is contributed by Rajput-Ji
<script> // Javascript implementation to find the cantor set// for n levels and// for a given start_num and end_num// The Linked List Structure for the Cantor Setclass Cantor{ constructor() { this.start = 0; this.end = 0; this.next = null; }}; var cantor = null; // Function to initialize the Cantor Set Listfunction startList(head, start_num, end_num){ if (head == null) { head = new Cantor(); head.start = start_num; head.end = end_num; head.next = null; } return head;}// Function to propagate the list// by adding new nodes for the next levelsfunction propagate(head){ var temp = head; if (temp != null) { var newNode = new Cantor(); var diff = (((temp.end) - (temp.start)) / 3); // Modifying the start and end values // for the next level newNode.end = temp.end; temp.end = ((temp.start) + diff); newNode.start = (newNode.end) - diff; // Changing the pointers // to the next node newNode.next = temp.next; temp.next = newNode; // Recursively call the function // to generate the Cantor Set // for the entire level propagate(temp.next.next); } return head;}// Function to print a level of the Setfunction print(temp){ while (temp != null) { document.write("["+temp.start.toFixed(6)+"] -- ["+ temp.end.toFixed(6)+"] "); temp = temp.next; } document.write("<br>");}// Function to build and display// the Cantor Set for each levelfunction buildCantorSet(A, B, L){ var head = null; head = startList(head, A, B); for (var i = 0; i < L; i++) { document.write("Level_"+ i +" : "); print(head); propagate(head); } document.write("Level_"+ L +" : "); print(head);}// Driver codevar A = 0;var B = 9;var L = 2;buildCantorSet(A, B, L); </script>
References: Cantor Set Wikipedia Related Article: N-th term of George Cantor set of rational numbers
Rajput-Ji
shivanisinghss2110
itsok
saurabh1990aror
Technical Scripter 2019
Linked List
Mathematical
Technical Scripter
Linked List
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Circular Linked List | Set 2 (Traversal)
Swap nodes in a linked list without swapping data
Program to implement Singly Linked List in C++ using class
Circular Singly Linked List | Insertion
Given a linked list which is sorted, how will you insert in sorted way
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": 26179,
"s": 26151,
"text": "\n01 Feb, 2022"
},
{
"code": null,
"e": 26525,
"s": 26179,
"text": "Given three integers A, B and L, the task is to print the ternary cantor set from range [A, B] upto L levels. Ternary Cantor Set: A ternary Cantor set is a set built by removing the middle part of a line segment when divided into 3 parts and repeating this process with the remaining shorter segments. Below is an illustration of a cantor set. "
},
{
"code": null,
"e": 26565,
"s": 26525,
"text": "An illustration of a Ternary Cantor Set"
},
{
"code": null,
"e": 26577,
"s": 26565,
"text": "Examples: "
},
{
"code": null,
"e": 27482,
"s": 26577,
"text": "Input: A = 0, B = 1, L = 2 Output: Level 0: [0.000000] — [1.000000] Level 1: [0.000000] — [0.333333] [0.666667] — [1.000000] Level 2: [0.000000] — [0.111111] [0.222222] — [0.333333] [0.666667] — [0.777778] [0.888889] — [1.000000] Explanation: For the given range [0, 1], in level 1, it is divided into three parts ([0, 0.33], [0.33, 0.67], [0.67, 1]). From the three parts, the middle part is ignored. This process is continued for every part in the subsequent executions.Input: A = 0, B = 9, L = 3 Output: Level_0: [0.000000] — [9.000000] Level_1: [0.000000] — [3.000000] [6.000000] — [9.000000] Level_2: [0.000000] — [1.000000] [2.000000] — [3.000000] [6.000000] — [7.000000] [8.000000] — [9.000000] Level_3: [0.000000] — [0.333333] [0.666667] — [1.000000] [2.000000] — [2.333333] [2.666667] — [3.000000] [6.000000] — [6.333333] [6.666667] — [7.000000] [8.000000] — [8.333333] [8.666667] — [9.000000] "
},
{
"code": null,
"e": 27495,
"s": 27484,
"text": "Approach: "
},
{
"code": null,
"e": 28016,
"s": 27495,
"text": "Create a linked list data structure for each node of the Set, having the start value, end value and a pointer to the next node.Initialize the list with the start and end value given as the input.For the next level: Create a new node where the difference between the start and end values is of the initial, i.e. start value is less than the initial end value.Further, modify the original node, such that the end value is more of the initial start value.Place the pointer to the new node after the original one accordingly"
},
{
"code": null,
"e": 28144,
"s": 28016,
"text": "Create a linked list data structure for each node of the Set, having the start value, end value and a pointer to the next node."
},
{
"code": null,
"e": 28213,
"s": 28144,
"text": "Initialize the list with the start and end value given as the input."
},
{
"code": null,
"e": 28539,
"s": 28213,
"text": "For the next level: Create a new node where the difference between the start and end values is of the initial, i.e. start value is less than the initial end value.Further, modify the original node, such that the end value is more of the initial start value.Place the pointer to the new node after the original one accordingly"
},
{
"code": null,
"e": 28683,
"s": 28539,
"text": "Create a new node where the difference between the start and end values is of the initial, i.e. start value is less than the initial end value."
},
{
"code": null,
"e": 28778,
"s": 28683,
"text": "Further, modify the original node, such that the end value is more of the initial start value."
},
{
"code": null,
"e": 28847,
"s": 28778,
"text": "Place the pointer to the new node after the original one accordingly"
},
{
"code": null,
"e": 28900,
"s": 28847,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 28904,
"s": 28900,
"text": "C++"
},
{
"code": null,
"e": 28906,
"s": 28904,
"text": "C"
},
{
"code": null,
"e": 28911,
"s": 28906,
"text": "Java"
},
{
"code": null,
"e": 28914,
"s": 28911,
"text": "C#"
},
{
"code": null,
"e": 28925,
"s": 28914,
"text": "Javascript"
},
{
"code": "// C++ implementation to find the cantor set// for n levels and// for a given start_num and end_num#include <bits/stdc++.h>using namespace std; // The Linked List Structure for the Cantor Settypedef struct cantor { double start, end; struct cantor* next;} Cantor; // Function to initialize the Cantor Set ListCantor* startList(Cantor* head, double start_num, double end_num){ if (head == NULL) { head = new Cantor; head->start = start_num; head->end = end_num; head->next = NULL; } return head;} // Function to propagate the list// by adding new nodes for the next levelsCantor* propagate(Cantor* head){ Cantor* temp = head; if (temp != NULL) { Cantor* newNode = new Cantor; double diff = (((temp->end) - (temp->start)) / 3); // Modifying the start and end values // for the next level newNode->end = temp->end; temp->end = ((temp->start) + diff); newNode->start = (newNode->end) - diff; // Changing the pointers // to the next node newNode->next = temp->next; temp->next = newNode; // Recursively call the function // to generate the Cantor Set // for the entire level propagate(temp->next->next); } return head;} // Function to print a level of the Setvoid print(Cantor* temp){ while (temp != NULL) { printf(\"[%lf] -- [%lf]\\t\", temp->start, temp->end); temp = temp->next; } cout << endl;} // Function to build and display// the Cantor Set for each levelvoid buildCantorSet(int A, int B, int L){ Cantor* head = NULL; head = startList(head, A, B); for (int i = 0; i < L; i++) { cout <<\"Level_\"<< i<<\" : \"; print(head); propagate(head); } cout <<\"Level_\"<< L<<\" : \"; print(head);} // Driver codeint main(){ int A = 0; int B = 9; int L = 2; buildCantorSet(A, B, L); return 0;} // This code is contributed by shivanisingh",
"e": 30950,
"s": 28925,
"text": null
},
{
"code": "// C implementation to find the cantor set// for n levels and// for a given start_num and end_num #include <stdio.h>#include <stdlib.h>#include <string.h> // The Linked List Structure for the Cantor Settypedef struct cantor { double start, end; struct cantor* next;} Cantor; // Function to initialize the Cantor Set ListCantor* startList(Cantor* head, double start_num, double end_num){ if (head == NULL) { head = (Cantor*)malloc(sizeof(Cantor)); head->start = start_num; head->end = end_num; head->next = NULL; } return head;} // Function to propagate the list// by adding new nodes for the next levelsCantor* propagate(Cantor* head){ Cantor* temp = head; if (temp != NULL) { Cantor* newNode = (Cantor*)malloc(sizeof(Cantor)); double diff = (((temp->end) - (temp->start)) / 3); // Modifying the start and end values // for the next level newNode->end = temp->end; temp->end = ((temp->start) + diff); newNode->start = (newNode->end) - diff; // Changing the pointers // to the next node newNode->next = temp->next; temp->next = newNode; // Recursively call the function // to generate the Cantor Set // for the entire level propagate(temp->next->next); } return head;} // Function to print a level of the Setvoid print(Cantor* temp){ while (temp != NULL) { printf(\"[%lf] -- [%lf]\\t\", temp->start, temp->end); temp = temp->next; } printf(\"\\n\");} // Function to build and display// the Cantor Set for each levelvoid buildCantorSet(int A, int B, int L){ Cantor* head = NULL; head = startList(head, A, B); for (int i = 0; i < L; i++) { printf(\"Level_%d : \", i); print(head); propagate(head); } printf(\"Level_%d : \", L); print(head);} // Driver codeint main(){ int A = 0; int B = 9; int L = 2; buildCantorSet(A, B, L); return 0;}",
"e": 32987,
"s": 30950,
"text": null
},
{
"code": "// Java implementation to find the cantor set// for n levels and// for a given start_num and end_num class GFG{ // The Linked List Structure for the Cantor Set static class Cantor { double start, end; Cantor next; }; static Cantor Cantor; // Function to initialize the Cantor Set List static Cantor startList(Cantor head, double start_num, double end_num) { if (head == null) { head = new Cantor(); head.start = start_num; head.end = end_num; head.next = null; } return head; } // Function to propagate the list // by adding new nodes for the next levels static Cantor propagate(Cantor head) { Cantor temp = head; if (temp != null) { Cantor newNode = new Cantor(); double diff = (((temp.end) - (temp.start)) / 3); // Modifying the start and end values // for the next level newNode.end = temp.end; temp.end = ((temp.start) + diff); newNode.start = (newNode.end) - diff; // Changing the pointers // to the next node newNode.next = temp.next; temp.next = newNode; // Recursively call the function // to generate the Cantor Set // for the entire level propagate(temp.next.next); } return head; } // Function to print a level of the Set static void print(Cantor temp) { while (temp != null) { System.out.printf(\"[%f] -- [%f]\", temp.start, temp.end); temp = temp.next; } System.out.printf(\"\\n\"); } // Function to build and display // the Cantor Set for each level static void buildCantorSet(int A, int B, int L) { Cantor head = null; head = startList(head, A, B); for (int i = 0; i < L; i++) { System.out.printf(\"Level_%d : \", i); print(head); propagate(head); } System.out.printf(\"Level_%d : \", L); print(head); } // Driver code public static void main(String[] args) { int A = 0; int B = 9; int L = 2; buildCantorSet(A, B, L); }} // This code is contributed by Rajput-Ji",
"e": 35321,
"s": 32987,
"text": null
},
{
"code": "// C# implementation to find the cantor set// for n levels and// for a given start_num and end_numusing System; class GFG{ // The Linked List Structure for the Cantor Set class Cantor { public double start, end; public Cantor next; }; static Cantor cantor; // Function to initialize the Cantor Set List static Cantor startList(Cantor head, double start_num, double end_num) { if (head == null) { head = new Cantor(); head.start = start_num; head.end = end_num; head.next = null; } return head; } // Function to propagate the list // by adding new nodes for the next levels static Cantor propagate(Cantor head) { Cantor temp = head; if (temp != null) { Cantor newNode = new Cantor(); double diff = (((temp.end) - (temp.start)) / 3); // Modifying the start and end values // for the next level newNode.end = temp.end; temp.end = ((temp.start) + diff); newNode.start = (newNode.end) - diff; // Changing the pointers // to the next node newNode.next = temp.next; temp.next = newNode; // Recursively call the function // to generate the Cantor Set // for the entire level propagate(temp.next.next); } return head; } // Function to print a level of the Set static void print(Cantor temp) { while (temp != null) { Console.Write(\"[{0:F6}] -- [{1:F6}]\", temp.start, temp.end); temp = temp.next; } Console.Write(\"\\n\"); } // Function to build and display // the Cantor Set for each level static void buildCantorSet(int A, int B, int L) { Cantor head = null; head = startList(head, A, B); for (int i = 0; i < L; i++) { Console.Write(\"Level_{0} : \", i); print(head); propagate(head); } Console.Write(\"Level_{0} : \", L); print(head); } // Driver code public static void Main(String[] args) { int A = 0; int B = 9; int L = 2; buildCantorSet(A, B, L); }} // This code is contributed by Rajput-Ji",
"e": 37694,
"s": 35321,
"text": null
},
{
"code": "<script> // Javascript implementation to find the cantor set// for n levels and// for a given start_num and end_num// The Linked List Structure for the Cantor Setclass Cantor{ constructor() { this.start = 0; this.end = 0; this.next = null; }}; var cantor = null; // Function to initialize the Cantor Set Listfunction startList(head, start_num, end_num){ if (head == null) { head = new Cantor(); head.start = start_num; head.end = end_num; head.next = null; } return head;}// Function to propagate the list// by adding new nodes for the next levelsfunction propagate(head){ var temp = head; if (temp != null) { var newNode = new Cantor(); var diff = (((temp.end) - (temp.start)) / 3); // Modifying the start and end values // for the next level newNode.end = temp.end; temp.end = ((temp.start) + diff); newNode.start = (newNode.end) - diff; // Changing the pointers // to the next node newNode.next = temp.next; temp.next = newNode; // Recursively call the function // to generate the Cantor Set // for the entire level propagate(temp.next.next); } return head;}// Function to print a level of the Setfunction print(temp){ while (temp != null) { document.write(\"[\"+temp.start.toFixed(6)+\"] -- [\"+ temp.end.toFixed(6)+\"] \"); temp = temp.next; } document.write(\"<br>\");}// Function to build and display// the Cantor Set for each levelfunction buildCantorSet(A, B, L){ var head = null; head = startList(head, A, B); for (var i = 0; i < L; i++) { document.write(\"Level_\"+ i +\" : \"); print(head); propagate(head); } document.write(\"Level_\"+ L +\" : \"); print(head);}// Driver codevar A = 0;var B = 9;var L = 2;buildCantorSet(A, B, L); </script>",
"e": 39599,
"s": 37694,
"text": null
},
{
"code": null,
"e": 39701,
"s": 39599,
"text": "References: Cantor Set Wikipedia Related Article: N-th term of George Cantor set of rational numbers "
},
{
"code": null,
"e": 39711,
"s": 39701,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 39730,
"s": 39711,
"text": "shivanisinghss2110"
},
{
"code": null,
"e": 39736,
"s": 39730,
"text": "itsok"
},
{
"code": null,
"e": 39752,
"s": 39736,
"text": "saurabh1990aror"
},
{
"code": null,
"e": 39776,
"s": 39752,
"text": "Technical Scripter 2019"
},
{
"code": null,
"e": 39788,
"s": 39776,
"text": "Linked List"
},
{
"code": null,
"e": 39801,
"s": 39788,
"text": "Mathematical"
},
{
"code": null,
"e": 39820,
"s": 39801,
"text": "Technical Scripter"
},
{
"code": null,
"e": 39832,
"s": 39820,
"text": "Linked List"
},
{
"code": null,
"e": 39845,
"s": 39832,
"text": "Mathematical"
},
{
"code": null,
"e": 39943,
"s": 39845,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 39984,
"s": 39943,
"text": "Circular Linked List | Set 2 (Traversal)"
},
{
"code": null,
"e": 40034,
"s": 39984,
"text": "Swap nodes in a linked list without swapping data"
},
{
"code": null,
"e": 40093,
"s": 40034,
"text": "Program to implement Singly Linked List in C++ using class"
},
{
"code": null,
"e": 40133,
"s": 40093,
"text": "Circular Singly Linked List | Insertion"
},
{
"code": null,
"e": 40204,
"s": 40133,
"text": "Given a linked list which is sorted, how will you insert in sorted way"
},
{
"code": null,
"e": 40234,
"s": 40204,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 40294,
"s": 40234,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 40309,
"s": 40294,
"text": "C++ Data Types"
},
{
"code": null,
"e": 40352,
"s": 40309,
"text": "Set in C++ Standard Template Library (STL)"
}
] |
Find duplicates in an Array with values 1 to N using counting sort - GeeksforGeeks | 04 Apr, 2022
Given a constant array of N elements which contain elements from 1 to N – 1, with any of these numbers appearing any number of times.Examples:
Input: N = 5, arr[] = {1, 3, 4, 2, 2} Output: 2 Explanation: 2 is the number occurring more than once.Input: N = 5, arr[] = {3, 1, 3, 4, 2} Output: 3 Explanation: 3 is the number occurring more than once.
Naive Approach: The naive method is to first sort the given array and then look for adjacent positions of the array to find the duplicate number. Time Complexity: O(N*log N) Auxiliary Space: O(1)Efficient Approach: To optimize the above method the idea is to use the concept of Counting Sort. Since the range of elements in the array is known, hence we could use this sorting technique to improvise the time complexity. The idea is to initialize another array(say count[]) with the same size N and initialize all the elements as 0. Then count the occurrences of each element of the array and update the count in the count[]. Print all the element whose count is greater than 1.Below is the implementation of above approach:
C++
Java
Python3
C#
Javascript
// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to find the duplicate// number using counting sort methodint findDuplicate(int arr[], int n){ int countArr[n + 1], i; // Initialize all the elements // of the countArr to 0 for (i = 0; i <= n; i++) countArr[i] = 0; // Count the occurences of each // element of the array for (i = 0; i <= n; i++) countArr[arr[i]]++; bool a = false; // Find the element with more // than one count for (i = 1; i <= n; i++) { if (countArr[i] > 1) { a = true; cout << i << ' '; } } // If unique elements are ther // print "-1" if (!a) cout << "-1";} // Driver Codeint main(){ // Given N int n = 4; // Given array arr[] int arr[] = { 1, 3, 4, 2, 2 }; // Function Call findDuplicate(arr, n); return 0;}
// Java program for the above approachimport java.util.*; class GFG { // Function to find the duplicate number // using counting sort method public static int findDuplicate(int arr[], int n) { int countArr[] = new int[n + 1], i; // Initialize all the elements of the // countArr to 0 for (i = 0; i <= n; i++) countArr[i] = 0; // Count the occurences of each // element of the array for (i = 0; i <= n; i++) countArr[arr[i]]++; bool a = false; // Find the element with more // than one count for (i = 1; i <= n; i++) { if (countArr[i] > 1) { a = true; System.out.print(i + " "); } } if (!a) System.out.println("-1"); } // Driver Code public static void main(String[] args) { int n = 4; int arr[] = { 1, 3, 4, 2, 2 }; // Function Call findDuplicate(arr, n); }}
# Python3 program for the above approach # Function to find the duplicate# number using counting sort methoddef findDuplicate(arr, n): # Initialize all the elements # of the countArr to 0 countArr = [0] * (n + 1) # Count the occurences of each # element of the array for i in range(n + 1): countArr[arr[i]] += 1 a = False # Find the element with more # than one count for i in range(1, n + 1): if(countArr[i] > 1): a = True print(i, end = " ") # If unique elements are there # print "-1" if(not a): print(-1) # Driver codeif __name__ == '__main__': # Given N n = 4 # Given array arr[] arr = [ 1, 3, 4, 2, 2 ] # Function Call findDuplicate(arr, n) # This code is contributed by Shivam Singh
// C# program for the above approachusing System; class GFG{ // Function to find the duplicate number// using counting sort methodstatic void findDuplicate(int []arr, int n){ int []countArr = new int[n + 1]; int i; // Initialize all the elements of the // countArr to 0 for(i = 0; i <= n; i++) countArr[i] = 0; // Count the occurences of each // element of the array for(i = 0; i <= n; i++) countArr[arr[i]]++; bool a = false; // Find the element with more // than one count for(i = 1; i <= n; i++) { if (countArr[i] > 1) { a = true; Console.Write(i + " "); } } if (!a) Console.WriteLine("-1");} // Driver Codepublic static void Main(String[] args){ int n = 4; int []arr = { 1, 3, 4, 2, 2 }; // Function Call findDuplicate(arr, n);}} // This code is contributed by Amit Katiyar
<script> // JavaScript program for the above approach // Function to find the duplicate number // using counting sort method function findDuplicate(arr, n) { let countArr = Array.from({length: n+1}, (_, i) => 0), i; // Initialize all the elements of the // countArr to 0 for (i = 0; i <= n; i++) countArr[i] = 0; // Count the occurences of each // element of the array for (i = 0; i <= n; i++) countArr[arr[i]]++; let a = false; // Find the element with more // than one count for (i = 1; i <= n; i++) { if (countArr[i] > 1) { a = true; document.write(i + " "); } } if (!a) document.write("-1"); } // Driver Code let n = 4; let arr = [ 1, 3, 4, 2, 2 ]; // Function Call findDuplicate(arr, n); </script>
2
Time Complexity: O(N) Auxiliary Space: O(N)Related articles:
Find duplicates in O(n) time and O(1) extra space | Set 1Duplicates in an array in O(n) and by using O(1) extra space | Set-2
Find duplicates in O(n) time and O(1) extra space | Set 1
Duplicates in an array in O(n) and by using O(1) extra space | Set-2
SHIVAMSINGH67
amit143katiyar
susmitakundugoaldanga
gulshankumarar231
rajat garg
counting-sort
Arrays
Competitive Programming
Searching
Sorting
Arrays
Searching
Sorting
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Count pairs with given sum
Chocolate Distribution Problem
Window Sliding Technique
Reversal algorithm for array rotation
Next Greater Element
Competitive Programming - A Complete Guide
Practice for cracking any coding interview
Arrow operator -> in C/C++ with Examples
Prefix Sum Array - Implementation and Applications in Competitive Programming
Fast I/O for Competitive Programming | [
{
"code": null,
"e": 26041,
"s": 26013,
"text": "\n04 Apr, 2022"
},
{
"code": null,
"e": 26186,
"s": 26041,
"text": "Given a constant array of N elements which contain elements from 1 to N – 1, with any of these numbers appearing any number of times.Examples: "
},
{
"code": null,
"e": 26393,
"s": 26186,
"text": "Input: N = 5, arr[] = {1, 3, 4, 2, 2} Output: 2 Explanation: 2 is the number occurring more than once.Input: N = 5, arr[] = {3, 1, 3, 4, 2} Output: 3 Explanation: 3 is the number occurring more than once. "
},
{
"code": null,
"e": 27120,
"s": 26395,
"text": "Naive Approach: The naive method is to first sort the given array and then look for adjacent positions of the array to find the duplicate number. Time Complexity: O(N*log N) Auxiliary Space: O(1)Efficient Approach: To optimize the above method the idea is to use the concept of Counting Sort. Since the range of elements in the array is known, hence we could use this sorting technique to improvise the time complexity. The idea is to initialize another array(say count[]) with the same size N and initialize all the elements as 0. Then count the occurrences of each element of the array and update the count in the count[]. Print all the element whose count is greater than 1.Below is the implementation of above approach: "
},
{
"code": null,
"e": 27124,
"s": 27120,
"text": "C++"
},
{
"code": null,
"e": 27129,
"s": 27124,
"text": "Java"
},
{
"code": null,
"e": 27137,
"s": 27129,
"text": "Python3"
},
{
"code": null,
"e": 27140,
"s": 27137,
"text": "C#"
},
{
"code": null,
"e": 27151,
"s": 27140,
"text": "Javascript"
},
{
"code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to find the duplicate// number using counting sort methodint findDuplicate(int arr[], int n){ int countArr[n + 1], i; // Initialize all the elements // of the countArr to 0 for (i = 0; i <= n; i++) countArr[i] = 0; // Count the occurences of each // element of the array for (i = 0; i <= n; i++) countArr[arr[i]]++; bool a = false; // Find the element with more // than one count for (i = 1; i <= n; i++) { if (countArr[i] > 1) { a = true; cout << i << ' '; } } // If unique elements are ther // print \"-1\" if (!a) cout << \"-1\";} // Driver Codeint main(){ // Given N int n = 4; // Given array arr[] int arr[] = { 1, 3, 4, 2, 2 }; // Function Call findDuplicate(arr, n); return 0;}",
"e": 28057,
"s": 27151,
"text": null
},
{
"code": "// Java program for the above approachimport java.util.*; class GFG { // Function to find the duplicate number // using counting sort method public static int findDuplicate(int arr[], int n) { int countArr[] = new int[n + 1], i; // Initialize all the elements of the // countArr to 0 for (i = 0; i <= n; i++) countArr[i] = 0; // Count the occurences of each // element of the array for (i = 0; i <= n; i++) countArr[arr[i]]++; bool a = false; // Find the element with more // than one count for (i = 1; i <= n; i++) { if (countArr[i] > 1) { a = true; System.out.print(i + \" \"); } } if (!a) System.out.println(\"-1\"); } // Driver Code public static void main(String[] args) { int n = 4; int arr[] = { 1, 3, 4, 2, 2 }; // Function Call findDuplicate(arr, n); }}",
"e": 29058,
"s": 28057,
"text": null
},
{
"code": "# Python3 program for the above approach # Function to find the duplicate# number using counting sort methoddef findDuplicate(arr, n): # Initialize all the elements # of the countArr to 0 countArr = [0] * (n + 1) # Count the occurences of each # element of the array for i in range(n + 1): countArr[arr[i]] += 1 a = False # Find the element with more # than one count for i in range(1, n + 1): if(countArr[i] > 1): a = True print(i, end = \" \") # If unique elements are there # print \"-1\" if(not a): print(-1) # Driver codeif __name__ == '__main__': # Given N n = 4 # Given array arr[] arr = [ 1, 3, 4, 2, 2 ] # Function Call findDuplicate(arr, n) # This code is contributed by Shivam Singh",
"e": 29856,
"s": 29058,
"text": null
},
{
"code": "// C# program for the above approachusing System; class GFG{ // Function to find the duplicate number// using counting sort methodstatic void findDuplicate(int []arr, int n){ int []countArr = new int[n + 1]; int i; // Initialize all the elements of the // countArr to 0 for(i = 0; i <= n; i++) countArr[i] = 0; // Count the occurences of each // element of the array for(i = 0; i <= n; i++) countArr[arr[i]]++; bool a = false; // Find the element with more // than one count for(i = 1; i <= n; i++) { if (countArr[i] > 1) { a = true; Console.Write(i + \" \"); } } if (!a) Console.WriteLine(\"-1\");} // Driver Codepublic static void Main(String[] args){ int n = 4; int []arr = { 1, 3, 4, 2, 2 }; // Function Call findDuplicate(arr, n);}} // This code is contributed by Amit Katiyar",
"e": 30754,
"s": 29856,
"text": null
},
{
"code": "<script> // JavaScript program for the above approach // Function to find the duplicate number // using counting sort method function findDuplicate(arr, n) { let countArr = Array.from({length: n+1}, (_, i) => 0), i; // Initialize all the elements of the // countArr to 0 for (i = 0; i <= n; i++) countArr[i] = 0; // Count the occurences of each // element of the array for (i = 0; i <= n; i++) countArr[arr[i]]++; let a = false; // Find the element with more // than one count for (i = 1; i <= n; i++) { if (countArr[i] > 1) { a = true; document.write(i + \" \"); } } if (!a) document.write(\"-1\"); } // Driver Code let n = 4; let arr = [ 1, 3, 4, 2, 2 ]; // Function Call findDuplicate(arr, n); </script>",
"e": 31687,
"s": 30754,
"text": null
},
{
"code": null,
"e": 31689,
"s": 31687,
"text": "2"
},
{
"code": null,
"e": 31754,
"s": 31691,
"text": "Time Complexity: O(N) Auxiliary Space: O(N)Related articles: "
},
{
"code": null,
"e": 31880,
"s": 31754,
"text": "Find duplicates in O(n) time and O(1) extra space | Set 1Duplicates in an array in O(n) and by using O(1) extra space | Set-2"
},
{
"code": null,
"e": 31938,
"s": 31880,
"text": "Find duplicates in O(n) time and O(1) extra space | Set 1"
},
{
"code": null,
"e": 32007,
"s": 31938,
"text": "Duplicates in an array in O(n) and by using O(1) extra space | Set-2"
},
{
"code": null,
"e": 32023,
"s": 32009,
"text": "SHIVAMSINGH67"
},
{
"code": null,
"e": 32038,
"s": 32023,
"text": "amit143katiyar"
},
{
"code": null,
"e": 32060,
"s": 32038,
"text": "susmitakundugoaldanga"
},
{
"code": null,
"e": 32078,
"s": 32060,
"text": "gulshankumarar231"
},
{
"code": null,
"e": 32089,
"s": 32078,
"text": "rajat garg"
},
{
"code": null,
"e": 32103,
"s": 32089,
"text": "counting-sort"
},
{
"code": null,
"e": 32110,
"s": 32103,
"text": "Arrays"
},
{
"code": null,
"e": 32134,
"s": 32110,
"text": "Competitive Programming"
},
{
"code": null,
"e": 32144,
"s": 32134,
"text": "Searching"
},
{
"code": null,
"e": 32152,
"s": 32144,
"text": "Sorting"
},
{
"code": null,
"e": 32159,
"s": 32152,
"text": "Arrays"
},
{
"code": null,
"e": 32169,
"s": 32159,
"text": "Searching"
},
{
"code": null,
"e": 32177,
"s": 32169,
"text": "Sorting"
},
{
"code": null,
"e": 32275,
"s": 32177,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32302,
"s": 32275,
"text": "Count pairs with given sum"
},
{
"code": null,
"e": 32333,
"s": 32302,
"text": "Chocolate Distribution Problem"
},
{
"code": null,
"e": 32358,
"s": 32333,
"text": "Window Sliding Technique"
},
{
"code": null,
"e": 32396,
"s": 32358,
"text": "Reversal algorithm for array rotation"
},
{
"code": null,
"e": 32417,
"s": 32396,
"text": "Next Greater Element"
},
{
"code": null,
"e": 32460,
"s": 32417,
"text": "Competitive Programming - A Complete Guide"
},
{
"code": null,
"e": 32503,
"s": 32460,
"text": "Practice for cracking any coding interview"
},
{
"code": null,
"e": 32544,
"s": 32503,
"text": "Arrow operator -> in C/C++ with Examples"
},
{
"code": null,
"e": 32622,
"s": 32544,
"text": "Prefix Sum Array - Implementation and Applications in Competitive Programming"
}
] |
Python - Media object in Tweepy - GeeksforGeeks | 21 Jun, 2020
Twitter is a popular social network where users share messages called tweets. Twitter allows us to mine the data of any user using Twitter API or Tweepy. The data will be tweets extracted from the user. The first thing to do is get the consumer key, consumer secret, access key and access secret from twitter developer available easily for each user. These keys will help the API for authentication.
The Media object in Tweepy module contains the information about a media file uploaded on Twitter.
Here are the list of attributes in the Media object :
media_id : The ID of the media object.
media_id_str : The ID of the media object as a string.
size : The size of the media object in bytes.
expires_after_secs : The time in seconds after which the media object expires.
image_type : The type of image.
w : The width of the media object.
h : The height of the media object.
Example : We will use media_upload() method to upload and fetch the media object.
Consider the following image :
# import the moduleimport tweepy # assign the values accordinglyconsumer_key = ""consumer_secret = ""access_token = ""access_token_secret = "" # authorization of consumer key and consumer secretauth = tweepy.OAuthHandler(consumer_key, consumer_secret) # set access to user's access key and access secret auth.set_access_token(access_token, access_token_secret) # calling the api api = tweepy.API(auth) # uploading the media and fetching the Media objectmedia = api.media_upload("gfg.png") # printing the informationprint("The media_id is : " + str(media.media_id))print("The media_id_string is : " + media.media_id_string)print("The size is : " + str(media.size))print("The expires_after_secs is : " + str(media.expires_after_secs))print("The image_type is : " + str(media.image["image_type"]))print("The w is : " + str(media.image["w"]))print("The h is : " + str(media.image["h"]))
Output :
The media_id is : 1273526215773573121
The media_id_string is : 1273526215773573121
The size is : 3346
The expires_after_secs is : 86400
The image_type is : image/png
The w is : 225
The h is : 225
Python-Tweepy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
*args and **kwargs in Python
Reading and Writing to text files in Python
Create a Pandas DataFrame from Lists | [
{
"code": null,
"e": 25377,
"s": 25349,
"text": "\n21 Jun, 2020"
},
{
"code": null,
"e": 25777,
"s": 25377,
"text": "Twitter is a popular social network where users share messages called tweets. Twitter allows us to mine the data of any user using Twitter API or Tweepy. The data will be tweets extracted from the user. The first thing to do is get the consumer key, consumer secret, access key and access secret from twitter developer available easily for each user. These keys will help the API for authentication."
},
{
"code": null,
"e": 25876,
"s": 25777,
"text": "The Media object in Tweepy module contains the information about a media file uploaded on Twitter."
},
{
"code": null,
"e": 25930,
"s": 25876,
"text": "Here are the list of attributes in the Media object :"
},
{
"code": null,
"e": 25969,
"s": 25930,
"text": "media_id : The ID of the media object."
},
{
"code": null,
"e": 26024,
"s": 25969,
"text": "media_id_str : The ID of the media object as a string."
},
{
"code": null,
"e": 26070,
"s": 26024,
"text": "size : The size of the media object in bytes."
},
{
"code": null,
"e": 26149,
"s": 26070,
"text": "expires_after_secs : The time in seconds after which the media object expires."
},
{
"code": null,
"e": 26181,
"s": 26149,
"text": "image_type : The type of image."
},
{
"code": null,
"e": 26216,
"s": 26181,
"text": "w : The width of the media object."
},
{
"code": null,
"e": 26252,
"s": 26216,
"text": "h : The height of the media object."
},
{
"code": null,
"e": 26334,
"s": 26252,
"text": "Example : We will use media_upload() method to upload and fetch the media object."
},
{
"code": null,
"e": 26365,
"s": 26334,
"text": "Consider the following image :"
},
{
"code": "# import the moduleimport tweepy # assign the values accordinglyconsumer_key = \"\"consumer_secret = \"\"access_token = \"\"access_token_secret = \"\" # authorization of consumer key and consumer secretauth = tweepy.OAuthHandler(consumer_key, consumer_secret) # set access to user's access key and access secret auth.set_access_token(access_token, access_token_secret) # calling the api api = tweepy.API(auth) # uploading the media and fetching the Media objectmedia = api.media_upload(\"gfg.png\") # printing the informationprint(\"The media_id is : \" + str(media.media_id))print(\"The media_id_string is : \" + media.media_id_string)print(\"The size is : \" + str(media.size))print(\"The expires_after_secs is : \" + str(media.expires_after_secs))print(\"The image_type is : \" + str(media.image[\"image_type\"]))print(\"The w is : \" + str(media.image[\"w\"]))print(\"The h is : \" + str(media.image[\"h\"]))",
"e": 27254,
"s": 26365,
"text": null
},
{
"code": null,
"e": 27263,
"s": 27254,
"text": "Output :"
},
{
"code": null,
"e": 27460,
"s": 27263,
"text": "The media_id is : 1273526215773573121\nThe media_id_string is : 1273526215773573121\nThe size is : 3346\nThe expires_after_secs is : 86400\nThe image_type is : image/png\nThe w is : 225\nThe h is : 225\n"
},
{
"code": null,
"e": 27474,
"s": 27460,
"text": "Python-Tweepy"
},
{
"code": null,
"e": 27481,
"s": 27474,
"text": "Python"
},
{
"code": null,
"e": 27579,
"s": 27481,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27597,
"s": 27579,
"text": "Python Dictionary"
},
{
"code": null,
"e": 27632,
"s": 27597,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 27664,
"s": 27632,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27686,
"s": 27664,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 27728,
"s": 27686,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 27758,
"s": 27728,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 27784,
"s": 27758,
"text": "Python String | replace()"
},
{
"code": null,
"e": 27813,
"s": 27784,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 27857,
"s": 27813,
"text": "Reading and Writing to text files in Python"
}
] |
Python Program To Find Length Of The Longest Substring Without Repeating Characters - GeeksforGeeks | 20 Dec, 2021
Given a string str, find the length of the longest substring without repeating characters.
For “ABDEFGABEF”, the longest substring are “BDEFGA” and “DEFGAB”, with length 6.
For “BBBB” the longest substring is “B”, with length 1.
For “GEEKSFORGEEKS”, there are two longest substrings shown in the below diagrams, with length 7
The desired time complexity is O(n) where n is the length of the string.
Method 1 (Simple : O(n3)): We can consider all substrings one by one and check for each substring whether it contains all unique characters or not. There will be n*(n+1)/2 substrings. Whether a substring contains all unique characters or not can be checked in linear time by scanning it from left to right and keeping a map of visited characters. Time complexity of this solution would be O(n^3).
Python3
# Python3 program to find the length# of the longest substring without# repeating characters # This functionr eturns true if all# characters in strr[i..j] are # distinct, otherwise returns falsedef areDistinct(strr, i, j): # Note : Default values in visited are false visited = [0] * (26) for k in range(i, j + 1): if (visited[ord(strr[k]) - ord('a')] == True): return False visited[ord(strr[k]) - ord('a')] = True return True # Returns length of the longest substring# with all distinct characters.def longestUniqueSubsttr(strr): n = len(strr) # Result res = 0 for i in range(n): for j in range(i, n): if (areDistinct(strr, i, j)): res = max(res, j - i + 1) return res # Driver codeif __name__ == '__main__': strr = "geeksforgeeks" print("The input is ", strr) len = longestUniqueSubsttr(strr) print("The length of the longest " "non-repeating character substring is ", len) # This code is contributed by mohit kumar 29
The input string is geeksforgeeks
The length of the longest non-repeating character substring is 7
Method 2 (Better : O(n2)) The idea is to use window sliding. Whenever we see repetition, we remove the previous occurrence and slide the window.
Python3
# Python3 program to find the # length of the longest substring# without repeating charactersdef longestUniqueSubsttr(str): n = len(str) # Result res = 0 for i in range(n): # Note : Default values in # visited are false visited = [0] * 256 for j in range(i, n): # If current character is visited # Break the loop if (visited[ord(str[j])] == True): break # Else update the result if # this window is larger, and mark # current character as visited. else: res = max(res, j - i + 1) visited[ord(str[j])] = True # Remove the first character of previous # window visited[ord(str[i])] = False return res # Driver codestr = "geeksforgeeks"print("The input is ", str) len = longestUniqueSubsttr(str)print("The length of the longest " "non-repeating character substring is ", len) # This code is contributed by sanjoy_62
The input string is geeksforgeeks
The length of the longest non-repeating character substring is 7
Method 4 (Linear Time): Let us talk about the linear time solution now. This solution uses extra space to store the last indexes of already visited characters. The idea is to scan the string from left to right, keep track of the maximum length Non-Repeating Character Substring seen so far in res. When we traverse the string, to know the length of current window we need two indexes. 1) Ending index ( j ) : We consider current index as ending index. 2) Starting index ( i ) : It is same as previous window if current character was not present in the previous window. To check if the current character was present in the previous window or not, we store last index of every character in an array lasIndex[]. If lastIndex[str[j]] + 1 is more than previous start, then we updated the start index i. Else we keep same i.
Below is the implementation of the above approach :
Python3
# Python3 program to find the length# of the longest substring# without repeating charactersdef longestUniqueSubsttr(string): # last index of every character last_idx = {} max_len = 0 # starting index of current # window to calculate max_len start_idx = 0 for i in range(0, len(string)): # Find the last index of str[i] # Update start_idx (starting index of current window) # as maximum of current value of start_idx and last # index plus 1 if string[i] in last_idx: start_idx = max(start_idx, last_idx[string[i]] + 1) # Update result if we get a larger window max_len = max(max_len, i-start_idx + 1) # Update last index of current char. last_idx[string[i]] = i return max_len # Driver program to test the above functionstring = "geeksforgeeks"print("The input string is " + string)length = longestUniqueSubsttr(string)print("The length of the longest non-repeating character" + " substring is " + str(length))
The input string is geeksforgeeks
The length of the longest non-repeating character substring is 7
Time Complexity: O(n + d) where n is length of the input string and d is number of characters in input string alphabet. For example, if string consists of lowercase English characters then value of d is 26. Auxiliary Space: O(d)
Alternate Implementation :
Python
# Here, we are planning to implement a simple sliding window methodology def longestUniqueSubsttr(string): # Creating a set to store the last positions of occurrence seen = {} maximum_length = 0 # starting the initial point of window to index 0 start = 0 for end in range(len(string)): # Checking if we have already seen the element or not if string[end] in seen: # If we have seen the number, move the start pointer # to position after the last occurrence start = max(start, seen[string[end]] + 1) # Updating the last seen value of the character seen[string[end]] = end maximum_length = max(maximum_length, end-start + 1) return maximum_length # Driver Codestring = "geeksforgeeks"print("The input string is", string)length = longestUniqueSubsttr(string)print("The length of the longest non-repeating character substring is", length)
The input String is geeksforgeeks
The length of the longest non-repeating character substring is 7
As an exercise, try the modified version of the above problem where you need to print the maximum length NRCS also (the above program only prints the length of it).
Please refer complete article on Length of the longest substring without repeating characters for more details!
Amazon
Housing.com
Microsoft
Morgan Stanley
Python Programs
Strings
Morgan Stanley
Amazon
Microsoft
Housing.com
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Appending to list in Python dictionary
Python program to interchange first and last elements in a list
How to inverse a matrix using NumPy
Python | Get the first key in dictionary
Differences and Applications of List, Tuple, Set and Dictionary in Python
Write a program to reverse an array or string
Reverse a string in Java
Write a program to print all permutations of a given string
C++ Data Types
Longest Common Subsequence | DP-4 | [
{
"code": null,
"e": 26097,
"s": 26069,
"text": "\n20 Dec, 2021"
},
{
"code": null,
"e": 26189,
"s": 26097,
"text": "Given a string str, find the length of the longest substring without repeating characters. "
},
{
"code": null,
"e": 26271,
"s": 26189,
"text": "For “ABDEFGABEF”, the longest substring are “BDEFGA” and “DEFGAB”, with length 6."
},
{
"code": null,
"e": 26327,
"s": 26271,
"text": "For “BBBB” the longest substring is “B”, with length 1."
},
{
"code": null,
"e": 26424,
"s": 26327,
"text": "For “GEEKSFORGEEKS”, there are two longest substrings shown in the below diagrams, with length 7"
},
{
"code": null,
"e": 26497,
"s": 26424,
"text": "The desired time complexity is O(n) where n is the length of the string."
},
{
"code": null,
"e": 26894,
"s": 26497,
"text": "Method 1 (Simple : O(n3)): We can consider all substrings one by one and check for each substring whether it contains all unique characters or not. There will be n*(n+1)/2 substrings. Whether a substring contains all unique characters or not can be checked in linear time by scanning it from left to right and keeping a map of visited characters. Time complexity of this solution would be O(n^3)."
},
{
"code": null,
"e": 26902,
"s": 26894,
"text": "Python3"
},
{
"code": "# Python3 program to find the length# of the longest substring without# repeating characters # This functionr eturns true if all# characters in strr[i..j] are # distinct, otherwise returns falsedef areDistinct(strr, i, j): # Note : Default values in visited are false visited = [0] * (26) for k in range(i, j + 1): if (visited[ord(strr[k]) - ord('a')] == True): return False visited[ord(strr[k]) - ord('a')] = True return True # Returns length of the longest substring# with all distinct characters.def longestUniqueSubsttr(strr): n = len(strr) # Result res = 0 for i in range(n): for j in range(i, n): if (areDistinct(strr, i, j)): res = max(res, j - i + 1) return res # Driver codeif __name__ == '__main__': strr = \"geeksforgeeks\" print(\"The input is \", strr) len = longestUniqueSubsttr(strr) print(\"The length of the longest \" \"non-repeating character substring is \", len) # This code is contributed by mohit kumar 29",
"e": 28036,
"s": 26902,
"text": null
},
{
"code": null,
"e": 28135,
"s": 28036,
"text": "The input string is geeksforgeeks\nThe length of the longest non-repeating character substring is 7"
},
{
"code": null,
"e": 28280,
"s": 28135,
"text": "Method 2 (Better : O(n2)) The idea is to use window sliding. Whenever we see repetition, we remove the previous occurrence and slide the window."
},
{
"code": null,
"e": 28288,
"s": 28280,
"text": "Python3"
},
{
"code": "# Python3 program to find the # length of the longest substring# without repeating charactersdef longestUniqueSubsttr(str): n = len(str) # Result res = 0 for i in range(n): # Note : Default values in # visited are false visited = [0] * 256 for j in range(i, n): # If current character is visited # Break the loop if (visited[ord(str[j])] == True): break # Else update the result if # this window is larger, and mark # current character as visited. else: res = max(res, j - i + 1) visited[ord(str[j])] = True # Remove the first character of previous # window visited[ord(str[i])] = False return res # Driver codestr = \"geeksforgeeks\"print(\"The input is \", str) len = longestUniqueSubsttr(str)print(\"The length of the longest \" \"non-repeating character substring is \", len) # This code is contributed by sanjoy_62",
"e": 29355,
"s": 28288,
"text": null
},
{
"code": null,
"e": 29454,
"s": 29355,
"text": "The input string is geeksforgeeks\nThe length of the longest non-repeating character substring is 7"
},
{
"code": null,
"e": 30275,
"s": 29454,
"text": "Method 4 (Linear Time): Let us talk about the linear time solution now. This solution uses extra space to store the last indexes of already visited characters. The idea is to scan the string from left to right, keep track of the maximum length Non-Repeating Character Substring seen so far in res. When we traverse the string, to know the length of current window we need two indexes. 1) Ending index ( j ) : We consider current index as ending index. 2) Starting index ( i ) : It is same as previous window if current character was not present in the previous window. To check if the current character was present in the previous window or not, we store last index of every character in an array lasIndex[]. If lastIndex[str[j]] + 1 is more than previous start, then we updated the start index i. Else we keep same i. "
},
{
"code": null,
"e": 30327,
"s": 30275,
"text": "Below is the implementation of the above approach :"
},
{
"code": null,
"e": 30335,
"s": 30327,
"text": "Python3"
},
{
"code": "# Python3 program to find the length# of the longest substring# without repeating charactersdef longestUniqueSubsttr(string): # last index of every character last_idx = {} max_len = 0 # starting index of current # window to calculate max_len start_idx = 0 for i in range(0, len(string)): # Find the last index of str[i] # Update start_idx (starting index of current window) # as maximum of current value of start_idx and last # index plus 1 if string[i] in last_idx: start_idx = max(start_idx, last_idx[string[i]] + 1) # Update result if we get a larger window max_len = max(max_len, i-start_idx + 1) # Update last index of current char. last_idx[string[i]] = i return max_len # Driver program to test the above functionstring = \"geeksforgeeks\"print(\"The input string is \" + string)length = longestUniqueSubsttr(string)print(\"The length of the longest non-repeating character\" + \" substring is \" + str(length))",
"e": 31373,
"s": 30335,
"text": null
},
{
"code": null,
"e": 31472,
"s": 31373,
"text": "The input string is geeksforgeeks\nThe length of the longest non-repeating character substring is 7"
},
{
"code": null,
"e": 31702,
"s": 31472,
"text": "Time Complexity: O(n + d) where n is length of the input string and d is number of characters in input string alphabet. For example, if string consists of lowercase English characters then value of d is 26. Auxiliary Space: O(d) "
},
{
"code": null,
"e": 31730,
"s": 31702,
"text": "Alternate Implementation : "
},
{
"code": null,
"e": 31737,
"s": 31730,
"text": "Python"
},
{
"code": "# Here, we are planning to implement a simple sliding window methodology def longestUniqueSubsttr(string): # Creating a set to store the last positions of occurrence seen = {} maximum_length = 0 # starting the initial point of window to index 0 start = 0 for end in range(len(string)): # Checking if we have already seen the element or not if string[end] in seen: # If we have seen the number, move the start pointer # to position after the last occurrence start = max(start, seen[string[end]] + 1) # Updating the last seen value of the character seen[string[end]] = end maximum_length = max(maximum_length, end-start + 1) return maximum_length # Driver Codestring = \"geeksforgeeks\"print(\"The input string is\", string)length = longestUniqueSubsttr(string)print(\"The length of the longest non-repeating character substring is\", length)",
"e": 32691,
"s": 31737,
"text": null
},
{
"code": null,
"e": 32790,
"s": 32691,
"text": "The input String is geeksforgeeks\nThe length of the longest non-repeating character substring is 7"
},
{
"code": null,
"e": 32955,
"s": 32790,
"text": "As an exercise, try the modified version of the above problem where you need to print the maximum length NRCS also (the above program only prints the length of it)."
},
{
"code": null,
"e": 33067,
"s": 32955,
"text": "Please refer complete article on Length of the longest substring without repeating characters for more details!"
},
{
"code": null,
"e": 33074,
"s": 33067,
"text": "Amazon"
},
{
"code": null,
"e": 33086,
"s": 33074,
"text": "Housing.com"
},
{
"code": null,
"e": 33096,
"s": 33086,
"text": "Microsoft"
},
{
"code": null,
"e": 33111,
"s": 33096,
"text": "Morgan Stanley"
},
{
"code": null,
"e": 33127,
"s": 33111,
"text": "Python Programs"
},
{
"code": null,
"e": 33135,
"s": 33127,
"text": "Strings"
},
{
"code": null,
"e": 33150,
"s": 33135,
"text": "Morgan Stanley"
},
{
"code": null,
"e": 33157,
"s": 33150,
"text": "Amazon"
},
{
"code": null,
"e": 33167,
"s": 33157,
"text": "Microsoft"
},
{
"code": null,
"e": 33179,
"s": 33167,
"text": "Housing.com"
},
{
"code": null,
"e": 33187,
"s": 33179,
"text": "Strings"
},
{
"code": null,
"e": 33285,
"s": 33187,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 33324,
"s": 33285,
"text": "Appending to list in Python dictionary"
},
{
"code": null,
"e": 33388,
"s": 33324,
"text": "Python program to interchange first and last elements in a list"
},
{
"code": null,
"e": 33424,
"s": 33388,
"text": "How to inverse a matrix using NumPy"
},
{
"code": null,
"e": 33465,
"s": 33424,
"text": "Python | Get the first key in dictionary"
},
{
"code": null,
"e": 33539,
"s": 33465,
"text": "Differences and Applications of List, Tuple, Set and Dictionary in Python"
},
{
"code": null,
"e": 33585,
"s": 33539,
"text": "Write a program to reverse an array or string"
},
{
"code": null,
"e": 33610,
"s": 33585,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 33670,
"s": 33610,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 33685,
"s": 33670,
"text": "C++ Data Types"
}
] |
Count of ways in which N can be represented as sum of Fibonacci numbers without repetition - GeeksforGeeks | 18 Jan, 2022
Given a number N, the task is to find the number of ways in which the integer N can be represented as a sum of Fibonacci numbers without repetition of any Fibonacci number.
Examples:
Input: N = 13Output: 3Explanation: The possible ways to select N as 13 are: {13} {8, 5} {8, 3, 2}. Note that it is not possible to select {5 + 5 + 3} because 5 appears twice.
Input: N = 87Output: 5Explanation:The possible ways to select N as 13 are: {55 + 21 + 8 + 3}, {55 + 21 + 8 + 2 + 1}, {55 + 21 + 5 + 3 + 2 + 1}, {55 + 13 + 8 + 5 + 3 + 2 + 1}, {34 + 21 + 13 + 8 + 5 + 3 + 2 + 1}.
Naive Approach: The naive idea is to write all the possible combinations that add up to given number N. Check if any combination has repeated integers then don’t increase the counter otherwise increase the count by 1 each time. Return the count at the end.
Time Complexity: O(N)Auxiliary Space: O(1)
Efficient Approach: The idea is to use Dynamic Programming to optimize the above approach. Below are the steps:
Let us represent a number in the Fibonacci code.
Imagine Fibonacci coding by following way: the i-th bit of number corresponds to the i-th Fibonacci number. For Example: 16 = 13 + 3 will be written as 100100.
Write Fibonacci Code for every positive number such that no two adjacent bit is 1.
This is true for all numbers because if there are two adjacent bits are 1-bits then we can transform it into a single 1-bit by property of Fibonacci number. Let’s call this representation as canonical representation.
Get the Canonical Representation. Generate several Fibonacci numbers (about 90) and after that try to subtract all of them in the decreasing order.
Let’s store positions of 1-bits of the canonical representation of a given number into an array v in the increasing order and decompose any 1-bits into two 1-bits as follows:
Starting canonical representation: 1000000001After decomposing leftmost 1-bit into two smaller 1-bits: 0110000001After decomposing 2’nd leftmost 1-bit into two smaller 1-bits: 0101100001 After decomposing 3’rd leftmost 1-bit into two smaller 1-bits: 0101011001After decomposing 4’th leftmost 1-bit into two smaller 1-bits: 0101010111
After a number of such operations, we will get the next 1-bit(or the end of the number). This 1-bit also can be decomposed, but it can be shifted by only one bit.
Initialize a dp array dp1[], dp1[i] is a number of ways to represent a number that consists of i leftmost 1-bits of the number for the case where all the remaining 1-bits are not decomposed. Also, take dp2[i] which marks the number of ways to represent a number that consists of i leftmost 1-bits of the number for the case where all the remaining 1-bits are decomposed.
For Example: N = 87
Canonical form of N = 101010100 Other 4 possible representations of N are 101010011, 101001111, 100111111, 011111111
Below is the illustration of the same:
Hence, the answer is dp1[cnt] + dp2[cnt], where cnt is the total number of 1-bits in the canonical representation.
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; long long fib[101], dp1[101];long long dp2[101], v[101]; // Function to generate the// fibonacci numbervoid fibonacci(){ // First two number of // fibonacci sequence fib[1] = 1; fib[2] = 2; for (int i = 3; i <= 87; i++) { fib[i] = fib[i - 1] + fib[i - 2]; }} // Function to find maximum ways to// represent num as the sum of// fibonacci numberint find(int num){ int cnt = 0; // Generate the Canonical form // of given number for (int i = 87; i > 0; i--) { if (num >= fib[i]) { v[cnt++] = i; num -= fib[i]; } } // Reverse the number reverse(v, v + cnt); // Base condition of dp1 and dp2 dp1[0] = 1; dp2[0] = (v[0] - 1) / 2; // Iterate from 1 to cnt for (int i = 1; i < cnt; i++) { // Calculate dp1[] dp1[i] = dp1[i - 1] + dp2[i - 1]; // Calculate dp2[] dp2[i] = ((v[i] - v[i - 1]) / 2) * dp2[i - 1] + ((v[i] - v[i - 1] - 1) / 2) * dp1[i - 1]; } // Return final ans return (dp1[cnt - 1] + dp2[cnt - 1]);} // Driver Codeint main(){ // Function call to generate the // fibonacci numbers fibonacci(); // Given Number int num = 13; // Function Call cout << find(num); return 0;}
// Java program for the above approachimport java.util.*; class GFG{ static long[] fib = new long[101];static long[] dp1 = new long[101];static long[] dp2 = new long[101];static long[] v = new long[101]; // Function to generate the// fibonacci numberstatic void fibonacci(){ // First two number of // fibonacci sequence fib[1] = 1; fib[2] = 2; for(int i = 3; i <= 87; i++) { fib[i] = fib[i - 1] + fib[i - 2]; }} // Function to find maximum ways to// represent num as the sum of// fibonacci numberstatic long find(int num){ int cnt = 0; // Generate the Canonical form // of given number for(int i = 87; i > 0; i--) { if (num >= fib[i]) { v[cnt++] = i; num -= fib[i]; } } // Reverse the number for(int i = 0; i < cnt / 2; i++) { long t = v[i]; v[i] = v[cnt - i - 1]; v[cnt - i - 1] = t; } // Base condition of dp1 and dp2 dp1[0] = 1; dp2[0] = (v[0] - 1) / 2; // Iterate from 1 to cnt for(int i = 1; i < cnt; i++) { // Calculate dp1[] dp1[i] = dp1[i - 1] + dp2[i - 1]; // Calculate dp2[] dp2[i] = ((v[i] - v[i - 1]) / 2) * dp2[i - 1] + ((v[i] - v[i - 1] - 1) / 2) * dp1[i - 1]; } // Return final ans return (dp1[cnt - 1] + dp2[cnt - 1]);} // Driver codepublic static void main (String[] args){ // Function call to generate the // fibonacci numbers fibonacci(); // Given number int num = 13; // Function call System.out.print(find(num));}} // This code is contributed by offbeat
# Python3 program for the above approachfib = [0] * 101dp1 = [0] * 101dp2 = [0] * 101v = [0] * 101 # Function to generate the# fibonacci numberdef fibonacci(): # First two number of # fibonacci sequence fib[1] = 1 fib[2] = 2 for i in range(3, 87 + 1): fib[i] = fib[i - 1] + fib[i - 2] # Function to find maximum ways to# represent num as the sum of# fibonacci numberdef find(num): cnt = 0 # Generate the Canonical form # of given number for i in range(87, 0, -1): if(num >= fib[i]): v[cnt] = i cnt += 1 num -= fib[i] # Reverse the number v[::-1] # Base condition of dp1 and dp2 dp1[0] = 1 dp2[0] = (v[0] - 1) // 2 # Iterate from 1 to cnt for i in range(1, cnt): # Calculate dp1[] dp1[i] = dp1[i - 1] + dp2[i - 1] # Calculate dp2[] dp2[i] = (((v[i] - v[i - 1]) // 2) * dp2[i - 1] + ((v[i] - v[i - 1] - 1) // 2) * dp1[i - 1]) # Return final ans return dp1[cnt - 1] + dp2[cnt - 1] # Driver Code # Function call to generate the# fibonacci numbersfibonacci() # Given numbernum = 13 # Function callprint(find(num)) # This code is contributed by Shivam Singh
// C# program for the above approachusing System; class GFG{ static long[] fib = new long[101];static long[] dp1 = new long[101]; static long[] dp2 = new long[101];static long[] v = new long[101]; // Function to generate the // fibonacci number static void fibonacci() { // First two number of // fibonacci sequence fib[1] = 1; fib[2] = 2; for(int i = 3; i <= 87; i++) { fib[i] = fib[i - 1] + fib[i - 2]; } } // Function to find maximum ways to // represent num as the sum of // fibonacci number static long find(long num) { int cnt = 0; // Generate the Canonical form // of given number for(int i = 87; i > 0; i--) { if (num >= fib[i]) { v[cnt++] = i; num -= fib[i]; } } // Reverse the number for(int i = 0; i < cnt / 2; i++) { long t = v[i]; v[i] = v[cnt - i - 1]; v[cnt - i - 1] = t; } // Base condition of dp1 and dp2 dp1[0] = 1; dp2[0] = (v[0] - 1) / 2; // Iterate from 1 to cnt for(int i = 1; i < cnt; i++) { // Calculate dp1[] dp1[i] = dp1[i - 1] + dp2[i - 1]; // Calculate dp2[] dp2[i] = ((v[i] - v[i - 1]) / 2) * dp2[i - 1] + ((v[i] - v[i - 1] - 1) / 2) * dp1[i - 1]; } // Return final ans return (dp1[cnt - 1] + dp2[cnt - 1]); } // Driver codestatic void Main(){ // Function call to generate the // fibonacci numbers fibonacci(); // Given number int num = 13; // Function call Console.Write(find(num));}} // This code is contributed by divyeshrabadiya07
<script> // Javascript program for the above approachvar fib = Array(101).fill(0);var dp1 = Array(101).fill(0);var dp2 = Array(101).fill(0);var v = Array(101).fill(0); // Function to generate the// fibonacci numberfunction fibonacci(){ // First two number of // fibonacci sequence fib[1] = 1; fib[2] = 2; for(i = 3; i <= 87; i++) { fib[i] = fib[i - 1] + fib[i - 2]; }} // Function to find maximum ways to// represent num as the sum of// fibonacci numberfunction find(num){ var cnt = 0; // Generate the Canonical form // of given number for(i = 87; i > 0; i--) { if (num >= fib[i]) { v[cnt++] = i; num -= fib[i]; } } // Reverse the number for(i = 0; i < cnt / 2; i++) { var t = v[i]; v[i] = v[cnt - i - 1]; v[cnt - i - 1] = t; } // Base condition of dp1 and dp2 dp1[0] = 1; dp2[0] = parseInt((v[0] - 1) / 2); // Iterate from 1 to cnt for(i = 1; i < cnt; i++) { // Calculate dp1 dp1[i] = dp1[i - 1] + dp2[i - 1]; // Calculate dp2 dp2[i] = parseInt((v[i] - v[i - 1]) / 2) * dp2[i - 1] + parseInt((v[i] - v[i - 1] - 1) / 2) * dp1[i - 1]; } // Return final ans return (dp1[cnt - 1] + dp2[cnt - 1]);} // Driver code // Function call to generate the// fibonacci numbersfibonacci(); // Given numbervar num = 13; // Function calldocument.write(find(num)); // This code is contributed by todaysgaurav </script>
3
Time Complexity: O(log N)Auxiliary Space: O(log N)
SHIVAMSINGH67
offbeat
divyeshrabadiya07
todaysgaurav
kk9826225
Algorithms-Dynamic Programming
Fibonacci
Maths
Combinatorial
Dynamic Programming
Mathematical
Dynamic Programming
Mathematical
Fibonacci
Combinatorial
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Ways to sum to N using Natural Numbers up to K with repetitions allowed
Combinations with repetitions
Generate all possible combinations of K numbers that sums to N
Largest substring with same Characters
Generate all possible combinations of at most X characters from a given array
Largest Independent Set Problem | DP-26
Word Wrap Problem | DP-19
Partition problem | DP-18
Sieve of Eratosthenes
Maximum Length Chain of Pairs | DP-20 | [
{
"code": null,
"e": 26721,
"s": 26693,
"text": "\n18 Jan, 2022"
},
{
"code": null,
"e": 26895,
"s": 26721,
"text": "Given a number N, the task is to find the number of ways in which the integer N can be represented as a sum of Fibonacci numbers without repetition of any Fibonacci number. "
},
{
"code": null,
"e": 26905,
"s": 26895,
"text": "Examples:"
},
{
"code": null,
"e": 27080,
"s": 26905,
"text": "Input: N = 13Output: 3Explanation: The possible ways to select N as 13 are: {13} {8, 5} {8, 3, 2}. Note that it is not possible to select {5 + 5 + 3} because 5 appears twice."
},
{
"code": null,
"e": 27291,
"s": 27080,
"text": "Input: N = 87Output: 5Explanation:The possible ways to select N as 13 are: {55 + 21 + 8 + 3}, {55 + 21 + 8 + 2 + 1}, {55 + 21 + 5 + 3 + 2 + 1}, {55 + 13 + 8 + 5 + 3 + 2 + 1}, {34 + 21 + 13 + 8 + 5 + 3 + 2 + 1}."
},
{
"code": null,
"e": 27548,
"s": 27291,
"text": "Naive Approach: The naive idea is to write all the possible combinations that add up to given number N. Check if any combination has repeated integers then don’t increase the counter otherwise increase the count by 1 each time. Return the count at the end."
},
{
"code": null,
"e": 27591,
"s": 27548,
"text": "Time Complexity: O(N)Auxiliary Space: O(1)"
},
{
"code": null,
"e": 27703,
"s": 27591,
"text": "Efficient Approach: The idea is to use Dynamic Programming to optimize the above approach. Below are the steps:"
},
{
"code": null,
"e": 27752,
"s": 27703,
"text": "Let us represent a number in the Fibonacci code."
},
{
"code": null,
"e": 27912,
"s": 27752,
"text": "Imagine Fibonacci coding by following way: the i-th bit of number corresponds to the i-th Fibonacci number. For Example: 16 = 13 + 3 will be written as 100100."
},
{
"code": null,
"e": 27995,
"s": 27912,
"text": "Write Fibonacci Code for every positive number such that no two adjacent bit is 1."
},
{
"code": null,
"e": 28212,
"s": 27995,
"text": "This is true for all numbers because if there are two adjacent bits are 1-bits then we can transform it into a single 1-bit by property of Fibonacci number. Let’s call this representation as canonical representation."
},
{
"code": null,
"e": 28360,
"s": 28212,
"text": "Get the Canonical Representation. Generate several Fibonacci numbers (about 90) and after that try to subtract all of them in the decreasing order."
},
{
"code": null,
"e": 28535,
"s": 28360,
"text": "Let’s store positions of 1-bits of the canonical representation of a given number into an array v in the increasing order and decompose any 1-bits into two 1-bits as follows:"
},
{
"code": null,
"e": 28931,
"s": 28535,
"text": "Starting canonical representation: 1000000001After decomposing leftmost 1-bit into two smaller 1-bits: 0110000001After decomposing 2’nd leftmost 1-bit into two smaller 1-bits: 0101100001 After decomposing 3’rd leftmost 1-bit into two smaller 1-bits: 0101011001After decomposing 4’th leftmost 1-bit into two smaller 1-bits: 0101010111 "
},
{
"code": null,
"e": 29094,
"s": 28931,
"text": "After a number of such operations, we will get the next 1-bit(or the end of the number). This 1-bit also can be decomposed, but it can be shifted by only one bit."
},
{
"code": null,
"e": 29465,
"s": 29094,
"text": "Initialize a dp array dp1[], dp1[i] is a number of ways to represent a number that consists of i leftmost 1-bits of the number for the case where all the remaining 1-bits are not decomposed. Also, take dp2[i] which marks the number of ways to represent a number that consists of i leftmost 1-bits of the number for the case where all the remaining 1-bits are decomposed."
},
{
"code": null,
"e": 29485,
"s": 29465,
"text": "For Example: N = 87"
},
{
"code": null,
"e": 29603,
"s": 29485,
"text": "Canonical form of N = 101010100 Other 4 possible representations of N are 101010011, 101001111, 100111111, 011111111"
},
{
"code": null,
"e": 29642,
"s": 29603,
"text": "Below is the illustration of the same:"
},
{
"code": null,
"e": 29758,
"s": 29642,
"text": "Hence, the answer is dp1[cnt] + dp2[cnt], where cnt is the total number of 1-bits in the canonical representation. "
},
{
"code": null,
"e": 29809,
"s": 29758,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 29813,
"s": 29809,
"text": "C++"
},
{
"code": null,
"e": 29818,
"s": 29813,
"text": "Java"
},
{
"code": null,
"e": 29826,
"s": 29818,
"text": "Python3"
},
{
"code": null,
"e": 29829,
"s": 29826,
"text": "C#"
},
{
"code": null,
"e": 29840,
"s": 29829,
"text": "Javascript"
},
{
"code": "// C++ program for the above approach #include <bits/stdc++.h>using namespace std; long long fib[101], dp1[101];long long dp2[101], v[101]; // Function to generate the// fibonacci numbervoid fibonacci(){ // First two number of // fibonacci sequence fib[1] = 1; fib[2] = 2; for (int i = 3; i <= 87; i++) { fib[i] = fib[i - 1] + fib[i - 2]; }} // Function to find maximum ways to// represent num as the sum of// fibonacci numberint find(int num){ int cnt = 0; // Generate the Canonical form // of given number for (int i = 87; i > 0; i--) { if (num >= fib[i]) { v[cnt++] = i; num -= fib[i]; } } // Reverse the number reverse(v, v + cnt); // Base condition of dp1 and dp2 dp1[0] = 1; dp2[0] = (v[0] - 1) / 2; // Iterate from 1 to cnt for (int i = 1; i < cnt; i++) { // Calculate dp1[] dp1[i] = dp1[i - 1] + dp2[i - 1]; // Calculate dp2[] dp2[i] = ((v[i] - v[i - 1]) / 2) * dp2[i - 1] + ((v[i] - v[i - 1] - 1) / 2) * dp1[i - 1]; } // Return final ans return (dp1[cnt - 1] + dp2[cnt - 1]);} // Driver Codeint main(){ // Function call to generate the // fibonacci numbers fibonacci(); // Given Number int num = 13; // Function Call cout << find(num); return 0;}",
"e": 31222,
"s": 29840,
"text": null
},
{
"code": "// Java program for the above approachimport java.util.*; class GFG{ static long[] fib = new long[101];static long[] dp1 = new long[101];static long[] dp2 = new long[101];static long[] v = new long[101]; // Function to generate the// fibonacci numberstatic void fibonacci(){ // First two number of // fibonacci sequence fib[1] = 1; fib[2] = 2; for(int i = 3; i <= 87; i++) { fib[i] = fib[i - 1] + fib[i - 2]; }} // Function to find maximum ways to// represent num as the sum of// fibonacci numberstatic long find(int num){ int cnt = 0; // Generate the Canonical form // of given number for(int i = 87; i > 0; i--) { if (num >= fib[i]) { v[cnt++] = i; num -= fib[i]; } } // Reverse the number for(int i = 0; i < cnt / 2; i++) { long t = v[i]; v[i] = v[cnt - i - 1]; v[cnt - i - 1] = t; } // Base condition of dp1 and dp2 dp1[0] = 1; dp2[0] = (v[0] - 1) / 2; // Iterate from 1 to cnt for(int i = 1; i < cnt; i++) { // Calculate dp1[] dp1[i] = dp1[i - 1] + dp2[i - 1]; // Calculate dp2[] dp2[i] = ((v[i] - v[i - 1]) / 2) * dp2[i - 1] + ((v[i] - v[i - 1] - 1) / 2) * dp1[i - 1]; } // Return final ans return (dp1[cnt - 1] + dp2[cnt - 1]);} // Driver codepublic static void main (String[] args){ // Function call to generate the // fibonacci numbers fibonacci(); // Given number int num = 13; // Function call System.out.print(find(num));}} // This code is contributed by offbeat",
"e": 32883,
"s": 31222,
"text": null
},
{
"code": "# Python3 program for the above approachfib = [0] * 101dp1 = [0] * 101dp2 = [0] * 101v = [0] * 101 # Function to generate the# fibonacci numberdef fibonacci(): # First two number of # fibonacci sequence fib[1] = 1 fib[2] = 2 for i in range(3, 87 + 1): fib[i] = fib[i - 1] + fib[i - 2] # Function to find maximum ways to# represent num as the sum of# fibonacci numberdef find(num): cnt = 0 # Generate the Canonical form # of given number for i in range(87, 0, -1): if(num >= fib[i]): v[cnt] = i cnt += 1 num -= fib[i] # Reverse the number v[::-1] # Base condition of dp1 and dp2 dp1[0] = 1 dp2[0] = (v[0] - 1) // 2 # Iterate from 1 to cnt for i in range(1, cnt): # Calculate dp1[] dp1[i] = dp1[i - 1] + dp2[i - 1] # Calculate dp2[] dp2[i] = (((v[i] - v[i - 1]) // 2) * dp2[i - 1] + ((v[i] - v[i - 1] - 1) // 2) * dp1[i - 1]) # Return final ans return dp1[cnt - 1] + dp2[cnt - 1] # Driver Code # Function call to generate the# fibonacci numbersfibonacci() # Given numbernum = 13 # Function callprint(find(num)) # This code is contributed by Shivam Singh",
"e": 34125,
"s": 32883,
"text": null
},
{
"code": "// C# program for the above approachusing System; class GFG{ static long[] fib = new long[101];static long[] dp1 = new long[101]; static long[] dp2 = new long[101];static long[] v = new long[101]; // Function to generate the // fibonacci number static void fibonacci() { // First two number of // fibonacci sequence fib[1] = 1; fib[2] = 2; for(int i = 3; i <= 87; i++) { fib[i] = fib[i - 1] + fib[i - 2]; } } // Function to find maximum ways to // represent num as the sum of // fibonacci number static long find(long num) { int cnt = 0; // Generate the Canonical form // of given number for(int i = 87; i > 0; i--) { if (num >= fib[i]) { v[cnt++] = i; num -= fib[i]; } } // Reverse the number for(int i = 0; i < cnt / 2; i++) { long t = v[i]; v[i] = v[cnt - i - 1]; v[cnt - i - 1] = t; } // Base condition of dp1 and dp2 dp1[0] = 1; dp2[0] = (v[0] - 1) / 2; // Iterate from 1 to cnt for(int i = 1; i < cnt; i++) { // Calculate dp1[] dp1[i] = dp1[i - 1] + dp2[i - 1]; // Calculate dp2[] dp2[i] = ((v[i] - v[i - 1]) / 2) * dp2[i - 1] + ((v[i] - v[i - 1] - 1) / 2) * dp1[i - 1]; } // Return final ans return (dp1[cnt - 1] + dp2[cnt - 1]); } // Driver codestatic void Main(){ // Function call to generate the // fibonacci numbers fibonacci(); // Given number int num = 13; // Function call Console.Write(find(num));}} // This code is contributed by divyeshrabadiya07",
"e": 35843,
"s": 34125,
"text": null
},
{
"code": "<script> // Javascript program for the above approachvar fib = Array(101).fill(0);var dp1 = Array(101).fill(0);var dp2 = Array(101).fill(0);var v = Array(101).fill(0); // Function to generate the// fibonacci numberfunction fibonacci(){ // First two number of // fibonacci sequence fib[1] = 1; fib[2] = 2; for(i = 3; i <= 87; i++) { fib[i] = fib[i - 1] + fib[i - 2]; }} // Function to find maximum ways to// represent num as the sum of// fibonacci numberfunction find(num){ var cnt = 0; // Generate the Canonical form // of given number for(i = 87; i > 0; i--) { if (num >= fib[i]) { v[cnt++] = i; num -= fib[i]; } } // Reverse the number for(i = 0; i < cnt / 2; i++) { var t = v[i]; v[i] = v[cnt - i - 1]; v[cnt - i - 1] = t; } // Base condition of dp1 and dp2 dp1[0] = 1; dp2[0] = parseInt((v[0] - 1) / 2); // Iterate from 1 to cnt for(i = 1; i < cnt; i++) { // Calculate dp1 dp1[i] = dp1[i - 1] + dp2[i - 1]; // Calculate dp2 dp2[i] = parseInt((v[i] - v[i - 1]) / 2) * dp2[i - 1] + parseInt((v[i] - v[i - 1] - 1) / 2) * dp1[i - 1]; } // Return final ans return (dp1[cnt - 1] + dp2[cnt - 1]);} // Driver code // Function call to generate the// fibonacci numbersfibonacci(); // Given numbervar num = 13; // Function calldocument.write(find(num)); // This code is contributed by todaysgaurav </script>",
"e": 37414,
"s": 35843,
"text": null
},
{
"code": null,
"e": 37416,
"s": 37414,
"text": "3"
},
{
"code": null,
"e": 37469,
"s": 37418,
"text": "Time Complexity: O(log N)Auxiliary Space: O(log N)"
},
{
"code": null,
"e": 37483,
"s": 37469,
"text": "SHIVAMSINGH67"
},
{
"code": null,
"e": 37491,
"s": 37483,
"text": "offbeat"
},
{
"code": null,
"e": 37509,
"s": 37491,
"text": "divyeshrabadiya07"
},
{
"code": null,
"e": 37522,
"s": 37509,
"text": "todaysgaurav"
},
{
"code": null,
"e": 37532,
"s": 37522,
"text": "kk9826225"
},
{
"code": null,
"e": 37563,
"s": 37532,
"text": "Algorithms-Dynamic Programming"
},
{
"code": null,
"e": 37573,
"s": 37563,
"text": "Fibonacci"
},
{
"code": null,
"e": 37579,
"s": 37573,
"text": "Maths"
},
{
"code": null,
"e": 37593,
"s": 37579,
"text": "Combinatorial"
},
{
"code": null,
"e": 37613,
"s": 37593,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 37626,
"s": 37613,
"text": "Mathematical"
},
{
"code": null,
"e": 37646,
"s": 37626,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 37659,
"s": 37646,
"text": "Mathematical"
},
{
"code": null,
"e": 37669,
"s": 37659,
"text": "Fibonacci"
},
{
"code": null,
"e": 37683,
"s": 37669,
"text": "Combinatorial"
},
{
"code": null,
"e": 37781,
"s": 37683,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 37853,
"s": 37781,
"text": "Ways to sum to N using Natural Numbers up to K with repetitions allowed"
},
{
"code": null,
"e": 37883,
"s": 37853,
"text": "Combinations with repetitions"
},
{
"code": null,
"e": 37946,
"s": 37883,
"text": "Generate all possible combinations of K numbers that sums to N"
},
{
"code": null,
"e": 37985,
"s": 37946,
"text": "Largest substring with same Characters"
},
{
"code": null,
"e": 38063,
"s": 37985,
"text": "Generate all possible combinations of at most X characters from a given array"
},
{
"code": null,
"e": 38103,
"s": 38063,
"text": "Largest Independent Set Problem | DP-26"
},
{
"code": null,
"e": 38129,
"s": 38103,
"text": "Word Wrap Problem | DP-19"
},
{
"code": null,
"e": 38155,
"s": 38129,
"text": "Partition problem | DP-18"
},
{
"code": null,
"e": 38177,
"s": 38155,
"text": "Sieve of Eratosthenes"
}
] |
Java - String compareTo() Method | This method compares this String to another Object.
Here is the syntax of this method −
int compareTo(Object o)
Here is the detail of parameters −
O − the Object to be compared.
O − the Object to be compared.
The value 0 if the argument is a string lexicographically equal to this string; a value less than 0 if the argument is a string lexicographically greater than this string; and a value greater than 0 if the argument is a string lexicographically less than this string.
The value 0 if the argument is a string lexicographically equal to this string; a value less than 0 if the argument is a string lexicographically greater than this string; and a value greater than 0 if the argument is a string lexicographically less than this string.
public class Test {
public static void main(String args[]) {
String str1 = "Strings are immutable";
String str2 = new String("Strings are immutable");
String str3 = new String("Integers are not immutable");
int result = str1.compareTo( str2 );
System.out.println(result);
result = str2.compareTo( str3 );
System.out.println(result);
}
}
This will produce the following result −
0
10
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": 2429,
"s": 2377,
"text": "This method compares this String to another Object."
},
{
"code": null,
"e": 2465,
"s": 2429,
"text": "Here is the syntax of this method −"
},
{
"code": null,
"e": 2490,
"s": 2465,
"text": "int compareTo(Object o)\n"
},
{
"code": null,
"e": 2525,
"s": 2490,
"text": "Here is the detail of parameters −"
},
{
"code": null,
"e": 2556,
"s": 2525,
"text": "O − the Object to be compared."
},
{
"code": null,
"e": 2587,
"s": 2556,
"text": "O − the Object to be compared."
},
{
"code": null,
"e": 2855,
"s": 2587,
"text": "The value 0 if the argument is a string lexicographically equal to this string; a value less than 0 if the argument is a string lexicographically greater than this string; and a value greater than 0 if the argument is a string lexicographically less than this string."
},
{
"code": null,
"e": 3123,
"s": 2855,
"text": "The value 0 if the argument is a string lexicographically equal to this string; a value less than 0 if the argument is a string lexicographically greater than this string; and a value greater than 0 if the argument is a string lexicographically less than this string."
},
{
"code": null,
"e": 3523,
"s": 3123,
"text": "public class Test {\n\n public static void main(String args[]) {\n String str1 = \"Strings are immutable\";\n String str2 = new String(\"Strings are immutable\");\n String str3 = new String(\"Integers are not immutable\");\n \n int result = str1.compareTo( str2 );\n System.out.println(result);\n \n result = str2.compareTo( str3 );\n System.out.println(result);\n }\n}"
},
{
"code": null,
"e": 3564,
"s": 3523,
"text": "This will produce the following result −"
},
{
"code": null,
"e": 3570,
"s": 3564,
"text": "0\n10\n"
},
{
"code": null,
"e": 3603,
"s": 3570,
"text": "\n 16 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 3619,
"s": 3603,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 3652,
"s": 3619,
"text": "\n 19 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 3668,
"s": 3652,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 3703,
"s": 3668,
"text": "\n 25 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 3717,
"s": 3703,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 3751,
"s": 3717,
"text": "\n 126 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 3765,
"s": 3751,
"text": " Tushar Kale"
},
{
"code": null,
"e": 3802,
"s": 3765,
"text": "\n 119 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 3817,
"s": 3802,
"text": " Monica Mittal"
},
{
"code": null,
"e": 3850,
"s": 3817,
"text": "\n 76 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 3869,
"s": 3850,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 3876,
"s": 3869,
"text": " Print"
},
{
"code": null,
"e": 3887,
"s": 3876,
"text": " Add Notes"
}
] |
Angular 8 - Authentication and Authorization | Authentication is the process matching the visitor of a web application with the pre-defined set of user identity in the system. In other word, it is the process of recognizing the user’s identity. Authentication is very important process in the system with respect to security.
Authorization is the process of giving permission to the user to access certain resource in the system. Only the authenticated user can be authorised to access a resource.
Let us learn how to do Authentication and Authorization in Angular application in this chapter.
In a web application, a resource is referred by url. Every user in the system will be allowed access a set of urls. For example, an administrator may be assigned all the url coming under administration section.
As we know already, URLs are handled by Routing. Angular routing enables the urls to be guarded and restricted based on programming logic. So, a url may be denied for a normal user and allowed for an administrator.
Angular provides a concept called Router Guards which can be used to prevent unauthorised access to certain part of the application through routing. Angular provides multiple guards and they are as follows:
CanActivate − Used to stop the access to a route.
CanActivate − Used to stop the access to a route.
CanActivateChild − Used to stop the access to a child route.
CanActivateChild − Used to stop the access to a child route.
CanDeactivate − Used to stop ongoing process getting feedback from user. For example, delete process can be stop if the user replies in negative.
CanDeactivate − Used to stop ongoing process getting feedback from user. For example, delete process can be stop if the user replies in negative.
Resolve − Used to pre-fetch the data before navigating to the route.
Resolve − Used to pre-fetch the data before navigating to the route.
CanLoad − Used to load assets.
CanLoad − Used to load assets.
Let us try to add login functionality to our application and secure it using CanActivate guard.
Open command prompt and go to project root folder.
cd /go/to/expense-manager
Start the application.
ng serve
Create a new service, AuthService to authenticate the user.
ng generate service auth
CREATE src/app/auth.service.spec.ts (323 bytes)
CREATE src/app/auth.service.ts (133 bytes)
Open AuthService and include below code.
import { Injectable } from '@angular/core';
import { Observable, of } from 'rxjs';
import { tap, delay } from 'rxjs/operators';
@Injectable({
providedIn: 'root'
})
export class AuthService {
isUserLoggedIn: boolean = false;
login(userName: string, password: string): Observable {
console.log(userName);
console.log(password);
this.isUserLoggedIn = userName == 'admin' && password == 'admin';
localStorage.setItem('isUserLoggedIn', this.isUserLoggedIn ? "true" : "false");
return of(this.isUserLoggedIn).pipe(
delay(1000),
tap(val => {
console.log("Is User Authentication is successful: " + val);
})
);
}
logout(): void {
this.isUserLoggedIn = false;
localStorage.removeItem('isUserLoggedIn');
}
constructor() { }
}
Here,
We have written two methods, login and logout.
We have written two methods, login and logout.
The purpose of the login method is to validate the user and if the user successfully validated, it stores the information in localStorage and then returns true.
The purpose of the login method is to validate the user and if the user successfully validated, it stores the information in localStorage and then returns true.
Authentication validation is that the user name and password should be admin.
Authentication validation is that the user name and password should be admin.
We have not used any backend. Instead, we have simulated a delay of 1s using Observables.
We have not used any backend. Instead, we have simulated a delay of 1s using Observables.
The purpose of the logout method is to invalidate the user and removes the information stored in localStorage.
The purpose of the logout method is to invalidate the user and removes the information stored in localStorage.
Create a login component using below command −
ng generate component login
CREATE src/app/login/login.component.html (20 bytes)
CREATE src/app/login/login.component.spec.ts (621 bytes)
CREATE src/app/login/login.component.ts (265 bytes)
CREATE src/app/login/login.component.css (0 bytes)
UPDATE src/app/app.module.ts (1207 bytes)
Open LoginComponent and include below code −
import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl } from '@angular/forms';
import { AuthService } from '../auth.service';
import { Router } from '@angular/router';
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
userName: string;
password: string;
formData: FormGroup;
constructor(private authService : AuthService, private router : Router) { }
ngOnInit() {
this.formData = new FormGroup({
userName: new FormControl("admin"),
password: new FormControl("admin"),
});
}
onClickSubmit(data: any) {
this.userName = data.userName;
this.password = data.password;
console.log("Login page: " + this.userName);
console.log("Login page: " + this.password);
this.authService.login(this.userName, this.password)
.subscribe( data => {
console.log("Is Login Success: " + data);
if(data) this.router.navigate(['/expenses']);
});
}
}
Here,
Used reactive forms.
Used reactive forms.
Imported AuthService and Router and configured it in constructor.
Imported AuthService and Router and configured it in constructor.
Created an instance of FormGroup and included two instance of FormControl, one for user name and another for password.
Created an instance of FormGroup and included two instance of FormControl, one for user name and another for password.
Created a onClickSubmit to validate the user using authService and if successful, navigate to expense list.
Created a onClickSubmit to validate the user using authService and if successful, navigate to expense list.
Open LoginComponent template and include below template code.
<!-- Page Content -->
<div class="container">
<div class="row">
<div class="col-lg-12 text-center" style="padding-top: 20px;">
<div class="container box" style="margin-top: 10px; padding-left: 0px; padding-right: 0px;">
<div class="row">
<div class="col-12" style="text-align: center;">
<form [formGroup]="formData" (ngSubmit)="onClickSubmit(formData.value)"
class="form-signin">
<h2 class="form-signin-heading">Please sign in</h2>
<label for="inputEmail" class="sr-only">Email address</label>
<input type="text" id="username" class="form-control"
formControlName="userName" placeholder="Username" required autofocus>
<label for="inputPassword" class="sr-only">Password</label>
<input type="password" id="inputPassword" class="form-control"
formControlName="password" placeholder="Password" required>
<button class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
Here,
Created a reactive form and designed a login form.
Attached the onClickSubmit method to the form submit action.
Open LoginComponent style and include below CSS Code.
.form-signin {
max-width: 330px;
padding: 15px;
margin: 0 auto;
}
input {
margin-bottom: 20px;
}
Here, some styles are added to design the login form.
Create a logout component using below command −
ng generate component logout
CREATE src/app/logout/logout.component.html (21 bytes)
CREATE src/app/logout/logout.component.spec.ts (628 bytes)
CREATE src/app/logout/logout.component.ts (269 bytes)
CREATE src/app/logout/logout.component.css (0 bytes)
UPDATE src/app/app.module.ts (1368 bytes)
Open LogoutComponent and include below code.
import { Component, OnInit } from '@angular/core';
import { AuthService } from '../auth.service';
import { Router } from '@angular/router';
@Component({
selector: 'app-logout',
templateUrl: './logout.component.html',
styleUrls: ['./logout.component.css']
})
export class LogoutComponent implements OnInit {
constructor(private authService : AuthService, private router: Router) { }
ngOnInit() {
this.authService.logout();
this.router.navigate(['/']);
}
}
Here,
Used logout method of AuthService.
Once the user is logged out, the page will redirect to home page (/).
Create a guard using below command −
ng generate guard expense
CREATE src/app/expense.guard.spec.ts (364 bytes)
CREATE src/app/expense.guard.ts (459 bytes)
Open ExpenseGuard and include below code −
import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router, UrlTree } from '@angular/router';
import { Observable } from 'rxjs';
import { AuthService } from './auth.service';
@Injectable({
providedIn: 'root'
})
export class ExpenseGuard implements CanActivate {
constructor(private authService: AuthService, private router: Router) {}
canActivate(
next: ActivatedRouteSnapshot,
state: RouterStateSnapshot): boolean | UrlTree {
let url: string = state.url;
return this.checkLogin(url);
}
checkLogin(url: string): true | UrlTree {
console.log("Url: " + url)
let val: string = localStorage.getItem('isUserLoggedIn');
if(val != null && val == "true"){
if(url == "/login")
this.router.parseUrl('/expenses');
else
return true;
} else {
return this.router.parseUrl('/login');
}
}
}
Here,
checkLogin will check whether the localStorage has the user information and if it is available, then it returns true.
If the user is logged in and goes to login page, it will redirect the user to expenses page
If the user is not logged in, then the user will be redirected to login page.
Open AppRoutingModule (src/app/app-routing.module.ts) and update below code −
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { ExpenseEntryComponent } from './expense-entry/expense-entry.component';
import { ExpenseEntryListComponent } from './expense-entry-list/expense-entry-list.component';
import { LoginComponent } from './login/login.component';
import { LogoutComponent } from './logout/logout.component';
import { ExpenseGuard } from './expense.guard';
const routes: Routes = [
{ path: 'login', component: LoginComponent },
{ path: 'logout', component: LogoutComponent },
{ path: 'expenses', component: ExpenseEntryListComponent, canActivate: [ExpenseGuard]},
{ path: 'expenses/detail/:id', component: ExpenseEntryComponent, canActivate: [ExpenseGuard]},
{ path: '', redirectTo: 'expenses', pathMatch: 'full' }
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
Here,
Imported LoginComponent and LogoutComponent.
Imported ExpenseGuard.
Created two new routes, login and logout to access LoginComponent and LogoutComponent respectively.
Add new option canActivate for ExpenseEntryComponent and ExpenseEntryListComponent.
Open AppComponent template and add two login and logout link.
<div class="collapse navbar-collapse" id="navbarResponsive">
<ul class="navbar-nav ml-auto">
<li class="nav-item active">
<a class="nav-link" href="#">Home
<span class="sr-only" routerLink="/">(current)</span>
</a>
</li>
<li class="nav-item">
<a class="nav-link" routerLink="/expenses">Report</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Add Expense</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">About</a>
</li>
<li class="nav-item">
<div *ngIf="isUserLoggedIn; else isLogOut">
<a class="nav-link" routerLink="/logout">Logout</a>
</div>
<ng-template #isLogOut>
<a class="nav-link" routerLink="/login">Login</a>
</ng-template>
</li>
</ul>
</div>
Open AppComponent and update below code −
import { Component } from '@angular/core';
import { AuthService } from './auth.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'Expense Manager';
isUserLoggedIn = false;
constructor(private authService: AuthService) {}
ngOnInit() {
let storeData = localStorage.getItem("isUserLoggedIn");
console.log("StoreData: " + storeData);
if( storeData != null && storeData == "true")
this.isUserLoggedIn = true;
else
this.isUserLoggedIn = false;
}
}
Here, we have added the logic to identify the user status so that we can show login / logout functionality.
Open AppModule (src/app/app.module.ts) and configure ReactiveFormsModule
import { ReactiveFormsModule } from '@angular/forms';
imports: [
ReactiveFormsModule
]
Now, run the application and the application opens the login page.
Enter admin and admin as username and password and then, click submit. The application process the login and redirects the user to expense list page as shown below −
Finally, your can click logout and exit the application.
16 Lectures
1.5 hours
Anadi Sharma
28 Lectures
2.5 hours
Anadi Sharma
11 Lectures
7.5 hours
SHIVPRASAD KOIRALA
16 Lectures
2.5 hours
Frahaan Hussain
69 Lectures
5 hours
Senol Atac
53 Lectures
3.5 hours
Senol Atac
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2667,
"s": 2388,
"text": "Authentication is the process matching the visitor of a web application with the pre-defined set of user identity in the system. In other word, it is the process of recognizing the user’s identity. Authentication is very important process in the system with respect to security."
},
{
"code": null,
"e": 2839,
"s": 2667,
"text": "Authorization is the process of giving permission to the user to access certain resource in the system. Only the authenticated user can be authorised to access a resource."
},
{
"code": null,
"e": 2935,
"s": 2839,
"text": "Let us learn how to do Authentication and Authorization in Angular application in this chapter."
},
{
"code": null,
"e": 3146,
"s": 2935,
"text": "In a web application, a resource is referred by url. Every user in the system will be allowed access a set of urls. For example, an administrator may be assigned all the url coming under administration section."
},
{
"code": null,
"e": 3361,
"s": 3146,
"text": "As we know already, URLs are handled by Routing. Angular routing enables the urls to be guarded and restricted based on programming logic. So, a url may be denied for a normal user and allowed for an administrator."
},
{
"code": null,
"e": 3568,
"s": 3361,
"text": "Angular provides a concept called Router Guards which can be used to prevent unauthorised access to certain part of the application through routing. Angular provides multiple guards and they are as follows:"
},
{
"code": null,
"e": 3618,
"s": 3568,
"text": "CanActivate − Used to stop the access to a route."
},
{
"code": null,
"e": 3668,
"s": 3618,
"text": "CanActivate − Used to stop the access to a route."
},
{
"code": null,
"e": 3729,
"s": 3668,
"text": "CanActivateChild − Used to stop the access to a child route."
},
{
"code": null,
"e": 3790,
"s": 3729,
"text": "CanActivateChild − Used to stop the access to a child route."
},
{
"code": null,
"e": 3936,
"s": 3790,
"text": "CanDeactivate − Used to stop ongoing process getting feedback from user. For example, delete process can be stop if the user replies in negative."
},
{
"code": null,
"e": 4082,
"s": 3936,
"text": "CanDeactivate − Used to stop ongoing process getting feedback from user. For example, delete process can be stop if the user replies in negative."
},
{
"code": null,
"e": 4151,
"s": 4082,
"text": "Resolve − Used to pre-fetch the data before navigating to the route."
},
{
"code": null,
"e": 4220,
"s": 4151,
"text": "Resolve − Used to pre-fetch the data before navigating to the route."
},
{
"code": null,
"e": 4251,
"s": 4220,
"text": "CanLoad − Used to load assets."
},
{
"code": null,
"e": 4282,
"s": 4251,
"text": "CanLoad − Used to load assets."
},
{
"code": null,
"e": 4378,
"s": 4282,
"text": "Let us try to add login functionality to our application and secure it using CanActivate guard."
},
{
"code": null,
"e": 4429,
"s": 4378,
"text": "Open command prompt and go to project root folder."
},
{
"code": null,
"e": 4455,
"s": 4429,
"text": "cd /go/to/expense-manager"
},
{
"code": null,
"e": 4478,
"s": 4455,
"text": "Start the application."
},
{
"code": null,
"e": 4487,
"s": 4478,
"text": "ng serve"
},
{
"code": null,
"e": 4547,
"s": 4487,
"text": "Create a new service, AuthService to authenticate the user."
},
{
"code": null,
"e": 4663,
"s": 4547,
"text": "ng generate service auth\nCREATE src/app/auth.service.spec.ts (323 bytes)\nCREATE src/app/auth.service.ts (133 bytes)"
},
{
"code": null,
"e": 4704,
"s": 4663,
"text": "Open AuthService and include below code."
},
{
"code": null,
"e": 5517,
"s": 4704,
"text": "import { Injectable } from '@angular/core';\n\nimport { Observable, of } from 'rxjs';\nimport { tap, delay } from 'rxjs/operators';\n\n@Injectable({\n providedIn: 'root'\n})\nexport class AuthService {\n\n isUserLoggedIn: boolean = false;\n\n login(userName: string, password: string): Observable {\n console.log(userName);\n console.log(password);\n this.isUserLoggedIn = userName == 'admin' && password == 'admin';\n localStorage.setItem('isUserLoggedIn', this.isUserLoggedIn ? \"true\" : \"false\"); \n\n return of(this.isUserLoggedIn).pipe(\n delay(1000),\n tap(val => { \n console.log(\"Is User Authentication is successful: \" + val); \n })\n );\n }\n\n logout(): void {\n this.isUserLoggedIn = false;\n localStorage.removeItem('isUserLoggedIn'); \n }\n\n constructor() { }\n}"
},
{
"code": null,
"e": 5523,
"s": 5517,
"text": "Here,"
},
{
"code": null,
"e": 5570,
"s": 5523,
"text": "We have written two methods, login and logout."
},
{
"code": null,
"e": 5617,
"s": 5570,
"text": "We have written two methods, login and logout."
},
{
"code": null,
"e": 5778,
"s": 5617,
"text": "The purpose of the login method is to validate the user and if the user successfully validated, it stores the information in localStorage and then returns true."
},
{
"code": null,
"e": 5939,
"s": 5778,
"text": "The purpose of the login method is to validate the user and if the user successfully validated, it stores the information in localStorage and then returns true."
},
{
"code": null,
"e": 6017,
"s": 5939,
"text": "Authentication validation is that the user name and password should be admin."
},
{
"code": null,
"e": 6095,
"s": 6017,
"text": "Authentication validation is that the user name and password should be admin."
},
{
"code": null,
"e": 6185,
"s": 6095,
"text": "We have not used any backend. Instead, we have simulated a delay of 1s using Observables."
},
{
"code": null,
"e": 6275,
"s": 6185,
"text": "We have not used any backend. Instead, we have simulated a delay of 1s using Observables."
},
{
"code": null,
"e": 6386,
"s": 6275,
"text": "The purpose of the logout method is to invalidate the user and removes the information stored in localStorage."
},
{
"code": null,
"e": 6497,
"s": 6386,
"text": "The purpose of the logout method is to invalidate the user and removes the information stored in localStorage."
},
{
"code": null,
"e": 6544,
"s": 6497,
"text": "Create a login component using below command −"
},
{
"code": null,
"e": 6827,
"s": 6544,
"text": "ng generate component login\nCREATE src/app/login/login.component.html (20 bytes)\nCREATE src/app/login/login.component.spec.ts (621 bytes)\nCREATE src/app/login/login.component.ts (265 bytes)\nCREATE src/app/login/login.component.css (0 bytes)\nUPDATE src/app/app.module.ts (1207 bytes)"
},
{
"code": null,
"e": 6872,
"s": 6827,
"text": "Open LoginComponent and include below code −"
},
{
"code": null,
"e": 7987,
"s": 6872,
"text": "import { Component, OnInit } from '@angular/core';\n\nimport { FormGroup, FormControl } from '@angular/forms';\nimport { AuthService } from '../auth.service';\nimport { Router } from '@angular/router';\n\n@Component({\n selector: 'app-login',\n templateUrl: './login.component.html',\n styleUrls: ['./login.component.css']\n})\nexport class LoginComponent implements OnInit {\n\n userName: string;\n password: string;\n formData: FormGroup;\n\n constructor(private authService : AuthService, private router : Router) { }\n\n ngOnInit() {\n this.formData = new FormGroup({\n userName: new FormControl(\"admin\"),\n password: new FormControl(\"admin\"),\n });\n }\n\n onClickSubmit(data: any) {\n this.userName = data.userName;\n this.password = data.password;\n\n console.log(\"Login page: \" + this.userName);\n console.log(\"Login page: \" + this.password);\n\n this.authService.login(this.userName, this.password)\n .subscribe( data => { \n console.log(\"Is Login Success: \" + data); \n \n if(data) this.router.navigate(['/expenses']); \n });\n }\n}"
},
{
"code": null,
"e": 7993,
"s": 7987,
"text": "Here,"
},
{
"code": null,
"e": 8014,
"s": 7993,
"text": "Used reactive forms."
},
{
"code": null,
"e": 8035,
"s": 8014,
"text": "Used reactive forms."
},
{
"code": null,
"e": 8101,
"s": 8035,
"text": "Imported AuthService and Router and configured it in constructor."
},
{
"code": null,
"e": 8167,
"s": 8101,
"text": "Imported AuthService and Router and configured it in constructor."
},
{
"code": null,
"e": 8286,
"s": 8167,
"text": "Created an instance of FormGroup and included two instance of FormControl, one for user name and another for password."
},
{
"code": null,
"e": 8405,
"s": 8286,
"text": "Created an instance of FormGroup and included two instance of FormControl, one for user name and another for password."
},
{
"code": null,
"e": 8513,
"s": 8405,
"text": "Created a onClickSubmit to validate the user using authService and if successful, navigate to expense list."
},
{
"code": null,
"e": 8621,
"s": 8513,
"text": "Created a onClickSubmit to validate the user using authService and if successful, navigate to expense list."
},
{
"code": null,
"e": 8683,
"s": 8621,
"text": "Open LoginComponent template and include below template code."
},
{
"code": null,
"e": 10121,
"s": 8683,
"text": "<!-- Page Content -->\n<div class=\"container\">\n <div class=\"row\">\n <div class=\"col-lg-12 text-center\" style=\"padding-top: 20px;\">\n <div class=\"container box\" style=\"margin-top: 10px; padding-left: 0px; padding-right: 0px;\">\n <div class=\"row\">\n <div class=\"col-12\" style=\"text-align: center;\">\n <form [formGroup]=\"formData\" (ngSubmit)=\"onClickSubmit(formData.value)\" \n class=\"form-signin\">\n <h2 class=\"form-signin-heading\">Please sign in</h2>\n <label for=\"inputEmail\" class=\"sr-only\">Email address</label>\n <input type=\"text\" id=\"username\" class=\"form-control\" \n formControlName=\"userName\" placeholder=\"Username\" required autofocus>\n <label for=\"inputPassword\" class=\"sr-only\">Password</label>\n <input type=\"password\" id=\"inputPassword\" class=\"form-control\" \n formControlName=\"password\" placeholder=\"Password\" required>\n <button class=\"btn btn-lg btn-primary btn-block\" type=\"submit\">Sign in</button>\n </form>\n </div>\n </div>\n </div>\n </div>\n </div>\n</div>"
},
{
"code": null,
"e": 10127,
"s": 10121,
"text": "Here,"
},
{
"code": null,
"e": 10178,
"s": 10127,
"text": "Created a reactive form and designed a login form."
},
{
"code": null,
"e": 10239,
"s": 10178,
"text": "Attached the onClickSubmit method to the form submit action."
},
{
"code": null,
"e": 10293,
"s": 10239,
"text": "Open LoginComponent style and include below CSS Code."
},
{
"code": null,
"e": 10404,
"s": 10293,
"text": ".form-signin {\n max-width: 330px;\n\n padding: 15px;\n margin: 0 auto;\n}\n\ninput {\n margin-bottom: 20px;\n}"
},
{
"code": null,
"e": 10458,
"s": 10404,
"text": "Here, some styles are added to design the login form."
},
{
"code": null,
"e": 10506,
"s": 10458,
"text": "Create a logout component using below command −"
},
{
"code": null,
"e": 10798,
"s": 10506,
"text": "ng generate component logout\nCREATE src/app/logout/logout.component.html (21 bytes)\nCREATE src/app/logout/logout.component.spec.ts (628 bytes)\nCREATE src/app/logout/logout.component.ts (269 bytes)\nCREATE src/app/logout/logout.component.css (0 bytes)\nUPDATE src/app/app.module.ts (1368 bytes)"
},
{
"code": null,
"e": 10843,
"s": 10798,
"text": "Open LogoutComponent and include below code."
},
{
"code": null,
"e": 11333,
"s": 10843,
"text": "import { Component, OnInit } from '@angular/core';\n\nimport { AuthService } from '../auth.service';\nimport { Router } from '@angular/router';\n\n@Component({\n selector: 'app-logout',\n templateUrl: './logout.component.html',\n styleUrls: ['./logout.component.css']\n})\nexport class LogoutComponent implements OnInit {\n\n constructor(private authService : AuthService, private router: Router) { }\n\n ngOnInit() {\n this.authService.logout();\n this.router.navigate(['/']);\n }\n\n}"
},
{
"code": null,
"e": 11339,
"s": 11333,
"text": "Here,"
},
{
"code": null,
"e": 11374,
"s": 11339,
"text": "Used logout method of AuthService."
},
{
"code": null,
"e": 11444,
"s": 11374,
"text": "Once the user is logged out, the page will redirect to home page (/)."
},
{
"code": null,
"e": 11481,
"s": 11444,
"text": "Create a guard using below command −"
},
{
"code": null,
"e": 11600,
"s": 11481,
"text": "ng generate guard expense\nCREATE src/app/expense.guard.spec.ts (364 bytes)\nCREATE src/app/expense.guard.ts (459 bytes)"
},
{
"code": null,
"e": 11643,
"s": 11600,
"text": "Open ExpenseGuard and include below code −"
},
{
"code": null,
"e": 12645,
"s": 11643,
"text": "import { Injectable } from '@angular/core';\nimport { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router, UrlTree } from '@angular/router';\nimport { Observable } from 'rxjs';\n\nimport { AuthService } from './auth.service';\n\n@Injectable({\n providedIn: 'root'\n})\nexport class ExpenseGuard implements CanActivate {\n\n constructor(private authService: AuthService, private router: Router) {}\n\n canActivate(\n next: ActivatedRouteSnapshot,\n state: RouterStateSnapshot): boolean | UrlTree {\n let url: string = state.url;\n\n return this.checkLogin(url);\n }\n\n checkLogin(url: string): true | UrlTree {\n console.log(\"Url: \" + url)\n let val: string = localStorage.getItem('isUserLoggedIn');\n\n if(val != null && val == \"true\"){\n if(url == \"/login\")\n this.router.parseUrl('/expenses');\n else \n return true;\n } else {\n return this.router.parseUrl('/login');\n }\n }\n}"
},
{
"code": null,
"e": 12651,
"s": 12645,
"text": "Here,"
},
{
"code": null,
"e": 12769,
"s": 12651,
"text": "checkLogin will check whether the localStorage has the user information and if it is available, then it returns true."
},
{
"code": null,
"e": 12861,
"s": 12769,
"text": "If the user is logged in and goes to login page, it will redirect the user to expenses page"
},
{
"code": null,
"e": 12939,
"s": 12861,
"text": "If the user is not logged in, then the user will be redirected to login page."
},
{
"code": null,
"e": 13017,
"s": 12939,
"text": "Open AppRoutingModule (src/app/app-routing.module.ts) and update below code −"
},
{
"code": null,
"e": 13955,
"s": 13017,
"text": "import { NgModule } from '@angular/core';\nimport { Routes, RouterModule } from '@angular/router';\nimport { ExpenseEntryComponent } from './expense-entry/expense-entry.component';\nimport { ExpenseEntryListComponent } from './expense-entry-list/expense-entry-list.component';\nimport { LoginComponent } from './login/login.component';\nimport { LogoutComponent } from './logout/logout.component';\n\nimport { ExpenseGuard } from './expense.guard';\n\nconst routes: Routes = [\n { path: 'login', component: LoginComponent },\n { path: 'logout', component: LogoutComponent },\n { path: 'expenses', component: ExpenseEntryListComponent, canActivate: [ExpenseGuard]},\n { path: 'expenses/detail/:id', component: ExpenseEntryComponent, canActivate: [ExpenseGuard]},\n { path: '', redirectTo: 'expenses', pathMatch: 'full' }\n];\n\n@NgModule({\n imports: [RouterModule.forRoot(routes)],\n exports: [RouterModule]\n})\nexport class AppRoutingModule { }"
},
{
"code": null,
"e": 13961,
"s": 13955,
"text": "Here,"
},
{
"code": null,
"e": 14006,
"s": 13961,
"text": "Imported LoginComponent and LogoutComponent."
},
{
"code": null,
"e": 14029,
"s": 14006,
"text": "Imported ExpenseGuard."
},
{
"code": null,
"e": 14129,
"s": 14029,
"text": "Created two new routes, login and logout to access LoginComponent and LogoutComponent respectively."
},
{
"code": null,
"e": 14213,
"s": 14129,
"text": "Add new option canActivate for ExpenseEntryComponent and ExpenseEntryListComponent."
},
{
"code": null,
"e": 14275,
"s": 14213,
"text": "Open AppComponent template and add two login and logout link."
},
{
"code": null,
"e": 15203,
"s": 14275,
"text": "<div class=\"collapse navbar-collapse\" id=\"navbarResponsive\">\n <ul class=\"navbar-nav ml-auto\">\n <li class=\"nav-item active\">\n <a class=\"nav-link\" href=\"#\">Home\n <span class=\"sr-only\" routerLink=\"/\">(current)</span>\n\n </a>\n </li>\n <li class=\"nav-item\">\n <a class=\"nav-link\" routerLink=\"/expenses\">Report</a>\n </li>\n <li class=\"nav-item\">\n <a class=\"nav-link\" href=\"#\">Add Expense</a>\n </li>\n <li class=\"nav-item\">\n\n <a class=\"nav-link\" href=\"#\">About</a>\n </li>\n <li class=\"nav-item\">\n <div *ngIf=\"isUserLoggedIn; else isLogOut\">\n <a class=\"nav-link\" routerLink=\"/logout\">Logout</a>\n </div>\n\n <ng-template #isLogOut>\n <a class=\"nav-link\" routerLink=\"/login\">Login</a>\n </ng-template>\n </li>\n </ul>\n</div>"
},
{
"code": null,
"e": 15245,
"s": 15203,
"text": "Open AppComponent and update below code −"
},
{
"code": null,
"e": 15867,
"s": 15245,
"text": "import { Component } from '@angular/core';\n\nimport { AuthService } from './auth.service';\n\n@Component({\n selector: 'app-root',\n templateUrl: './app.component.html',\n styleUrls: ['./app.component.css']\n})\nexport class AppComponent {\n\n title = 'Expense Manager';\n isUserLoggedIn = false;\n\n constructor(private authService: AuthService) {}\n\n ngOnInit() {\n let storeData = localStorage.getItem(\"isUserLoggedIn\");\n console.log(\"StoreData: \" + storeData);\n\n if( storeData != null && storeData == \"true\")\n this.isUserLoggedIn = true;\n else\n\n\n this.isUserLoggedIn = false;\n }\n}"
},
{
"code": null,
"e": 15975,
"s": 15867,
"text": "Here, we have added the logic to identify the user status so that we can show login / logout functionality."
},
{
"code": null,
"e": 16048,
"s": 15975,
"text": "Open AppModule (src/app/app.module.ts) and configure ReactiveFormsModule"
},
{
"code": null,
"e": 16141,
"s": 16048,
"text": "import { ReactiveFormsModule } from '@angular/forms'; \nimports: [ \n ReactiveFormsModule \n]"
},
{
"code": null,
"e": 16208,
"s": 16141,
"text": "Now, run the application and the application opens the login page."
},
{
"code": null,
"e": 16374,
"s": 16208,
"text": "Enter admin and admin as username and password and then, click submit. The application process the login and redirects the user to expense list page as shown below −"
},
{
"code": null,
"e": 16431,
"s": 16374,
"text": "Finally, your can click logout and exit the application."
},
{
"code": null,
"e": 16466,
"s": 16431,
"text": "\n 16 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 16480,
"s": 16466,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 16515,
"s": 16480,
"text": "\n 28 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 16529,
"s": 16515,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 16564,
"s": 16529,
"text": "\n 11 Lectures \n 7.5 hours \n"
},
{
"code": null,
"e": 16584,
"s": 16564,
"text": " SHIVPRASAD KOIRALA"
},
{
"code": null,
"e": 16619,
"s": 16584,
"text": "\n 16 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 16636,
"s": 16619,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 16669,
"s": 16636,
"text": "\n 69 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 16681,
"s": 16669,
"text": " Senol Atac"
},
{
"code": null,
"e": 16716,
"s": 16681,
"text": "\n 53 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 16728,
"s": 16716,
"text": " Senol Atac"
},
{
"code": null,
"e": 16735,
"s": 16728,
"text": " Print"
},
{
"code": null,
"e": 16746,
"s": 16735,
"text": " Add Notes"
}
] |
WiFi with Arduino – Connect to a Network | In order to use WiFi with Arduino Uno, or any other board, you may need to get a WiFi shield(unless you are using a board with built-in WiFi capabilities, like Arduino Uno WiFi). The WiFi shield, like any other shield, stacks up on your board, and provides access to the pins of Arduino on the shield itself.
You can read more about the WiFi shield here −
https://www.arduino.cc/en/pmwiki.php?n=Main/ArduinoWiFiShield
https://www.arduino.cc/en/pmwiki.php?n=Main/ArduinoWiFiShield
https://www.arduino.cc/en/Guide/ArduinoWiFiShield
https://www.arduino.cc/en/Guide/ArduinoWiFiShield
Assuming you have a WiFi shield with you, you will need the WiFi library to get started. You don’t need to download it separately; it will be built-in in your IDE. If you don’t get a compilation error at
#include <WiFi.h>
then your IDE contains the library.
In this article, we will walk through a built-in example of the WiFi library – Connect with WPA.You can find the example here.
Most networks you come across will have WPA2 encryption. If you create a hotspot field using your mobile phone, you will generally opt for WPA2 encryption and set a password.
We begin with the inclusion of the SPI and WiFi libraries (SPI because the shield uses SPI for communication).
#include <SPI.h>
#include <WiFi.h>
Next, we define some global variables, including SSID, password of the network you intend to connect your Arduino to and a status int.
char ssid[] = "yourNetwork"; // your network SSID (name)
char pass[] = "secretPassword"; // your network password
int status = WL_IDLE_STATUS; // the Wifi radio's status
Within the setup, we do the following −
Initialize Serial
Initialize Serial
Check for the presence of the WiFi shield
Check for the presence of the WiFi shield
Check if the fw_version of the shield is correct or needs to be upgraded
Check if the fw_version of the shield is correct or needs to be upgraded
Attempt to connect to the network using WiFi.begin()
Attempt to connect to the network using WiFi.begin()
Once connected, print details of the network (SSID, BSSID (MAC address of router),Signal strength or RSSI, and encryption type), using printCurrentNet()
Once connected, print details of the network (SSID, BSSID (MAC address of router),Signal strength or RSSI, and encryption type), using printCurrentNet()
Also, print the WiFi details (local IP and MAC address) using printWifiData()
Also, print the WiFi details (local IP and MAC address) using printWifiData()
Within the loop, we just keep network details every 10 seconds using printCurrentNet()
void setup() {
//Initialize serial and wait for port to open:
Serial.begin(9600);
while (!Serial) {
; // wait for serial port to connect. Needed for native USB port only
}
// check for the presence of the shield:
if (WiFi.status() == WL_NO_SHIELD) {
Serial.println("WiFi shield not present");
// don't continue:
while (true);
}
String fv = WiFi.firmwareVersion();
if (fv != "1.1.0") {
Serial.println("Please upgrade the firmware");
}
// attempt to connect to Wifi network:
while (status != WL_CONNECTED) {
Serial.print("Attempting to connect to WPA SSID: ");
Serial.println(ssid);
// Connect to WPA/WPA2 network:
status = WiFi.begin(ssid, pass);
// wait 10 seconds for connection:
delay(10000);
}
// you're connected now, so print out the data:
Serial.print("You're connected to the network");
printCurrentNet();
printWifiData();
}
void loop() {
// check the network connection once every 10 seconds:
delay(10000);
printCurrentNet();
}
void printWifiData() {
// print your WiFi shield's IP address:
IPAddress ip = WiFi.localIP();
Serial.print("IP Address: ");
Serial.println(ip);
Serial.println(ip);
// print your MAC address:
byte mac[6];
WiFi.macAddress(mac);
Serial.print("MAC address: ");
Serial.print(mac[5], HEX);
Serial.print(":");
Serial.print(mac[4], HEX);
Serial.print(":");
Serial.print(mac[3], HEX);
Serial.print(":");
Serial.print(mac[2], HEX);
Serial.print(":");
Serial.print(mac[1], HEX);
Serial.print(":");
Serial.println(mac[0], HEX);
}
void printCurrentNet() {
// print the SSID of the network you're attached to:
Serial.print("SSID: ");
Serial.println(WiFi.SSID());
// print the MAC address of the router you're attached to:
byte bssid[6];
WiFi.BSSID(bssid);
Serial.print("BSSID: ");
Serial.print(bssid[5], HEX);
Serial.print(":");
Serial.print(bssid[4], HEX);
Serial.print(":");
Serial.print(bssid[3], HEX);
Serial.print(":");
Serial.print(bssid[2], HEX);
Serial.print(":");
Serial.print(bssid[1], HEX);
Serial.print(":");
Serial.println(bssid[0], HEX);
// print the received signal strength:
long rssi = WiFi.RSSI();
Serial.print("signal strength (RSSI):");
Serial.println(rssi);
// print the encryption type:
byte encryption = WiFi.encryptionType();
Serial.print("Encryption Type:");
Serial.println(encryption, HEX);
Serial.println();
}
Note that the MAC address of the WiFi and the router (WiFi.macAddress() and WiFi.BSSID()) is stored in 6-byte array, and each byte is printed in the hex format one by one. The difference between the two is that WiFi.macAddress() gives you the MAC address of your device (Arduino with WiFi shield), whereas WiFi.BSSID() gives you the MAC address of the router or the access point to which your device is connected. | [
{
"code": null,
"e": 1371,
"s": 1062,
"text": "In order to use WiFi with Arduino Uno, or any other board, you may need to get a WiFi shield(unless you are using a board with built-in WiFi capabilities, like Arduino Uno WiFi). The WiFi shield, like any other shield, stacks up on your board, and provides access to the pins of Arduino on the shield itself."
},
{
"code": null,
"e": 1418,
"s": 1371,
"text": "You can read more about the WiFi shield here −"
},
{
"code": null,
"e": 1480,
"s": 1418,
"text": "https://www.arduino.cc/en/pmwiki.php?n=Main/ArduinoWiFiShield"
},
{
"code": null,
"e": 1542,
"s": 1480,
"text": "https://www.arduino.cc/en/pmwiki.php?n=Main/ArduinoWiFiShield"
},
{
"code": null,
"e": 1592,
"s": 1542,
"text": "https://www.arduino.cc/en/Guide/ArduinoWiFiShield"
},
{
"code": null,
"e": 1642,
"s": 1592,
"text": "https://www.arduino.cc/en/Guide/ArduinoWiFiShield"
},
{
"code": null,
"e": 1846,
"s": 1642,
"text": "Assuming you have a WiFi shield with you, you will need the WiFi library to get started. You don’t need to download it separately; it will be built-in in your IDE. If you don’t get a compilation error at"
},
{
"code": null,
"e": 1864,
"s": 1846,
"text": "#include <WiFi.h>"
},
{
"code": null,
"e": 1900,
"s": 1864,
"text": "then your IDE contains the library."
},
{
"code": null,
"e": 2027,
"s": 1900,
"text": "In this article, we will walk through a built-in example of the WiFi library – Connect with WPA.You can find the example here."
},
{
"code": null,
"e": 2202,
"s": 2027,
"text": "Most networks you come across will have WPA2 encryption. If you create a hotspot field using your mobile phone, you will generally opt for WPA2 encryption and set a password."
},
{
"code": null,
"e": 2313,
"s": 2202,
"text": "We begin with the inclusion of the SPI and WiFi libraries (SPI because the shield uses SPI for communication)."
},
{
"code": null,
"e": 2348,
"s": 2313,
"text": "#include <SPI.h>\n#include <WiFi.h>"
},
{
"code": null,
"e": 2483,
"s": 2348,
"text": "Next, we define some global variables, including SSID, password of the network you intend to connect your Arduino to and a status int."
},
{
"code": null,
"e": 2661,
"s": 2483,
"text": "char ssid[] = \"yourNetwork\"; // your network SSID (name)\nchar pass[] = \"secretPassword\"; // your network password\nint status = WL_IDLE_STATUS; // the Wifi radio's status"
},
{
"code": null,
"e": 2701,
"s": 2661,
"text": "Within the setup, we do the following −"
},
{
"code": null,
"e": 2719,
"s": 2701,
"text": "Initialize Serial"
},
{
"code": null,
"e": 2737,
"s": 2719,
"text": "Initialize Serial"
},
{
"code": null,
"e": 2779,
"s": 2737,
"text": "Check for the presence of the WiFi shield"
},
{
"code": null,
"e": 2821,
"s": 2779,
"text": "Check for the presence of the WiFi shield"
},
{
"code": null,
"e": 2894,
"s": 2821,
"text": "Check if the fw_version of the shield is correct or needs to be upgraded"
},
{
"code": null,
"e": 2967,
"s": 2894,
"text": "Check if the fw_version of the shield is correct or needs to be upgraded"
},
{
"code": null,
"e": 3020,
"s": 2967,
"text": "Attempt to connect to the network using WiFi.begin()"
},
{
"code": null,
"e": 3073,
"s": 3020,
"text": "Attempt to connect to the network using WiFi.begin()"
},
{
"code": null,
"e": 3226,
"s": 3073,
"text": "Once connected, print details of the network (SSID, BSSID (MAC address of router),Signal strength or RSSI, and encryption type), using printCurrentNet()"
},
{
"code": null,
"e": 3379,
"s": 3226,
"text": "Once connected, print details of the network (SSID, BSSID (MAC address of router),Signal strength or RSSI, and encryption type), using printCurrentNet()"
},
{
"code": null,
"e": 3457,
"s": 3379,
"text": "Also, print the WiFi details (local IP and MAC address) using printWifiData()"
},
{
"code": null,
"e": 3535,
"s": 3457,
"text": "Also, print the WiFi details (local IP and MAC address) using printWifiData()"
},
{
"code": null,
"e": 3622,
"s": 3535,
"text": "Within the loop, we just keep network details every 10 seconds using printCurrentNet()"
},
{
"code": null,
"e": 6156,
"s": 3622,
"text": "void setup() {\n //Initialize serial and wait for port to open:\n Serial.begin(9600);\n while (!Serial) {\n ; // wait for serial port to connect. Needed for native USB port only\n }\n\n // check for the presence of the shield:\n if (WiFi.status() == WL_NO_SHIELD) {\n Serial.println(\"WiFi shield not present\");\n // don't continue:\n while (true);\n }\n\n String fv = WiFi.firmwareVersion();\n if (fv != \"1.1.0\") {\n Serial.println(\"Please upgrade the firmware\");\n }\n\n // attempt to connect to Wifi network:\n while (status != WL_CONNECTED) {\n Serial.print(\"Attempting to connect to WPA SSID: \");\n Serial.println(ssid);\n // Connect to WPA/WPA2 network:\n status = WiFi.begin(ssid, pass);\n // wait 10 seconds for connection:\n delay(10000);\n }\n\n // you're connected now, so print out the data:\n Serial.print(\"You're connected to the network\");\n printCurrentNet();\n printWifiData();\n}\n\nvoid loop() {\n // check the network connection once every 10 seconds:\n delay(10000);\n printCurrentNet();\n}\n\nvoid printWifiData() {\n // print your WiFi shield's IP address:\n IPAddress ip = WiFi.localIP();\n Serial.print(\"IP Address: \");\n Serial.println(ip);\n Serial.println(ip);\n // print your MAC address:\n byte mac[6];\n WiFi.macAddress(mac);\n Serial.print(\"MAC address: \");\n Serial.print(mac[5], HEX);\n Serial.print(\":\");\n Serial.print(mac[4], HEX);\n Serial.print(\":\");\n Serial.print(mac[3], HEX);\n Serial.print(\":\");\n Serial.print(mac[2], HEX);\n Serial.print(\":\");\n Serial.print(mac[1], HEX);\n Serial.print(\":\");\n Serial.println(mac[0], HEX);\n}\n\nvoid printCurrentNet() {\n // print the SSID of the network you're attached to:\n Serial.print(\"SSID: \");\n Serial.println(WiFi.SSID());\n // print the MAC address of the router you're attached to:\n byte bssid[6];\n WiFi.BSSID(bssid);\n Serial.print(\"BSSID: \");\n Serial.print(bssid[5], HEX);\n Serial.print(\":\");\n Serial.print(bssid[4], HEX);\n Serial.print(\":\");\n Serial.print(bssid[3], HEX);\n Serial.print(\":\");\n Serial.print(bssid[2], HEX);\n Serial.print(\":\");\n Serial.print(bssid[1], HEX);\n Serial.print(\":\");\n Serial.println(bssid[0], HEX);\n // print the received signal strength:\n long rssi = WiFi.RSSI();\n Serial.print(\"signal strength (RSSI):\");\n Serial.println(rssi);\n\n // print the encryption type:\n byte encryption = WiFi.encryptionType();\n Serial.print(\"Encryption Type:\");\n Serial.println(encryption, HEX);\n Serial.println();\n}"
},
{
"code": null,
"e": 6570,
"s": 6156,
"text": "Note that the MAC address of the WiFi and the router (WiFi.macAddress() and WiFi.BSSID()) is stored in 6-byte array, and each byte is printed in the hex format one by one. The difference between the two is that WiFi.macAddress() gives you the MAC address of your device (Arduino with WiFi shield), whereas WiFi.BSSID() gives you the MAC address of the router or the access point to which your device is connected."
}
] |
HTML <script> integrity Attribute - GeeksforGeeks | 27 Sep, 2021
The integrity attribute is used to give permission to the Browser to check the fetched script to make ensure the source code is never loaded. It is used to check that whether the third party has been altered the resource or not.
Subresource Integrity(SRI) is a security feature developed by w3comsortium which is used to give permission to a Browser to verify all the external scripts that would be fetched. It gives surety that the scripts are not altered by the third party.
The working process of SRI is going to follow the steps:
The webpage holds the hash value and on the other side, the server holds the .js file.
Now, the browser matches the hash value of the integrity attribute
In the end, if the value of hash matches then the file is used otherwise the file is blocked.
Syntax
<script integrity="filehash">
Attribute Values:
filehash:It indicates the hash value of the external script file.
Example 1:
HTML
<!DOCTYPE html><html> <head> <title> HTML script integrity Attribute </title></head> <body style="text-align:center;"> <h1> GeeksForGeeks </h1> <h2> HTML script integrity Attribute </h2> <script id="myGeeks" type="text/javascript" src="my_script.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo"> </script> <br> <button>Submit</button></body> </html>
Output:
Example 2:
HTML
<!DOCTYPE html><html> <head> <title> script tag </title> <style> body { text-align: center; } h1 { color: green; } </style></head> <body> <h1>GeeksforGeeks</h1> <h2> HTML integrity Attribute in <script> Element </h2> <p id="Geeks"></p> <script charset="UTF-8" integrity="e0d123e5f316bef78bfdf5a008837577OOo_2.0.1_LinuxIntel_install.tar.gz"> document.getElementById("Geeks") .innerHTML = "Hello GeeksforGeeks!"; </script></body> </html>
Output:
Supported Browsers:
Google Chrome 45.0
Internet Explorer 17.0
Opera66.0
Apple safari 13.0
Firefox 43.0
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.
simranarora5sos
HTML-Attributes
HTML-Tags
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
REST API (Introduction)
Design a web page using HTML and CSS
Form validation using jQuery
Angular File Upload
How to Dynamically Add/Remove Table Rows using jQuery ?
Installation of Node.js on Linux
Roadmap to Become a Web Developer in 2022
How to fetch data from an API in ReactJS ?
Difference between var, let and const keywords in JavaScript
How to calculate the number of days between two dates in javascript? | [
{
"code": null,
"e": 24814,
"s": 24786,
"text": "\n27 Sep, 2021"
},
{
"code": null,
"e": 25044,
"s": 24814,
"text": "The integrity attribute is used to give permission to the Browser to check the fetched script to make ensure the source code is never loaded. It is used to check that whether the third party has been altered the resource or not. "
},
{
"code": null,
"e": 25293,
"s": 25044,
"text": "Subresource Integrity(SRI) is a security feature developed by w3comsortium which is used to give permission to a Browser to verify all the external scripts that would be fetched. It gives surety that the scripts are not altered by the third party. "
},
{
"code": null,
"e": 25351,
"s": 25293,
"text": "The working process of SRI is going to follow the steps: "
},
{
"code": null,
"e": 25438,
"s": 25351,
"text": "The webpage holds the hash value and on the other side, the server holds the .js file."
},
{
"code": null,
"e": 25505,
"s": 25438,
"text": "Now, the browser matches the hash value of the integrity attribute"
},
{
"code": null,
"e": 25599,
"s": 25505,
"text": "In the end, if the value of hash matches then the file is used otherwise the file is blocked."
},
{
"code": null,
"e": 25607,
"s": 25599,
"text": "Syntax "
},
{
"code": null,
"e": 25637,
"s": 25607,
"text": "<script integrity=\"filehash\">"
},
{
"code": null,
"e": 25657,
"s": 25637,
"text": " Attribute Values: "
},
{
"code": null,
"e": 25723,
"s": 25657,
"text": "filehash:It indicates the hash value of the external script file."
},
{
"code": null,
"e": 25737,
"s": 25723,
"text": "Example 1: "
},
{
"code": null,
"e": 25742,
"s": 25737,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <title> HTML script integrity Attribute </title></head> <body style=\"text-align:center;\"> <h1> GeeksForGeeks </h1> <h2> HTML script integrity Attribute </h2> <script id=\"myGeeks\" type=\"text/javascript\" src=\"my_script.js\" integrity=\"sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo\"> </script> <br> <button>Submit</button></body> </html>",
"e": 26199,
"s": 25742,
"text": null
},
{
"code": null,
"e": 26207,
"s": 26199,
"text": "Output:"
},
{
"code": null,
"e": 26219,
"s": 26207,
"text": "Example 2: "
},
{
"code": null,
"e": 26224,
"s": 26219,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <title> script tag </title> <style> body { text-align: center; } h1 { color: green; } </style></head> <body> <h1>GeeksforGeeks</h1> <h2> HTML integrity Attribute in <script> Element </h2> <p id=\"Geeks\"></p> <script charset=\"UTF-8\" integrity=\"e0d123e5f316bef78bfdf5a008837577OOo_2.0.1_LinuxIntel_install.tar.gz\"> document.getElementById(\"Geeks\") .innerHTML = \"Hello GeeksforGeeks!\"; </script></body> </html>",
"e": 26779,
"s": 26224,
"text": null
},
{
"code": null,
"e": 26787,
"s": 26779,
"text": "Output:"
},
{
"code": null,
"e": 26808,
"s": 26787,
"text": "Supported Browsers: "
},
{
"code": null,
"e": 26827,
"s": 26808,
"text": "Google Chrome 45.0"
},
{
"code": null,
"e": 26850,
"s": 26827,
"text": "Internet Explorer 17.0"
},
{
"code": null,
"e": 26860,
"s": 26850,
"text": "Opera66.0"
},
{
"code": null,
"e": 26878,
"s": 26860,
"text": "Apple safari 13.0"
},
{
"code": null,
"e": 26891,
"s": 26878,
"text": "Firefox 43.0"
},
{
"code": null,
"e": 27028,
"s": 26891,
"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": 27044,
"s": 27028,
"text": "simranarora5sos"
},
{
"code": null,
"e": 27060,
"s": 27044,
"text": "HTML-Attributes"
},
{
"code": null,
"e": 27070,
"s": 27060,
"text": "HTML-Tags"
},
{
"code": null,
"e": 27075,
"s": 27070,
"text": "HTML"
},
{
"code": null,
"e": 27092,
"s": 27075,
"text": "Web Technologies"
},
{
"code": null,
"e": 27097,
"s": 27092,
"text": "HTML"
},
{
"code": null,
"e": 27195,
"s": 27097,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27204,
"s": 27195,
"text": "Comments"
},
{
"code": null,
"e": 27217,
"s": 27204,
"text": "Old Comments"
},
{
"code": null,
"e": 27241,
"s": 27217,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 27278,
"s": 27241,
"text": "Design a web page using HTML and CSS"
},
{
"code": null,
"e": 27307,
"s": 27278,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 27327,
"s": 27307,
"text": "Angular File Upload"
},
{
"code": null,
"e": 27383,
"s": 27327,
"text": "How to Dynamically Add/Remove Table Rows using jQuery ?"
},
{
"code": null,
"e": 27416,
"s": 27383,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 27458,
"s": 27416,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 27501,
"s": 27458,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 27562,
"s": 27501,
"text": "Difference between var, let and const keywords in JavaScript"
}
] |
How to Sort Words in Alphabetic Order using Python? | Assuming that the a string object contains multiple words separated by one space. The split() method of string class returns a list of words separated by space character. This list object is sorted by invoking sort() method of built-in list class
>>> string='Hello how are you?'
>>> list=string.split()
>>> list
['Hello', 'how', 'are', 'you?']
>>> list.sort()
>>> list
['Hello', 'are', 'how', 'you?'] | [
{
"code": null,
"e": 1309,
"s": 1062,
"text": "Assuming that the a string object contains multiple words separated by one space. The split() method of string class returns a list of words separated by space character. This list object is sorted by invoking sort() method of built-in list class"
},
{
"code": null,
"e": 1463,
"s": 1309,
"text": ">>> string='Hello how are you?'\n>>> list=string.split()\n>>> list\n['Hello', 'how', 'are', 'you?']\n>>> list.sort()\n>>> list\n['Hello', 'are', 'how', 'you?']"
}
] |
Sum of Array Elements | Practice | GeeksforGeeks | Given an integer array arr of size n, you need to sum the elements of arr.
Example 1:
Input:
n = 3
arr[] = {3 2 1}
Output: 6
Example 2:
Input:
n = 4
arr[] = {1 2 3 4}
Output: 10
Your Task:
You need to complete the function sumElement() that takes arr and n and returns the sum. The printing is done by the driver code.
Expected Time Complexity: O(n).
Expected Auxiliary Space: O(1).
Constraints:
1 <= n <= 103
1 <= arri <= 104
0
adityadixit7054in 6 hours
Take a variable sum=0
then iterate the array and add to sum
then return sum
def sumElement(arr,n): sum=0 for i in range(n): sum=sum+arr[i] return sum
0
mehtay0375 days ago
Python Solution:
def sumElement(arr,n): #code here return sum(arr)
0
atif836145 days ago
JAVA SOLUTION
if(n==0){
return 0;
}
int sum=0;
for(int i=0;i<n;i++){
sum=sum+arr[i];
}
return sum;
0
rishabhchemistry36 days ago
int res=0; for(int i=0;i<n;i++){ res=res+arr[i]; } return res;
0
zubairbinmasood786abcd1 week ago
C++ Recursion
if(n<0)
return 0;
return arr[n - 1] + sumElement(arr,n - 1);
0
zubairbinmasood786abcd1 week ago
C++ One Liner : )
return accumulate(arr,arr + n,0);
0
diagovenk1 week ago
Hello guys. Four lines easy java solution
public static int sumElement(int arr[], int n) { // Your code here int sum = 0; for(int i=0; i<n; i++){ sum += arr[i]; } return sum; }
0
shaikhusama7453 weeks ago
C++ Code using Recursionint sumElement(int arr[],int n){ //Base Case if( n == 0 ){ return 0; } if( n == 1 ){ return arr[0]; }
//Recursive Call
int remainingPart = sumElement(arr+1,n-1); int sum = arr[0] + remainingPart; return sum;}
0
rapuriteja1 month ago
def sumElement(arr,n): su = sum(arr) return su
0
ravi119033851 month ago
//JAVA
int sum=0; for(int i: arr) { sum+=i; } return sum;
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": 301,
"s": 226,
"text": "Given an integer array arr of size n, you need to sum the elements of arr."
},
{
"code": null,
"e": 312,
"s": 301,
"text": "Example 1:"
},
{
"code": null,
"e": 351,
"s": 312,
"text": "Input:\nn = 3\narr[] = {3 2 1}\nOutput: 6"
},
{
"code": null,
"e": 362,
"s": 351,
"text": "Example 2:"
},
{
"code": null,
"e": 405,
"s": 362,
"text": "Input:\nn = 4\narr[] = {1 2 3 4}\nOutput: 10\n"
},
{
"code": null,
"e": 546,
"s": 405,
"text": "Your Task:\nYou need to complete the function sumElement() that takes arr and n and returns the sum. The printing is done by the driver code."
},
{
"code": null,
"e": 610,
"s": 546,
"text": "Expected Time Complexity: O(n).\nExpected Auxiliary Space: O(1)."
},
{
"code": null,
"e": 654,
"s": 610,
"text": "Constraints:\n1 <= n <= 103\n1 <= arri <= 104"
},
{
"code": null,
"e": 656,
"s": 654,
"text": "0"
},
{
"code": null,
"e": 682,
"s": 656,
"text": "adityadixit7054in 6 hours"
},
{
"code": null,
"e": 704,
"s": 682,
"text": "Take a variable sum=0"
},
{
"code": null,
"e": 742,
"s": 704,
"text": "then iterate the array and add to sum"
},
{
"code": null,
"e": 758,
"s": 742,
"text": "then return sum"
},
{
"code": null,
"e": 844,
"s": 758,
"text": "def sumElement(arr,n): sum=0 for i in range(n): sum=sum+arr[i] return sum"
},
{
"code": null,
"e": 846,
"s": 844,
"text": "0"
},
{
"code": null,
"e": 866,
"s": 846,
"text": "mehtay0375 days ago"
},
{
"code": null,
"e": 883,
"s": 866,
"text": "Python Solution:"
},
{
"code": null,
"e": 938,
"s": 883,
"text": "def sumElement(arr,n): #code here return sum(arr) "
},
{
"code": null,
"e": 940,
"s": 938,
"text": "0"
},
{
"code": null,
"e": 960,
"s": 940,
"text": "atif836145 days ago"
},
{
"code": null,
"e": 974,
"s": 960,
"text": "JAVA SOLUTION"
},
{
"code": null,
"e": 1117,
"s": 974,
"text": " if(n==0){\n return 0;\n }\n int sum=0;\n for(int i=0;i<n;i++){\n sum=sum+arr[i];\n }\n return sum;"
},
{
"code": null,
"e": 1119,
"s": 1117,
"text": "0"
},
{
"code": null,
"e": 1147,
"s": 1119,
"text": "rishabhchemistry36 days ago"
},
{
"code": null,
"e": 1223,
"s": 1147,
"text": " int res=0; for(int i=0;i<n;i++){ res=res+arr[i]; } return res;"
},
{
"code": null,
"e": 1225,
"s": 1223,
"text": "0"
},
{
"code": null,
"e": 1258,
"s": 1225,
"text": "zubairbinmasood786abcd1 week ago"
},
{
"code": null,
"e": 1272,
"s": 1258,
"text": "C++ Recursion"
},
{
"code": null,
"e": 1341,
"s": 1272,
"text": "if(n<0)\n return 0;\nreturn arr[n - 1] + sumElement(arr,n - 1);"
},
{
"code": null,
"e": 1343,
"s": 1341,
"text": "0"
},
{
"code": null,
"e": 1376,
"s": 1343,
"text": "zubairbinmasood786abcd1 week ago"
},
{
"code": null,
"e": 1394,
"s": 1376,
"text": "C++ One Liner : )"
},
{
"code": null,
"e": 1428,
"s": 1394,
"text": "return accumulate(arr,arr + n,0);"
},
{
"code": null,
"e": 1430,
"s": 1428,
"text": "0"
},
{
"code": null,
"e": 1450,
"s": 1430,
"text": "diagovenk1 week ago"
},
{
"code": null,
"e": 1492,
"s": 1450,
"text": "Hello guys. Four lines easy java solution"
},
{
"code": null,
"e": 1671,
"s": 1492,
"text": "public static int sumElement(int arr[], int n) { // Your code here int sum = 0; for(int i=0; i<n; i++){ sum += arr[i]; } return sum; }"
},
{
"code": null,
"e": 1673,
"s": 1671,
"text": "0"
},
{
"code": null,
"e": 1699,
"s": 1673,
"text": "shaikhusama7453 weeks ago"
},
{
"code": null,
"e": 1847,
"s": 1699,
"text": "C++ Code using Recursionint sumElement(int arr[],int n){ //Base Case if( n == 0 ){ return 0; } if( n == 1 ){ return arr[0]; }"
},
{
"code": null,
"e": 1867,
"s": 1847,
"text": " //Recursive Call"
},
{
"code": null,
"e": 1971,
"s": 1867,
"text": " int remainingPart = sumElement(arr+1,n-1); int sum = arr[0] + remainingPart; return sum;} "
},
{
"code": null,
"e": 1973,
"s": 1971,
"text": "0"
},
{
"code": null,
"e": 1995,
"s": 1973,
"text": "rapuriteja1 month ago"
},
{
"code": null,
"e": 2046,
"s": 1995,
"text": "def sumElement(arr,n): su = sum(arr) return su"
},
{
"code": null,
"e": 2048,
"s": 2046,
"text": "0"
},
{
"code": null,
"e": 2072,
"s": 2048,
"text": "ravi119033851 month ago"
},
{
"code": null,
"e": 2079,
"s": 2072,
"text": "//JAVA"
},
{
"code": null,
"e": 2164,
"s": 2079,
"text": "int sum=0; for(int i: arr) { sum+=i; } return sum;"
},
{
"code": null,
"e": 2310,
"s": 2164,
"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": 2346,
"s": 2310,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 2356,
"s": 2346,
"text": "\nProblem\n"
},
{
"code": null,
"e": 2366,
"s": 2356,
"text": "\nContest\n"
},
{
"code": null,
"e": 2429,
"s": 2366,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 2577,
"s": 2429,
"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": 2785,
"s": 2577,
"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": 2891,
"s": 2785,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
Find data for specific date in MongoDB? | Let’s say you have saved the Login date of users. Now, you want the count of records for specific date only i.e. login date. For this, use gteandlt operator along with count(). Let us first create a collection with documents −
> db.findDataByDateDemo.insertOne({"UserName":"John","UserLoginDate":new ISODate("2019-01-31")});
{
"acknowledged" : true,
"insertedId" : ObjectId("5cdd8cd7bf3115999ed511ed")
}
> db.findDataByDateDemo.insertOne({"UserName":"Larry","UserLoginDate":new ISODate("2019-02-01")});
{
"acknowledged" : true,
"insertedId" : ObjectId("5cdd8ce7bf3115999ed511ee")
}
> db.findDataByDateDemo.insertOne({"UserName":"Sam","UserLoginDate":new ISODate("2019-05-02")});
{
"acknowledged" : true,
"insertedId" : ObjectId("5cdd8cf3bf3115999ed511ef")
}
> db.findDataByDateDemo.insertOne({"UserName":"David","UserLoginDate":new ISODate("2019-05-16")});
{
"acknowledged" : true,
"insertedId" : ObjectId("5cdd8d00bf3115999ed511f0")
}
> db.findDataByDateDemo.insertOne({"UserName":"Carol","UserLoginDate":new ISODate("2019-10-19")});
{
"acknowledged" : true,
"insertedId" : ObjectId("5cdd8d0ebf3115999ed511f1")
}
Following is the query to display all documents from a collection with the help of find() method −
> db.findDataByDateDemo.find();
This will produce the following output −
{ "_id" : ObjectId("5cdd8cd7bf3115999ed511ed"), "UserName" : "John", "UserLoginDate" : ISODate("2019-01-31T00:00:00Z") }
{ "_id" : ObjectId("5cdd8ce7bf3115999ed511ee"), "UserName" : "Larry", "UserLoginDate" : ISODate("2019-02-01T00:00:00Z") }
{ "_id" : ObjectId("5cdd8cf3bf3115999ed511ef"), "UserName" : "Sam", "UserLoginDate" : ISODate("2019-05-02T00:00:00Z") }
{ "_id" : ObjectId("5cdd8d00bf3115999ed511f0"), "UserName" : "David", "UserLoginDate" : ISODate("2019-05-16T00:00:00Z") }
{ "_id" : ObjectId("5cdd8d0ebf3115999ed511f1"), "UserName" : "Carol", "UserLoginDate" : ISODate("2019-10-19T00:00:00Z") }
Following is the query to find data for a specific date in MongoDB. Here, we are getting the users who logged in between specific dates −
> db.findDataByDateDemo.count({"UserLoginDate":{ "$gte": new Date("2019-05-02"), "$lt": new Date("2019-05-18") }});
This will produce the following output −
2 | [
{
"code": null,
"e": 1289,
"s": 1062,
"text": "Let’s say you have saved the Login date of users. Now, you want the count of records for specific date only i.e. login date. For this, use gteandlt operator along with count(). Let us first create a collection with documents −"
},
{
"code": null,
"e": 2206,
"s": 1289,
"text": "> db.findDataByDateDemo.insertOne({\"UserName\":\"John\",\"UserLoginDate\":new ISODate(\"2019-01-31\")});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5cdd8cd7bf3115999ed511ed\")\n}\n> db.findDataByDateDemo.insertOne({\"UserName\":\"Larry\",\"UserLoginDate\":new ISODate(\"2019-02-01\")});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5cdd8ce7bf3115999ed511ee\")\n}\n> db.findDataByDateDemo.insertOne({\"UserName\":\"Sam\",\"UserLoginDate\":new ISODate(\"2019-05-02\")});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5cdd8cf3bf3115999ed511ef\")\n}\n> db.findDataByDateDemo.insertOne({\"UserName\":\"David\",\"UserLoginDate\":new ISODate(\"2019-05-16\")});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5cdd8d00bf3115999ed511f0\")\n}\n> db.findDataByDateDemo.insertOne({\"UserName\":\"Carol\",\"UserLoginDate\":new ISODate(\"2019-10-19\")});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5cdd8d0ebf3115999ed511f1\")\n}"
},
{
"code": null,
"e": 2305,
"s": 2206,
"text": "Following is the query to display all documents from a collection with the help of find() method −"
},
{
"code": null,
"e": 2337,
"s": 2305,
"text": "> db.findDataByDateDemo.find();"
},
{
"code": null,
"e": 2378,
"s": 2337,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2988,
"s": 2378,
"text": "{ \"_id\" : ObjectId(\"5cdd8cd7bf3115999ed511ed\"), \"UserName\" : \"John\", \"UserLoginDate\" : ISODate(\"2019-01-31T00:00:00Z\") }\n{ \"_id\" : ObjectId(\"5cdd8ce7bf3115999ed511ee\"), \"UserName\" : \"Larry\", \"UserLoginDate\" : ISODate(\"2019-02-01T00:00:00Z\") }\n{ \"_id\" : ObjectId(\"5cdd8cf3bf3115999ed511ef\"), \"UserName\" : \"Sam\", \"UserLoginDate\" : ISODate(\"2019-05-02T00:00:00Z\") }\n{ \"_id\" : ObjectId(\"5cdd8d00bf3115999ed511f0\"), \"UserName\" : \"David\", \"UserLoginDate\" : ISODate(\"2019-05-16T00:00:00Z\") }\n{ \"_id\" : ObjectId(\"5cdd8d0ebf3115999ed511f1\"), \"UserName\" : \"Carol\", \"UserLoginDate\" : ISODate(\"2019-10-19T00:00:00Z\") }"
},
{
"code": null,
"e": 3126,
"s": 2988,
"text": "Following is the query to find data for a specific date in MongoDB. Here, we are getting the users who logged in between specific dates −"
},
{
"code": null,
"e": 3242,
"s": 3126,
"text": "> db.findDataByDateDemo.count({\"UserLoginDate\":{ \"$gte\": new Date(\"2019-05-02\"), \"$lt\": new Date(\"2019-05-18\") }});"
},
{
"code": null,
"e": 3283,
"s": 3242,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 3285,
"s": 3283,
"text": "2"
}
] |
Merge Two Sorted Lists in Python | Suppose we have two sorted lists A and B. We have to merge them and form only one sorted list C. The size of lists may different.
For an example, suppose A = [1,2,4,7] and B = [1,3,4,5,6,8], then merged list C will be [1,1,2,3,4,4,5,6,7,8]
We will solve this using recursion. So the function will work like below −
Suppose the lists A and B of function merge()
if A is empty, then return B, if B is empty, then return A
if value in A <= value in B, then A.next = merge(A.next, B) and return A
otherwise, then B.next = merge(A, B.next) and return B
Let us see the implementation to get a better understanding
Live Demo
class ListNode:
def __init__(self, data, next = None):
self.val = data
self.next = next
def make_list(elements):
head = ListNode(elements[0])
for element in elements[1:]:
ptr = head
while ptr.next:
ptr = ptr.next
ptr.next = ListNode(element)
return head
def print_list(head):
ptr = head
print('[', end = "")
while ptr:
print(ptr.val, end = ", ")
ptr = ptr.next
print(']')
class Solution:
def mergeTwoLists(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
if not l1:
return l2
if not l2:
return l1
if(l1.val<=l2.val):
l1.next = self.mergeTwoLists(l1.next,l2)
return l1
else:
l2.next = self.mergeTwoLists(l1,l2.next)
return l2
head1 = make_list([1,2,4,7])
head2 = make_list([1,3,4,5,6,8])
ob1 = Solution()
head3 = ob1.mergeTwoLists(head1,head2)
print_list(head3)
head1 = make_list([1,2,4,7])
head2 = make_list([1,3,4,5,6,8])
[1, 1, 2, 3, 4, 4, 5, 6, 7, 8, ] | [
{
"code": null,
"e": 1192,
"s": 1062,
"text": "Suppose we have two sorted lists A and B. We have to merge them and form only one sorted list C. The size of lists may different."
},
{
"code": null,
"e": 1302,
"s": 1192,
"text": "For an example, suppose A = [1,2,4,7] and B = [1,3,4,5,6,8], then merged list C will be [1,1,2,3,4,4,5,6,7,8]"
},
{
"code": null,
"e": 1377,
"s": 1302,
"text": "We will solve this using recursion. So the function will work like below −"
},
{
"code": null,
"e": 1423,
"s": 1377,
"text": "Suppose the lists A and B of function merge()"
},
{
"code": null,
"e": 1482,
"s": 1423,
"text": "if A is empty, then return B, if B is empty, then return A"
},
{
"code": null,
"e": 1555,
"s": 1482,
"text": "if value in A <= value in B, then A.next = merge(A.next, B) and return A"
},
{
"code": null,
"e": 1610,
"s": 1555,
"text": "otherwise, then B.next = merge(A, B.next) and return B"
},
{
"code": null,
"e": 1670,
"s": 1610,
"text": "Let us see the implementation to get a better understanding"
},
{
"code": null,
"e": 1681,
"s": 1670,
"text": " Live Demo"
},
{
"code": null,
"e": 2681,
"s": 1681,
"text": "class ListNode:\n def __init__(self, data, next = None):\n self.val = data\n self.next = next\n def make_list(elements):\n head = ListNode(elements[0])\n for element in elements[1:]:\n ptr = head\n while ptr.next:\n ptr = ptr.next\n ptr.next = ListNode(element)\n return head\ndef print_list(head):\n ptr = head\n print('[', end = \"\")\n while ptr:\n print(ptr.val, end = \", \")\n ptr = ptr.next\n print(']')\nclass Solution:\n def mergeTwoLists(self, l1, l2):\n \"\"\"\n :type l1: ListNode\n :type l2: ListNode\n :rtype: ListNode\n \"\"\"\n if not l1:\n return l2\n if not l2:\n return l1\n if(l1.val<=l2.val):\n l1.next = self.mergeTwoLists(l1.next,l2)\n return l1\n else:\n l2.next = self.mergeTwoLists(l1,l2.next)\n return l2\nhead1 = make_list([1,2,4,7])\nhead2 = make_list([1,3,4,5,6,8])\nob1 = Solution()\nhead3 = ob1.mergeTwoLists(head1,head2)\nprint_list(head3)"
},
{
"code": null,
"e": 2743,
"s": 2681,
"text": "head1 = make_list([1,2,4,7])\nhead2 = make_list([1,3,4,5,6,8])"
},
{
"code": null,
"e": 2776,
"s": 2743,
"text": "[1, 1, 2, 3, 4, 4, 5, 6, 7, 8, ]"
}
] |
How do you animate the change of background color of a view on Android using Kotlin? | This example demonstrates how to animate the change of background color of a view on Android using Kotlin.
Step 1 − Create a new project in Android Studio, go to File? New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/relativeLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="8dp"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="50dp"
android:text="Tutorials Point"
android:textAlignment="center"
android:textColor="@android:color/holo_green_dark"
android:textSize="32sp"
android:textStyle="bold" />
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="@id/textView"
android:layout_centerInParent="true"
android:layout_marginBottom="15dp"
android:text="Animate background color" />
<TextView
android:id="@+id/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="Changing Background color of this view."
android:textAlignment="center"
android:textColor="@android:color/background_dark"
android:textSize="36sp"
android:textStyle="bold" />
</RelativeLayout>
Step 3 − Add the following code to src/MainActivity.kt
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.graphics.drawable.TransitionDrawable
import android.os.Bundle
import android.widget.Button
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
lateinit var textView: TextView
lateinit var button: Button
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
title = "KotlinApp"
textView = findViewById(R.id.textView)
button = findViewById(R.id.button)
button.setOnClickListener {
val colorDrawables = arrayOf(ColorDrawable(Color.GREEN),
ColorDrawable(Color.RED), ColorDrawable(Color.YELLOW))
val transitionDrawable = TransitionDrawable(colorDrawables)
textView.background = transitionDrawable
transitionDrawable.startTransition(2000)
}
}
}
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.q11">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen | [
{
"code": null,
"e": 1169,
"s": 1062,
"text": "This example demonstrates how to animate the change of background color of a view on Android using Kotlin."
},
{
"code": null,
"e": 1297,
"s": 1169,
"text": "Step 1 − Create a new project in Android Studio, go to File? New Project and fill all required details to create a new project."
},
{
"code": null,
"e": 1362,
"s": 1297,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 2789,
"s": 1362,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:id=\"@+id/relativeLayout\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:padding=\"8dp\"\n tools:context=\".MainActivity\">\n <TextView\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_centerHorizontal=\"true\"\n android:layout_marginTop=\"50dp\"\n android:text=\"Tutorials Point\"\n android:textAlignment=\"center\"\n android:textColor=\"@android:color/holo_green_dark\"\n android:textSize=\"32sp\"\n android:textStyle=\"bold\" />\n <Button\n android:id=\"@+id/button\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_above=\"@id/textView\"\n android:layout_centerInParent=\"true\"\n android:layout_marginBottom=\"15dp\"\n android:text=\"Animate background color\" />\n <TextView\n android:id=\"@+id/textView\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n android:layout_centerInParent=\"true\"\n android:text=\"Changing Background color of this view.\"\n android:textAlignment=\"center\"\n android:textColor=\"@android:color/background_dark\"\n android:textSize=\"36sp\"\n android:textStyle=\"bold\" />\n</RelativeLayout>"
},
{
"code": null,
"e": 2844,
"s": 2789,
"text": "Step 3 − Add the following code to src/MainActivity.kt"
},
{
"code": null,
"e": 3817,
"s": 2844,
"text": "import android.graphics.Color\nimport android.graphics.drawable.ColorDrawable\nimport android.graphics.drawable.TransitionDrawable\nimport android.os.Bundle\nimport android.widget.Button\nimport android.widget.TextView\nimport androidx.appcompat.app.AppCompatActivity\nclass MainActivity : AppCompatActivity() {\n lateinit var textView: TextView\n lateinit var button: Button\n override fun onCreate(savedInstanceState: Bundle?) {\n super.onCreate(savedInstanceState)\n setContentView(R.layout.activity_main)\n title = \"KotlinApp\"\n textView = findViewById(R.id.textView)\n button = findViewById(R.id.button)\n button.setOnClickListener {\n val colorDrawables = arrayOf(ColorDrawable(Color.GREEN),\n ColorDrawable(Color.RED), ColorDrawable(Color.YELLOW))\n val transitionDrawable = TransitionDrawable(colorDrawables)\n textView.background = transitionDrawable\n transitionDrawable.startTransition(2000)\n }\n }\n}"
},
{
"code": null,
"e": 3872,
"s": 3817,
"text": "Step 4 − Add the following code to androidManifest.xml"
},
{
"code": null,
"e": 4539,
"s": 3872,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"app.com.q11\">\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": 4887,
"s": 4539,
"text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen"
}
] |
Frog Jump in C++ | Suppose there is a frog that is crossing a river. The river is divided into x units and at each unit there may be a stone. The frog can jump on a stone, but not water. Here we have a list of stones' positions in sorted ascending order sequence, we have to check whether the frog is able to cross the river by landing on the last stone, or not. Initially, the frog is on the first stone and assume the first jump must be of 1 unit.
When the frog's current jump was k units, then its next jump must be either k - 1, k, or k + 1 units. And frog can only jump in the forward direction.
So if the given array is like [0,1,3,4,5,7,9,10,12], then the answer will be true as, the frog can jump to the 1 unit to 2nd stone, 2 units to 3rd stone, then again 2 units to 4th stone, then 3 units to 6th stone, 4 units to 7th stone and finally 5 units to 8th stone.
To solve this, we will follow these steps −
Define a map called visited
Define a function canCross(), this will take an array stones, pos initialize it with 0, k initialize it with 0,
key := pos OR (left shift k 11 bits)
if key is present in the visited, then −return visited[key]
return visited[key]
for initialize i := pos + 1, when i < size of stones, update (increase i by 1), do −gap := stones[i] - stones[pos]if gap < k - 1, then −Ignore following part, skip to the next iterationif gap > k + 1, then −visited[key] := falsereturn falseif call the function canCross(stones, i, gap) is non-zero, then −visited[key] = truereturn true
gap := stones[i] - stones[pos]
if gap < k - 1, then −Ignore following part, skip to the next iteration
Ignore following part, skip to the next iteration
if gap > k + 1, then −visited[key] := falsereturn false
visited[key] := false
return false
if call the function canCross(stones, i, gap) is non-zero, then −visited[key] = truereturn true
visited[key] = true
return true
visited[key] = true when (pos is same as size of stones - 1) otherwise false
return visited[key]
Let us see the following implementation to get better understanding −
Live Demo
#include <bits/stdc++.h>
using namespace std;
typedef long long int lli;
class Solution {
public:
unordered_map < lli, int > visited;
bool canCross(vector<int>& stones, int pos = 0, int k = 0) {
lli key = pos | k << 11;
if(visited.find(key) != visited.end())return visited[key];
for(int i = pos + 1; i < stones.size(); i++){
int gap = stones[i] - stones[pos];
if(gap < k - 1)continue;
if(gap > k + 1){
return visited[key] = false;
}
if(canCross(stones, i, gap))return visited[key] = true;
}
return visited[key] = (pos == stones.size() - 1);
}
};
main(){
Solution ob;
vector<int> v = {0,1,3,5,6,8,12,17};
cout << (ob.canCross(v));
}
0,1,3,5,6,8,12,17
1 | [
{
"code": null,
"e": 1493,
"s": 1062,
"text": "Suppose there is a frog that is crossing a river. The river is divided into x units and at each unit there may be a stone. The frog can jump on a stone, but not water. Here we have a list of stones' positions in sorted ascending order sequence, we have to check whether the frog is able to cross the river by landing on the last stone, or not. Initially, the frog is on the first stone and assume the first jump must be of 1 unit."
},
{
"code": null,
"e": 1644,
"s": 1493,
"text": "When the frog's current jump was k units, then its next jump must be either k - 1, k, or k + 1 units. And frog can only jump in the forward direction."
},
{
"code": null,
"e": 1913,
"s": 1644,
"text": "So if the given array is like [0,1,3,4,5,7,9,10,12], then the answer will be true as, the frog can jump to the 1 unit to 2nd stone, 2 units to 3rd stone, then again 2 units to 4th stone, then 3 units to 6th stone, 4 units to 7th stone and finally 5 units to 8th stone."
},
{
"code": null,
"e": 1957,
"s": 1913,
"text": "To solve this, we will follow these steps −"
},
{
"code": null,
"e": 1985,
"s": 1957,
"text": "Define a map called visited"
},
{
"code": null,
"e": 2097,
"s": 1985,
"text": "Define a function canCross(), this will take an array stones, pos initialize it with 0, k initialize it with 0,"
},
{
"code": null,
"e": 2134,
"s": 2097,
"text": "key := pos OR (left shift k 11 bits)"
},
{
"code": null,
"e": 2194,
"s": 2134,
"text": "if key is present in the visited, then −return visited[key]"
},
{
"code": null,
"e": 2214,
"s": 2194,
"text": "return visited[key]"
},
{
"code": null,
"e": 2550,
"s": 2214,
"text": "for initialize i := pos + 1, when i < size of stones, update (increase i by 1), do −gap := stones[i] - stones[pos]if gap < k - 1, then −Ignore following part, skip to the next iterationif gap > k + 1, then −visited[key] := falsereturn falseif call the function canCross(stones, i, gap) is non-zero, then −visited[key] = truereturn true"
},
{
"code": null,
"e": 2581,
"s": 2550,
"text": "gap := stones[i] - stones[pos]"
},
{
"code": null,
"e": 2653,
"s": 2581,
"text": "if gap < k - 1, then −Ignore following part, skip to the next iteration"
},
{
"code": null,
"e": 2703,
"s": 2653,
"text": "Ignore following part, skip to the next iteration"
},
{
"code": null,
"e": 2759,
"s": 2703,
"text": "if gap > k + 1, then −visited[key] := falsereturn false"
},
{
"code": null,
"e": 2781,
"s": 2759,
"text": "visited[key] := false"
},
{
"code": null,
"e": 2794,
"s": 2781,
"text": "return false"
},
{
"code": null,
"e": 2890,
"s": 2794,
"text": "if call the function canCross(stones, i, gap) is non-zero, then −visited[key] = truereturn true"
},
{
"code": null,
"e": 2910,
"s": 2890,
"text": "visited[key] = true"
},
{
"code": null,
"e": 2922,
"s": 2910,
"text": "return true"
},
{
"code": null,
"e": 2999,
"s": 2922,
"text": "visited[key] = true when (pos is same as size of stones - 1) otherwise false"
},
{
"code": null,
"e": 3019,
"s": 2999,
"text": "return visited[key]"
},
{
"code": null,
"e": 3089,
"s": 3019,
"text": "Let us see the following implementation to get better understanding −"
},
{
"code": null,
"e": 3100,
"s": 3089,
"text": " Live Demo"
},
{
"code": null,
"e": 3837,
"s": 3100,
"text": "#include <bits/stdc++.h>\nusing namespace std;\ntypedef long long int lli;\nclass Solution {\npublic:\n unordered_map < lli, int > visited;\n bool canCross(vector<int>& stones, int pos = 0, int k = 0) {\n lli key = pos | k << 11;\n if(visited.find(key) != visited.end())return visited[key];\n for(int i = pos + 1; i < stones.size(); i++){\n int gap = stones[i] - stones[pos];\n if(gap < k - 1)continue;\n if(gap > k + 1){\n return visited[key] = false;\n }\n if(canCross(stones, i, gap))return visited[key] = true;\n }\n return visited[key] = (pos == stones.size() - 1);\n }\n};\nmain(){\n Solution ob;\n vector<int> v = {0,1,3,5,6,8,12,17};\n cout << (ob.canCross(v));\n}"
},
{
"code": null,
"e": 3855,
"s": 3837,
"text": "0,1,3,5,6,8,12,17"
},
{
"code": null,
"e": 3857,
"s": 3855,
"text": "1"
}
] |
How to generate a random BigInteger value in Java? | To generate random BigInteger in Java, let us first set a min and max value −
BigInteger maxLimit = new BigInteger("5000000000000");
BigInteger minLimit = new BigInteger("25000000000");
Now, subtract the min and max −
BigInteger bigInteger = maxLimit.subtract(minLimit);
Declare a Random object and find the length of the maxLimit:
Random randNum = new Random();
int len = maxLimit.bitLength();
Now, set a new B integer with the length and the random object created above.
Live Demo
import java.math.BigInteger;
import java.util.Random;
public class Demo {
public static void main(String[] args) {
BigInteger maxLimit = new BigInteger("5000000000000");
BigInteger minLimit = new BigInteger("25000000000");
BigInteger bigInteger = maxLimit.subtract(minLimit);
Random randNum = new Random();
int len = maxLimit.bitLength();
BigInteger res = new BigInteger(len, randNum);
if (res.compareTo(minLimit) < 0)
res = res.add(minLimit);
if (res.compareTo(bigInteger) >= 0)
res = res.mod(bigInteger).add(minLimit);
System.out.println("The random BigInteger = "+res);
}
}
The random BigInteger = 3874699348568 | [
{
"code": null,
"e": 1140,
"s": 1062,
"text": "To generate random BigInteger in Java, let us first set a min and max value −"
},
{
"code": null,
"e": 1248,
"s": 1140,
"text": "BigInteger maxLimit = new BigInteger(\"5000000000000\");\nBigInteger minLimit = new BigInteger(\"25000000000\");"
},
{
"code": null,
"e": 1280,
"s": 1248,
"text": "Now, subtract the min and max −"
},
{
"code": null,
"e": 1457,
"s": 1280,
"text": "BigInteger bigInteger = maxLimit.subtract(minLimit);\nDeclare a Random object and find the length of the maxLimit:\nRandom randNum = new Random();\nint len = maxLimit.bitLength();"
},
{
"code": null,
"e": 1535,
"s": 1457,
"text": "Now, set a new B integer with the length and the random object created above."
},
{
"code": null,
"e": 1546,
"s": 1535,
"text": " Live Demo"
},
{
"code": null,
"e": 2204,
"s": 1546,
"text": "import java.math.BigInteger;\nimport java.util.Random;\npublic class Demo {\n public static void main(String[] args) {\n BigInteger maxLimit = new BigInteger(\"5000000000000\");\n BigInteger minLimit = new BigInteger(\"25000000000\");\n BigInteger bigInteger = maxLimit.subtract(minLimit);\n Random randNum = new Random();\n int len = maxLimit.bitLength();\n BigInteger res = new BigInteger(len, randNum);\n if (res.compareTo(minLimit) < 0)\n res = res.add(minLimit);\n if (res.compareTo(bigInteger) >= 0)\n res = res.mod(bigInteger).add(minLimit);\n System.out.println(\"The random BigInteger = \"+res);\n }\n}"
},
{
"code": null,
"e": 2242,
"s": 2204,
"text": "The random BigInteger = 3874699348568"
}
] |
How to use CheckBox in Android Kotlin? | This example demonstrates how to use CheckBox in Android Kotlin.
Step 1 − Create a new project in Android Studio, go to File ⇒New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="16dp"
tools:context="MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="50dp"
android:text="Tutorials Point"
android:textAlignment="center"
android:textColor="@android:color/holo_green_dark"
android:textSize="32sp"
android:textStyle="bold" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_above="@id/checkBox1"
android:layout_marginBottom="30dp"
android:text="Select your products!"
android:textAlignment="center"
android:textColor="@android:color/background_dark"
android:textSize="24sp"
android:textStyle="bold|italic" />
<CheckBox
android:id="@+id/checkBox1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="Pizza" />
<CheckBox
android:id="@+id/checkBox2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/checkBox1"
android:layout_centerInParent="true"
android:layout_marginTop="10dp"
android:text="Coffee" />
<CheckBox
android:id="@+id/checkBox3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/checkBox2"
android:layout_centerInParent="true"
android:layout_marginTop="10dp"
android:text="Burger" />
<Button
android:id="@+id/button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/checkBox3"
android:layout_marginTop="10dp"
android:text="Complete purchase" />
</RelativeLayout>
Step 3 − Add the following code to src/MainActivity.kt
import android.os.Bundle
import android.widget.Button
import android.widget.CheckBox
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import java.lang.StringBuilder
class MainActivity : AppCompatActivity() {
lateinit var pizza: CheckBox
lateinit var coffee: CheckBox
lateinit var burger: CheckBox
lateinit var button: Button
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
title = "KotlinApp"
pizza = findViewById(R.id.checkBox1)
coffee = findViewById(R.id.checkBox2)
burger = findViewById(R.id.checkBox3)
button = findViewById(R.id.button)
button.setOnClickListener {
var totalAmount: Int = 0
val result = StringBuilder()
result.append("Selected Items")
if (pizza.isChecked) {
result.append("\nPizza 100Rs")
totalAmount += 100
}
if (coffee.isChecked) {
result.append("\nCoffee 50Rs")
totalAmount += 50
}
if (burger.isChecked) {
result.append("\nBurger 120Rs")
totalAmount += 120
}
result.append("\nTotal: " + totalAmount + "Rs")
Toast.makeText(applicationContext, result.toString(), Toast.LENGTH_SHORT).show()
}
}
}
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.kotlipapp">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −
Click here to download the project code. | [
{
"code": null,
"e": 1127,
"s": 1062,
"text": "This example demonstrates how to use CheckBox in Android Kotlin."
},
{
"code": null,
"e": 1255,
"s": 1127,
"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": 1320,
"s": 1255,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 3490,
"s": 1320,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:app=\"http://schemas.android.com/apk/res-auto\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:padding=\"16dp\"\n tools:context=\"MainActivity\">\n <TextView\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_centerHorizontal=\"true\"\n android:layout_marginTop=\"50dp\"\n android:text=\"Tutorials Point\"\n android:textAlignment=\"center\"\n android:textColor=\"@android:color/holo_green_dark\"\n android:textSize=\"32sp\"\n android:textStyle=\"bold\" />\n <TextView\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n android:layout_above=\"@id/checkBox1\"\n android:layout_marginBottom=\"30dp\"\n android:text=\"Select your products!\"\n android:textAlignment=\"center\"\n android:textColor=\"@android:color/background_dark\"\n android:textSize=\"24sp\"\n android:textStyle=\"bold|italic\" />\n <CheckBox\n android:id=\"@+id/checkBox1\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_centerInParent=\"true\"\n android:text=\"Pizza\" />\n <CheckBox\n android:id=\"@+id/checkBox2\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_below=\"@id/checkBox1\"\n android:layout_centerInParent=\"true\"\n android:layout_marginTop=\"10dp\"\n android:text=\"Coffee\" />\n <CheckBox\n android:id=\"@+id/checkBox3\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_below=\"@id/checkBox2\"\n android:layout_centerInParent=\"true\"\n android:layout_marginTop=\"10dp\"\n android:text=\"Burger\" />\n <Button\n android:id=\"@+id/button\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n android:layout_below=\"@id/checkBox3\"\n android:layout_marginTop=\"10dp\"\n android:text=\"Complete purchase\" />\n</RelativeLayout>"
},
{
"code": null,
"e": 3545,
"s": 3490,
"text": "Step 3 − Add the following code to src/MainActivity.kt"
},
{
"code": null,
"e": 4911,
"s": 3545,
"text": "import android.os.Bundle\nimport android.widget.Button\nimport android.widget.CheckBox\nimport android.widget.Toast\nimport androidx.appcompat.app.AppCompatActivity\nimport java.lang.StringBuilder\nclass MainActivity : AppCompatActivity() {\n lateinit var pizza: CheckBox\n lateinit var coffee: CheckBox\n lateinit var burger: CheckBox\n lateinit var button: Button\n override fun onCreate(savedInstanceState: Bundle?) {\n super.onCreate(savedInstanceState)\n setContentView(R.layout.activity_main)\n title = \"KotlinApp\"\n pizza = findViewById(R.id.checkBox1)\n coffee = findViewById(R.id.checkBox2)\n burger = findViewById(R.id.checkBox3)\n button = findViewById(R.id.button)\n button.setOnClickListener {\n var totalAmount: Int = 0\n val result = StringBuilder()\n result.append(\"Selected Items\")\n if (pizza.isChecked) {\n result.append(\"\\nPizza 100Rs\")\n totalAmount += 100\n }\n if (coffee.isChecked) {\n result.append(\"\\nCoffee 50Rs\")\n totalAmount += 50\n }\n if (burger.isChecked) {\n result.append(\"\\nBurger 120Rs\")\n totalAmount += 120\n }\n result.append(\"\\nTotal: \" + totalAmount + \"Rs\")\n Toast.makeText(applicationContext, result.toString(), Toast.LENGTH_SHORT).show()\n }\n }\n}"
},
{
"code": null,
"e": 4966,
"s": 4911,
"text": "Step 4 − Add the following code to androidManifest.xml"
},
{
"code": null,
"e": 5642,
"s": 4966,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\n package=\"app.com.kotlipapp\">\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": 5992,
"s": 5642,
"text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −"
},
{
"code": null,
"e": 6033,
"s": 5992,
"text": "Click here to download the project code."
}
] |
Git Clone from GitHub | Now we have our own fork, but only on GitHub. We also want a
clone on our local Git to keep working on it.
A clone is a full copy of a repository, including all logging and versions of files.
Move back to the original repository, and click the green "Code" button to get the
URL to clone:
Open your Git bash and clone the repository:
git clone https://github.com/w3schools-test/w3schools-test.github.io.git
Cloning into 'w3schools-test.github.io'...
remote: Enumerating objects: 33, done.
remote: Counting objects: 100% (33/33), done.
remote: Compressing objects: 100% (15/15), done.
remote: Total 33 (delta 18), reused 33 (delta 18), pack-reused 0
Receiving objects: 100% (33/33), 94.79 KiB | 3.16 MiB/s, done.
Resolving deltas: 100% (18/18), done.
Take a look in your file system, and you will see a new directory named after the cloned project:
ls
w3schools-test.github.io/
Note: To specify a specific folder to clone to, add the name of the folder after the repository
URL, like this:
git clone https://github.com/w3schools-test/w3schools-test.github.io.git myfolder
Navigate to the new directory, and check the status:
cd w3schools-test.github.io
git status
On branch master
Your branch is up to date with 'origin/master'.
nothing to commit, working tree clean
And check the log to confirm that we have the full repository data:
git log
commit facaeae8fd87dcb63629f108f401aa9c3614d4e6 (HEAD -> master, origin/master, origin/HEAD)
Merge: e7de78f 5a04b6f
Author: w3schools-test
Date: Fri Mar 26 15:44:10 2021 +0100
Merge branch 'master' of https://github.com/w3schools-test/hello-world
commit e7de78fdefdda51f6f961829fcbdf197e9b926b6
Author: w3schools-test
Date: Fri Mar 26 15:37:22 2021 +0100
Updated index.html. Resized image
.....
Now we have a full copy of the original repository.
Basically, we have a full copy of a repository, whose
origin we are not allowed to make changes to.
Let's see how the remotes of this Git is set up:
git remote -v
origin https://github.com/w3schools-test/w3schools-test.github.io.git (fetch)
origin https://github.com/w3schools-test/w3schools-test.github.io.git (push)
We see that origin is set up to the original "w3schools-test" repository, we also want to add our own
fork.
First, we rename the original
origin remote:
git remote rename origin upstream
git remote -v
upstream https://github.com/w3schools-test/w3schools-test.github.io.git (fetch)
upstream https://github.com/w3schools-test/w3schools-test.github.io.git (push)
Then fetch the URL of our own
fork:
And add that as origin:
git remote add origin https://github.com/kaijim/w3schools-test.github.io.git
git remote -v
origin https://github.com/kaijim/w3schools-test.github.io.git (fetch)
origin https://github.com/kaijim/w3schools-test.github.io.git (push)
upstream https://github.com/w3schools-test/w3schools-test.github.io.git (fetch)
upstream https://github.com/w3schools-test/w3schools-test.github.io.git (push)
Note: According to Git naming conventions, it is recommended to name your own repository
origin, and the one you forked for
upstream
Now we have 2 remotes:
origin - our own
fork, where we have read and write access
upstream - the original, where we have read-only access
Now we are going to make some changes to the code. In the next chapter, we
will cover how we suggest those changes to the original repository.
Clone the repository: https://abc.com/x/y.git to your local Git:
git
Start the Exercise
We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
help@w3schools.com
Your message has been sent to W3Schools. | [
{
"code": null,
"e": 108,
"s": 0,
"text": "Now we have our own fork, but only on GitHub. We also want a \nclone on our local Git to keep working on it."
},
{
"code": null,
"e": 193,
"s": 108,
"text": "A clone is a full copy of a repository, including all logging and versions of files."
},
{
"code": null,
"e": 291,
"s": 193,
"text": "Move back to the original repository, and click the green \"Code\" button to get the \nURL to clone:"
},
{
"code": null,
"e": 336,
"s": 291,
"text": "Open your Git bash and clone the repository:"
},
{
"code": null,
"e": 752,
"s": 336,
"text": "git clone https://github.com/w3schools-test/w3schools-test.github.io.git\nCloning into 'w3schools-test.github.io'...\nremote: Enumerating objects: 33, done.\nremote: Counting objects: 100% (33/33), done.\nremote: Compressing objects: 100% (15/15), done.\nremote: Total 33 (delta 18), reused 33 (delta 18), pack-reused 0\nReceiving objects: 100% (33/33), 94.79 KiB | 3.16 MiB/s, done.\nResolving deltas: 100% (18/18), done."
},
{
"code": null,
"e": 850,
"s": 752,
"text": "Take a look in your file system, and you will see a new directory named after the cloned project:"
},
{
"code": null,
"e": 879,
"s": 850,
"text": "ls\nw3schools-test.github.io/"
},
{
"code": null,
"e": 1078,
"s": 879,
"text": "Note: To specify a specific folder to clone to, add the name of the folder after the repository \nURL, like this: \n git clone https://github.com/w3schools-test/w3schools-test.github.io.git myfolder"
},
{
"code": null,
"e": 1133,
"s": 1078,
"text": "Navigate to the new directory, and check the status:\n\n"
},
{
"code": null,
"e": 1276,
"s": 1133,
"text": "cd w3schools-test.github.io\ngit status\nOn branch master\nYour branch is up to date with 'origin/master'.\n\nnothing to commit, working tree clean"
},
{
"code": null,
"e": 1344,
"s": 1276,
"text": "And check the log to confirm that we have the full repository data:"
},
{
"code": null,
"e": 1769,
"s": 1344,
"text": "git log\ncommit facaeae8fd87dcb63629f108f401aa9c3614d4e6 (HEAD -> master, origin/master, origin/HEAD)\nMerge: e7de78f 5a04b6f\nAuthor: w3schools-test \nDate: Fri Mar 26 15:44:10 2021 +0100\n\n Merge branch 'master' of https://github.com/w3schools-test/hello-world\n\ncommit e7de78fdefdda51f6f961829fcbdf197e9b926b6\nAuthor: w3schools-test \nDate: Fri Mar 26 15:37:22 2021 +0100\n\n Updated index.html. Resized image\n \n....."
},
{
"code": null,
"e": 1821,
"s": 1769,
"text": "Now we have a full copy of the original repository."
},
{
"code": null,
"e": 1922,
"s": 1821,
"text": "Basically, we have a full copy of a repository, whose \norigin we are not allowed to make changes to."
},
{
"code": null,
"e": 1971,
"s": 1922,
"text": "Let's see how the remotes of this Git is set up:"
},
{
"code": null,
"e": 2142,
"s": 1971,
"text": "git remote -v\norigin https://github.com/w3schools-test/w3schools-test.github.io.git (fetch)\norigin https://github.com/w3schools-test/w3schools-test.github.io.git (push)"
},
{
"code": null,
"e": 2251,
"s": 2142,
"text": "We see that origin is set up to the original \"w3schools-test\" repository, we also want to add our own \nfork."
},
{
"code": null,
"e": 2297,
"s": 2251,
"text": "First, we rename the original \norigin remote:"
},
{
"code": null,
"e": 2518,
"s": 2297,
"text": "git remote rename origin upstream\ngit remote -v\nupstream https://github.com/w3schools-test/w3schools-test.github.io.git (fetch)\nupstream https://github.com/w3schools-test/w3schools-test.github.io.git (push)"
},
{
"code": null,
"e": 2555,
"s": 2518,
"text": "Then fetch the URL of our own \nfork:"
},
{
"code": null,
"e": 2579,
"s": 2555,
"text": "And add that as origin:"
},
{
"code": null,
"e": 2984,
"s": 2579,
"text": "git remote add origin https://github.com/kaijim/w3schools-test.github.io.git\ngit remote -v\norigin https://github.com/kaijim/w3schools-test.github.io.git (fetch)\norigin https://github.com/kaijim/w3schools-test.github.io.git (push)\nupstream https://github.com/w3schools-test/w3schools-test.github.io.git (fetch)\nupstream https://github.com/w3schools-test/w3schools-test.github.io.git (push)"
},
{
"code": null,
"e": 3123,
"s": 2984,
"text": "Note: According to Git naming conventions, it is recommended to name your own repository \n origin, and the one you forked for \n upstream"
},
{
"code": null,
"e": 3146,
"s": 3123,
"text": "Now we have 2 remotes:"
},
{
"code": null,
"e": 3208,
"s": 3146,
"text": "origin - our own \n fork, where we have read and write access"
},
{
"code": null,
"e": 3264,
"s": 3208,
"text": "upstream - the original, where we have read-only access"
},
{
"code": null,
"e": 3408,
"s": 3264,
"text": "Now we are going to make some changes to the code. In the next chapter, we \nwill cover how we suggest those changes to the original repository."
},
{
"code": null,
"e": 3473,
"s": 3408,
"text": "Clone the repository: https://abc.com/x/y.git to your local Git:"
},
{
"code": null,
"e": 3480,
"s": 3473,
"text": "git \n"
},
{
"code": null,
"e": 3500,
"s": 3480,
"text": "\nStart the Exercise"
},
{
"code": null,
"e": 3533,
"s": 3500,
"text": "We just launchedW3Schools videos"
},
{
"code": null,
"e": 3575,
"s": 3533,
"text": "Get certifiedby completinga course today!"
},
{
"code": null,
"e": 3682,
"s": 3575,
"text": "If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:"
},
{
"code": null,
"e": 3701,
"s": 3682,
"text": "help@w3schools.com"
}
] |
MapStruct - Quick Guide | MapStruct is an annotation processor which is plugged into Java Compiler. Once plugged in, it can be used by command line tools like maven, gradle to process the mapping annotation to create a mapper class at compile time.
In multilayered applications, data objects are used to fetch data from database and UI interacts with Models. Now data fetched into data models is required to map to Model or java beans to be passed to UI.Consider the following case.
Entity class connected with database.
StudentEntity.java
@Entity
class StudentEntity {
String id;
String name;
}
Model class connected with UI.
Student.java
class Student {
String id;
String name;
}
MapStruct automates the process of creating a mapper to map data objects with model objects using annotations. It creates a mapper implementation at compile time which helps developer to figure out error during development and make is easy to understand. For example −
StudentMapper.java
@Mapper
class StudentMapper {
StudentMapper INSTANCE = Mappers.getMapper( StudentMapper.class );
StudentEntity modelToEntity(Student student);
}
Now StudentMapper.INSTANCE can be used to get mapped objects easily.
StudentEntity studentEntity = StudentMapper.INSTANCE.modelToEntity(student);
MapStruct is a Java based library, so the very first requirement is to have JDK installed on your machine.
You can download the latest version of SDK from Oracle's Java site − Java SE Downloads. You will find instructions for installing JDK in downloaded files, follow the given instructions to install and configure the setup. Finally set PATH and JAVA_HOME environment variables to refer to the directory that contains java and javac, typically java_install_dir/bin and java_install_dir respectively.
If you are running Windows and have installed the JDK in C:\jdk-9.0.1, you would have to put the following line in your C:\autoexec.bat file.
set PATH=C:\jdk-11.0.11\bin;%PATH%
set JAVA_HOME=C:\jdk-11.0.11
Alternatively, on Windows NT/2000/XP, you will have to right-click on My Computer, select Properties → Advanced → Environment Variables. Then, you will have to update the PATH value and click the OK button.
On Unix (Solaris, Linux, etc.), if the SDK is installed in /usr/local/jdk-9.0.1 and you use the C shell, you will have to put the following into your .cshrc file.
setenv PATH /usr/local/jdk-11.0.11/bin:$PATH
setenv JAVA_HOME /usr/local/jdk-11.0.11
Alternatively, if you use an Integrated Development Environment (IDE) like Borland JBuilder, Eclipse, IntelliJ IDEA, or Sun ONE Studio, you will have to compile and run a simple program to confirm that the IDE knows where you have installed Java. Otherwise, you will have to carry out a proper setup as given in the document of the IDE.
Download following jars from MVNRepository and use them in your classpath.
mapstruct-1.5.0.Beta1.jar
mapstruct-1.5.0.Beta1.jar
mapstruct-processor-1.5.0.Beta1.jar
mapstruct-processor-1.5.0.Beta1.jar
Make sure you set your CLASSPATH variable on this directory properly otherwise you will face a problem while running your application.
All the examples in this tutorial have been written using Eclipse IDE. So we would suggest you should have the latest version of Eclipse installed on your machine.
To install Eclipse IDE, download the latest Eclipse binaries from www.eclipse.org/downloads. Once you download the installation, unpack the binary distribution into a convenient location. For example, in C:\eclipse on Windows, or /usr/local/eclipse on Linux/Unix and finally set PATH variable appropriately.
Eclipse can be started by executing the following commands on Windows machine, or you can simply double-click on eclipse.exe
%C:\eclipse\eclipse.exe
Eclipse can be started by executing the following commands on Unix (Solaris, Linux, etc.) machine −
$/usr/local/eclipse/eclipse
After a successful startup, if everything is fine then it should display the following result −
C:\MVN>mvn archetype:generate
-DgroupId = com.tutorialspoint.mapping
-DartifactId = mapping
-DarchetypeArtifactId = maven-archetype-quickstart
-DinteractiveMode = false
It will create a maven project. Now update the pom.xml file as follows −
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.tutorialspoint.mapping</groupId>
<artifactId>mapping</artifactId>
<packaging>jar</packaging>
<version>1.0-SNAPSHOT</version>
<name>mapping</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>5.0.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct</artifactId>
<version>1.5.0.Beta1</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<source>11</source>
<target>11</target>
<annotationProcessorPaths>
<path>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct-processor</artifactId>
<version>1.5.0.Beta1</version>
</path>
</annotationProcessorPaths>
</configuration>
</plugin>
</plugins>
</build>
</project>
Run the following command to update maven dependencies and build project.
mvn package
Once command is successful. Import the maven based project in Eclipse as a maven project. Rest Eclipse will handle.
Using mapstruct is very easy. To create a mapper use org.mapstruct.Mapper annotation on an interface.
@Mapper
public interface StudentMapper {...}
Now create a conversion method in interface.
@Mapper
public interface StudentMapper {
Student getModelFromEntity(StudentEntity student);
}
In case both source and target object properties have same name, those properties will be mapped automatically. In case property name is different, use the @Mapping annotation as following −
@Mapper
public interface StudentMapper {
@Mapping(target="className", source="classVal")
Student getModelFromEntity(StudentEntity student);
}
Here className is the property name in Student, a target object and classVal is the property name in StudentEntity, a source object.
Open project mapping as created in Environment Setup chapter in Eclipse.
Create Student.java with following code −
Student.java
package com.tutorialspoint.model;
public class Student {
private int id;
private String name;
private String className;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getClassName() {
return className;
}
public void setClassName(String className) {
this.className = className;
}
}
Create Student.java with following code −
StudentEntity.java
package com.tutorialspoint.entity;
public class StudentEntity {
private int id;
private String name;
private String classVal;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getClassVal() {
return classVal;
}
public void setClassVal(String classVal) {
this.classVal = classVal;
}
}
Create StudentMapper.java with following code −
StudentMapper.java
package com.tutorialspoint.mapper;
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import com.tutorialspoint.entity.StudentEntity;
import com.tutorialspoint.model.Student;
@Mapper
public interface StudentMapper {
@Mapping(target="className", source="classVal")
Student getModelFromEntity(StudentEntity student);
@Mapping(target="classVal", source="className")
StudentEntity getEntityFromModel(Student student);
}
Create StudentMapperTest.java with following code −
StudentMapperTest.java
package com.tutorialspoint.mapping;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
import org.mapstruct.factory.Mappers;
import com.tutorialspoint.entity.StudentEntity;
import com.tutorialspoint.mapper.StudentMapper;
import com.tutorialspoint.model.Student;
public class StudentMapperTest {
private StudentMapper studentMapper
= Mappers.getMapper(StudentMapper.class);
@Test
public void testEntityToModel() {
StudentEntity entity = new StudentEntity();
entity.setClassVal("X");
entity.setName("John");
entity.setId(1);
Student model = studentMapper.getModelFromEntity(entity);
assertEquals(entity.getClassVal(), model.getClassName());
assertEquals(entity.getName(), model.getName());
assertEquals(entity.getId(), model.getId());
}
@Test
public void testModelToEntity() {
Student model = new Student();
model.setId(1);
model.setName("John");
model.setClassName("X");
StudentEntity entity = studentMapper.getEntityFromModel(model);
assertEquals(entity.getClassVal(), model.getClassName());
assertEquals(entity.getName(), model.getName());
assertEquals(entity.getId(), model.getId());
}
}
Run the follwing command to test the mappings.
mvn clean test
Once command is successful. Verify the output.
mvn clean test
[INFO] Scanning for projects...
...
[INFO] --- maven-surefire-plugin:2.12.4:test (default-test) @ mapping ---
[INFO] Surefire report directory: \mvn\mapping\target\surefire-reports
-------------------------------------------------------
T E S T S
-------------------------------------------------------
Running com.tutorialspoint.mapping.StudentMapperTest
Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.004 sec
...
We can add custom methods as well to the Mapper created using org.mapstruct.Mapper annotation. We can create abstract class as well intead of an Interface. Mapstruct automatically creates the corresponding mapper class.
Now create a default conversion method in interface.
@Mapper
public interface StudentMapper {
default Student getModelFromEntity(StudentEntity studentEntity){
Student student = new Student();
student.setId(studentEntity.getId());
student.setName(studentEntity.getName());
student.setClassName(studentEntity.getClassVal());
return student;
}
}
In similar fashion, we can create an abstract class as well as a mapper.
@Mapper
public absgract class StudentMapper {
Student getModelFromEntity(StudentEntity studentEntity){
Student student = new Student();
student.setId(studentEntity.getId());
student.setName(studentEntity.getName());
student.setClassName(studentEntity.getClassVal());
return student;
}
}
Open project mediaPlayer as created in Environment Setup chapter in Eclipse.
Create Student.java with following code −
Student.java
package com.tutorialspoint.model;
public class Student {
private int id;
private String name;
private String className;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getClassName() {
return className;
}
public void setClassName(String className) {
this.className = className;
}
}
Create Student.java with following code −
StudentEntity.java
package com.tutorialspoint.entity;
public class StudentEntity {
private int id;
private String name;
private String classVal;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getClassVal() {
return classVal;
}
public void setClassVal(String classVal) {
this.classVal = classVal;
}
}
Create StudentMapper.java with following code −
StudentMapper.java
package com.tutorialspoint.mapper;
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import com.tutorialspoint.entity.StudentEntity;
import com.tutorialspoint.model.Student;
@Mapper
public interface StudentMapper {
default Student getModelFromEntity(StudentEntity studentEntity){
Student student = new Student();
student.setId(studentEntity.getId());
student.setName(studentEntity.getName());
student.setClassName(studentEntity.getClassVal());
return student;
}
@Mapping(target="classVal", source="className")
StudentEntity getEntityFromModel(Student student);
}
Create StudentMapperTest.java with following code −
StudentMapperTest.java
package com.tutorialspoint.mapping;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
import org.mapstruct.factory.Mappers;
import com.tutorialspoint.entity.StudentEntity;
import com.tutorialspoint.mapper.StudentMapper;
import com.tutorialspoint.model.Student;
public class StudentMapperTest {
private StudentMapper studentMapper
= Mappers.getMapper(StudentMapper.class);
@Test
public void testEntityToModel() {
StudentEntity entity = new StudentEntity();
entity.setClassVal("X");
entity.setName("John");
entity.setId(1);
Student model = studentMapper.getModelFromEntity(entity);
assertEquals(entity.getClassVal(), model.getClassName());
assertEquals(entity.getName(), model.getName());
assertEquals(entity.getId(), model.getId());
}
@Test
public void testModelToEntity() {
Student model = new Student();
model.setId(1);
model.setName("John");
model.setClassName("X");
StudentEntity entity = studentMapper.getEntityFromModel(model);
assertEquals(entity.getClassVal(), model.getClassName());
assertEquals(entity.getName(), model.getName());
assertEquals(entity.getId(), model.getId());
}
}
Run the follwing command to test the mappings.
mvn clean test
Once command is successful. Verify the output.
mvn clean test
[INFO] Scanning for projects...
...
[INFO] --- maven-surefire-plugin:2.12.4:test (default-test) @ mapping ---
[INFO] Surefire report directory: \mvn\mapping\target\surefire-reports
-------------------------------------------------------
T E S T S
-------------------------------------------------------
Running com.tutorialspoint.mapping.StudentMapperTest
Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.004 sec
...
We can add map multiple objects as well. For Example, we want to get a DeliveryAddress Object using Student and Address object.
Now create a mapper interface which can map two objects into one.
@Mapper
public interface DeliveryAddressMapper {
@Mapping(source = "student.name", target = "name")
@Mapping(source = "address.houseNo", target = "houseNumber")
DeliveryAddress getDeliveryAddress(StudentEntity student, AddressEntity address);
}
Open project mapping as updated in Custom Mapping chapter in Eclipse.
Create DeliveryAddress.java with following code −
DeliveryAddress.java
package com.tutorialspoint.model;
public class DeliveryAddress {
private String name;
private int houseNumber;
private String city;
private String state;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getHouseNumber() {
return houseNumber;
}
public void setHouseNumber(int houseNumber) {
this.houseNumber = houseNumber;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
}
Create AddressEntity.java with following code −
AddressEntity.java
package com.tutorialspoint.entity;
public class AddressEntity {
private int houseNo;
private String city;
private String state;
public int getHouseNo() {
return houseNo;
}
public void setHouseNo(int houseNo) {
this.houseNo = houseNo;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
}
Create DeliveryAddressMapper.java with following code −
DeliveryAddressMapper.java
package com.tutorialspoint.mapper;
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import com.tutorialspoint.entity.AddressEntity;
import com.tutorialspoint.entity.StudentEntity;
import com.tutorialspoint.model.DeliveryAddress;
@Mapper
public interface DeliveryAddressMapper {
@Mapping(source = "student.name", target = "name")
@Mapping(source = "address.houseNo", target = "houseNumber")
DeliveryAddress getDeliveryAddress(StudentEntity student, AddressEntity address);
}
Create DeliveryAddressMapperTest.java with following code −
DeliveryAddressMapperTest.java
package com.tutorialspoint.mapping;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
import org.mapstruct.factory.Mappers;
import com.tutorialspoint.entity.AddressEntity;
import com.tutorialspoint.entity.StudentEntity;
import com.tutorialspoint.mapper.DeliveryAddressMapper;
import com.tutorialspoint.model.DeliveryAddress;
public class DeliveryAddressMapperTest {
private DeliveryAddressMapper deliveryAddressMapper
= Mappers.getMapper(DeliveryAddressMapper.class);
@Test
public void testEntityToModel() {
StudentEntity student = new StudentEntity();
student.setClassVal("X");
student.setName("John");
student.setId(1);
AddressEntity address = new AddressEntity();
address.setCity("Y");
address.setState("Z");
address.setHouseNo(1);
DeliveryAddress deliveryAddress = deliveryAddressMapper.getDeliveryAddress(student, address);
assertEquals(deliveryAddress.getName(), student.getName());
assertEquals(deliveryAddress.getCity(), address.getCity());
assertEquals(deliveryAddress.getState(), address.getState());
assertEquals(deliveryAddress.getHouseNumber(), address.getHouseNo());
}
}
Run the follwing command to test the mappings.
mvn clean test
Once command is successful. Verify the output.
mvn clean test
[INFO] Scanning for projects...
...
[INFO] --- maven-surefire-plugin:2.12.4:test (default-test) @ mapping ---
[INFO] Surefire report directory: \mvn\mapping\target\surefire-reports
-------------------------------------------------------
T E S T S
-------------------------------------------------------
Running com.tutorialspoint.mapping.DeliveryAddressMapperTest
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.011 sec
Running com.tutorialspoint.mapping.StudentMapperTest
Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.001 sec
Results :
Tests run: 3, Failures: 0, Errors: 0, Skipped: 0
...
MapStruct handles nested mapping seemlessly. For example, a Student with Subject as nested bean.
Now create a mapper interface which can map nested objects.
@Mapper
public interface StudentMapper {
@Mapping(target="className", source="classVal")
@Mapping(target="subject", source="subject.name")
Student getModelFromEntity(StudentEntity studentEntity);
@Mapping(target="classVal", source="className")
@Mapping(target="subject.name", source="subject")
StudentEntity getEntityFromModel(Student student);
}
Open project mapping as updated in Mapping Multiple Objects chapter in Eclipse.
Create SubjectEntity.java with following code −
SubjectEntity.java
package com.tutorialspoint.entity;
public class SubjectEntity {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Update StudentEntity.java with following code −
StudentEntity.java
package com.tutorialspoint.entity;
public class StudentEntity {
private int id;
private String name;
private String classVal;
private SubjectEntity subject;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getClassVal() {
return classVal;
}
public void setClassVal(String classVal) {
this.classVal = classVal;
}
public SubjectEntity getSubject() {
return subject;
}
public void setSubject(SubjectEntity subject) {
this.subject = subject;
}
}
Update Student.java with following code −
Student.java
package com.tutorialspoint.model;
public class Student {
private int id;
private String name;
private String className;
private String subject;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getClassName() {
return className;
}
public void setClassName(String className) {
this.className = className;
}
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
}
Update StudentMapper.java with following code −
StudentMapper.java
package com.tutorialspoint.mapper;
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import com.tutorialspoint.entity.StudentEntity;
import com.tutorialspoint.model.Student;
@Mapper
public interface StudentMapper {
@Mapping(target="className", source="classVal")
@Mapping(target="subject", source="subject.name")
Student getModelFromEntity(StudentEntity studentEntity);
@Mapping(target="classVal", source="className")
@Mapping(target="subject.name", source="subject")
StudentEntity getEntityFromModel(Student student);
}
Update StudentMapperTest.java with following code −
StudentMapperTest.java
package com.tutorialspoint.mapping;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
import org.mapstruct.factory.Mappers;
import com.tutorialspoint.entity.StudentEntity;
import com.tutorialspoint.entity.SubjectEntity;
import com.tutorialspoint.mapper.StudentMapper;
import com.tutorialspoint.model.Student;
public class StudentMapperTest {
private StudentMapper studentMapper
= Mappers.getMapper(StudentMapper.class);
@Test
public void testEntityToModel() {
StudentEntity entity = new StudentEntity();
entity.setClassVal("X");
entity.setName("John");
entity.setId(1);
SubjectEntity subject = new SubjectEntity();
subject.setName("Computer");
entity.setSubject(subject);
Student model = studentMapper.getModelFromEntity(entity);
assertEquals(entity.getClassVal(), model.getClassName());
assertEquals(entity.getName(), model.getName());
assertEquals(entity.getId(), model.getId());
assertEquals(entity.getSubject().getName(), model.getSubject());
}
@Test
public void testModelToEntity() {
Student model = new Student();
model.setId(1);
model.setName("John");
model.setClassName("X");
model.setSubject("Science");
StudentEntity entity = studentMapper.getEntityFromModel(model);
assertEquals(entity.getClassVal(), model.getClassName());
assertEquals(entity.getName(), model.getName());
assertEquals(entity.getId(), model.getId());
assertEquals(entity.getSubject().getName(), model.getSubject());
}
}
Run the follwing command to test the mappings.
mvn clean test
Once command is successful. Verify the output.
mvn clean test
[INFO] Scanning for projects...
...
[INFO] --- maven-surefire-plugin:2.12.4:test (default-test) @ mapping ---
[INFO] Surefire report directory: \mvn\mapping\target\surefire-reports
-------------------------------------------------------
T E S T S
-------------------------------------------------------
Running com.tutorialspoint.mapping.DeliveryAddressMapperTest
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.005 sec
Running com.tutorialspoint.mapping.StudentMapperTest
Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.002 sec
Results :
Tests run: 3, Failures: 0, Errors: 0, Skipped: 0
...
MapStruct handles direct fields mapping easily. For example, a Student with section as private property and StudentEntity with section as public property. To have both getter/setter mapping, a property should be public. In case of public final, only getter method will be present for mapping.
Now create a mapper interface. We'll use @InheritInverseConfiguration annotation to copy reverse configuration now.
@Mapper
public interface StudentMapper {
@Mapping(target="className", source="classVal")
@Mapping(target="subject", source="subject.name")
Student getModelFromEntity(StudentEntity studentEntity);
@InheritInverseConfiguration
StudentEntity getEntityFromModel(Student student);
}
Open project mapping as updated in Mapping Nested Objects chapter in Eclipse.
Update StudentEntity.java with following code −
StudentEntity.java
package com.tutorialspoint.entity;
public class StudentEntity {
private int id;
private String name;
private String classVal;
private SubjectEntity subject;
public String section;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getClassVal() {
return classVal;
}
public void setClassVal(String classVal) {
this.classVal = classVal;
}
public SubjectEntity getSubject() {
return subject;
}
public void setSubject(SubjectEntity subject) {
this.subject = subject;
}
}
Update Student.java with following code −
Student.java
package com.tutorialspoint.model;
public class Student {
private int id;
private String name;
private String className;
private String subject;
private String section;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getClassName() {
return className;
}
public void setClassName(String className) {
this.className = className;
}
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
public String getSection() {
return section;
}
public void setSection(String section) {
this.section = section;
}
}
Update StudentMapper.java with following code −
StudentMapper.java
package com.tutorialspoint.mapper;
import org.mapstruct.InheritInverseConfiguration;
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import com.tutorialspoint.entity.StudentEntity;
import com.tutorialspoint.model.Student;
@Mapper
public interface StudentMapper {
@Mapping(target="className", source="classVal")
@Mapping(target="subject", source="subject.name")
Student getModelFromEntity(StudentEntity studentEntity);
@InheritInverseConfiguration
StudentEntity getEntityFromModel(Student student);
}
Update StudentMapperTest.java with following code −
StudentMapperTest.java
package com.tutorialspoint.mapping;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
import org.mapstruct.factory.Mappers;
import com.tutorialspoint.entity.StudentEntity;
import com.tutorialspoint.entity.SubjectEntity;
import com.tutorialspoint.mapper.StudentMapper;
import com.tutorialspoint.model.Student;
public class StudentMapperTest {
private StudentMapper studentMapper
= Mappers.getMapper(StudentMapper.class);
@Test
public void testEntityToModel() {
StudentEntity entity = new StudentEntity();
entity.setClassVal("X");
entity.setName("John");
entity.setId(1);
entity.section = "A";
SubjectEntity subject = new SubjectEntity();
subject.setName("Computer");
entity.setSubject(subject);
Student model = studentMapper.getModelFromEntity(entity);
assertEquals(entity.getClassVal(), model.getClassName());
assertEquals(entity.getName(), model.getName());
assertEquals(entity.getId(), model.getId());
assertEquals(entity.getSubject().getName(), model.getSubject());
assertEquals(entity.section, model.getSection());
}
@Test
public void testModelToEntity() {
Student model = new Student();
model.setId(1);
model.setName("John");
model.setClassName("X");
model.setSubject("Science");
model.setSection("A");
StudentEntity entity = studentMapper.getEntityFromModel(model);
assertEquals(entity.getClassVal(), model.getClassName());
assertEquals(entity.getName(), model.getName());
assertEquals(entity.getId(), model.getId());
assertEquals(entity.getSubject().getName(), model.getSubject());
assertEquals(entity.section, model.getSection());
}
}
Run the follwing command to test the mappings.
mvn clean test
Once command is successful. Verify the output.
mvn clean test
[INFO] Scanning for projects...
...
[INFO] --- maven-surefire-plugin:2.12.4:test (default-test) @ mapping ---
[INFO] Surefire report directory: \mvn\mapping\target\surefire-reports
-------------------------------------------------------
T E S T S
-------------------------------------------------------
Running com.tutorialspoint.mapping.DeliveryAddressMapperTest
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.005 sec
Running com.tutorialspoint.mapping.StudentMapperTest
Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.002 sec
Results :
Tests run: 3, Failures: 0, Errors: 0, Skipped: 0
...
MapStruct allows to use Builders. We can use Builder frameworks or can use our custom builder. In below example, we are using a custom builder.
Open project mapping as updated in Mapping Direct Fields chapter in Eclipse.
Update Student.java with following code −
Student.java
package com.tutorialspoint.model;
public class Student {
private final String name;
private final int id;
protected Student(Student.Builder builder) {
this.name = builder.name;
this.id = builder.id;
}
public static Student.Builder builder() {
return new Student.Builder();
}
public static class Builder {
private String name;
private int id;
public Builder name(String name) {
this.name = name;
return this;
}
public Builder id(int id) {
this.id = id;
return this;
}
public Student create() {
return new Student( this );
}
}
public String getName() {
return name;
}
public int getId() {
return id;
}
}
Update StudentMapper.java with following code −
StudentMapper.java
package com.tutorialspoint.mapper;
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import com.tutorialspoint.entity.StudentEntity;
import com.tutorialspoint.model.Student;
@Mapper
public interface StudentMapper {
Student getModelFromEntity(StudentEntity studentEntity);
@Mapping(target="id", source="id")
@Mapping(target="name", source="name")
StudentEntity getEntityFromModel(Student student);
}
Update StudentMapperTest.java with following code −
StudentMapperTest.java
package com.tutorialspoint.mapping;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
import org.mapstruct.factory.Mappers;
import com.tutorialspoint.entity.StudentEntity;
import com.tutorialspoint.entity.SubjectEntity;
import com.tutorialspoint.mapper.StudentMapper;
import com.tutorialspoint.model.Student;
public class StudentMapperTest {
private StudentMapper studentMapper = Mappers.getMapper(StudentMapper.class);
@Test
public void testEntityToModel() {
StudentEntity entity = new StudentEntity();
entity.setName("John");
entity.setId(1);
Student model = studentMapper.getModelFromEntity(entity);
assertEquals(entity.getName(), model.getName());
assertEquals(entity.getId(), model.getId());
}
@Test
public void testModelToEntity() {
Student.Builder builder = Student.builder().id(1).name("John");
Student model = builder.create();
StudentEntity entity = studentMapper.getEntityFromModel(model);
assertEquals(entity.getName(), model.getName());
assertEquals(entity.getId(), model.getId());
}
}
Run the following command to test the mappings.
mvn clean test
Once command is successful. Verify the output.
mvn clean test
[INFO] Scanning for projects...
...
[INFO] --- maven-surefire-plugin:2.12.4:test (default-test) @ mapping ---
[INFO] Surefire report directory: \mvn\mapping\target\surefire-reports
-------------------------------------------------------
T E S T S
-------------------------------------------------------
Running com.tutorialspoint.mapping.DeliveryAddressMapperTest
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.005 sec
Running com.tutorialspoint.mapping.StudentMapperTest
Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.002 sec
Results :
Tests run: 3, Failures: 0, Errors: 0, Skipped: 0
...
MapStruct handles conversion of type conversions automatically in most of the cases. For example, int to Long or String conversion. Conversion handles null values as well. Following are the some of the important automatic conversions.
Between primitive types and Corresponding Wrapper Classes.
Between primitive types and Corresponding Wrapper Classes.
Between primitive types and String.
Between primitive types and String.
Between enum types and String.
Between enum types and String.
Between BigInt, BigDecimal and String.
Between BigInt, BigDecimal and String.
Between Calendar/Date and XMLGregorianCalendar.
Between Calendar/Date and XMLGregorianCalendar.
Between XMLGregorianCalendar and String.
Between XMLGregorianCalendar and String.
Between Jodas date types and String.
Between Jodas date types and String.
Open project mapping as updated in Mapping Using Builder chapter in Eclipse.
Update StudentEntity.java with following code −
StudentEntity.java
package com.tutorialspoint.entity;
public class StudentEntity {
private String id;
private String name;
private String classVal;
private SubjectEntity subject;
public String section;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getClassVal() {
return classVal;
}
public void setClassVal(String classVal) {
this.classVal = classVal;
}
public SubjectEntity getSubject() {
return subject;
}
public void setSubject(SubjectEntity subject) {
this.subject = subject;
}
}
Student.java is unchanged with following code −
Student.java
package com.tutorialspoint.model;
public class Student {
private final String name;
private final int id;
protected Student(Student.Builder builder) {
this.name = builder.name;
this.id = builder.id;
}
public static Student.Builder builder() {
return new Student.Builder();
}
public static class Builder {
private String name;
private int id;
public Builder name(String name) {
this.name = name;
return this;
}
public Builder id(int id) {
this.id = id;
return this;
}
public Student create() {
return new Student( this );
}
}
public String getName() {
return name;
}
public int getId() {
ret+urn id;
}
}
Update DeliveryAddressMapperTest.java with following code −
DeliveryAddressMapperTest.java
package com.tutorialspoint.mapping;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
import org.mapstruct.factory.Mappers;
import com.tutorialspoint.entity.AddressEntity;
import com.tutorialspoint.entity.StudentEntity;
import com.tutorialspoint.mapper.DeliveryAddressMapper;
import com.tutorialspoint.model.DeliveryAddress;
public class DeliveryAddressMapperTest {
private DeliveryAddressMapper deliveryAddressMapper
= Mappers.getMapper(DeliveryAddressMapper.class);
@Test
public void testEntityToModel() {
StudentEntity student = new StudentEntity();
student.setClassVal("X");
student.setName("John");
student.setId("1");
AddressEntity address = new AddressEntity();
address.setCity("Y");
address.setState("Z");
address.setHouseNo(1);
DeliveryAddress deliveryAddress = deliveryAddressMapper.getDeliveryAddress(student, address);
assertEquals(deliveryAddress.getName(), student.getName());
assertEquals(deliveryAddress.getCity(), address.getCity());
assertEquals(deliveryAddress.getState(), address.getState());
assertEquals(deliveryAddress.getHouseNumber(), address.getHouseNo());
}
}
Update StudentMapperTest.java with following code −
StudentMapperTest.java
package com.tutorialspoint.mapping;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
import org.mapstruct.factory.Mappers;
import com.tutorialspoint.entity.StudentEntity;
import com.tutorialspoint.entity.SubjectEntity;
import com.tutorialspoint.mapper.StudentMapper;
import com.tutorialspoint.model.Student;
public class StudentMapperTest {
private StudentMapper studentMapper
= Mappers.getMapper(StudentMapper.class);
@Test
public void testEntityToModel() {
StudentEntity entity = new StudentEntity();
entity.setName("John");
entity.setId("1");
Student model = studentMapper.getModelFromEntity(entity);
assertEquals(entity.getName(), model.getName());
assertEquals(Integer.parseInt(entity.getId()), model.getId());
}
@Test
public void testModelToEntity() {
Student.Builder builder = Student.builder().id(1).name("John");
Student model = builder.create();
StudentEntity entity = studentMapper.getEntityFromModel(model);
assertEquals(entity.getName(), model.getName());
assertEquals(Integer.parseInt(entity.getId()), model.getId());
}
}
Run the follwing command to test the mappings.
mvn clean test
Once command is successful. Verify the output.
mvn clean test
[INFO] Scanning for projects...
...
[INFO] --- maven-surefire-plugin:2.12.4:test (default-test) @ mapping ---
[INFO] Surefire report directory: \mvn\mapping\target\surefire-reports
-------------------------------------------------------
T E S T S
-------------------------------------------------------
Running com.tutorialspoint.mapping.DeliveryAddressMapperTest
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.005 sec
Running com.tutorialspoint.mapping.StudentMapperTest
Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.002 sec
Results :
Tests run: 3, Failures: 0, Errors: 0, Skipped: 0
...
MapStruct handles conversion of numbers to String in required format seamlessly. We can pass the required format as numberFormat during @Mapping annotation. For example, consider a case where an amount stored in numbers is to be shown in currency format.
Source - Entity has price as 350.
Source - Entity has price as 350.
Target - Model to show price as $350.00.
Target - Model to show price as $350.00.
numberFormat - Use format $#.00
numberFormat - Use format $#.00
Open project mapping as updated in Mapping Implicit Type Conversions chapter in Eclipse.
Create CarEntity.java with following code −
CarEntity.java
package com.tutorialspoint.entity;
public class CarEntity {
private int id;
private double price;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
}
Create Car.java with following code −
Car.java
package com.tutorialspoint.model;
public class Car {
private int id;
private String price;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
}
Create CarMapper.java with following code −
CarMapper.java
package com.tutorialspoint.mapper;
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import com.tutorialspoint.entity.CarEntity;
import com.tutorialspoint.model.Car;
@Mapper
public interface CarMapper {
@Mapping(source = "price", target = "price", numberFormat = "$#.00")
Car getModelFromEntity(CarEntity carEntity);
}
Create CarMapperTest.java with following code −
CarMapperTest.java
package com.tutorialspoint.mapping;
import static org.junit.jupiter.api.Assertions.assertEquals;
import org.junit.jupiter.api.Test;
import org.mapstruct.factory.Mappers;
import com.tutorialspoint.entity.CarEntity;
import com.tutorialspoint.mapper.CarMapper;
import com.tutorialspoint.model.Car;
public class CarMapperTest {
private CarMapper carMapper
= Mappers.getMapper(CarMapper.class);
@Test
public void testEntityToModel() {
CarEntity entity = new CarEntity();
entity.setPrice(345000);
entity.setId(1);
Car model = carMapper.getModelFromEntity(entity);
assertEquals(model.getPrice(), "$345000.00");
assertEquals(entity.getId(), model.getId());
}
}
Run the follwing command to test the mappings.
mvn clean test
Once command is successful. Verify the output.
mvn clean test
[INFO] Scanning for projects...
...
[INFO] --- maven-surefire-plugin:2.12.4:test (default-test) @ mapping ---
[INFO] Surefire report directory: \mvn\mapping\target\surefire-reports
-------------------------------------------------------
T E S T S
-------------------------------------------------------
Running com.tutorialspoint.mapping.CarMapperTest
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.035 sec
Running com.tutorialspoint.mapping.DeliveryAddressMapperTest
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0 sec
Running com.tutorialspoint.mapping.StudentMapperTest
Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.001 sec
Results :
Tests run: 4, Failures: 0, Errors: 0, Skipped: 0
...
MapStruct handles conversion of date to String in required format seamlessly. We can pass the required format as dateFormat during @Mapping annotation. For example, consider a case where a date stored in numbers is to be shown in particular format.
Source - Entity has date as GregorianCalendar(2015, 3, 5).
Source - Entity has date as GregorianCalendar(2015, 3, 5).
Target - Model to show date as 05.04.2015.
Target - Model to show date as 05.04.2015.
dateFormat - Use format dd.MM.yyyy
dateFormat - Use format dd.MM.yyyy
Open project mapping as updated in Mapping Using numberFormat chapter in Eclipse.
Update CarEntity.java with following code −
CarEntity.java
package com.tutorialspoint.entity;
import java.util.GregorianCalendar;
public class CarEntity {
private int id;
private double price;
private GregorianCalendar manufacturingDate;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public GregorianCalendar getManufacturingDate() {
return manufacturingDate;
}
public void setManufacturingDate(GregorianCalendar manufacturingDate) {
this.manufacturingDate = manufacturingDate;
}
}
Update Car.java with following code −
Car.java
package com.tutorialspoint.model;
public class Car {
private int id;
private String price;
private String manufacturingDate;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
public String getManufacturingDate() {
return manufacturingDate;
}
public void setManufacturingDate(String manufacturingDate) {
this.manufacturingDate = manufacturingDate;
}
}
Update CarMapper.java with following code −
CarMapper.java
package com.tutorialspoint.mapper;
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import com.tutorialspoint.entity.CarEntity;
import com.tutorialspoint.model.Car;
@Mapper
public interface CarMapper {
@Mapping(source = "price", target = "price", numberFormat = "$#.00")
@Mapping(source = "manufacturingDate", target = "manufacturingDate", dateFormat = "dd.MM.yyyy")
Car getModelFromEntity(CarEntity carEntity);
}
Update CarMapperTest.java with following code −
CarMapperTest.java
package com.tutorialspoint.mapping;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.GregorianCalendar;
import org.junit.jupiter.api.Test;
import org.mapstruct.factory.Mappers;
import com.tutorialspoint.entity.CarEntity;
import com.tutorialspoint.mapper.CarMapper;
import com.tutorialspoint.model.Car;
public class CarMapperTest {
private CarMapper carMapper
= Mappers.getMapper(CarMapper.class);
@Test
public void testEntityToModel() {
CarEntity entity = new CarEntity();
entity.setPrice(345000);
entity.setId(1);
entity.setManufacturingDate(new GregorianCalendar(2015, 3, 5));
Car model = carMapper.getModelFromEntity(entity);
assertEquals(model.getPrice(), "$345000.00");
assertEquals(entity.getId(), model.getId());
assertEquals("05.04.2015", model.getManufacturingDate());
}
}
Run the follwing command to test the mappings.
mvn clean test
Once command is successful. Verify the output.
mvn clean test
[INFO] Scanning for projects...
...
[INFO] --- maven-surefire-plugin:2.12.4:test (default-test) @ mapping ---
[INFO] Surefire report directory: \mvn\mapping\target\surefire-reports
-------------------------------------------------------
T E S T S
-------------------------------------------------------
Running com.tutorialspoint.mapping.CarMapperTest
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.035 sec
Running com.tutorialspoint.mapping.DeliveryAddressMapperTest
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0 sec
Running com.tutorialspoint.mapping.StudentMapperTest
Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.001 sec
Results :
Tests run: 4, Failures: 0, Errors: 0, Skipped: 0
...
MapStruct allows to call a conversion method for customized logic. We can use expression to achieve the same where we can pass any java object and call its method to do the conversion.
@Mapping(target = "target-property",
expression = "java(target-method())")
Here
target-property - the property for which we are doing the mapping.
target-property - the property for which we are doing the mapping.
expression - mapper will call the java method written in the expression.
expression - mapper will call the java method written in the expression.
target-method - target-method is the method to be called. In case method is present in different class, use new class-name.target-method()
target-method - target-method is the method to be called. In case method is present in different class, use new class-name.target-method()
Open project mapping as updated in Mapping Using dateFormat chapter in Eclipse.
Update CarEntity.java with following code −
CarEntity.java
package com.tutorialspoint.entity;
import java.util.GregorianCalendar;
public class CarEntity {
private int id;
private double price;
private GregorianCalendar manufacturingDate;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public GregorianCalendar getManufacturingDate() {
return manufacturingDate;
}
public void setManufacturingDate(GregorianCalendar manufacturingDate) {
this.manufacturingDate = manufacturingDate;
}
}
Update Car.java with following code −
Car.java
package com.tutorialspoint.model;
public class Car {
private int id;
private String price;
private String manufacturingDate;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
public String getManufacturingDate() {
return manufacturingDate;
}
public void setManufacturingDate(String manufacturingDate) {
this.manufacturingDate = manufacturingDate;
}
}
Update CarMapper.java with following code −
CarMapper.java
package com.tutorialspoint.mapper;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.GregorianCalendar;
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import com.tutorialspoint.entity.CarEntity;
import com.tutorialspoint.model.Car;
@Mapper
public interface CarMapper {
@Mapping(source = "price", target = "price", numberFormat = "$#.00")
@Mapping(target = "manufacturingDate",
expression = "java(getManufacturingDate(carEntity.getManufacturingDate()))")
Car getModelFromEntity(CarEntity carEntity);
default String getManufacturingDate(GregorianCalendar manufacturingDate) {
Date d = manufacturingDate.getTime();
SimpleDateFormat sdf = new SimpleDateFormat( "dd.MM.yyyy" );
return sdf.format( d );
}
}
Update CarMapperTest.java with following code −
CarMapperTest.java
package com.tutorialspoint.mapping;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.GregorianCalendar;
import org.junit.jupiter.api.Test;
import org.mapstruct.factory.Mappers;
import com.tutorialspoint.entity.CarEntity;
import com.tutorialspoint.mapper.CarMapper;
import com.tutorialspoint.model.Car;
public class CarMapperTest {
private CarMapper carMapper
= Mappers.getMapper(CarMapper.class);
@Test
public void testEntityToModel() {
CarEntity entity = new CarEntity();
entity.setPrice(345000);
entity.setId(1);
entity.setManufacturingDate(new GregorianCalendar(2015, 3, 5));
Car model = carMapper.getModelFromEntity(entity);
assertEquals(model.getPrice(), "$345000.00");
assertEquals(entity.getId(), model.getId());
assertEquals("05.04.2015", model.getManufacturingDate());
}
}
Run the follwing command to test the mappings.
mvn clean test
Once command is successful. Verify the output.
mvn clean test
[INFO] Scanning for projects...
...
[INFO] --- maven-surefire-plugin:2.12.4:test (default-test) @ mapping ---
[INFO] Surefire report directory: \mvn\mapping\target\surefire-reports
-------------------------------------------------------
T E S T S
-------------------------------------------------------
Running com.tutorialspoint.mapping.CarMapperTest
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.035 sec
Running com.tutorialspoint.mapping.DeliveryAddressMapperTest
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0 sec
Running com.tutorialspoint.mapping.StudentMapperTest
Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.001 sec
Results :
Tests run: 4, Failures: 0, Errors: 0, Skipped: 0
...
MapStruct allows to map a constant value to a property.
@Mapping(target = "target-property", const = "const-value")
Here
target-property - the property for which we are doing the mapping.
target-property - the property for which we are doing the mapping.
const-value - mapper will map the const-value to target-property.
const-value - mapper will map the const-value to target-property.
Following example demonstrates the same.
Open project mapping as updated in Mapping Using dateFormat chapter in Eclipse.
Update CarEntity.java with following code −
CarEntity.java
package com.tutorialspoint.entity;
import java.util.GregorianCalendar;
public class CarEntity {
private int id;
private double price;
private GregorianCalendar manufacturingDate;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public GregorianCalendar getManufacturingDate() {
return manufacturingDate;
}
public void setManufacturingDate(GregorianCalendar manufacturingDate) {
this.manufacturingDate = manufacturingDate;
}
}
Update Car.java with following code −
Car.java
package com.tutorialspoint.model;
public class Car {
private int id;
private String price;
private String manufacturingDate;
private String brand;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
public String getManufacturingDate() {
return manufacturingDate;
}
public void setManufacturingDate(String manufacturingDate) {
this.manufacturingDate = manufacturingDate;
}
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
}
Update CarMapper.java with following code −
CarMapper.java
package com.tutorialspoint.mapper;
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import com.tutorialspoint.entity.CarEntity;
import com.tutorialspoint.model.Car;
@Mapper
public interface CarMapper {
@Mapping(target = "brand", constant = "BMW")
@Mapping(source = "price", target = "price", numberFormat = "$#.00")
@Mapping(source = "manufacturingDate", target = "manufacturingDate", dateFormat = "dd.MM.yyyy")
Car getModelFromEntity(CarEntity carEntity);
}
Update CarMapperTest.java with following code −
CarMapperTest.java
package com.tutorialspoint.mapping;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.GregorianCalendar;
import org.junit.jupiter.api.Test;
import org.mapstruct.factory.Mappers;
import com.tutorialspoint.entity.CarEntity;
import com.tutorialspoint.mapper.CarMapper;
import com.tutorialspoint.model.Car;
public class CarMapperTest {
private CarMapper carMapper
= Mappers.getMapper(CarMapper.class);
@Test
public void testEntityToModel() {
CarEntity entity = new CarEntity();
entity.setPrice(345000);
entity.setId(1);
entity.setManufacturingDate(new GregorianCalendar(2015, 3, 5));
Car model = carMapper.getModelFromEntity(entity);
assertEquals(model.getPrice(), "$345000.00");
assertEquals(entity.getId(), model.getId());
assertEquals("05.04.2015", model.getManufacturingDate());
assertEquals("BMW", model.getBrand());
}
}
Run the follwing command to test the mappings.
mvn clean test
Once command is successful. Verify the output.
mvn clean test
[INFO] Scanning for projects...
...
[INFO] --- maven-surefire-plugin:2.12.4:test (default-test) @ mapping ---
[INFO] Surefire report directory: \mvn\mapping\target\surefire-reports
-------------------------------------------------------
T E S T S
-------------------------------------------------------
Running com.tutorialspoint.mapping.CarMapperTest
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.035 sec
Running com.tutorialspoint.mapping.DeliveryAddressMapperTest
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0 sec
Running com.tutorialspoint.mapping.StudentMapperTest
Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.001 sec
Results :
Tests run: 4, Failures: 0, Errors: 0, Skipped: 0
...
Using Mapstruct we can pass the default value in case source property is null using defaultValue attribute of @Mapping annotation.
@Mapping(target = "target-property", source="source-property"
defaultValue = "default-value")
Here
default-value - target-property will be set as default-value in case source-property is null.
default-value - target-property will be set as default-value in case source-property is null.
Following example demonstrates the same.
Open project mapping as updated in Mapping Using Constant chapter in Eclipse.
Update CarEntity.java with following code −
CarEntity.java
package com.tutorialspoint.entity;
import java.util.GregorianCalendar;
public class CarEntity {
private int id;
private double price;
private GregorianCalendar manufacturingDate;
private String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public GregorianCalendar getManufacturingDate() {
return manufacturingDate;
}
public void setManufacturingDate(GregorianCalendar manufacturingDate) {
this.manufacturingDate = manufacturingDate;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Update Car.java with following code −
Car.java
package com.tutorialspoint.model;
public class Car {
private int id;
private String price;
private String manufacturingDate;
private String brand;
private String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
public String getManufacturingDate() {
return manufacturingDate;
}
public void setManufacturingDate(String manufacturingDate) {
this.manufacturingDate = manufacturingDate;
}
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Update CarMapper.java with following code −
CarMapper.java
package com.tutorialspoint.mapper;
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import com.tutorialspoint.entity.CarEntity;
import com.tutorialspoint.model.Car;
@Mapper
public interface CarMapper {
@Mapping(source = "name", target = "name", defaultValue = "Sample")
@Mapping(target = "brand", constant = "BMW")
@Mapping(source = "price", target = "price", numberFormat = "$#.00")
@Mapping(source = "manufacturingDate", target = "manufacturingDate", dateFormat = "dd.MM.yyyy")
Car getModelFromEntity(CarEntity carEntity);
}
Update CarMapperTest.java with following code −
CarMapperTest.java
package com.tutorialspoint.mapping;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.GregorianCalendar;
import org.junit.jupiter.api.Test;
import org.mapstruct.factory.Mappers;
import com.tutorialspoint.entity.CarEntity;
import com.tutorialspoint.mapper.CarMapper;
import com.tutorialspoint.model.Car;
public class CarMapperTest {
private CarMapper carMapper
= Mappers.getMapper(CarMapper.class);
@Test
public void testEntityToModel() {
CarEntity entity = new CarEntity();
entity.setPrice(345000);
entity.setId(1);
entity.setManufacturingDate(new GregorianCalendar(2015, 3, 5));
Car model = carMapper.getModelFromEntity(entity);
assertEquals(model.getPrice(), "$345000.00");
assertEquals(entity.getId(), model.getId());
assertEquals("05.04.2015", model.getManufacturingDate());
assertEquals("Sample", model.getName());
assertEquals("BMW", model.getBrand());
}
}
Run the follwing command to test the mappings.
mvn clean test
Once command is successful. Verify the output.
mvn clean test
[INFO] Scanning for projects...
...
[INFO] --- maven-surefire-plugin:2.12.4:test (default-test) @ mapping ---
[INFO] Surefire report directory: \mvn\mapping\target\surefire-reports
-------------------------------------------------------
T E S T S
-------------------------------------------------------
Running com.tutorialspoint.mapping.CarMapperTest
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.035 sec
Running com.tutorialspoint.mapping.DeliveryAddressMapperTest
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0 sec
Running com.tutorialspoint.mapping.StudentMapperTest
Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.001 sec
Results :
Tests run: 4, Failures: 0, Errors: 0, Skipped: 0
...
Using Mapstruct we can pass a computed value using defaultExpression in case source property is null using defaultExpression attribute of @Mapping annotation.
@Mapping(target = "target-property", source="source-property" defaultExpression = "default-value-method")
Here
default-value-method − target-property will be set as result of default-value-method in case source-property is null.
default-value-method − target-property will be set as result of default-value-method in case source-property is null.
Following example demonstrates the same.
Open project mapping as updated in Mapping Using defaultValue chapter in Eclipse.
Update CarEntity.java with following code −
CarEntity.java
package com.tutorialspoint.entity;
import java.util.GregorianCalendar;
public class CarEntity {
private int id;
private double price;
private GregorianCalendar manufacturingDate;
private String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public GregorianCalendar getManufacturingDate() {
return manufacturingDate;
}
public void setManufacturingDate(GregorianCalendar manufacturingDate) {
this.manufacturingDate = manufacturingDate;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Update Car.java with following code −
Car.java
package com.tutorialspoint.model;
public class Car {
private int id;
private String price;
private String manufacturingDate;
private String brand;
private String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
public String getManufacturingDate() {
return manufacturingDate;
}
public void setManufacturingDate(String manufacturingDate) {
this.manufacturingDate = manufacturingDate;
}
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Update CarMapper.java with following code −
CarMapper.java
package com.tutorialspoint.mapper;
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import com.tutorialspoint.entity.CarEntity;
import com.tutorialspoint.model.Car;
import java.util.UUID;
@Mapper( imports = UUID.class )
public interface CarMapper {
@Mapping(source = "name", target = "name", defaultExpression = "java(UUID.randomUUID().toString())")
@Mapping(target = "brand", constant = "BMW")
@Mapping(source = "price", target = "price", numberFormat = "$#.00")
@Mapping(source = "manufacturingDate", target = "manufacturingDate", dateFormat = "dd.MM.yyyy")
Car getModelFromEntity(CarEntity carEntity);
}
Update CarMapperTest.java with following code −
CarMapperTest.java
package com.tutorialspoint.mapping;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import java.util.GregorianCalendar;
import org.junit.jupiter.api.Test;
import org.mapstruct.factory.Mappers;
import com.tutorialspoint.entity.CarEntity;
import com.tutorialspoint.mapper.CarMapper;
import com.tutorialspoint.model.Car;
public class CarMapperTest {
private CarMapper carMapper=Mappers.getMapper(CarMapper.class);
@Test
public void testEntityToModel() {
CarEntity entity = new CarEntity();
entity.setPrice(345000);
entity.setId(1);
entity.setManufacturingDate(new GregorianCalendar(2015, 3, 5));
Car model = carMapper.getModelFromEntity(entity);
assertEquals(model.getPrice(), "$345000.00");
assertEquals(entity.getId(), model.getId());
assertEquals("05.04.2015", model.getManufacturingDate());
assertNotNull(model.getName());
assertEquals("BMW", model.getBrand());
}
}
Run the following command to test the mappings.
mvn clean test
Once command is successful. Verify the output.
mvn clean test
[INFO] Scanning for projects...
...
[INFO] --- maven-surefire-plugin:2.12.4:test (default-test) @ mapping ---
[INFO] Surefire report directory: \mvn\mapping\target\surefire-reports
-------------------------------------------------------
T E S T S
-------------------------------------------------------
Running com.tutorialspoint.mapping.CarMapperTest
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.035 sec
Running com.tutorialspoint.mapping.DeliveryAddressMapperTest
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0 sec
Running com.tutorialspoint.mapping.StudentMapperTest
Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.001 sec
Results :
Tests run: 4, Failures: 0, Errors: 0, Skipped: 0
...
Using Mapstruct we can map list in similar fashion as we map primitives. To get a list of objects, we should provide a mapper method which can map an object.
@Mapper
public interface CarMapper {
List<String> getListOfStrings(List<Integer> listOfIntegers);
List<Car> getCars(List<CarEntity> carEntities);
Car getModelFromEntity(CarEntity carEntity);
}
Following example demonstrates the same.
Open project mapping as updated in Mapping Using defaultExpression chapter in Eclipse.
Update CarEntity.java with following code −
CarEntity.java
package com.tutorialspoint.entity;
import java.util.GregorianCalendar;
public class CarEntity {
private int id;
private double price;
private GregorianCalendar manufacturingDate;
private String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public GregorianCalendar getManufacturingDate() {
return manufacturingDate;
}
public void setManufacturingDate(GregorianCalendar manufacturingDate) {
this.manufacturingDate = manufacturingDate;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Update Car.java with following code −
Car.java
package com.tutorialspoint.model;
public class Car {
private int id;
private String price;
private String manufacturingDate;
private String brand;
private String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
public String getManufacturingDate() {
return manufacturingDate;
}
public void setManufacturingDate(String manufacturingDate) {
this.manufacturingDate = manufacturingDate;
}
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Update CarMapper.java with following code −
CarMapper.java
package com.tutorialspoint.mapper;
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import com.tutorialspoint.entity.CarEntity;
import com.tutorialspoint.model.Car;
import java.util.List;
import java.util.UUID;
@Mapper( imports = UUID.class )
public interface CarMapper {
@Mapping(source = "name", target = "name", defaultExpression = "java(UUID.randomUUID().toString())")
@Mapping(target = "brand", constant = "BMW")
@Mapping(source = "price", target = "price", numberFormat = "$#.00")
@Mapping(source = "manufacturingDate", target = "manufacturingDate", dateFormat = "dd.MM.yyyy")
Car getModelFromEntity(CarEntity carEntity);
List<String> getListOfStrings(List<Integer> listOfIntegers);
List<Car> getCars(List<CarEntity> carEntities);
}
Update CarMapperTest.java with following code −
CarMapperTest.java
package com.tutorialspoint.mapping;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import java.util.Arrays;
import java.util.GregorianCalendar;
import java.util.List;
import org.junit.jupiter.api.Test;
import org.mapstruct.factory.Mappers;
import com.tutorialspoint.entity.CarEntity;
import com.tutorialspoint.mapper.CarMapper;
import com.tutorialspoint.model.Car;
public class CarMapperTest {
private CarMapper carMapper
= Mappers.getMapper(CarMapper.class);
@Test
public void testEntityToModel() {
CarEntity entity = new CarEntity();
entity.setPrice(345000);
entity.setId(1);
entity.setManufacturingDate(new GregorianCalendar(2015, 3, 5));
CarEntity entity1 = new CarEntity();
entity1.setPrice(445000);
entity1.setId(2);
entity1.setManufacturingDate(new GregorianCalendar(2015, 3, 5));
List<CarEntity> carEntities = Arrays.asList(entity, entity1);
Car model = carMapper.getModelFromEntity(entity);
assertEquals("$345000.00",model.getPrice());
assertEquals(entity.getId(), model.getId());
assertEquals("BMW", model.getBrand());
assertEquals("05.04.2015", model.getManufacturingDate());
List<Integer> list = Arrays.asList(1,2,3);
List<String> listOfStrings = carMapper.getListOfStrings(list);
List<Car> listOfCars = carMapper.getCars(carEntities);
assertEquals(3, listOfStrings.size());
assertEquals(2, listOfCars.size());
}
}
Run the follwing command to test the mappings.
mvn clean test
Once command is successful. Verify the output.
mvn clean test
[INFO] Scanning for projects...
...
[INFO] --- maven-surefire-plugin:2.12.4:test (default-test) @ mapping ---
[INFO] Surefire report directory: \mvn\mapping\target\surefire-reports
-------------------------------------------------------
T E S T S
-------------------------------------------------------
Running com.tutorialspoint.mapping.CarMapperTest
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.035 sec
Running com.tutorialspoint.mapping.DeliveryAddressMapperTest
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0 sec
Running com.tutorialspoint.mapping.StudentMapperTest
Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.001 sec
Results :
Tests run: 4, Failures: 0, Errors: 0, Skipped: 0
...
Using Mapstruct we can create mapping of map objects using @MapMapping annotation. Other rules of mapping are same as we've seen so far.
@Mapper
public interface UtilityMapper {
@MapMapping(valueDateFormat = "dd.MM.yyyy")
Map<String, String> getMap(Map<Long, GregorianCalendar> source);
}
Following example demonstrates the same.
Open project mapping as updated in Mapping List chapter in Eclipse.
Create UtilityMapper.java with following code −
UtilityMapper.java
package com.tutorialspoint.mapper;
import java.util.GregorianCalendar;
import java.util.Map;
import org.mapstruct.MapMapping;
import org.mapstruct.Mapper;
@Mapper
public interface UtilityMapper {
@MapMapping(valueDateFormat = "dd.MM.yyyy")
Map<String, String> getMap(Map<Long, GregorianCalendar> source);
}
Create UtilityMapperTest.java with following code −
UtilityMapperTest.java
package com.tutorialspoint.mapping;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.Map;
import org.junit.jupiter.api.Test;
import org.mapstruct.factory.Mappers;
import com.tutorialspoint.mapper.UtilityMapper;
public class UtilityMapperTest {
private UtilityMapper utilityMapper
= Mappers.getMapper(UtilityMapper.class);
@Test
public void testMapMapping() {
Map<Long, GregorianCalendar> source = new HashMap<>();
source.put(1L, new GregorianCalendar(2015, 3, 5));
Map<String, String> target = utilityMapper.getMap(source);
assertEquals("05.04.2015", target.get("1"));
}
}
Run the follwing command to test the mappings.
mvn clean test
Once command is successful. Verify the output.
mvn clean test
[INFO] Scanning for projects...
...
[INFO] --- maven-surefire-plugin:2.12.4:test (default-test) @ mapping ---
[INFO] Surefire report directory: \mvn\mapping\target\surefire-reports
-------------------------------------------------------
T E S T S
-------------------------------------------------------
Running com.tutorialspoint.mapping.CarMapperTest
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.327 sec
Running com.tutorialspoint.mapping.DeliveryAddressMapperTest
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.001 sec
Running com.tutorialspoint.mapping.StudentMapperTest
Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.001 sec
Running com.tutorialspoint.mapping.UtilityMapperTest
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.001 sec
Results :
Tests run: 5, Failures: 0, Errors: 0, Skipped: 0
...
Using Mapstruct we can create mapping of streams in the same way as we did for collections.
@Mapper
public interface UtilityMapper {
Stream<String> getStream(Stream<Integer> source);
}
Following example demonstrates the same.
Open project mapping as updated in Mapping Map chapter in Eclipse.
Update UtilityMapper.java with following code −
UtilityMapper.java
package com.tutorialspoint.mapper;
import java.util.GregorianCalendar;
import java.util.Map;
import java.util.stream.Stream;
import org.mapstruct.MapMapping;
import org.mapstruct.Mapper;
@Mapper
public interface UtilityMapper {
@MapMapping(valueDateFormat = "dd.MM.yyyy")
Map<String, String> getMap(Map<Long, GregorianCalendar> source);
Stream<String> getStream(Stream<Integer> source);
}
Update UtilityMapperTest.java with following code −
UtilityMapperTest.java
package com.tutorialspoint.mapping;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.Arrays;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Stream;
import org.junit.jupiter.api.Test;
import org.mapstruct.factory.Mappers;
import com.tutorialspoint.mapper.UtilityMapper;
public class UtilityMapperTest {
private UtilityMapper utilityMapper=Mappers.getMapper(UtilityMapper.class);
@Test
public void testMapMapping() {
Map<Long, GregorianCalendar> source = new HashMap<>();
source.put(1L, new GregorianCalendar(2015, 3, 5));
Map<String, String> target = utilityMapper.getMap(source);
assertEquals("05.04.2015", target.get("1"));
}
@Test
public void testGetStream() {
Stream<Integer> numbers = Arrays.asList(1, 2, 3, 4).stream();
Stream<String> strings = utilityMapper.getStream(numbers);
assertEquals(4, strings.count());
}
}
Run the following command to test the mappings.
mvn clean test
Once command is successful. Verify the output.
mvn clean test
[INFO] Scanning for projects...
...
[INFO] --- maven-surefire-plugin:2.12.4:test (default-test) @ mapping ---
[INFO] Surefire report directory: \mvn\mapping\target\surefire-reports
-------------------------------------------------------
T E S T S
-------------------------------------------------------
Running com.tutorialspoint.mapping.CarMapperTest
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.327 sec
Running com.tutorialspoint.mapping.DeliveryAddressMapperTest
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.001 sec
Running com.tutorialspoint.mapping.StudentMapperTest
Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.001 sec
Running com.tutorialspoint.mapping.UtilityMapperTest
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.001 sec
Results :
Tests run: 5, Failures: 0, Errors: 0, Skipped: 0
...
Mapstruct automatically maps enums. Enums with same name are mapped automatically. In case of different name, we can use @ValueMapping annotation to do the mapping.
@Mapper
public interface UtilityMapper {
@ValueMapping(source = "EXTRA", target = "SPECIAL")
PlacedOrderType getEnum(OrderType order);
}
Following example demonstrates the same.
Open project mapping as updated in Mapping Stream chapter in Eclipse.
Create OrderType.java with following code −
OrderType.java
package com.tutorialspoint.enums;
public enum OrderType {
EXTRA, NORMAL, STANDARD
}
Create PlacedOrderType.java with following code −
PlacedOrderType.java
package com.tutorialspoint.enums;
public enum PlacedOrderType {
SPECIAL, NORMAL, STANDARD
}
Update UtilityMapper.java with following code −
UtilityMapper.java
package com.tutorialspoint.mapper;
import java.util.GregorianCalendar;
import java.util.Map;
import java.util.stream.Stream;
import org.mapstruct.MapMapping;
import org.mapstruct.Mapper;
import org.mapstruct.ValueMapping;
import com.tutorialspoint.enums.OrderType;
import com.tutorialspoint.enums.PlacedOrderType;
@Mapper
public interface UtilityMapper {
@MapMapping(valueDateFormat = "dd.MM.yyyy")
Map<String, String> getMap(Map<Long, GregorianCalendar> source);
Stream<String> getStream(Stream<Integer> source);
@ValueMapping(source = "EXTRA", target = "SPECIAL")
PlacedOrderType getEnum(OrderType order);
}
Update UtilityMapperTest.java with following code −
UtilityMapperTest.java
package com.tutorialspoint.mapping;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.Arrays;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Stream;
import org.junit.jupiter.api.Test;
import org.mapstruct.factory.Mappers;
import com.tutorialspoint.enums.OrderType;
import com.tutorialspoint.enums.PlacedOrderType;
import com.tutorialspoint.mapper.UtilityMapper;
public class UtilityMapperTest {
private UtilityMapper utilityMapper=Mappers.getMapper(UtilityMapper.class);
@Test
public void testMapMapping() {
Map<Long, GregorianCalendar> source = new HashMap<>();
source.put(1L, new GregorianCalendar(2015, 3, 5));
Map<String, String> target = utilityMapper.getMap(source);
assertEquals("05.04.2015", target.get("1"));
}
@Test
public void testGetStream() {
Stream<Integer> numbers = Arrays.asList(1, 2, 3, 4).stream();
Stream<String> strings = utilityMapper.getStream(numbers);
assertEquals(4, strings.count());
}
@Test
public void testGetEnum() {
PlacedOrderType placedOrderType = utilityMapper.getEnum(OrderType.EXTRA);
PlacedOrderType placedOrderType1 = utilityMapper.getEnum(OrderType.NORMAL);
PlacedOrderType placedOrderType2 = utilityMapper.getEnum(OrderType.STANDARD);
assertEquals(PlacedOrderType.SPECIAL.name(), placedOrderType.name());
assertEquals(PlacedOrderType.NORMAL.name(), placedOrderType1.name());
assertEquals(PlacedOrderType.STANDARD.name(), placedOrderType2.name());
}
}
Run the following command to test the mappings.
mvn clean test
Once command is successful. Verify the output.
mvn clean test
[INFO] Scanning for projects...
...
[INFO] --- maven-surefire-plugin:2.12.4:test (default-test) @ mapping ---
[INFO] Surefire report directory: \mvn\mapping\target\surefire-reports
-------------------------------------------------------
T E S T S
-------------------------------------------------------
Running com.tutorialspoint.mapping.CarMapperTest
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.256 sec
Running com.tutorialspoint.mapping.DeliveryAddressMapperTest
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.001 sec
Running com.tutorialspoint.mapping.StudentMapperTest
Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0 sec
Running com.tutorialspoint.mapping.UtilityMapperTest
Tests run: 3, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0 sec
Results :
Tests run: 7, Failures: 0, Errors: 0, Skipped: 0
...
Mapstruct mapper allows throwing specific exception. Consider a case of custom mapping method where we want to throw our custom exception in case of invalid data.
@Mapper(uses=DateMapper.class)
public interface UtilityMapper {
CarEntity getCarEntity(Car car) throws ParseException;
}
Following example demonstrates the same.
Open project mapping as updated in Mapping Enum chapter in Eclipse.
Update UtilityMapper.java with following code −
UtilityMapper.java
package com.tutorialspoint.mapper;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Map;
import java.util.stream.Stream;
import org.mapstruct.MapMapping;
import org.mapstruct.Mapper;
import org.mapstruct.ValueMapping;
import com.tutorialspoint.entity.CarEntity;
import com.tutorialspoint.enums.OrderType;
import com.tutorialspoint.enums.PlacedOrderType;
import com.tutorialspoint.model.Car;
@Mapper(uses=DateMapper.class)
public interface UtilityMapper {
@MapMapping(valueDateFormat = "dd.MM.yyyy")
Map<String, String> getMap(Map<Long, GregorianCalendar> source);
Stream<String> getStream(Stream<Integer> source);
@ValueMapping(source = "EXTRA", target = "SPECIAL")
PlacedOrderType getEnum(OrderType order);
CarEntity getCarEntity(Car car) throws ParseException;
}
class DateMapper {
public String asString(GregorianCalendar date) {
return date != null ? new SimpleDateFormat( "yyyy-MM-dd" )
.format( date.getTime() ) : null;
}
public GregorianCalendar asDate(String date) throws ParseException {
Date date1 = date != null ? new SimpleDateFormat( "yyyy-MM-dd" )
.parse( date ) : null;
if(date1 != null) {
return new GregorianCalendar(date1.getYear(), date1.getMonth(),date1.getDay());
}
return null;
}
}
Update UtilityMapperTest.java with following code −
UtilityMapperTest.java
package com.tutorialspoint.mapping;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.text.ParseException;
import java.util.Arrays;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Stream;
import org.junit.jupiter.api.Test;
import org.mapstruct.factory.Mappers;
import com.tutorialspoint.entity.CarEntity;
import com.tutorialspoint.enums.OrderType;
import com.tutorialspoint.enums.PlacedOrderType;
import com.tutorialspoint.mapper.UtilityMapper;
import com.tutorialspoint.model.Car;
public class UtilityMapperTest {
private UtilityMapper utilityMapper
= Mappers.getMapper(UtilityMapper.class);
@Test
public void testMapMapping() {
Map<Long, GregorianCalendar> source = new HashMap<>();
source.put(1L, new GregorianCalendar(2015, 3, 5));
Map<String, String> target = utilityMapper.getMap(source);
assertEquals("2015-04-05", target.get("1"));
}
@Test
public void testGetStream() {
Stream<Integer> numbers = Arrays.asList(1, 2, 3, 4).stream();
Stream<String> strings = utilityMapper.getStream(numbers);
assertEquals(4, strings.count());
}
@Test
public void testGetEnum() {
PlacedOrderType placedOrderType = utilityMapper.getEnum(OrderType.EXTRA);
PlacedOrderType placedOrderType1 = utilityMapper.getEnum(OrderType.NORMAL);
PlacedOrderType placedOrderType2 = utilityMapper.getEnum(OrderType.STANDARD);
assertEquals(PlacedOrderType.SPECIAL.name(), placedOrderType.name());
assertEquals(PlacedOrderType.NORMAL.name(), placedOrderType1.name());
assertEquals(PlacedOrderType.STANDARD.name(), placedOrderType2.name());
}
@Test
public void testGetCar() {
Car car = new Car();
car.setId(1);
car.setManufacturingDate("11/10/2020");
boolean exceptionOccured = false;
try {
CarEntity carEntity = utilityMapper.getCarEntity(car);
} catch (ParseException e) {
exceptionOccured = true;
}
assertTrue(exceptionOccured);
}
}
Run the follwing command to test the mappings.
mvn clean test
Once command is successful. Verify the output.
mvn clean test
[INFO] Scanning for projects...
...
[INFO] --- maven-surefire-plugin:2.12.4:test (default-test) @ mapping ---
[INFO] Surefire report directory: \mvn\mapping\target\surefire-reports
-------------------------------------------------------
T E S T S
-------------------------------------------------------
Running com.tutorialspoint.mapping.CarMapperTest
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.256 sec
Running com.tutorialspoint.mapping.DeliveryAddressMapperTest
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.001 sec
Running com.tutorialspoint.mapping.StudentMapperTest
Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0 sec
Running com.tutorialspoint.mapping.UtilityMapperTest
Tests run: 4, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0 sec
Results :
Tests run: 8, Failures: 0, Errors: 0, Skipped: 0
...
Mapstruct mapper allows creating a custom mapper method to map an object. To mapper interface, we can add a default method.
@Mapper(uses=DateMapper.class)
public interface UtilityMapper {
default Car getCar(CarEntity entity) {
Car car = new Car();
car.setId(entity.getId());
car.setName(entity.getName());
return car;
}
}
Following example demonstrates the same.
Open project mapping as updated in Mapping Enum chapter in Eclipse.
Update UtilityMapper.java with following code −
UtilityMapper.java
package com.tutorialspoint.mapper;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Map;
import java.util.stream.Stream;
import org.mapstruct.MapMapping;
import org.mapstruct.Mapper;
import org.mapstruct.ValueMapping;
import com.tutorialspoint.entity.CarEntity;
import com.tutorialspoint.enums.OrderType;
import com.tutorialspoint.enums.PlacedOrderType;
import com.tutorialspoint.model.Car;
@Mapper(uses=DateMapper.class)
public interface UtilityMapper {
@MapMapping(valueDateFormat = "dd.MM.yyyy")
Map<String, String> getMap(Map<Long, GregorianCalendar> source);
Stream<String> getStream(Stream<Integer> source);
@ValueMapping(source = "EXTRA", target = "SPECIAL")
PlacedOrderType getEnum(OrderType order);
CarEntity getCarEntity(Car car) throws ParseException;
default Car getCar(CarEntity entity) {
Car car = new Car();
car.setId(entity.getId());
car.setName(entity.getName());
return car;
}
}
class DateMapper {
public String asString(GregorianCalendar date) {
return date != null ? new SimpleDateFormat( "yyyy-MM-dd" )
.format( date.getTime() ) : null;
}
public GregorianCalendar asDate(String date) throws ParseException {
Date date1 = date != null ? new SimpleDateFormat( "yyyy-MM-dd" )
.parse( date ) : null;
if(date1 != null) {
return new GregorianCalendar(date1.getYear(), date1.getMonth(),date1.getDay());
}
return null;
}
}
Update UtilityMapperTest.java with following code −
UtilityMapperTest.java
package com.tutorialspoint.mapping;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.text.ParseException;
import java.util.Arrays;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Stream;
import org.junit.jupiter.api.Test;
import org.mapstruct.factory.Mappers;
import com.tutorialspoint.entity.CarEntity;
import com.tutorialspoint.enums.OrderType;
import com.tutorialspoint.enums.PlacedOrderType;
import com.tutorialspoint.mapper.UtilityMapper;
import com.tutorialspoint.model.Car;
public class UtilityMapperTest {
private UtilityMapper utilityMapper
= Mappers.getMapper(UtilityMapper.class);
@Test
public void testMapMapping() {
Map<Long, GregorianCalendar> source = new HashMap<>();
source.put(1L, new GregorianCalendar(2015, 3, 5));
Map<String, String> target = utilityMapper.getMap(source);
assertEquals("2015-04-05", target.get("1"));
}
@Test
public void testGetStream() {
Stream<Integer> numbers = Arrays.asList(1, 2, 3, 4).stream();
Stream<String> strings = utilityMapper.getStream(numbers);
assertEquals(4, strings.count());
}
@Test
public void testGetEnum() {
PlacedOrderType placedOrderType = utilityMapper.getEnum(OrderType.EXTRA);
PlacedOrderType placedOrderType1 = utilityMapper.getEnum(OrderType.NORMAL);
PlacedOrderType placedOrderType2 = utilityMapper.getEnum(OrderType.STANDARD);
assertEquals(PlacedOrderType.SPECIAL.name(), placedOrderType.name());
assertEquals(PlacedOrderType.NORMAL.name(), placedOrderType1.name());
assertEquals(PlacedOrderType.STANDARD.name(), placedOrderType2.name());
}
@Test
public void testGetCarEntity() {
Car car = new Car();
car.setId(1);
car.setManufacturingDate("11/10/2020");
boolean exceptionOccured = false;
try {
CarEntity carEntity = utilityMapper.getCarEntity(car);
} catch (ParseException e) {
exceptionOccured = true;
}
assertTrue(exceptionOccured);
}
@Test
public void testGetCar() {
CarEntity entity = new CarEntity();
entity.setId(1);
entity.setName("ZEN");
Car car = utilityMapper.getCar(entity);
assertEquals(entity.getId(), car.getId());
assertEquals(entity.getName(), car.getName());
}
}
Run the follwing command to test the mappings.
mvn clean test
Once command is successful. Verify the output.
mvn clean test
[INFO] Scanning for projects...
...
[INFO] --- maven-surefire-plugin:2.12.4:test (default-test) @ mapping ---
[INFO] Surefire report directory: \mvn\mapping\target\surefire-reports
-------------------------------------------------------
T E S T S
-------------------------------------------------------
Running com.tutorialspoint.mapping.CarMapperTest
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.256 sec
Running com.tutorialspoint.mapping.DeliveryAddressMapperTest
Tests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.001 sec
Running com.tutorialspoint.mapping.StudentMapperTest
Tests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0 sec
Running com.tutorialspoint.mapping.UtilityMapperTest
Tests run: 5, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0 sec
Results :
Tests run: 9, Failures: 0, Errors: 0, Skipped: 0
...
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2483,
"s": 2260,
"text": "MapStruct is an annotation processor which is plugged into Java Compiler. Once plugged in, it can be used by command line tools like maven, gradle to process the mapping annotation to create a mapper class at compile time."
},
{
"code": null,
"e": 2717,
"s": 2483,
"text": "In multilayered applications, data objects are used to fetch data from database and UI interacts with Models. Now data fetched into data models is required to map to Model or java beans to be passed to UI.Consider the following case."
},
{
"code": null,
"e": 2755,
"s": 2717,
"text": "Entity class connected with database."
},
{
"code": null,
"e": 2774,
"s": 2755,
"text": "StudentEntity.java"
},
{
"code": null,
"e": 2836,
"s": 2774,
"text": "@Entity\nclass StudentEntity {\n String id;\n String name;\n}"
},
{
"code": null,
"e": 2867,
"s": 2836,
"text": "Model class connected with UI."
},
{
"code": null,
"e": 2880,
"s": 2867,
"text": "Student.java"
},
{
"code": null,
"e": 2928,
"s": 2880,
"text": "class Student {\n String id;\n String name;\n}"
},
{
"code": null,
"e": 3198,
"s": 2928,
"text": "MapStruct automates the process of creating a mapper to map data objects with model objects using annotations. It creates a mapper implementation at compile time which helps developer to figure out error during development and make is easy to understand. For example −"
},
{
"code": null,
"e": 3217,
"s": 3198,
"text": "StudentMapper.java"
},
{
"code": null,
"e": 3371,
"s": 3217,
"text": "@Mapper\nclass StudentMapper {\n StudentMapper INSTANCE = Mappers.getMapper( StudentMapper.class ); \n StudentEntity modelToEntity(Student student);\n}"
},
{
"code": null,
"e": 3440,
"s": 3371,
"text": "Now StudentMapper.INSTANCE can be used to get mapped objects easily."
},
{
"code": null,
"e": 3518,
"s": 3440,
"text": "StudentEntity studentEntity = StudentMapper.INSTANCE.modelToEntity(student);\n"
},
{
"code": null,
"e": 3625,
"s": 3518,
"text": "MapStruct is a Java based library, so the very first requirement is to have JDK installed on your machine."
},
{
"code": null,
"e": 4021,
"s": 3625,
"text": "You can download the latest version of SDK from Oracle's Java site − Java SE Downloads. You will find instructions for installing JDK in downloaded files, follow the given instructions to install and configure the setup. Finally set PATH and JAVA_HOME environment variables to refer to the directory that contains java and javac, typically java_install_dir/bin and java_install_dir respectively."
},
{
"code": null,
"e": 4163,
"s": 4021,
"text": "If you are running Windows and have installed the JDK in C:\\jdk-9.0.1, you would have to put the following line in your C:\\autoexec.bat file."
},
{
"code": null,
"e": 4229,
"s": 4163,
"text": "set PATH=C:\\jdk-11.0.11\\bin;%PATH% \nset JAVA_HOME=C:\\jdk-11.0.11\n"
},
{
"code": null,
"e": 4436,
"s": 4229,
"text": "Alternatively, on Windows NT/2000/XP, you will have to right-click on My Computer, select Properties → Advanced → Environment Variables. Then, you will have to update the PATH value and click the OK button."
},
{
"code": null,
"e": 4599,
"s": 4436,
"text": "On Unix (Solaris, Linux, etc.), if the SDK is installed in /usr/local/jdk-9.0.1 and you use the C shell, you will have to put the following into your .cshrc file."
},
{
"code": null,
"e": 4686,
"s": 4599,
"text": "setenv PATH /usr/local/jdk-11.0.11/bin:$PATH \nsetenv JAVA_HOME /usr/local/jdk-11.0.11\n"
},
{
"code": null,
"e": 5023,
"s": 4686,
"text": "Alternatively, if you use an Integrated Development Environment (IDE) like Borland JBuilder, Eclipse, IntelliJ IDEA, or Sun ONE Studio, you will have to compile and run a simple program to confirm that the IDE knows where you have installed Java. Otherwise, you will have to carry out a proper setup as given in the document of the IDE."
},
{
"code": null,
"e": 5098,
"s": 5023,
"text": "Download following jars from MVNRepository and use them in your classpath."
},
{
"code": null,
"e": 5124,
"s": 5098,
"text": "mapstruct-1.5.0.Beta1.jar"
},
{
"code": null,
"e": 5150,
"s": 5124,
"text": "mapstruct-1.5.0.Beta1.jar"
},
{
"code": null,
"e": 5186,
"s": 5150,
"text": "mapstruct-processor-1.5.0.Beta1.jar"
},
{
"code": null,
"e": 5222,
"s": 5186,
"text": "mapstruct-processor-1.5.0.Beta1.jar"
},
{
"code": null,
"e": 5357,
"s": 5222,
"text": "Make sure you set your CLASSPATH variable on this directory properly otherwise you will face a problem while running your application."
},
{
"code": null,
"e": 5521,
"s": 5357,
"text": "All the examples in this tutorial have been written using Eclipse IDE. So we would suggest you should have the latest version of Eclipse installed on your machine."
},
{
"code": null,
"e": 5829,
"s": 5521,
"text": "To install Eclipse IDE, download the latest Eclipse binaries from www.eclipse.org/downloads. Once you download the installation, unpack the binary distribution into a convenient location. For example, in C:\\eclipse on Windows, or /usr/local/eclipse on Linux/Unix and finally set PATH variable appropriately."
},
{
"code": null,
"e": 5954,
"s": 5829,
"text": "Eclipse can be started by executing the following commands on Windows machine, or you can simply double-click on eclipse.exe"
},
{
"code": null,
"e": 5980,
"s": 5954,
"text": "%C:\\eclipse\\eclipse.exe \n"
},
{
"code": null,
"e": 6080,
"s": 5980,
"text": "Eclipse can be started by executing the following commands on Unix (Solaris, Linux, etc.) machine −"
},
{
"code": null,
"e": 6109,
"s": 6080,
"text": "$/usr/local/eclipse/eclipse\n"
},
{
"code": null,
"e": 6205,
"s": 6109,
"text": "After a successful startup, if everything is fine then it should display the following result −"
},
{
"code": null,
"e": 6378,
"s": 6205,
"text": "C:\\MVN>mvn archetype:generate\n-DgroupId = com.tutorialspoint.mapping \n-DartifactId = mapping \n-DarchetypeArtifactId = maven-archetype-quickstart \n-DinteractiveMode = false\n"
},
{
"code": null,
"e": 6451,
"s": 6378,
"text": "It will create a maven project. Now update the pom.xml file as follows −"
},
{
"code": null,
"e": 8004,
"s": 6451,
"text": "<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd\">\n <modelVersion>4.0.0</modelVersion>\n <groupId>com.tutorialspoint.mapping</groupId>\n <artifactId>mapping</artifactId>\n <packaging>jar</packaging>\n <version>1.0-SNAPSHOT</version>\n <name>mapping</name>\n <url>http://maven.apache.org</url>\n <dependencies>\n <dependency>\n <groupId>org.junit.jupiter</groupId>\n <artifactId>junit-jupiter-engine</artifactId>\n <version>5.0.0</version>\n <scope>test</scope>\n </dependency>\n <dependency>\n <groupId>org.mapstruct</groupId>\n <artifactId>mapstruct</artifactId>\n <version>1.5.0.Beta1</version>\n </dependency>\n </dependencies>\n <build>\n <plugins>\n <plugin>\n <groupId>org.apache.maven.plugins</groupId>\n <artifactId>maven-compiler-plugin</artifactId>\n <version>3.8.1</version>\n <configuration>\n <source>11</source> \n <target>11</target> \n <annotationProcessorPaths>\n <path>\n <groupId>org.mapstruct</groupId>\n <artifactId>mapstruct-processor</artifactId>\n <version>1.5.0.Beta1</version>\n </path>\n </annotationProcessorPaths>\n </configuration>\n </plugin>\n </plugins>\n </build>\n</project>"
},
{
"code": null,
"e": 8078,
"s": 8004,
"text": "Run the following command to update maven dependencies and build project."
},
{
"code": null,
"e": 8091,
"s": 8078,
"text": "mvn package\n"
},
{
"code": null,
"e": 8207,
"s": 8091,
"text": "Once command is successful. Import the maven based project in Eclipse as a maven project. Rest Eclipse will handle."
},
{
"code": null,
"e": 8309,
"s": 8207,
"text": "Using mapstruct is very easy. To create a mapper use org.mapstruct.Mapper annotation on an interface."
},
{
"code": null,
"e": 8354,
"s": 8309,
"text": "@Mapper\npublic interface StudentMapper {...}"
},
{
"code": null,
"e": 8399,
"s": 8354,
"text": "Now create a conversion method in interface."
},
{
"code": null,
"e": 8496,
"s": 8399,
"text": "@Mapper\npublic interface StudentMapper {\n Student getModelFromEntity(StudentEntity student);\n}"
},
{
"code": null,
"e": 8687,
"s": 8496,
"text": "In case both source and target object properties have same name, those properties will be mapped automatically. In case property name is different, use the @Mapping annotation as following −"
},
{
"code": null,
"e": 8835,
"s": 8687,
"text": "@Mapper\npublic interface StudentMapper {\n @Mapping(target=\"className\", source=\"classVal\")\n Student getModelFromEntity(StudentEntity student);\n}"
},
{
"code": null,
"e": 8968,
"s": 8835,
"text": "Here className is the property name in Student, a target object and classVal is the property name in StudentEntity, a source object."
},
{
"code": null,
"e": 9041,
"s": 8968,
"text": "Open project mapping as created in Environment Setup chapter in Eclipse."
},
{
"code": null,
"e": 9083,
"s": 9041,
"text": "Create Student.java with following code −"
},
{
"code": null,
"e": 9096,
"s": 9083,
"text": "Student.java"
},
{
"code": null,
"e": 9601,
"s": 9096,
"text": "package com.tutorialspoint.model;\n\npublic class Student {\n private int id;\n private String name;\n private String className;\n\n public int getId() {\n return id;\n }\n public void setId(int id) {\n this.id = id;\n }\n public String getName() {\n return name;\n }\n public void setName(String name) {\n this.name = name;\n }\n public String getClassName() {\n return className;\n }\n public void setClassName(String className) {\n this.className = className;\n }\n}"
},
{
"code": null,
"e": 9643,
"s": 9601,
"text": "Create Student.java with following code −"
},
{
"code": null,
"e": 9662,
"s": 9643,
"text": "StudentEntity.java"
},
{
"code": null,
"e": 10166,
"s": 9662,
"text": "package com.tutorialspoint.entity;\n\npublic class StudentEntity {\n private int id;\n private String name;\n private String classVal;\n public int getId() {\n return id;\n }\n public void setId(int id) {\n this.id = id;\n }\n public String getName() {\n return name;\n }\n public void setName(String name) {\n this.name = name;\n }\n public String getClassVal() {\n return classVal;\n }\n public void setClassVal(String classVal) {\n this.classVal = classVal;\n }\n}"
},
{
"code": null,
"e": 10214,
"s": 10166,
"text": "Create StudentMapper.java with following code −"
},
{
"code": null,
"e": 10233,
"s": 10214,
"text": "StudentMapper.java"
},
{
"code": null,
"e": 10674,
"s": 10233,
"text": "package com.tutorialspoint.mapper;\n\nimport org.mapstruct.Mapper;\nimport org.mapstruct.Mapping;\n\nimport com.tutorialspoint.entity.StudentEntity;\nimport com.tutorialspoint.model.Student;\n\n@Mapper\npublic interface StudentMapper {\n\n @Mapping(target=\"className\", source=\"classVal\")\n Student getModelFromEntity(StudentEntity student);\n\n @Mapping(target=\"classVal\", source=\"className\")\n StudentEntity getEntityFromModel(Student student);\n}"
},
{
"code": null,
"e": 10726,
"s": 10674,
"text": "Create StudentMapperTest.java with following code −"
},
{
"code": null,
"e": 10749,
"s": 10726,
"text": "StudentMapperTest.java"
},
{
"code": null,
"e": 12018,
"s": 10749,
"text": "package com.tutorialspoint.mapping;\n\nimport static org.junit.jupiter.api.Assertions.assertEquals;\n\nimport org.junit.jupiter.api.Test;\nimport org.mapstruct.factory.Mappers;\n\nimport com.tutorialspoint.entity.StudentEntity;\nimport com.tutorialspoint.mapper.StudentMapper;\nimport com.tutorialspoint.model.Student;\n\npublic class StudentMapperTest {\n\n private StudentMapper studentMapper\n = Mappers.getMapper(StudentMapper.class);\n\n @Test\n public void testEntityToModel() {\n StudentEntity entity = new StudentEntity();\n entity.setClassVal(\"X\");\n entity.setName(\"John\");\n entity.setId(1);\n\n Student model = studentMapper.getModelFromEntity(entity);\n\n assertEquals(entity.getClassVal(), model.getClassName());\n assertEquals(entity.getName(), model.getName());\n assertEquals(entity.getId(), model.getId());\n }\n\n @Test\n public void testModelToEntity() {\n Student model = new Student();\n model.setId(1);\n model.setName(\"John\");\n model.setClassName(\"X\");\n\n StudentEntity entity = studentMapper.getEntityFromModel(model);\n\n assertEquals(entity.getClassVal(), model.getClassName());\n assertEquals(entity.getName(), model.getName());\n assertEquals(entity.getId(), model.getId());\n }\n}"
},
{
"code": null,
"e": 12065,
"s": 12018,
"text": "Run the follwing command to test the mappings."
},
{
"code": null,
"e": 12081,
"s": 12065,
"text": "mvn clean test\n"
},
{
"code": null,
"e": 12128,
"s": 12081,
"text": "Once command is successful. Verify the output."
},
{
"code": null,
"e": 12580,
"s": 12128,
"text": "mvn clean test\n[INFO] Scanning for projects...\n...\n[INFO] --- maven-surefire-plugin:2.12.4:test (default-test) @ mapping ---\n[INFO] Surefire report directory: \\mvn\\mapping\\target\\surefire-reports\n\n-------------------------------------------------------\n T E S T S\n-------------------------------------------------------\nRunning com.tutorialspoint.mapping.StudentMapperTest\nTests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.004 sec\n...\n"
},
{
"code": null,
"e": 12800,
"s": 12580,
"text": "We can add custom methods as well to the Mapper created using org.mapstruct.Mapper annotation. We can create abstract class as well intead of an Interface. Mapstruct automatically creates the corresponding mapper class."
},
{
"code": null,
"e": 12853,
"s": 12800,
"text": "Now create a default conversion method in interface."
},
{
"code": null,
"e": 13179,
"s": 12853,
"text": "@Mapper\npublic interface StudentMapper {\n default Student getModelFromEntity(StudentEntity studentEntity){\n Student student = new Student();\n student.setId(studentEntity.getId());\n student.setName(studentEntity.getName());\n student.setClassName(studentEntity.getClassVal());\n return student;\n }\n}"
},
{
"code": null,
"e": 13252,
"s": 13179,
"text": "In similar fashion, we can create an abstract class as well as a mapper."
},
{
"code": null,
"e": 13575,
"s": 13252,
"text": "@Mapper\npublic absgract class StudentMapper {\n Student getModelFromEntity(StudentEntity studentEntity){\n Student student = new Student();\n student.setId(studentEntity.getId());\n student.setName(studentEntity.getName());\n student.setClassName(studentEntity.getClassVal());\n return student;\n }\n}"
},
{
"code": null,
"e": 13652,
"s": 13575,
"text": "Open project mediaPlayer as created in Environment Setup chapter in Eclipse."
},
{
"code": null,
"e": 13694,
"s": 13652,
"text": "Create Student.java with following code −"
},
{
"code": null,
"e": 13707,
"s": 13694,
"text": "Student.java"
},
{
"code": null,
"e": 14212,
"s": 13707,
"text": "package com.tutorialspoint.model;\n\npublic class Student {\n private int id;\n private String name;\n private String className;\n\n public int getId() {\n return id;\n }\n public void setId(int id) {\n this.id = id;\n }\n public String getName() {\n return name;\n }\n public void setName(String name) {\n this.name = name;\n }\n public String getClassName() {\n return className;\n }\n public void setClassName(String className) {\n this.className = className;\n }\n}"
},
{
"code": null,
"e": 14254,
"s": 14212,
"text": "Create Student.java with following code −"
},
{
"code": null,
"e": 14273,
"s": 14254,
"text": "StudentEntity.java"
},
{
"code": null,
"e": 14777,
"s": 14273,
"text": "package com.tutorialspoint.entity;\n\npublic class StudentEntity {\n private int id;\n private String name;\n private String classVal;\n public int getId() {\n return id;\n }\n public void setId(int id) {\n this.id = id;\n }\n public String getName() {\n return name;\n }\n public void setName(String name) {\n this.name = name;\n }\n public String getClassVal() {\n return classVal;\n }\n public void setClassVal(String classVal) {\n this.classVal = classVal;\n }\n}"
},
{
"code": null,
"e": 14825,
"s": 14777,
"text": "Create StudentMapper.java with following code −"
},
{
"code": null,
"e": 14844,
"s": 14825,
"text": "StudentMapper.java"
},
{
"code": null,
"e": 15463,
"s": 14844,
"text": "package com.tutorialspoint.mapper;\n\nimport org.mapstruct.Mapper;\nimport org.mapstruct.Mapping;\n\nimport com.tutorialspoint.entity.StudentEntity;\nimport com.tutorialspoint.model.Student;\n\n@Mapper\npublic interface StudentMapper {\n\n default Student getModelFromEntity(StudentEntity studentEntity){\n Student student = new Student();\n student.setId(studentEntity.getId());\n student.setName(studentEntity.getName());\n student.setClassName(studentEntity.getClassVal());\n return student;\n }\n\n @Mapping(target=\"classVal\", source=\"className\")\n StudentEntity getEntityFromModel(Student student);\n}"
},
{
"code": null,
"e": 15515,
"s": 15463,
"text": "Create StudentMapperTest.java with following code −"
},
{
"code": null,
"e": 15538,
"s": 15515,
"text": "StudentMapperTest.java"
},
{
"code": null,
"e": 16807,
"s": 15538,
"text": "package com.tutorialspoint.mapping;\n\nimport static org.junit.jupiter.api.Assertions.assertEquals;\n\nimport org.junit.jupiter.api.Test;\nimport org.mapstruct.factory.Mappers;\n\nimport com.tutorialspoint.entity.StudentEntity;\nimport com.tutorialspoint.mapper.StudentMapper;\nimport com.tutorialspoint.model.Student;\n\npublic class StudentMapperTest {\n\n private StudentMapper studentMapper\n = Mappers.getMapper(StudentMapper.class);\n\n @Test\n public void testEntityToModel() {\n StudentEntity entity = new StudentEntity();\n entity.setClassVal(\"X\");\n entity.setName(\"John\");\n entity.setId(1);\n\n Student model = studentMapper.getModelFromEntity(entity);\n\n assertEquals(entity.getClassVal(), model.getClassName());\n assertEquals(entity.getName(), model.getName());\n assertEquals(entity.getId(), model.getId());\n }\n\n @Test\n public void testModelToEntity() {\n Student model = new Student();\n model.setId(1);\n model.setName(\"John\");\n model.setClassName(\"X\");\n\n StudentEntity entity = studentMapper.getEntityFromModel(model);\n\n assertEquals(entity.getClassVal(), model.getClassName());\n assertEquals(entity.getName(), model.getName());\n assertEquals(entity.getId(), model.getId());\n }\n}"
},
{
"code": null,
"e": 16854,
"s": 16807,
"text": "Run the follwing command to test the mappings."
},
{
"code": null,
"e": 16870,
"s": 16854,
"text": "mvn clean test\n"
},
{
"code": null,
"e": 16917,
"s": 16870,
"text": "Once command is successful. Verify the output."
},
{
"code": null,
"e": 17369,
"s": 16917,
"text": "mvn clean test\n[INFO] Scanning for projects...\n...\n[INFO] --- maven-surefire-plugin:2.12.4:test (default-test) @ mapping ---\n[INFO] Surefire report directory: \\mvn\\mapping\\target\\surefire-reports\n\n-------------------------------------------------------\n T E S T S\n-------------------------------------------------------\nRunning com.tutorialspoint.mapping.StudentMapperTest\nTests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.004 sec\n...\n"
},
{
"code": null,
"e": 17497,
"s": 17369,
"text": "We can add map multiple objects as well. For Example, we want to get a DeliveryAddress Object using Student and Address object."
},
{
"code": null,
"e": 17563,
"s": 17497,
"text": "Now create a mapper interface which can map two objects into one."
},
{
"code": null,
"e": 17820,
"s": 17563,
"text": "@Mapper\npublic interface DeliveryAddressMapper {\n @Mapping(source = \"student.name\", target = \"name\")\n @Mapping(source = \"address.houseNo\", target = \"houseNumber\")\n DeliveryAddress getDeliveryAddress(StudentEntity student, AddressEntity address); \n}"
},
{
"code": null,
"e": 17890,
"s": 17820,
"text": "Open project mapping as updated in Custom Mapping chapter in Eclipse."
},
{
"code": null,
"e": 17940,
"s": 17890,
"text": "Create DeliveryAddress.java with following code −"
},
{
"code": null,
"e": 17961,
"s": 17940,
"text": "DeliveryAddress.java"
},
{
"code": null,
"e": 18581,
"s": 17961,
"text": "package com.tutorialspoint.model;\n\npublic class DeliveryAddress {\t\n\tprivate String name;\n\tprivate int houseNumber;\n\tprivate String city;\n\tprivate String state;\n\tpublic String getName() {\n\t\treturn name;\n\t}\n\tpublic void setName(String name) {\n\t\tthis.name = name;\n\t}\n\tpublic int getHouseNumber() {\n\t\treturn houseNumber;\n\t}\n\tpublic void setHouseNumber(int houseNumber) {\n\t\tthis.houseNumber = houseNumber;\n\t}\n\tpublic String getCity() {\n\t\treturn city;\n\t}\n\tpublic void setCity(String city) {\n\t\tthis.city = city;\n\t}\n\tpublic String getState() {\n\t\treturn state;\n\t}\n\tpublic void setState(String state) {\n\t\tthis.state = state;\n\t}\n}"
},
{
"code": null,
"e": 18629,
"s": 18581,
"text": "Create AddressEntity.java with following code −"
},
{
"code": null,
"e": 18648,
"s": 18629,
"text": "AddressEntity.java"
},
{
"code": null,
"e": 19112,
"s": 18648,
"text": "package com.tutorialspoint.entity;\n\npublic class AddressEntity {\n\tprivate int houseNo;\n\tprivate String city;\n\tprivate String state;\n\tpublic int getHouseNo() {\n\t\treturn houseNo;\n\t}\n\tpublic void setHouseNo(int houseNo) {\n\t\tthis.houseNo = houseNo;\n\t}\n\tpublic String getCity() {\n\t\treturn city;\n\t}\n\tpublic void setCity(String city) {\n\t\tthis.city = city;\n\t}\n\tpublic String getState() {\n\t\treturn state;\n\t}\n\tpublic void setState(String state) {\n\t\tthis.state = state;\n\t}\n}"
},
{
"code": null,
"e": 19168,
"s": 19112,
"text": "Create DeliveryAddressMapper.java with following code −"
},
{
"code": null,
"e": 19195,
"s": 19168,
"text": "DeliveryAddressMapper.java"
},
{
"code": null,
"e": 19694,
"s": 19195,
"text": "package com.tutorialspoint.mapper;\n\nimport org.mapstruct.Mapper;\nimport org.mapstruct.Mapping;\n\nimport com.tutorialspoint.entity.AddressEntity;\nimport com.tutorialspoint.entity.StudentEntity;\nimport com.tutorialspoint.model.DeliveryAddress;\n\n@Mapper\npublic interface DeliveryAddressMapper {\n @Mapping(source = \"student.name\", target = \"name\")\n @Mapping(source = \"address.houseNo\", target = \"houseNumber\")\n DeliveryAddress getDeliveryAddress(StudentEntity student, AddressEntity address); \n}"
},
{
"code": null,
"e": 19754,
"s": 19694,
"text": "Create DeliveryAddressMapperTest.java with following code −"
},
{
"code": null,
"e": 19785,
"s": 19754,
"text": "DeliveryAddressMapperTest.java"
},
{
"code": null,
"e": 21023,
"s": 19785,
"text": "package com.tutorialspoint.mapping;\n\nimport static org.junit.jupiter.api.Assertions.assertEquals;\n\nimport org.junit.jupiter.api.Test;\nimport org.mapstruct.factory.Mappers;\n\nimport com.tutorialspoint.entity.AddressEntity;\nimport com.tutorialspoint.entity.StudentEntity;\nimport com.tutorialspoint.mapper.DeliveryAddressMapper;\nimport com.tutorialspoint.model.DeliveryAddress;\n\npublic class DeliveryAddressMapperTest {\n\n private DeliveryAddressMapper deliveryAddressMapper\n = Mappers.getMapper(DeliveryAddressMapper.class);\n\n @Test\n public void testEntityToModel() {\n StudentEntity student = new StudentEntity();\n student.setClassVal(\"X\");\n student.setName(\"John\");\n student.setId(1);\n\n AddressEntity address = new AddressEntity();\n address.setCity(\"Y\");\n address.setState(\"Z\");\n address.setHouseNo(1);\n\n DeliveryAddress deliveryAddress = deliveryAddressMapper.getDeliveryAddress(student, address);\n\n assertEquals(deliveryAddress.getName(), student.getName());\n assertEquals(deliveryAddress.getCity(), address.getCity());\n assertEquals(deliveryAddress.getState(), address.getState());\n assertEquals(deliveryAddress.getHouseNumber(), address.getHouseNo());\n\n }\n}\t"
},
{
"code": null,
"e": 21070,
"s": 21023,
"text": "Run the follwing command to test the mappings."
},
{
"code": null,
"e": 21086,
"s": 21070,
"text": "mvn clean test\n"
},
{
"code": null,
"e": 21133,
"s": 21086,
"text": "Once command is successful. Verify the output."
},
{
"code": null,
"e": 21781,
"s": 21133,
"text": "mvn clean test\n[INFO] Scanning for projects...\n...\n[INFO] --- maven-surefire-plugin:2.12.4:test (default-test) @ mapping ---\n[INFO] Surefire report directory: \\mvn\\mapping\\target\\surefire-reports\n\n-------------------------------------------------------\n T E S T S\n-------------------------------------------------------\nRunning com.tutorialspoint.mapping.DeliveryAddressMapperTest\nTests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.011 sec\nRunning com.tutorialspoint.mapping.StudentMapperTest\nTests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.001 sec\n\nResults :\n\nTests run: 3, Failures: 0, Errors: 0, Skipped: 0\n...\n"
},
{
"code": null,
"e": 21878,
"s": 21781,
"text": "MapStruct handles nested mapping seemlessly. For example, a Student with Subject as nested bean."
},
{
"code": null,
"e": 21938,
"s": 21878,
"text": "Now create a mapper interface which can map nested objects."
},
{
"code": null,
"e": 22305,
"s": 21938,
"text": "@Mapper\npublic interface StudentMapper {\n @Mapping(target=\"className\", source=\"classVal\")\n @Mapping(target=\"subject\", source=\"subject.name\")\n Student getModelFromEntity(StudentEntity studentEntity);\n\t\n @Mapping(target=\"classVal\", source=\"className\")\n @Mapping(target=\"subject.name\", source=\"subject\")\n StudentEntity getEntityFromModel(Student student);\n}"
},
{
"code": null,
"e": 22385,
"s": 22305,
"text": "Open project mapping as updated in Mapping Multiple Objects chapter in Eclipse."
},
{
"code": null,
"e": 22435,
"s": 22387,
"text": "Create SubjectEntity.java with following code −"
},
{
"code": null,
"e": 22454,
"s": 22435,
"text": "SubjectEntity.java"
},
{
"code": null,
"e": 22667,
"s": 22454,
"text": "package com.tutorialspoint.entity;\n\npublic class SubjectEntity {\n private String name;\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\t\n}"
},
{
"code": null,
"e": 22715,
"s": 22667,
"text": "Update StudentEntity.java with following code −"
},
{
"code": null,
"e": 22734,
"s": 22715,
"text": "StudentEntity.java"
},
{
"code": null,
"e": 23424,
"s": 22734,
"text": "package com.tutorialspoint.entity;\n\npublic class StudentEntity {\n private int id;\n private String name;\n private String classVal;\n private SubjectEntity subject;\n public int getId() {\n return id;\n }\n public void setId(int id) {\n this.id = id;\n }\n public String getName() {\n return name;\n }\n public void setName(String name) {\n this.name = name;\n }\n public String getClassVal() {\n return classVal;\n }\n public void setClassVal(String classVal) {\n this.classVal = classVal;\n }\n public SubjectEntity getSubject() {\n return subject;\n }\n public void setSubject(SubjectEntity subject) {\n this.subject = subject;\n }\n}"
},
{
"code": null,
"e": 23466,
"s": 23424,
"text": "Update Student.java with following code −"
},
{
"code": null,
"e": 23479,
"s": 23466,
"text": "Student.java"
},
{
"code": null,
"e": 24148,
"s": 23479,
"text": "package com.tutorialspoint.model;\n\npublic class Student {\n private int id;\n private String name;\n private String className;\n private String subject;\n public int getId() {\n return id;\n }\n public void setId(int id) {\n this.id = id;\n }\n public String getName() {\n return name;\n }\n public void setName(String name) {\n this.name = name;\n }\n public String getClassName() {\n return className;\n }\n public void setClassName(String className) {\n this.className = className;\n }\n public String getSubject() {\n return subject;\n }\n public void setSubject(String subject) {\n this.subject = subject;\n }\n}"
},
{
"code": null,
"e": 24196,
"s": 24148,
"text": "Update StudentMapper.java with following code −"
},
{
"code": null,
"e": 24215,
"s": 24196,
"text": "StudentMapper.java"
},
{
"code": null,
"e": 24768,
"s": 24215,
"text": "package com.tutorialspoint.mapper;\n\nimport org.mapstruct.Mapper;\nimport org.mapstruct.Mapping;\n\nimport com.tutorialspoint.entity.StudentEntity;\nimport com.tutorialspoint.model.Student;\n\n@Mapper\npublic interface StudentMapper {\n\n @Mapping(target=\"className\", source=\"classVal\")\n @Mapping(target=\"subject\", source=\"subject.name\")\n Student getModelFromEntity(StudentEntity studentEntity);\n\n @Mapping(target=\"classVal\", source=\"className\")\n @Mapping(target=\"subject.name\", source=\"subject\")\n StudentEntity getEntityFromModel(Student student);\n}"
},
{
"code": null,
"e": 24820,
"s": 24768,
"text": "Update StudentMapperTest.java with following code −"
},
{
"code": null,
"e": 24843,
"s": 24820,
"text": "StudentMapperTest.java"
},
{
"code": null,
"e": 26464,
"s": 24843,
"text": "package com.tutorialspoint.mapping;\n\nimport static org.junit.jupiter.api.Assertions.assertEquals;\n\nimport org.junit.jupiter.api.Test;\nimport org.mapstruct.factory.Mappers;\n\nimport com.tutorialspoint.entity.StudentEntity;\nimport com.tutorialspoint.entity.SubjectEntity;\nimport com.tutorialspoint.mapper.StudentMapper;\nimport com.tutorialspoint.model.Student;\n\npublic class StudentMapperTest {\n private StudentMapper studentMapper\n = Mappers.getMapper(StudentMapper.class);\n\n @Test\n public void testEntityToModel() {\n StudentEntity entity = new StudentEntity();\n entity.setClassVal(\"X\");\n entity.setName(\"John\");\n entity.setId(1);\n\n SubjectEntity subject = new SubjectEntity();\n subject.setName(\"Computer\");\n entity.setSubject(subject);\n\n Student model = studentMapper.getModelFromEntity(entity);\n\n assertEquals(entity.getClassVal(), model.getClassName());\n assertEquals(entity.getName(), model.getName());\n assertEquals(entity.getId(), model.getId());\n assertEquals(entity.getSubject().getName(), model.getSubject()); \n }\n\n @Test\n public void testModelToEntity() {\n Student model = new Student();\n model.setId(1);\n model.setName(\"John\");\n model.setClassName(\"X\");\n model.setSubject(\"Science\");\n StudentEntity entity = studentMapper.getEntityFromModel(model);\n\n assertEquals(entity.getClassVal(), model.getClassName());\n assertEquals(entity.getName(), model.getName());\n assertEquals(entity.getId(), model.getId());\n assertEquals(entity.getSubject().getName(), model.getSubject());\n }\n}"
},
{
"code": null,
"e": 26511,
"s": 26464,
"text": "Run the follwing command to test the mappings."
},
{
"code": null,
"e": 26527,
"s": 26511,
"text": "mvn clean test\n"
},
{
"code": null,
"e": 26574,
"s": 26527,
"text": "Once command is successful. Verify the output."
},
{
"code": null,
"e": 27222,
"s": 26574,
"text": "mvn clean test\n[INFO] Scanning for projects...\n...\n[INFO] --- maven-surefire-plugin:2.12.4:test (default-test) @ mapping ---\n[INFO] Surefire report directory: \\mvn\\mapping\\target\\surefire-reports\n\n-------------------------------------------------------\n T E S T S\n-------------------------------------------------------\nRunning com.tutorialspoint.mapping.DeliveryAddressMapperTest\nTests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.005 sec\nRunning com.tutorialspoint.mapping.StudentMapperTest\nTests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.002 sec\n\nResults :\n\nTests run: 3, Failures: 0, Errors: 0, Skipped: 0\n...\n"
},
{
"code": null,
"e": 27515,
"s": 27222,
"text": "MapStruct handles direct fields mapping easily. For example, a Student with section as private property and StudentEntity with section as public property. To have both getter/setter mapping, a property should be public. In case of public final, only getter method will be present for mapping."
},
{
"code": null,
"e": 27631,
"s": 27515,
"text": "Now create a mapper interface. We'll use @InheritInverseConfiguration annotation to copy reverse configuration now."
},
{
"code": null,
"e": 27926,
"s": 27631,
"text": "@Mapper\npublic interface StudentMapper {\n @Mapping(target=\"className\", source=\"classVal\")\n @Mapping(target=\"subject\", source=\"subject.name\")\n Student getModelFromEntity(StudentEntity studentEntity);\n\t\n @InheritInverseConfiguration\n StudentEntity getEntityFromModel(Student student);\n}"
},
{
"code": null,
"e": 28004,
"s": 27926,
"text": "Open project mapping as updated in Mapping Nested Objects chapter in Eclipse."
},
{
"code": null,
"e": 28052,
"s": 28004,
"text": "Update StudentEntity.java with following code −"
},
{
"code": null,
"e": 28071,
"s": 28052,
"text": "StudentEntity.java"
},
{
"code": null,
"e": 28787,
"s": 28071,
"text": "package com.tutorialspoint.entity;\n\npublic class StudentEntity {\n private int id;\n private String name;\n private String classVal;\n private SubjectEntity subject;\n public String section;\n public int getId() {\n return id;\n }\n public void setId(int id) {\n this.id = id;\n }\n public String getName() {\n return name;\n }\n public void setName(String name) {\n this.name = name;\n }\n public String getClassVal() {\n return classVal;\n }\n public void setClassVal(String classVal) {\n this.classVal = classVal;\n }\n public SubjectEntity getSubject() {\n return subject;\n }\n public void setSubject(SubjectEntity subject) {\n this.subject = subject;\n }\n}"
},
{
"code": null,
"e": 28829,
"s": 28787,
"text": "Update Student.java with following code −"
},
{
"code": null,
"e": 28842,
"s": 28829,
"text": "Student.java"
},
{
"code": null,
"e": 29676,
"s": 28842,
"text": "package com.tutorialspoint.model;\n\npublic class Student {\n private int id;\n private String name;\n private String className;\n private String subject;\n private String section;\n public int getId() {\n return id;\n }\n public void setId(int id) {\n this.id = id;\n }\n public String getName() {\n return name;\n }\n public void setName(String name) {\n this.name = name;\n }\n public String getClassName() {\n return className;\n }\n public void setClassName(String className) {\n this.className = className;\n }\n public String getSubject() {\n return subject;\n }\n public void setSubject(String subject) {\n this.subject = subject;\n }\n public String getSection() {\n return section;\n }\n public void setSection(String section) {\n this.section = section;\n }\n}"
},
{
"code": null,
"e": 29724,
"s": 29676,
"text": "Update StudentMapper.java with following code −"
},
{
"code": null,
"e": 29743,
"s": 29724,
"text": "StudentMapper.java"
},
{
"code": null,
"e": 30274,
"s": 29743,
"text": "package com.tutorialspoint.mapper;\n\nimport org.mapstruct.InheritInverseConfiguration;\nimport org.mapstruct.Mapper;\nimport org.mapstruct.Mapping;\n\nimport com.tutorialspoint.entity.StudentEntity;\nimport com.tutorialspoint.model.Student;\n\n@Mapper\npublic interface StudentMapper {\n\n @Mapping(target=\"className\", source=\"classVal\")\n @Mapping(target=\"subject\", source=\"subject.name\")\n Student getModelFromEntity(StudentEntity studentEntity);\n\n @InheritInverseConfiguration\n StudentEntity getEntityFromModel(Student student);\n}"
},
{
"code": null,
"e": 30326,
"s": 30274,
"text": "Update StudentMapperTest.java with following code −"
},
{
"code": null,
"e": 30349,
"s": 30326,
"text": "StudentMapperTest.java"
},
{
"code": null,
"e": 32133,
"s": 30349,
"text": "package com.tutorialspoint.mapping;\n\nimport static org.junit.jupiter.api.Assertions.assertEquals;\n\nimport org.junit.jupiter.api.Test;\nimport org.mapstruct.factory.Mappers;\n\nimport com.tutorialspoint.entity.StudentEntity;\nimport com.tutorialspoint.entity.SubjectEntity;\nimport com.tutorialspoint.mapper.StudentMapper;\nimport com.tutorialspoint.model.Student;\n\npublic class StudentMapperTest {\n private StudentMapper studentMapper\n = Mappers.getMapper(StudentMapper.class);\n\n @Test\n public void testEntityToModel() {\n StudentEntity entity = new StudentEntity();\n entity.setClassVal(\"X\");\n entity.setName(\"John\");\n entity.setId(1);\n entity.section = \"A\";\n SubjectEntity subject = new SubjectEntity();\n subject.setName(\"Computer\");\n entity.setSubject(subject);\n\n Student model = studentMapper.getModelFromEntity(entity);\n\n assertEquals(entity.getClassVal(), model.getClassName());\n assertEquals(entity.getName(), model.getName());\n assertEquals(entity.getId(), model.getId());\n assertEquals(entity.getSubject().getName(), model.getSubject());\n assertEquals(entity.section, model.getSection());\t \n }\n\n @Test\n public void testModelToEntity() {\n Student model = new Student();\n model.setId(1);\n model.setName(\"John\");\n model.setClassName(\"X\");\n model.setSubject(\"Science\");\n model.setSection(\"A\");\n StudentEntity entity = studentMapper.getEntityFromModel(model);\n\n assertEquals(entity.getClassVal(), model.getClassName());\n assertEquals(entity.getName(), model.getName());\n assertEquals(entity.getId(), model.getId());\n assertEquals(entity.getSubject().getName(), model.getSubject());\n assertEquals(entity.section, model.getSection());\n }\n}"
},
{
"code": null,
"e": 32180,
"s": 32133,
"text": "Run the follwing command to test the mappings."
},
{
"code": null,
"e": 32196,
"s": 32180,
"text": "mvn clean test\n"
},
{
"code": null,
"e": 32243,
"s": 32196,
"text": "Once command is successful. Verify the output."
},
{
"code": null,
"e": 32891,
"s": 32243,
"text": "mvn clean test\n[INFO] Scanning for projects...\n...\n[INFO] --- maven-surefire-plugin:2.12.4:test (default-test) @ mapping ---\n[INFO] Surefire report directory: \\mvn\\mapping\\target\\surefire-reports\n\n-------------------------------------------------------\n T E S T S\n-------------------------------------------------------\nRunning com.tutorialspoint.mapping.DeliveryAddressMapperTest\nTests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.005 sec\nRunning com.tutorialspoint.mapping.StudentMapperTest\nTests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.002 sec\n\nResults :\n\nTests run: 3, Failures: 0, Errors: 0, Skipped: 0\n...\n"
},
{
"code": null,
"e": 33035,
"s": 32891,
"text": "MapStruct allows to use Builders. We can use Builder frameworks or can use our custom builder. In below example, we are using a custom builder."
},
{
"code": null,
"e": 33112,
"s": 33035,
"text": "Open project mapping as updated in Mapping Direct Fields chapter in Eclipse."
},
{
"code": null,
"e": 33154,
"s": 33112,
"text": "Update Student.java with following code −"
},
{
"code": null,
"e": 33167,
"s": 33154,
"text": "Student.java"
},
{
"code": null,
"e": 33930,
"s": 33167,
"text": "package com.tutorialspoint.model;\n\npublic class Student {\n private final String name;\n private final int id;\n\n protected Student(Student.Builder builder) {\n this.name = builder.name;\n this.id = builder.id;\n }\n public static Student.Builder builder() {\n return new Student.Builder();\n }\n public static class Builder {\n private String name;\n private int id;\n public Builder name(String name) {\n this.name = name;\n return this;\n }\n public Builder id(int id) {\n this.id = id;\n return this;\n }\n public Student create() {\n return new Student( this );\n }\n }\n public String getName() {\n return name;\n }\n public int getId() {\n return id;\n }\n}"
},
{
"code": null,
"e": 33978,
"s": 33930,
"text": "Update StudentMapper.java with following code −"
},
{
"code": null,
"e": 33997,
"s": 33978,
"text": "StudentMapper.java"
},
{
"code": null,
"e": 34419,
"s": 33997,
"text": "package com.tutorialspoint.mapper;\n\nimport org.mapstruct.Mapper;\nimport org.mapstruct.Mapping;\nimport com.tutorialspoint.entity.StudentEntity;\nimport com.tutorialspoint.model.Student;\n\n@Mapper\npublic interface StudentMapper {\n Student getModelFromEntity(StudentEntity studentEntity);\n @Mapping(target=\"id\", source=\"id\")\n @Mapping(target=\"name\", source=\"name\")\n StudentEntity getEntityFromModel(Student student);\n}"
},
{
"code": null,
"e": 34471,
"s": 34419,
"text": "Update StudentMapperTest.java with following code −"
},
{
"code": null,
"e": 34494,
"s": 34471,
"text": "StudentMapperTest.java"
},
{
"code": null,
"e": 35632,
"s": 34494,
"text": "package com.tutorialspoint.mapping;\n\nimport static org.junit.jupiter.api.Assertions.assertEquals;\nimport org.junit.jupiter.api.Test;\nimport org.mapstruct.factory.Mappers;\nimport com.tutorialspoint.entity.StudentEntity;\nimport com.tutorialspoint.entity.SubjectEntity;\nimport com.tutorialspoint.mapper.StudentMapper;\nimport com.tutorialspoint.model.Student;\n\npublic class StudentMapperTest {\n private StudentMapper studentMapper = Mappers.getMapper(StudentMapper.class);\n \n @Test\n public void testEntityToModel() {\n StudentEntity entity = new StudentEntity();\n entity.setName(\"John\");\n entity.setId(1);\n Student model = studentMapper.getModelFromEntity(entity);\n assertEquals(entity.getName(), model.getName());\n assertEquals(entity.getId(), model.getId());\n }\n @Test\n public void testModelToEntity() {\n Student.Builder builder = Student.builder().id(1).name(\"John\");\n Student model = builder.create();\n StudentEntity entity = studentMapper.getEntityFromModel(model);\n assertEquals(entity.getName(), model.getName());\n assertEquals(entity.getId(), model.getId());\n }\n}"
},
{
"code": null,
"e": 35680,
"s": 35632,
"text": "Run the following command to test the mappings."
},
{
"code": null,
"e": 35696,
"s": 35680,
"text": "mvn clean test\n"
},
{
"code": null,
"e": 35743,
"s": 35696,
"text": "Once command is successful. Verify the output."
},
{
"code": null,
"e": 36391,
"s": 35743,
"text": "mvn clean test\n[INFO] Scanning for projects...\n...\n[INFO] --- maven-surefire-plugin:2.12.4:test (default-test) @ mapping ---\n[INFO] Surefire report directory: \\mvn\\mapping\\target\\surefire-reports\n\n-------------------------------------------------------\n T E S T S\n-------------------------------------------------------\nRunning com.tutorialspoint.mapping.DeliveryAddressMapperTest\nTests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.005 sec\nRunning com.tutorialspoint.mapping.StudentMapperTest\nTests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.002 sec\n\nResults :\n\nTests run: 3, Failures: 0, Errors: 0, Skipped: 0\n...\n"
},
{
"code": null,
"e": 36626,
"s": 36391,
"text": "MapStruct handles conversion of type conversions automatically in most of the cases. For example, int to Long or String conversion. Conversion handles null values as well. Following are the some of the important automatic conversions."
},
{
"code": null,
"e": 36685,
"s": 36626,
"text": "Between primitive types and Corresponding Wrapper Classes."
},
{
"code": null,
"e": 36744,
"s": 36685,
"text": "Between primitive types and Corresponding Wrapper Classes."
},
{
"code": null,
"e": 36780,
"s": 36744,
"text": "Between primitive types and String."
},
{
"code": null,
"e": 36816,
"s": 36780,
"text": "Between primitive types and String."
},
{
"code": null,
"e": 36847,
"s": 36816,
"text": "Between enum types and String."
},
{
"code": null,
"e": 36878,
"s": 36847,
"text": "Between enum types and String."
},
{
"code": null,
"e": 36917,
"s": 36878,
"text": "Between BigInt, BigDecimal and String."
},
{
"code": null,
"e": 36956,
"s": 36917,
"text": "Between BigInt, BigDecimal and String."
},
{
"code": null,
"e": 37004,
"s": 36956,
"text": "Between Calendar/Date and XMLGregorianCalendar."
},
{
"code": null,
"e": 37052,
"s": 37004,
"text": "Between Calendar/Date and XMLGregorianCalendar."
},
{
"code": null,
"e": 37093,
"s": 37052,
"text": "Between XMLGregorianCalendar and String."
},
{
"code": null,
"e": 37134,
"s": 37093,
"text": "Between XMLGregorianCalendar and String."
},
{
"code": null,
"e": 37171,
"s": 37134,
"text": "Between Jodas date types and String."
},
{
"code": null,
"e": 37208,
"s": 37171,
"text": "Between Jodas date types and String."
},
{
"code": null,
"e": 37285,
"s": 37208,
"text": "Open project mapping as updated in Mapping Using Builder chapter in Eclipse."
},
{
"code": null,
"e": 37333,
"s": 37285,
"text": "Update StudentEntity.java with following code −"
},
{
"code": null,
"e": 37352,
"s": 37333,
"text": "StudentEntity.java"
},
{
"code": null,
"e": 38077,
"s": 37352,
"text": "package com.tutorialspoint.entity;\n\npublic class StudentEntity {\n private String id;\n private String name;\n private String classVal;\n private SubjectEntity subject;\n public String section;\n public String getId() {\n return id;\n }\n public void setId(String id) {\n this.id = id;\n }\n public String getName() {\n return name;\n }\n public void setName(String name) {\n this.name = name;\n }\n public String getClassVal() {\n return classVal;\n }\n public void setClassVal(String classVal) {\n this.classVal = classVal;\n }\n public SubjectEntity getSubject() {\n return subject;\n }\n public void setSubject(SubjectEntity subject) {\n this.subject = subject;\n }\n}"
},
{
"code": null,
"e": 38125,
"s": 38077,
"text": "Student.java is unchanged with following code −"
},
{
"code": null,
"e": 38138,
"s": 38125,
"text": "Student.java"
},
{
"code": null,
"e": 38909,
"s": 38138,
"text": "package com.tutorialspoint.model;\n\npublic class Student {\n private final String name;\n private final int id;\n\n protected Student(Student.Builder builder) {\n this.name = builder.name;\n this.id = builder.id;\n }\n\n public static Student.Builder builder() {\n return new Student.Builder();\n }\n\n public static class Builder {\n private String name;\n private int id;\n\n public Builder name(String name) {\n this.name = name;\n return this;\n }\n\n public Builder id(int id) {\n this.id = id;\n return this;\n }\n\n public Student create() {\n return new Student( this );\n }\n }\n\n public String getName() {\n return name;\n }\n\n public int getId() {\n ret+urn id;\n }\n}"
},
{
"code": null,
"e": 38969,
"s": 38909,
"text": "Update DeliveryAddressMapperTest.java with following code −"
},
{
"code": null,
"e": 39000,
"s": 38969,
"text": "DeliveryAddressMapperTest.java"
},
{
"code": null,
"e": 40239,
"s": 39000,
"text": "package com.tutorialspoint.mapping;\n\nimport static org.junit.jupiter.api.Assertions.assertEquals;\n\nimport org.junit.jupiter.api.Test;\nimport org.mapstruct.factory.Mappers;\n\nimport com.tutorialspoint.entity.AddressEntity;\nimport com.tutorialspoint.entity.StudentEntity;\nimport com.tutorialspoint.mapper.DeliveryAddressMapper;\nimport com.tutorialspoint.model.DeliveryAddress;\n\npublic class DeliveryAddressMapperTest {\n\n private DeliveryAddressMapper deliveryAddressMapper\n = Mappers.getMapper(DeliveryAddressMapper.class);\n\n @Test\n public void testEntityToModel() {\n StudentEntity student = new StudentEntity();\n student.setClassVal(\"X\");\n student.setName(\"John\");\n student.setId(\"1\");\n\n AddressEntity address = new AddressEntity();\n address.setCity(\"Y\");\n address.setState(\"Z\");\n address.setHouseNo(1);\n\n DeliveryAddress deliveryAddress = deliveryAddressMapper.getDeliveryAddress(student, address);\n\n assertEquals(deliveryAddress.getName(), student.getName());\n assertEquals(deliveryAddress.getCity(), address.getCity());\n assertEquals(deliveryAddress.getState(), address.getState());\n assertEquals(deliveryAddress.getHouseNumber(), address.getHouseNo());\n\n }\n}"
},
{
"code": null,
"e": 40291,
"s": 40239,
"text": "Update StudentMapperTest.java with following code −"
},
{
"code": null,
"e": 40314,
"s": 40291,
"text": "StudentMapperTest.java"
},
{
"code": null,
"e": 41499,
"s": 40314,
"text": "package com.tutorialspoint.mapping;\n\nimport static org.junit.jupiter.api.Assertions.assertEquals;\n\nimport org.junit.jupiter.api.Test;\nimport org.mapstruct.factory.Mappers;\n\nimport com.tutorialspoint.entity.StudentEntity;\nimport com.tutorialspoint.entity.SubjectEntity;\nimport com.tutorialspoint.mapper.StudentMapper;\nimport com.tutorialspoint.model.Student;\n\npublic class StudentMapperTest {\n\n private StudentMapper studentMapper\n = Mappers.getMapper(StudentMapper.class);\n\n @Test\n public void testEntityToModel() {\n StudentEntity entity = new StudentEntity();\n entity.setName(\"John\");\n entity.setId(\"1\");\n\n Student model = studentMapper.getModelFromEntity(entity);\n assertEquals(entity.getName(), model.getName());\n assertEquals(Integer.parseInt(entity.getId()), model.getId());\n }\n\n @Test\n public void testModelToEntity() {\n Student.Builder builder = Student.builder().id(1).name(\"John\");\n Student model = builder.create();\n StudentEntity entity = studentMapper.getEntityFromModel(model);\n\n assertEquals(entity.getName(), model.getName());\n assertEquals(Integer.parseInt(entity.getId()), model.getId());\n }\n}"
},
{
"code": null,
"e": 41546,
"s": 41499,
"text": "Run the follwing command to test the mappings."
},
{
"code": null,
"e": 41562,
"s": 41546,
"text": "mvn clean test\n"
},
{
"code": null,
"e": 41609,
"s": 41562,
"text": "Once command is successful. Verify the output."
},
{
"code": null,
"e": 42257,
"s": 41609,
"text": "mvn clean test\n[INFO] Scanning for projects...\n...\n[INFO] --- maven-surefire-plugin:2.12.4:test (default-test) @ mapping ---\n[INFO] Surefire report directory: \\mvn\\mapping\\target\\surefire-reports\n\n-------------------------------------------------------\n T E S T S\n-------------------------------------------------------\nRunning com.tutorialspoint.mapping.DeliveryAddressMapperTest\nTests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.005 sec\nRunning com.tutorialspoint.mapping.StudentMapperTest\nTests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.002 sec\n\nResults :\n\nTests run: 3, Failures: 0, Errors: 0, Skipped: 0\n...\n"
},
{
"code": null,
"e": 42512,
"s": 42257,
"text": "MapStruct handles conversion of numbers to String in required format seamlessly. We can pass the required format as numberFormat during @Mapping annotation. For example, consider a case where an amount stored in numbers is to be shown in currency format."
},
{
"code": null,
"e": 42546,
"s": 42512,
"text": "Source - Entity has price as 350."
},
{
"code": null,
"e": 42580,
"s": 42546,
"text": "Source - Entity has price as 350."
},
{
"code": null,
"e": 42621,
"s": 42580,
"text": "Target - Model to show price as $350.00."
},
{
"code": null,
"e": 42662,
"s": 42621,
"text": "Target - Model to show price as $350.00."
},
{
"code": null,
"e": 42694,
"s": 42662,
"text": "numberFormat - Use format $#.00"
},
{
"code": null,
"e": 42726,
"s": 42694,
"text": "numberFormat - Use format $#.00"
},
{
"code": null,
"e": 42815,
"s": 42726,
"text": "Open project mapping as updated in Mapping Implicit Type Conversions chapter in Eclipse."
},
{
"code": null,
"e": 42859,
"s": 42815,
"text": "Create CarEntity.java with following code −"
},
{
"code": null,
"e": 42874,
"s": 42859,
"text": "CarEntity.java"
},
{
"code": null,
"e": 43209,
"s": 42874,
"text": "package com.tutorialspoint.entity;\n\npublic class CarEntity {\n private int id;\n private double price;\n public int getId() {\n return id;\n }\n public void setId(int id) {\n this.id = id;\n }\n public double getPrice() {\n return price;\n }\n public void setPrice(double price) {\n this.price = price;\n }\n}"
},
{
"code": null,
"e": 43247,
"s": 43209,
"text": "Create Car.java with following code −"
},
{
"code": null,
"e": 43256,
"s": 43247,
"text": "Car.java"
},
{
"code": null,
"e": 43584,
"s": 43256,
"text": "package com.tutorialspoint.model;\n\npublic class Car {\n private int id;\n private String price;\n public int getId() {\n return id;\n }\n public void setId(int id) {\n this.id = id;\n }\n public String getPrice() {\n return price;\n }\n public void setPrice(String price) {\n this.price = price;\n }\n}"
},
{
"code": null,
"e": 43628,
"s": 43584,
"text": "Create CarMapper.java with following code −"
},
{
"code": null,
"e": 43643,
"s": 43628,
"text": "CarMapper.java"
},
{
"code": null,
"e": 43980,
"s": 43643,
"text": "package com.tutorialspoint.mapper;\n\nimport org.mapstruct.Mapper;\nimport org.mapstruct.Mapping;\n\nimport com.tutorialspoint.entity.CarEntity;\nimport com.tutorialspoint.model.Car;\n\n@Mapper\npublic interface CarMapper {\n @Mapping(source = \"price\", target = \"price\", numberFormat = \"$#.00\")\n Car getModelFromEntity(CarEntity carEntity);\n}"
},
{
"code": null,
"e": 44028,
"s": 43980,
"text": "Create CarMapperTest.java with following code −"
},
{
"code": null,
"e": 44047,
"s": 44028,
"text": "CarMapperTest.java"
},
{
"code": null,
"e": 44760,
"s": 44047,
"text": "package com.tutorialspoint.mapping;\n\nimport static org.junit.jupiter.api.Assertions.assertEquals;\n\nimport org.junit.jupiter.api.Test;\nimport org.mapstruct.factory.Mappers;\n\nimport com.tutorialspoint.entity.CarEntity;\nimport com.tutorialspoint.mapper.CarMapper;\nimport com.tutorialspoint.model.Car;\n\npublic class CarMapperTest {\n private CarMapper carMapper\n = Mappers.getMapper(CarMapper.class);\n\n @Test\n public void testEntityToModel() {\n CarEntity entity = new CarEntity();\n entity.setPrice(345000);\n entity.setId(1);\n\n Car model = carMapper.getModelFromEntity(entity);\n assertEquals(model.getPrice(), \"$345000.00\");\n assertEquals(entity.getId(), model.getId());\n }\n}"
},
{
"code": null,
"e": 44807,
"s": 44760,
"text": "Run the follwing command to test the mappings."
},
{
"code": null,
"e": 44823,
"s": 44807,
"text": "mvn clean test\n"
},
{
"code": null,
"e": 44870,
"s": 44823,
"text": "Once command is successful. Verify the output."
},
{
"code": null,
"e": 45637,
"s": 44870,
"text": "mvn clean test\n[INFO] Scanning for projects...\n...\n[INFO] --- maven-surefire-plugin:2.12.4:test (default-test) @ mapping ---\n[INFO] Surefire report directory: \\mvn\\mapping\\target\\surefire-reports\n\n-------------------------------------------------------\n T E S T S\n-------------------------------------------------------\nRunning com.tutorialspoint.mapping.CarMapperTest\nTests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.035 sec\nRunning com.tutorialspoint.mapping.DeliveryAddressMapperTest\nTests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0 sec\nRunning com.tutorialspoint.mapping.StudentMapperTest\nTests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.001 sec\n\nResults :\n\nTests run: 4, Failures: 0, Errors: 0, Skipped: 0\n...\n"
},
{
"code": null,
"e": 45886,
"s": 45637,
"text": "MapStruct handles conversion of date to String in required format seamlessly. We can pass the required format as dateFormat during @Mapping annotation. For example, consider a case where a date stored in numbers is to be shown in particular format."
},
{
"code": null,
"e": 45945,
"s": 45886,
"text": "Source - Entity has date as GregorianCalendar(2015, 3, 5)."
},
{
"code": null,
"e": 46004,
"s": 45945,
"text": "Source - Entity has date as GregorianCalendar(2015, 3, 5)."
},
{
"code": null,
"e": 46047,
"s": 46004,
"text": "Target - Model to show date as 05.04.2015."
},
{
"code": null,
"e": 46090,
"s": 46047,
"text": "Target - Model to show date as 05.04.2015."
},
{
"code": null,
"e": 46125,
"s": 46090,
"text": "dateFormat - Use format dd.MM.yyyy"
},
{
"code": null,
"e": 46160,
"s": 46125,
"text": "dateFormat - Use format dd.MM.yyyy"
},
{
"code": null,
"e": 46242,
"s": 46160,
"text": "Open project mapping as updated in Mapping Using numberFormat chapter in Eclipse."
},
{
"code": null,
"e": 46286,
"s": 46242,
"text": "Update CarEntity.java with following code −"
},
{
"code": null,
"e": 46301,
"s": 46286,
"text": "CarEntity.java"
},
{
"code": null,
"e": 46940,
"s": 46301,
"text": "package com.tutorialspoint.entity;\nimport java.util.GregorianCalendar;\n\npublic class CarEntity {\n private int id;\n private double price;\n private GregorianCalendar manufacturingDate;\n public int getId() {\n return id;\n }\n public void setId(int id) {\n this.id = id;\n }\n public double getPrice() {\n return price;\n }\n public void setPrice(double price) {\n this.price = price;\n }\n public GregorianCalendar getManufacturingDate() {\n return manufacturingDate;\n }\n public void setManufacturingDate(GregorianCalendar manufacturingDate) {\n this.manufacturingDate = manufacturingDate;\n }\n}"
},
{
"code": null,
"e": 46978,
"s": 46940,
"text": "Update Car.java with following code −"
},
{
"code": null,
"e": 46987,
"s": 46978,
"text": "Car.java"
},
{
"code": null,
"e": 47550,
"s": 46987,
"text": "package com.tutorialspoint.model;\n\npublic class Car {\n private int id;\n private String price;\n private String manufacturingDate;\n public int getId() {\n return id;\n }\n public void setId(int id) {\n this.id = id;\n }\n public String getPrice() {\n return price;\n }\n public void setPrice(String price) {\n this.price = price;\n }\n public String getManufacturingDate() {\n return manufacturingDate;\n }\n public void setManufacturingDate(String manufacturingDate) {\n this.manufacturingDate = manufacturingDate;\n }\n}"
},
{
"code": null,
"e": 47594,
"s": 47550,
"text": "Update CarMapper.java with following code −"
},
{
"code": null,
"e": 47609,
"s": 47594,
"text": "CarMapper.java"
},
{
"code": null,
"e": 48045,
"s": 47609,
"text": "package com.tutorialspoint.mapper;\n\nimport org.mapstruct.Mapper;\nimport org.mapstruct.Mapping;\n\nimport com.tutorialspoint.entity.CarEntity;\nimport com.tutorialspoint.model.Car;\n\n@Mapper\npublic interface CarMapper {\n @Mapping(source = \"price\", target = \"price\", numberFormat = \"$#.00\")\n @Mapping(source = \"manufacturingDate\", target = \"manufacturingDate\", dateFormat = \"dd.MM.yyyy\")\n Car getModelFromEntity(CarEntity carEntity);\n}"
},
{
"code": null,
"e": 48093,
"s": 48045,
"text": "Update CarMapperTest.java with following code −"
},
{
"code": null,
"e": 48112,
"s": 48093,
"text": "CarMapperTest.java"
},
{
"code": null,
"e": 48993,
"s": 48112,
"text": "package com.tutorialspoint.mapping;\n\nimport static org.junit.jupiter.api.Assertions.assertEquals;\nimport java.util.GregorianCalendar;\nimport org.junit.jupiter.api.Test;\nimport org.mapstruct.factory.Mappers;\n\nimport com.tutorialspoint.entity.CarEntity;\nimport com.tutorialspoint.mapper.CarMapper;\nimport com.tutorialspoint.model.Car;\n\npublic class CarMapperTest {\n private CarMapper carMapper\n = Mappers.getMapper(CarMapper.class);\n\n @Test\n public void testEntityToModel() {\n CarEntity entity = new CarEntity();\n entity.setPrice(345000);\n entity.setId(1);\n entity.setManufacturingDate(new GregorianCalendar(2015, 3, 5));\n Car model = carMapper.getModelFromEntity(entity);\n assertEquals(model.getPrice(), \"$345000.00\");\n assertEquals(entity.getId(), model.getId());\n assertEquals(\"05.04.2015\", model.getManufacturingDate());\n }\n}"
},
{
"code": null,
"e": 49040,
"s": 48993,
"text": "Run the follwing command to test the mappings."
},
{
"code": null,
"e": 49056,
"s": 49040,
"text": "mvn clean test\n"
},
{
"code": null,
"e": 49103,
"s": 49056,
"text": "Once command is successful. Verify the output."
},
{
"code": null,
"e": 49870,
"s": 49103,
"text": "mvn clean test\n[INFO] Scanning for projects...\n...\n[INFO] --- maven-surefire-plugin:2.12.4:test (default-test) @ mapping ---\n[INFO] Surefire report directory: \\mvn\\mapping\\target\\surefire-reports\n\n-------------------------------------------------------\n T E S T S\n-------------------------------------------------------\nRunning com.tutorialspoint.mapping.CarMapperTest\nTests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.035 sec\nRunning com.tutorialspoint.mapping.DeliveryAddressMapperTest\nTests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0 sec\nRunning com.tutorialspoint.mapping.StudentMapperTest\nTests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.001 sec\n\nResults :\n\nTests run: 4, Failures: 0, Errors: 0, Skipped: 0\n...\n"
},
{
"code": null,
"e": 50055,
"s": 49870,
"text": "MapStruct allows to call a conversion method for customized logic. We can use expression to achieve the same where we can pass any java object and call its method to do the conversion."
},
{
"code": null,
"e": 50132,
"s": 50055,
"text": "@Mapping(target = \"target-property\", \n\texpression = \"java(target-method())\")"
},
{
"code": null,
"e": 50137,
"s": 50132,
"text": "Here"
},
{
"code": null,
"e": 50204,
"s": 50137,
"text": "target-property - the property for which we are doing the mapping."
},
{
"code": null,
"e": 50271,
"s": 50204,
"text": "target-property - the property for which we are doing the mapping."
},
{
"code": null,
"e": 50344,
"s": 50271,
"text": "expression - mapper will call the java method written in the expression."
},
{
"code": null,
"e": 50417,
"s": 50344,
"text": "expression - mapper will call the java method written in the expression."
},
{
"code": null,
"e": 50556,
"s": 50417,
"text": "target-method - target-method is the method to be called. In case method is present in different class, use new class-name.target-method()"
},
{
"code": null,
"e": 50695,
"s": 50556,
"text": "target-method - target-method is the method to be called. In case method is present in different class, use new class-name.target-method()"
},
{
"code": null,
"e": 50775,
"s": 50695,
"text": "Open project mapping as updated in Mapping Using dateFormat chapter in Eclipse."
},
{
"code": null,
"e": 50819,
"s": 50775,
"text": "Update CarEntity.java with following code −"
},
{
"code": null,
"e": 50834,
"s": 50819,
"text": "CarEntity.java"
},
{
"code": null,
"e": 51473,
"s": 50834,
"text": "package com.tutorialspoint.entity;\nimport java.util.GregorianCalendar;\n\npublic class CarEntity {\n private int id;\n private double price;\n private GregorianCalendar manufacturingDate;\n public int getId() {\n return id;\n }\n public void setId(int id) {\n this.id = id;\n }\n public double getPrice() {\n return price;\n }\n public void setPrice(double price) {\n this.price = price;\n }\n public GregorianCalendar getManufacturingDate() {\n return manufacturingDate;\n }\n public void setManufacturingDate(GregorianCalendar manufacturingDate) {\n this.manufacturingDate = manufacturingDate;\n }\n}"
},
{
"code": null,
"e": 51511,
"s": 51473,
"text": "Update Car.java with following code −"
},
{
"code": null,
"e": 51520,
"s": 51511,
"text": "Car.java"
},
{
"code": null,
"e": 52083,
"s": 51520,
"text": "package com.tutorialspoint.model;\n\npublic class Car {\n private int id;\n private String price;\n private String manufacturingDate;\n public int getId() {\n return id;\n }\n public void setId(int id) {\n this.id = id;\n }\n public String getPrice() {\n return price;\n }\n public void setPrice(String price) {\n this.price = price;\n }\n public String getManufacturingDate() {\n return manufacturingDate;\n }\n public void setManufacturingDate(String manufacturingDate) {\n this.manufacturingDate = manufacturingDate;\n }\n}"
},
{
"code": null,
"e": 52127,
"s": 52083,
"text": "Update CarMapper.java with following code −"
},
{
"code": null,
"e": 52142,
"s": 52127,
"text": "CarMapper.java"
},
{
"code": null,
"e": 52925,
"s": 52142,
"text": "package com.tutorialspoint.mapper;\n\nimport java.text.SimpleDateFormat;\nimport java.util.Date;\nimport java.util.GregorianCalendar;\n\nimport org.mapstruct.Mapper;\nimport org.mapstruct.Mapping;\n\nimport com.tutorialspoint.entity.CarEntity;\nimport com.tutorialspoint.model.Car;\n\n@Mapper\npublic interface CarMapper {\n @Mapping(source = \"price\", target = \"price\", numberFormat = \"$#.00\")\n @Mapping(target = \"manufacturingDate\", \n expression = \"java(getManufacturingDate(carEntity.getManufacturingDate()))\")\n Car getModelFromEntity(CarEntity carEntity);\n\n default String getManufacturingDate(GregorianCalendar manufacturingDate) {\n Date d = manufacturingDate.getTime();\n SimpleDateFormat sdf = new SimpleDateFormat( \"dd.MM.yyyy\" );\n return sdf.format( d );\n }\n}"
},
{
"code": null,
"e": 52973,
"s": 52925,
"text": "Update CarMapperTest.java with following code −"
},
{
"code": null,
"e": 52992,
"s": 52973,
"text": "CarMapperTest.java"
},
{
"code": null,
"e": 53873,
"s": 52992,
"text": "package com.tutorialspoint.mapping;\n\nimport static org.junit.jupiter.api.Assertions.assertEquals;\nimport java.util.GregorianCalendar;\nimport org.junit.jupiter.api.Test;\nimport org.mapstruct.factory.Mappers;\n\nimport com.tutorialspoint.entity.CarEntity;\nimport com.tutorialspoint.mapper.CarMapper;\nimport com.tutorialspoint.model.Car;\n\npublic class CarMapperTest {\n private CarMapper carMapper\n = Mappers.getMapper(CarMapper.class);\n\n @Test\n public void testEntityToModel() {\n CarEntity entity = new CarEntity();\n entity.setPrice(345000);\n entity.setId(1);\n entity.setManufacturingDate(new GregorianCalendar(2015, 3, 5));\n Car model = carMapper.getModelFromEntity(entity);\n assertEquals(model.getPrice(), \"$345000.00\");\n assertEquals(entity.getId(), model.getId());\n assertEquals(\"05.04.2015\", model.getManufacturingDate());\n }\n}"
},
{
"code": null,
"e": 53920,
"s": 53873,
"text": "Run the follwing command to test the mappings."
},
{
"code": null,
"e": 53936,
"s": 53920,
"text": "mvn clean test\n"
},
{
"code": null,
"e": 53983,
"s": 53936,
"text": "Once command is successful. Verify the output."
},
{
"code": null,
"e": 54750,
"s": 53983,
"text": "mvn clean test\n[INFO] Scanning for projects...\n...\n[INFO] --- maven-surefire-plugin:2.12.4:test (default-test) @ mapping ---\n[INFO] Surefire report directory: \\mvn\\mapping\\target\\surefire-reports\n\n-------------------------------------------------------\n T E S T S\n-------------------------------------------------------\nRunning com.tutorialspoint.mapping.CarMapperTest\nTests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.035 sec\nRunning com.tutorialspoint.mapping.DeliveryAddressMapperTest\nTests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0 sec\nRunning com.tutorialspoint.mapping.StudentMapperTest\nTests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.001 sec\n\nResults :\n\nTests run: 4, Failures: 0, Errors: 0, Skipped: 0\n...\n"
},
{
"code": null,
"e": 54807,
"s": 54750,
"text": "MapStruct allows to map a constant value to a property. "
},
{
"code": null,
"e": 54867,
"s": 54807,
"text": "@Mapping(target = \"target-property\", const = \"const-value\")"
},
{
"code": null,
"e": 54872,
"s": 54867,
"text": "Here"
},
{
"code": null,
"e": 54939,
"s": 54872,
"text": "target-property - the property for which we are doing the mapping."
},
{
"code": null,
"e": 55006,
"s": 54939,
"text": "target-property - the property for which we are doing the mapping."
},
{
"code": null,
"e": 55072,
"s": 55006,
"text": "const-value - mapper will map the const-value to target-property."
},
{
"code": null,
"e": 55138,
"s": 55072,
"text": "const-value - mapper will map the const-value to target-property."
},
{
"code": null,
"e": 55179,
"s": 55138,
"text": "Following example demonstrates the same."
},
{
"code": null,
"e": 55259,
"s": 55179,
"text": "Open project mapping as updated in Mapping Using dateFormat chapter in Eclipse."
},
{
"code": null,
"e": 55303,
"s": 55259,
"text": "Update CarEntity.java with following code −"
},
{
"code": null,
"e": 55318,
"s": 55303,
"text": "CarEntity.java"
},
{
"code": null,
"e": 55957,
"s": 55318,
"text": "package com.tutorialspoint.entity;\nimport java.util.GregorianCalendar;\n\npublic class CarEntity {\n private int id;\n private double price;\n private GregorianCalendar manufacturingDate;\n public int getId() {\n return id;\n }\n public void setId(int id) {\n this.id = id;\n }\n public double getPrice() {\n return price;\n }\n public void setPrice(double price) {\n this.price = price;\n }\n public GregorianCalendar getManufacturingDate() {\n return manufacturingDate;\n }\n public void setManufacturingDate(GregorianCalendar manufacturingDate) {\n this.manufacturingDate = manufacturingDate;\n }\n}"
},
{
"code": null,
"e": 55995,
"s": 55957,
"text": "Update Car.java with following code −"
},
{
"code": null,
"e": 56004,
"s": 55995,
"text": "Car.java"
},
{
"code": null,
"e": 56718,
"s": 56004,
"text": "package com.tutorialspoint.model;\n\npublic class Car {\n private int id;\n private String price;\n private String manufacturingDate;\n private String brand;\n public int getId() {\n return id;\n }\n public void setId(int id) {\n this.id = id;\n }\n public String getPrice() {\n return price;\n }\n public void setPrice(String price) {\n this.price = price;\n }\n public String getManufacturingDate() {\n return manufacturingDate;\n }\n public void setManufacturingDate(String manufacturingDate) {\n this.manufacturingDate = manufacturingDate;\n }\n public String getBrand() {\n return brand;\n }\n public void setBrand(String brand) {\n this.brand = brand;\n }\n}"
},
{
"code": null,
"e": 56762,
"s": 56718,
"text": "Update CarMapper.java with following code −"
},
{
"code": null,
"e": 56777,
"s": 56762,
"text": "CarMapper.java"
},
{
"code": null,
"e": 57261,
"s": 56777,
"text": "package com.tutorialspoint.mapper;\n\nimport org.mapstruct.Mapper;\nimport org.mapstruct.Mapping;\n\nimport com.tutorialspoint.entity.CarEntity;\nimport com.tutorialspoint.model.Car;\n\n@Mapper\npublic interface CarMapper {\n @Mapping(target = \"brand\", constant = \"BMW\")\n @Mapping(source = \"price\", target = \"price\", numberFormat = \"$#.00\")\n @Mapping(source = \"manufacturingDate\", target = \"manufacturingDate\", dateFormat = \"dd.MM.yyyy\")\n Car getModelFromEntity(CarEntity carEntity);\n}"
},
{
"code": null,
"e": 57309,
"s": 57261,
"text": "Update CarMapperTest.java with following code −"
},
{
"code": null,
"e": 57328,
"s": 57309,
"text": "CarMapperTest.java"
},
{
"code": null,
"e": 58254,
"s": 57328,
"text": "package com.tutorialspoint.mapping;\n\nimport static org.junit.jupiter.api.Assertions.assertEquals;\nimport java.util.GregorianCalendar;\nimport org.junit.jupiter.api.Test;\nimport org.mapstruct.factory.Mappers;\n\nimport com.tutorialspoint.entity.CarEntity;\nimport com.tutorialspoint.mapper.CarMapper;\nimport com.tutorialspoint.model.Car;\n\npublic class CarMapperTest {\n private CarMapper carMapper\n = Mappers.getMapper(CarMapper.class);\n\n @Test\n public void testEntityToModel() {\n CarEntity entity = new CarEntity();\n entity.setPrice(345000);\n entity.setId(1);\n entity.setManufacturingDate(new GregorianCalendar(2015, 3, 5));\n Car model = carMapper.getModelFromEntity(entity);\n assertEquals(model.getPrice(), \"$345000.00\");\n assertEquals(entity.getId(), model.getId());\n assertEquals(\"05.04.2015\", model.getManufacturingDate());\n assertEquals(\"BMW\", model.getBrand());\n }\n}"
},
{
"code": null,
"e": 58301,
"s": 58254,
"text": "Run the follwing command to test the mappings."
},
{
"code": null,
"e": 58317,
"s": 58301,
"text": "mvn clean test\n"
},
{
"code": null,
"e": 58364,
"s": 58317,
"text": "Once command is successful. Verify the output."
},
{
"code": null,
"e": 59131,
"s": 58364,
"text": "mvn clean test\n[INFO] Scanning for projects...\n...\n[INFO] --- maven-surefire-plugin:2.12.4:test (default-test) @ mapping ---\n[INFO] Surefire report directory: \\mvn\\mapping\\target\\surefire-reports\n\n-------------------------------------------------------\n T E S T S\n-------------------------------------------------------\nRunning com.tutorialspoint.mapping.CarMapperTest\nTests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.035 sec\nRunning com.tutorialspoint.mapping.DeliveryAddressMapperTest\nTests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0 sec\nRunning com.tutorialspoint.mapping.StudentMapperTest\nTests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.001 sec\n\nResults :\n\nTests run: 4, Failures: 0, Errors: 0, Skipped: 0\n...\n"
},
{
"code": null,
"e": 59262,
"s": 59131,
"text": "Using Mapstruct we can pass the default value in case source property is null using defaultValue attribute of @Mapping annotation."
},
{
"code": null,
"e": 59357,
"s": 59262,
"text": "@Mapping(target = \"target-property\", source=\"source-property\" \ndefaultValue = \"default-value\")"
},
{
"code": null,
"e": 59362,
"s": 59357,
"text": "Here"
},
{
"code": null,
"e": 59456,
"s": 59362,
"text": "default-value - target-property will be set as default-value in case source-property is null."
},
{
"code": null,
"e": 59550,
"s": 59456,
"text": "default-value - target-property will be set as default-value in case source-property is null."
},
{
"code": null,
"e": 59591,
"s": 59550,
"text": "Following example demonstrates the same."
},
{
"code": null,
"e": 59669,
"s": 59591,
"text": "Open project mapping as updated in Mapping Using Constant chapter in Eclipse."
},
{
"code": null,
"e": 59713,
"s": 59669,
"text": "Update CarEntity.java with following code −"
},
{
"code": null,
"e": 59728,
"s": 59713,
"text": "CarEntity.java"
},
{
"code": null,
"e": 60511,
"s": 59728,
"text": "package com.tutorialspoint.entity;\nimport java.util.GregorianCalendar;\n\npublic class CarEntity {\n private int id;\n private double price;\n private GregorianCalendar manufacturingDate;\n private String name;\n public int getId() {\n return id;\n }\n public void setId(int id) {\n this.id = id;\n }\n public double getPrice() {\n return price;\n }\n public void setPrice(double price) {\n this.price = price;\n }\n public GregorianCalendar getManufacturingDate() {\n return manufacturingDate;\n }\n public void setManufacturingDate(GregorianCalendar manufacturingDate) {\n this.manufacturingDate = manufacturingDate;\n }\n public String getName() {\n return name;\n }\n public void setName(String name) {\n this.name = name;\n }\n}"
},
{
"code": null,
"e": 60549,
"s": 60511,
"text": "Update Car.java with following code −"
},
{
"code": null,
"e": 60558,
"s": 60549,
"text": "Car.java"
},
{
"code": null,
"e": 61416,
"s": 60558,
"text": "package com.tutorialspoint.model;\n\npublic class Car {\n private int id;\n private String price;\n private String manufacturingDate;\n private String brand;\n private String name;\n public int getId() {\n return id;\n }\n public void setId(int id) {\n this.id = id;\n }\n public String getPrice() {\n return price;\n }\n public void setPrice(String price) {\n this.price = price;\n }\n public String getManufacturingDate() {\n return manufacturingDate;\n }\n public void setManufacturingDate(String manufacturingDate) {\n this.manufacturingDate = manufacturingDate;\n }\n public String getBrand() {\n return brand;\n }\n public void setBrand(String brand) {\n this.brand = brand;\n }\n public String getName() {\n return name;\n }\n public void setName(String name) {\n this.name = name;\n }\n}"
},
{
"code": null,
"e": 61460,
"s": 61416,
"text": "Update CarMapper.java with following code −"
},
{
"code": null,
"e": 61475,
"s": 61460,
"text": "CarMapper.java"
},
{
"code": null,
"e": 62030,
"s": 61475,
"text": "package com.tutorialspoint.mapper;\n\nimport org.mapstruct.Mapper;\nimport org.mapstruct.Mapping;\n\nimport com.tutorialspoint.entity.CarEntity;\nimport com.tutorialspoint.model.Car;\n\n@Mapper\npublic interface CarMapper {\n @Mapping(source = \"name\", target = \"name\", defaultValue = \"Sample\")\n @Mapping(target = \"brand\", constant = \"BMW\")\n @Mapping(source = \"price\", target = \"price\", numberFormat = \"$#.00\")\n @Mapping(source = \"manufacturingDate\", target = \"manufacturingDate\", dateFormat = \"dd.MM.yyyy\")\n Car getModelFromEntity(CarEntity carEntity);\n}"
},
{
"code": null,
"e": 62078,
"s": 62030,
"text": "Update CarMapperTest.java with following code −"
},
{
"code": null,
"e": 62097,
"s": 62078,
"text": "CarMapperTest.java"
},
{
"code": null,
"e": 63070,
"s": 62097,
"text": "package com.tutorialspoint.mapping;\n\nimport static org.junit.jupiter.api.Assertions.assertEquals;\nimport java.util.GregorianCalendar;\nimport org.junit.jupiter.api.Test;\nimport org.mapstruct.factory.Mappers;\n\nimport com.tutorialspoint.entity.CarEntity;\nimport com.tutorialspoint.mapper.CarMapper;\nimport com.tutorialspoint.model.Car;\n\npublic class CarMapperTest {\n private CarMapper carMapper\n = Mappers.getMapper(CarMapper.class);\n\n @Test\n public void testEntityToModel() {\n CarEntity entity = new CarEntity();\n entity.setPrice(345000);\n entity.setId(1);\n entity.setManufacturingDate(new GregorianCalendar(2015, 3, 5));\n Car model = carMapper.getModelFromEntity(entity);\n assertEquals(model.getPrice(), \"$345000.00\");\n assertEquals(entity.getId(), model.getId());\n assertEquals(\"05.04.2015\", model.getManufacturingDate());\n assertEquals(\"Sample\", model.getName());\n assertEquals(\"BMW\", model.getBrand());\n }\n}"
},
{
"code": null,
"e": 63117,
"s": 63070,
"text": "Run the follwing command to test the mappings."
},
{
"code": null,
"e": 63133,
"s": 63117,
"text": "mvn clean test\n"
},
{
"code": null,
"e": 63180,
"s": 63133,
"text": "Once command is successful. Verify the output."
},
{
"code": null,
"e": 63947,
"s": 63180,
"text": "mvn clean test\n[INFO] Scanning for projects...\n...\n[INFO] --- maven-surefire-plugin:2.12.4:test (default-test) @ mapping ---\n[INFO] Surefire report directory: \\mvn\\mapping\\target\\surefire-reports\n\n-------------------------------------------------------\n T E S T S\n-------------------------------------------------------\nRunning com.tutorialspoint.mapping.CarMapperTest\nTests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.035 sec\nRunning com.tutorialspoint.mapping.DeliveryAddressMapperTest\nTests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0 sec\nRunning com.tutorialspoint.mapping.StudentMapperTest\nTests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.001 sec\n\nResults :\n\nTests run: 4, Failures: 0, Errors: 0, Skipped: 0\n...\n"
},
{
"code": null,
"e": 64106,
"s": 63947,
"text": "Using Mapstruct we can pass a computed value using defaultExpression in case source property is null using defaultExpression attribute of @Mapping annotation."
},
{
"code": null,
"e": 64213,
"s": 64106,
"text": "@Mapping(target = \"target-property\", source=\"source-property\" defaultExpression = \"default-value-method\")\n"
},
{
"code": null,
"e": 64218,
"s": 64213,
"text": "Here"
},
{
"code": null,
"e": 64336,
"s": 64218,
"text": "default-value-method − target-property will be set as result of default-value-method in case source-property is null."
},
{
"code": null,
"e": 64454,
"s": 64336,
"text": "default-value-method − target-property will be set as result of default-value-method in case source-property is null."
},
{
"code": null,
"e": 64495,
"s": 64454,
"text": "Following example demonstrates the same."
},
{
"code": null,
"e": 64577,
"s": 64495,
"text": "Open project mapping as updated in Mapping Using defaultValue chapter in Eclipse."
},
{
"code": null,
"e": 64621,
"s": 64577,
"text": "Update CarEntity.java with following code −"
},
{
"code": null,
"e": 64636,
"s": 64621,
"text": "CarEntity.java"
},
{
"code": null,
"e": 65419,
"s": 64636,
"text": "package com.tutorialspoint.entity;\nimport java.util.GregorianCalendar;\n\npublic class CarEntity {\n private int id;\n private double price;\n private GregorianCalendar manufacturingDate;\n private String name;\n public int getId() {\n return id;\n }\n public void setId(int id) {\n this.id = id;\n }\n public double getPrice() {\n return price;\n }\n public void setPrice(double price) {\n this.price = price;\n }\n public GregorianCalendar getManufacturingDate() {\n return manufacturingDate;\n }\n public void setManufacturingDate(GregorianCalendar manufacturingDate) {\n this.manufacturingDate = manufacturingDate;\n }\n public String getName() {\n return name;\n }\n public void setName(String name) {\n this.name = name;\n }\n}"
},
{
"code": null,
"e": 65457,
"s": 65419,
"text": "Update Car.java with following code −"
},
{
"code": null,
"e": 65466,
"s": 65457,
"text": "Car.java"
},
{
"code": null,
"e": 66323,
"s": 65466,
"text": "package com.tutorialspoint.model;\npublic class Car {\n private int id;\n private String price;\n private String manufacturingDate;\n private String brand;\n private String name;\n public int getId() {\n return id;\n }\n public void setId(int id) {\n this.id = id;\n }\n public String getPrice() {\n return price;\n }\n public void setPrice(String price) {\n this.price = price;\n }\n public String getManufacturingDate() {\n return manufacturingDate;\n }\n public void setManufacturingDate(String manufacturingDate) {\n this.manufacturingDate = manufacturingDate;\n }\n public String getBrand() {\n return brand;\n }\n public void setBrand(String brand) {\n this.brand = brand;\n }\n public String getName() {\n return name;\n }\n public void setName(String name) {\n this.name = name;\n }\n}"
},
{
"code": null,
"e": 66367,
"s": 66323,
"text": "Update CarMapper.java with following code −"
},
{
"code": null,
"e": 66382,
"s": 66367,
"text": "CarMapper.java"
},
{
"code": null,
"e": 67016,
"s": 66382,
"text": "package com.tutorialspoint.mapper;\n\nimport org.mapstruct.Mapper;\nimport org.mapstruct.Mapping;\nimport com.tutorialspoint.entity.CarEntity;\nimport com.tutorialspoint.model.Car;\nimport java.util.UUID;\n\n@Mapper( imports = UUID.class )\npublic interface CarMapper {\n @Mapping(source = \"name\", target = \"name\", defaultExpression = \"java(UUID.randomUUID().toString())\")\n @Mapping(target = \"brand\", constant = \"BMW\")\n @Mapping(source = \"price\", target = \"price\", numberFormat = \"$#.00\")\n @Mapping(source = \"manufacturingDate\", target = \"manufacturingDate\", dateFormat = \"dd.MM.yyyy\")\n Car getModelFromEntity(CarEntity carEntity);\n}"
},
{
"code": null,
"e": 67064,
"s": 67016,
"text": "Update CarMapperTest.java with following code −"
},
{
"code": null,
"e": 67083,
"s": 67064,
"text": "CarMapperTest.java"
},
{
"code": null,
"e": 68100,
"s": 67083,
"text": "package com.tutorialspoint.mapping;\n\nimport static org.junit.jupiter.api.Assertions.assertEquals;\nimport static org.junit.jupiter.api.Assertions.assertNotNull;\nimport java.util.GregorianCalendar;\nimport org.junit.jupiter.api.Test;\nimport org.mapstruct.factory.Mappers;\nimport com.tutorialspoint.entity.CarEntity;\nimport com.tutorialspoint.mapper.CarMapper;\nimport com.tutorialspoint.model.Car;\n\npublic class CarMapperTest {\n private CarMapper carMapper=Mappers.getMapper(CarMapper.class);\n\n @Test\n public void testEntityToModel() {\n CarEntity entity = new CarEntity();\n entity.setPrice(345000);\n entity.setId(1);\n entity.setManufacturingDate(new GregorianCalendar(2015, 3, 5));\n Car model = carMapper.getModelFromEntity(entity);\n assertEquals(model.getPrice(), \"$345000.00\");\n assertEquals(entity.getId(), model.getId());\n assertEquals(\"05.04.2015\", model.getManufacturingDate());\n assertNotNull(model.getName());\n assertEquals(\"BMW\", model.getBrand());\n }\n}"
},
{
"code": null,
"e": 68148,
"s": 68100,
"text": "Run the following command to test the mappings."
},
{
"code": null,
"e": 68164,
"s": 68148,
"text": "mvn clean test\n"
},
{
"code": null,
"e": 68211,
"s": 68164,
"text": "Once command is successful. Verify the output."
},
{
"code": null,
"e": 68978,
"s": 68211,
"text": "mvn clean test\n[INFO] Scanning for projects...\n...\n[INFO] --- maven-surefire-plugin:2.12.4:test (default-test) @ mapping ---\n[INFO] Surefire report directory: \\mvn\\mapping\\target\\surefire-reports\n\n-------------------------------------------------------\n T E S T S\n-------------------------------------------------------\nRunning com.tutorialspoint.mapping.CarMapperTest\nTests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.035 sec\nRunning com.tutorialspoint.mapping.DeliveryAddressMapperTest\nTests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0 sec\nRunning com.tutorialspoint.mapping.StudentMapperTest\nTests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.001 sec\n\nResults :\n\nTests run: 4, Failures: 0, Errors: 0, Skipped: 0\n...\n"
},
{
"code": null,
"e": 69136,
"s": 68978,
"text": "Using Mapstruct we can map list in similar fashion as we map primitives. To get a list of objects, we should provide a mapper method which can map an object."
},
{
"code": null,
"e": 69338,
"s": 69136,
"text": "@Mapper\npublic interface CarMapper {\n List<String> getListOfStrings(List<Integer> listOfIntegers);\n List<Car> getCars(List<CarEntity> carEntities);\n Car getModelFromEntity(CarEntity carEntity);\n}"
},
{
"code": null,
"e": 69379,
"s": 69338,
"text": "Following example demonstrates the same."
},
{
"code": null,
"e": 69466,
"s": 69379,
"text": "Open project mapping as updated in Mapping Using defaultExpression chapter in Eclipse."
},
{
"code": null,
"e": 69510,
"s": 69466,
"text": "Update CarEntity.java with following code −"
},
{
"code": null,
"e": 69525,
"s": 69510,
"text": "CarEntity.java"
},
{
"code": null,
"e": 70308,
"s": 69525,
"text": "package com.tutorialspoint.entity;\nimport java.util.GregorianCalendar;\n\npublic class CarEntity {\n private int id;\n private double price;\n private GregorianCalendar manufacturingDate;\n private String name;\n public int getId() {\n return id;\n }\n public void setId(int id) {\n this.id = id;\n }\n public double getPrice() {\n return price;\n }\n public void setPrice(double price) {\n this.price = price;\n }\n public GregorianCalendar getManufacturingDate() {\n return manufacturingDate;\n }\n public void setManufacturingDate(GregorianCalendar manufacturingDate) {\n this.manufacturingDate = manufacturingDate;\n }\n public String getName() {\n return name;\n }\n public void setName(String name) {\n this.name = name;\n }\n}"
},
{
"code": null,
"e": 70346,
"s": 70308,
"text": "Update Car.java with following code −"
},
{
"code": null,
"e": 70355,
"s": 70346,
"text": "Car.java"
},
{
"code": null,
"e": 71213,
"s": 70355,
"text": "package com.tutorialspoint.model;\n\npublic class Car {\n private int id;\n private String price;\n private String manufacturingDate;\n private String brand;\n private String name;\n public int getId() {\n return id;\n }\n public void setId(int id) {\n this.id = id;\n }\n public String getPrice() {\n return price;\n }\n public void setPrice(String price) {\n this.price = price;\n }\n public String getManufacturingDate() {\n return manufacturingDate;\n }\n public void setManufacturingDate(String manufacturingDate) {\n this.manufacturingDate = manufacturingDate;\n }\n public String getBrand() {\n return brand;\n }\n public void setBrand(String brand) {\n this.brand = brand;\n }\n public String getName() {\n return name;\n }\n public void setName(String name) {\n this.name = name;\n }\n}"
},
{
"code": null,
"e": 71257,
"s": 71213,
"text": "Update CarMapper.java with following code −"
},
{
"code": null,
"e": 71272,
"s": 71257,
"text": "CarMapper.java"
},
{
"code": null,
"e": 72047,
"s": 71272,
"text": "package com.tutorialspoint.mapper;\n\nimport org.mapstruct.Mapper;\nimport org.mapstruct.Mapping;\n\nimport com.tutorialspoint.entity.CarEntity;\nimport com.tutorialspoint.model.Car;\n\nimport java.util.List;\nimport java.util.UUID;\n\n@Mapper( imports = UUID.class )\npublic interface CarMapper {\n @Mapping(source = \"name\", target = \"name\", defaultExpression = \"java(UUID.randomUUID().toString())\")\n @Mapping(target = \"brand\", constant = \"BMW\")\n @Mapping(source = \"price\", target = \"price\", numberFormat = \"$#.00\")\n @Mapping(source = \"manufacturingDate\", target = \"manufacturingDate\", dateFormat = \"dd.MM.yyyy\")\n Car getModelFromEntity(CarEntity carEntity);\n\n List<String> getListOfStrings(List<Integer> listOfIntegers);\n List<Car> getCars(List<CarEntity> carEntities);\n}"
},
{
"code": null,
"e": 72095,
"s": 72047,
"text": "Update CarMapperTest.java with following code −"
},
{
"code": null,
"e": 72114,
"s": 72095,
"text": "CarMapperTest.java"
},
{
"code": null,
"e": 73661,
"s": 72114,
"text": "package com.tutorialspoint.mapping;\n\nimport static org.junit.jupiter.api.Assertions.assertEquals;\nimport static org.junit.jupiter.api.Assertions.assertNotNull;\n\nimport java.util.Arrays;\nimport java.util.GregorianCalendar;\nimport java.util.List;\n\nimport org.junit.jupiter.api.Test;\nimport org.mapstruct.factory.Mappers;\n\nimport com.tutorialspoint.entity.CarEntity;\nimport com.tutorialspoint.mapper.CarMapper;\nimport com.tutorialspoint.model.Car;\n\npublic class CarMapperTest {\n private CarMapper carMapper\n = Mappers.getMapper(CarMapper.class);\n\n @Test\n public void testEntityToModel() {\n CarEntity entity = new CarEntity();\n entity.setPrice(345000);\n entity.setId(1);\n entity.setManufacturingDate(new GregorianCalendar(2015, 3, 5));\n\n CarEntity entity1 = new CarEntity();\n entity1.setPrice(445000);\n entity1.setId(2);\n entity1.setManufacturingDate(new GregorianCalendar(2015, 3, 5));\n\n List<CarEntity> carEntities = Arrays.asList(entity, entity1);\n\n Car model = carMapper.getModelFromEntity(entity);\n assertEquals(\"$345000.00\",model.getPrice());\n assertEquals(entity.getId(), model.getId());\n\n assertEquals(\"BMW\", model.getBrand());\n assertEquals(\"05.04.2015\", model.getManufacturingDate());\n\n List<Integer> list = Arrays.asList(1,2,3);\n List<String> listOfStrings = carMapper.getListOfStrings(list);\n List<Car> listOfCars = carMapper.getCars(carEntities);\n\n assertEquals(3, listOfStrings.size());\n assertEquals(2, listOfCars.size());\n }\n}"
},
{
"code": null,
"e": 73708,
"s": 73661,
"text": "Run the follwing command to test the mappings."
},
{
"code": null,
"e": 73724,
"s": 73708,
"text": "mvn clean test\n"
},
{
"code": null,
"e": 73771,
"s": 73724,
"text": "Once command is successful. Verify the output."
},
{
"code": null,
"e": 74538,
"s": 73771,
"text": "mvn clean test\n[INFO] Scanning for projects...\n...\n[INFO] --- maven-surefire-plugin:2.12.4:test (default-test) @ mapping ---\n[INFO] Surefire report directory: \\mvn\\mapping\\target\\surefire-reports\n\n-------------------------------------------------------\n T E S T S\n-------------------------------------------------------\nRunning com.tutorialspoint.mapping.CarMapperTest\nTests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.035 sec\nRunning com.tutorialspoint.mapping.DeliveryAddressMapperTest\nTests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0 sec\nRunning com.tutorialspoint.mapping.StudentMapperTest\nTests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.001 sec\n\nResults :\n\nTests run: 4, Failures: 0, Errors: 0, Skipped: 0\n...\n"
},
{
"code": null,
"e": 74675,
"s": 74538,
"text": "Using Mapstruct we can create mapping of map objects using @MapMapping annotation. Other rules of mapping are same as we've seen so far."
},
{
"code": null,
"e": 74833,
"s": 74675,
"text": "@Mapper\npublic interface UtilityMapper {\n @MapMapping(valueDateFormat = \"dd.MM.yyyy\")\n Map<String, String> getMap(Map<Long, GregorianCalendar> source);\n}"
},
{
"code": null,
"e": 74874,
"s": 74833,
"text": "Following example demonstrates the same."
},
{
"code": null,
"e": 74942,
"s": 74874,
"text": "Open project mapping as updated in Mapping List chapter in Eclipse."
},
{
"code": null,
"e": 74990,
"s": 74942,
"text": "Create UtilityMapper.java with following code −"
},
{
"code": null,
"e": 75009,
"s": 74990,
"text": "UtilityMapper.java"
},
{
"code": null,
"e": 75325,
"s": 75009,
"text": "package com.tutorialspoint.mapper;\n\nimport java.util.GregorianCalendar;\nimport java.util.Map;\n\nimport org.mapstruct.MapMapping;\nimport org.mapstruct.Mapper;\n\n@Mapper\npublic interface UtilityMapper {\n @MapMapping(valueDateFormat = \"dd.MM.yyyy\")\n Map<String, String> getMap(Map<Long, GregorianCalendar> source);\n}"
},
{
"code": null,
"e": 75377,
"s": 75325,
"text": "Create UtilityMapperTest.java with following code −"
},
{
"code": null,
"e": 75400,
"s": 75377,
"text": "UtilityMapperTest.java"
},
{
"code": null,
"e": 76115,
"s": 75400,
"text": "package com.tutorialspoint.mapping;\n\nimport static org.junit.jupiter.api.Assertions.assertEquals;\n\nimport java.util.GregorianCalendar;\nimport java.util.HashMap;\nimport java.util.Map;\n\nimport org.junit.jupiter.api.Test;\nimport org.mapstruct.factory.Mappers;\n\nimport com.tutorialspoint.mapper.UtilityMapper;\n\npublic class UtilityMapperTest {\n private UtilityMapper utilityMapper\n = Mappers.getMapper(UtilityMapper.class);\n\n @Test\n public void testMapMapping() {\n Map<Long, GregorianCalendar> source = new HashMap<>();\n source.put(1L, new GregorianCalendar(2015, 3, 5));\n\n Map<String, String> target = utilityMapper.getMap(source);\n assertEquals(\"05.04.2015\", target.get(\"1\"));\t\t\n }\n}"
},
{
"code": null,
"e": 76162,
"s": 76115,
"text": "Run the follwing command to test the mappings."
},
{
"code": null,
"e": 76178,
"s": 76162,
"text": "mvn clean test\n"
},
{
"code": null,
"e": 76225,
"s": 76178,
"text": "Once command is successful. Verify the output."
},
{
"code": null,
"e": 77123,
"s": 76225,
"text": "mvn clean test\n[INFO] Scanning for projects...\n...\n[INFO] --- maven-surefire-plugin:2.12.4:test (default-test) @ mapping ---\n[INFO] Surefire report directory: \\mvn\\mapping\\target\\surefire-reports\n\n-------------------------------------------------------\n T E S T S\n-------------------------------------------------------\nRunning com.tutorialspoint.mapping.CarMapperTest\nTests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.327 sec\nRunning com.tutorialspoint.mapping.DeliveryAddressMapperTest\nTests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.001 sec\nRunning com.tutorialspoint.mapping.StudentMapperTest\nTests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.001 sec\nRunning com.tutorialspoint.mapping.UtilityMapperTest\nTests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.001 sec\n\nResults :\n\nTests run: 5, Failures: 0, Errors: 0, Skipped: 0\n...\n"
},
{
"code": null,
"e": 77215,
"s": 77123,
"text": "Using Mapstruct we can create mapping of streams in the same way as we did for collections."
},
{
"code": null,
"e": 77312,
"s": 77215,
"text": "@Mapper\npublic interface UtilityMapper {\n Stream<String> getStream(Stream<Integer> source);\n}\n"
},
{
"code": null,
"e": 77353,
"s": 77312,
"text": "Following example demonstrates the same."
},
{
"code": null,
"e": 77420,
"s": 77353,
"text": "Open project mapping as updated in Mapping Map chapter in Eclipse."
},
{
"code": null,
"e": 77468,
"s": 77420,
"text": "Update UtilityMapper.java with following code −"
},
{
"code": null,
"e": 77487,
"s": 77468,
"text": "UtilityMapper.java"
},
{
"code": null,
"e": 77887,
"s": 77487,
"text": "package com.tutorialspoint.mapper;\n\nimport java.util.GregorianCalendar;\nimport java.util.Map;\nimport java.util.stream.Stream;\nimport org.mapstruct.MapMapping;\nimport org.mapstruct.Mapper;\n\n@Mapper\npublic interface UtilityMapper {\n @MapMapping(valueDateFormat = \"dd.MM.yyyy\")\n Map<String, String> getMap(Map<Long, GregorianCalendar> source);\n Stream<String> getStream(Stream<Integer> source);\n}"
},
{
"code": null,
"e": 77939,
"s": 77887,
"text": "Update UtilityMapperTest.java with following code −"
},
{
"code": null,
"e": 77962,
"s": 77939,
"text": "UtilityMapperTest.java"
},
{
"code": null,
"e": 78950,
"s": 77962,
"text": "package com.tutorialspoint.mapping;\n\nimport static org.junit.jupiter.api.Assertions.assertEquals;\nimport java.util.Arrays;\nimport java.util.GregorianCalendar;\nimport java.util.HashMap;\nimport java.util.Map;\nimport java.util.stream.Stream;\nimport org.junit.jupiter.api.Test;\nimport org.mapstruct.factory.Mappers;\nimport com.tutorialspoint.mapper.UtilityMapper;\n\npublic class UtilityMapperTest {\n private UtilityMapper utilityMapper=Mappers.getMapper(UtilityMapper.class);\n \n @Test\n public void testMapMapping() {\n Map<Long, GregorianCalendar> source = new HashMap<>();\n source.put(1L, new GregorianCalendar(2015, 3, 5));\n\n Map<String, String> target = utilityMapper.getMap(source);\n assertEquals(\"05.04.2015\", target.get(\"1\"));\t\t\n }\n @Test\n public void testGetStream() {\n Stream<Integer> numbers = Arrays.asList(1, 2, 3, 4).stream();\n\n Stream<String> strings = utilityMapper.getStream(numbers);\n assertEquals(4, strings.count());\t\t\t\n }\n}"
},
{
"code": null,
"e": 78998,
"s": 78950,
"text": "Run the following command to test the mappings."
},
{
"code": null,
"e": 79014,
"s": 78998,
"text": "mvn clean test\n"
},
{
"code": null,
"e": 79061,
"s": 79014,
"text": "Once command is successful. Verify the output."
},
{
"code": null,
"e": 79959,
"s": 79061,
"text": "mvn clean test\n[INFO] Scanning for projects...\n...\n[INFO] --- maven-surefire-plugin:2.12.4:test (default-test) @ mapping ---\n[INFO] Surefire report directory: \\mvn\\mapping\\target\\surefire-reports\n\n-------------------------------------------------------\n T E S T S\n-------------------------------------------------------\nRunning com.tutorialspoint.mapping.CarMapperTest\nTests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.327 sec\nRunning com.tutorialspoint.mapping.DeliveryAddressMapperTest\nTests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.001 sec\nRunning com.tutorialspoint.mapping.StudentMapperTest\nTests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.001 sec\nRunning com.tutorialspoint.mapping.UtilityMapperTest\nTests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.001 sec\n\nResults :\n\nTests run: 5, Failures: 0, Errors: 0, Skipped: 0\n...\n"
},
{
"code": null,
"e": 80124,
"s": 79959,
"text": "Mapstruct automatically maps enums. Enums with same name are mapped automatically. In case of different name, we can use @ValueMapping annotation to do the mapping."
},
{
"code": null,
"e": 80268,
"s": 80124,
"text": "@Mapper\npublic interface UtilityMapper {\n @ValueMapping(source = \"EXTRA\", target = \"SPECIAL\")\n PlacedOrderType getEnum(OrderType order);\n}\n"
},
{
"code": null,
"e": 80309,
"s": 80268,
"text": "Following example demonstrates the same."
},
{
"code": null,
"e": 80379,
"s": 80309,
"text": "Open project mapping as updated in Mapping Stream chapter in Eclipse."
},
{
"code": null,
"e": 80423,
"s": 80379,
"text": "Create OrderType.java with following code −"
},
{
"code": null,
"e": 80438,
"s": 80423,
"text": "OrderType.java"
},
{
"code": null,
"e": 80525,
"s": 80438,
"text": "package com.tutorialspoint.enums;\npublic enum OrderType {\n EXTRA, NORMAL, STANDARD\n}"
},
{
"code": null,
"e": 80575,
"s": 80525,
"text": "Create PlacedOrderType.java with following code −"
},
{
"code": null,
"e": 80596,
"s": 80575,
"text": "PlacedOrderType.java"
},
{
"code": null,
"e": 80691,
"s": 80596,
"text": "package com.tutorialspoint.enums;\npublic enum PlacedOrderType {\n SPECIAL, NORMAL, STANDARD\n}"
},
{
"code": null,
"e": 80739,
"s": 80691,
"text": "Update UtilityMapper.java with following code −"
},
{
"code": null,
"e": 80758,
"s": 80739,
"text": "UtilityMapper.java"
},
{
"code": null,
"e": 81389,
"s": 80758,
"text": "package com.tutorialspoint.mapper;\n\nimport java.util.GregorianCalendar;\nimport java.util.Map;\nimport java.util.stream.Stream;\nimport org.mapstruct.MapMapping;\nimport org.mapstruct.Mapper;\nimport org.mapstruct.ValueMapping;\nimport com.tutorialspoint.enums.OrderType;\nimport com.tutorialspoint.enums.PlacedOrderType;\n\n@Mapper\npublic interface UtilityMapper {\n @MapMapping(valueDateFormat = \"dd.MM.yyyy\")\n Map<String, String> getMap(Map<Long, GregorianCalendar> source);\n Stream<String> getStream(Stream<Integer> source);\n \n @ValueMapping(source = \"EXTRA\", target = \"SPECIAL\")\n PlacedOrderType getEnum(OrderType order);\n}"
},
{
"code": null,
"e": 81441,
"s": 81389,
"text": "Update UtilityMapperTest.java with following code −"
},
{
"code": null,
"e": 81464,
"s": 81441,
"text": "UtilityMapperTest.java"
},
{
"code": null,
"e": 83064,
"s": 81464,
"text": "package com.tutorialspoint.mapping;\n\nimport static org.junit.jupiter.api.Assertions.assertEquals;\nimport java.util.Arrays;\nimport java.util.GregorianCalendar;\nimport java.util.HashMap;\nimport java.util.Map;\nimport java.util.stream.Stream;\nimport org.junit.jupiter.api.Test;\nimport org.mapstruct.factory.Mappers;\nimport com.tutorialspoint.enums.OrderType;\nimport com.tutorialspoint.enums.PlacedOrderType;\nimport com.tutorialspoint.mapper.UtilityMapper;\n\npublic class UtilityMapperTest {\n private UtilityMapper utilityMapper=Mappers.getMapper(UtilityMapper.class);\n\n @Test\n public void testMapMapping() {\n Map<Long, GregorianCalendar> source = new HashMap<>();\n source.put(1L, new GregorianCalendar(2015, 3, 5));\n\n Map<String, String> target = utilityMapper.getMap(source);\n assertEquals(\"05.04.2015\", target.get(\"1\"));\t\t\n }\n @Test\n public void testGetStream() {\n Stream<Integer> numbers = Arrays.asList(1, 2, 3, 4).stream();\n Stream<String> strings = utilityMapper.getStream(numbers);\n assertEquals(4, strings.count());\t\t\t\n } \n @Test\n public void testGetEnum() {\n PlacedOrderType placedOrderType = utilityMapper.getEnum(OrderType.EXTRA);\n PlacedOrderType placedOrderType1 = utilityMapper.getEnum(OrderType.NORMAL);\n PlacedOrderType placedOrderType2 = utilityMapper.getEnum(OrderType.STANDARD);\n assertEquals(PlacedOrderType.SPECIAL.name(), placedOrderType.name());\n assertEquals(PlacedOrderType.NORMAL.name(), placedOrderType1.name());\n assertEquals(PlacedOrderType.STANDARD.name(), placedOrderType2.name());\n }\n}"
},
{
"code": null,
"e": 83112,
"s": 83064,
"text": "Run the following command to test the mappings."
},
{
"code": null,
"e": 83128,
"s": 83112,
"text": "mvn clean test\n"
},
{
"code": null,
"e": 83175,
"s": 83128,
"text": "Once command is successful. Verify the output."
},
{
"code": null,
"e": 84065,
"s": 83175,
"text": "mvn clean test\n[INFO] Scanning for projects...\n...\n[INFO] --- maven-surefire-plugin:2.12.4:test (default-test) @ mapping ---\n[INFO] Surefire report directory: \\mvn\\mapping\\target\\surefire-reports\n\n-------------------------------------------------------\n T E S T S\n-------------------------------------------------------\nRunning com.tutorialspoint.mapping.CarMapperTest\nTests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.256 sec\nRunning com.tutorialspoint.mapping.DeliveryAddressMapperTest\nTests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.001 sec\nRunning com.tutorialspoint.mapping.StudentMapperTest\nTests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0 sec\nRunning com.tutorialspoint.mapping.UtilityMapperTest\nTests run: 3, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0 sec\n\nResults :\n\nTests run: 7, Failures: 0, Errors: 0, Skipped: 0\n...\n"
},
{
"code": null,
"e": 84228,
"s": 84065,
"text": "Mapstruct mapper allows throwing specific exception. Consider a case of custom mapping method where we want to throw our custom exception in case of invalid data."
},
{
"code": null,
"e": 84353,
"s": 84228,
"text": "@Mapper(uses=DateMapper.class)\npublic interface UtilityMapper {\n CarEntity getCarEntity(Car car) throws ParseException;\n}"
},
{
"code": null,
"e": 84394,
"s": 84353,
"text": "Following example demonstrates the same."
},
{
"code": null,
"e": 84462,
"s": 84394,
"text": "Open project mapping as updated in Mapping Enum chapter in Eclipse."
},
{
"code": null,
"e": 84510,
"s": 84462,
"text": "Update UtilityMapper.java with following code −"
},
{
"code": null,
"e": 84529,
"s": 84510,
"text": "UtilityMapper.java"
},
{
"code": null,
"e": 85932,
"s": 84529,
"text": "package com.tutorialspoint.mapper;\n\nimport java.text.ParseException;\nimport java.text.SimpleDateFormat;\nimport java.util.Date;\nimport java.util.GregorianCalendar;\nimport java.util.Map;\nimport java.util.stream.Stream;\n\nimport org.mapstruct.MapMapping;\nimport org.mapstruct.Mapper;\nimport org.mapstruct.ValueMapping;\n\nimport com.tutorialspoint.entity.CarEntity;\nimport com.tutorialspoint.enums.OrderType;\nimport com.tutorialspoint.enums.PlacedOrderType;\nimport com.tutorialspoint.model.Car;\n\n@Mapper(uses=DateMapper.class)\npublic interface UtilityMapper {\n @MapMapping(valueDateFormat = \"dd.MM.yyyy\")\n Map<String, String> getMap(Map<Long, GregorianCalendar> source);\n\n Stream<String> getStream(Stream<Integer> source);\n\n @ValueMapping(source = \"EXTRA\", target = \"SPECIAL\")\n PlacedOrderType getEnum(OrderType order);\n\n CarEntity getCarEntity(Car car) throws ParseException;\n}\n\nclass DateMapper {\n public String asString(GregorianCalendar date) {\n return date != null ? new SimpleDateFormat( \"yyyy-MM-dd\" )\n .format( date.getTime() ) : null;\n }\n\n public GregorianCalendar asDate(String date) throws ParseException {\n Date date1 = date != null ? new SimpleDateFormat( \"yyyy-MM-dd\" )\n .parse( date ) : null;\n if(date1 != null) {\n return new GregorianCalendar(date1.getYear(), date1.getMonth(),date1.getDay());\n }\n return null; \n }\n}"
},
{
"code": null,
"e": 85984,
"s": 85932,
"text": "Update UtilityMapperTest.java with following code −"
},
{
"code": null,
"e": 86007,
"s": 85984,
"text": "UtilityMapperTest.java"
},
{
"code": null,
"e": 88158,
"s": 86007,
"text": "package com.tutorialspoint.mapping;\n\nimport static org.junit.jupiter.api.Assertions.assertEquals;\nimport static org.junit.jupiter.api.Assertions.assertTrue;\n\nimport java.text.ParseException;\nimport java.util.Arrays;\nimport java.util.GregorianCalendar;\nimport java.util.HashMap;\nimport java.util.Map;\nimport java.util.stream.Stream;\n\nimport org.junit.jupiter.api.Test;\nimport org.mapstruct.factory.Mappers;\n\nimport com.tutorialspoint.entity.CarEntity;\nimport com.tutorialspoint.enums.OrderType;\nimport com.tutorialspoint.enums.PlacedOrderType;\nimport com.tutorialspoint.mapper.UtilityMapper;\nimport com.tutorialspoint.model.Car;\n\npublic class UtilityMapperTest {\n private UtilityMapper utilityMapper\n = Mappers.getMapper(UtilityMapper.class);\n\n @Test\n public void testMapMapping() {\n Map<Long, GregorianCalendar> source = new HashMap<>();\n source.put(1L, new GregorianCalendar(2015, 3, 5));\n\n Map<String, String> target = utilityMapper.getMap(source);\n assertEquals(\"2015-04-05\", target.get(\"1\"));\t\t\n }\n\n @Test\n public void testGetStream() {\n Stream<Integer> numbers = Arrays.asList(1, 2, 3, 4).stream();\n\n Stream<String> strings = utilityMapper.getStream(numbers);\n assertEquals(4, strings.count());\t\t\t\n }\n\n @Test\n public void testGetEnum() {\n PlacedOrderType placedOrderType = utilityMapper.getEnum(OrderType.EXTRA);\n PlacedOrderType placedOrderType1 = utilityMapper.getEnum(OrderType.NORMAL);\n PlacedOrderType placedOrderType2 = utilityMapper.getEnum(OrderType.STANDARD);\n assertEquals(PlacedOrderType.SPECIAL.name(), placedOrderType.name());\n assertEquals(PlacedOrderType.NORMAL.name(), placedOrderType1.name());\n assertEquals(PlacedOrderType.STANDARD.name(), placedOrderType2.name());\n }\n\n @Test\n public void testGetCar() {\n Car car = new Car();\n car.setId(1);\n car.setManufacturingDate(\"11/10/2020\");\n boolean exceptionOccured = false;\n try {\n CarEntity carEntity = utilityMapper.getCarEntity(car);\n } catch (ParseException e) {\n exceptionOccured = true;\n }\n assertTrue(exceptionOccured);\n }\n}"
},
{
"code": null,
"e": 88205,
"s": 88158,
"text": "Run the follwing command to test the mappings."
},
{
"code": null,
"e": 88221,
"s": 88205,
"text": "mvn clean test\n"
},
{
"code": null,
"e": 88268,
"s": 88221,
"text": "Once command is successful. Verify the output."
},
{
"code": null,
"e": 89158,
"s": 88268,
"text": "mvn clean test\n[INFO] Scanning for projects...\n...\n[INFO] --- maven-surefire-plugin:2.12.4:test (default-test) @ mapping ---\n[INFO] Surefire report directory: \\mvn\\mapping\\target\\surefire-reports\n\n-------------------------------------------------------\n T E S T S\n-------------------------------------------------------\nRunning com.tutorialspoint.mapping.CarMapperTest\nTests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.256 sec\nRunning com.tutorialspoint.mapping.DeliveryAddressMapperTest\nTests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.001 sec\nRunning com.tutorialspoint.mapping.StudentMapperTest\nTests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0 sec\nRunning com.tutorialspoint.mapping.UtilityMapperTest\nTests run: 4, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0 sec\n\nResults :\n\nTests run: 8, Failures: 0, Errors: 0, Skipped: 0\n...\n"
},
{
"code": null,
"e": 89282,
"s": 89158,
"text": "Mapstruct mapper allows creating a custom mapper method to map an object. To mapper interface, we can add a default method."
},
{
"code": null,
"e": 89510,
"s": 89282,
"text": "@Mapper(uses=DateMapper.class)\npublic interface UtilityMapper {\n default Car getCar(CarEntity entity) {\n Car car = new Car();\n car.setId(entity.getId());\n car.setName(entity.getName());\n return car;\n }\n}"
},
{
"code": null,
"e": 89551,
"s": 89510,
"text": "Following example demonstrates the same."
},
{
"code": null,
"e": 89619,
"s": 89551,
"text": "Open project mapping as updated in Mapping Enum chapter in Eclipse."
},
{
"code": null,
"e": 89667,
"s": 89619,
"text": "Update UtilityMapper.java with following code −"
},
{
"code": null,
"e": 89686,
"s": 89667,
"text": "UtilityMapper.java"
},
{
"code": null,
"e": 91255,
"s": 89686,
"text": "package com.tutorialspoint.mapper;\n\nimport java.text.ParseException;\nimport java.text.SimpleDateFormat;\nimport java.util.Date;\nimport java.util.GregorianCalendar;\nimport java.util.Map;\nimport java.util.stream.Stream;\n\nimport org.mapstruct.MapMapping;\nimport org.mapstruct.Mapper;\nimport org.mapstruct.ValueMapping;\n\nimport com.tutorialspoint.entity.CarEntity;\nimport com.tutorialspoint.enums.OrderType;\nimport com.tutorialspoint.enums.PlacedOrderType;\nimport com.tutorialspoint.model.Car;\n\n@Mapper(uses=DateMapper.class)\npublic interface UtilityMapper {\n @MapMapping(valueDateFormat = \"dd.MM.yyyy\")\n Map<String, String> getMap(Map<Long, GregorianCalendar> source);\n\n Stream<String> getStream(Stream<Integer> source);\n\n @ValueMapping(source = \"EXTRA\", target = \"SPECIAL\")\n PlacedOrderType getEnum(OrderType order);\n\n CarEntity getCarEntity(Car car) throws ParseException;\n \n default Car getCar(CarEntity entity) {\n Car car = new Car();\n car.setId(entity.getId());\n car.setName(entity.getName());\n return car;\n }\n}\n\nclass DateMapper {\n public String asString(GregorianCalendar date) {\n return date != null ? new SimpleDateFormat( \"yyyy-MM-dd\" )\n .format( date.getTime() ) : null;\n }\n\n public GregorianCalendar asDate(String date) throws ParseException {\n Date date1 = date != null ? new SimpleDateFormat( \"yyyy-MM-dd\" )\n .parse( date ) : null;\n if(date1 != null) {\n return new GregorianCalendar(date1.getYear(), date1.getMonth(),date1.getDay());\n }\n return null; \n }\n}"
},
{
"code": null,
"e": 91307,
"s": 91255,
"text": "Update UtilityMapperTest.java with following code −"
},
{
"code": null,
"e": 91330,
"s": 91307,
"text": "UtilityMapperTest.java"
},
{
"code": null,
"e": 93777,
"s": 91330,
"text": "package com.tutorialspoint.mapping;\n\nimport static org.junit.jupiter.api.Assertions.assertEquals;\nimport static org.junit.jupiter.api.Assertions.assertTrue;\n\nimport java.text.ParseException;\nimport java.util.Arrays;\nimport java.util.GregorianCalendar;\nimport java.util.HashMap;\nimport java.util.Map;\nimport java.util.stream.Stream;\n\nimport org.junit.jupiter.api.Test;\nimport org.mapstruct.factory.Mappers;\n\nimport com.tutorialspoint.entity.CarEntity;\nimport com.tutorialspoint.enums.OrderType;\nimport com.tutorialspoint.enums.PlacedOrderType;\nimport com.tutorialspoint.mapper.UtilityMapper;\nimport com.tutorialspoint.model.Car;\n\npublic class UtilityMapperTest {\n private UtilityMapper utilityMapper\n = Mappers.getMapper(UtilityMapper.class);\n\n @Test\n public void testMapMapping() {\n Map<Long, GregorianCalendar> source = new HashMap<>();\n source.put(1L, new GregorianCalendar(2015, 3, 5));\n\n Map<String, String> target = utilityMapper.getMap(source);\n assertEquals(\"2015-04-05\", target.get(\"1\"));\t\t\n }\n\n @Test\n public void testGetStream() {\n Stream<Integer> numbers = Arrays.asList(1, 2, 3, 4).stream();\n Stream<String> strings = utilityMapper.getStream(numbers);\n assertEquals(4, strings.count());\t\t\t\n }\n\n @Test\n public void testGetEnum() {\n PlacedOrderType placedOrderType = utilityMapper.getEnum(OrderType.EXTRA);\n PlacedOrderType placedOrderType1 = utilityMapper.getEnum(OrderType.NORMAL);\n PlacedOrderType placedOrderType2 = utilityMapper.getEnum(OrderType.STANDARD);\n assertEquals(PlacedOrderType.SPECIAL.name(), placedOrderType.name());\n assertEquals(PlacedOrderType.NORMAL.name(), placedOrderType1.name());\n assertEquals(PlacedOrderType.STANDARD.name(), placedOrderType2.name());\n }\n\n @Test\n public void testGetCarEntity() {\n Car car = new Car();\n car.setId(1);\n car.setManufacturingDate(\"11/10/2020\");\n boolean exceptionOccured = false;\n try {\n CarEntity carEntity = utilityMapper.getCarEntity(car);\n } catch (ParseException e) {\n exceptionOccured = true;\n }\n assertTrue(exceptionOccured);\n }\n\n @Test\n public void testGetCar() {\n CarEntity entity = new CarEntity();\n entity.setId(1);\n entity.setName(\"ZEN\");\n\n Car car = utilityMapper.getCar(entity);\n\n assertEquals(entity.getId(), car.getId());\n assertEquals(entity.getName(), car.getName());\t\t\n }\n}"
},
{
"code": null,
"e": 93824,
"s": 93777,
"text": "Run the follwing command to test the mappings."
},
{
"code": null,
"e": 93840,
"s": 93824,
"text": "mvn clean test\n"
},
{
"code": null,
"e": 93887,
"s": 93840,
"text": "Once command is successful. Verify the output."
},
{
"code": null,
"e": 94777,
"s": 93887,
"text": "mvn clean test\n[INFO] Scanning for projects...\n...\n[INFO] --- maven-surefire-plugin:2.12.4:test (default-test) @ mapping ---\n[INFO] Surefire report directory: \\mvn\\mapping\\target\\surefire-reports\n\n-------------------------------------------------------\n T E S T S\n-------------------------------------------------------\nRunning com.tutorialspoint.mapping.CarMapperTest\nTests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.256 sec\nRunning com.tutorialspoint.mapping.DeliveryAddressMapperTest\nTests run: 1, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0.001 sec\nRunning com.tutorialspoint.mapping.StudentMapperTest\nTests run: 2, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0 sec\nRunning com.tutorialspoint.mapping.UtilityMapperTest\nTests run: 5, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 0 sec\n\nResults :\n\nTests run: 9, Failures: 0, Errors: 0, Skipped: 0\n...\n"
},
{
"code": null,
"e": 94784,
"s": 94777,
"text": " Print"
},
{
"code": null,
"e": 94795,
"s": 94784,
"text": " Add Notes"
}
] |
Output of Java program | Set 22 (Overloading) - GeeksforGeeks | 03 Feb, 2021
Prerequisite – Overloading in Java1) What is the output of the following program?
Java
public class Test{ public int getData() //getdata() 1 { return 0; } public long getData() //getdata 2 { return 1; } public static void main(String[] args) { Test obj = new Test(); System.out.println(obj.getData()); }}
a) 1 b) 0 c) Runtime error d) Compilation errorAns. (d) Explanation: For method overloading, methods must have different signatures. Return type of methods does not contribute towards different method signature, so the code above give compilation error. Both getdata 1 and getdata 2 only differ in return types and NOT signatures. 2) What is the output of the following program?
Java
public class Test{ public int getData(String temp) throws IOException { return 0; } public int getData(String temp) throws Exception { return 1; } public static void main(String[] args) { Test obj = new Test(); System.out.println(obj.getData("GFG")); }}
a) 0 b) 1 c) Compilation error d) Runtime errorAns. (c) Explanation: Methods that throws different exceptions are not overloaded as their signature are still the same.3) What is the output of the following program?
Java
public class Test{ private String function() { return ("GFG"); } public final static String function(int data) { return ("GeeksforGeeks"); } public static void main(String[] args) { Test obj = new Test(); System.out.println(obj.function()); }}
a) Compilation error b) Runtime error c) GFG d) None of theseAns. (c) Explanation: Access modifiers associated with methods doesn’t determine the criteria for overloading. The overloaded methods could also be declared as final or static without affecting the overloading criteria.4) What is the output of the following program?
Java
public class Test{ private String function(String temp, int data) { return ("GFG"); } private String function(int data, String temp) { return ("GeeksforGeeks"); } public static void main(String[] args) { Test obj = new Test(); System.out.println(obj.function(4, "GFG")); }}
a) GFG b) GeeksforGeeks c) Compilation error d) Runtime errorAns. (b) Explanation: The order of argument are an important parameter for determining method overloading. As the order of attributes are different, the methods are overloaded.5) What is the output of the following program?
Java
public class Test{ private String function(String temp, int data, int sum) { return ("GFG"); } private String function(String temp, int data) { return ("GeeksforGeeks"); } public static void main(String[] args) { Test obj = new Test(); System.out.println(obj.function("GFG", 0, 20)); }}
a) GFG b) Compilation error c) Runtime error d) GeeksforGeeksAns. (a) Explanation: The order of argument are an important parameter for determining method overloading. 6) What is the output of the following program?
Java
public class Test{ private String function(float i, int f) { return ("gfg"); } private String function(double i, double f) { return ("GFG"); } public static void main(String[] args) { Test obj = new Test(); System.out.println(obj.function(1., 20)); }}
a) GFG b) Compilation error c) Runtime error d) GeeksforGeeksAns. (a) Explanation: This one is really simple. Different types of arguments contribute towards method overloading as the signature of methods is changed with different type of attributes. Whichever method matches the set of arguments passed in the main function will be called. Here, the first argument passed is double, and hence GFG is printed.
This article is contributed by Mayank Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
29AjayKumar
rutvikumak
710priyanshu
Java-Output
Java-Overloading
Program Output
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Different ways to copy a string in C/C++
Runtime Errors
unsigned specifier (%u) in C with Examples
Output of C++ Program | Set 1
Output of C Programs | Set 3
How to show full column content in a PySpark Dataframe ?
Output of Java program | Set 26
error: call of overloaded ‘function(x)’ is ambiguous | Ambiguity in Function overloading in C++
Discrete Fourier Transform and its Inverse using MATLAB
Output of python program | Set 2 | [
{
"code": null,
"e": 24480,
"s": 24452,
"text": "\n03 Feb, 2021"
},
{
"code": null,
"e": 24564,
"s": 24480,
"text": "Prerequisite – Overloading in Java1) What is the output of the following program? "
},
{
"code": null,
"e": 24569,
"s": 24564,
"text": "Java"
},
{
"code": "public class Test{ public int getData() //getdata() 1 { return 0; } public long getData() //getdata 2 { return 1; } public static void main(String[] args) { Test obj = new Test(); System.out.println(obj.getData()); }}",
"e": 24845,
"s": 24569,
"text": null
},
{
"code": null,
"e": 25228,
"s": 24845,
"text": "a) 1 b) 0 c) Runtime error d) Compilation errorAns. (d) Explanation: For method overloading, methods must have different signatures. Return type of methods does not contribute towards different method signature, so the code above give compilation error. Both getdata 1 and getdata 2 only differ in return types and NOT signatures. 2) What is the output of the following program? "
},
{
"code": null,
"e": 25233,
"s": 25228,
"text": "Java"
},
{
"code": "public class Test{ public int getData(String temp) throws IOException { return 0; } public int getData(String temp) throws Exception { return 1; } public static void main(String[] args) { Test obj = new Test(); System.out.println(obj.getData(\"GFG\")); }}",
"e": 25545,
"s": 25233,
"text": null
},
{
"code": null,
"e": 25762,
"s": 25545,
"text": "a) 0 b) 1 c) Compilation error d) Runtime errorAns. (c) Explanation: Methods that throws different exceptions are not overloaded as their signature are still the same.3) What is the output of the following program? "
},
{
"code": null,
"e": 25767,
"s": 25762,
"text": "Java"
},
{
"code": "public class Test{ private String function() { return (\"GFG\"); } public final static String function(int data) { return (\"GeeksforGeeks\"); } public static void main(String[] args) { Test obj = new Test(); System.out.println(obj.function()); }}",
"e": 26069,
"s": 25767,
"text": null
},
{
"code": null,
"e": 26399,
"s": 26069,
"text": "a) Compilation error b) Runtime error c) GFG d) None of theseAns. (c) Explanation: Access modifiers associated with methods doesn’t determine the criteria for overloading. The overloaded methods could also be declared as final or static without affecting the overloading criteria.4) What is the output of the following program? "
},
{
"code": null,
"e": 26404,
"s": 26399,
"text": "Java"
},
{
"code": "public class Test{ private String function(String temp, int data) { return (\"GFG\"); } private String function(int data, String temp) { return (\"GeeksforGeeks\"); } public static void main(String[] args) { Test obj = new Test(); System.out.println(obj.function(4, \"GFG\")); }}",
"e": 26736,
"s": 26404,
"text": null
},
{
"code": null,
"e": 27023,
"s": 26736,
"text": "a) GFG b) GeeksforGeeks c) Compilation error d) Runtime errorAns. (b) Explanation: The order of argument are an important parameter for determining method overloading. As the order of attributes are different, the methods are overloaded.5) What is the output of the following program? "
},
{
"code": null,
"e": 27028,
"s": 27023,
"text": "Java"
},
{
"code": "public class Test{ private String function(String temp, int data, int sum) { return (\"GFG\"); } private String function(String temp, int data) { return (\"GeeksforGeeks\"); } public static void main(String[] args) { Test obj = new Test(); System.out.println(obj.function(\"GFG\", 0, 20)); }}",
"e": 27373,
"s": 27028,
"text": null
},
{
"code": null,
"e": 27591,
"s": 27373,
"text": "a) GFG b) Compilation error c) Runtime error d) GeeksforGeeksAns. (a) Explanation: The order of argument are an important parameter for determining method overloading. 6) What is the output of the following program? "
},
{
"code": null,
"e": 27596,
"s": 27591,
"text": "Java"
},
{
"code": "public class Test{ private String function(float i, int f) { return (\"gfg\"); } private String function(double i, double f) { return (\"GFG\"); } public static void main(String[] args) { Test obj = new Test(); System.out.println(obj.function(1., 20)); }}",
"e": 27907,
"s": 27596,
"text": null
},
{
"code": null,
"e": 28317,
"s": 27907,
"text": "a) GFG b) Compilation error c) Runtime error d) GeeksforGeeksAns. (a) Explanation: This one is really simple. Different types of arguments contribute towards method overloading as the signature of methods is changed with different type of attributes. Whichever method matches the set of arguments passed in the main function will be called. Here, the first argument passed is double, and hence GFG is printed."
},
{
"code": null,
"e": 28742,
"s": 28317,
"text": "This article is contributed by Mayank Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 28754,
"s": 28742,
"text": "29AjayKumar"
},
{
"code": null,
"e": 28765,
"s": 28754,
"text": "rutvikumak"
},
{
"code": null,
"e": 28778,
"s": 28765,
"text": "710priyanshu"
},
{
"code": null,
"e": 28790,
"s": 28778,
"text": "Java-Output"
},
{
"code": null,
"e": 28807,
"s": 28790,
"text": "Java-Overloading"
},
{
"code": null,
"e": 28822,
"s": 28807,
"text": "Program Output"
},
{
"code": null,
"e": 28920,
"s": 28822,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28961,
"s": 28920,
"text": "Different ways to copy a string in C/C++"
},
{
"code": null,
"e": 28976,
"s": 28961,
"text": "Runtime Errors"
},
{
"code": null,
"e": 29019,
"s": 28976,
"text": "unsigned specifier (%u) in C with Examples"
},
{
"code": null,
"e": 29049,
"s": 29019,
"text": "Output of C++ Program | Set 1"
},
{
"code": null,
"e": 29078,
"s": 29049,
"text": "Output of C Programs | Set 3"
},
{
"code": null,
"e": 29135,
"s": 29078,
"text": "How to show full column content in a PySpark Dataframe ?"
},
{
"code": null,
"e": 29167,
"s": 29135,
"text": "Output of Java program | Set 26"
},
{
"code": null,
"e": 29263,
"s": 29167,
"text": "error: call of overloaded ‘function(x)’ is ambiguous | Ambiguity in Function overloading in C++"
},
{
"code": null,
"e": 29319,
"s": 29263,
"text": "Discrete Fourier Transform and its Inverse using MATLAB"
}
] |
Importing 100M+ Records into DynamoDB in Under 30 Minutes | by Paul Singman | Towards Data Science | No longer will anyone suffer while setting up the process of doing a full export of a DynamoDB table to S3.
The same cannot be said, however, for someone looking to import data into a Dynamo table. Particularly a large amount of data and fast.
The need for quick bulk imports can occur when records in a table get corrupted, and the easiest way to fix them is do a full table drop-and-recreate. Or when streaming data into a table, it can be useful to run a nightly batch “true-up” job to correct any intra-day anomalies that may have occurred.
Reducing the time to completion for these types of jobs from over an hour to under a minute gives you more confidence in the state of your data at any given point in time. And it provides a more stable foundation for low-latent applications to be built on top of your data.
Say we have data in an S3 bucket at point A, and we want to move it into a Dynamo table at point B... how do we do this?
Well, the simplest approach is to write a little script that reads the file into a DataFrame object, loops through that object’s rows, and then does a dynamo.Table().batch_writer().put_item() operation to insert items into the table.
Running this script on a 500k row DataFrame results in the following write performance:
As you can see, the number of writes per second (w/s) to the table gets capped at about 650 w/s. Amazon indicates that the true limit of a single-process writing to Dynamo is 1,000 w/s, but due to network and other overhead, the observed value is lower (running locally from my laptop).
For 500,000 records, it takes about 15 minutes to insert all the records into the table. Depending on your use case, this might be acceptable. But for bulk inserts of larger datasets — say 100 million rows(!) — it’s clear that improving the write throughput rate would be helpful.
Can we do better?
To increase write performance it is clear there needs to be more than one process writing to the table. So how do we enable multiple processes to write in parallel?
The most elegant way I’ve found to achieve this is to invoke multiple Lambda Function writer instances simultaneously. Each one picks up a slice of the dataset and writes it to the Dynamo table in parallel.
The way this works is by setting a Lambda function to trigger off an SQS queue. This means that if a message is placed on the queue, the Lambda function will invoke and execute its code — taking the SQS message value as a function input parameter.
To go a step further — if such a Lambda were to contain code like in the simple_dynamo_write.py snippet above, and the message placed on the queue is an S3 filepath pointer to the data we want written, then it should be clear how this data will make it’s way into Dynamo!
Each Lambda instance will write to the table at 750-to-1000 w/s, so once we get multiple going at the same time, we can achieve write speeds much higher!
The trick is to split up and organize the data in such a way that Lambda can process it efficiently without error. There are AWS-imposed limits to how many Lambdas can be invoked simultaneously (1,000), how long a single Lambda invocation can run before it shuts down (15 min), and how many writes per second a single Dynamo table can handle (40,000).
It’s always smart to know the relevant quotas when working with a service, and in general AWS does a good job of documenting and making this information available.
With these limits in mind, it should be clear that with full parallelization we cannot distribute the dataset into more than 1000 SQS messages — otherwise we’ll hit the limit of 1000 simultaneous Lambda invocations.
Each file also can’t be too big, otherwise it’ll take more than 15 minutes for a Lambda to write it to the table (as a reminder, it took nearly 15 minutes to write a 500,000 row file earlier). It would not be good for a Lambda to shut down mid-file, since there would be no way to guarantee all rows get written without re-processing the entire file.
The way to control for all of these factors is to create a maximum of 40 SQS messages composed of comma-separated strings of the data’s S3 filepaths.
For example, if we have 3 files in S3 to write into Dynamo, we could create an SQS message like:
's3://bucket/file1.csv,s3://bucket/file2.csv,s3://bucket/file3.csv'
With this message as an input, what the Lambda does is:
Pop off the last filepath from the input string.Write that file’s data into the Dynamo table.Create a new message on the SQS queue that triggers itself with only the unprocessed files remaining.
Pop off the last filepath from the input string.
Write that file’s data into the Dynamo table.
Create a new message on the SQS queue that triggers itself with only the unprocessed files remaining.
So after writing one file, the new SQS message created will look like the below, and crucially a new instance of the Lambda function will almost immediately invoke to start processing file2.
's3://bucket/file1.csv,s3://bucket/file2.csv'
And once file2 gets processed, a new SQS message gets placed on the queue:
's3://bucket/file1.csv'
And after file1 gets written, no more queue messages are generated, no more Lambdas get invoked, and there’s no more data not in the Dynamo table!
To give a more tangible image of this recursive strategy, here’s an example Lambda function code:
Now, instead of the bounded write capacity metrics graph, you’ll be seeing more exciting visuals like this!
With this architecture, we can achieve writes per second speeds of up to 40k into Dynamo, since up to 40 processes can run in parallel, each writing at 1k rows per second.
Whereas before a 100M row dataset would take 40 hours at 1,000 w/s, at the increased rate we can import the full dataset in just 40 minutes! (As an aside, the 40k max write speed limit on a Dynamo table is simply the AWS default, and can be increased upon request).
In working with Dynamo as the backend for several data-intensive applications, I’ve found it extremely useful to have the ability to refresh the full dataset quickly in this way. In situations where specific rows may have become corrupted or mis-processed, more surgical approaches to fixing the data can be error-prone and time consuming, and are not recommended.
Lastly, there are a couple other factors I didn’t get a chance to cover in the article, like ideal handling of the Dynamo Capacity mode, and how related processes like Dynamo streams are impacted.
If curious about these, ask in the comments below or reach out on Twitter.
Thank you to Ryan Kelly and Michael Petryszyn for inspiration for this article. | [
{
"code": null,
"e": 280,
"s": 172,
"text": "No longer will anyone suffer while setting up the process of doing a full export of a DynamoDB table to S3."
},
{
"code": null,
"e": 416,
"s": 280,
"text": "The same cannot be said, however, for someone looking to import data into a Dynamo table. Particularly a large amount of data and fast."
},
{
"code": null,
"e": 717,
"s": 416,
"text": "The need for quick bulk imports can occur when records in a table get corrupted, and the easiest way to fix them is do a full table drop-and-recreate. Or when streaming data into a table, it can be useful to run a nightly batch “true-up” job to correct any intra-day anomalies that may have occurred."
},
{
"code": null,
"e": 991,
"s": 717,
"text": "Reducing the time to completion for these types of jobs from over an hour to under a minute gives you more confidence in the state of your data at any given point in time. And it provides a more stable foundation for low-latent applications to be built on top of your data."
},
{
"code": null,
"e": 1112,
"s": 991,
"text": "Say we have data in an S3 bucket at point A, and we want to move it into a Dynamo table at point B... how do we do this?"
},
{
"code": null,
"e": 1346,
"s": 1112,
"text": "Well, the simplest approach is to write a little script that reads the file into a DataFrame object, loops through that object’s rows, and then does a dynamo.Table().batch_writer().put_item() operation to insert items into the table."
},
{
"code": null,
"e": 1434,
"s": 1346,
"text": "Running this script on a 500k row DataFrame results in the following write performance:"
},
{
"code": null,
"e": 1721,
"s": 1434,
"text": "As you can see, the number of writes per second (w/s) to the table gets capped at about 650 w/s. Amazon indicates that the true limit of a single-process writing to Dynamo is 1,000 w/s, but due to network and other overhead, the observed value is lower (running locally from my laptop)."
},
{
"code": null,
"e": 2002,
"s": 1721,
"text": "For 500,000 records, it takes about 15 minutes to insert all the records into the table. Depending on your use case, this might be acceptable. But for bulk inserts of larger datasets — say 100 million rows(!) — it’s clear that improving the write throughput rate would be helpful."
},
{
"code": null,
"e": 2020,
"s": 2002,
"text": "Can we do better?"
},
{
"code": null,
"e": 2185,
"s": 2020,
"text": "To increase write performance it is clear there needs to be more than one process writing to the table. So how do we enable multiple processes to write in parallel?"
},
{
"code": null,
"e": 2392,
"s": 2185,
"text": "The most elegant way I’ve found to achieve this is to invoke multiple Lambda Function writer instances simultaneously. Each one picks up a slice of the dataset and writes it to the Dynamo table in parallel."
},
{
"code": null,
"e": 2640,
"s": 2392,
"text": "The way this works is by setting a Lambda function to trigger off an SQS queue. This means that if a message is placed on the queue, the Lambda function will invoke and execute its code — taking the SQS message value as a function input parameter."
},
{
"code": null,
"e": 2912,
"s": 2640,
"text": "To go a step further — if such a Lambda were to contain code like in the simple_dynamo_write.py snippet above, and the message placed on the queue is an S3 filepath pointer to the data we want written, then it should be clear how this data will make it’s way into Dynamo!"
},
{
"code": null,
"e": 3066,
"s": 2912,
"text": "Each Lambda instance will write to the table at 750-to-1000 w/s, so once we get multiple going at the same time, we can achieve write speeds much higher!"
},
{
"code": null,
"e": 3418,
"s": 3066,
"text": "The trick is to split up and organize the data in such a way that Lambda can process it efficiently without error. There are AWS-imposed limits to how many Lambdas can be invoked simultaneously (1,000), how long a single Lambda invocation can run before it shuts down (15 min), and how many writes per second a single Dynamo table can handle (40,000)."
},
{
"code": null,
"e": 3582,
"s": 3418,
"text": "It’s always smart to know the relevant quotas when working with a service, and in general AWS does a good job of documenting and making this information available."
},
{
"code": null,
"e": 3798,
"s": 3582,
"text": "With these limits in mind, it should be clear that with full parallelization we cannot distribute the dataset into more than 1000 SQS messages — otherwise we’ll hit the limit of 1000 simultaneous Lambda invocations."
},
{
"code": null,
"e": 4149,
"s": 3798,
"text": "Each file also can’t be too big, otherwise it’ll take more than 15 minutes for a Lambda to write it to the table (as a reminder, it took nearly 15 minutes to write a 500,000 row file earlier). It would not be good for a Lambda to shut down mid-file, since there would be no way to guarantee all rows get written without re-processing the entire file."
},
{
"code": null,
"e": 4299,
"s": 4149,
"text": "The way to control for all of these factors is to create a maximum of 40 SQS messages composed of comma-separated strings of the data’s S3 filepaths."
},
{
"code": null,
"e": 4396,
"s": 4299,
"text": "For example, if we have 3 files in S3 to write into Dynamo, we could create an SQS message like:"
},
{
"code": null,
"e": 4464,
"s": 4396,
"text": "'s3://bucket/file1.csv,s3://bucket/file2.csv,s3://bucket/file3.csv'"
},
{
"code": null,
"e": 4520,
"s": 4464,
"text": "With this message as an input, what the Lambda does is:"
},
{
"code": null,
"e": 4715,
"s": 4520,
"text": "Pop off the last filepath from the input string.Write that file’s data into the Dynamo table.Create a new message on the SQS queue that triggers itself with only the unprocessed files remaining."
},
{
"code": null,
"e": 4764,
"s": 4715,
"text": "Pop off the last filepath from the input string."
},
{
"code": null,
"e": 4810,
"s": 4764,
"text": "Write that file’s data into the Dynamo table."
},
{
"code": null,
"e": 4912,
"s": 4810,
"text": "Create a new message on the SQS queue that triggers itself with only the unprocessed files remaining."
},
{
"code": null,
"e": 5103,
"s": 4912,
"text": "So after writing one file, the new SQS message created will look like the below, and crucially a new instance of the Lambda function will almost immediately invoke to start processing file2."
},
{
"code": null,
"e": 5149,
"s": 5103,
"text": "'s3://bucket/file1.csv,s3://bucket/file2.csv'"
},
{
"code": null,
"e": 5224,
"s": 5149,
"text": "And once file2 gets processed, a new SQS message gets placed on the queue:"
},
{
"code": null,
"e": 5248,
"s": 5224,
"text": "'s3://bucket/file1.csv'"
},
{
"code": null,
"e": 5395,
"s": 5248,
"text": "And after file1 gets written, no more queue messages are generated, no more Lambdas get invoked, and there’s no more data not in the Dynamo table!"
},
{
"code": null,
"e": 5493,
"s": 5395,
"text": "To give a more tangible image of this recursive strategy, here’s an example Lambda function code:"
},
{
"code": null,
"e": 5601,
"s": 5493,
"text": "Now, instead of the bounded write capacity metrics graph, you’ll be seeing more exciting visuals like this!"
},
{
"code": null,
"e": 5773,
"s": 5601,
"text": "With this architecture, we can achieve writes per second speeds of up to 40k into Dynamo, since up to 40 processes can run in parallel, each writing at 1k rows per second."
},
{
"code": null,
"e": 6039,
"s": 5773,
"text": "Whereas before a 100M row dataset would take 40 hours at 1,000 w/s, at the increased rate we can import the full dataset in just 40 minutes! (As an aside, the 40k max write speed limit on a Dynamo table is simply the AWS default, and can be increased upon request)."
},
{
"code": null,
"e": 6404,
"s": 6039,
"text": "In working with Dynamo as the backend for several data-intensive applications, I’ve found it extremely useful to have the ability to refresh the full dataset quickly in this way. In situations where specific rows may have become corrupted or mis-processed, more surgical approaches to fixing the data can be error-prone and time consuming, and are not recommended."
},
{
"code": null,
"e": 6601,
"s": 6404,
"text": "Lastly, there are a couple other factors I didn’t get a chance to cover in the article, like ideal handling of the Dynamo Capacity mode, and how related processes like Dynamo streams are impacted."
},
{
"code": null,
"e": 6676,
"s": 6601,
"text": "If curious about these, ask in the comments below or reach out on Twitter."
}
] |
Spring Boot EhCache Example | Boot @Cachable @EnableCaching | PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC
EXCEPTIONS
COLLECTIONS
SWING
JDBC
JAVA 8
SPRING
SPRING BOOT
HIBERNATE
PYTHON
PHP
JQUERY
PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
In this tutorial, I am going to show you how to integrate Spring Boot EhCache.
Doc Says: Ehcache is an open source, a standards-based cache that boosts an application performance offloads your database, and simplifies scalability. It’s the most widely-used Java-based cache because it’s robust, proven, full-featured, and integrates with other popular libraries and frameworks like Spring.
A complete example is to read a list of items from the MySQL database initially, and the next subsequent calls should get the data from the EhCache.
spring-boot-starter-2.0.5
spring-boot-starter-jdbc
ehcache 2.9.0
Java 8
Maven
Include ehcache dependency in pom.xml
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache</artifactId>
<version>2.9.0</version>
</dependency>
Including all spring boot and MySQL dependencies.
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.onlinetutorialspoint</groupId>
<artifactId>Springboot_EHCache_Example</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>Springboot_EHCache_Example</name>
<description>Spring Boot EhCache Example</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.5.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-cache</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache</artifactId>
<version>2.9.0</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
Creating application.properties with all database related information, enabling the spring boot actuator endpoints to see the ehcache size details and spring cache declarations.
# Database
server.port=8080
spring.datasource.driver-class-name: com.mysql.jdbc.Driver
spring.datasource.url: jdbc:mysql://localhost:3306/otp
spring.datasource.username: root
spring.datasource.password: 1234
management.endpoints.web.exposure.include=*
spring.cache.cache-names=itemCache
spring.cache.type=ehcache
spring.cache.ehcache.config=classpath:ehcache.xml
Creating an ehcache.xml file containing ehcache configuration. Find more about ehcache configuration here.
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNameSpaceSchemaLocation="ehcache.xsd"
updateCheck="true"
monitoring="autodetect"
dynamicConfig="true">
<diskStore path="java.io.tmpdir"/>
<cache name="itemCache"
maxEntriesLocalHeap="1000"
maxEntriesLocalDisk="1000"
eternal="false"
diskSpoolBufferSizeMB="20"
timeToIdleSeconds="300"
timeToLiveSeconds="600"
memoryStoreEvictionPolicy="LFU"
transactionalMode="off">
<persistence strategy="localTempSwap"/>
</cache>
</ehcache>
Configuring EhCache in Spring boot application: @EnableCaching annotation is used to enabling the caching feature declaratively.
I am creating EhCacheManagerFactory bean by passing the ehcache.xml configuration file.
package com.onlinetutorialspoint.config;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.ehcache.EhCacheCacheManager;
import org.springframework.cache.ehcache.EhCacheManagerFactoryBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
@EnableCaching
@Configuration
public class EHCacheConfig {
@Bean
public CacheManager cacheManager(){
return new EhCacheCacheManager(ehCacheManagerFactory().getObject());
}
@Bean
public EhCacheManagerFactoryBean ehCacheManagerFactory(){
EhCacheManagerFactoryBean ehCacheBean = new EhCacheManagerFactoryBean();
ehCacheBean.setConfigLocation(new ClassPathResource("ehcache.xml"));
ehCacheBean.setShared(true);
return ehCacheBean;
}
}
Creating Item rest controller, responsible for reading data from ItemCache.
package com.onlinetutorialspoint.controller;
import com.onlinetutorialspoint.cache.ItemCache;
import com.onlinetutorialspoint.model.Item;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
@RestController
public class ItemController {
@Autowired
ItemCache itemCache;
@GetMapping("/item/{itemId}")
@ResponseBody
public ResponseEntity<Item> getItem(@PathVariable int itemId) throws Exception{
Item item = itemCache.getItem(itemId);
return new ResponseEntity<Item>(item, HttpStatus.OK);
}
@PutMapping("/updateItem")
@ResponseBody
public ResponseEntity<Item> updateItem(@RequestBody Item item){
if(item != null){
itemCache.updateItem(item);
}
return new ResponseEntity<Item>(item, HttpStatus.OK);
}
@DeleteMapping("/delete/{id}")
@ResponseBody
public ResponseEntity<Void> deleteItem(@PathVariable int id){
itemCache.deleteItem(id);
return new ResponseEntity<Void>(HttpStatus.ACCEPTED);
}
}
Creating ItemCache, responsible for reading items from a database using JdbcTemplate and making the method as @Cachable.
package com.onlinetutorialspoint.cache;
import com.onlinetutorialspoint.model.Item;
import com.onlinetutorialspoint.repo.ItemRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Component;
@Component
public class ItemCache {
@Autowired
ItemRepository itemRepo;
@Cacheable(value="itemCache", key="#id")
public Item getItem(int id) throws Exception{
System.out.println("In ItemCache Component..");
return itemRepo.getItem(id);
}
@CacheEvict(value="itemCache",key = "#id")
public int deleteItem(int id){
System.out.println("In ItemCache Component..");
return itemRepo.deleteItem(id);
}
@CachePut(value="itemCache")
public void updateItem(Item item){
System.out.println("In ItemCache Component..");
itemRepo.updateItem(item);
}
}
@Cachable: Is used to adding the cache behaviour to a method. We can also give the name to it, where the cache results would be saved.
@CacheEvict: Is used to remove the one or more cached values. allEntries=true parameter allows us to remove all entries from the cache.
@CachePut: Is used to update the cached value.
Creating an Item model
package com.onlinetutorialspoint.model;
import java.io.Serializable;
public class Item implements Serializable {
private int id;
private String name;
private String category;
public Item() {
}
public Item(int id, String name, String category) {
this.id = id;
this.name = name;
this.category = category;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
}
Creating Item repository
package com.onlinetutorialspoint.repo;
import com.onlinetutorialspoint.model.Item;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
@Repository
public class ItemRepository {
@Autowired
JdbcTemplate template;
/*Getting a specific item by item id from table*/
public Item getItem(int itemId){
String query = "SELECT * FROM ITEM WHERE ID=?";
return template.queryForObject(query,new Object[]{itemId},new BeanPropertyRowMapper<>(Item.class));
}
/*delete an item from database*/
public int deleteItem(int id){
String query = "DELETE FROM ITEM WHERE ID =?";
int size = template.update(query,id);
return size;
}
/*update an item from database*/
public void updateItem(Item item){
String query = "UPDATE ITEM SET name=?, category=? WHERE id =?";
template.update(query,
new Object[] {
item.getName(),item.getCategory(), Integer.valueOf(item.getId())
});
}
}
Spring Boot main class
package com.onlinetutorialspoint;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SpringbootApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootApplication.class, args);
}
}
> mvn spring-boot:run
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.0.5.RELEASE)
2018-10-02 21:33:34.975 INFO 9448 --- [ main] c.o.SpringbootApplication : Starting SpringbootApplication on DESKTOP-RN4SMHT with PID 9448 (E:\work\Springboo
t_EHCache_Example\target\classes started by Lenovo in E:\work\Springboot_EHCache_Example)
2018-10-02 21:33:34.993 INFO 9448 --- [ main] c.o.SpringbootApplication : No active profile set, falling back to default profiles: default
.........
.........
Accessing Spring Boot actuator endpoint to get the cache size.
We can observe the initial cache size as zero.
Accessing item from DB.
We can observe the log statements flow. For the very first call, the data flow happened from Controller -> ItemCache -> Repository. After fetching the data from the database, it will be stored in the cache so that the next subsequent calls will be fetched from the cache itself.
If we ask the same item 1 again we will get this from the cache, because of this we will see the RestController.. statement in logs like below.
Accessing item 2,
After accessing the item 1 and 2, we can observe the cache growth in the actuator.
Deleting Item 2 from the database.
After successful deletion of Item, the cache automatically gets updated as we used @CacheEvect.
EhCache
Spring Boot Actuator
SpringBoot JDBC Template Example
Happy Learning 🙂
Springboot_EHCache_Example
File size: 89 KB
Downloads: 719
Spring Boot Hazelcast Cache Example
Simple Spring Boot Example
Spring Boot Lazy Loading Beans Example
Spring Boot How to change the Tomcat to Jetty Server
Spring Boot H2 Database + JDBC Template Example
Spring Boot In Memory Basic Authentication Security
Spring Boot RabbitMQ Message Publishing Example
Spring Boot Actuator Database Health Check
Spring Boot JNDI Configuration – External Tomcat
Spring Boot Apache ActiveMq In Memory Example
Spring Boot Redis Cache Example – Redis Server
Spring Boot MongoDB + Spring Data Example
Spring Boot MVC Example Tutorials
Spring Boot JPA Integration Example
Spring Boot Hibernate Integration Example
Spring Boot Hazelcast Cache Example
Simple Spring Boot Example
Spring Boot Lazy Loading Beans Example
Spring Boot How to change the Tomcat to Jetty Server
Spring Boot H2 Database + JDBC Template Example
Spring Boot In Memory Basic Authentication Security
Spring Boot RabbitMQ Message Publishing Example
Spring Boot Actuator Database Health Check
Spring Boot JNDI Configuration – External Tomcat
Spring Boot Apache ActiveMq In Memory Example
Spring Boot Redis Cache Example – Redis Server
Spring Boot MongoDB + Spring Data Example
Spring Boot MVC Example Tutorials
Spring Boot JPA Integration Example
Spring Boot Hibernate Integration Example
satish
May 28, 2019 at 5:22 pm - Reply
Nice post. I also learned actutator in this process
satish
May 28, 2019 at 5:22 pm - Reply
Nice post. I also learned actutator in this process
Nice post. I also learned actutator in this process
Δ
Spring Boot – Hello World
Spring Boot – MVC Example
Spring Boot- Change Context Path
Spring Boot – Change Tomcat Port Number
Spring Boot – Change Tomcat to Jetty Server
Spring Boot – Tomcat session timeout
Spring Boot – Enable Random Port
Spring Boot – Properties File
Spring Boot – Beans Lazy Loading
Spring Boot – Set Favicon image
Spring Boot – Set Custom Banner
Spring Boot – Set Application TimeZone
Spring Boot – Send Mail
Spring Boot – FileUpload Ajax
Spring Boot – Actuator
Spring Boot – Actuator Database Health Check
Spring Boot – Swagger
Spring Boot – Enable CORS
Spring Boot – External Apache ActiveMQ Setup
Spring Boot – Inmemory Apache ActiveMq
Spring Boot – Scheduler Job
Spring Boot – Exception Handling
Spring Boot – Hibernate CRUD
Spring Boot – JPA Integration CRUD
Spring Boot – JPA DataRest CRUD
Spring Boot – JdbcTemplate CRUD
Spring Boot – Multiple Data Sources Config
Spring Boot – JNDI Configuration
Spring Boot – H2 Database CRUD
Spring Boot – MongoDB CRUD
Spring Boot – Redis Data CRUD
Spring Boot – MVC Login Form Validation
Spring Boot – Custom Error Pages
Spring Boot – iText PDF
Spring Boot – Enable SSL (HTTPs)
Spring Boot – Basic Authentication
Spring Boot – In Memory Basic Authentication
Spring Boot – Security MySQL Database Integration
Spring Boot – Redis Cache – Redis Server
Spring Boot – Hazelcast Cache
Spring Boot – EhCache
Spring Boot – Kafka Producer
Spring Boot – Kafka Consumer
Spring Boot – Kafka JSON Message to Kafka Topic
Spring Boot – RabbitMQ Publisher
Spring Boot – RabbitMQ Consumer
Spring Boot – SOAP Consumer
Spring Boot – Soap WebServices
Spring Boot – Batch Csv to Database
Spring Boot – Eureka Server
Spring Boot – MockMvc JUnit
Spring Boot – Docker Deployment | [
{
"code": null,
"e": 158,
"s": 123,
"text": "PROGRAMMINGJava ExamplesC Examples"
},
{
"code": null,
"e": 172,
"s": 158,
"text": "Java Examples"
},
{
"code": null,
"e": 183,
"s": 172,
"text": "C Examples"
},
{
"code": null,
"e": 195,
"s": 183,
"text": "C Tutorials"
},
{
"code": null,
"e": 199,
"s": 195,
"text": "aws"
},
{
"code": null,
"e": 234,
"s": 199,
"text": "JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC"
},
{
"code": null,
"e": 245,
"s": 234,
"text": "EXCEPTIONS"
},
{
"code": null,
"e": 257,
"s": 245,
"text": "COLLECTIONS"
},
{
"code": null,
"e": 263,
"s": 257,
"text": "SWING"
},
{
"code": null,
"e": 268,
"s": 263,
"text": "JDBC"
},
{
"code": null,
"e": 275,
"s": 268,
"text": "JAVA 8"
},
{
"code": null,
"e": 282,
"s": 275,
"text": "SPRING"
},
{
"code": null,
"e": 294,
"s": 282,
"text": "SPRING BOOT"
},
{
"code": null,
"e": 304,
"s": 294,
"text": "HIBERNATE"
},
{
"code": null,
"e": 311,
"s": 304,
"text": "PYTHON"
},
{
"code": null,
"e": 315,
"s": 311,
"text": "PHP"
},
{
"code": null,
"e": 322,
"s": 315,
"text": "JQUERY"
},
{
"code": null,
"e": 357,
"s": 322,
"text": "PROGRAMMINGJava ExamplesC Examples"
},
{
"code": null,
"e": 371,
"s": 357,
"text": "Java Examples"
},
{
"code": null,
"e": 382,
"s": 371,
"text": "C Examples"
},
{
"code": null,
"e": 394,
"s": 382,
"text": "C Tutorials"
},
{
"code": null,
"e": 398,
"s": 394,
"text": "aws"
},
{
"code": null,
"e": 478,
"s": 398,
"text": "In this tutorial, I am going to show you how to integrate Spring Boot EhCache. "
},
{
"code": null,
"e": 789,
"s": 478,
"text": "Doc Says: Ehcache is an open source, a standards-based cache that boosts an application performance offloads your database, and simplifies scalability. It’s the most widely-used Java-based cache because it’s robust, proven, full-featured, and integrates with other popular libraries and frameworks like Spring."
},
{
"code": null,
"e": 938,
"s": 789,
"text": "A complete example is to read a list of items from the MySQL database initially, and the next subsequent calls should get the data from the EhCache."
},
{
"code": null,
"e": 964,
"s": 938,
"text": "spring-boot-starter-2.0.5"
},
{
"code": null,
"e": 989,
"s": 964,
"text": "spring-boot-starter-jdbc"
},
{
"code": null,
"e": 1003,
"s": 989,
"text": "ehcache 2.9.0"
},
{
"code": null,
"e": 1010,
"s": 1003,
"text": "Java 8"
},
{
"code": null,
"e": 1016,
"s": 1010,
"text": "Maven"
},
{
"code": null,
"e": 1054,
"s": 1016,
"text": "Include ehcache dependency in pom.xml"
},
{
"code": null,
"e": 1179,
"s": 1054,
"text": "<dependency>\n <groupId>net.sf.ehcache</groupId>\n <artifactId>ehcache</artifactId>\n <version>2.9.0</version>\n</dependency>"
},
{
"code": null,
"e": 1229,
"s": 1179,
"text": "Including all spring boot and MySQL dependencies."
},
{
"code": null,
"e": 3169,
"s": 1229,
"text": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd\">\n <modelVersion>4.0.0</modelVersion>\n <groupId>com.onlinetutorialspoint</groupId>\n <artifactId>Springboot_EHCache_Example</artifactId>\n <version>0.0.1-SNAPSHOT</version>\n <packaging>jar</packaging>\n <name>Springboot_EHCache_Example</name>\n <description>Spring Boot EhCache Example</description>\n <parent>\n <groupId>org.springframework.boot</groupId>\n <artifactId>spring-boot-starter-parent</artifactId>\n <version>2.0.5.RELEASE</version>\n <relativePath/> <!-- lookup parent from repository -->\n </parent>\n <properties>\n <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>\n <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>\n <java.version>1.8</java.version>\n </properties>\n <dependencies>\n <dependency>\n <groupId>org.springframework.boot</groupId>\n <artifactId>spring-boot-starter-cache</artifactId>\n </dependency>\n <dependency>\n <groupId>org.springframework.boot</groupId>\n <artifactId>spring-boot-starter-web</artifactId>\n </dependency>\n <dependency>\n <groupId>org.springframework.boot</groupId>\n <artifactId>spring-boot-starter-jdbc</artifactId>\n </dependency>\n <dependency>\n <groupId>net.sf.ehcache</groupId>\n <artifactId>ehcache</artifactId>\n <version>2.9.0</version>\n </dependency>\n <dependency>\n <groupId>mysql</groupId>\n <artifactId>mysql-connector-java</artifactId>\n <scope>runtime</scope>\n </dependency>\n </dependencies>\n <build>\n <plugins>\n <plugin>\n <groupId>org.springframework.boot</groupId>\n <artifactId>spring-boot-maven-plugin</artifactId>\n </plugin>\n </plugins>\n </build>\n</project>"
},
{
"code": null,
"e": 3347,
"s": 3169,
"text": "Creating application.properties with all database related information, enabling the spring boot actuator endpoints to see the ehcache size details and spring cache declarations."
},
{
"code": null,
"e": 3711,
"s": 3347,
"text": "# Database\nserver.port=8080\nspring.datasource.driver-class-name: com.mysql.jdbc.Driver\nspring.datasource.url: jdbc:mysql://localhost:3306/otp\nspring.datasource.username: root\nspring.datasource.password: 1234\n\nmanagement.endpoints.web.exposure.include=*\nspring.cache.cache-names=itemCache\nspring.cache.type=ehcache\nspring.cache.ehcache.config=classpath:ehcache.xml"
},
{
"code": null,
"e": 3819,
"s": 3711,
"text": "Creating an ehcache.xml file containing ehcache configuration. Find more about ehcache configuration here."
},
{
"code": null,
"e": 4465,
"s": 3819,
"text": "<ehcache xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:noNameSpaceSchemaLocation=\"ehcache.xsd\"\n updateCheck=\"true\"\n monitoring=\"autodetect\"\n dynamicConfig=\"true\">\n <diskStore path=\"java.io.tmpdir\"/>\n <cache name=\"itemCache\"\n maxEntriesLocalHeap=\"1000\"\n maxEntriesLocalDisk=\"1000\"\n eternal=\"false\"\n diskSpoolBufferSizeMB=\"20\"\n timeToIdleSeconds=\"300\"\n timeToLiveSeconds=\"600\"\n memoryStoreEvictionPolicy=\"LFU\"\n transactionalMode=\"off\">\n <persistence strategy=\"localTempSwap\"/>\n </cache>\n\n</ehcache>"
},
{
"code": null,
"e": 4594,
"s": 4465,
"text": "Configuring EhCache in Spring boot application: @EnableCaching annotation is used to enabling the caching feature declaratively."
},
{
"code": null,
"e": 4682,
"s": 4594,
"text": "I am creating EhCacheManagerFactory bean by passing the ehcache.xml configuration file."
},
{
"code": null,
"e": 5627,
"s": 4682,
"text": "package com.onlinetutorialspoint.config;\n\nimport org.springframework.cache.CacheManager;\nimport org.springframework.cache.annotation.EnableCaching;\nimport org.springframework.cache.ehcache.EhCacheCacheManager;\nimport org.springframework.cache.ehcache.EhCacheManagerFactoryBean;\nimport org.springframework.context.annotation.Bean;\nimport org.springframework.context.annotation.Configuration;\nimport org.springframework.core.io.ClassPathResource;\n\n@EnableCaching\n@Configuration\npublic class EHCacheConfig {\n\n @Bean\n public CacheManager cacheManager(){\n return new EhCacheCacheManager(ehCacheManagerFactory().getObject());\n }\n\n @Bean\n public EhCacheManagerFactoryBean ehCacheManagerFactory(){\n EhCacheManagerFactoryBean ehCacheBean = new EhCacheManagerFactoryBean();\n ehCacheBean.setConfigLocation(new ClassPathResource(\"ehcache.xml\"));\n ehCacheBean.setShared(true);\n return ehCacheBean;\n }\n\n}\n"
},
{
"code": null,
"e": 5703,
"s": 5627,
"text": "Creating Item rest controller, responsible for reading data from ItemCache."
},
{
"code": null,
"e": 6873,
"s": 5703,
"text": "package com.onlinetutorialspoint.controller;\n\nimport com.onlinetutorialspoint.cache.ItemCache;\nimport com.onlinetutorialspoint.model.Item;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.http.HttpStatus;\nimport org.springframework.http.ResponseEntity;\nimport org.springframework.web.bind.annotation.*;\n\n@RestController\npublic class ItemController {\n\n @Autowired\n ItemCache itemCache;\n @GetMapping(\"/item/{itemId}\")\n @ResponseBody\n public ResponseEntity<Item> getItem(@PathVariable int itemId) throws Exception{\n Item item = itemCache.getItem(itemId);\n return new ResponseEntity<Item>(item, HttpStatus.OK);\n }\n\n @PutMapping(\"/updateItem\")\n @ResponseBody\n public ResponseEntity<Item> updateItem(@RequestBody Item item){\n if(item != null){\n itemCache.updateItem(item);\n }\n return new ResponseEntity<Item>(item, HttpStatus.OK);\n }\n\n @DeleteMapping(\"/delete/{id}\")\n @ResponseBody\n public ResponseEntity<Void> deleteItem(@PathVariable int id){\n itemCache.deleteItem(id);\n return new ResponseEntity<Void>(HttpStatus.ACCEPTED);\n }\n}\n"
},
{
"code": null,
"e": 6995,
"s": 6873,
"text": "Creating ItemCache, responsible for reading items from a database using JdbcTemplate and making the method as @Cachable."
},
{
"code": null,
"e": 8045,
"s": 6995,
"text": "package com.onlinetutorialspoint.cache;\n\nimport com.onlinetutorialspoint.model.Item;\nimport com.onlinetutorialspoint.repo.ItemRepository;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.cache.annotation.CacheEvict;\nimport org.springframework.cache.annotation.CachePut;\nimport org.springframework.cache.annotation.Cacheable;\nimport org.springframework.stereotype.Component;\n\n@Component\npublic class ItemCache {\n\n @Autowired\n ItemRepository itemRepo;\n\n @Cacheable(value=\"itemCache\", key=\"#id\")\n public Item getItem(int id) throws Exception{\n System.out.println(\"In ItemCache Component..\");\n return itemRepo.getItem(id);\n }\n\n @CacheEvict(value=\"itemCache\",key = \"#id\")\n public int deleteItem(int id){\n System.out.println(\"In ItemCache Component..\");\n return itemRepo.deleteItem(id);\n }\n\n @CachePut(value=\"itemCache\")\n public void updateItem(Item item){\n System.out.println(\"In ItemCache Component..\");\n itemRepo.updateItem(item);\n }\n}\n"
},
{
"code": null,
"e": 8363,
"s": 8045,
"text": "@Cachable: Is used to adding the cache behaviour to a method. We can also give the name to it, where the cache results would be saved.\n@CacheEvict: Is used to remove the one or more cached values. allEntries=true parameter allows us to remove all entries from the cache.\n@CachePut: Is used to update the cached value."
},
{
"code": null,
"e": 8386,
"s": 8363,
"text": "Creating an Item model"
},
{
"code": null,
"e": 9146,
"s": 8386,
"text": "package com.onlinetutorialspoint.model;\n\nimport java.io.Serializable;\n\npublic class Item implements Serializable {\n private int id;\n private String name;\n private String category;\n\n public Item() {\n }\n\n public Item(int id, String name, String category) {\n this.id = id;\n this.name = name;\n this.category = category;\n }\n\n public int getId() {\n return id;\n }\n\n public void setId(int id) {\n this.id = id;\n }\n\n public String getName() {\n return name;\n }\n\n public void setName(String name) {\n this.name = name;\n }\n\n public String getCategory() {\n return category;\n }\n\n public void setCategory(String category) {\n this.category = category;\n }\n}\n"
},
{
"code": null,
"e": 9171,
"s": 9146,
"text": "Creating Item repository"
},
{
"code": null,
"e": 10359,
"s": 9171,
"text": "package com.onlinetutorialspoint.repo;\n\nimport com.onlinetutorialspoint.model.Item;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.jdbc.core.BeanPropertyRowMapper;\nimport org.springframework.jdbc.core.JdbcTemplate;\nimport org.springframework.stereotype.Repository;\n\n@Repository\npublic class ItemRepository {\n\n @Autowired\n JdbcTemplate template;\n\n /*Getting a specific item by item id from table*/\n public Item getItem(int itemId){\n String query = \"SELECT * FROM ITEM WHERE ID=?\";\n return template.queryForObject(query,new Object[]{itemId},new BeanPropertyRowMapper<>(Item.class));\n }\n\n /*delete an item from database*/\n public int deleteItem(int id){\n String query = \"DELETE FROM ITEM WHERE ID =?\";\n int size = template.update(query,id);\n return size;\n }\n\n /*update an item from database*/\n public void updateItem(Item item){\n String query = \"UPDATE ITEM SET name=?, category=? WHERE id =?\";\n template.update(query,\n new Object[] {\n item.getName(),item.getCategory(), Integer.valueOf(item.getId())\n });\n }\n\n}\n"
},
{
"code": null,
"e": 10382,
"s": 10359,
"text": "Spring Boot main class"
},
{
"code": null,
"e": 10711,
"s": 10382,
"text": "package com.onlinetutorialspoint;\n\nimport org.springframework.boot.SpringApplication;\nimport org.springframework.boot.autoconfigure.SpringBootApplication;\n\n@SpringBootApplication\npublic class SpringbootApplication {\n\n public static void main(String[] args) {\n SpringApplication.run(SpringbootApplication.class, args);\n }\n}\n"
},
{
"code": null,
"e": 11487,
"s": 10711,
"text": "> mvn spring-boot:run\n\n . ____ _ __ _ _\n /\\\\ / ___'_ __ _ _(_)_ __ __ _ \\ \\ \\ \\\n( ( )\\___ | '_ | '_| | '_ \\/ _` | \\ \\ \\ \\\n \\\\/ ___)| |_)| | | | | || (_| | ) ) ) )\n ' |____| .__|_| |_|_| |_\\__, | / / / /\n =========|_|==============|___/=/_/_/_/\n :: Spring Boot :: (v2.0.5.RELEASE)\n\n2018-10-02 21:33:34.975 INFO 9448 --- [ main] c.o.SpringbootApplication : Starting SpringbootApplication on DESKTOP-RN4SMHT with PID 9448 (E:\\work\\Springboo\nt_EHCache_Example\\target\\classes started by Lenovo in E:\\work\\Springboot_EHCache_Example)\n2018-10-02 21:33:34.993 INFO 9448 --- [ main] c.o.SpringbootApplication : No active profile set, falling back to default profiles: default\n\n.........\n.........\n"
},
{
"code": null,
"e": 11550,
"s": 11487,
"text": "Accessing Spring Boot actuator endpoint to get the cache size."
},
{
"code": null,
"e": 11597,
"s": 11550,
"text": "We can observe the initial cache size as zero."
},
{
"code": null,
"e": 11621,
"s": 11597,
"text": "Accessing item from DB."
},
{
"code": null,
"e": 11901,
"s": 11621,
"text": "We can observe the log statements flow. For the very first call, the data flow happened from Controller -> ItemCache -> Repository. After fetching the data from the database, it will be stored in the cache so that the next subsequent calls will be fetched from the cache itself."
},
{
"code": null,
"e": 12045,
"s": 11901,
"text": "If we ask the same item 1 again we will get this from the cache, because of this we will see the RestController.. statement in logs like below."
},
{
"code": null,
"e": 12065,
"s": 12047,
"text": "Accessing item 2,"
},
{
"code": null,
"e": 12148,
"s": 12065,
"text": "After accessing the item 1 and 2, we can observe the cache growth in the actuator."
},
{
"code": null,
"e": 12183,
"s": 12148,
"text": "Deleting Item 2 from the database."
},
{
"code": null,
"e": 12279,
"s": 12183,
"text": "After successful deletion of Item, the cache automatically gets updated as we used @CacheEvect."
},
{
"code": null,
"e": 12287,
"s": 12279,
"text": "EhCache"
},
{
"code": null,
"e": 12308,
"s": 12287,
"text": "Spring Boot Actuator"
},
{
"code": null,
"e": 12341,
"s": 12308,
"text": "SpringBoot JDBC Template Example"
},
{
"code": null,
"e": 12358,
"s": 12341,
"text": "Happy Learning 🙂"
},
{
"code": null,
"e": 12421,
"s": 12358,
"text": "\n\nSpringboot_EHCache_Example\n\nFile size: 89 KB\nDownloads: 719\n"
},
{
"code": null,
"e": 13065,
"s": 12421,
"text": "\nSpring Boot Hazelcast Cache Example\nSimple Spring Boot Example\nSpring Boot Lazy Loading Beans Example\nSpring Boot How to change the Tomcat to Jetty Server\nSpring Boot H2 Database + JDBC Template Example\nSpring Boot In Memory Basic Authentication Security\nSpring Boot RabbitMQ Message Publishing Example\nSpring Boot Actuator Database Health Check\nSpring Boot JNDI Configuration – External Tomcat\nSpring Boot Apache ActiveMq In Memory Example\nSpring Boot Redis Cache Example – Redis Server\nSpring Boot MongoDB + Spring Data Example\nSpring Boot MVC Example Tutorials\nSpring Boot JPA Integration Example\nSpring Boot Hibernate Integration Example\n"
},
{
"code": null,
"e": 13101,
"s": 13065,
"text": "Spring Boot Hazelcast Cache Example"
},
{
"code": null,
"e": 13128,
"s": 13101,
"text": "Simple Spring Boot Example"
},
{
"code": null,
"e": 13167,
"s": 13128,
"text": "Spring Boot Lazy Loading Beans Example"
},
{
"code": null,
"e": 13220,
"s": 13167,
"text": "Spring Boot How to change the Tomcat to Jetty Server"
},
{
"code": null,
"e": 13268,
"s": 13220,
"text": "Spring Boot H2 Database + JDBC Template Example"
},
{
"code": null,
"e": 13320,
"s": 13268,
"text": "Spring Boot In Memory Basic Authentication Security"
},
{
"code": null,
"e": 13368,
"s": 13320,
"text": "Spring Boot RabbitMQ Message Publishing Example"
},
{
"code": null,
"e": 13411,
"s": 13368,
"text": "Spring Boot Actuator Database Health Check"
},
{
"code": null,
"e": 13460,
"s": 13411,
"text": "Spring Boot JNDI Configuration – External Tomcat"
},
{
"code": null,
"e": 13506,
"s": 13460,
"text": "Spring Boot Apache ActiveMq In Memory Example"
},
{
"code": null,
"e": 13553,
"s": 13506,
"text": "Spring Boot Redis Cache Example – Redis Server"
},
{
"code": null,
"e": 13595,
"s": 13553,
"text": "Spring Boot MongoDB + Spring Data Example"
},
{
"code": null,
"e": 13629,
"s": 13595,
"text": "Spring Boot MVC Example Tutorials"
},
{
"code": null,
"e": 13665,
"s": 13629,
"text": "Spring Boot JPA Integration Example"
},
{
"code": null,
"e": 13707,
"s": 13665,
"text": "Spring Boot Hibernate Integration Example"
},
{
"code": null,
"e": 13811,
"s": 13707,
"text": "\n\n\n\n\n\nsatish\nMay 28, 2019 at 5:22 pm - Reply \n\nNice post. I also learned actutator in this process\n\n\n\n\n"
},
{
"code": null,
"e": 13913,
"s": 13811,
"text": "\n\n\n\n\nsatish\nMay 28, 2019 at 5:22 pm - Reply \n\nNice post. I also learned actutator in this process\n\n\n\n"
},
{
"code": null,
"e": 13965,
"s": 13913,
"text": "Nice post. I also learned actutator in this process"
},
{
"code": null,
"e": 13971,
"s": 13969,
"text": "Δ"
},
{
"code": null,
"e": 13998,
"s": 13971,
"text": " Spring Boot – Hello World"
},
{
"code": null,
"e": 14025,
"s": 13998,
"text": " Spring Boot – MVC Example"
},
{
"code": null,
"e": 14059,
"s": 14025,
"text": " Spring Boot- Change Context Path"
},
{
"code": null,
"e": 14100,
"s": 14059,
"text": " Spring Boot – Change Tomcat Port Number"
},
{
"code": null,
"e": 14145,
"s": 14100,
"text": " Spring Boot – Change Tomcat to Jetty Server"
},
{
"code": null,
"e": 14183,
"s": 14145,
"text": " Spring Boot – Tomcat session timeout"
},
{
"code": null,
"e": 14217,
"s": 14183,
"text": " Spring Boot – Enable Random Port"
},
{
"code": null,
"e": 14248,
"s": 14217,
"text": " Spring Boot – Properties File"
},
{
"code": null,
"e": 14282,
"s": 14248,
"text": " Spring Boot – Beans Lazy Loading"
},
{
"code": null,
"e": 14315,
"s": 14282,
"text": " Spring Boot – Set Favicon image"
},
{
"code": null,
"e": 14348,
"s": 14315,
"text": " Spring Boot – Set Custom Banner"
},
{
"code": null,
"e": 14388,
"s": 14348,
"text": " Spring Boot – Set Application TimeZone"
},
{
"code": null,
"e": 14413,
"s": 14388,
"text": " Spring Boot – Send Mail"
},
{
"code": null,
"e": 14444,
"s": 14413,
"text": " Spring Boot – FileUpload Ajax"
},
{
"code": null,
"e": 14468,
"s": 14444,
"text": " Spring Boot – Actuator"
},
{
"code": null,
"e": 14514,
"s": 14468,
"text": " Spring Boot – Actuator Database Health Check"
},
{
"code": null,
"e": 14537,
"s": 14514,
"text": " Spring Boot – Swagger"
},
{
"code": null,
"e": 14564,
"s": 14537,
"text": " Spring Boot – Enable CORS"
},
{
"code": null,
"e": 14610,
"s": 14564,
"text": " Spring Boot – External Apache ActiveMQ Setup"
},
{
"code": null,
"e": 14650,
"s": 14610,
"text": " Spring Boot – Inmemory Apache ActiveMq"
},
{
"code": null,
"e": 14679,
"s": 14650,
"text": " Spring Boot – Scheduler Job"
},
{
"code": null,
"e": 14713,
"s": 14679,
"text": " Spring Boot – Exception Handling"
},
{
"code": null,
"e": 14743,
"s": 14713,
"text": " Spring Boot – Hibernate CRUD"
},
{
"code": null,
"e": 14779,
"s": 14743,
"text": " Spring Boot – JPA Integration CRUD"
},
{
"code": null,
"e": 14812,
"s": 14779,
"text": " Spring Boot – JPA DataRest CRUD"
},
{
"code": null,
"e": 14845,
"s": 14812,
"text": " Spring Boot – JdbcTemplate CRUD"
},
{
"code": null,
"e": 14889,
"s": 14845,
"text": " Spring Boot – Multiple Data Sources Config"
},
{
"code": null,
"e": 14923,
"s": 14889,
"text": " Spring Boot – JNDI Configuration"
},
{
"code": null,
"e": 14955,
"s": 14923,
"text": " Spring Boot – H2 Database CRUD"
},
{
"code": null,
"e": 14983,
"s": 14955,
"text": " Spring Boot – MongoDB CRUD"
},
{
"code": null,
"e": 15014,
"s": 14983,
"text": " Spring Boot – Redis Data CRUD"
},
{
"code": null,
"e": 15055,
"s": 15014,
"text": " Spring Boot – MVC Login Form Validation"
},
{
"code": null,
"e": 15089,
"s": 15055,
"text": " Spring Boot – Custom Error Pages"
},
{
"code": null,
"e": 15114,
"s": 15089,
"text": " Spring Boot – iText PDF"
},
{
"code": null,
"e": 15148,
"s": 15114,
"text": " Spring Boot – Enable SSL (HTTPs)"
},
{
"code": null,
"e": 15184,
"s": 15148,
"text": " Spring Boot – Basic Authentication"
},
{
"code": null,
"e": 15230,
"s": 15184,
"text": " Spring Boot – In Memory Basic Authentication"
},
{
"code": null,
"e": 15281,
"s": 15230,
"text": " Spring Boot – Security MySQL Database Integration"
},
{
"code": null,
"e": 15323,
"s": 15281,
"text": " Spring Boot – Redis Cache – Redis Server"
},
{
"code": null,
"e": 15354,
"s": 15323,
"text": " Spring Boot – Hazelcast Cache"
},
{
"code": null,
"e": 15377,
"s": 15354,
"text": " Spring Boot – EhCache"
},
{
"code": null,
"e": 15407,
"s": 15377,
"text": " Spring Boot – Kafka Producer"
},
{
"code": null,
"e": 15437,
"s": 15407,
"text": " Spring Boot – Kafka Consumer"
},
{
"code": null,
"e": 15486,
"s": 15437,
"text": " Spring Boot – Kafka JSON Message to Kafka Topic"
},
{
"code": null,
"e": 15520,
"s": 15486,
"text": " Spring Boot – RabbitMQ Publisher"
},
{
"code": null,
"e": 15553,
"s": 15520,
"text": " Spring Boot – RabbitMQ Consumer"
},
{
"code": null,
"e": 15582,
"s": 15553,
"text": " Spring Boot – SOAP Consumer"
},
{
"code": null,
"e": 15614,
"s": 15582,
"text": " Spring Boot – Soap WebServices"
},
{
"code": null,
"e": 15651,
"s": 15614,
"text": " Spring Boot – Batch Csv to Database"
},
{
"code": null,
"e": 15680,
"s": 15651,
"text": " Spring Boot – Eureka Server"
},
{
"code": null,
"e": 15709,
"s": 15680,
"text": " Spring Boot – MockMvc JUnit"
}
] |
How to save Matplotlib 3d rotating plots? | To save Matplotlib 3d roatating plots, we can take the following steps −
Set the figure size and adjust the padding between and around the subplots.
Create a new figure or activate an existing figure.
Add an '~.axes.Axes' to the figure as part of a subplot arrangement.
Return a tuple X, Y, Z with a test data set.
Plot a 3D wireframe.
Rotate the axis with an angle.
Redraw the current figure.
Run the GUI event loop for some seconds.
To display the figure, use show() method.
from mpl_toolkits.mplot3d import axes3d
import matplotlib.pyplot as plt
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
X, Y, Z = axes3d.get_test_data(0.1)
ax.plot_wireframe(X, Y, Z, rstride=5, cstride=5)
for angle in range(0, 360):
ax.view_init(30, angle)
plt.draw()
plt.pause(.001)
plt.show() | [
{
"code": null,
"e": 1135,
"s": 1062,
"text": "To save Matplotlib 3d roatating plots, we can take the following steps −"
},
{
"code": null,
"e": 1211,
"s": 1135,
"text": "Set the figure size and adjust the padding between and around the subplots."
},
{
"code": null,
"e": 1263,
"s": 1211,
"text": "Create a new figure or activate an existing figure."
},
{
"code": null,
"e": 1332,
"s": 1263,
"text": "Add an '~.axes.Axes' to the figure as part of a subplot arrangement."
},
{
"code": null,
"e": 1377,
"s": 1332,
"text": "Return a tuple X, Y, Z with a test data set."
},
{
"code": null,
"e": 1398,
"s": 1377,
"text": "Plot a 3D wireframe."
},
{
"code": null,
"e": 1429,
"s": 1398,
"text": "Rotate the axis with an angle."
},
{
"code": null,
"e": 1456,
"s": 1429,
"text": "Redraw the current figure."
},
{
"code": null,
"e": 1497,
"s": 1456,
"text": "Run the GUI event loop for some seconds."
},
{
"code": null,
"e": 1539,
"s": 1497,
"text": "To display the figure, use show() method."
},
{
"code": null,
"e": 1948,
"s": 1539,
"text": "from mpl_toolkits.mplot3d import axes3d\nimport matplotlib.pyplot as plt\n\nplt.rcParams[\"figure.figsize\"] = [7.50, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\n\nfig = plt.figure()\nax = fig.add_subplot(111, projection='3d')\nX, Y, Z = axes3d.get_test_data(0.1)\nax.plot_wireframe(X, Y, Z, rstride=5, cstride=5)\n\nfor angle in range(0, 360):\n ax.view_init(30, angle)\n plt.draw()\n plt.pause(.001)\n\nplt.show()"
}
] |
distinct() vs dropDuplicates() in Apache Spark | by Giorgos Myrianthous | Towards Data Science | The Spark DataFrame API comes with two functions that can be used in order to remove duplicates from a given DataFrame. These are distinct() and dropDuplicates() . Even though both methods pretty much do the same job, they actually come with one difference which is quite important in some use cases.
In this article, we are going to explore how both of these functions work and what their main difference is. Additionally, we will discuss when to use one over the other.
Note that the examples that we’ll use to explore these methods have been constructed using the Python API. However, they are fairly simple and thus can be used using the Scala API too (even though some links provided will refer to the former API).
distinct()
Returns a new DataFrame containing the distinct rows in this DataFrame.
distinct() will return the distinct rows of the DataFrame. As an example consider the following DataFrame
>>> df.show()+---+------+---+ | id| name|age|+---+------+---+| 1|Andrew| 25|| 1|Andrew| 25|| 1|Andrew| 26|| 2| Maria| 30|+---+------+---+
The method take no arguments and thus all columns are taken into account when dropping the duplicates:
>>> df.distinct().show()+---+------+---+| id| name|age|+---+------+---+| 1|Andrew| 26|| 2| Maria| 30|| 1|Andrew| 25|+---+------+---+
Now if you need to consider only a subset of the columns when dropping duplicates, then you first have to make a column selection before calling distinct() as shown below.
>>> df.select(['id', 'name']).distinct().show()+---+------+| id| name|+---+------+| 2| Maria|| 1|Andrew|+---+------+
This means that the returned DataFrame will contain only the subset of the columns that was used to eliminate the duplicates. If that’s the case, then probably distinct() won’t do the trick.
dropDuplicates(subset=None)
Return a new DataFrame with duplicate rows removed, optionally only considering certain columns.
For a static batch DataFrame, it just drops duplicate rows. For a streaming DataFrame, it will keep all data across triggers as intermediate state to drop duplicates rows. You can use withWatermark() to limit how late the duplicate data can be and system will accordingly limit the state. In addition, too late data older than watermark will be dropped to avoid any possibility of duplicates.
drop_duplicates() is an alias for dropDuplicates().
Now dropDuplicates() will drop the duplicates detected over a specified set of columns (if provided) but in contrast to distinct() , it will return all the columns of the original dataframe. For instance, if you want to drop duplicates by considering all the columns you could run the following command
>>> df.dropDuplicates().show()+---+------+---+| id| name|age|+---+------+---+| 1|Andrew| 26|| 2| Maria| 30|| 1|Andrew| 25|+---+------+---+
Therefore, dropDuplicates() is the way to go if you want to drop duplicates over a subset of columns, but at the same time you want to keep all the columns of the original structure.
df.dropDuplicates(['id', 'name']).show()+---+------+---+| id| name|age|+---+------+---+| 2| Maria| 30|| 1|Andrew| 25|+---+------+---+
In this article we explored two useful functions of the Spark DataFrame API, namely the distinct() and dropDuplicates() methods. Both can be used to eliminate duplicated rows of a Spark DataFrame however, their difference is that distinct() takes no arguments at all, while dropDuplicates() can be given a subset of columns to consider when dropping duplicated records.
This means that dropDuplicates() is a more suitable option when one wants to drop duplicates by considering only a subset of the columns but at the same time all the columns of the original DataFrame should be returned. | [
{
"code": null,
"e": 473,
"s": 172,
"text": "The Spark DataFrame API comes with two functions that can be used in order to remove duplicates from a given DataFrame. These are distinct() and dropDuplicates() . Even though both methods pretty much do the same job, they actually come with one difference which is quite important in some use cases."
},
{
"code": null,
"e": 644,
"s": 473,
"text": "In this article, we are going to explore how both of these functions work and what their main difference is. Additionally, we will discuss when to use one over the other."
},
{
"code": null,
"e": 892,
"s": 644,
"text": "Note that the examples that we’ll use to explore these methods have been constructed using the Python API. However, they are fairly simple and thus can be used using the Scala API too (even though some links provided will refer to the former API)."
},
{
"code": null,
"e": 903,
"s": 892,
"text": "distinct()"
},
{
"code": null,
"e": 975,
"s": 903,
"text": "Returns a new DataFrame containing the distinct rows in this DataFrame."
},
{
"code": null,
"e": 1081,
"s": 975,
"text": "distinct() will return the distinct rows of the DataFrame. As an example consider the following DataFrame"
},
{
"code": null,
"e": 1287,
"s": 1081,
"text": ">>> df.show()+---+------+---+ | id| name|age|+---+------+---+| 1|Andrew| 25|| 1|Andrew| 25|| 1|Andrew| 26|| 2| Maria| 30|+---+------+---+"
},
{
"code": null,
"e": 1390,
"s": 1287,
"text": "The method take no arguments and thus all columns are taken into account when dropping the duplicates:"
},
{
"code": null,
"e": 1527,
"s": 1390,
"text": ">>> df.distinct().show()+---+------+---+| id| name|age|+---+------+---+| 1|Andrew| 26|| 2| Maria| 30|| 1|Andrew| 25|+---+------+---+"
},
{
"code": null,
"e": 1699,
"s": 1527,
"text": "Now if you need to consider only a subset of the columns when dropping duplicates, then you first have to make a column selection before calling distinct() as shown below."
},
{
"code": null,
"e": 1819,
"s": 1699,
"text": ">>> df.select(['id', 'name']).distinct().show()+---+------+| id| name|+---+------+| 2| Maria|| 1|Andrew|+---+------+"
},
{
"code": null,
"e": 2010,
"s": 1819,
"text": "This means that the returned DataFrame will contain only the subset of the columns that was used to eliminate the duplicates. If that’s the case, then probably distinct() won’t do the trick."
},
{
"code": null,
"e": 2038,
"s": 2010,
"text": "dropDuplicates(subset=None)"
},
{
"code": null,
"e": 2135,
"s": 2038,
"text": "Return a new DataFrame with duplicate rows removed, optionally only considering certain columns."
},
{
"code": null,
"e": 2528,
"s": 2135,
"text": "For a static batch DataFrame, it just drops duplicate rows. For a streaming DataFrame, it will keep all data across triggers as intermediate state to drop duplicates rows. You can use withWatermark() to limit how late the duplicate data can be and system will accordingly limit the state. In addition, too late data older than watermark will be dropped to avoid any possibility of duplicates."
},
{
"code": null,
"e": 2580,
"s": 2528,
"text": "drop_duplicates() is an alias for dropDuplicates()."
},
{
"code": null,
"e": 2883,
"s": 2580,
"text": "Now dropDuplicates() will drop the duplicates detected over a specified set of columns (if provided) but in contrast to distinct() , it will return all the columns of the original dataframe. For instance, if you want to drop duplicates by considering all the columns you could run the following command"
},
{
"code": null,
"e": 3026,
"s": 2883,
"text": ">>> df.dropDuplicates().show()+---+------+---+| id| name|age|+---+------+---+| 1|Andrew| 26|| 2| Maria| 30|| 1|Andrew| 25|+---+------+---+"
},
{
"code": null,
"e": 3209,
"s": 3026,
"text": "Therefore, dropDuplicates() is the way to go if you want to drop duplicates over a subset of columns, but at the same time you want to keep all the columns of the original structure."
},
{
"code": null,
"e": 3346,
"s": 3209,
"text": "df.dropDuplicates(['id', 'name']).show()+---+------+---+| id| name|age|+---+------+---+| 2| Maria| 30|| 1|Andrew| 25|+---+------+---+"
},
{
"code": null,
"e": 3716,
"s": 3346,
"text": "In this article we explored two useful functions of the Spark DataFrame API, namely the distinct() and dropDuplicates() methods. Both can be used to eliminate duplicated rows of a Spark DataFrame however, their difference is that distinct() takes no arguments at all, while dropDuplicates() can be given a subset of columns to consider when dropping duplicated records."
}
] |
How to get rid of Java TLE problem - GeeksforGeeks | 23 Mar, 2022
It happens many times that you have written correct Java code with as much optimization as needed according to the constraints. But, you get TLE ????. This happens due to the time taken by Java to take input and write output using Scanner class which is slow as compared to BufferedReader and StringBuffer class. Read in detail about Scanner Class here. Have a look at some tips to get rid of this TLE issue (when your logic is correct obviously)?
Tip 1 : Avoid using Scanner Class and try to use BufferedReader class. Tip 2 : Try to use StringBuffer class in case you have to print large number of data.
Let’s take a problem from GeeksforGeeks practice and solve the TLE issue: Problem : Segregate an Array of 0s, 1s and 2s In short, problem is, given an array of 0s, 1s and 2s. We have to segregate all the 0s in starting of array, all the 1s in mid of the array, and all the 2s in last of the array. Examples:
Input : 1 1 2 0 0 2 1
Output : 0 0 1 1 1 2 2
Approach : Segregate array of 0s, 1s and 2sBelow is the implementation of above Approach :
Java
// Program to segregate the// array of 0s, 1s and 2simport java.util.*;import java.lang.*;import java.io.*;class GFG { public static void main(String[] args) { // Using Scanner class to take input Scanner sc = new Scanner(System.in); // Number of testcase input int t = sc.nextInt(); // Iterating through all the testcases while (t-- > 0) { // Input n, i.e. size of array int n = sc.nextInt(); int arr[] = new int[n]; // Taking input of array elements for (int i = 0; i < n; i++) arr[i] = sc.nextInt(); // Calling function to segregate // input array segregateArr(arr, n); // printing the modified array for (int i = 0; i < n; i++) { System.out.print(arr[i] + " "); } System.out.println(); } sc.close(); } // Function to segregate 0s, 1s and 2s public static void segregateArr(int arr[], int n) { /* low : to keep left index high : to keep right index mid : to get middle element */ int low = 0, high = n - 1, mid = 0; // Iterating through the array and // segregating elements while (mid <= high) { // If element at mid is 0 // move it to left if (arr[mid] == 0) { int temp = arr[low]; arr[low] = arr[mid]; arr[mid] = temp; low++; mid++; } // If element at mid is 1 // nothing to do else if (arr[mid] == 1) { mid++; } // If element at mid is 2 // move it to last else { int temp = arr[mid]; arr[mid] = arr[high]; arr[high] = temp; high--; } } }}
According to our expectations, it should pass all the testcases and get accepted on GeeksforGeeks practice. But, when we submit this code on GeeksforGeeks IDE, it shows TLE.
This signifies that we have exceeded the time limit as expected. Not an issue, let’s use the tips given above.
Use BufferedReader to take input.Use StringBuffer to save and print output.
Use BufferedReader to take input.
Use StringBuffer to save and print output.
Approach : Segregate array of 0s, 1s and 2sBelow is the implementation of Java code for segregating 0s, 1s and 2s
Java
// Java program to segregate// array of 0s, 1s and 2simport java.io.*;import java.util.*; class GFG { // Driver Code public static void main(String[] args) throws IOException { // Using BufferedReader class to take input BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); // taking input of number of testcase int t = Integer.parseInt(br.readLine()); while (t-- > 0) { // n : size of array int n = Integer.parseInt(br.readLine()); // Declaring array int arr[] = new int[n]; // to read multiple integers line String line = br.readLine(); String[] strs = line.trim().split("\\s+"); // array elements input for (int i = 0; i < n; i++) arr[i] = Integer.parseInt(strs[i]); // Calling Functions to segregate Array elements segregateArr(arr, n); // Using string buffer to append each output in a string StringBuffer sb = new StringBuffer(); for (int i = 0; i < n; i++) sb.append(arr[i] + " "); // finally printing the string System.out.println(sb); } br.close(); } // Function to segregate 0s, 1s and 2s public static void segregateArr(int arr[], int n) { /* low : to keep left index high : to keep right index mid : to get middle element */ int low = 0, high = n - 1, mid = 0; // Iterating through the array and // segregating elements while (mid <= high) { // If element at mid is 0 // move it to left if (arr[mid] == 0) { int temp = arr[low]; arr[low] = arr[mid]; arr[mid] = temp; low++; mid++; } // If element at mid is 1 // nothing to do else if (arr[mid] == 1) { mid++; } // If element at mid is 2 // move it to last else { int temp = arr[mid]; arr[mid] = arr[high]; arr[high] = temp; high--; } } }}
Great! You have leveled up. Java TLE issue? Seems pretty much simple :). You may try it now.
patrick.1729
sumitgumber28
simmytarika5
Competitive Programming
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Modulo 10^9+7 (1000000007)
Prefix Sum Array - Implementation and Applications in Competitive Programming
Bits manipulation (Important tactics)
Algorithm Library | C++ Magicians STL Algorithm
Shortest path in a directed graph by Dijkstra’s algorithm
For-each loop in Java
Arrays.sort() in Java with examples
Reverse a string in Java
Initialize an ArrayList in Java
HashMap in Java with Examples | [
{
"code": null,
"e": 24658,
"s": 24630,
"text": "\n23 Mar, 2022"
},
{
"code": null,
"e": 25108,
"s": 24658,
"text": "It happens many times that you have written correct Java code with as much optimization as needed according to the constraints. But, you get TLE ????. This happens due to the time taken by Java to take input and write output using Scanner class which is slow as compared to BufferedReader and StringBuffer class. Read in detail about Scanner Class here. Have a look at some tips to get rid of this TLE issue (when your logic is correct obviously)? "
},
{
"code": null,
"e": 25265,
"s": 25108,
"text": "Tip 1 : Avoid using Scanner Class and try to use BufferedReader class. Tip 2 : Try to use StringBuffer class in case you have to print large number of data."
},
{
"code": null,
"e": 25575,
"s": 25265,
"text": "Let’s take a problem from GeeksforGeeks practice and solve the TLE issue: Problem : Segregate an Array of 0s, 1s and 2s In short, problem is, given an array of 0s, 1s and 2s. We have to segregate all the 0s in starting of array, all the 1s in mid of the array, and all the 2s in last of the array. Examples: "
},
{
"code": null,
"e": 25620,
"s": 25575,
"text": "Input : 1 1 2 0 0 2 1\nOutput : 0 0 1 1 1 2 2"
},
{
"code": null,
"e": 25713,
"s": 25620,
"text": "Approach : Segregate array of 0s, 1s and 2sBelow is the implementation of above Approach : "
},
{
"code": null,
"e": 25718,
"s": 25713,
"text": "Java"
},
{
"code": "// Program to segregate the// array of 0s, 1s and 2simport java.util.*;import java.lang.*;import java.io.*;class GFG { public static void main(String[] args) { // Using Scanner class to take input Scanner sc = new Scanner(System.in); // Number of testcase input int t = sc.nextInt(); // Iterating through all the testcases while (t-- > 0) { // Input n, i.e. size of array int n = sc.nextInt(); int arr[] = new int[n]; // Taking input of array elements for (int i = 0; i < n; i++) arr[i] = sc.nextInt(); // Calling function to segregate // input array segregateArr(arr, n); // printing the modified array for (int i = 0; i < n; i++) { System.out.print(arr[i] + \" \"); } System.out.println(); } sc.close(); } // Function to segregate 0s, 1s and 2s public static void segregateArr(int arr[], int n) { /* low : to keep left index high : to keep right index mid : to get middle element */ int low = 0, high = n - 1, mid = 0; // Iterating through the array and // segregating elements while (mid <= high) { // If element at mid is 0 // move it to left if (arr[mid] == 0) { int temp = arr[low]; arr[low] = arr[mid]; arr[mid] = temp; low++; mid++; } // If element at mid is 1 // nothing to do else if (arr[mid] == 1) { mid++; } // If element at mid is 2 // move it to last else { int temp = arr[mid]; arr[mid] = arr[high]; arr[high] = temp; high--; } } }}",
"e": 27669,
"s": 25718,
"text": null
},
{
"code": null,
"e": 27845,
"s": 27669,
"text": "According to our expectations, it should pass all the testcases and get accepted on GeeksforGeeks practice. But, when we submit this code on GeeksforGeeks IDE, it shows TLE. "
},
{
"code": null,
"e": 27958,
"s": 27845,
"text": "This signifies that we have exceeded the time limit as expected. Not an issue, let’s use the tips given above. "
},
{
"code": null,
"e": 28034,
"s": 27958,
"text": "Use BufferedReader to take input.Use StringBuffer to save and print output."
},
{
"code": null,
"e": 28068,
"s": 28034,
"text": "Use BufferedReader to take input."
},
{
"code": null,
"e": 28111,
"s": 28068,
"text": "Use StringBuffer to save and print output."
},
{
"code": null,
"e": 28227,
"s": 28111,
"text": "Approach : Segregate array of 0s, 1s and 2sBelow is the implementation of Java code for segregating 0s, 1s and 2s "
},
{
"code": null,
"e": 28232,
"s": 28227,
"text": "Java"
},
{
"code": "// Java program to segregate// array of 0s, 1s and 2simport java.io.*;import java.util.*; class GFG { // Driver Code public static void main(String[] args) throws IOException { // Using BufferedReader class to take input BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); // taking input of number of testcase int t = Integer.parseInt(br.readLine()); while (t-- > 0) { // n : size of array int n = Integer.parseInt(br.readLine()); // Declaring array int arr[] = new int[n]; // to read multiple integers line String line = br.readLine(); String[] strs = line.trim().split(\"\\\\s+\"); // array elements input for (int i = 0; i < n; i++) arr[i] = Integer.parseInt(strs[i]); // Calling Functions to segregate Array elements segregateArr(arr, n); // Using string buffer to append each output in a string StringBuffer sb = new StringBuffer(); for (int i = 0; i < n; i++) sb.append(arr[i] + \" \"); // finally printing the string System.out.println(sb); } br.close(); } // Function to segregate 0s, 1s and 2s public static void segregateArr(int arr[], int n) { /* low : to keep left index high : to keep right index mid : to get middle element */ int low = 0, high = n - 1, mid = 0; // Iterating through the array and // segregating elements while (mid <= high) { // If element at mid is 0 // move it to left if (arr[mid] == 0) { int temp = arr[low]; arr[low] = arr[mid]; arr[mid] = temp; low++; mid++; } // If element at mid is 1 // nothing to do else if (arr[mid] == 1) { mid++; } // If element at mid is 2 // move it to last else { int temp = arr[mid]; arr[mid] = arr[high]; arr[high] = temp; high--; } } }}",
"e": 30499,
"s": 28232,
"text": null
},
{
"code": null,
"e": 30593,
"s": 30499,
"text": "Great! You have leveled up. Java TLE issue? Seems pretty much simple :). You may try it now. "
},
{
"code": null,
"e": 30606,
"s": 30593,
"text": "patrick.1729"
},
{
"code": null,
"e": 30620,
"s": 30606,
"text": "sumitgumber28"
},
{
"code": null,
"e": 30633,
"s": 30620,
"text": "simmytarika5"
},
{
"code": null,
"e": 30657,
"s": 30633,
"text": "Competitive Programming"
},
{
"code": null,
"e": 30662,
"s": 30657,
"text": "Java"
},
{
"code": null,
"e": 30667,
"s": 30662,
"text": "Java"
},
{
"code": null,
"e": 30765,
"s": 30667,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30792,
"s": 30765,
"text": "Modulo 10^9+7 (1000000007)"
},
{
"code": null,
"e": 30870,
"s": 30792,
"text": "Prefix Sum Array - Implementation and Applications in Competitive Programming"
},
{
"code": null,
"e": 30908,
"s": 30870,
"text": "Bits manipulation (Important tactics)"
},
{
"code": null,
"e": 30956,
"s": 30908,
"text": "Algorithm Library | C++ Magicians STL Algorithm"
},
{
"code": null,
"e": 31014,
"s": 30956,
"text": "Shortest path in a directed graph by Dijkstra’s algorithm"
},
{
"code": null,
"e": 31036,
"s": 31014,
"text": "For-each loop in Java"
},
{
"code": null,
"e": 31072,
"s": 31036,
"text": "Arrays.sort() in Java with examples"
},
{
"code": null,
"e": 31097,
"s": 31072,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 31129,
"s": 31097,
"text": "Initialize an ArrayList in Java"
}
] |
ReactJS - Controlled Component | Controlled component has to follow a specific process to do form programming. Let us check the step by step process to be followed for a single input element.
Create a form element.
<input type="text" name="username" />
Create a state for input element.
this.state = {
username: ''
}
Add a value attribute and assign the value from state.
<input type="text" name="username" value={this.state.username} />
Add a onChange attribute and assign a handler method.
<input type="text" name="username" value={this.state.username} onChange={this.handleUsernameChange} />
Write the handler method and update the state whenever the event is fired.
handleUsernameChange(e) {
this.setState({
username = e.target.value
});
}
Bind the event handler in the constructor of the component.
this.handleUsernameChange = this.handleUsernameChange.bind(this)
Finally, get the input value using username from this.state during validation and submission.
handleSubmit(e) {
e.preventDefault();
alert(this.state.username);
}
Let us create a simple form to add expense entry using controller component in this chapter.
First, create a new react application, react-form-app using Create React App or Rollup bundler by following instruction in Creating a React application chapter.
Next, open the application in your favorite editor.
In the next step, create src folder under the root directory of the application.
Further to the above process, create components folder under src folder.
Next, create a file, ExpenseForm.css under src folder to style the component.
input[type=text], input[type=number], input[type=date], select {
width: 100%;
padding: 12px 20px;
margin: 8px 0;
display: inline-block;
border: 1px solid #ccc;
border-radius: 4px;
box-sizing: border-box;
}
input[type=submit] {
width: 100%;
background-color: #4CAF50;
color: white;
padding: 14px 20px;
margin: 8px 0;
border: none;
border-radius: 4px;
cursor: pointer;
}
input[type=submit]:hover {
background-color: #45a049;
}
input:focus {
border: 1px solid #d9d5e0;
}
#expenseForm div {
border-radius: 5px;
background-color: #f2f2f2;
padding: 20px;
}
Next, create a file, ExpenseForm.js under src/components folder and start editing.
Next, import React library.
import React from 'react';
Next, import ExpenseForm.css file.
import './ExpenseForm.css'
Next, create a class, ExpenseForm and call constructor with props.
class ExpenseForm extends React.Component {
constructor(props) {
super(props);
}
}
Next, initialize the state of the component.
this.state = {
item: {}
}
Next, create render() method and add a form with input fields to add expense items.
render() {
return (
<div id="expenseForm">
<form>
<label for="name">Title</label>
<input type="text" id="name" name="name" placeholder="Enter expense title" />
<label for="amount">Amount</label>
<input type="number" id="amount" name="amount" placeholder="Enter expense amount" />
<label for="date">Spend Date</label>
<input type="date" id="date" name="date" placeholder="Enter date" />
<label for="category">Category</label>
<select id="category" name="category"
<option value="">Select</option>
<option value="Food">Food</option>
<option value="Entertainment">Entertainment</option>
<option value="Academic">Academic</option>
</select>
<input type="submit" value="Submit" />
</form>
</div>
)
}
Next, create event handler for all the input fields to update the expense detail in the state.
handleNameChange(e) {
this.setState( (state, props) => {
let item = state.item
item.name = e.target.value;
return { item: item }
});
}
handleAmountChange(e) {
this.setState( (state, props) => {
let item = state.item
item.amount = e.target.value;
return { item: item }
});
}
handleDateChange(e) {
this.setState( (state, props) => {
let item = state.item
item.date = e.target.value;
return { item: item }
});
}
handleCategoryChange(e) {
this.setState( (state, props) => {
let item = state.item
item.category = e.target.value;
return { item: item }
});
}
Next, bind the event handler in the constructor.
this.handleNameChange = this.handleNameChange.bind(this);
this.handleAmountChange = this.handleAmountChange.bind(this);
this.handleDateChange = this.handleDateChange.bind(this);
this.handleCategoryChange = this.handleCategoryChange.bind(this);
Next, add an event handler for the submit action.
onSubmit = (e) => {
e.preventDefault();
alert(JSON.stringify(this.state.item));
}
Next, attach the event handlers to the form.
render() {
return (
<div id="expenseForm">
<form onSubmit={(e) => this.onSubmit(e)}>
<label for="name">Title</label>
<input type="text" id="name" name="name" placeholder="Enter expense title"
value={this.state.item.name}
onChange={this.handleNameChange} />
<label for="amount">Amount</label>
<input type="number" id="amount" name="amount" placeholder="Enter expense amount"
value={this.state.item.amount}
onChange={this.handleAmountChange} />
<label for="date">Spend Date</label>
<input type="date" id="date" name="date" placeholder="Enter date"
value={this.state.item.date}
onChange={this.handleDateChange} />
<label for="category">Category</label>
<select id="category" name="category"
value={this.state.item.category}
onChange={this.handleCategoryChange} >
<option value="">Select</option>
<option value="Food">Food</option>
<option value="Entertainment">Entertainment</option>
<option value="Academic">Academic</option>
</select>
<input type="submit" value="Submit" />
</form>
</div>
)
}
Finally, export the component.
export default ExpenseForm
The complete code of the ExpenseForm component is as follows −
import React from 'react';
import './ExpenseForm.css'
class ExpenseForm extends React.Component {
constructor(props) {
super(props);
this.state = {
item: {}
}
this.handleNameChange = this.handleNameChange.bind(this);
this.handleAmountChange = this.handleAmountChange.bind(this);
this.handleDateChange = this.handleDateChange.bind(this);
this.handleCategoryChange = this.handleCategoryChange.bind(this);
}
handleNameChange(e) {
this.setState( (state, props) => {
let item = state.item
item.name = e.target.value;
return { item: item }
});
}
handleAmountChange(e) {
this.setState( (state, props) => {
let item = state.item
item.amount = e.target.value;
return { item: item }
});
}
handleDateChange(e) {
this.setState( (state, props) => {
let item = state.item
item.date = e.target.value;
return { item: item }
});
}
handleCategoryChange(e) {
this.setState( (state, props) => {
let item = state.item
item.category = e.target.value;
return { item: item }
});
}
onSubmit = (e) => {
e.preventDefault();
alert(JSON.stringify(this.state.item));
}
render() {
return (
<div id="expenseForm">
<form onSubmit={(e) => this.onSubmit(e)}>
<label for="name">Title</label>
<input type="text" id="name" name="name" placeholder="Enter expense title"
value={this.state.item.name}
onChange={this.handleNameChange} />
<label for="amount">Amount</label>
<input type="number" id="amount" name="amount" placeholder="Enter expense amount"
value={this.state.item.amount}
onChange={this.handleAmountChange} />
<label for="date">Spend Date</label>
<input type="date" id="date" name="date" placeholder="Enter date"
value={this.state.item.date}
onChange={this.handleDateChange} />
<label for="category">Category</label>
<select id="category" name="category"
value={this.state.item.category}
onChange={this.handleCategoryChange} >
<option value="">Select</option>
<option value="Food">Food</option>
<option value="Entertainment">Entertainment</option>
<option value="Academic">Academic</option>
</select>
<input type="submit" value="Submit" />
</form>
</div>
)
}
}
export default ExpenseForm;
Next, create a file, index.js under the src folder and use ExpenseForm component.
import React from 'react';
import ReactDOM from 'react-dom';
import ExpenseForm from './components/ExpenseForm'
ReactDOM.render(
<React.StrictMode>
<ExpenseForm />
</React.StrictMode>,
document.getElementById('root')
);
Finally, create a public folder under the root folder and create index.html file.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>React App</title>
</head>
<body>
<div id="root"></div>
<script type="text/JavaScript" src="./index.js"></script>
</body>
</html>
Next, serve the application using npm command.
npm start
Next, open the browser and enter http://localhost:3000 in the address bar and press enter.
Finally, enter a sample expense detail and click submit. The submitted data will be collected and showed in a pop-up message box.
20 Lectures
1.5 hours
Anadi Sharma
60 Lectures
4.5 hours
Skillbakerystudios
165 Lectures
13 hours
Paul Carlo Tordecilla
63 Lectures
9.5 hours
TELCOMA Global
17 Lectures
2 hours
Mohd Raqif Warsi
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2192,
"s": 2033,
"text": "Controlled component has to follow a specific process to do form programming. Let us check the step by step process to be followed for a single input element."
},
{
"code": null,
"e": 2215,
"s": 2192,
"text": "Create a form element."
},
{
"code": null,
"e": 2254,
"s": 2215,
"text": "<input type=\"text\" name=\"username\" />\n"
},
{
"code": null,
"e": 2288,
"s": 2254,
"text": "Create a state for input element."
},
{
"code": null,
"e": 2324,
"s": 2288,
"text": "this.state = { \n username: '' \n}\n"
},
{
"code": null,
"e": 2379,
"s": 2324,
"text": "Add a value attribute and assign the value from state."
},
{
"code": null,
"e": 2446,
"s": 2379,
"text": "<input type=\"text\" name=\"username\" value={this.state.username} />\n"
},
{
"code": null,
"e": 2500,
"s": 2446,
"text": "Add a onChange attribute and assign a handler method."
},
{
"code": null,
"e": 2604,
"s": 2500,
"text": "<input type=\"text\" name=\"username\" value={this.state.username} onChange={this.handleUsernameChange} />\n"
},
{
"code": null,
"e": 2679,
"s": 2604,
"text": "Write the handler method and update the state whenever the event is fired."
},
{
"code": null,
"e": 2765,
"s": 2679,
"text": "handleUsernameChange(e) {\n this.setState({\n username = e.target.value\n });\n}"
},
{
"code": null,
"e": 2825,
"s": 2765,
"text": "Bind the event handler in the constructor of the component."
},
{
"code": null,
"e": 2890,
"s": 2825,
"text": "this.handleUsernameChange = this.handleUsernameChange.bind(this)"
},
{
"code": null,
"e": 2984,
"s": 2890,
"text": "Finally, get the input value using username from this.state during validation and submission."
},
{
"code": null,
"e": 3058,
"s": 2984,
"text": "handleSubmit(e) {\n e.preventDefault();\n alert(this.state.username);\n}"
},
{
"code": null,
"e": 3151,
"s": 3058,
"text": "Let us create a simple form to add expense entry using controller component in this chapter."
},
{
"code": null,
"e": 3312,
"s": 3151,
"text": "First, create a new react application, react-form-app using Create React App or Rollup bundler by following instruction in Creating a React application chapter."
},
{
"code": null,
"e": 3364,
"s": 3312,
"text": "Next, open the application in your favorite editor."
},
{
"code": null,
"e": 3445,
"s": 3364,
"text": "In the next step, create src folder under the root directory of the application."
},
{
"code": null,
"e": 3518,
"s": 3445,
"text": "Further to the above process, create components folder under src folder."
},
{
"code": null,
"e": 3596,
"s": 3518,
"text": "Next, create a file, ExpenseForm.css under src folder to style the component."
},
{
"code": null,
"e": 4207,
"s": 3596,
"text": "input[type=text], input[type=number], input[type=date], select {\n width: 100%;\n padding: 12px 20px;\n margin: 8px 0;\n display: inline-block;\n border: 1px solid #ccc;\n border-radius: 4px;\n box-sizing: border-box;\n}\ninput[type=submit] {\n width: 100%;\n background-color: #4CAF50;\n color: white;\n padding: 14px 20px;\n margin: 8px 0;\n border: none;\n border-radius: 4px;\n cursor: pointer;\n}\ninput[type=submit]:hover {\n background-color: #45a049;\n}\ninput:focus {\n border: 1px solid #d9d5e0;\n}\n#expenseForm div {\n border-radius: 5px;\n background-color: #f2f2f2;\n padding: 20px;\n}"
},
{
"code": null,
"e": 4290,
"s": 4207,
"text": "Next, create a file, ExpenseForm.js under src/components folder and start editing."
},
{
"code": null,
"e": 4318,
"s": 4290,
"text": "Next, import React library."
},
{
"code": null,
"e": 4345,
"s": 4318,
"text": "import React from 'react';"
},
{
"code": null,
"e": 4380,
"s": 4345,
"text": "Next, import ExpenseForm.css file."
},
{
"code": null,
"e": 4407,
"s": 4380,
"text": "import './ExpenseForm.css'"
},
{
"code": null,
"e": 4474,
"s": 4407,
"text": "Next, create a class, ExpenseForm and call constructor with props."
},
{
"code": null,
"e": 4569,
"s": 4474,
"text": "class ExpenseForm extends React.Component {\n constructor(props) {\n super(props);\n }\n}"
},
{
"code": null,
"e": 4614,
"s": 4569,
"text": "Next, initialize the state of the component."
},
{
"code": null,
"e": 4645,
"s": 4614,
"text": "this.state = { \n item: {} \n}"
},
{
"code": null,
"e": 4729,
"s": 4645,
"text": "Next, create render() method and add a form with input fields to add expense items."
},
{
"code": null,
"e": 5637,
"s": 4729,
"text": "render() {\n return (\n <div id=\"expenseForm\">\n <form>\n <label for=\"name\">Title</label>\n <input type=\"text\" id=\"name\" name=\"name\" placeholder=\"Enter expense title\" />\n <label for=\"amount\">Amount</label>\n <input type=\"number\" id=\"amount\" name=\"amount\" placeholder=\"Enter expense amount\" />\n <label for=\"date\">Spend Date</label>\n <input type=\"date\" id=\"date\" name=\"date\" placeholder=\"Enter date\" />\n <label for=\"category\">Category</label>\n <select id=\"category\" name=\"category\" \n <option value=\"\">Select</option>\n <option value=\"Food\">Food</option>\n <option value=\"Entertainment\">Entertainment</option>\n <option value=\"Academic\">Academic</option>\n </select>\n <input type=\"submit\" value=\"Submit\" />\n </form>\n </div>\n )\n}"
},
{
"code": null,
"e": 5732,
"s": 5637,
"text": "Next, create event handler for all the input fields to update the expense detail in the state."
},
{
"code": null,
"e": 6380,
"s": 5732,
"text": "handleNameChange(e) {\n this.setState( (state, props) => {\n let item = state.item\n item.name = e.target.value;\n return { item: item }\n });\n}\nhandleAmountChange(e) {\n this.setState( (state, props) => {\n let item = state.item\n item.amount = e.target.value;\n return { item: item }\n });\n}\nhandleDateChange(e) {\n this.setState( (state, props) => {\n let item = state.item\n item.date = e.target.value;\n return { item: item }\n });\n}\nhandleCategoryChange(e) {\n this.setState( (state, props) => {\n let item = state.item\n item.category = e.target.value;\n return { item: item }\n });\n}"
},
{
"code": null,
"e": 6429,
"s": 6380,
"text": "Next, bind the event handler in the constructor."
},
{
"code": null,
"e": 6673,
"s": 6429,
"text": "this.handleNameChange = this.handleNameChange.bind(this);\nthis.handleAmountChange = this.handleAmountChange.bind(this);\nthis.handleDateChange = this.handleDateChange.bind(this);\nthis.handleCategoryChange = this.handleCategoryChange.bind(this);"
},
{
"code": null,
"e": 6723,
"s": 6673,
"text": "Next, add an event handler for the submit action."
},
{
"code": null,
"e": 6811,
"s": 6723,
"text": "onSubmit = (e) => {\n e.preventDefault();\n alert(JSON.stringify(this.state.item));\n}"
},
{
"code": null,
"e": 6856,
"s": 6811,
"text": "Next, attach the event handlers to the form."
},
{
"code": null,
"e": 8186,
"s": 6856,
"text": "render() {\n return (\n <div id=\"expenseForm\">\n <form onSubmit={(e) => this.onSubmit(e)}>\n <label for=\"name\">Title</label>\n <input type=\"text\" id=\"name\" name=\"name\" placeholder=\"Enter expense title\" \n value={this.state.item.name}\n onChange={this.handleNameChange} />\n\n <label for=\"amount\">Amount</label>\n <input type=\"number\" id=\"amount\" name=\"amount\" placeholder=\"Enter expense amount\"\n value={this.state.item.amount}\n onChange={this.handleAmountChange} />\n\n <label for=\"date\">Spend Date</label>\n <input type=\"date\" id=\"date\" name=\"date\" placeholder=\"Enter date\" \n value={this.state.item.date}\n onChange={this.handleDateChange} />\n\n <label for=\"category\">Category</label>\n <select id=\"category\" name=\"category\"\n value={this.state.item.category}\n onChange={this.handleCategoryChange} >\n <option value=\"\">Select</option>\n <option value=\"Food\">Food</option>\n <option value=\"Entertainment\">Entertainment</option>\n <option value=\"Academic\">Academic</option>\n </select>\n\n <input type=\"submit\" value=\"Submit\" />\n </form>\n </div>\n )\n}"
},
{
"code": null,
"e": 8217,
"s": 8186,
"text": "Finally, export the component."
},
{
"code": null,
"e": 8245,
"s": 8217,
"text": "export default ExpenseForm\n"
},
{
"code": null,
"e": 8308,
"s": 8245,
"text": "The complete code of the ExpenseForm component is as follows −"
},
{
"code": null,
"e": 10996,
"s": 8308,
"text": "import React from 'react';\nimport './ExpenseForm.css'\n\nclass ExpenseForm extends React.Component {\n constructor(props) {\n super(props);\n this.state = {\n item: {}\n }\n this.handleNameChange = this.handleNameChange.bind(this);\n this.handleAmountChange = this.handleAmountChange.bind(this);\n this.handleDateChange = this.handleDateChange.bind(this);\n this.handleCategoryChange = this.handleCategoryChange.bind(this);\n }\n handleNameChange(e) {\n this.setState( (state, props) => {\n let item = state.item\n item.name = e.target.value;\n return { item: item }\n });\n }\n handleAmountChange(e) {\n this.setState( (state, props) => {\n let item = state.item\n item.amount = e.target.value;\n return { item: item }\n });\n }\n handleDateChange(e) {\n this.setState( (state, props) => {\n let item = state.item\n item.date = e.target.value;\n return { item: item }\n });\n }\n handleCategoryChange(e) {\n this.setState( (state, props) => {\n let item = state.item\n item.category = e.target.value;\n return { item: item }\n });\n }\n onSubmit = (e) => {\n e.preventDefault();\n alert(JSON.stringify(this.state.item));\n }\n render() {\n return (\n <div id=\"expenseForm\">\n <form onSubmit={(e) => this.onSubmit(e)}>\n <label for=\"name\">Title</label>\n <input type=\"text\" id=\"name\" name=\"name\" placeholder=\"Enter expense title\" \n value={this.state.item.name}\n onChange={this.handleNameChange} />\n\n <label for=\"amount\">Amount</label>\n <input type=\"number\" id=\"amount\" name=\"amount\" placeholder=\"Enter expense amount\"\n value={this.state.item.amount}\n onChange={this.handleAmountChange} />\n\n <label for=\"date\">Spend Date</label>\n <input type=\"date\" id=\"date\" name=\"date\" placeholder=\"Enter date\" \n value={this.state.item.date}\n onChange={this.handleDateChange} />\n\n <label for=\"category\">Category</label>\n <select id=\"category\" name=\"category\"\n value={this.state.item.category}\n onChange={this.handleCategoryChange} >\n <option value=\"\">Select</option>\n <option value=\"Food\">Food</option>\n <option value=\"Entertainment\">Entertainment</option>\n <option value=\"Academic\">Academic</option>\n </select>\n \n <input type=\"submit\" value=\"Submit\" />\n </form>\n </div>\n )\n }\n}\nexport default ExpenseForm;"
},
{
"code": null,
"e": 11078,
"s": 10996,
"text": "Next, create a file, index.js under the src folder and use ExpenseForm component."
},
{
"code": null,
"e": 11314,
"s": 11078,
"text": "import React from 'react';\nimport ReactDOM from 'react-dom';\nimport ExpenseForm from './components/ExpenseForm'\n\nReactDOM.render(\n <React.StrictMode>\n <ExpenseForm />\n </React.StrictMode>,\n document.getElementById('root')\n);"
},
{
"code": null,
"e": 11396,
"s": 11314,
"text": "Finally, create a public folder under the root folder and create index.html file."
},
{
"code": null,
"e": 11631,
"s": 11396,
"text": "<!DOCTYPE html>\n<html lang=\"en\">\n <head>\n <meta charset=\"utf-8\">\n <title>React App</title>\n </head>\n <body>\n <div id=\"root\"></div>\n <script type=\"text/JavaScript\" src=\"./index.js\"></script>\n </body>\n</html>"
},
{
"code": null,
"e": 11678,
"s": 11631,
"text": "Next, serve the application using npm command."
},
{
"code": null,
"e": 11689,
"s": 11678,
"text": "npm start\n"
},
{
"code": null,
"e": 11780,
"s": 11689,
"text": "Next, open the browser and enter http://localhost:3000 in the address bar and press enter."
},
{
"code": null,
"e": 11910,
"s": 11780,
"text": "Finally, enter a sample expense detail and click submit. The submitted data will be collected and showed in a pop-up message box."
},
{
"code": null,
"e": 11945,
"s": 11910,
"text": "\n 20 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 11959,
"s": 11945,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 11994,
"s": 11959,
"text": "\n 60 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 12014,
"s": 11994,
"text": " Skillbakerystudios"
},
{
"code": null,
"e": 12049,
"s": 12014,
"text": "\n 165 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 12072,
"s": 12049,
"text": " Paul Carlo Tordecilla"
},
{
"code": null,
"e": 12107,
"s": 12072,
"text": "\n 63 Lectures \n 9.5 hours \n"
},
{
"code": null,
"e": 12123,
"s": 12107,
"text": " TELCOMA Global"
},
{
"code": null,
"e": 12156,
"s": 12123,
"text": "\n 17 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 12174,
"s": 12156,
"text": " Mohd Raqif Warsi"
},
{
"code": null,
"e": 12181,
"s": 12174,
"text": " Print"
},
{
"code": null,
"e": 12192,
"s": 12181,
"text": " Add Notes"
}
] |