title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
---|---|---|
SortedList with Examples in C#?
|
The SortedList class in C# represents a collection of key/value pairs that are sorted by the keys and are accessible by key and by index.
Following are the properties of the SortedList class −
Following are some of the methods of the Sorted class −
Let us now see some examples −
To get the number of elements contained in the SortedList, the code is as follows −
Live Demo
using System;
using System.Collections;
public class Demo {
public static void Main(String[] args) {
SortedList sortedList = new SortedList();
sortedList.Add("A", "1");
sortedList.Add("B", "2");
sortedList.Add("C", "3");
sortedList.Add("D", "4");
sortedList.Add("E", "5");
sortedList.Add("F", "6");
sortedList.Add("G", "7");
sortedList.Add("H", "8");
sortedList.Add("I", "9");
sortedList.Add("J", "10");
Console.WriteLine("SortedList elements...");
foreach(DictionaryEntry d in sortedList) {
Console.WriteLine("Key = "+d.Key + ", Value = " + d.Value);
}
Console.WriteLine("Count of SortedList key-value pairs = "+sortedList.Count);
sortedList.Clear();
Console.WriteLine("Count of SortedList (updated) = "+sortedList.Count);
}
}
This will produce the following output −
SortedList elements...
Key = A, Value = 1
Key = B, Value = 2
Key = C, Value = 3
Key = D, Value = 4
Key = E, Value = 5
Key = F, Value = 6
Key = G, Value = 7
Key = H, Value = 8
Key = I, Value = 9
Key = J, Value = 10
Count of SortedList key-value pairs = 10
Count of SortedList (updated) = 0
To check if two SortedList objects are equal, the code is as follows −
Live Demo
using System;
using System.Collections;
public class Demo {
public static void Main(String[] args) {
SortedList list1 = new SortedList();
list1.Add("One", 1);
list1.Add("Two ", 2);
list1.Add("Three ", 3);
list1.Add("Four", 4);
list1.Add("Five", 5);
list1.Add("Six", 6);
list1.Add("Seven ", 7);
list1.Add("Eight ", 8);
list1.Add("Nine", 9);
list1.Add("Ten", 10);
Console.WriteLine("SortedList1 elements...");
foreach(DictionaryEntry d in list1) {
Console.WriteLine(d.Key + " " + d.Value);
}
SortedList list2 = new SortedList();
list2.Add("A", "Accessories");
list2.Add("B", "Books");
list2.Add("C", "Smart Wearable Tech");
list2.Add("D", "Home Appliances");
Console.WriteLine("\nSortedList2 elements...");
foreach(DictionaryEntry d in list2) {
Console.WriteLine(d.Key + " " + d.Value);
}
SortedList list3 = new SortedList();
list3 = list2;
Console.WriteLine("\nIs SortedList2 equal to SortedList3? = "+list3.Equals(list2));
}
}
This will produce the following output −
SortedList1 elements...
Eight 8
Five 5
Four 4
Nine 9
One 1
Seven 7
Six 6
Ten 10
Three 3
Two 2
SortedList2 elements...
A Accessories
B Books
C Smart Wearable Tech
D Home Appliances
Is SortedList2 equal to SortedList3? = True
|
[
{
"code": null,
"e": 1200,
"s": 1062,
"text": "The SortedList class in C# represents a collection of key/value pairs that are sorted by the keys and are accessible by key and by index."
},
{
"code": null,
"e": 1255,
"s": 1200,
"text": "Following are the properties of the SortedList class −"
},
{
"code": null,
"e": 1311,
"s": 1255,
"text": "Following are some of the methods of the Sorted class −"
},
{
"code": null,
"e": 1342,
"s": 1311,
"text": "Let us now see some examples −"
},
{
"code": null,
"e": 1426,
"s": 1342,
"text": "To get the number of elements contained in the SortedList, the code is as follows −"
},
{
"code": null,
"e": 1437,
"s": 1426,
"text": " Live Demo"
},
{
"code": null,
"e": 2282,
"s": 1437,
"text": "using System;\nusing System.Collections;\npublic class Demo {\n public static void Main(String[] args) {\n SortedList sortedList = new SortedList();\n sortedList.Add(\"A\", \"1\");\n sortedList.Add(\"B\", \"2\");\n sortedList.Add(\"C\", \"3\");\n sortedList.Add(\"D\", \"4\");\n sortedList.Add(\"E\", \"5\");\n sortedList.Add(\"F\", \"6\");\n sortedList.Add(\"G\", \"7\");\n sortedList.Add(\"H\", \"8\");\n sortedList.Add(\"I\", \"9\");\n sortedList.Add(\"J\", \"10\");\n Console.WriteLine(\"SortedList elements...\");\n foreach(DictionaryEntry d in sortedList) {\n Console.WriteLine(\"Key = \"+d.Key + \", Value = \" + d.Value);\n }\n Console.WriteLine(\"Count of SortedList key-value pairs = \"+sortedList.Count);\n sortedList.Clear();\n Console.WriteLine(\"Count of SortedList (updated) = \"+sortedList.Count);\n }\n}"
},
{
"code": null,
"e": 2323,
"s": 2282,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2612,
"s": 2323,
"text": "SortedList elements...\nKey = A, Value = 1\nKey = B, Value = 2\nKey = C, Value = 3\nKey = D, Value = 4\nKey = E, Value = 5\nKey = F, Value = 6\nKey = G, Value = 7\nKey = H, Value = 8\nKey = I, Value = 9\nKey = J, Value = 10\nCount of SortedList key-value pairs = 10\nCount of SortedList (updated) = 0"
},
{
"code": null,
"e": 2683,
"s": 2612,
"text": "To check if two SortedList objects are equal, the code is as follows −"
},
{
"code": null,
"e": 2694,
"s": 2683,
"text": " Live Demo"
},
{
"code": null,
"e": 3795,
"s": 2694,
"text": "using System;\nusing System.Collections;\npublic class Demo {\n public static void Main(String[] args) {\n SortedList list1 = new SortedList();\n list1.Add(\"One\", 1);\n list1.Add(\"Two \", 2);\n list1.Add(\"Three \", 3);\n list1.Add(\"Four\", 4);\n list1.Add(\"Five\", 5);\n list1.Add(\"Six\", 6);\n list1.Add(\"Seven \", 7);\n list1.Add(\"Eight \", 8);\n list1.Add(\"Nine\", 9);\n list1.Add(\"Ten\", 10);\n Console.WriteLine(\"SortedList1 elements...\");\n foreach(DictionaryEntry d in list1) {\n Console.WriteLine(d.Key + \" \" + d.Value);\n }\n SortedList list2 = new SortedList();\n list2.Add(\"A\", \"Accessories\");\n list2.Add(\"B\", \"Books\");\n list2.Add(\"C\", \"Smart Wearable Tech\");\n list2.Add(\"D\", \"Home Appliances\");\n Console.WriteLine(\"\\nSortedList2 elements...\");\n foreach(DictionaryEntry d in list2) {\n Console.WriteLine(d.Key + \" \" + d.Value);\n }\n SortedList list3 = new SortedList();\n list3 = list2;\n Console.WriteLine(\"\\nIs SortedList2 equal to SortedList3? = \"+list3.Equals(list2));\n }\n}"
},
{
"code": null,
"e": 3836,
"s": 3795,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 4065,
"s": 3836,
"text": "SortedList1 elements...\nEight 8\nFive 5\nFour 4\nNine 9\nOne 1\nSeven 7\nSix 6\nTen 10\nThree 3\nTwo 2\n\nSortedList2 elements...\nA Accessories\nB Books\nC Smart Wearable Tech\nD Home Appliances\nIs SortedList2 equal to SortedList3? = True"
}
] |
Mutex vs Semaphore
|
Mutex and Semaphore both provide synchronization services but they are not the same. Details about both Mutex and Semaphore are given below −
Mutex is a mutual exclusion object that synchronizes access to a resource. It is created with a unique name at the start of a program. The Mutex is a locking mechanism that makes sure only one thread can acquire the Mutex at a time and enter the critical section. This thread only releases the Mutex when it exits the critical section.
This is shown with the help of the following example −
wait (mutex);
.....
Critical Section
.....
signal (mutex);
A Mutex is different than a semaphore as it is a locking mechanism while a semaphore is a signalling mechanism. A binary semaphore can be used as a Mutex but a Mutex can never be used as a semaphore.
A semaphore is a signalling mechanism and a thread that is waiting on a semaphore can be signaled by another thread. This is different than a mutex as the mutex can be signaled only by the thread that called the wait function.
A semaphore uses two atomic operations, wait and signal for process synchronization.
The wait operation decrements the value of its argument S, if it is positive. If S is negative or zero, then no operation is performed.
wait(S)
{
while (S<=0);
S--;
}
The signal operation increments the value of its argument S.
signal(S)
{
S++;
}
There are mainly two types of semaphores i.e. counting semaphores and binary semaphores.
Counting Semaphores are integer value semaphores and have an unrestricted value domain. These semaphores are used to coordinate the resource access, where the semaphore count is the number of available resources.
The binary semaphores are like counting semaphores but their value is restricted to 0 and 1. The wait operation only works when the semaphore is 1 and the signal operation succeeds when semaphore is 0.
|
[
{
"code": null,
"e": 1204,
"s": 1062,
"text": "Mutex and Semaphore both provide synchronization services but they are not the same. Details about both Mutex and Semaphore are given below −"
},
{
"code": null,
"e": 1540,
"s": 1204,
"text": "Mutex is a mutual exclusion object that synchronizes access to a resource. It is created with a unique name at the start of a program. The Mutex is a locking mechanism that makes sure only one thread can acquire the Mutex at a time and enter the critical section. This thread only releases the Mutex when it exits the critical section."
},
{
"code": null,
"e": 1595,
"s": 1540,
"text": "This is shown with the help of the following example −"
},
{
"code": null,
"e": 1654,
"s": 1595,
"text": "wait (mutex);\n.....\nCritical Section\n.....\nsignal (mutex);"
},
{
"code": null,
"e": 1854,
"s": 1654,
"text": "A Mutex is different than a semaphore as it is a locking mechanism while a semaphore is a signalling mechanism. A binary semaphore can be used as a Mutex but a Mutex can never be used as a semaphore."
},
{
"code": null,
"e": 2081,
"s": 1854,
"text": "A semaphore is a signalling mechanism and a thread that is waiting on a semaphore can be signaled by another thread. This is different than a mutex as the mutex can be signaled only by the thread that called the wait function."
},
{
"code": null,
"e": 2166,
"s": 2081,
"text": "A semaphore uses two atomic operations, wait and signal for process synchronization."
},
{
"code": null,
"e": 2302,
"s": 2166,
"text": "The wait operation decrements the value of its argument S, if it is positive. If S is negative or zero, then no operation is performed."
},
{
"code": null,
"e": 2339,
"s": 2302,
"text": "wait(S)\n{\n while (S<=0);\n S--;\n}"
},
{
"code": null,
"e": 2400,
"s": 2339,
"text": "The signal operation increments the value of its argument S."
},
{
"code": null,
"e": 2422,
"s": 2400,
"text": "signal(S)\n{\n S++;\n}"
},
{
"code": null,
"e": 2511,
"s": 2422,
"text": "There are mainly two types of semaphores i.e. counting semaphores and binary semaphores."
},
{
"code": null,
"e": 2724,
"s": 2511,
"text": "Counting Semaphores are integer value semaphores and have an unrestricted value domain. These semaphores are used to coordinate the resource access, where the semaphore count is the number of available resources."
},
{
"code": null,
"e": 2926,
"s": 2724,
"text": "The binary semaphores are like counting semaphores but their value is restricted to 0 and 1. The wait operation only works when the semaphore is 1 and the signal operation succeeds when semaphore is 0."
}
] |
A Practical Guide to Linear Regression | by Destin Gong | Towards Data Science
|
Linear regression is a typical regression algorithm that is responsible for numeric prediction. It is distinct to classification models — such as decision tree, support vector machine or neural network. In a nutshell, a linear regression finds the optimal linear relationship between independent variables and dependent variables, then makes prediction accordingly.
I guess most people have frequently encountered the function y = b0 + b1x in math class. It is basically the form of simple linear regression, where b0 defines the intercept and b1 defines the slope of the line. I will explain more theory behind the algorithm in the section “Model Implementation”, and the aim of this article is to go practical! And if you would like to access the code, please visit my website.
I use Kaggle public dataset “Insurance Premium Prediction” in this exercise. The data includes independent variables: age, sex, bmi, children, smoker, region, and target variable — expenses. Firstly, let’s load the data and have a preliminary examination of the data using df.info()
import pandas as pdimport seaborn as snsimport matplotlib.pyplot as pltfrom pandas.api.types import is_string_dtype, is_numeric_dtypedf = pd.read_csv('../input/insurance-premium-prediction/insurance.csv')df.info()
Key take-away:
categorical variables: sex, smoker, regionnumerical variables: age, bmi, children, expensesno missing data among 1338 records
categorical variables: sex, smoker, region
numerical variables: age, bmi, children, expenses
no missing data among 1338 records
EDA is essential to both investigate the data quality and reveal hidden correlations among variables. In this exercise, I cover three techniques relevant to linear regression. To have a comprehensive view of EDA, check out:
towardsdatascience.com
Visualize the data distribution using histogram for numeric variables and bar chart for categorical variables.
Why do we need univariate analysis?
identify if dataset contains outliers
identify if need data transformation or feature engineering
In this case, we found out that “expenses” follows a power law distribution, which means that log transformation is required as a step of feature engineering step, to convert it to normal distribution.
When thinking of linear regression, the first visualization technique that we can think of is scatterplot. By plotting the target variable against the independent variables using a single line of code sns.pairplot(df), the underlying linear relationship becomes more evident.
Now, how about adding the categorical variable as the legend?
From the scatter plot segmented by smoker vs. non-smoker, we can observe that smokers (in blue color) have distinctively higher medical expenses. It indicates that the feature “smoker” can potentially be a strong predictor of expenses.
Correlation analysis examines the linear correlation between variable pairs. And this is can be achieved by combining corr() function with sns.heatmap() .
Note that this is after the categorical variable encoding (as in “Feature Engineering” section), so that not only numerical variables are shown in the heatmap.
Why do we need correlation analysis?
identify collinearity between independent variables — linear regression assumes no collinearity among independent features, therefore it is essential to drop some features if collinearity exists. In this example, none of the independent variables are highly correlated with another, hence no need of dropping any.
identify independent variables that are strongly correlated with the target — they are the strong predictors. Once again, we can see that “smoker” is correlated with expenses.
EDA brought some insights of what types of feature engineering techniques are suitable for the dataset.
We have found out that target variable — “expenses” is right skewed and follows a power law distribution. Since linear regression assumes linear relationship between input and output variable, it is necessary to use log transformation to “expenses” variable. As shown below, the data tends to be more normally distributed after applying np.log2(). Besides, spoiler alert, this transformation does increase the linear regression model score from 0.76 to 0.78.
Another requirement of machine learning algorithms is to encode categorical variable into numbers. Two common methods are one-hot encoding and label encoding. If you would like to know more about the difference, please check out: “Feature Selection and EDA in Machine Learning”.
Here I compare the implementation of these two and the outcome.
one hot encoding
df = pd.get_dummies(df, columns = cat_list)
label encoding
However both methods result in a model score of 0.78, suggesting that choosing either doesn’t make a significant difference in this sense.
A simple linear regression, y = b0 + b1x, predicts relationship between one independent variable x and one dependent variable y, for instance, the classic height — weight correlation. As more features/independent variables are introduced, it evolves into multiple linear regression y = b0 + b1x1 + b2x2 + ... + bnxn, which cannot be easily plotted using a line in a two dimensional space.
I applied LinearRegression() from scikit-learn to implement the linear regression. I specified normalize = True so that independent variables will be normalized and transformed into same scale. scikit-learn linear regression utilizes Ordinary Least Squares to find the optimal line to fit the data. So that the line, defined by coefficients b0, b1, b2 ... bn, minimizes the residual sum of squares between the observed targets and the predictions (the blue lines in chart)
The implementation is quite straightforward and returns some attributes:
model.coef_: the coefficient values — b1, b2, b3 ... bn
model.intercept_: the constant values — b0
model.score: the determination R squared of the prediction which helps to evaluation model performance (more detail in model evaluation section)
Let’s roughly estimate the feature importance using coefficient value and visualize it. As expected, smoker is the primary predictor of medical expenses.
sns.barplot(x = X_train.columns, y = coef, palette = "GnBu")
Recall that we have log transformed the target variable, therefore don’t forget to used 2**y_pred to revert back to the actual predicted expenses.
Linear regression model can be qualitatively evaluated by visualizing error distribution. There are also quantitative measures such as MAE, MSE, RMSE and R squared.
Firstly, I use histogram to visualize the distribution of error. Ideally, it should somewhat conform to a normal distribution. A non-normal error distribution may indicates that there is non-linear relationship that model failed to pick up, or more data transformations are necessary.
Mean Absolute Error (MAE): the mean of the absolute value of the errors
Mean Squared Error (MSE): the mean of the squared errors
Root Mean Squared Error (RMSE): the square root of the mean of the squared errors
All three methods measures the errors by calculating the difference between predicted values ŷ and actual value y, hence the smaller the better. The main difference is that MSE/RMSE penalized large errors and are differentiable whereas MAE is not differentiable which makes it hard to apply in gradient descent. Compared to MSE, RMSE takes the square root thus maintains the original data scale.
R squared or coefficient of determination is a value between 0 and 1, indicating the amount of variance in actual target variables explained by the model. R squared is defined as 1 — RSS/TSS, 1 minus the ratio between sum of squares of residuals (RSS) and total sum of squares (TSS). Higher R squared means better model performance.
Residual Sum of Squares (RSS)
Total Sum of Squares (TSS)
In this case, a R squared value of 0.78 indicating that the model explains 78% of variation in target variable, which is generally considered as a good rate and not reaching the level of overfitting.
Hope you enjoy my article :). If you would like to read more of my articles on Medium, I would really appreciate your support by signing up Medium membership.
This article provides a practical guide to implement linear regression, walking through the model building lifecycle:
EDA: univariate analysis, scatter plot, correlation analysisFeature Engineering: log transformation, categorical variable encodingModel implementation: scikit learn LinearRegression()Model evaluation: MAE, MSE, RMSE, R Squared
EDA: univariate analysis, scatter plot, correlation analysis
Feature Engineering: log transformation, categorical variable encoding
Model implementation: scikit learn LinearRegression()
Model evaluation: MAE, MSE, RMSE, R Squared
And if you are interested in a Video Guide :)
https://www.youtube.com/watch?v=tMcbmyK6QiM
towardsdatascience.com
towardsdatascience.com
towardsdatascience.com
Originally published at https://www.visual-design.net on September 18th, 2021.
|
[
{
"code": null,
"e": 538,
"s": 172,
"text": "Linear regression is a typical regression algorithm that is responsible for numeric prediction. It is distinct to classification models — such as decision tree, support vector machine or neural network. In a nutshell, a linear regression finds the optimal linear relationship between independent variables and dependent variables, then makes prediction accordingly."
},
{
"code": null,
"e": 952,
"s": 538,
"text": "I guess most people have frequently encountered the function y = b0 + b1x in math class. It is basically the form of simple linear regression, where b0 defines the intercept and b1 defines the slope of the line. I will explain more theory behind the algorithm in the section “Model Implementation”, and the aim of this article is to go practical! And if you would like to access the code, please visit my website."
},
{
"code": null,
"e": 1235,
"s": 952,
"text": "I use Kaggle public dataset “Insurance Premium Prediction” in this exercise. The data includes independent variables: age, sex, bmi, children, smoker, region, and target variable — expenses. Firstly, let’s load the data and have a preliminary examination of the data using df.info()"
},
{
"code": null,
"e": 1449,
"s": 1235,
"text": "import pandas as pdimport seaborn as snsimport matplotlib.pyplot as pltfrom pandas.api.types import is_string_dtype, is_numeric_dtypedf = pd.read_csv('../input/insurance-premium-prediction/insurance.csv')df.info()"
},
{
"code": null,
"e": 1464,
"s": 1449,
"text": "Key take-away:"
},
{
"code": null,
"e": 1590,
"s": 1464,
"text": "categorical variables: sex, smoker, regionnumerical variables: age, bmi, children, expensesno missing data among 1338 records"
},
{
"code": null,
"e": 1633,
"s": 1590,
"text": "categorical variables: sex, smoker, region"
},
{
"code": null,
"e": 1683,
"s": 1633,
"text": "numerical variables: age, bmi, children, expenses"
},
{
"code": null,
"e": 1718,
"s": 1683,
"text": "no missing data among 1338 records"
},
{
"code": null,
"e": 1942,
"s": 1718,
"text": "EDA is essential to both investigate the data quality and reveal hidden correlations among variables. In this exercise, I cover three techniques relevant to linear regression. To have a comprehensive view of EDA, check out:"
},
{
"code": null,
"e": 1965,
"s": 1942,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 2076,
"s": 1965,
"text": "Visualize the data distribution using histogram for numeric variables and bar chart for categorical variables."
},
{
"code": null,
"e": 2112,
"s": 2076,
"text": "Why do we need univariate analysis?"
},
{
"code": null,
"e": 2150,
"s": 2112,
"text": "identify if dataset contains outliers"
},
{
"code": null,
"e": 2210,
"s": 2150,
"text": "identify if need data transformation or feature engineering"
},
{
"code": null,
"e": 2412,
"s": 2210,
"text": "In this case, we found out that “expenses” follows a power law distribution, which means that log transformation is required as a step of feature engineering step, to convert it to normal distribution."
},
{
"code": null,
"e": 2688,
"s": 2412,
"text": "When thinking of linear regression, the first visualization technique that we can think of is scatterplot. By plotting the target variable against the independent variables using a single line of code sns.pairplot(df), the underlying linear relationship becomes more evident."
},
{
"code": null,
"e": 2750,
"s": 2688,
"text": "Now, how about adding the categorical variable as the legend?"
},
{
"code": null,
"e": 2986,
"s": 2750,
"text": "From the scatter plot segmented by smoker vs. non-smoker, we can observe that smokers (in blue color) have distinctively higher medical expenses. It indicates that the feature “smoker” can potentially be a strong predictor of expenses."
},
{
"code": null,
"e": 3141,
"s": 2986,
"text": "Correlation analysis examines the linear correlation between variable pairs. And this is can be achieved by combining corr() function with sns.heatmap() ."
},
{
"code": null,
"e": 3301,
"s": 3141,
"text": "Note that this is after the categorical variable encoding (as in “Feature Engineering” section), so that not only numerical variables are shown in the heatmap."
},
{
"code": null,
"e": 3338,
"s": 3301,
"text": "Why do we need correlation analysis?"
},
{
"code": null,
"e": 3652,
"s": 3338,
"text": "identify collinearity between independent variables — linear regression assumes no collinearity among independent features, therefore it is essential to drop some features if collinearity exists. In this example, none of the independent variables are highly correlated with another, hence no need of dropping any."
},
{
"code": null,
"e": 3828,
"s": 3652,
"text": "identify independent variables that are strongly correlated with the target — they are the strong predictors. Once again, we can see that “smoker” is correlated with expenses."
},
{
"code": null,
"e": 3932,
"s": 3828,
"text": "EDA brought some insights of what types of feature engineering techniques are suitable for the dataset."
},
{
"code": null,
"e": 4391,
"s": 3932,
"text": "We have found out that target variable — “expenses” is right skewed and follows a power law distribution. Since linear regression assumes linear relationship between input and output variable, it is necessary to use log transformation to “expenses” variable. As shown below, the data tends to be more normally distributed after applying np.log2(). Besides, spoiler alert, this transformation does increase the linear regression model score from 0.76 to 0.78."
},
{
"code": null,
"e": 4670,
"s": 4391,
"text": "Another requirement of machine learning algorithms is to encode categorical variable into numbers. Two common methods are one-hot encoding and label encoding. If you would like to know more about the difference, please check out: “Feature Selection and EDA in Machine Learning”."
},
{
"code": null,
"e": 4734,
"s": 4670,
"text": "Here I compare the implementation of these two and the outcome."
},
{
"code": null,
"e": 4751,
"s": 4734,
"text": "one hot encoding"
},
{
"code": null,
"e": 4795,
"s": 4751,
"text": "df = pd.get_dummies(df, columns = cat_list)"
},
{
"code": null,
"e": 4810,
"s": 4795,
"text": "label encoding"
},
{
"code": null,
"e": 4949,
"s": 4810,
"text": "However both methods result in a model score of 0.78, suggesting that choosing either doesn’t make a significant difference in this sense."
},
{
"code": null,
"e": 5338,
"s": 4949,
"text": "A simple linear regression, y = b0 + b1x, predicts relationship between one independent variable x and one dependent variable y, for instance, the classic height — weight correlation. As more features/independent variables are introduced, it evolves into multiple linear regression y = b0 + b1x1 + b2x2 + ... + bnxn, which cannot be easily plotted using a line in a two dimensional space."
},
{
"code": null,
"e": 5811,
"s": 5338,
"text": "I applied LinearRegression() from scikit-learn to implement the linear regression. I specified normalize = True so that independent variables will be normalized and transformed into same scale. scikit-learn linear regression utilizes Ordinary Least Squares to find the optimal line to fit the data. So that the line, defined by coefficients b0, b1, b2 ... bn, minimizes the residual sum of squares between the observed targets and the predictions (the blue lines in chart)"
},
{
"code": null,
"e": 5884,
"s": 5811,
"text": "The implementation is quite straightforward and returns some attributes:"
},
{
"code": null,
"e": 5940,
"s": 5884,
"text": "model.coef_: the coefficient values — b1, b2, b3 ... bn"
},
{
"code": null,
"e": 5983,
"s": 5940,
"text": "model.intercept_: the constant values — b0"
},
{
"code": null,
"e": 6128,
"s": 5983,
"text": "model.score: the determination R squared of the prediction which helps to evaluation model performance (more detail in model evaluation section)"
},
{
"code": null,
"e": 6282,
"s": 6128,
"text": "Let’s roughly estimate the feature importance using coefficient value and visualize it. As expected, smoker is the primary predictor of medical expenses."
},
{
"code": null,
"e": 6343,
"s": 6282,
"text": "sns.barplot(x = X_train.columns, y = coef, palette = \"GnBu\")"
},
{
"code": null,
"e": 6490,
"s": 6343,
"text": "Recall that we have log transformed the target variable, therefore don’t forget to used 2**y_pred to revert back to the actual predicted expenses."
},
{
"code": null,
"e": 6655,
"s": 6490,
"text": "Linear regression model can be qualitatively evaluated by visualizing error distribution. There are also quantitative measures such as MAE, MSE, RMSE and R squared."
},
{
"code": null,
"e": 6940,
"s": 6655,
"text": "Firstly, I use histogram to visualize the distribution of error. Ideally, it should somewhat conform to a normal distribution. A non-normal error distribution may indicates that there is non-linear relationship that model failed to pick up, or more data transformations are necessary."
},
{
"code": null,
"e": 7012,
"s": 6940,
"text": "Mean Absolute Error (MAE): the mean of the absolute value of the errors"
},
{
"code": null,
"e": 7069,
"s": 7012,
"text": "Mean Squared Error (MSE): the mean of the squared errors"
},
{
"code": null,
"e": 7151,
"s": 7069,
"text": "Root Mean Squared Error (RMSE): the square root of the mean of the squared errors"
},
{
"code": null,
"e": 7548,
"s": 7151,
"text": "All three methods measures the errors by calculating the difference between predicted values ŷ and actual value y, hence the smaller the better. The main difference is that MSE/RMSE penalized large errors and are differentiable whereas MAE is not differentiable which makes it hard to apply in gradient descent. Compared to MSE, RMSE takes the square root thus maintains the original data scale."
},
{
"code": null,
"e": 7881,
"s": 7548,
"text": "R squared or coefficient of determination is a value between 0 and 1, indicating the amount of variance in actual target variables explained by the model. R squared is defined as 1 — RSS/TSS, 1 minus the ratio between sum of squares of residuals (RSS) and total sum of squares (TSS). Higher R squared means better model performance."
},
{
"code": null,
"e": 7911,
"s": 7881,
"text": "Residual Sum of Squares (RSS)"
},
{
"code": null,
"e": 7938,
"s": 7911,
"text": "Total Sum of Squares (TSS)"
},
{
"code": null,
"e": 8138,
"s": 7938,
"text": "In this case, a R squared value of 0.78 indicating that the model explains 78% of variation in target variable, which is generally considered as a good rate and not reaching the level of overfitting."
},
{
"code": null,
"e": 8297,
"s": 8138,
"text": "Hope you enjoy my article :). If you would like to read more of my articles on Medium, I would really appreciate your support by signing up Medium membership."
},
{
"code": null,
"e": 8415,
"s": 8297,
"text": "This article provides a practical guide to implement linear regression, walking through the model building lifecycle:"
},
{
"code": null,
"e": 8642,
"s": 8415,
"text": "EDA: univariate analysis, scatter plot, correlation analysisFeature Engineering: log transformation, categorical variable encodingModel implementation: scikit learn LinearRegression()Model evaluation: MAE, MSE, RMSE, R Squared"
},
{
"code": null,
"e": 8703,
"s": 8642,
"text": "EDA: univariate analysis, scatter plot, correlation analysis"
},
{
"code": null,
"e": 8774,
"s": 8703,
"text": "Feature Engineering: log transformation, categorical variable encoding"
},
{
"code": null,
"e": 8828,
"s": 8774,
"text": "Model implementation: scikit learn LinearRegression()"
},
{
"code": null,
"e": 8872,
"s": 8828,
"text": "Model evaluation: MAE, MSE, RMSE, R Squared"
},
{
"code": null,
"e": 8918,
"s": 8872,
"text": "And if you are interested in a Video Guide :)"
},
{
"code": null,
"e": 8962,
"s": 8918,
"text": "https://www.youtube.com/watch?v=tMcbmyK6QiM"
},
{
"code": null,
"e": 8985,
"s": 8962,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 9008,
"s": 8985,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 9031,
"s": 9008,
"text": "towardsdatascience.com"
}
] |
Android Hello World Example | Android Hello World Run on Emulator
|
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, we will see our first Android Hello World application.
Technologies :
Android 6.0 (Marshmallow)
Android SDK 27
Android Studio 3.0.1
Gradle
Open Android studio and create Android Hello World project. Give project name, project location and click on next.
Recommended: How install Android Studio on Windows 10 Operating System.
Select Android API version, I am working on Android 6.0 (Marshmallow) and click on Next.
Select an Empty Activity, Hello World message will appear on this activity.
Give name to selected activity, as this is a main activity, I am giving the name as MainActivity and click on Finish.
Now It will create our first Android Hello World project like below structure.
Manifest: The is the Most Important File in Android as it contains all the Information about the app. It will act as a bridge between the application developer and android system.
Java: It contains all the .java files and classes where you actually code the backend of your app.
Res: This is the folder where it is mainly focused on front end and UI of the app
Drawable: This folder holds images used for the app
Layout: This folder contains layout of the screen.
Values: Colors contains the Hex values of colors used in app.
Strings: It holds strings and app name
Styles: It contains style components of the app.
Drawable: This folder holds images used for the app
Layout: This folder contains layout of the screen.
Values: Colors contains the Hex values of colors used in app.
Strings: It holds strings and app name
Styles: It contains style components of the app.
Gradle Scripts: It provides the components and libraries required for app
MainActivity.java
package onlinetutorialspoint.com.helloworld;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="onlinetutorialspoint.com.helloworld.MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
Run Application :
We can run the Android applications in 2 different modes.
Running on Android Emulator and
Running on Actual Device
Emulator is nothing an Android phone used for debugging and testing android apps. It’s more like an console where you see an output.
To run the application under Emulator mode, first we should configure the emulator.
Click on Run Button which you can see on Top Right of Toolbar, then Deployment Target wizard will open like below.
Create New Virtual Device :
Select any mobile, prefer selecting an 5.5 phone and then click on next.
Now you need to download the androd system image for your emulator, so recommended is select Nougat or Marshmallow the download will be started.(it may take some time)
Click on Finish.
Now select the downloaded version of system image and click next.
Click on Finish to create a new virtual Device
Now when you click on Run again, you can find your newly created Virtual Device.
Select the Device and click OK.
Emulator may take some time to load and after successful gradle build you will see the output like this
Happy Learning 🙂
How to add Android Device to Android Studio
How to Configure Android Studio
Hello World Java Program Example
How to install Android Studio on Windows 10
How to install Android SDK Windows 10 Manual Process
Basic Android Login Form Example
Simple Spring Boot Example
How to Install Git windows 10 Operating System
How to add Android Device to Android Studio
How to Configure Android Studio
Hello World Java Program Example
How to install Android Studio on Windows 10
How to install Android SDK Windows 10 Manual Process
Basic Android Login Form Example
Simple Spring Boot Example
How to Install Git windows 10 Operating System
|
[
{
"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": 471,
"s": 398,
"text": "In this tutorial, we will see our first Android Hello World application."
},
{
"code": null,
"e": 486,
"s": 471,
"text": "Technologies :"
},
{
"code": null,
"e": 512,
"s": 486,
"text": "Android 6.0 (Marshmallow)"
},
{
"code": null,
"e": 527,
"s": 512,
"text": "Android SDK 27"
},
{
"code": null,
"e": 548,
"s": 527,
"text": "Android Studio 3.0.1"
},
{
"code": null,
"e": 555,
"s": 548,
"text": "Gradle"
},
{
"code": null,
"e": 670,
"s": 555,
"text": "Open Android studio and create Android Hello World project. Give project name, project location and click on next."
},
{
"code": null,
"e": 742,
"s": 670,
"text": "Recommended: How install Android Studio on Windows 10 Operating System."
},
{
"code": null,
"e": 831,
"s": 742,
"text": "Select Android API version, I am working on Android 6.0 (Marshmallow) and click on Next."
},
{
"code": null,
"e": 907,
"s": 831,
"text": "Select an Empty Activity, Hello World message will appear on this activity."
},
{
"code": null,
"e": 1025,
"s": 907,
"text": "Give name to selected activity, as this is a main activity, I am giving the name as MainActivity and click on Finish."
},
{
"code": null,
"e": 1104,
"s": 1025,
"text": "Now It will create our first Android Hello World project like below structure."
},
{
"code": null,
"e": 1284,
"s": 1104,
"text": "Manifest: The is the Most Important File in Android as it contains all the Information about the app. It will act as a bridge between the application developer and android system."
},
{
"code": null,
"e": 1383,
"s": 1284,
"text": "Java: It contains all the .java files and classes where you actually code the backend of your app."
},
{
"code": null,
"e": 1465,
"s": 1383,
"text": "Res: This is the folder where it is mainly focused on front end and UI of the app"
},
{
"code": null,
"e": 1721,
"s": 1465,
"text": "\nDrawable: This folder holds images used for the app\nLayout: This folder contains layout of the screen.\nValues: Colors contains the Hex values of colors used in app.\nStrings: It holds strings and app name\nStyles: It contains style components of the app.\n"
},
{
"code": null,
"e": 1774,
"s": 1721,
"text": "Drawable: This folder holds images used for the app"
},
{
"code": null,
"e": 1825,
"s": 1774,
"text": "Layout: This folder contains layout of the screen."
},
{
"code": null,
"e": 1887,
"s": 1825,
"text": "Values: Colors contains the Hex values of colors used in app."
},
{
"code": null,
"e": 1926,
"s": 1887,
"text": "Strings: It holds strings and app name"
},
{
"code": null,
"e": 1975,
"s": 1926,
"text": "Styles: It contains style components of the app."
},
{
"code": null,
"e": 2049,
"s": 1975,
"text": "Gradle Scripts: It provides the components and libraries required for app"
},
{
"code": null,
"e": 2067,
"s": 2049,
"text": "MainActivity.java"
},
{
"code": null,
"e": 2416,
"s": 2067,
"text": "package onlinetutorialspoint.com.helloworld;\n\nimport android.support.v7.app.AppCompatActivity;\nimport android.os.Bundle;\n\npublic class MainActivity extends AppCompatActivity {\n\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n }\n}\n"
},
{
"code": null,
"e": 2434,
"s": 2416,
"text": "activity_main.xml"
},
{
"code": null,
"e": 3239,
"s": 2434,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<android.support.constraint.ConstraintLayout 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 tools:context=\"onlinetutorialspoint.com.helloworld.MainActivity\">\n\n <TextView\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:text=\"Hello World!\"\n app:layout_constraintBottom_toBottomOf=\"parent\"\n app:layout_constraintLeft_toLeftOf=\"parent\"\n app:layout_constraintRight_toRightOf=\"parent\"\n app:layout_constraintTop_toTopOf=\"parent\" />\n\n</android.support.constraint.ConstraintLayout>\n"
},
{
"code": null,
"e": 3257,
"s": 3239,
"text": "Run Application :"
},
{
"code": null,
"e": 3315,
"s": 3257,
"text": "We can run the Android applications in 2 different modes."
},
{
"code": null,
"e": 3347,
"s": 3315,
"text": "Running on Android Emulator and"
},
{
"code": null,
"e": 3372,
"s": 3347,
"text": "Running on Actual Device"
},
{
"code": null,
"e": 3505,
"s": 3372,
"text": "Emulator is nothing an Android phone used for debugging and testing android apps. It’s more like an console where you see an output."
},
{
"code": null,
"e": 3589,
"s": 3505,
"text": "To run the application under Emulator mode, first we should configure the emulator."
},
{
"code": null,
"e": 3704,
"s": 3589,
"text": "Click on Run Button which you can see on Top Right of Toolbar, then Deployment Target wizard will open like below."
},
{
"code": null,
"e": 3732,
"s": 3704,
"text": "Create New Virtual Device :"
},
{
"code": null,
"e": 3805,
"s": 3732,
"text": "Select any mobile, prefer selecting an 5.5 phone and then click on next."
},
{
"code": null,
"e": 3974,
"s": 3805,
"text": "Now you need to download the androd system image for your emulator, so recommended is select Nougat or Marshmallow the download will be started.(it may take some time)"
},
{
"code": null,
"e": 3991,
"s": 3974,
"text": "Click on Finish."
},
{
"code": null,
"e": 4057,
"s": 3991,
"text": "Now select the downloaded version of system image and click next."
},
{
"code": null,
"e": 4104,
"s": 4057,
"text": "Click on Finish to create a new virtual Device"
},
{
"code": null,
"e": 4185,
"s": 4104,
"text": "Now when you click on Run again, you can find your newly created Virtual Device."
},
{
"code": null,
"e": 4217,
"s": 4185,
"text": "Select the Device and click OK."
},
{
"code": null,
"e": 4321,
"s": 4217,
"text": "Emulator may take some time to load and after successful gradle build you will see the output like this"
},
{
"code": null,
"e": 4338,
"s": 4321,
"text": "Happy Learning 🙂"
},
{
"code": null,
"e": 4653,
"s": 4338,
"text": "\nHow to add Android Device to Android Studio\nHow to Configure Android Studio\nHello World Java Program Example\nHow to install Android Studio on Windows 10\nHow to install Android SDK Windows 10 Manual Process\nBasic Android Login Form Example\nSimple Spring Boot Example\nHow to Install Git windows 10 Operating System\n"
},
{
"code": null,
"e": 4697,
"s": 4653,
"text": "How to add Android Device to Android Studio"
},
{
"code": null,
"e": 4729,
"s": 4697,
"text": "How to Configure Android Studio"
},
{
"code": null,
"e": 4762,
"s": 4729,
"text": "Hello World Java Program Example"
},
{
"code": null,
"e": 4806,
"s": 4762,
"text": "How to install Android Studio on Windows 10"
},
{
"code": null,
"e": 4859,
"s": 4806,
"text": "How to install Android SDK Windows 10 Manual Process"
},
{
"code": null,
"e": 4892,
"s": 4859,
"text": "Basic Android Login Form Example"
},
{
"code": null,
"e": 4919,
"s": 4892,
"text": "Simple Spring Boot Example"
}
] |
Count numbers from range whose prime factors are only 2 and 3 - GeeksforGeeks
|
18 Nov, 2021
Given two positive integers L and R, the task is to count the elements from the range [L, R] whose prime factors are only 2 and 3.Examples:
Input: L = 1, R = 10 Output: 6 2 = 2 3 = 3 4 = 2 * 2 6 = 2 * 3 8 = 2 * 2 * 2 9 = 3 * 3Input: L = 100, R = 200 Output: 5
Approach: Start a loop from L to R and for every element num:
While num is divisible by 2, divide it by 2.
While num is divisible by 3, divide it by 3.
If num = 1 then increment the count as num has only 2 and 3 as its prime factors.
Print the count in the end.Below is the implementation of the above approach:
C++
Java
Python3
C#
PHP
Javascript
// C++ program to count the numbers within a range// whose prime factors are only 2 and 3#include <bits/stdc++.h>using namespace std; // Function to count the number within a range// whose prime factors are only 2 and 3int findTwoThreePrime(int l, int r){ // Start with 2 so that 1 doesn't get counted if (l == 1) l++; int count = 0; for (int i = l; i <= r; i++) { int num = i; // While num is divisible by 2, divide it by 2 while (num % 2 == 0) num /= 2; // While num is divisible by 3, divide it by 3 while (num % 3 == 0) num /= 3; // If num got reduced to 1 then it has // only 2 and 3 as prime factors if (num == 1) count++; } return count;} // Driver codeint main(){ int l = 1, r = 10; cout << findTwoThreePrime(l, r); return 0;}
//Java program to count the numbers within a range// whose prime factors are only 2 and 3 import java.io.*; class GFG { // Function to count the number within a range// whose prime factors are only 2 and 3static int findTwoThreePrime(int l, int r){ // Start with 2 so that 1 doesn't get counted if (l == 1) l++; int count = 0; for (int i = l; i <= r; i++) { int num = i; // While num is divisible by 2, divide it by 2 while (num % 2 == 0) num /= 2; // While num is divisible by 3, divide it by 3 while (num % 3 == 0) num /= 3; // If num got reduced to 1 then it has // only 2 and 3 as prime factors if (num == 1) count++; } return count;} // Driver code public static void main (String[] args) { int l = 1, r = 10; System.out.println (findTwoThreePrime(l, r)); }//This code is contributed by ajit }
# Python3 program to count the numbers# within a range whose prime factors# are only 2 and 3 # Function to count the number within# a range whose prime factors are only# 2 and 3def findTwoThreePrime(l, r) : # Start with 2 so that 1 # doesn't get counted if (l == 1) : l += 1 count = 0 for i in range(l, r + 1) : num = i # While num is divisible by 2, # divide it by 2 while (num % 2 == 0) : num //= 2; # While num is divisible by 3, # divide it by 3 while (num % 3 == 0) : num //= 3 # If num got reduced to 1 then it has # only 2 and 3 as prime factors if (num == 1) : count += 1 return count # Driver codeif __name__ == "__main__" : l = 1 r = 10 print(findTwoThreePrime(l, r)) # This code is contributed by Ryuga
// C# program to count the numbers// within a range whose prime factors// are only 2 and 3using System; class GFG{ // Function to count the number// within a range whose prime// factors are only 2 and 3static int findTwoThreePrime(int l, int r){ // Start with 2 so that 1 // doesn't get counted if (l == 1) l++; int count = 0; for (int i = l; i <= r; i++) { int num = i; // While num is divisible by 2, // divide it by 2 while (num % 2 == 0) num /= 2; // While num is divisible by 3, // divide it by 3 while (num % 3 == 0) num /= 3; // If num got reduced to 1 then it // has only 2 and 3 as prime factors if (num == 1) count++; } return count;} // Driver codestatic public void Main (){ int l = 1, r = 10; Console.WriteLine(findTwoThreePrime(l, r));}} // This code is contributed by akt_mit
<?php// PHP program to count the numbers// within a range whose prime factors// are only 2 and 3 // Function to count the number// within a range whose prime// factors are only 2 and 3function findTwoThreePrime($l, $r){ // Start with 2 so that 1 // doesn't get counted if ($l == 1) $l++; $count = 0; for ($i = $l; $i <= $r; $i++) { $num = $i; // While num is divisible by 2, // divide it by 2 while ($num % 2 == 0) $num /= 2; // While num is divisible by 3, // divide it by 3 while ($num % 3 == 0) $num /= 3; // If num got reduced to 1 then it has // only 2 and 3 as prime factors if ($num == 1) $count++; } return $count;} // Driver code$l = 1;$r = 10;echo findTwoThreePrime($l, $r); // This code is contributed by ajit?>
<script> // Javascript program to count the numbers // within a range whose prime factors // are only 2 and 3 // Function to count the number // within a range whose prime // factors are only 2 and 3 function findTwoThreePrime(l, r) { // Start with 2 so that 1 // doesn't get counted if (l == 1) l++; let count = 0; for (let i = l; i <= r; i++) { let num = i; // While num is divisible by 2, // divide it by 2 while (num % 2 == 0) num = parseInt(num / 2, 10); // While num is divisible by 3, // divide it by 3 while (num % 3 == 0) num = parseInt(num / 3, 10); // If num got reduced to 1 then it // has only 2 and 3 as prime factors if (num == 1) count++; } return count; } let l = 1, r = 10; document.write(findTwoThreePrime(l, r)); </script>
Time Complexity: O((r-l)*log2(r-l))
Auxiliary Space: O(1)
jit_t
ankthon
mukesh07
rohitkumarsinghcna
prime-factor
C++ Programs
Competitive Programming
Mathematical
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C++ Program for QuickSort
cin in C++
delete keyword in C++
CSV file management using C++
Shallow Copy and Deep Copy in C++
Competitive Programming - A Complete Guide
Practice for cracking any coding interview
Arrow operator -> in C/C++ with Examples
Top 10 Algorithms and Data Structures for Competitive Programming
Bits manipulation (Important tactics)
|
[
{
"code": null,
"e": 25514,
"s": 25486,
"text": "\n18 Nov, 2021"
},
{
"code": null,
"e": 25656,
"s": 25514,
"text": "Given two positive integers L and R, the task is to count the elements from the range [L, R] whose prime factors are only 2 and 3.Examples: "
},
{
"code": null,
"e": 25778,
"s": 25656,
"text": "Input: L = 1, R = 10 Output: 6 2 = 2 3 = 3 4 = 2 * 2 6 = 2 * 3 8 = 2 * 2 * 2 9 = 3 * 3Input: L = 100, R = 200 Output: 5 "
},
{
"code": null,
"e": 25844,
"s": 25780,
"text": "Approach: Start a loop from L to R and for every element num: "
},
{
"code": null,
"e": 25889,
"s": 25844,
"text": "While num is divisible by 2, divide it by 2."
},
{
"code": null,
"e": 25934,
"s": 25889,
"text": "While num is divisible by 3, divide it by 3."
},
{
"code": null,
"e": 26016,
"s": 25934,
"text": "If num = 1 then increment the count as num has only 2 and 3 as its prime factors."
},
{
"code": null,
"e": 26095,
"s": 26016,
"text": "Print the count in the end.Below is the implementation of the above approach: "
},
{
"code": null,
"e": 26099,
"s": 26095,
"text": "C++"
},
{
"code": null,
"e": 26104,
"s": 26099,
"text": "Java"
},
{
"code": null,
"e": 26112,
"s": 26104,
"text": "Python3"
},
{
"code": null,
"e": 26115,
"s": 26112,
"text": "C#"
},
{
"code": null,
"e": 26119,
"s": 26115,
"text": "PHP"
},
{
"code": null,
"e": 26130,
"s": 26119,
"text": "Javascript"
},
{
"code": "// C++ program to count the numbers within a range// whose prime factors are only 2 and 3#include <bits/stdc++.h>using namespace std; // Function to count the number within a range// whose prime factors are only 2 and 3int findTwoThreePrime(int l, int r){ // Start with 2 so that 1 doesn't get counted if (l == 1) l++; int count = 0; for (int i = l; i <= r; i++) { int num = i; // While num is divisible by 2, divide it by 2 while (num % 2 == 0) num /= 2; // While num is divisible by 3, divide it by 3 while (num % 3 == 0) num /= 3; // If num got reduced to 1 then it has // only 2 and 3 as prime factors if (num == 1) count++; } return count;} // Driver codeint main(){ int l = 1, r = 10; cout << findTwoThreePrime(l, r); return 0;}",
"e": 26994,
"s": 26130,
"text": null
},
{
"code": "//Java program to count the numbers within a range// whose prime factors are only 2 and 3 import java.io.*; class GFG { // Function to count the number within a range// whose prime factors are only 2 and 3static int findTwoThreePrime(int l, int r){ // Start with 2 so that 1 doesn't get counted if (l == 1) l++; int count = 0; for (int i = l; i <= r; i++) { int num = i; // While num is divisible by 2, divide it by 2 while (num % 2 == 0) num /= 2; // While num is divisible by 3, divide it by 3 while (num % 3 == 0) num /= 3; // If num got reduced to 1 then it has // only 2 and 3 as prime factors if (num == 1) count++; } return count;} // Driver code public static void main (String[] args) { int l = 1, r = 10; System.out.println (findTwoThreePrime(l, r)); }//This code is contributed by ajit }",
"e": 27940,
"s": 26994,
"text": null
},
{
"code": "# Python3 program to count the numbers# within a range whose prime factors# are only 2 and 3 # Function to count the number within# a range whose prime factors are only# 2 and 3def findTwoThreePrime(l, r) : # Start with 2 so that 1 # doesn't get counted if (l == 1) : l += 1 count = 0 for i in range(l, r + 1) : num = i # While num is divisible by 2, # divide it by 2 while (num % 2 == 0) : num //= 2; # While num is divisible by 3, # divide it by 3 while (num % 3 == 0) : num //= 3 # If num got reduced to 1 then it has # only 2 and 3 as prime factors if (num == 1) : count += 1 return count # Driver codeif __name__ == \"__main__\" : l = 1 r = 10 print(findTwoThreePrime(l, r)) # This code is contributed by Ryuga",
"e": 28808,
"s": 27940,
"text": null
},
{
"code": "// C# program to count the numbers// within a range whose prime factors// are only 2 and 3using System; class GFG{ // Function to count the number// within a range whose prime// factors are only 2 and 3static int findTwoThreePrime(int l, int r){ // Start with 2 so that 1 // doesn't get counted if (l == 1) l++; int count = 0; for (int i = l; i <= r; i++) { int num = i; // While num is divisible by 2, // divide it by 2 while (num % 2 == 0) num /= 2; // While num is divisible by 3, // divide it by 3 while (num % 3 == 0) num /= 3; // If num got reduced to 1 then it // has only 2 and 3 as prime factors if (num == 1) count++; } return count;} // Driver codestatic public void Main (){ int l = 1, r = 10; Console.WriteLine(findTwoThreePrime(l, r));}} // This code is contributed by akt_mit",
"e": 29753,
"s": 28808,
"text": null
},
{
"code": "<?php// PHP program to count the numbers// within a range whose prime factors// are only 2 and 3 // Function to count the number// within a range whose prime// factors are only 2 and 3function findTwoThreePrime($l, $r){ // Start with 2 so that 1 // doesn't get counted if ($l == 1) $l++; $count = 0; for ($i = $l; $i <= $r; $i++) { $num = $i; // While num is divisible by 2, // divide it by 2 while ($num % 2 == 0) $num /= 2; // While num is divisible by 3, // divide it by 3 while ($num % 3 == 0) $num /= 3; // If num got reduced to 1 then it has // only 2 and 3 as prime factors if ($num == 1) $count++; } return $count;} // Driver code$l = 1;$r = 10;echo findTwoThreePrime($l, $r); // This code is contributed by ajit?>",
"e": 30619,
"s": 29753,
"text": null
},
{
"code": "<script> // Javascript program to count the numbers // within a range whose prime factors // are only 2 and 3 // Function to count the number // within a range whose prime // factors are only 2 and 3 function findTwoThreePrime(l, r) { // Start with 2 so that 1 // doesn't get counted if (l == 1) l++; let count = 0; for (let i = l; i <= r; i++) { let num = i; // While num is divisible by 2, // divide it by 2 while (num % 2 == 0) num = parseInt(num / 2, 10); // While num is divisible by 3, // divide it by 3 while (num % 3 == 0) num = parseInt(num / 3, 10); // If num got reduced to 1 then it // has only 2 and 3 as prime factors if (num == 1) count++; } return count; } let l = 1, r = 10; document.write(findTwoThreePrime(l, r)); </script>",
"e": 31638,
"s": 30619,
"text": null
},
{
"code": null,
"e": 31674,
"s": 31638,
"text": "Time Complexity: O((r-l)*log2(r-l))"
},
{
"code": null,
"e": 31696,
"s": 31674,
"text": "Auxiliary Space: O(1)"
},
{
"code": null,
"e": 31702,
"s": 31696,
"text": "jit_t"
},
{
"code": null,
"e": 31710,
"s": 31702,
"text": "ankthon"
},
{
"code": null,
"e": 31719,
"s": 31710,
"text": "mukesh07"
},
{
"code": null,
"e": 31738,
"s": 31719,
"text": "rohitkumarsinghcna"
},
{
"code": null,
"e": 31751,
"s": 31738,
"text": "prime-factor"
},
{
"code": null,
"e": 31764,
"s": 31751,
"text": "C++ Programs"
},
{
"code": null,
"e": 31788,
"s": 31764,
"text": "Competitive Programming"
},
{
"code": null,
"e": 31801,
"s": 31788,
"text": "Mathematical"
},
{
"code": null,
"e": 31814,
"s": 31801,
"text": "Mathematical"
},
{
"code": null,
"e": 31912,
"s": 31814,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31938,
"s": 31912,
"text": "C++ Program for QuickSort"
},
{
"code": null,
"e": 31949,
"s": 31938,
"text": "cin in C++"
},
{
"code": null,
"e": 31971,
"s": 31949,
"text": "delete keyword in C++"
},
{
"code": null,
"e": 32001,
"s": 31971,
"text": "CSV file management using C++"
},
{
"code": null,
"e": 32035,
"s": 32001,
"text": "Shallow Copy and Deep Copy in C++"
},
{
"code": null,
"e": 32078,
"s": 32035,
"text": "Competitive Programming - A Complete Guide"
},
{
"code": null,
"e": 32121,
"s": 32078,
"text": "Practice for cracking any coding interview"
},
{
"code": null,
"e": 32162,
"s": 32121,
"text": "Arrow operator -> in C/C++ with Examples"
},
{
"code": null,
"e": 32228,
"s": 32162,
"text": "Top 10 Algorithms and Data Structures for Competitive Programming"
}
] |
Area of a polygon with given n ordered vertices in C++
|
In this program, we have to find the area of a polygon. The coordinates of the vertices of this polygon are given. Before we move further lets brushup old concepts for a better understanding of the concept that follows.
The area is the quantitative representation of the extent of any two-dimensional figure.
Polygon is a closed figure with a given number of sides.
Coordinates of vertices are the value of points in the 2-d plane. For example (0,0).
Now, let's see the mathematical formula for finding the area.
Area = 1⁄2 [(x1y2 + x2y3 + ...... + x(n-1)yn + xny1) - (x2y1 + x3y2 + ....... + xny(n-1) + x1yn ) ]
Using this formula the area can be calculated,
Live Demo
#include <iostream>
#include <math.h>
using namespace std;
double areaOfPolygon(double x[], double y[], int n){
double area = 0.0;
int j = n - 1;
for (int i = 0; i < n; i++){
area += (x[j] + x[i]) * (y[j] - y[i]);
j = i;
}
return abs(area / 2.0);
}
int main(){
double X[] = {0, 1, 4, 8};
double Y[] = {0, 2, 5, 9};
int n = sizeof(X)/sizeof(X[0]);
cout<<"The area is "<<areaOfPolygon(X, Y, n);
}
The area is 3.5
|
[
{
"code": null,
"e": 1282,
"s": 1062,
"text": "In this program, we have to find the area of a polygon. The coordinates of the vertices of this polygon are given. Before we move further lets brushup old concepts for a better understanding of the concept that follows."
},
{
"code": null,
"e": 1371,
"s": 1282,
"text": "The area is the quantitative representation of the extent of any two-dimensional figure."
},
{
"code": null,
"e": 1428,
"s": 1371,
"text": "Polygon is a closed figure with a given number of sides."
},
{
"code": null,
"e": 1513,
"s": 1428,
"text": "Coordinates of vertices are the value of points in the 2-d plane. For example (0,0)."
},
{
"code": null,
"e": 1575,
"s": 1513,
"text": "Now, let's see the mathematical formula for finding the area."
},
{
"code": null,
"e": 1675,
"s": 1575,
"text": "Area = 1⁄2 [(x1y2 + x2y3 + ...... + x(n-1)yn + xny1) - (x2y1 + x3y2 + ....... + xny(n-1) + x1yn ) ]"
},
{
"code": null,
"e": 1722,
"s": 1675,
"text": "Using this formula the area can be calculated,"
},
{
"code": null,
"e": 1733,
"s": 1722,
"text": " Live Demo"
},
{
"code": null,
"e": 2167,
"s": 1733,
"text": "#include <iostream>\n#include <math.h>\nusing namespace std;\ndouble areaOfPolygon(double x[], double y[], int n){\n double area = 0.0;\n int j = n - 1;\n for (int i = 0; i < n; i++){\n area += (x[j] + x[i]) * (y[j] - y[i]);\n j = i;\n }\n return abs(area / 2.0);\n}\nint main(){\n double X[] = {0, 1, 4, 8};\n double Y[] = {0, 2, 5, 9};\n int n = sizeof(X)/sizeof(X[0]);\n cout<<\"The area is \"<<areaOfPolygon(X, Y, n);\n}"
},
{
"code": null,
"e": 2183,
"s": 2167,
"text": "The area is 3.5"
}
] |
Select and Deselect Text Inside an Element using JavaScript
|
Following is the code to select and deselect text inside an element using JavaScript −
Live Demo
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
body {
font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
}
.result {
font-size: 20px;
font-weight: 500;
}
</style>
</head>
<body>
<h1>Select and Deselect Text Inside an Element</h1>
<div style="color: green;" class="result">
Here is some text inside the div
</div>
<button class="Btn">SELECT</button>
<button class="Btn">DESELECT</button>
<h3>Click on the above button to select/de-select text inside the div</h3>
<script>
let resEle = document.querySelector(".result");
let BtnEle = document.querySelectorAll(".Btn");
BtnEle[0].addEventListener("click", () => {
window.getSelection().selectAllChildren(resEle);
});
BtnEle[1].addEventListener("click", () => {
window.getSelection().removeAllRanges();
});
</script>
</body>
</html>
The above code will produce the following output −
On clicking the ‘SELECT’ button −
On clicking the ‘DESELECT’ button −
|
[
{
"code": null,
"e": 1149,
"s": 1062,
"text": "Following is the code to select and deselect text inside an element using JavaScript −"
},
{
"code": null,
"e": 1160,
"s": 1149,
"text": " Live Demo"
},
{
"code": null,
"e": 2133,
"s": 1160,
"text": "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"UTF-8\" />\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n<title>Document</title>\n<style>\n body {\n font-family: \"Segoe UI\", Tahoma, Geneva, Verdana, sans-serif;\n }\n .result {\n font-size: 20px;\n font-weight: 500;\n }\n</style>\n</head>\n<body>\n<h1>Select and Deselect Text Inside an Element</h1>\n<div style=\"color: green;\" class=\"result\">\nHere is some text inside the div\n</div>\n<button class=\"Btn\">SELECT</button>\n<button class=\"Btn\">DESELECT</button>\n<h3>Click on the above button to select/de-select text inside the div</h3>\n<script>\n let resEle = document.querySelector(\".result\");\n let BtnEle = document.querySelectorAll(\".Btn\");\n BtnEle[0].addEventListener(\"click\", () => {\n window.getSelection().selectAllChildren(resEle);\n });\n BtnEle[1].addEventListener(\"click\", () => {\n window.getSelection().removeAllRanges();\n });\n</script>\n</body>\n</html>"
},
{
"code": null,
"e": 2184,
"s": 2133,
"text": "The above code will produce the following output −"
},
{
"code": null,
"e": 2218,
"s": 2184,
"text": "On clicking the ‘SELECT’ button −"
},
{
"code": null,
"e": 2254,
"s": 2218,
"text": "On clicking the ‘DESELECT’ button −"
}
] |
5 Data Transformers to know from Scikit-Learn | by Cornellius Yudha Wijaya | Towards Data Science
|
If you enjoy my content and want to get more in-depth knowledge regarding data or just daily life as a Data Scientist, please consider subscribing to my newsletter here.
As Data scientists, we are often faced with many situations where we faced difficulty when exploring data and developing machine learning. The struggle could come from the statistical assumption who did not fit your data or too much noise in the data. This is where you might need to transform your data to get a better clarity or fill the statistical method's assumption.
Previously, I have read a beginner-friendly article regarding Data Transformation, which you could read here.
towardsdatascience.com
I suggest you read the article above if you did not understand what Data Transformation is and the benefit (or not) of transforming your data. If you feel have understood the concepts, then we could move on to a more depth discussion.
One disclaimer I would make is that you need to be careful when doing Data Transformation because you would end up with a transformed data — which is not your original data anymore. You need to understand why you need to transform your data and the transformed data output, which is why I write this article.
In this article, I want to outline a more advanced Data Transformation from the Scikit-Learn, which we could use in the specific situation. What are they? Let’s get into it.
Quantile Transformation is a non-parametric data transformation technique to transform your numerical data distribution to following a certain data distribution (often the Gaussian Distribution (Normal Distribution)). In the Scikit-Learn, the Quantile Transformer can transform the data into Normal distribution or Uniform distribution; it depends on your distribution references.
How is the Quantile Transformation works? Conceptually, Quantile Transformer applying Quantile Function into the data intended to transform. Quantile Function itself is an inversed function of the Cumulative Distribution Function (CDF) which you could check here for the Normal Distribution. If you use Uniform Distribution, the transformed data would be the quantile position of the data. Let’s use example data to understand the transformation better.
import seaborn as snsimport numpy as npfrom sklearn.preprocessing import QuantileTransformer#Using mpg datampg = sns.load_dataset('mpg')#Quantile Transformation (by default it is Uniform)quantile_transformer = QuantileTransformer(random_state=0, output_distribution='uniform')mpg['mpg_trans'] = pd.Series(quantile_transformer.fit_transform(np.array(mpg['mpg']).reshape(-1, 1))[:,0])mpg[['mpg', 'mpg_trans']].head()
As you can see in the image above, the real data in the index 0 is 18, and the transformed data is 0.28; why is it 0,28? Let’s try to take the quantile 0.28 of the mpg columns.
np.quantile(mpg['mpg'], 0.28)
The result is 18; this is means that the transformed data is the approximation of the quantile position of the actual data. For note, when you are applying Quantile Transformation, you would lose the Linear Correlation between the variable you transformed because Quantile Transformer is a Non-Linear transformer. However, it is not expected to measure the linear correlation between transformed variables as the data have been changed.
Quantile transformation is often used to remove outliers or fit the Normal Distribution, although there are many similar data transformations that you could compare with.
While Quantile Transformer is a non-parametric transformer applying Quantile Function, Power Transformer is a parametric transformer via power function. Like the Quantile Transformer, Power Transformer is often used to transform data to follow the Normal Distribution.
From Scikit-Learn, two methods are given within the Power Transformer class: Yeo-Johnson transform, and Box-Cox transforms. The basic difference between the methods is the data they allowed to be transformed — Box-Cox needs the data to be positive, while Yeo-Johnson allowed the data to be both negative and positive. Let’s use the example data to use the Power Transformation from Scikit-Learn. I want to use the previous dataset as some features are not distributed normally — for example, the weight feature.
sns.distplot(mpg['weight'])
As we can see in the image above, the distribution is clearly skew-right or positive skew, which means it did not follow the normal distribution. Let’s use the Power Transformer to transform the data to follow the normal distribution closely.
from sklearn.preprocessing import PowerTransformerpt = PowerTransformer(method = 'box-cox')mpg['weight_trans'] = pt.fit_transform(np.array(mpg['weight']).reshape(-1,1))[:,0]sns.distplot(mpg['weight_trans'])
Using the Power Transformer (Box-Cox in this example) would push the data to follow the normal distribution closely. As the data is quite skewed, the transformed data are not completely following the normal distribution, but it is closer than the untransformed data.
While both Quantile Transformer and Power Transformer can transform your data into another data distribution by preserving the ranks, the use might still depend on your data and the scale you expected from the transformation. There is no certain way to say that one transformer is better than the other; what you can do to know which transformer is good for your data is by applying it and measure the metrics you use.
Discretization is a process of transforming the continuous feature into a categorical feature by partitioning it into several bins within the expected value range (intervals). I would show you the sample data and discretization transformation in the table below.
In the table above, I have five data points (10,15,20,25,30), and I discretize the continuous value into a categorical feature I called Bins, which holds values 1 and 2. In the Bins feature, I input values between 10–20 into category 1 and the rest into category 2 — This is how essentially discretization work.
In the Scikit-Learn, the process of Discretization using a binning with a set interval (often quantile) is compiled in the KBinsDiscretization class. Let’s use the dataset example to get a better understanding of the function.
from sklearn.preprocessing import KBinsDiscretizer#Setting the divided bins into 5 bins with quantile interval and transformation into ordinal categoryest = KBinsDiscretizer(n_bins = 5, encode = 'ordinal', strategy='quantile')mpg['mpg_discrete'] = est.fit_transform(np.array(mpg['mpg']).reshape(-1,1))mpg[['mpg', 'mpg_discrete']].sample(5)
As we can see from the table above, the continuous feature mpg is discretized into an ordinal categorical feature. You would often benefit from the One-Hot Encoding of the discretization feature; that is why the KBinsDiscretizer also offers you the One-Hot capability (in fact, the default encode parameter is ‘onehot’). However, I often use the Pandas get_dummies feature for the OHE process as it is easier to process than directly from the KBinsDiscretizer.
Feature Binarization is a simple discretization process using a certain threshold to transform the continuous feature into a categorical feature. The value results from Feature Binarization is Boolean value — True or False (0 or 1). Let’s try to use the Binarization class from Scikit-Learn to understand the concept.
from sklearn.preprocessing import Binarizer#Setting the threshold to 20transformer = Binarizer( threshold = 20)mpg['mpg_binary'] = transformer.fit_transform(np.array(mpg['mpg']).reshape(-1,1))mpg[['mpg', 'mpg_binary']].sample(5)
As you can see from the table above, the value below 20 would return False (0), and the rest would return True (1). The threshold is something we set so often; you might want to know why you set the current threshold. Note that if you used KBinsDiscretizer n_bins to 2, it would be similar to the Binarizer if the threshold is similar to the bin edge value.
Scikit-Learn has provided us many transformation methods that we could use for the data preprocessing pipeline. However, we want to apply our own function for data transformation, but Scikit-Learn did not offer it. That is why Scikit-Learn also presents the Function Transformers class to develop their own data transformation function.
Why do we want to develop our own custom function with Scikit-Learn? It is only somewhat required to have a Scikit-Learn pipeline for your model and need to have a custom transformation in your data pipeline. The more you work with the model and data, you would realize that a custom transformer is used more often than you think.
Let’s try to create our own transformers with Function Transformers. I want to transform my data into log value in my data pipeline, but Scikit-Learn did not offer the function; that is why I need to develop it by myself.
from sklearn.preprocessing import FunctionTransformer#Passing the log function from numpy which would be applied to every data in the columntransformer = FunctionTransformer(np.log, validate=True)mpg['mpg_log'] = transformer.fit_transform(np.array(mpg['mpg']).reshape(-1,1))mpg[['mpg', 'mpg_log']].head(5)
With the Function Transformer, you could control your own transformation result like the above result. The data is transformed into log data, and you could use it for further processes.
You don't necessarily need to rely on the Numpy package; you could always create your own function — what is important is the function produces an output. For example, I create my own function on the below code.
def cust_func(x): return x + 1
The function would return a numerical value with an addition process (plus one). Let’s pass it into our custom transformers.
transformer = FunctionTransformer(cust_func, validate=True)mpg['mpg_cust'] = transformer.fit_transform(np.array(mpg['mpg']).reshape(-1,1))mpg[['mpg', 'mpg_cust']].head(5)
As you can see from the table above, our value result follows the function we have previously developed. Function Transformer sounds easy, but in a long way, it would help your pipeline process.
Data Transformation is a typical process in your data work and often benefits your work if you know what the data transformation process results. Scikit-Learn have provided us with few data transformations method, including:
Quantile TransformerPower TransformerK-Bins DiscretizerFeature BinarizationFunction Transformers
Quantile Transformer
Power Transformer
K-Bins Discretizer
Feature Binarization
Function Transformers
I hope it helps!
Visit me on my LinkedIn or Twitter.
If you are not subscribed as a Medium Member, please consider subscribing through my referral.
|
[
{
"code": null,
"e": 342,
"s": 172,
"text": "If you enjoy my content and want to get more in-depth knowledge regarding data or just daily life as a Data Scientist, please consider subscribing to my newsletter here."
},
{
"code": null,
"e": 715,
"s": 342,
"text": "As Data scientists, we are often faced with many situations where we faced difficulty when exploring data and developing machine learning. The struggle could come from the statistical assumption who did not fit your data or too much noise in the data. This is where you might need to transform your data to get a better clarity or fill the statistical method's assumption."
},
{
"code": null,
"e": 825,
"s": 715,
"text": "Previously, I have read a beginner-friendly article regarding Data Transformation, which you could read here."
},
{
"code": null,
"e": 848,
"s": 825,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 1083,
"s": 848,
"text": "I suggest you read the article above if you did not understand what Data Transformation is and the benefit (or not) of transforming your data. If you feel have understood the concepts, then we could move on to a more depth discussion."
},
{
"code": null,
"e": 1392,
"s": 1083,
"text": "One disclaimer I would make is that you need to be careful when doing Data Transformation because you would end up with a transformed data — which is not your original data anymore. You need to understand why you need to transform your data and the transformed data output, which is why I write this article."
},
{
"code": null,
"e": 1566,
"s": 1392,
"text": "In this article, I want to outline a more advanced Data Transformation from the Scikit-Learn, which we could use in the specific situation. What are they? Let’s get into it."
},
{
"code": null,
"e": 1947,
"s": 1566,
"text": "Quantile Transformation is a non-parametric data transformation technique to transform your numerical data distribution to following a certain data distribution (often the Gaussian Distribution (Normal Distribution)). In the Scikit-Learn, the Quantile Transformer can transform the data into Normal distribution or Uniform distribution; it depends on your distribution references."
},
{
"code": null,
"e": 2401,
"s": 1947,
"text": "How is the Quantile Transformation works? Conceptually, Quantile Transformer applying Quantile Function into the data intended to transform. Quantile Function itself is an inversed function of the Cumulative Distribution Function (CDF) which you could check here for the Normal Distribution. If you use Uniform Distribution, the transformed data would be the quantile position of the data. Let’s use example data to understand the transformation better."
},
{
"code": null,
"e": 2817,
"s": 2401,
"text": "import seaborn as snsimport numpy as npfrom sklearn.preprocessing import QuantileTransformer#Using mpg datampg = sns.load_dataset('mpg')#Quantile Transformation (by default it is Uniform)quantile_transformer = QuantileTransformer(random_state=0, output_distribution='uniform')mpg['mpg_trans'] = pd.Series(quantile_transformer.fit_transform(np.array(mpg['mpg']).reshape(-1, 1))[:,0])mpg[['mpg', 'mpg_trans']].head()"
},
{
"code": null,
"e": 2994,
"s": 2817,
"text": "As you can see in the image above, the real data in the index 0 is 18, and the transformed data is 0.28; why is it 0,28? Let’s try to take the quantile 0.28 of the mpg columns."
},
{
"code": null,
"e": 3024,
"s": 2994,
"text": "np.quantile(mpg['mpg'], 0.28)"
},
{
"code": null,
"e": 3461,
"s": 3024,
"text": "The result is 18; this is means that the transformed data is the approximation of the quantile position of the actual data. For note, when you are applying Quantile Transformation, you would lose the Linear Correlation between the variable you transformed because Quantile Transformer is a Non-Linear transformer. However, it is not expected to measure the linear correlation between transformed variables as the data have been changed."
},
{
"code": null,
"e": 3632,
"s": 3461,
"text": "Quantile transformation is often used to remove outliers or fit the Normal Distribution, although there are many similar data transformations that you could compare with."
},
{
"code": null,
"e": 3901,
"s": 3632,
"text": "While Quantile Transformer is a non-parametric transformer applying Quantile Function, Power Transformer is a parametric transformer via power function. Like the Quantile Transformer, Power Transformer is often used to transform data to follow the Normal Distribution."
},
{
"code": null,
"e": 4413,
"s": 3901,
"text": "From Scikit-Learn, two methods are given within the Power Transformer class: Yeo-Johnson transform, and Box-Cox transforms. The basic difference between the methods is the data they allowed to be transformed — Box-Cox needs the data to be positive, while Yeo-Johnson allowed the data to be both negative and positive. Let’s use the example data to use the Power Transformation from Scikit-Learn. I want to use the previous dataset as some features are not distributed normally — for example, the weight feature."
},
{
"code": null,
"e": 4441,
"s": 4413,
"text": "sns.distplot(mpg['weight'])"
},
{
"code": null,
"e": 4684,
"s": 4441,
"text": "As we can see in the image above, the distribution is clearly skew-right or positive skew, which means it did not follow the normal distribution. Let’s use the Power Transformer to transform the data to follow the normal distribution closely."
},
{
"code": null,
"e": 4891,
"s": 4684,
"text": "from sklearn.preprocessing import PowerTransformerpt = PowerTransformer(method = 'box-cox')mpg['weight_trans'] = pt.fit_transform(np.array(mpg['weight']).reshape(-1,1))[:,0]sns.distplot(mpg['weight_trans'])"
},
{
"code": null,
"e": 5158,
"s": 4891,
"text": "Using the Power Transformer (Box-Cox in this example) would push the data to follow the normal distribution closely. As the data is quite skewed, the transformed data are not completely following the normal distribution, but it is closer than the untransformed data."
},
{
"code": null,
"e": 5577,
"s": 5158,
"text": "While both Quantile Transformer and Power Transformer can transform your data into another data distribution by preserving the ranks, the use might still depend on your data and the scale you expected from the transformation. There is no certain way to say that one transformer is better than the other; what you can do to know which transformer is good for your data is by applying it and measure the metrics you use."
},
{
"code": null,
"e": 5840,
"s": 5577,
"text": "Discretization is a process of transforming the continuous feature into a categorical feature by partitioning it into several bins within the expected value range (intervals). I would show you the sample data and discretization transformation in the table below."
},
{
"code": null,
"e": 6152,
"s": 5840,
"text": "In the table above, I have five data points (10,15,20,25,30), and I discretize the continuous value into a categorical feature I called Bins, which holds values 1 and 2. In the Bins feature, I input values between 10–20 into category 1 and the rest into category 2 — This is how essentially discretization work."
},
{
"code": null,
"e": 6379,
"s": 6152,
"text": "In the Scikit-Learn, the process of Discretization using a binning with a set interval (often quantile) is compiled in the KBinsDiscretization class. Let’s use the dataset example to get a better understanding of the function."
},
{
"code": null,
"e": 6719,
"s": 6379,
"text": "from sklearn.preprocessing import KBinsDiscretizer#Setting the divided bins into 5 bins with quantile interval and transformation into ordinal categoryest = KBinsDiscretizer(n_bins = 5, encode = 'ordinal', strategy='quantile')mpg['mpg_discrete'] = est.fit_transform(np.array(mpg['mpg']).reshape(-1,1))mpg[['mpg', 'mpg_discrete']].sample(5)"
},
{
"code": null,
"e": 7180,
"s": 6719,
"text": "As we can see from the table above, the continuous feature mpg is discretized into an ordinal categorical feature. You would often benefit from the One-Hot Encoding of the discretization feature; that is why the KBinsDiscretizer also offers you the One-Hot capability (in fact, the default encode parameter is ‘onehot’). However, I often use the Pandas get_dummies feature for the OHE process as it is easier to process than directly from the KBinsDiscretizer."
},
{
"code": null,
"e": 7498,
"s": 7180,
"text": "Feature Binarization is a simple discretization process using a certain threshold to transform the continuous feature into a categorical feature. The value results from Feature Binarization is Boolean value — True or False (0 or 1). Let’s try to use the Binarization class from Scikit-Learn to understand the concept."
},
{
"code": null,
"e": 7727,
"s": 7498,
"text": "from sklearn.preprocessing import Binarizer#Setting the threshold to 20transformer = Binarizer( threshold = 20)mpg['mpg_binary'] = transformer.fit_transform(np.array(mpg['mpg']).reshape(-1,1))mpg[['mpg', 'mpg_binary']].sample(5)"
},
{
"code": null,
"e": 8085,
"s": 7727,
"text": "As you can see from the table above, the value below 20 would return False (0), and the rest would return True (1). The threshold is something we set so often; you might want to know why you set the current threshold. Note that if you used KBinsDiscretizer n_bins to 2, it would be similar to the Binarizer if the threshold is similar to the bin edge value."
},
{
"code": null,
"e": 8422,
"s": 8085,
"text": "Scikit-Learn has provided us many transformation methods that we could use for the data preprocessing pipeline. However, we want to apply our own function for data transformation, but Scikit-Learn did not offer it. That is why Scikit-Learn also presents the Function Transformers class to develop their own data transformation function."
},
{
"code": null,
"e": 8753,
"s": 8422,
"text": "Why do we want to develop our own custom function with Scikit-Learn? It is only somewhat required to have a Scikit-Learn pipeline for your model and need to have a custom transformation in your data pipeline. The more you work with the model and data, you would realize that a custom transformer is used more often than you think."
},
{
"code": null,
"e": 8975,
"s": 8753,
"text": "Let’s try to create our own transformers with Function Transformers. I want to transform my data into log value in my data pipeline, but Scikit-Learn did not offer the function; that is why I need to develop it by myself."
},
{
"code": null,
"e": 9281,
"s": 8975,
"text": "from sklearn.preprocessing import FunctionTransformer#Passing the log function from numpy which would be applied to every data in the columntransformer = FunctionTransformer(np.log, validate=True)mpg['mpg_log'] = transformer.fit_transform(np.array(mpg['mpg']).reshape(-1,1))mpg[['mpg', 'mpg_log']].head(5)"
},
{
"code": null,
"e": 9467,
"s": 9281,
"text": "With the Function Transformer, you could control your own transformation result like the above result. The data is transformed into log data, and you could use it for further processes."
},
{
"code": null,
"e": 9679,
"s": 9467,
"text": "You don't necessarily need to rely on the Numpy package; you could always create your own function — what is important is the function produces an output. For example, I create my own function on the below code."
},
{
"code": null,
"e": 9713,
"s": 9679,
"text": "def cust_func(x): return x + 1"
},
{
"code": null,
"e": 9838,
"s": 9713,
"text": "The function would return a numerical value with an addition process (plus one). Let’s pass it into our custom transformers."
},
{
"code": null,
"e": 10009,
"s": 9838,
"text": "transformer = FunctionTransformer(cust_func, validate=True)mpg['mpg_cust'] = transformer.fit_transform(np.array(mpg['mpg']).reshape(-1,1))mpg[['mpg', 'mpg_cust']].head(5)"
},
{
"code": null,
"e": 10204,
"s": 10009,
"text": "As you can see from the table above, our value result follows the function we have previously developed. Function Transformer sounds easy, but in a long way, it would help your pipeline process."
},
{
"code": null,
"e": 10429,
"s": 10204,
"text": "Data Transformation is a typical process in your data work and often benefits your work if you know what the data transformation process results. Scikit-Learn have provided us with few data transformations method, including:"
},
{
"code": null,
"e": 10526,
"s": 10429,
"text": "Quantile TransformerPower TransformerK-Bins DiscretizerFeature BinarizationFunction Transformers"
},
{
"code": null,
"e": 10547,
"s": 10526,
"text": "Quantile Transformer"
},
{
"code": null,
"e": 10565,
"s": 10547,
"text": "Power Transformer"
},
{
"code": null,
"e": 10584,
"s": 10565,
"text": "K-Bins Discretizer"
},
{
"code": null,
"e": 10605,
"s": 10584,
"text": "Feature Binarization"
},
{
"code": null,
"e": 10627,
"s": 10605,
"text": "Function Transformers"
},
{
"code": null,
"e": 10644,
"s": 10627,
"text": "I hope it helps!"
},
{
"code": null,
"e": 10680,
"s": 10644,
"text": "Visit me on my LinkedIn or Twitter."
}
] |
How to get attribute of an element when using the 'click' event in jQuery?
|
To get attribute of an element, use the attr() method in jQuery. You can try to run the following code to get attribute of an element using the ‘click’ event −
Live Demo
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
alert("Width of image: " + $("img").attr("width"));
});
});
</script>
</head>
<body>
<img src="/videotutorials/images/coding_ground_home.jpg" alt="Coding Ground" width="284" height="280"><br>
<button>Get Width</button>
</body>
</html>
|
[
{
"code": null,
"e": 1222,
"s": 1062,
"text": "To get attribute of an element, use the attr() method in jQuery. You can try to run the following code to get attribute of an element using the ‘click’ event −"
},
{
"code": null,
"e": 1232,
"s": 1222,
"text": "Live Demo"
},
{
"code": null,
"e": 1674,
"s": 1232,
"text": "<!DOCTYPE html>\n<html>\n<head>\n<script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js\"></script>\n<script>\n$(document).ready(function(){\n $(\"button\").click(function(){\n alert(\"Width of image: \" + $(\"img\").attr(\"width\"));\n });\n});\n</script>\n</head>\n<body>\n\n<img src=\"/videotutorials/images/coding_ground_home.jpg\" alt=\"Coding Ground\" width=\"284\" height=\"280\"><br>\n\n<button>Get Width</button>\n\n</body>\n</html>"
}
] |
Namedtuple in Python
|
The NamedTuple is another class, under the collections module. Like the dictionary type objects, it contains keys and that are mapped to some values. In this case we can access the elements using keys and indexes.
To use it at first we need to import it the collections standard library module.
import collections
In this section we will see some functions of the NamedTuple class.
From NamedTuple, we can access the values using indexes, keys and the getattr() method. The attribute values of NamedTuple are ordered. So we can access them using the indexes.
The NamedTuple converts the field names as attributes. So using getattr() it is possible to get the data from that attribute.
import collections as col
#create employee NamedTuple
Employee = col.namedtuple('Employee', ['name', 'city', 'salary'])
#Add two employees
e1 = Employee('Asim', 'Delhi', '25000')
e2 = Employee('Bibhas', 'Kolkata', '30000')
#Access the elements using index
print('The name and salary of e1: ' + e1[0] + ' and ' + e1[2])
#Access the elements using attribute name
print('The name and salary of e2: ' + e2.name + ' and ' + e2.salary)
#Access the elements using getattr()
print('The City of e1 and e2: ' + getattr(e1, 'city') + ' and ' + getattr(e2, 'city'))
The name and salary of e1: Asim and 25000
The name and salary of e2: Bibhas and 30000
The City of e1 and e2: Delhi and Kolkata
There are some methods to convert other collections to NamedTuple. The _make() method can be used to convert an iterable object like list, tuple, etc to NamedTuple object.
We can also convert a dictionary type object to NamedTuple object. For this conversion, we need the ** operator.
NamedTuple can return the values with keys as OrderedDict type object. To make it OrderedDict, we have to use the _asdict() method.
import collections as col
#create employee NamedTuple
Employee = col.namedtuple('Employee', ['name', 'city', 'salary'])
#List of values to Employee
my_list = ['Asim', 'Delhi', '25000']
e1 = Employee._make(my_list)
print(e1)
#Dict to convert Employee
my_dict = {'name':'Bibhas', 'city' : 'Kolkata', 'salary' : '30000'}
e2 = Employee(**my_dict)
print(e2)
#Show the named tuple as dictionary
emp_dict = e1._asdict()
print(emp_dict)
Employee(name='Asim', city='Delhi', salary='25000')
Employee(name='Bibhas', city='Kolkata', salary='30000')
OrderedDict([('name', 'Asim'), ('city', 'Delhi'), ('salary', '25000')])
There are some other method like _fields() and _replace(). Using the _fields() method we can check what are the different fields of NamedTuple. The _replace() method is used to replace the value of some other value.
import collections as col
#create employee NamedTuple
Employee = col.namedtuple('Employee', ['name', 'city', 'salary'])
#Add an employees
e1 = Employee('Asim', 'Delhi', '25000')
print(e1)
print('The fields of Employee: ' + str(e1._fields))
#replace the city of employee e1
e1 = e1._replace(city='Mumbai')
print(e1)
Employee(name='Asim', city='Delhi', salary='25000')
The fields of Employee: ('name', 'city', 'salary')
Employee(name='Asim', city='Mumbai', salary='25000')
|
[
{
"code": null,
"e": 1276,
"s": 1062,
"text": "The NamedTuple is another class, under the collections module. Like the dictionary type objects, it contains keys and that are mapped to some values. In this case we can access the elements using keys and indexes."
},
{
"code": null,
"e": 1357,
"s": 1276,
"text": "To use it at first we need to import it the collections standard library module."
},
{
"code": null,
"e": 1377,
"s": 1357,
"text": "import collections\n"
},
{
"code": null,
"e": 1445,
"s": 1377,
"text": "In this section we will see some functions of the NamedTuple class."
},
{
"code": null,
"e": 1622,
"s": 1445,
"text": "From NamedTuple, we can access the values using indexes, keys and the getattr() method. The attribute values of NamedTuple are ordered. So we can access them using the indexes."
},
{
"code": null,
"e": 1748,
"s": 1622,
"text": "The NamedTuple converts the field names as attributes. So using getattr() it is possible to get the data from that attribute."
},
{
"code": null,
"e": 2302,
"s": 1748,
"text": "import collections as col\n#create employee NamedTuple\nEmployee = col.namedtuple('Employee', ['name', 'city', 'salary'])\n#Add two employees\ne1 = Employee('Asim', 'Delhi', '25000')\ne2 = Employee('Bibhas', 'Kolkata', '30000')\n#Access the elements using index\nprint('The name and salary of e1: ' + e1[0] + ' and ' + e1[2])\n#Access the elements using attribute name\nprint('The name and salary of e2: ' + e2.name + ' and ' + e2.salary)\n#Access the elements using getattr()\nprint('The City of e1 and e2: ' + getattr(e1, 'city') + ' and ' + getattr(e2, 'city'))"
},
{
"code": null,
"e": 2430,
"s": 2302,
"text": "The name and salary of e1: Asim and 25000\nThe name and salary of e2: Bibhas and 30000\nThe City of e1 and e2: Delhi and Kolkata\n"
},
{
"code": null,
"e": 2602,
"s": 2430,
"text": "There are some methods to convert other collections to NamedTuple. The _make() method can be used to convert an iterable object like list, tuple, etc to NamedTuple object."
},
{
"code": null,
"e": 2715,
"s": 2602,
"text": "We can also convert a dictionary type object to NamedTuple object. For this conversion, we need the ** operator."
},
{
"code": null,
"e": 2847,
"s": 2715,
"text": "NamedTuple can return the values with keys as OrderedDict type object. To make it OrderedDict, we have to use the _asdict() method."
},
{
"code": null,
"e": 3276,
"s": 2847,
"text": "import collections as col\n#create employee NamedTuple\nEmployee = col.namedtuple('Employee', ['name', 'city', 'salary'])\n#List of values to Employee\nmy_list = ['Asim', 'Delhi', '25000']\ne1 = Employee._make(my_list)\nprint(e1)\n#Dict to convert Employee\nmy_dict = {'name':'Bibhas', 'city' : 'Kolkata', 'salary' : '30000'}\ne2 = Employee(**my_dict)\nprint(e2)\n#Show the named tuple as dictionary\nemp_dict = e1._asdict()\nprint(emp_dict)"
},
{
"code": null,
"e": 3457,
"s": 3276,
"text": "Employee(name='Asim', city='Delhi', salary='25000')\nEmployee(name='Bibhas', city='Kolkata', salary='30000')\nOrderedDict([('name', 'Asim'), ('city', 'Delhi'), ('salary', '25000')])\n"
},
{
"code": null,
"e": 3673,
"s": 3457,
"text": "There are some other method like _fields() and _replace(). Using the _fields() method we can check what are the different fields of NamedTuple. The _replace() method is used to replace the value of some other value."
},
{
"code": null,
"e": 3988,
"s": 3673,
"text": "import collections as col\n#create employee NamedTuple\nEmployee = col.namedtuple('Employee', ['name', 'city', 'salary'])\n#Add an employees\ne1 = Employee('Asim', 'Delhi', '25000')\nprint(e1)\nprint('The fields of Employee: ' + str(e1._fields))\n#replace the city of employee e1\ne1 = e1._replace(city='Mumbai')\nprint(e1)"
},
{
"code": null,
"e": 4145,
"s": 3988,
"text": "Employee(name='Asim', city='Delhi', salary='25000')\nThe fields of Employee: ('name', 'city', 'salary')\nEmployee(name='Asim', city='Mumbai', salary='25000')\n"
}
] |
How tracking apps analyse your GPS data: a hands-on tutorial in Python | by Steven Van Dorpe | Towards Data Science
|
Sport tracking applications and the social networks accompanying them are all over the place nowadays. Everyone wants to make the biggest or the fastest effort on apps like Nike+ Run or Strava. But have you ever wondered where all these fancy statistics come from, or how they are calculated?
Let’s start with explaining how your phone knows where you are, or more precisely, how the GPS receiver in your phone knows where you are. The Global Positioning System (GPS) is a satellite-based radionavigation system owned by the United States government.
It is a global navigation satellite system that provides geolocation and time information to a GPS receiver anywhere on the planet where there is an unobstructed line of sight to four or more GPS satellites. Your phone’s receiver’s location is usually converted to latitude, longitude and altitude, accompanied by a time stamp and stored as a gpx-file (more about the file format below).
In this tutorial we’ll extract, munge and analyse the gpx data of one single route in a Jupyter Notebook with Python. We’ll start with extracting the data from the gpx-file into a convenient pandas dataframe. From there we’ll explore the data and try to replicate the stats and graphs that the interface of our favorite running application provides us with.
Most of the populair tracking apps allow you to download your effort as a gpx-file. In this tutorial, we download an eleven kilometer run from Strava. The gpx-file, short for GPS Exchange Format, can usually be obtained by clicking on export. The screenshot below shows you where you can download your gpx-file in Strava. You can download the file used in this article here.
Gpx is an XML-schema designed as a common GPS data format for software applications. It can be used to describe waypoints, tracks, and routes. This also means that all the code below can be used to run on any GPS data, provided that you take into account the speed and type of movement.
First, it’s important to understand the structure of our gpx-file. After opening the file into any text editor (Notepad ++ here), you should get an XML-file with a lot of entries like the ones below. Note that each trackpoint consists of four values: latitude, longitude, elevation or altitude and a timestamp. These four values will be the backbone of our analysis.
Now, we want to load our gpx data into a pandas dataframe. There is no direct way to do this, so we’ll have to use the gpxpy library to assist us. While we’re importing modules, you might want to make sure that you have the following libraries installed as well: matplotlib, datetime, geopy, math, numpy, pandas, haversine and plotly (optional). Download the libraries, and make sure the following code can run successfully.
import gpxpyimport matplotlib.pyplot as pltimport datetimefrom geopy import distancefrom math import sqrt, floorimport numpy as npimport pandas as pdimport plotly.plotly as pyimport plotly.graph_objs as goimport haversine
Loading the gpx data into Python is as easy as opening the file in read mode and parsing it into a new variable.
gpx_file = open('my_run_001.gpx', 'r')gpx = gpxpy.parse(gpx_file)
Take a look at the new object and note that it’s a GPX object that consists of a list of GPXTrack objects. The GPXTrack objects on their turn exist of a list of GPXTrackSegment objects, which on their turn exist of GPXTrackPoints. These points are the four-value data points we’re interested in. They can be accessed with the longitude, latitude, elevation and time attributes.
Before consuming the data, it’s important to check how your data is divided between these objects. You can do this by checking the length of the tracks, segments and points list.
len(gpx.tracks)len(gpx.tracks[0].segments)len(gpx.tracks[0].segments[0].points)
In our example the length of both tracks and segments is 1. This means all the data is concentrated in the points attribute of the first segment of the first track. It makes sense to create a new variable that points directly to the list of data points.
data = gpx.tracks[0].segments[0].points
Take a look at your start point and end point and make sure everything makes sense (i.e. start time < end time, start elevation = end elevation, etc...). If not, there might be something wrong with your data, or you might have forgotten about some tracks or segments.
## Start Positionstart = data[0]## End Positionfinish = data[-1]
Once you’ve located all your data, pouring everything into a dataframe is easy. Just create an empty dataframe and iterate through all the data points while adding them to the dataframe.
df = pd.DataFrame(columns=['lon', 'lat', 'alt', 'time'])for point in data: df = df.append({'lon': point.longitude, 'lat' : point.latitude, 'alt' : point.elevation, 'time' : point.time}, ignore_index=True)
The head of the dataframe should look like this:
Note that the time interval between data points is supposed to be one second (for Strava, you can change this in your settings). Unfortunately, my device can’t always provide the GPS-data, due to connectivity problems. In case of such a failure the data point is skipped (without an error of any kind) and the application will collect the data at the next time interval. It is important to keep this in mind for further analysis and not to assume that the interval between all points is the same.
Now we have our data loaded, we can start exploring it with plotting some basic graphs. The two easiest ones are a 2d map (longitude vs latitude) and our elevation gain during our activity (altitude vs time). Comparing these plots with the ones from our app, we can see we did a pretty good job, so far.
plt.plot(df['lon'], df['lat'])
plt.plot(df['time'], df['alt'])
If we want to get really fancy, we can plot an interactive 3d line of our data with plotly. Although it’s debatable if this plot adds any analytical value to our story, it always feels good to look at your tremendous effort from another angle. If you haven’t used plotly before, don’t forget to create an account on plot.ly and set your username and API-key in the credentials-file.
_data = [go.Scatter3d(x=df['lon'], y=df['lat'], z=df['alt'], mode='lines')]py.iplot(_data)
If you want to learn how to overlay your plot on Google Maps, take a look a this tutorial about gmplot.
While we’ve done pretty good so far, we are still missing a few key values, such as distance and speed. It doesn’t seem too hard to calculate these two, but there are a few trap-holes. The first one is that we have to take into account that the distance between two LL-points (longitude, latitude) isn’t a straight line, but spherical.
There are two main approaches to calculate the distance between two points on a spherical surface: the Haversine distance and the Vincenty distance. The two formulas take a different approach on calculating the distance, but this is outside the scoop of this article. You can find more information on their Wikipedia pages: Haversine Formula Wiki and Vincenty Formula Wiki.
The next issue is that we might want to take into account the elevation gain or loss in our calculations. The easiest way to do this, is to calculate the spherical 2d distance and then use the Euclidean formula to add the third dimension. The formula below shows this last step.
distance_3d = sqrt(distance_2d**2 + (alt2 — alt1)**2)
Now we have all the theoretical background needed, we can start implementing the formula in our code. For convenience, we leave our dataframe for what it is, and iterate through all the data points just like we did before. We create a list for every possible implementation of our distance formula (Haversine or Vincenty and 2d or 3d) and add the total distance to the end of the list for every data point.
While we’re looping through the data points, we also create a list for the altitude difference, time difference and distance difference between all the consecutive data points.
alt_dif = [0]time_dif = [0]dist_vin = [0]dist_hav = [0]dist_vin_no_alt = [0]dist_hav_no_alt = [0]dist_dif_hav_2d = [0]dist_dif_vin_2d = [0]for index in range(len(data)): if index == 0: pass else: start = data[index-1] stop = data[index] distance_vin_2d = distance.vincenty((start.latitude, start.longitude), (stop.latitude, stop.longitude)).m dist_dif_vin_2d.append(distance_vin_2d) distance_hav_2d = haversine.haversine((start.latitude, start.longitude), (stop.latitude, stop.longitude))*1000dist_dif_hav_2d.append(distance_hav_2d) dist_vin_no_alt.append(dist_vin_no_alt[-1] + distance_vin_2d) dist_hav_no_alt.append(dist_hav_no_alt[-1] + distance_hav_2d) alt_d = start.elevation - stop.elevation alt_dif.append(alt_d) distance_vin_3d = sqrt(distance_vin_2d**2 + (alt_d)**2) distance_hav_3d = sqrt(distance_hav_2d**2 + (alt_d)**2) time_delta = (stop.time - start.time).total_seconds() time_dif.append(time_delta) dist_vin.append(dist_vin[-1] + distance_vin_3d) dist_hav.append(dist_hav[-1] + distance_hav_3d)
For further convenience, we can pour the data in our previously created dataframe.
df['dis_vin_2d'] = dist_vin_no_alt df['dist_hav_2d'] = dist_hav_no_altdf['dis_vin_3d'] = dist_vindf['dis_hav_3d'] = dist_havdf['alt_dif'] = alt_difdf['time_dif'] = time_difdf['dis_dif_hav_2d'] = dist_dif_hav_2ddf['dis_dif_vin_2d'] = dist_dif_vin_2d
Check the results with the following print command.
print('Vincenty 2D : ', dist_vin_no_alt[-1])print('Haversine 2D : ', dist_hav_no_alt[-1])print('Vincenty 3D : ', dist_vin[-1])print('Haversine 3D : ', dist_hav[-1])print('Total Time : ', floor(sum(time_dif)/60),' min ', int(sum(time_dif)%60),' sec ')
The output should look like this. Let’s also compare our results with the statistics our running app shows us.
There are a few things to notice. Firstly, all our total distance calculations — especially the 2d ones — seem to be a good approximation of the distance our app calculated for us. Secondly, the total activity time agrees completely with our calculations, but the moving time seems to be different.
This can signify that whenever the distance between two data points was too small, the app has stopped the moving time, but still took the distance into account, this can be realistic when we have to slow down and stop for a traffic light, for example.
In this scenario our 2d calculations are right and the we can conclude the app doesn’t take elevation into account. This is indeed confirmed by a blogpost from the app company.
A flat surface is assumed, and vertical speed from topography is not accounted for. — Strava
Worrisome? Not really. The difference between the distance proposed by the app and our maximum 3d estimate is only 61m (0.55%). This means that the total round-down for a 100km run (or ride) would by around 600m. Note that this difference will increase if you undertake more altitude-intense activities (mountain biking or hiking).
Let’s see if we can figure out which threshold Strava uses to stop the timer (and therefore boost our average speed). To do so, we need to create a new variable that calculates our movement in meters per second (and not just movement per data point, hence why we created the time difference variable). Let’s do this for our haversine 2d distance, since that’s the closest approximation of the distance proposed by the app.
df['dist_dif_per_sec'] = df['dis_dif_hav_2d'] / df['time_dif']
With this new variable we can iterate through a bunch of thresholds, let’s say between 50 cm and 1 meter, and try to figure out which one adds up to a timer time-out closest to 51 seconds.
for treshold in [0.5, 0.6, 0.7, 0.8, 0.9, 1]: print(treshold, 'm', ' : Time:', sum(df[df['dist_dif_per_sec'] < treshold]['time_dif']), ' seconds')
Your Notebook should print something like this.
We can therefore conclude that if the movement per seconde was less than 80 centimeters, the application didn’t consider it as a movement and stopped the timer. This seems very reasonable, since 80 centimeters per second is about 2.9 km per hour, a speed far below most people their walking pace.
While talking about pace, we might as well calculate the speed for every data point. First, we create a new column in our dataframe named speed. This new variable is calculated by dividing the distance traveled in meters by the time it took in seconds, and then converted to km/h.
df['spd'] = (df['dis_dif_hav_2d'] / df['time_dif']) * 3.6
Next, we filter out all the data where the movement per second is larger than 90 centimeters (see section above for the reason).
df_with_timeout = df[df['dist_dif_per_sec'] > 0.9]
Then we calculate the weighted average speed and convert it to minutes and second per kilometer (a metric widely used by runners).
avg_km_h = (sum((df_with_timeout['spd'] * df_with_timeout['time_dif'])) / sum(df_with_timeout['time_dif']))print(floor(60 / avg_km_h), 'minutes', round(((60 / avg_km_h - floor(60 / avg_km_h))*60), 0), ' seconds')
This results in an average speed of 5 minutes and 3 seconds per kilometer, exactly the same speed as proposed by our app. Let’s also draw a plot of our speed. Drawing a data point for every second would be to fine-grained, so we’ll draw an average speed data point for every 10 seconds.
Therefore, create a new variable that rounds down the cumulative sum of our time difference to 10 seconds, and plot the aggregated speed against it.
df['time10s'] = list(map(lambda x: round(x, -1) , np.cumsum(df['time_dif'])))plt.plot(df.groupby(['time10s']).mean()['spd'])
The result is a smooth line plot where we can see the speed in km/h against the time in seconds.
The last metric we’ll take a closer look at, is the elevation gain. According to the apps documentation, the cumulative elevation gain refers to the sum of every gain in elevation throughout an entire trip. This means we should only take into account the positive altitude gain.
We can write a simple function and map it over our altitude difference column of our dataframe.
def positive_only(x): if x > 0: return x else: return 0pos_only = list(map(positive_only, df['alt_dif']))sum(pos_only)
The sum is about 237 meters, pretty far from what our app told us we elevated (150 m). Taking a closer look to the altitude difference we can see that it’s measured down to 10 centimeters.
In case of running this could be jumping up and down a pavement, or scratching your head with your phone in your hand. It would make sense to round the numbers down to 1 meter. We can do this by mapping a lambda function over our previous results.
sum(list(map(lambda x: round(x,0) , pos_only)))
The new result is 137m, pretty close to the elevation proposed by the app. Knowing this, we should also recalculate our 3d distances with these new elevation values in place. Without doing the calculations, we know that the total distance will go down and close in on the 2d distance. This makes the not taking into account of the altitude gain in total distance even more justified.
I’ll round up this article with a revelation about the elevation gain: I didn’t gain any altitude during the actual run (except for a few minor staircases). There is even more, my phone, just like most lower market phones, does not have a barometer.
A barometer is an instrument measuring atmospheric pressure, used especially in forecasting the weather and determining altitude. But how did Strava determine our altitude then? The answer is Strava’s Elevation Basemap.
It is created using data from the community. By collecting the barometric altimeter measurements (from devices with a barometer) from any activity uploaded to Strava in the past, they are able to build a global elevation database.
For now the Basemap isn’t reliable enough and doesn’t cover enough of the world. But if they can make it more reliable in the future, they might be able, in combination with 3d calculations and a more complicated model on elevation gain, to provide all you sporters out there with even more accurate statistics.
In a follow-up of this article we’ll visualize all the data obtained during this tutorial with another hot kid on the block: QlikView.
— Please feel free to bring any inconsistencies or mistakes to my attention in the comments or by leaving a private note. —
|
[
{
"code": null,
"e": 464,
"s": 171,
"text": "Sport tracking applications and the social networks accompanying them are all over the place nowadays. Everyone wants to make the biggest or the fastest effort on apps like Nike+ Run or Strava. But have you ever wondered where all these fancy statistics come from, or how they are calculated?"
},
{
"code": null,
"e": 722,
"s": 464,
"text": "Let’s start with explaining how your phone knows where you are, or more precisely, how the GPS receiver in your phone knows where you are. The Global Positioning System (GPS) is a satellite-based radionavigation system owned by the United States government."
},
{
"code": null,
"e": 1110,
"s": 722,
"text": "It is a global navigation satellite system that provides geolocation and time information to a GPS receiver anywhere on the planet where there is an unobstructed line of sight to four or more GPS satellites. Your phone’s receiver’s location is usually converted to latitude, longitude and altitude, accompanied by a time stamp and stored as a gpx-file (more about the file format below)."
},
{
"code": null,
"e": 1468,
"s": 1110,
"text": "In this tutorial we’ll extract, munge and analyse the gpx data of one single route in a Jupyter Notebook with Python. We’ll start with extracting the data from the gpx-file into a convenient pandas dataframe. From there we’ll explore the data and try to replicate the stats and graphs that the interface of our favorite running application provides us with."
},
{
"code": null,
"e": 1843,
"s": 1468,
"text": "Most of the populair tracking apps allow you to download your effort as a gpx-file. In this tutorial, we download an eleven kilometer run from Strava. The gpx-file, short for GPS Exchange Format, can usually be obtained by clicking on export. The screenshot below shows you where you can download your gpx-file in Strava. You can download the file used in this article here."
},
{
"code": null,
"e": 2130,
"s": 1843,
"text": "Gpx is an XML-schema designed as a common GPS data format for software applications. It can be used to describe waypoints, tracks, and routes. This also means that all the code below can be used to run on any GPS data, provided that you take into account the speed and type of movement."
},
{
"code": null,
"e": 2497,
"s": 2130,
"text": "First, it’s important to understand the structure of our gpx-file. After opening the file into any text editor (Notepad ++ here), you should get an XML-file with a lot of entries like the ones below. Note that each trackpoint consists of four values: latitude, longitude, elevation or altitude and a timestamp. These four values will be the backbone of our analysis."
},
{
"code": null,
"e": 2922,
"s": 2497,
"text": "Now, we want to load our gpx data into a pandas dataframe. There is no direct way to do this, so we’ll have to use the gpxpy library to assist us. While we’re importing modules, you might want to make sure that you have the following libraries installed as well: matplotlib, datetime, geopy, math, numpy, pandas, haversine and plotly (optional). Download the libraries, and make sure the following code can run successfully."
},
{
"code": null,
"e": 3144,
"s": 2922,
"text": "import gpxpyimport matplotlib.pyplot as pltimport datetimefrom geopy import distancefrom math import sqrt, floorimport numpy as npimport pandas as pdimport plotly.plotly as pyimport plotly.graph_objs as goimport haversine"
},
{
"code": null,
"e": 3257,
"s": 3144,
"text": "Loading the gpx data into Python is as easy as opening the file in read mode and parsing it into a new variable."
},
{
"code": null,
"e": 3323,
"s": 3257,
"text": "gpx_file = open('my_run_001.gpx', 'r')gpx = gpxpy.parse(gpx_file)"
},
{
"code": null,
"e": 3701,
"s": 3323,
"text": "Take a look at the new object and note that it’s a GPX object that consists of a list of GPXTrack objects. The GPXTrack objects on their turn exist of a list of GPXTrackSegment objects, which on their turn exist of GPXTrackPoints. These points are the four-value data points we’re interested in. They can be accessed with the longitude, latitude, elevation and time attributes."
},
{
"code": null,
"e": 3880,
"s": 3701,
"text": "Before consuming the data, it’s important to check how your data is divided between these objects. You can do this by checking the length of the tracks, segments and points list."
},
{
"code": null,
"e": 3960,
"s": 3880,
"text": "len(gpx.tracks)len(gpx.tracks[0].segments)len(gpx.tracks[0].segments[0].points)"
},
{
"code": null,
"e": 4214,
"s": 3960,
"text": "In our example the length of both tracks and segments is 1. This means all the data is concentrated in the points attribute of the first segment of the first track. It makes sense to create a new variable that points directly to the list of data points."
},
{
"code": null,
"e": 4254,
"s": 4214,
"text": "data = gpx.tracks[0].segments[0].points"
},
{
"code": null,
"e": 4522,
"s": 4254,
"text": "Take a look at your start point and end point and make sure everything makes sense (i.e. start time < end time, start elevation = end elevation, etc...). If not, there might be something wrong with your data, or you might have forgotten about some tracks or segments."
},
{
"code": null,
"e": 4587,
"s": 4522,
"text": "## Start Positionstart = data[0]## End Positionfinish = data[-1]"
},
{
"code": null,
"e": 4774,
"s": 4587,
"text": "Once you’ve located all your data, pouring everything into a dataframe is easy. Just create an empty dataframe and iterate through all the data points while adding them to the dataframe."
},
{
"code": null,
"e": 4982,
"s": 4774,
"text": "df = pd.DataFrame(columns=['lon', 'lat', 'alt', 'time'])for point in data: df = df.append({'lon': point.longitude, 'lat' : point.latitude, 'alt' : point.elevation, 'time' : point.time}, ignore_index=True)"
},
{
"code": null,
"e": 5031,
"s": 4982,
"text": "The head of the dataframe should look like this:"
},
{
"code": null,
"e": 5528,
"s": 5031,
"text": "Note that the time interval between data points is supposed to be one second (for Strava, you can change this in your settings). Unfortunately, my device can’t always provide the GPS-data, due to connectivity problems. In case of such a failure the data point is skipped (without an error of any kind) and the application will collect the data at the next time interval. It is important to keep this in mind for further analysis and not to assume that the interval between all points is the same."
},
{
"code": null,
"e": 5832,
"s": 5528,
"text": "Now we have our data loaded, we can start exploring it with plotting some basic graphs. The two easiest ones are a 2d map (longitude vs latitude) and our elevation gain during our activity (altitude vs time). Comparing these plots with the ones from our app, we can see we did a pretty good job, so far."
},
{
"code": null,
"e": 5863,
"s": 5832,
"text": "plt.plot(df['lon'], df['lat'])"
},
{
"code": null,
"e": 5895,
"s": 5863,
"text": "plt.plot(df['time'], df['alt'])"
},
{
"code": null,
"e": 6278,
"s": 5895,
"text": "If we want to get really fancy, we can plot an interactive 3d line of our data with plotly. Although it’s debatable if this plot adds any analytical value to our story, it always feels good to look at your tremendous effort from another angle. If you haven’t used plotly before, don’t forget to create an account on plot.ly and set your username and API-key in the credentials-file."
},
{
"code": null,
"e": 6378,
"s": 6278,
"text": "_data = [go.Scatter3d(x=df['lon'], y=df['lat'], z=df['alt'], mode='lines')]py.iplot(_data)"
},
{
"code": null,
"e": 6482,
"s": 6378,
"text": "If you want to learn how to overlay your plot on Google Maps, take a look a this tutorial about gmplot."
},
{
"code": null,
"e": 6818,
"s": 6482,
"text": "While we’ve done pretty good so far, we are still missing a few key values, such as distance and speed. It doesn’t seem too hard to calculate these two, but there are a few trap-holes. The first one is that we have to take into account that the distance between two LL-points (longitude, latitude) isn’t a straight line, but spherical."
},
{
"code": null,
"e": 7192,
"s": 6818,
"text": "There are two main approaches to calculate the distance between two points on a spherical surface: the Haversine distance and the Vincenty distance. The two formulas take a different approach on calculating the distance, but this is outside the scoop of this article. You can find more information on their Wikipedia pages: Haversine Formula Wiki and Vincenty Formula Wiki."
},
{
"code": null,
"e": 7471,
"s": 7192,
"text": "The next issue is that we might want to take into account the elevation gain or loss in our calculations. The easiest way to do this, is to calculate the spherical 2d distance and then use the Euclidean formula to add the third dimension. The formula below shows this last step."
},
{
"code": null,
"e": 7525,
"s": 7471,
"text": "distance_3d = sqrt(distance_2d**2 + (alt2 — alt1)**2)"
},
{
"code": null,
"e": 7932,
"s": 7525,
"text": "Now we have all the theoretical background needed, we can start implementing the formula in our code. For convenience, we leave our dataframe for what it is, and iterate through all the data points just like we did before. We create a list for every possible implementation of our distance formula (Haversine or Vincenty and 2d or 3d) and add the total distance to the end of the list for every data point."
},
{
"code": null,
"e": 8109,
"s": 7932,
"text": "While we’re looping through the data points, we also create a list for the altitude difference, time difference and distance difference between all the consecutive data points."
},
{
"code": null,
"e": 9357,
"s": 8109,
"text": "alt_dif = [0]time_dif = [0]dist_vin = [0]dist_hav = [0]dist_vin_no_alt = [0]dist_hav_no_alt = [0]dist_dif_hav_2d = [0]dist_dif_vin_2d = [0]for index in range(len(data)): if index == 0: pass else: start = data[index-1] stop = data[index] distance_vin_2d = distance.vincenty((start.latitude, start.longitude), (stop.latitude, stop.longitude)).m dist_dif_vin_2d.append(distance_vin_2d) distance_hav_2d = haversine.haversine((start.latitude, start.longitude), (stop.latitude, stop.longitude))*1000dist_dif_hav_2d.append(distance_hav_2d) dist_vin_no_alt.append(dist_vin_no_alt[-1] + distance_vin_2d) dist_hav_no_alt.append(dist_hav_no_alt[-1] + distance_hav_2d) alt_d = start.elevation - stop.elevation alt_dif.append(alt_d) distance_vin_3d = sqrt(distance_vin_2d**2 + (alt_d)**2) distance_hav_3d = sqrt(distance_hav_2d**2 + (alt_d)**2) time_delta = (stop.time - start.time).total_seconds() time_dif.append(time_delta) dist_vin.append(dist_vin[-1] + distance_vin_3d) dist_hav.append(dist_hav[-1] + distance_hav_3d)"
},
{
"code": null,
"e": 9440,
"s": 9357,
"text": "For further convenience, we can pour the data in our previously created dataframe."
},
{
"code": null,
"e": 9689,
"s": 9440,
"text": "df['dis_vin_2d'] = dist_vin_no_alt df['dist_hav_2d'] = dist_hav_no_altdf['dis_vin_3d'] = dist_vindf['dis_hav_3d'] = dist_havdf['alt_dif'] = alt_difdf['time_dif'] = time_difdf['dis_dif_hav_2d'] = dist_dif_hav_2ddf['dis_dif_vin_2d'] = dist_dif_vin_2d"
},
{
"code": null,
"e": 9741,
"s": 9689,
"text": "Check the results with the following print command."
},
{
"code": null,
"e": 9992,
"s": 9741,
"text": "print('Vincenty 2D : ', dist_vin_no_alt[-1])print('Haversine 2D : ', dist_hav_no_alt[-1])print('Vincenty 3D : ', dist_vin[-1])print('Haversine 3D : ', dist_hav[-1])print('Total Time : ', floor(sum(time_dif)/60),' min ', int(sum(time_dif)%60),' sec ')"
},
{
"code": null,
"e": 10103,
"s": 9992,
"text": "The output should look like this. Let’s also compare our results with the statistics our running app shows us."
},
{
"code": null,
"e": 10402,
"s": 10103,
"text": "There are a few things to notice. Firstly, all our total distance calculations — especially the 2d ones — seem to be a good approximation of the distance our app calculated for us. Secondly, the total activity time agrees completely with our calculations, but the moving time seems to be different."
},
{
"code": null,
"e": 10655,
"s": 10402,
"text": "This can signify that whenever the distance between two data points was too small, the app has stopped the moving time, but still took the distance into account, this can be realistic when we have to slow down and stop for a traffic light, for example."
},
{
"code": null,
"e": 10832,
"s": 10655,
"text": "In this scenario our 2d calculations are right and the we can conclude the app doesn’t take elevation into account. This is indeed confirmed by a blogpost from the app company."
},
{
"code": null,
"e": 10925,
"s": 10832,
"text": "A flat surface is assumed, and vertical speed from topography is not accounted for. — Strava"
},
{
"code": null,
"e": 11257,
"s": 10925,
"text": "Worrisome? Not really. The difference between the distance proposed by the app and our maximum 3d estimate is only 61m (0.55%). This means that the total round-down for a 100km run (or ride) would by around 600m. Note that this difference will increase if you undertake more altitude-intense activities (mountain biking or hiking)."
},
{
"code": null,
"e": 11680,
"s": 11257,
"text": "Let’s see if we can figure out which threshold Strava uses to stop the timer (and therefore boost our average speed). To do so, we need to create a new variable that calculates our movement in meters per second (and not just movement per data point, hence why we created the time difference variable). Let’s do this for our haversine 2d distance, since that’s the closest approximation of the distance proposed by the app."
},
{
"code": null,
"e": 11743,
"s": 11680,
"text": "df['dist_dif_per_sec'] = df['dis_dif_hav_2d'] / df['time_dif']"
},
{
"code": null,
"e": 11932,
"s": 11743,
"text": "With this new variable we can iterate through a bunch of thresholds, let’s say between 50 cm and 1 meter, and try to figure out which one adds up to a timer time-out closest to 51 seconds."
},
{
"code": null,
"e": 12100,
"s": 11932,
"text": "for treshold in [0.5, 0.6, 0.7, 0.8, 0.9, 1]: print(treshold, 'm', ' : Time:', sum(df[df['dist_dif_per_sec'] < treshold]['time_dif']), ' seconds')"
},
{
"code": null,
"e": 12148,
"s": 12100,
"text": "Your Notebook should print something like this."
},
{
"code": null,
"e": 12445,
"s": 12148,
"text": "We can therefore conclude that if the movement per seconde was less than 80 centimeters, the application didn’t consider it as a movement and stopped the timer. This seems very reasonable, since 80 centimeters per second is about 2.9 km per hour, a speed far below most people their walking pace."
},
{
"code": null,
"e": 12726,
"s": 12445,
"text": "While talking about pace, we might as well calculate the speed for every data point. First, we create a new column in our dataframe named speed. This new variable is calculated by dividing the distance traveled in meters by the time it took in seconds, and then converted to km/h."
},
{
"code": null,
"e": 12784,
"s": 12726,
"text": "df['spd'] = (df['dis_dif_hav_2d'] / df['time_dif']) * 3.6"
},
{
"code": null,
"e": 12913,
"s": 12784,
"text": "Next, we filter out all the data where the movement per second is larger than 90 centimeters (see section above for the reason)."
},
{
"code": null,
"e": 12964,
"s": 12913,
"text": "df_with_timeout = df[df['dist_dif_per_sec'] > 0.9]"
},
{
"code": null,
"e": 13095,
"s": 12964,
"text": "Then we calculate the weighted average speed and convert it to minutes and second per kilometer (a metric widely used by runners)."
},
{
"code": null,
"e": 13346,
"s": 13095,
"text": "avg_km_h = (sum((df_with_timeout['spd'] * df_with_timeout['time_dif'])) / sum(df_with_timeout['time_dif']))print(floor(60 / avg_km_h), 'minutes', round(((60 / avg_km_h - floor(60 / avg_km_h))*60), 0), ' seconds')"
},
{
"code": null,
"e": 13633,
"s": 13346,
"text": "This results in an average speed of 5 minutes and 3 seconds per kilometer, exactly the same speed as proposed by our app. Let’s also draw a plot of our speed. Drawing a data point for every second would be to fine-grained, so we’ll draw an average speed data point for every 10 seconds."
},
{
"code": null,
"e": 13782,
"s": 13633,
"text": "Therefore, create a new variable that rounds down the cumulative sum of our time difference to 10 seconds, and plot the aggregated speed against it."
},
{
"code": null,
"e": 13931,
"s": 13782,
"text": "df['time10s'] = list(map(lambda x: round(x, -1) , np.cumsum(df['time_dif'])))plt.plot(df.groupby(['time10s']).mean()['spd'])"
},
{
"code": null,
"e": 14028,
"s": 13931,
"text": "The result is a smooth line plot where we can see the speed in km/h against the time in seconds."
},
{
"code": null,
"e": 14307,
"s": 14028,
"text": "The last metric we’ll take a closer look at, is the elevation gain. According to the apps documentation, the cumulative elevation gain refers to the sum of every gain in elevation throughout an entire trip. This means we should only take into account the positive altitude gain."
},
{
"code": null,
"e": 14403,
"s": 14307,
"text": "We can write a simple function and map it over our altitude difference column of our dataframe."
},
{
"code": null,
"e": 14542,
"s": 14403,
"text": "def positive_only(x): if x > 0: return x else: return 0pos_only = list(map(positive_only, df['alt_dif']))sum(pos_only)"
},
{
"code": null,
"e": 14731,
"s": 14542,
"text": "The sum is about 237 meters, pretty far from what our app told us we elevated (150 m). Taking a closer look to the altitude difference we can see that it’s measured down to 10 centimeters."
},
{
"code": null,
"e": 14979,
"s": 14731,
"text": "In case of running this could be jumping up and down a pavement, or scratching your head with your phone in your hand. It would make sense to round the numbers down to 1 meter. We can do this by mapping a lambda function over our previous results."
},
{
"code": null,
"e": 15027,
"s": 14979,
"text": "sum(list(map(lambda x: round(x,0) , pos_only)))"
},
{
"code": null,
"e": 15411,
"s": 15027,
"text": "The new result is 137m, pretty close to the elevation proposed by the app. Knowing this, we should also recalculate our 3d distances with these new elevation values in place. Without doing the calculations, we know that the total distance will go down and close in on the 2d distance. This makes the not taking into account of the altitude gain in total distance even more justified."
},
{
"code": null,
"e": 15661,
"s": 15411,
"text": "I’ll round up this article with a revelation about the elevation gain: I didn’t gain any altitude during the actual run (except for a few minor staircases). There is even more, my phone, just like most lower market phones, does not have a barometer."
},
{
"code": null,
"e": 15881,
"s": 15661,
"text": "A barometer is an instrument measuring atmospheric pressure, used especially in forecasting the weather and determining altitude. But how did Strava determine our altitude then? The answer is Strava’s Elevation Basemap."
},
{
"code": null,
"e": 16112,
"s": 15881,
"text": "It is created using data from the community. By collecting the barometric altimeter measurements (from devices with a barometer) from any activity uploaded to Strava in the past, they are able to build a global elevation database."
},
{
"code": null,
"e": 16424,
"s": 16112,
"text": "For now the Basemap isn’t reliable enough and doesn’t cover enough of the world. But if they can make it more reliable in the future, they might be able, in combination with 3d calculations and a more complicated model on elevation gain, to provide all you sporters out there with even more accurate statistics."
},
{
"code": null,
"e": 16559,
"s": 16424,
"text": "In a follow-up of this article we’ll visualize all the data obtained during this tutorial with another hot kid on the block: QlikView."
}
] |
Print all possible combinations of r elements in a given array of size n in C++
|
In this problem, we are given an array of size n and a positive integer r. Our
task is to print all possible combinations of the elements of the array of size
r.
Let’s take an example to understand the problem −
Input: {5,6,7,8} ; r = 3
Output : {5,6,7}, {5,6,8}, {5,7,8}, {6,7,8}
To solve this problem an approach would be fixing elements and then recuring or looping over others to find all combinations. In this, we have to fix first n-r+1 elements only and loop or recur over the rest.
#include<iostream>
using namespace std;
void printRElementCombination(int arr[], int combination[], int start, int
end, int index, int r){
if (index == r){
cout<<"{ ";
for (int j = 0; j < r; j++)
cout << combination[j] << " ";
cout<<"}\t";
return;
}
for (int i = start; i <= end && end - i + 1 >= r - index; i++){
combination[index] = arr[i];
printRElementCombination(arr, combination, i+1, end, index+1, r);
}
}
int main(){
int arr[] = {1, 2, 3, 4, 5};
int r = 3;
int n = 5;
int combination[r];
cout<<"The combination is : \n";
printRElementCombination(arr, data, 0, n-1, 0, r);
}
The combination is −
{ 1 2 3 } { 1 2 4 } { 1 2 5 } { 1 3 4 } { 1 3 5 } { 1 4 5 }
{ 2 3 4 } { 2 3 5 } { 2 4 5 } { 3 4 5 }
Other methods to solve the same problem can be by checking the inclusion of
current element in the combination and print all combinations of required
size. The idea is the same, we will recure over the element and store the combination in combo array. But the fixing of the element is not done.
The below program will make the problem more understandable to you −
Live Demo
#include <iostream>
using namespace std;
void combinationUtil(int arr[], int n, int r, int index, int combo[], int i){
if (index == r){
cout<<"{";
for (int j = 0; j < r; j++)
cout << combo[j] << " ";
cout<<"}\t";
return;
}
if (i >= n)
return;
combo[index] = arr[i];
combinationUtil(arr, n, r, index + 1, combo, i + 1);
combinationUtil(arr, n, r, index, combo, i+1);
}
int main(){
int arr[] = {1, 2, 3, 4, 5};
int r = 3;
int n = 5;
int combo[r];
cout<<"The combination is : \n";
combinationUtil(arr, n, r, 0, combo, 0);
return 0;
}
The combination is −
{1 2 3 } {1 2 4 } {1 2 5 } {1 3 4 } {1 3 5 } {1 4 5 }
{2 3 4 } {2 3 5 } {2 4 5 } {3 4 5 }
|
[
{
"code": null,
"e": 1224,
"s": 1062,
"text": "In this problem, we are given an array of size n and a positive integer r. Our\ntask is to print all possible combinations of the elements of the array of size\nr."
},
{
"code": null,
"e": 1274,
"s": 1224,
"text": "Let’s take an example to understand the problem −"
},
{
"code": null,
"e": 1343,
"s": 1274,
"text": "Input: {5,6,7,8} ; r = 3\nOutput : {5,6,7}, {5,6,8}, {5,7,8}, {6,7,8}"
},
{
"code": null,
"e": 1552,
"s": 1343,
"text": "To solve this problem an approach would be fixing elements and then recuring or looping over others to find all combinations. In this, we have to fix first n-r+1 elements only and loop or recur over the rest."
},
{
"code": null,
"e": 2212,
"s": 1552,
"text": "#include<iostream>\nusing namespace std;\nvoid printRElementCombination(int arr[], int combination[], int start, int\nend, int index, int r){\n if (index == r){\n cout<<\"{ \";\n for (int j = 0; j < r; j++)\n cout << combination[j] << \" \";\n cout<<\"}\\t\";\n return;\n }\n for (int i = start; i <= end && end - i + 1 >= r - index; i++){\n combination[index] = arr[i];\n printRElementCombination(arr, combination, i+1, end, index+1, r);\n }\n}\nint main(){\n int arr[] = {1, 2, 3, 4, 5};\n int r = 3;\n int n = 5;\n int combination[r];\n cout<<\"The combination is : \\n\";\n printRElementCombination(arr, data, 0, n-1, 0, r);\n}"
},
{
"code": null,
"e": 2233,
"s": 2212,
"text": "The combination is −"
},
{
"code": null,
"e": 2333,
"s": 2233,
"text": "{ 1 2 3 } { 1 2 4 } { 1 2 5 } { 1 3 4 } { 1 3 5 } { 1 4 5 }\n{ 2 3 4 } { 2 3 5 } { 2 4 5 } { 3 4 5 }"
},
{
"code": null,
"e": 2628,
"s": 2333,
"text": "Other methods to solve the same problem can be by checking the inclusion of\ncurrent element in the combination and print all combinations of required\nsize. The idea is the same, we will recure over the element and store the combination in combo array. But the fixing of the element is not done."
},
{
"code": null,
"e": 2697,
"s": 2628,
"text": "The below program will make the problem more understandable to you −"
},
{
"code": null,
"e": 2708,
"s": 2697,
"text": " Live Demo"
},
{
"code": null,
"e": 3323,
"s": 2708,
"text": "#include <iostream>\nusing namespace std;\nvoid combinationUtil(int arr[], int n, int r, int index, int combo[], int i){\n if (index == r){\n cout<<\"{\";\n for (int j = 0; j < r; j++)\n cout << combo[j] << \" \";\n cout<<\"}\\t\";\n return;\n }\n if (i >= n)\n return;\n combo[index] = arr[i];\n combinationUtil(arr, n, r, index + 1, combo, i + 1);\n combinationUtil(arr, n, r, index, combo, i+1);\n}\nint main(){\n int arr[] = {1, 2, 3, 4, 5};\n int r = 3;\n int n = 5;\n int combo[r];\n cout<<\"The combination is : \\n\";\n combinationUtil(arr, n, r, 0, combo, 0);\n return 0;\n}"
},
{
"code": null,
"e": 3344,
"s": 3323,
"text": "The combination is −"
},
{
"code": null,
"e": 3465,
"s": 3344,
"text": "{1 2 3 } {1 2 4 } {1 2 5 } {1 3 4 } {1 3 5 } {1 4 5 }\n {2 3 4 } {2 3 5 } {2 4 5 } {3 4 5 }"
}
] |
C# | How to get all elements of a List that match the conditions specified by the predicate - GeeksforGeeks
|
01 Feb, 2019
List<T>.FindAll(Predicate<T>) Method is used to get all the elements that match the conditions defined by the specified predicate.
Properties of List:
It is different from the arrays. A list can be resized dynamically but arrays cannot.
List class can accept null as a valid value for reference types and it also allows duplicate elements.
If the Count becomes equals to Capacity then the capacity of the List increases automatically by reallocating the internal array. The existing elements will be copied to the new array before the addition of the new element.
Syntax:
public System.Collections.Generic.List<T> FindAll (Predicate<T> match);
Parameter:
match: It is the Predicate<T> delegate that defines the conditions of the elements which is to be searched.
Return value: This method returns a List<T> containing all the elements that match the conditions defined by the specified predicate otherwise it returns an empty List<T>.
Exception: This method will give ArgumentNullException if the match is null.
Below programs illustrate the use of List<T>.FindAll(Predicate<T>) Method:
Example 1:
// C# Program to get all the element that// match the specified conditions defined// by the predicateusing System;using System.Collections;using System.Collections.Generic; class Geeks { // function which checks whether an // element is even or not. Or you can // say it is the specified condition private static bool isEven(int i) { return ((i % 2) == 0); } // Main Method public static void Main(String[] args) { // Creating an List<T> of Integers List<int> firstlist = new List<int>(); // Adding elements to List firstlist.Add(2); firstlist.Add(4); firstlist.Add(7); firstlist.Add(2); firstlist.Add(3); firstlist.Add(2); firstlist.Add(4); Console.WriteLine("Elements Present in List:\n"); // Displaying the elements of List foreach(int k in firstlist) { Console.WriteLine(k); } Console.WriteLine(" "); Console.Write("Elements that Match: \n"); // Will give the List of Elements that // match the conditions defined by predicate List<int> Result = new List<int>(firstlist.FindAll(isEven)); foreach(int i in Result) { Console.WriteLine(i); } }}
Output:
Elements Present in List:
2
4
7
2
3
2
4
Elements that Match:
2
4
2
2
4
Example 2:
// C# Program to get all the element that// match the specified conditions defined// by the predicateusing System;using System.Collections;using System.Collections.Generic; class Geeks { // function which checks whether an // element is even or not. Or you can // say it is the specified condition private static bool isEven(int i) { return ((i % 2) == 0); } // Main Method public static void Main(String[] args) { // Creating an List<T> of Integers List<int> firstlist = new List<int>(); // Adding elements to List firstlist.Add(17); firstlist.Add(77); firstlist.Add(15); firstlist.Add(9); firstlist.Add(3); firstlist.Add(7); firstlist.Add(57); Console.WriteLine("Elements Present in List:\n"); // Displaying the elements of List foreach(int k in firstlist) { Console.WriteLine(k); } Console.WriteLine(" "); Console.Write("Result is: "); // Will give the List of Elements that // match the conditions defined by predicate // Here no even number found in the list // so it wil return an empty list List<int> Result = new List<int>(firstlist.FindAll(isEven)); // checking for the resultant // Elements in the List if ((Result.Count) == 0) { Console.WriteLine("No Match Found"); } }}
Output:
Elements Present in List:
17
77
15
9
3
7
57
Result is: No Match Found
Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1.findall?view=netframework-4.7.2
CSharp-Collections-Namespace
CSharp-Generic-List
CSharp-Generic-Namespace
CSharp-method
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
C# | Delegates
Top 50 C# Interview Questions & Answers
Introduction to .NET Framework
C# | Constructors
Extension Method in C#
C# | Class and Object
C# | Abstract Classes
Common Language Runtime (CLR) in C#
C# | Encapsulation
C# | Method Overloading
|
[
{
"code": null,
"e": 24103,
"s": 24075,
"text": "\n01 Feb, 2019"
},
{
"code": null,
"e": 24234,
"s": 24103,
"text": "List<T>.FindAll(Predicate<T>) Method is used to get all the elements that match the conditions defined by the specified predicate."
},
{
"code": null,
"e": 24254,
"s": 24234,
"text": "Properties of List:"
},
{
"code": null,
"e": 24340,
"s": 24254,
"text": "It is different from the arrays. A list can be resized dynamically but arrays cannot."
},
{
"code": null,
"e": 24443,
"s": 24340,
"text": "List class can accept null as a valid value for reference types and it also allows duplicate elements."
},
{
"code": null,
"e": 24667,
"s": 24443,
"text": "If the Count becomes equals to Capacity then the capacity of the List increases automatically by reallocating the internal array. The existing elements will be copied to the new array before the addition of the new element."
},
{
"code": null,
"e": 24675,
"s": 24667,
"text": "Syntax:"
},
{
"code": null,
"e": 24747,
"s": 24675,
"text": "public System.Collections.Generic.List<T> FindAll (Predicate<T> match);"
},
{
"code": null,
"e": 24758,
"s": 24747,
"text": "Parameter:"
},
{
"code": null,
"e": 24866,
"s": 24758,
"text": "match: It is the Predicate<T> delegate that defines the conditions of the elements which is to be searched."
},
{
"code": null,
"e": 25038,
"s": 24866,
"text": "Return value: This method returns a List<T> containing all the elements that match the conditions defined by the specified predicate otherwise it returns an empty List<T>."
},
{
"code": null,
"e": 25115,
"s": 25038,
"text": "Exception: This method will give ArgumentNullException if the match is null."
},
{
"code": null,
"e": 25190,
"s": 25115,
"text": "Below programs illustrate the use of List<T>.FindAll(Predicate<T>) Method:"
},
{
"code": null,
"e": 25201,
"s": 25190,
"text": "Example 1:"
},
{
"code": "// C# Program to get all the element that// match the specified conditions defined// by the predicateusing System;using System.Collections;using System.Collections.Generic; class Geeks { // function which checks whether an // element is even or not. Or you can // say it is the specified condition private static bool isEven(int i) { return ((i % 2) == 0); } // Main Method public static void Main(String[] args) { // Creating an List<T> of Integers List<int> firstlist = new List<int>(); // Adding elements to List firstlist.Add(2); firstlist.Add(4); firstlist.Add(7); firstlist.Add(2); firstlist.Add(3); firstlist.Add(2); firstlist.Add(4); Console.WriteLine(\"Elements Present in List:\\n\"); // Displaying the elements of List foreach(int k in firstlist) { Console.WriteLine(k); } Console.WriteLine(\" \"); Console.Write(\"Elements that Match: \\n\"); // Will give the List of Elements that // match the conditions defined by predicate List<int> Result = new List<int>(firstlist.FindAll(isEven)); foreach(int i in Result) { Console.WriteLine(i); } }}",
"e": 26488,
"s": 25201,
"text": null
},
{
"code": null,
"e": 26496,
"s": 26488,
"text": "Output:"
},
{
"code": null,
"e": 26572,
"s": 26496,
"text": "Elements Present in List:\n\n2\n4\n7\n2\n3\n2\n4\n \nElements that Match: \n2\n4\n2\n2\n4\n"
},
{
"code": null,
"e": 26583,
"s": 26572,
"text": "Example 2:"
},
{
"code": "// C# Program to get all the element that// match the specified conditions defined// by the predicateusing System;using System.Collections;using System.Collections.Generic; class Geeks { // function which checks whether an // element is even or not. Or you can // say it is the specified condition private static bool isEven(int i) { return ((i % 2) == 0); } // Main Method public static void Main(String[] args) { // Creating an List<T> of Integers List<int> firstlist = new List<int>(); // Adding elements to List firstlist.Add(17); firstlist.Add(77); firstlist.Add(15); firstlist.Add(9); firstlist.Add(3); firstlist.Add(7); firstlist.Add(57); Console.WriteLine(\"Elements Present in List:\\n\"); // Displaying the elements of List foreach(int k in firstlist) { Console.WriteLine(k); } Console.WriteLine(\" \"); Console.Write(\"Result is: \"); // Will give the List of Elements that // match the conditions defined by predicate // Here no even number found in the list // so it wil return an empty list List<int> Result = new List<int>(firstlist.FindAll(isEven)); // checking for the resultant // Elements in the List if ((Result.Count) == 0) { Console.WriteLine(\"No Match Found\"); } }}",
"e": 28027,
"s": 26583,
"text": null
},
{
"code": null,
"e": 28035,
"s": 28027,
"text": "Output:"
},
{
"code": null,
"e": 28109,
"s": 28035,
"text": "Elements Present in List:\n\n17\n77\n15\n9\n3\n7\n57\n \nResult is: No Match Found\n"
},
{
"code": null,
"e": 28120,
"s": 28109,
"text": "Reference:"
},
{
"code": null,
"e": 28230,
"s": 28120,
"text": "https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1.findall?view=netframework-4.7.2"
},
{
"code": null,
"e": 28259,
"s": 28230,
"text": "CSharp-Collections-Namespace"
},
{
"code": null,
"e": 28279,
"s": 28259,
"text": "CSharp-Generic-List"
},
{
"code": null,
"e": 28304,
"s": 28279,
"text": "CSharp-Generic-Namespace"
},
{
"code": null,
"e": 28318,
"s": 28304,
"text": "CSharp-method"
},
{
"code": null,
"e": 28321,
"s": 28318,
"text": "C#"
},
{
"code": null,
"e": 28419,
"s": 28321,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28428,
"s": 28419,
"text": "Comments"
},
{
"code": null,
"e": 28441,
"s": 28428,
"text": "Old Comments"
},
{
"code": null,
"e": 28456,
"s": 28441,
"text": "C# | Delegates"
},
{
"code": null,
"e": 28496,
"s": 28456,
"text": "Top 50 C# Interview Questions & Answers"
},
{
"code": null,
"e": 28527,
"s": 28496,
"text": "Introduction to .NET Framework"
},
{
"code": null,
"e": 28545,
"s": 28527,
"text": "C# | Constructors"
},
{
"code": null,
"e": 28568,
"s": 28545,
"text": "Extension Method in C#"
},
{
"code": null,
"e": 28590,
"s": 28568,
"text": "C# | Class and Object"
},
{
"code": null,
"e": 28612,
"s": 28590,
"text": "C# | Abstract Classes"
},
{
"code": null,
"e": 28648,
"s": 28612,
"text": "Common Language Runtime (CLR) in C#"
},
{
"code": null,
"e": 28667,
"s": 28648,
"text": "C# | Encapsulation"
}
] |
p5.js | duration() Function - GeeksforGeeks
|
17 Jan, 2020
The duration() function is an inbuilt function in p5.js library. This function is used to return the duration of a sound file in seconds which is loaded the audio on the web. Basically when you trigger this function then it will return the time in the second dot microsecond format of that audio’s playing time.
Syntax:
duration()
Note: All the sound-related functions only work when the sound library is included in the head section of the index.html file.Parameter: This function does not accept any parameter.
Return Values: This function return the duration of a sound file when this function is triggered.
Below example illustrate the p5.js duration() function in JavaScript:Example:
var sound; var dur; function preload() { // Initialize sound sound = loadSound("pfivesound.mp3"); } function setup() { //Checking duration time of the audio var dur = sound.duration(); console.log(dur); // Playing the preloaded sound sound.play(); }
Output:
212.53875 // Duration of that audio approx 3 min 32 seconds
Online editor: https://editor.p5js.org/Environment Setup: https://www.geeksforgeeks.org/p5-js-soundfile-object-installation-and-methods/
Supported Browsers: The browsers supported by p5.js duration() function are listed below:
Google Chrome
Internet Explorer
Firefox
Safari
Opera
JavaScript-p5.js
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Difference between var, let and const keywords in JavaScript
Difference Between PUT and PATCH Request
JavaScript | Promises
How to get character array from string in JavaScript?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
|
[
{
"code": null,
"e": 26627,
"s": 26599,
"text": "\n17 Jan, 2020"
},
{
"code": null,
"e": 26939,
"s": 26627,
"text": "The duration() function is an inbuilt function in p5.js library. This function is used to return the duration of a sound file in seconds which is loaded the audio on the web. Basically when you trigger this function then it will return the time in the second dot microsecond format of that audio’s playing time."
},
{
"code": null,
"e": 26947,
"s": 26939,
"text": "Syntax:"
},
{
"code": null,
"e": 26958,
"s": 26947,
"text": "duration()"
},
{
"code": null,
"e": 27140,
"s": 26958,
"text": "Note: All the sound-related functions only work when the sound library is included in the head section of the index.html file.Parameter: This function does not accept any parameter."
},
{
"code": null,
"e": 27238,
"s": 27140,
"text": "Return Values: This function return the duration of a sound file when this function is triggered."
},
{
"code": null,
"e": 27316,
"s": 27238,
"text": "Below example illustrate the p5.js duration() function in JavaScript:Example:"
},
{
"code": "var sound; var dur; function preload() { // Initialize sound sound = loadSound(\"pfivesound.mp3\"); } function setup() { //Checking duration time of the audio var dur = sound.duration(); console.log(dur); // Playing the preloaded sound sound.play(); } ",
"e": 27617,
"s": 27316,
"text": null
},
{
"code": null,
"e": 27625,
"s": 27617,
"text": "Output:"
},
{
"code": null,
"e": 27685,
"s": 27625,
"text": "212.53875 // Duration of that audio approx 3 min 32 seconds"
},
{
"code": null,
"e": 27822,
"s": 27685,
"text": "Online editor: https://editor.p5js.org/Environment Setup: https://www.geeksforgeeks.org/p5-js-soundfile-object-installation-and-methods/"
},
{
"code": null,
"e": 27912,
"s": 27822,
"text": "Supported Browsers: The browsers supported by p5.js duration() function are listed below:"
},
{
"code": null,
"e": 27926,
"s": 27912,
"text": "Google Chrome"
},
{
"code": null,
"e": 27944,
"s": 27926,
"text": "Internet Explorer"
},
{
"code": null,
"e": 27952,
"s": 27944,
"text": "Firefox"
},
{
"code": null,
"e": 27959,
"s": 27952,
"text": "Safari"
},
{
"code": null,
"e": 27965,
"s": 27959,
"text": "Opera"
},
{
"code": null,
"e": 27982,
"s": 27965,
"text": "JavaScript-p5.js"
},
{
"code": null,
"e": 27993,
"s": 27982,
"text": "JavaScript"
},
{
"code": null,
"e": 28010,
"s": 27993,
"text": "Web Technologies"
},
{
"code": null,
"e": 28108,
"s": 28010,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28148,
"s": 28108,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 28209,
"s": 28148,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 28250,
"s": 28209,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 28272,
"s": 28250,
"text": "JavaScript | Promises"
},
{
"code": null,
"e": 28326,
"s": 28272,
"text": "How to get character array from string in JavaScript?"
},
{
"code": null,
"e": 28366,
"s": 28326,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 28399,
"s": 28366,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 28442,
"s": 28399,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 28504,
"s": 28442,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
}
] |
Ruby | Enumerator each_with_index function - GeeksforGeeks
|
06 Jan, 2020
The each_with_index function in Ruby is used to Iterate over the object with its index and returns value of the given object.
Syntax: A.each_with_indexHere, A is the initialised object.
Parameters: This function does not accept any parameters.
Returns: the value of the given object.
Example 1:
# Initialising an array and calling each_with_index function[5, 10, 15, 20, 25, 30].each_with_index do |num, idx| # Getting the values of the array puts "#{num}" if ((idx) % 2 == 0) puts "end of line" end end
Output:
5
end of line
10
15
end of line
20
25
end of line
30
Example 2:
# Initialising an array and calling each_with_index function[5, 10, 15, 20, 25, 30].each_with_index do |num, idx| # Getting the values of the array puts "#{num}" if ((idx + 1) % 2 == 0) puts "end of line" end end
Output:
5
10
end of line
15
20
end of line
25
30
end of line
Ruby Enumerable-class
Ruby-Methods
Ruby
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Ruby | Array count() operation
Ruby | Array slice() function
Include v/s Extend in Ruby
Global Variable in Ruby
Ruby | Hash delete() function
Ruby | Types of Variables
Ruby | Case Statement
Ruby | Array select() function
Ruby | Numeric round() function
Ruby | Data Types
|
[
{
"code": null,
"e": 25115,
"s": 25087,
"text": "\n06 Jan, 2020"
},
{
"code": null,
"e": 25241,
"s": 25115,
"text": "The each_with_index function in Ruby is used to Iterate over the object with its index and returns value of the given object."
},
{
"code": null,
"e": 25301,
"s": 25241,
"text": "Syntax: A.each_with_indexHere, A is the initialised object."
},
{
"code": null,
"e": 25359,
"s": 25301,
"text": "Parameters: This function does not accept any parameters."
},
{
"code": null,
"e": 25399,
"s": 25359,
"text": "Returns: the value of the given object."
},
{
"code": null,
"e": 25410,
"s": 25399,
"text": "Example 1:"
},
{
"code": "# Initialising an array and calling each_with_index function[5, 10, 15, 20, 25, 30].each_with_index do |num, idx| # Getting the values of the array puts \"#{num}\" if ((idx) % 2 == 0) puts \"end of line\" end end ",
"e": 25636,
"s": 25410,
"text": null
},
{
"code": null,
"e": 25644,
"s": 25636,
"text": "Output:"
},
{
"code": null,
"e": 25697,
"s": 25644,
"text": "5\nend of line\n10\n15\nend of line\n20\n25\nend of line\n30"
},
{
"code": null,
"e": 25708,
"s": 25697,
"text": "Example 2:"
},
{
"code": "# Initialising an array and calling each_with_index function[5, 10, 15, 20, 25, 30].each_with_index do |num, idx| # Getting the values of the array puts \"#{num}\" if ((idx + 1) % 2 == 0) puts \"end of line\" end end ",
"e": 25938,
"s": 25708,
"text": null
},
{
"code": null,
"e": 25946,
"s": 25938,
"text": "Output:"
},
{
"code": null,
"e": 26000,
"s": 25946,
"text": "5\n10\nend of line\n15\n20\nend of line\n25\n30\nend of line\n"
},
{
"code": null,
"e": 26022,
"s": 26000,
"text": "Ruby Enumerable-class"
},
{
"code": null,
"e": 26035,
"s": 26022,
"text": "Ruby-Methods"
},
{
"code": null,
"e": 26040,
"s": 26035,
"text": "Ruby"
},
{
"code": null,
"e": 26138,
"s": 26040,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26169,
"s": 26138,
"text": "Ruby | Array count() operation"
},
{
"code": null,
"e": 26199,
"s": 26169,
"text": "Ruby | Array slice() function"
},
{
"code": null,
"e": 26226,
"s": 26199,
"text": "Include v/s Extend in Ruby"
},
{
"code": null,
"e": 26250,
"s": 26226,
"text": "Global Variable in Ruby"
},
{
"code": null,
"e": 26280,
"s": 26250,
"text": "Ruby | Hash delete() function"
},
{
"code": null,
"e": 26306,
"s": 26280,
"text": "Ruby | Types of Variables"
},
{
"code": null,
"e": 26328,
"s": 26306,
"text": "Ruby | Case Statement"
},
{
"code": null,
"e": 26359,
"s": 26328,
"text": "Ruby | Array select() function"
},
{
"code": null,
"e": 26391,
"s": 26359,
"text": "Ruby | Numeric round() function"
}
] |
Node.js os.constants - GeeksforGeeks
|
01 Feb, 2022
The os.constants is an inbuilt application programming interface of the os module which is used to get operating system specified constants for error code, signal constants, priority constant, dlopen constants, etc.Syntax:
os.constants
Return Value: It returns an object that contains operating system specified constants. Example: error codes, signal constants, priority constant, dlopen constants, etc.Signal constants can be accessed by using os.constants.signals and priority constants can be accessed by using os.constants.priority. Some of the constants are listed below:Signal Constants:
Error constants: 1. POSIX error constant
2. Windows specific error
dlopen Constants:
Priority constants:
libuv Constants:
Below examples illustrate the use of os.constants in Node.js:Example 1:
javascript
// Import os moduleconst os = require('os'); constants = os.constants; // Printing all os.constantsconsole.log(constants);
Output:
[Object: null prototype] {
UV_UDP_REUSEADDR: 4,
dlopen: [Object: null prototype] {},
errno:
[Object: null prototype] {
E2BIG: 7,
EACCES: 13,
EADDRINUSE: 100,
. . .
PRIORITY_HIGH: -14,
PRIORITY_HIGHEST: -20 } }
Example 2:
javascript
// Import os moduleconst os = require('os'); constants = os.constants; // Printing os.constants // Signals constantsif(constants.signals != undefined){ console.log("Signals:"); console.log(constants.signals);} // Priority constantsif(constants.priority!=undefined){ console.log("priority:"); console.log(constants.priority);}
Output:
Signals:
[Object: null prototype] {
SIGHUP: 1,
SIGINT: 2,
. . .
PRIORITY_HIGH: -14,
PRIORITY_HIGHEST: -20 }
Note: The above program will compile and run by using the node index.js command.Reference: https://nodejs.org/api/os.html#os_os_constants
avtarkumar719
Node.js-os-module
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to install the previous version of node.js and npm ?
Difference between promise and async await in Node.js
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 ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
|
[
{
"code": null,
"e": 25781,
"s": 25753,
"text": "\n01 Feb, 2022"
},
{
"code": null,
"e": 26006,
"s": 25781,
"text": "The os.constants is an inbuilt application programming interface of the os module which is used to get operating system specified constants for error code, signal constants, priority constant, dlopen constants, etc.Syntax: "
},
{
"code": null,
"e": 26019,
"s": 26006,
"text": "os.constants"
},
{
"code": null,
"e": 26380,
"s": 26019,
"text": "Return Value: It returns an object that contains operating system specified constants. Example: error codes, signal constants, priority constant, dlopen constants, etc.Signal constants can be accessed by using os.constants.signals and priority constants can be accessed by using os.constants.priority. Some of the constants are listed below:Signal Constants: "
},
{
"code": null,
"e": 26423,
"s": 26380,
"text": "Error constants: 1. POSIX error constant "
},
{
"code": null,
"e": 26451,
"s": 26423,
"text": "2. Windows specific error "
},
{
"code": null,
"e": 26471,
"s": 26451,
"text": "dlopen Constants: "
},
{
"code": null,
"e": 26493,
"s": 26471,
"text": "Priority constants: "
},
{
"code": null,
"e": 26512,
"s": 26493,
"text": "libuv Constants: "
},
{
"code": null,
"e": 26586,
"s": 26512,
"text": "Below examples illustrate the use of os.constants in Node.js:Example 1: "
},
{
"code": null,
"e": 26597,
"s": 26586,
"text": "javascript"
},
{
"code": "// Import os moduleconst os = require('os'); constants = os.constants; // Printing all os.constantsconsole.log(constants);",
"e": 26720,
"s": 26597,
"text": null
},
{
"code": null,
"e": 26730,
"s": 26720,
"text": "Output: "
},
{
"code": null,
"e": 26979,
"s": 26730,
"text": "[Object: null prototype] {\n UV_UDP_REUSEADDR: 4,\n dlopen: [Object: null prototype] {},\n errno:\n [Object: null prototype] {\n E2BIG: 7,\n EACCES: 13,\n EADDRINUSE: 100,\n . . .\n PRIORITY_HIGH: -14,\n PRIORITY_HIGHEST: -20 } }"
},
{
"code": null,
"e": 26992,
"s": 26979,
"text": "Example 2: "
},
{
"code": null,
"e": 27003,
"s": 26992,
"text": "javascript"
},
{
"code": "// Import os moduleconst os = require('os'); constants = os.constants; // Printing os.constants // Signals constantsif(constants.signals != undefined){ console.log(\"Signals:\"); console.log(constants.signals);} // Priority constantsif(constants.priority!=undefined){ console.log(\"priority:\"); console.log(constants.priority);}",
"e": 27341,
"s": 27003,
"text": null
},
{
"code": null,
"e": 27351,
"s": 27341,
"text": "Output: "
},
{
"code": null,
"e": 27469,
"s": 27351,
"text": "Signals:\n[Object: null prototype] {\n SIGHUP: 1,\n SIGINT: 2,\n . . .\n PRIORITY_HIGH: -14,\n PRIORITY_HIGHEST: -20 }"
},
{
"code": null,
"e": 27608,
"s": 27469,
"text": "Note: The above program will compile and run by using the node index.js command.Reference: https://nodejs.org/api/os.html#os_os_constants "
},
{
"code": null,
"e": 27622,
"s": 27608,
"text": "avtarkumar719"
},
{
"code": null,
"e": 27640,
"s": 27622,
"text": "Node.js-os-module"
},
{
"code": null,
"e": 27648,
"s": 27640,
"text": "Node.js"
},
{
"code": null,
"e": 27665,
"s": 27648,
"text": "Web Technologies"
},
{
"code": null,
"e": 27763,
"s": 27665,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27820,
"s": 27763,
"text": "How to install the previous version of node.js and npm ?"
},
{
"code": null,
"e": 27874,
"s": 27820,
"text": "Difference between promise and async await in Node.js"
},
{
"code": null,
"e": 27911,
"s": 27874,
"text": "How to use an ES6 import in Node.js?"
},
{
"code": null,
"e": 27951,
"s": 27911,
"text": "Mongoose | findByIdAndUpdate() Function"
},
{
"code": null,
"e": 27984,
"s": 27951,
"text": "Express.js res.render() Function"
},
{
"code": null,
"e": 28024,
"s": 27984,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 28069,
"s": 28024,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 28112,
"s": 28069,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 28174,
"s": 28112,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
}
] |
How to pad a String in Java - GeeksforGeeks
|
04 Apr, 2020
Given a string str of some specific length, the task is to pad this string with the given character ch, inorder to make the string of length L.
Note: Padding has to be done in all three formats: Left Padding, Right Padding and Center Padding.
Example:
Input: str = “Geeksforgeeks”, ch =’-‘, L = 20Output:Left Padding: ————GeeksForGeeksCenter Padding: ——GeeksForGeeks——Right Padding: GeeksForGeeks————
Input: str = “GfG”, ch =’#’, L = 5Output:Left Padding: ##GfGCenter Padding: #GfG#Right Padding: GfG##
There are many methods to pad a String:
Using String format() method: This method is used to return a formatted string using the given locale, specified format string and arguments.Note: This method can be used to do only left and right padding.Approach:Get the string in which padding is done.Use the String.format() method to pad the string with spaces on left and right, and then replace these spaces with the given character using String.replace() method.For left padding, the syntax to use the String.format() method is:String.format("%[L]s", str).replace(' ', ch);
For right padding, the syntax to use the String.format() method is:String.format("%-[L]s", str).replace(' ', ch);
If the length ‘L’ is less than initial length of the string, then the same string is returned unaltered.Below is the implementation of the above approach:Example:// Java implementation to pad a String import java.lang.*;import java.io.*; public class GFG { // Function to perform left padding public static String leftPadding(String input, char ch, int L) { String result = String // First left pad the string // with space up to length L .format("%" + L + "s", input) // Then replace all the spaces // with the given character ch .replace(' ', ch); // Return the resultant string return result; } // Function to perform right padding public static String rightPadding(String input, char ch, int L) { String result = String // First right pad the string // with space up to length L .format("%" + (-L) + "s", input) // Then replace all the spaces // with the given character ch .replace(' ', ch); // Return the resultant string return result; } // Driver code public static void main(String[] args) { String str = "GeeksForGeeks"; char ch = '-'; int L = 20; System.out.println( leftPadding(str, ch, L)); System.out.println( rightPadding(str, ch, L)); }}Output:-------GeeksForGeeks
GeeksForGeeks-------
Using Apache Common Lang: Apache Commons Lang package provides the StringUtils class, which contains the leftPad(), center() and rightPad() method to easily left pad, center pad and right pad a String respectively.Note: This module has to be installed before running of the code. Hence this code won’t run on Online compilers.Approach:Get the string in which padding is done.For left padding, the syntax to use the StringUtils.leftPad() method is:StringUtils.leftPad(str, L, ch);
For center padding, the syntax to use the StringUtils.center() method is:StringUtils.center(str, L, ch);
For right padding, the syntax to use the StringUtils.rightPad() method is:StringUtils.rightPad(str, L, ch);
If the length ‘L’ is less than initial length of the string, then the same string is returned unaltered.Below is the implementation of the above approach:Example:// Java implementation to pad a String import java.lang.*;import java.io.*; public class GFG { // Function to perform left padding public static String leftPadding(String input, char ch, int L) { // Left pad the string String result = StringUtils.leftPad(str, L, ch); // Return the resultant string return result; } // Function to perform center padding public static String centerPadding(String input, char ch, int L) { // Center pad the string String result = StringUtils.center(str, L, ch); // Return the resultant string return result; } // Function to perform right padding public static String rightPadding(String input, char ch, int L) { // Right pad the string String result = StringUtils.rightPad(str, L, ch); // Return the resultant string return result; } // Driver code public static void main(String[] args) { String str = "GeeksForGeeks"; char ch = '-'; int L = 20; System.out.println( leftPadding(str, ch, L)); System.out.println( centerPadding(str, ch, L)); System.out.println( rightPadding(str, ch, L)); }}Output:-------GeeksForGeeks
---GeeksForGeeks----
GeeksForGeeks-------
Using String format() method: This method is used to return a formatted string using the given locale, specified format string and arguments.Note: This method can be used to do only left and right padding.Approach:Get the string in which padding is done.Use the String.format() method to pad the string with spaces on left and right, and then replace these spaces with the given character using String.replace() method.For left padding, the syntax to use the String.format() method is:String.format("%[L]s", str).replace(' ', ch);
For right padding, the syntax to use the String.format() method is:String.format("%-[L]s", str).replace(' ', ch);
If the length ‘L’ is less than initial length of the string, then the same string is returned unaltered.Below is the implementation of the above approach:Example:// Java implementation to pad a String import java.lang.*;import java.io.*; public class GFG { // Function to perform left padding public static String leftPadding(String input, char ch, int L) { String result = String // First left pad the string // with space up to length L .format("%" + L + "s", input) // Then replace all the spaces // with the given character ch .replace(' ', ch); // Return the resultant string return result; } // Function to perform right padding public static String rightPadding(String input, char ch, int L) { String result = String // First right pad the string // with space up to length L .format("%" + (-L) + "s", input) // Then replace all the spaces // with the given character ch .replace(' ', ch); // Return the resultant string return result; } // Driver code public static void main(String[] args) { String str = "GeeksForGeeks"; char ch = '-'; int L = 20; System.out.println( leftPadding(str, ch, L)); System.out.println( rightPadding(str, ch, L)); }}Output:-------GeeksForGeeks
GeeksForGeeks-------
Note: This method can be used to do only left and right padding.
Approach:
Get the string in which padding is done.
Use the String.format() method to pad the string with spaces on left and right, and then replace these spaces with the given character using String.replace() method.
For left padding, the syntax to use the String.format() method is:String.format("%[L]s", str).replace(' ', ch);
String.format("%[L]s", str).replace(' ', ch);
For right padding, the syntax to use the String.format() method is:String.format("%-[L]s", str).replace(' ', ch);
String.format("%-[L]s", str).replace(' ', ch);
If the length ‘L’ is less than initial length of the string, then the same string is returned unaltered.
Below is the implementation of the above approach:
Example:
// Java implementation to pad a String import java.lang.*;import java.io.*; public class GFG { // Function to perform left padding public static String leftPadding(String input, char ch, int L) { String result = String // First left pad the string // with space up to length L .format("%" + L + "s", input) // Then replace all the spaces // with the given character ch .replace(' ', ch); // Return the resultant string return result; } // Function to perform right padding public static String rightPadding(String input, char ch, int L) { String result = String // First right pad the string // with space up to length L .format("%" + (-L) + "s", input) // Then replace all the spaces // with the given character ch .replace(' ', ch); // Return the resultant string return result; } // Driver code public static void main(String[] args) { String str = "GeeksForGeeks"; char ch = '-'; int L = 20; System.out.println( leftPadding(str, ch, L)); System.out.println( rightPadding(str, ch, L)); }}
-------GeeksForGeeks
GeeksForGeeks-------
Using Apache Common Lang: Apache Commons Lang package provides the StringUtils class, which contains the leftPad(), center() and rightPad() method to easily left pad, center pad and right pad a String respectively.Note: This module has to be installed before running of the code. Hence this code won’t run on Online compilers.Approach:Get the string in which padding is done.For left padding, the syntax to use the StringUtils.leftPad() method is:StringUtils.leftPad(str, L, ch);
For center padding, the syntax to use the StringUtils.center() method is:StringUtils.center(str, L, ch);
For right padding, the syntax to use the StringUtils.rightPad() method is:StringUtils.rightPad(str, L, ch);
If the length ‘L’ is less than initial length of the string, then the same string is returned unaltered.Below is the implementation of the above approach:Example:// Java implementation to pad a String import java.lang.*;import java.io.*; public class GFG { // Function to perform left padding public static String leftPadding(String input, char ch, int L) { // Left pad the string String result = StringUtils.leftPad(str, L, ch); // Return the resultant string return result; } // Function to perform center padding public static String centerPadding(String input, char ch, int L) { // Center pad the string String result = StringUtils.center(str, L, ch); // Return the resultant string return result; } // Function to perform right padding public static String rightPadding(String input, char ch, int L) { // Right pad the string String result = StringUtils.rightPad(str, L, ch); // Return the resultant string return result; } // Driver code public static void main(String[] args) { String str = "GeeksForGeeks"; char ch = '-'; int L = 20; System.out.println( leftPadding(str, ch, L)); System.out.println( centerPadding(str, ch, L)); System.out.println( rightPadding(str, ch, L)); }}Output:-------GeeksForGeeks
---GeeksForGeeks----
GeeksForGeeks-------
Note: This module has to be installed before running of the code. Hence this code won’t run on Online compilers.
Approach:
Get the string in which padding is done.
For left padding, the syntax to use the StringUtils.leftPad() method is:StringUtils.leftPad(str, L, ch);
StringUtils.leftPad(str, L, ch);
For center padding, the syntax to use the StringUtils.center() method is:StringUtils.center(str, L, ch);
StringUtils.center(str, L, ch);
For right padding, the syntax to use the StringUtils.rightPad() method is:StringUtils.rightPad(str, L, ch);
StringUtils.rightPad(str, L, ch);
If the length ‘L’ is less than initial length of the string, then the same string is returned unaltered.
Below is the implementation of the above approach:
Example:
// Java implementation to pad a String import java.lang.*;import java.io.*; public class GFG { // Function to perform left padding public static String leftPadding(String input, char ch, int L) { // Left pad the string String result = StringUtils.leftPad(str, L, ch); // Return the resultant string return result; } // Function to perform center padding public static String centerPadding(String input, char ch, int L) { // Center pad the string String result = StringUtils.center(str, L, ch); // Return the resultant string return result; } // Function to perform right padding public static String rightPadding(String input, char ch, int L) { // Right pad the string String result = StringUtils.rightPad(str, L, ch); // Return the resultant string return result; } // Driver code public static void main(String[] args) { String str = "GeeksForGeeks"; char ch = '-'; int L = 20; System.out.println( leftPadding(str, ch, L)); System.out.println( centerPadding(str, ch, L)); System.out.println( rightPadding(str, ch, L)); }}
-------GeeksForGeeks
---GeeksForGeeks----
GeeksForGeeks-------
Java-String-Programs
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
HashMap in Java with Examples
Stream In Java
Interfaces 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": 26145,
"s": 26117,
"text": "\n04 Apr, 2020"
},
{
"code": null,
"e": 26289,
"s": 26145,
"text": "Given a string str of some specific length, the task is to pad this string with the given character ch, inorder to make the string of length L."
},
{
"code": null,
"e": 26388,
"s": 26289,
"text": "Note: Padding has to be done in all three formats: Left Padding, Right Padding and Center Padding."
},
{
"code": null,
"e": 26397,
"s": 26388,
"text": "Example:"
},
{
"code": null,
"e": 26546,
"s": 26397,
"text": "Input: str = “Geeksforgeeks”, ch =’-‘, L = 20Output:Left Padding: ————GeeksForGeeksCenter Padding: ——GeeksForGeeks——Right Padding: GeeksForGeeks————"
},
{
"code": null,
"e": 26648,
"s": 26546,
"text": "Input: str = “GfG”, ch =’#’, L = 5Output:Left Padding: ##GfGCenter Padding: #GfG#Right Padding: GfG##"
},
{
"code": null,
"e": 26688,
"s": 26648,
"text": "There are many methods to pad a String:"
},
{
"code": null,
"e": 31154,
"s": 26688,
"text": "Using String format() method: This method is used to return a formatted string using the given locale, specified format string and arguments.Note: This method can be used to do only left and right padding.Approach:Get the string in which padding is done.Use the String.format() method to pad the string with spaces on left and right, and then replace these spaces with the given character using String.replace() method.For left padding, the syntax to use the String.format() method is:String.format(\"%[L]s\", str).replace(' ', ch);\nFor right padding, the syntax to use the String.format() method is:String.format(\"%-[L]s\", str).replace(' ', ch);\nIf the length ‘L’ is less than initial length of the string, then the same string is returned unaltered.Below is the implementation of the above approach:Example:// Java implementation to pad a String import java.lang.*;import java.io.*; public class GFG { // Function to perform left padding public static String leftPadding(String input, char ch, int L) { String result = String // First left pad the string // with space up to length L .format(\"%\" + L + \"s\", input) // Then replace all the spaces // with the given character ch .replace(' ', ch); // Return the resultant string return result; } // Function to perform right padding public static String rightPadding(String input, char ch, int L) { String result = String // First right pad the string // with space up to length L .format(\"%\" + (-L) + \"s\", input) // Then replace all the spaces // with the given character ch .replace(' ', ch); // Return the resultant string return result; } // Driver code public static void main(String[] args) { String str = \"GeeksForGeeks\"; char ch = '-'; int L = 20; System.out.println( leftPadding(str, ch, L)); System.out.println( rightPadding(str, ch, L)); }}Output:-------GeeksForGeeks\nGeeksForGeeks-------\nUsing Apache Common Lang: Apache Commons Lang package provides the StringUtils class, which contains the leftPad(), center() and rightPad() method to easily left pad, center pad and right pad a String respectively.Note: This module has to be installed before running of the code. Hence this code won’t run on Online compilers.Approach:Get the string in which padding is done.For left padding, the syntax to use the StringUtils.leftPad() method is:StringUtils.leftPad(str, L, ch);\nFor center padding, the syntax to use the StringUtils.center() method is:StringUtils.center(str, L, ch);\nFor right padding, the syntax to use the StringUtils.rightPad() method is:StringUtils.rightPad(str, L, ch);\nIf the length ‘L’ is less than initial length of the string, then the same string is returned unaltered.Below is the implementation of the above approach:Example:// Java implementation to pad a String import java.lang.*;import java.io.*; public class GFG { // Function to perform left padding public static String leftPadding(String input, char ch, int L) { // Left pad the string String result = StringUtils.leftPad(str, L, ch); // Return the resultant string return result; } // Function to perform center padding public static String centerPadding(String input, char ch, int L) { // Center pad the string String result = StringUtils.center(str, L, ch); // Return the resultant string return result; } // Function to perform right padding public static String rightPadding(String input, char ch, int L) { // Right pad the string String result = StringUtils.rightPad(str, L, ch); // Return the resultant string return result; } // Driver code public static void main(String[] args) { String str = \"GeeksForGeeks\"; char ch = '-'; int L = 20; System.out.println( leftPadding(str, ch, L)); System.out.println( centerPadding(str, ch, L)); System.out.println( rightPadding(str, ch, L)); }}Output:-------GeeksForGeeks\n---GeeksForGeeks----\nGeeksForGeeks-------\n"
},
{
"code": null,
"e": 33397,
"s": 31154,
"text": "Using String format() method: This method is used to return a formatted string using the given locale, specified format string and arguments.Note: This method can be used to do only left and right padding.Approach:Get the string in which padding is done.Use the String.format() method to pad the string with spaces on left and right, and then replace these spaces with the given character using String.replace() method.For left padding, the syntax to use the String.format() method is:String.format(\"%[L]s\", str).replace(' ', ch);\nFor right padding, the syntax to use the String.format() method is:String.format(\"%-[L]s\", str).replace(' ', ch);\nIf the length ‘L’ is less than initial length of the string, then the same string is returned unaltered.Below is the implementation of the above approach:Example:// Java implementation to pad a String import java.lang.*;import java.io.*; public class GFG { // Function to perform left padding public static String leftPadding(String input, char ch, int L) { String result = String // First left pad the string // with space up to length L .format(\"%\" + L + \"s\", input) // Then replace all the spaces // with the given character ch .replace(' ', ch); // Return the resultant string return result; } // Function to perform right padding public static String rightPadding(String input, char ch, int L) { String result = String // First right pad the string // with space up to length L .format(\"%\" + (-L) + \"s\", input) // Then replace all the spaces // with the given character ch .replace(' ', ch); // Return the resultant string return result; } // Driver code public static void main(String[] args) { String str = \"GeeksForGeeks\"; char ch = '-'; int L = 20; System.out.println( leftPadding(str, ch, L)); System.out.println( rightPadding(str, ch, L)); }}Output:-------GeeksForGeeks\nGeeksForGeeks-------\n"
},
{
"code": null,
"e": 33462,
"s": 33397,
"text": "Note: This method can be used to do only left and right padding."
},
{
"code": null,
"e": 33472,
"s": 33462,
"text": "Approach:"
},
{
"code": null,
"e": 33513,
"s": 33472,
"text": "Get the string in which padding is done."
},
{
"code": null,
"e": 33679,
"s": 33513,
"text": "Use the String.format() method to pad the string with spaces on left and right, and then replace these spaces with the given character using String.replace() method."
},
{
"code": null,
"e": 33792,
"s": 33679,
"text": "For left padding, the syntax to use the String.format() method is:String.format(\"%[L]s\", str).replace(' ', ch);\n"
},
{
"code": null,
"e": 33839,
"s": 33792,
"text": "String.format(\"%[L]s\", str).replace(' ', ch);\n"
},
{
"code": null,
"e": 33954,
"s": 33839,
"text": "For right padding, the syntax to use the String.format() method is:String.format(\"%-[L]s\", str).replace(' ', ch);\n"
},
{
"code": null,
"e": 34002,
"s": 33954,
"text": "String.format(\"%-[L]s\", str).replace(' ', ch);\n"
},
{
"code": null,
"e": 34107,
"s": 34002,
"text": "If the length ‘L’ is less than initial length of the string, then the same string is returned unaltered."
},
{
"code": null,
"e": 34158,
"s": 34107,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 34167,
"s": 34158,
"text": "Example:"
},
{
"code": "// Java implementation to pad a String import java.lang.*;import java.io.*; public class GFG { // Function to perform left padding public static String leftPadding(String input, char ch, int L) { String result = String // First left pad the string // with space up to length L .format(\"%\" + L + \"s\", input) // Then replace all the spaces // with the given character ch .replace(' ', ch); // Return the resultant string return result; } // Function to perform right padding public static String rightPadding(String input, char ch, int L) { String result = String // First right pad the string // with space up to length L .format(\"%\" + (-L) + \"s\", input) // Then replace all the spaces // with the given character ch .replace(' ', ch); // Return the resultant string return result; } // Driver code public static void main(String[] args) { String str = \"GeeksForGeeks\"; char ch = '-'; int L = 20; System.out.println( leftPadding(str, ch, L)); System.out.println( rightPadding(str, ch, L)); }}",
"e": 35554,
"s": 34167,
"text": null
},
{
"code": null,
"e": 35597,
"s": 35554,
"text": "-------GeeksForGeeks\nGeeksForGeeks-------\n"
},
{
"code": null,
"e": 37821,
"s": 35597,
"text": "Using Apache Common Lang: Apache Commons Lang package provides the StringUtils class, which contains the leftPad(), center() and rightPad() method to easily left pad, center pad and right pad a String respectively.Note: This module has to be installed before running of the code. Hence this code won’t run on Online compilers.Approach:Get the string in which padding is done.For left padding, the syntax to use the StringUtils.leftPad() method is:StringUtils.leftPad(str, L, ch);\nFor center padding, the syntax to use the StringUtils.center() method is:StringUtils.center(str, L, ch);\nFor right padding, the syntax to use the StringUtils.rightPad() method is:StringUtils.rightPad(str, L, ch);\nIf the length ‘L’ is less than initial length of the string, then the same string is returned unaltered.Below is the implementation of the above approach:Example:// Java implementation to pad a String import java.lang.*;import java.io.*; public class GFG { // Function to perform left padding public static String leftPadding(String input, char ch, int L) { // Left pad the string String result = StringUtils.leftPad(str, L, ch); // Return the resultant string return result; } // Function to perform center padding public static String centerPadding(String input, char ch, int L) { // Center pad the string String result = StringUtils.center(str, L, ch); // Return the resultant string return result; } // Function to perform right padding public static String rightPadding(String input, char ch, int L) { // Right pad the string String result = StringUtils.rightPad(str, L, ch); // Return the resultant string return result; } // Driver code public static void main(String[] args) { String str = \"GeeksForGeeks\"; char ch = '-'; int L = 20; System.out.println( leftPadding(str, ch, L)); System.out.println( centerPadding(str, ch, L)); System.out.println( rightPadding(str, ch, L)); }}Output:-------GeeksForGeeks\n---GeeksForGeeks----\nGeeksForGeeks-------\n"
},
{
"code": null,
"e": 37934,
"s": 37821,
"text": "Note: This module has to be installed before running of the code. Hence this code won’t run on Online compilers."
},
{
"code": null,
"e": 37944,
"s": 37934,
"text": "Approach:"
},
{
"code": null,
"e": 37985,
"s": 37944,
"text": "Get the string in which padding is done."
},
{
"code": null,
"e": 38091,
"s": 37985,
"text": "For left padding, the syntax to use the StringUtils.leftPad() method is:StringUtils.leftPad(str, L, ch);\n"
},
{
"code": null,
"e": 38125,
"s": 38091,
"text": "StringUtils.leftPad(str, L, ch);\n"
},
{
"code": null,
"e": 38231,
"s": 38125,
"text": "For center padding, the syntax to use the StringUtils.center() method is:StringUtils.center(str, L, ch);\n"
},
{
"code": null,
"e": 38264,
"s": 38231,
"text": "StringUtils.center(str, L, ch);\n"
},
{
"code": null,
"e": 38373,
"s": 38264,
"text": "For right padding, the syntax to use the StringUtils.rightPad() method is:StringUtils.rightPad(str, L, ch);\n"
},
{
"code": null,
"e": 38408,
"s": 38373,
"text": "StringUtils.rightPad(str, L, ch);\n"
},
{
"code": null,
"e": 38513,
"s": 38408,
"text": "If the length ‘L’ is less than initial length of the string, then the same string is returned unaltered."
},
{
"code": null,
"e": 38564,
"s": 38513,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 38573,
"s": 38564,
"text": "Example:"
},
{
"code": "// Java implementation to pad a String import java.lang.*;import java.io.*; public class GFG { // Function to perform left padding public static String leftPadding(String input, char ch, int L) { // Left pad the string String result = StringUtils.leftPad(str, L, ch); // Return the resultant string return result; } // Function to perform center padding public static String centerPadding(String input, char ch, int L) { // Center pad the string String result = StringUtils.center(str, L, ch); // Return the resultant string return result; } // Function to perform right padding public static String rightPadding(String input, char ch, int L) { // Right pad the string String result = StringUtils.rightPad(str, L, ch); // Return the resultant string return result; } // Driver code public static void main(String[] args) { String str = \"GeeksForGeeks\"; char ch = '-'; int L = 20; System.out.println( leftPadding(str, ch, L)); System.out.println( centerPadding(str, ch, L)); System.out.println( rightPadding(str, ch, L)); }}",
"e": 39872,
"s": 38573,
"text": null
},
{
"code": null,
"e": 39936,
"s": 39872,
"text": "-------GeeksForGeeks\n---GeeksForGeeks----\nGeeksForGeeks-------\n"
},
{
"code": null,
"e": 39957,
"s": 39936,
"text": "Java-String-Programs"
},
{
"code": null,
"e": 39962,
"s": 39957,
"text": "Java"
},
{
"code": null,
"e": 39967,
"s": 39962,
"text": "Java"
},
{
"code": null,
"e": 40065,
"s": 39967,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 40116,
"s": 40065,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 40146,
"s": 40116,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 40161,
"s": 40146,
"text": "Stream In Java"
},
{
"code": null,
"e": 40180,
"s": 40161,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 40211,
"s": 40180,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 40229,
"s": 40211,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 40261,
"s": 40229,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 40281,
"s": 40261,
"text": "Stack Class in Java"
},
{
"code": null,
"e": 40313,
"s": 40281,
"text": "Multidimensional Arrays in Java"
}
] |
How to check if a variable is an array in JavaScript? - GeeksforGeeks
|
20 Jul, 2021
In JavaScript, we can check if a variable is an array by using 3 methods, using the isArray method, using the instanceof operator and using checking the constructor type if it matches an Array object.
Method 1: Using the isArray methodThe Array.isArray() method checks whether the passed variable is an Array object.Syntax:Array.isArray(variableName)It returns a true boolean value if the variable is an array and false if it is not. This is shown in the example below.Example-1:<!DOCTYPE html><html lang="en"> <head> <title> How to check if a variable is an array in JavaScript? </title></head> <body> <h1 style="color: green"> GeeksforGeeks </h1> <b> How to check if a variable is an array in JavaScript? </b> <p> Click on the button to check if the variable is an array </p> <p>Output for string: <div class="outputString"> </div> <p>Output for number: <div class="outputNumber"> </div> <p>Output for array: <div class="outputArray"> </div> <button onclick="checkArray()"> Click here </button> <script type="text/javascript"> function checkArray() { let str = 'This is a string'; let num = 25; let arr = [10, 20, 30, 40]; ans = Array.isArray(str); document.querySelector( '.outputString').textContent = ans; ans = Array.isArray(num); document.querySelector( '.outputNumber').textContent = ans; ans = Array.isArray(arr); document.querySelector( '.outputArray').textContent = ans; } </script></body> </html>Output:
The Array.isArray() method checks whether the passed variable is an Array object.
Syntax:
Array.isArray(variableName)
It returns a true boolean value if the variable is an array and false if it is not. This is shown in the example below.
Example-1:
<!DOCTYPE html><html lang="en"> <head> <title> How to check if a variable is an array in JavaScript? </title></head> <body> <h1 style="color: green"> GeeksforGeeks </h1> <b> How to check if a variable is an array in JavaScript? </b> <p> Click on the button to check if the variable is an array </p> <p>Output for string: <div class="outputString"> </div> <p>Output for number: <div class="outputNumber"> </div> <p>Output for array: <div class="outputArray"> </div> <button onclick="checkArray()"> Click here </button> <script type="text/javascript"> function checkArray() { let str = 'This is a string'; let num = 25; let arr = [10, 20, 30, 40]; ans = Array.isArray(str); document.querySelector( '.outputString').textContent = ans; ans = Array.isArray(num); document.querySelector( '.outputNumber').textContent = ans; ans = Array.isArray(arr); document.querySelector( '.outputArray').textContent = ans; } </script></body> </html>
Output:
Method 2: Using the instanceof operatorThe instanceof operator is used to test whether the prototype property of a constructor appears anywhere in the prototype chain of an object. This can be used to evaluate if an the given variable has a prototype of ‘Array’.Syntax:variable instanceof ArrayThe operator returns a true boolean value if the variable is same as what is specified (here an Array) and false if it is not. This is shown in the example below.Example-2:<!DOCTYPE html><html lang="en"> <head> <title> How to check if a variable is an array in JavaScript? </title></head> <body> <h1 style="color: green"> GeeksforGeeks </h1> <b> How to check if a variable is an array in JavaScript? </b> <p> Click on the button to check if the variable is an array </p> <p>Output for string: <div class="outputString"></div> <p>Output for number: <div class="outputNumber"></div> <p>Output for array: <div class="outputArray"></div> <button onclick="checkArray()">Click here</button> <script type="text/javascript"> function checkArray() { let str = 'This is a string'; let num = 25; let arr = [10, 20, 30, 40]; ans = str instanceof Array; document.querySelector( '.outputString').textContent = ans; ans = num instanceof Array; document.querySelector( '.outputNumber').textContent = ans; ans = arr instanceof Array; document.querySelector( '.outputArray').textContent = ans; } </script></body> </html>Output:
Syntax:
variable instanceof Array
The operator returns a true boolean value if the variable is same as what is specified (here an Array) and false if it is not. This is shown in the example below.
Example-2:
<!DOCTYPE html><html lang="en"> <head> <title> How to check if a variable is an array in JavaScript? </title></head> <body> <h1 style="color: green"> GeeksforGeeks </h1> <b> How to check if a variable is an array in JavaScript? </b> <p> Click on the button to check if the variable is an array </p> <p>Output for string: <div class="outputString"></div> <p>Output for number: <div class="outputNumber"></div> <p>Output for array: <div class="outputArray"></div> <button onclick="checkArray()">Click here</button> <script type="text/javascript"> function checkArray() { let str = 'This is a string'; let num = 25; let arr = [10, 20, 30, 40]; ans = str instanceof Array; document.querySelector( '.outputString').textContent = ans; ans = num instanceof Array; document.querySelector( '.outputNumber').textContent = ans; ans = arr instanceof Array; document.querySelector( '.outputArray').textContent = ans; } </script></body> </html>
Output:
Method 3: Checking the constructor property of the variableAnother method to check a variable is an array is by checking it’s constructor with Array.Syntax:variable.constructor === ArrayThis becomes true if the variable is same as what is specified (here an Array) and false if it is not. This is shown in the example below.Example-3:<!DOCTYPE html><html lang="en"> <head> <title> How to check if a variable is an array in JavaScript? </title></head> <body> <h1 style="color: green"> GeeksforGeeks </h1> <b>How to check if a variable is an array in JavaScript?</b> <p>Click on the button to check if the variable is an array</p> <p>Output for string: <div class="outputString"></div> <p>Output for number: <div class="outputNumber"></div> <p>Output for array: <div class="outputArray"></div> <button onclick="checkArray()"> Click here </button> <script type="text/javascript"> function checkArray() { let str = 'This is a string'; let num = 25; let arr = [10, 20, 30, 40]; ans = str.constructor === Array; document.querySelector( '.outputString').textContent = ans; ans = num.constructor === Array; document.querySelector( '.outputNumber').textContent = ans; ans = arr.constructor === Array; document.querySelector( '.outputArray').textContent = ans; } </script></body> </html>Output:
Another method to check a variable is an array is by checking it’s constructor with Array.
Syntax:
variable.constructor === Array
This becomes true if the variable is same as what is specified (here an Array) and false if it is not. This is shown in the example below.
Example-3:
<!DOCTYPE html><html lang="en"> <head> <title> How to check if a variable is an array in JavaScript? </title></head> <body> <h1 style="color: green"> GeeksforGeeks </h1> <b>How to check if a variable is an array in JavaScript?</b> <p>Click on the button to check if the variable is an array</p> <p>Output for string: <div class="outputString"></div> <p>Output for number: <div class="outputNumber"></div> <p>Output for array: <div class="outputArray"></div> <button onclick="checkArray()"> Click here </button> <script type="text/javascript"> function checkArray() { let str = 'This is a string'; let num = 25; let arr = [10, 20, 30, 40]; ans = str.constructor === Array; document.querySelector( '.outputString').textContent = ans; ans = num.constructor === Array; document.querySelector( '.outputNumber').textContent = ans; ans = arr.constructor === Array; document.querySelector( '.outputArray').textContent = ans; } </script></body> </html>
Output:
JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples.
javascript-array
Picked
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": 31305,
"s": 31277,
"text": "\n20 Jul, 2021"
},
{
"code": null,
"e": 31506,
"s": 31305,
"text": "In JavaScript, we can check if a variable is an array by using 3 methods, using the isArray method, using the instanceof operator and using checking the constructor type if it matches an Array object."
},
{
"code": null,
"e": 33010,
"s": 31506,
"text": "Method 1: Using the isArray methodThe Array.isArray() method checks whether the passed variable is an Array object.Syntax:Array.isArray(variableName)It returns a true boolean value if the variable is an array and false if it is not. This is shown in the example below.Example-1:<!DOCTYPE html><html lang=\"en\"> <head> <title> How to check if a variable is an array in JavaScript? </title></head> <body> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b> How to check if a variable is an array in JavaScript? </b> <p> Click on the button to check if the variable is an array </p> <p>Output for string: <div class=\"outputString\"> </div> <p>Output for number: <div class=\"outputNumber\"> </div> <p>Output for array: <div class=\"outputArray\"> </div> <button onclick=\"checkArray()\"> Click here </button> <script type=\"text/javascript\"> function checkArray() { let str = 'This is a string'; let num = 25; let arr = [10, 20, 30, 40]; ans = Array.isArray(str); document.querySelector( '.outputString').textContent = ans; ans = Array.isArray(num); document.querySelector( '.outputNumber').textContent = ans; ans = Array.isArray(arr); document.querySelector( '.outputArray').textContent = ans; } </script></body> </html>Output:"
},
{
"code": null,
"e": 33092,
"s": 33010,
"text": "The Array.isArray() method checks whether the passed variable is an Array object."
},
{
"code": null,
"e": 33100,
"s": 33092,
"text": "Syntax:"
},
{
"code": null,
"e": 33128,
"s": 33100,
"text": "Array.isArray(variableName)"
},
{
"code": null,
"e": 33248,
"s": 33128,
"text": "It returns a true boolean value if the variable is an array and false if it is not. This is shown in the example below."
},
{
"code": null,
"e": 33259,
"s": 33248,
"text": "Example-1:"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <title> How to check if a variable is an array in JavaScript? </title></head> <body> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b> How to check if a variable is an array in JavaScript? </b> <p> Click on the button to check if the variable is an array </p> <p>Output for string: <div class=\"outputString\"> </div> <p>Output for number: <div class=\"outputNumber\"> </div> <p>Output for array: <div class=\"outputArray\"> </div> <button onclick=\"checkArray()\"> Click here </button> <script type=\"text/javascript\"> function checkArray() { let str = 'This is a string'; let num = 25; let arr = [10, 20, 30, 40]; ans = Array.isArray(str); document.querySelector( '.outputString').textContent = ans; ans = Array.isArray(num); document.querySelector( '.outputNumber').textContent = ans; ans = Array.isArray(arr); document.querySelector( '.outputArray').textContent = ans; } </script></body> </html>",
"e": 34478,
"s": 33259,
"text": null
},
{
"code": null,
"e": 34486,
"s": 34478,
"text": "Output:"
},
{
"code": null,
"e": 36190,
"s": 34486,
"text": "Method 2: Using the instanceof operatorThe instanceof operator is used to test whether the prototype property of a constructor appears anywhere in the prototype chain of an object. This can be used to evaluate if an the given variable has a prototype of ‘Array’.Syntax:variable instanceof ArrayThe operator returns a true boolean value if the variable is same as what is specified (here an Array) and false if it is not. This is shown in the example below.Example-2:<!DOCTYPE html><html lang=\"en\"> <head> <title> How to check if a variable is an array in JavaScript? </title></head> <body> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b> How to check if a variable is an array in JavaScript? </b> <p> Click on the button to check if the variable is an array </p> <p>Output for string: <div class=\"outputString\"></div> <p>Output for number: <div class=\"outputNumber\"></div> <p>Output for array: <div class=\"outputArray\"></div> <button onclick=\"checkArray()\">Click here</button> <script type=\"text/javascript\"> function checkArray() { let str = 'This is a string'; let num = 25; let arr = [10, 20, 30, 40]; ans = str instanceof Array; document.querySelector( '.outputString').textContent = ans; ans = num instanceof Array; document.querySelector( '.outputNumber').textContent = ans; ans = arr instanceof Array; document.querySelector( '.outputArray').textContent = ans; } </script></body> </html>Output:"
},
{
"code": null,
"e": 36198,
"s": 36190,
"text": "Syntax:"
},
{
"code": null,
"e": 36224,
"s": 36198,
"text": "variable instanceof Array"
},
{
"code": null,
"e": 36387,
"s": 36224,
"text": "The operator returns a true boolean value if the variable is same as what is specified (here an Array) and false if it is not. This is shown in the example below."
},
{
"code": null,
"e": 36398,
"s": 36387,
"text": "Example-2:"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <title> How to check if a variable is an array in JavaScript? </title></head> <body> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b> How to check if a variable is an array in JavaScript? </b> <p> Click on the button to check if the variable is an array </p> <p>Output for string: <div class=\"outputString\"></div> <p>Output for number: <div class=\"outputNumber\"></div> <p>Output for array: <div class=\"outputArray\"></div> <button onclick=\"checkArray()\">Click here</button> <script type=\"text/javascript\"> function checkArray() { let str = 'This is a string'; let num = 25; let arr = [10, 20, 30, 40]; ans = str instanceof Array; document.querySelector( '.outputString').textContent = ans; ans = num instanceof Array; document.querySelector( '.outputNumber').textContent = ans; ans = arr instanceof Array; document.querySelector( '.outputArray').textContent = ans; } </script></body> </html>",
"e": 37629,
"s": 36398,
"text": null
},
{
"code": null,
"e": 37637,
"s": 37629,
"text": "Output:"
},
{
"code": null,
"e": 39216,
"s": 37637,
"text": "Method 3: Checking the constructor property of the variableAnother method to check a variable is an array is by checking it’s constructor with Array.Syntax:variable.constructor === ArrayThis becomes true if the variable is same as what is specified (here an Array) and false if it is not. This is shown in the example below.Example-3:<!DOCTYPE html><html lang=\"en\"> <head> <title> How to check if a variable is an array in JavaScript? </title></head> <body> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b>How to check if a variable is an array in JavaScript?</b> <p>Click on the button to check if the variable is an array</p> <p>Output for string: <div class=\"outputString\"></div> <p>Output for number: <div class=\"outputNumber\"></div> <p>Output for array: <div class=\"outputArray\"></div> <button onclick=\"checkArray()\"> Click here </button> <script type=\"text/javascript\"> function checkArray() { let str = 'This is a string'; let num = 25; let arr = [10, 20, 30, 40]; ans = str.constructor === Array; document.querySelector( '.outputString').textContent = ans; ans = num.constructor === Array; document.querySelector( '.outputNumber').textContent = ans; ans = arr.constructor === Array; document.querySelector( '.outputArray').textContent = ans; } </script></body> </html>Output:"
},
{
"code": null,
"e": 39307,
"s": 39216,
"text": "Another method to check a variable is an array is by checking it’s constructor with Array."
},
{
"code": null,
"e": 39315,
"s": 39307,
"text": "Syntax:"
},
{
"code": null,
"e": 39346,
"s": 39315,
"text": "variable.constructor === Array"
},
{
"code": null,
"e": 39485,
"s": 39346,
"text": "This becomes true if the variable is same as what is specified (here an Array) and false if it is not. This is shown in the example below."
},
{
"code": null,
"e": 39496,
"s": 39485,
"text": "Example-3:"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <title> How to check if a variable is an array in JavaScript? </title></head> <body> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b>How to check if a variable is an array in JavaScript?</b> <p>Click on the button to check if the variable is an array</p> <p>Output for string: <div class=\"outputString\"></div> <p>Output for number: <div class=\"outputNumber\"></div> <p>Output for array: <div class=\"outputArray\"></div> <button onclick=\"checkArray()\"> Click here </button> <script type=\"text/javascript\"> function checkArray() { let str = 'This is a string'; let num = 25; let arr = [10, 20, 30, 40]; ans = str.constructor === Array; document.querySelector( '.outputString').textContent = ans; ans = num.constructor === Array; document.querySelector( '.outputNumber').textContent = ans; ans = arr.constructor === Array; document.querySelector( '.outputArray').textContent = ans; } </script></body> </html>",
"e": 40734,
"s": 39496,
"text": null
},
{
"code": null,
"e": 40742,
"s": 40734,
"text": "Output:"
},
{
"code": null,
"e": 40961,
"s": 40742,
"text": "JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples."
},
{
"code": null,
"e": 40978,
"s": 40961,
"text": "javascript-array"
},
{
"code": null,
"e": 40985,
"s": 40978,
"text": "Picked"
},
{
"code": null,
"e": 40996,
"s": 40985,
"text": "JavaScript"
},
{
"code": null,
"e": 41013,
"s": 40996,
"text": "Web Technologies"
},
{
"code": null,
"e": 41111,
"s": 41013,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 41151,
"s": 41111,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 41196,
"s": 41151,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 41257,
"s": 41196,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 41329,
"s": 41257,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 41398,
"s": 41329,
"text": "How to calculate the number of days between two dates in javascript?"
},
{
"code": null,
"e": 41438,
"s": 41398,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 41471,
"s": 41438,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 41516,
"s": 41471,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 41559,
"s": 41516,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
JavaScript | Function Invocation - GeeksforGeeks
|
07 Mar, 2019
JavaScript Function Invocation is used to executes the function code and it is common to use the term “call a function” instead of “invoke a function”. The code inside a function is executed when the function is invoked.
Syntax:
Invoking a Function as a Function:function myFunction( var ) {
return var;
}
myFunction( value );
function myFunction( var ) {
return var;
}
myFunction( value );
Invoking a Function as a Method:var myObject = {
var : value,
functionName: function () {
return this.var;
}
}
myObject.functionName();
var myObject = {
var : value,
functionName: function () {
return this.var;
}
}
myObject.functionName();
Parameters: It contains two parameters as mentioned above and described below:
functionName: The functionName method is a function and this function belongs to the object and myObject is the owner of the function.
this: The parameter this is the object that owns the JavaScript code and in this case the value of this is myObject.
Example 1: This example use function invocation to add two numbers.
<!DOCTYPE html><html> <head> <title> JavaScript Function Invocation </title></head> <body style="text-align:center;"> <h2>GeeksForGeeks</h2> <p> Function returns the addition of 50 and 60 </p> <p id="geeks"></p> <!-- Script to add two numbers --> <script> function myFunction(a, b) { return a + b; } document.getElementById("geeks").innerHTML = window.myFunction(50, 60); </script></body> </html>
Output:
Example 2: This example use function invocation to concatenate strings.
<!DOCTYPE html><html> <head> <title> JavaScript Function Invocation </title></head> <body style="text-align:center;"> <h2>GeeksForGeeks</h2> <p> myObject.fullName() will return GeeksforGeeks </p> <p id="geeks"></p> <!-- Script to implement Function Invocation --> <script> var myObject = { firstName:"Geeks", middleName:"for", lastName: "Geeks", fullName: function() { return this.firstName + this.middleName + this.lastName; } } document.getElementById("geeks").innerHTML = myObject.fullName(); </script></body> </html>
Output:
javascript-functions
Picked
JavaScript
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Difference between var, let and const keywords in JavaScript
Difference Between PUT and PATCH Request
JavaScript | Promises
How to get character array from string in JavaScript?
How to filter object array based on attributes?
How to remove duplicate elements from JavaScript Array ?
Lodash _.debounce() Method
Angular File Upload
How to get selected value in dropdown list using JavaScript ?
|
[
{
"code": null,
"e": 26567,
"s": 26539,
"text": "\n07 Mar, 2019"
},
{
"code": null,
"e": 26788,
"s": 26567,
"text": "JavaScript Function Invocation is used to executes the function code and it is common to use the term “call a function” instead of “invoke a function”. The code inside a function is executed when the function is invoked."
},
{
"code": null,
"e": 26796,
"s": 26788,
"text": "Syntax:"
},
{
"code": null,
"e": 26898,
"s": 26796,
"text": "Invoking a Function as a Function:function myFunction( var ) {\n return var;\n}\nmyFunction( value );"
},
{
"code": null,
"e": 26966,
"s": 26898,
"text": "function myFunction( var ) {\n return var;\n}\nmyFunction( value );"
},
{
"code": null,
"e": 27124,
"s": 26966,
"text": "Invoking a Function as a Method:var myObject = {\n var : value,\n functionName: function () {\n return this.var;\n }\n}\nmyObject.functionName(); "
},
{
"code": null,
"e": 27250,
"s": 27124,
"text": "var myObject = {\n var : value,\n functionName: function () {\n return this.var;\n }\n}\nmyObject.functionName(); "
},
{
"code": null,
"e": 27329,
"s": 27250,
"text": "Parameters: It contains two parameters as mentioned above and described below:"
},
{
"code": null,
"e": 27464,
"s": 27329,
"text": "functionName: The functionName method is a function and this function belongs to the object and myObject is the owner of the function."
},
{
"code": null,
"e": 27581,
"s": 27464,
"text": "this: The parameter this is the object that owns the JavaScript code and in this case the value of this is myObject."
},
{
"code": null,
"e": 27649,
"s": 27581,
"text": "Example 1: This example use function invocation to add two numbers."
},
{
"code": "<!DOCTYPE html><html> <head> <title> JavaScript Function Invocation </title></head> <body style=\"text-align:center;\"> <h2>GeeksForGeeks</h2> <p> Function returns the addition of 50 and 60 </p> <p id=\"geeks\"></p> <!-- Script to add two numbers --> <script> function myFunction(a, b) { return a + b; } document.getElementById(\"geeks\").innerHTML = window.myFunction(50, 60); </script></body> </html> ",
"e": 28211,
"s": 27649,
"text": null
},
{
"code": null,
"e": 28219,
"s": 28211,
"text": "Output:"
},
{
"code": null,
"e": 28291,
"s": 28219,
"text": "Example 2: This example use function invocation to concatenate strings."
},
{
"code": "<!DOCTYPE html><html> <head> <title> JavaScript Function Invocation </title></head> <body style=\"text-align:center;\"> <h2>GeeksForGeeks</h2> <p> myObject.fullName() will return GeeksforGeeks </p> <p id=\"geeks\"></p> <!-- Script to implement Function Invocation --> <script> var myObject = { firstName:\"Geeks\", middleName:\"for\", lastName: \"Geeks\", fullName: function() { return this.firstName + this.middleName + this.lastName; } } document.getElementById(\"geeks\").innerHTML = myObject.fullName(); </script></body> </html> ",
"e": 29037,
"s": 28291,
"text": null
},
{
"code": null,
"e": 29045,
"s": 29037,
"text": "Output:"
},
{
"code": null,
"e": 29066,
"s": 29045,
"text": "javascript-functions"
},
{
"code": null,
"e": 29073,
"s": 29066,
"text": "Picked"
},
{
"code": null,
"e": 29084,
"s": 29073,
"text": "JavaScript"
},
{
"code": null,
"e": 29182,
"s": 29084,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29222,
"s": 29182,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 29283,
"s": 29222,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 29324,
"s": 29283,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 29346,
"s": 29324,
"text": "JavaScript | Promises"
},
{
"code": null,
"e": 29400,
"s": 29346,
"text": "How to get character array from string in JavaScript?"
},
{
"code": null,
"e": 29448,
"s": 29400,
"text": "How to filter object array based on attributes?"
},
{
"code": null,
"e": 29505,
"s": 29448,
"text": "How to remove duplicate elements from JavaScript Array ?"
},
{
"code": null,
"e": 29532,
"s": 29505,
"text": "Lodash _.debounce() Method"
},
{
"code": null,
"e": 29552,
"s": 29532,
"text": "Angular File Upload"
}
] |
Functions that are executed before and after main() in C - GeeksforGeeks
|
28 May, 2017
With GCC family of C compilers, we can mark some functions to execute before and after main(). So some startup code can be executed before main() starts, and some cleanup code can be executed after main() ends. For example, in the following program, myStartupFun() is called before main() and myCleanupFun() is called after main().
#include<stdio.h> /* Apply the constructor attribute to myStartupFun() so that it is executed before main() */void myStartupFun (void) __attribute__ ((constructor)); /* Apply the destructor attribute to myCleanupFun() so that it is executed after main() */void myCleanupFun (void) __attribute__ ((destructor)); /* implementation of myStartupFun */void myStartupFun (void){ printf ("startup code before main()\n");} /* implementation of myCleanupFun */void myCleanupFun (void){ printf ("cleanup code after main()\n");} int main (void){ printf ("hello\n"); return 0;}
Output:
startup code before main()
hello
cleanup code after main()
Like the above feature, GCC has added many other interesting features to standard C language. See this for more details.
Related Article :Executing main() in C – behind the scene
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
C-Functions
C Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Substring in C++
Multidimensional Arrays in C / C++
Left Shift and Right Shift Operators in C/C++
Converting Strings to Numbers in C/C++
Function Pointer in C
Core Dump (Segmentation fault) in C/C++
rand() and srand() in C/C++
std::string class in C++
fork() in C
Command line arguments in C/C++
|
[
{
"code": null,
"e": 25973,
"s": 25945,
"text": "\n28 May, 2017"
},
{
"code": null,
"e": 26305,
"s": 25973,
"text": "With GCC family of C compilers, we can mark some functions to execute before and after main(). So some startup code can be executed before main() starts, and some cleanup code can be executed after main() ends. For example, in the following program, myStartupFun() is called before main() and myCleanupFun() is called after main()."
},
{
"code": "#include<stdio.h> /* Apply the constructor attribute to myStartupFun() so that it is executed before main() */void myStartupFun (void) __attribute__ ((constructor)); /* Apply the destructor attribute to myCleanupFun() so that it is executed after main() */void myCleanupFun (void) __attribute__ ((destructor)); /* implementation of myStartupFun */void myStartupFun (void){ printf (\"startup code before main()\\n\");} /* implementation of myCleanupFun */void myCleanupFun (void){ printf (\"cleanup code after main()\\n\");} int main (void){ printf (\"hello\\n\"); return 0;}",
"e": 26897,
"s": 26305,
"text": null
},
{
"code": null,
"e": 26905,
"s": 26897,
"text": "Output:"
},
{
"code": null,
"e": 26965,
"s": 26905,
"text": "startup code before main()\nhello\ncleanup code after main()\n"
},
{
"code": null,
"e": 27086,
"s": 26965,
"text": "Like the above feature, GCC has added many other interesting features to standard C language. See this for more details."
},
{
"code": null,
"e": 27144,
"s": 27086,
"text": "Related Article :Executing main() in C – behind the scene"
},
{
"code": null,
"e": 27269,
"s": 27144,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 27281,
"s": 27269,
"text": "C-Functions"
},
{
"code": null,
"e": 27292,
"s": 27281,
"text": "C Language"
},
{
"code": null,
"e": 27390,
"s": 27292,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27407,
"s": 27390,
"text": "Substring in C++"
},
{
"code": null,
"e": 27442,
"s": 27407,
"text": "Multidimensional Arrays in C / C++"
},
{
"code": null,
"e": 27488,
"s": 27442,
"text": "Left Shift and Right Shift Operators in C/C++"
},
{
"code": null,
"e": 27527,
"s": 27488,
"text": "Converting Strings to Numbers in C/C++"
},
{
"code": null,
"e": 27549,
"s": 27527,
"text": "Function Pointer in C"
},
{
"code": null,
"e": 27589,
"s": 27549,
"text": "Core Dump (Segmentation fault) in C/C++"
},
{
"code": null,
"e": 27617,
"s": 27589,
"text": "rand() and srand() in C/C++"
},
{
"code": null,
"e": 27642,
"s": 27617,
"text": "std::string class in C++"
},
{
"code": null,
"e": 27654,
"s": 27642,
"text": "fork() in C"
}
] |
How to remove object from array of objects using JavaScript ? - GeeksforGeeks
|
31 Dec, 2019
Given a JavaScript array containing objects in and the task is to delete certain objects from array of objects. There are two approaches to solve this problem which are discussed below:
Approach 1:
Use array.forEach() method to traverse every object of the array.
For each object use delete obj.property to delete the certain object element from array of objects.
Example: This example implements the above approach.
<!DOCTYPE HTML><html> <head> <title> Remove certain property for all objects in array with JavaScript. </title></head> <body style="text-align:center;"> <h1 style="color: green"> GeeksForGeeks </h1> <p id="GFG_UP"></p> <button onclick="gfg_Run()"> Click Here </button> <p id="GFG_DOWN" style="color:green;"> </p> <script> var el_up = document.getElementById("GFG_UP"); var el_down = document.getElementById("GFG_DOWN"); var arr = [{ a: 'Val_1', b: 'Val_2' }, { a: 'Val_3', b: 'Val_4' }, { a: 'Val_1', b: 'Val_2' }]; el_up.innerHTML = "Click on the button to delete" + " certain property of object.<br>Array - " + JSON.stringify(arr); function gfg_Run() { arr.forEach(function(obj) { delete obj.a }); el_down.innerHTML = JSON.stringify(arr); } </script></body> </html>
Output:
Before clicking the button:
After clicking the button:
Approach 2:
Use array.map() method to traverse every object of the array.
For each object use delete obj.property to delete the certain object from array of objects.
Example: This example implements the above approach.
<!DOCTYPE HTML><html> <head> <title> Remove certain property for all objects in array with JavaScript. </title></head> <body style="text-align:center;"> <h1 style="color: green"> GeeksForGeeks </h1> <p id="GFG_UP"></p> <button onclick="gfg_Run()"> Click Here </button> <p id="GFG_DOWN"></p> <script> var el_up = document.getElementById("GFG_UP"); var el_down = document.getElementById("GFG_DOWN"); var arr = [{ a: 'Val_1', b: 'Val_2' }, { a: 'Val_3', b: 'Val_4' }, { a: 'Val_1', b: 'Val_2' }]; el_up.innerHTML = "Click on the button to delete" + " certain property of object.<br>Array - " + JSON.stringify(arr); function gfg_Run() { arr.map(function(obj) { delete obj.a; return obj; }); el_down.innerHTML = JSON.stringify(arr); } </script></body> </html>
Output:
Before clicking on the button:
After clicking on the button:
JavaScript-Misc
JavaScript
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
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 ?
How to Open URL in New Tab using JavaScript ?
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
Difference between var, let and const keywords in JavaScript
|
[
{
"code": null,
"e": 25853,
"s": 25825,
"text": "\n31 Dec, 2019"
},
{
"code": null,
"e": 26039,
"s": 25853,
"text": "Given a JavaScript array containing objects in and the task is to delete certain objects from array of objects. There are two approaches to solve this problem which are discussed below:"
},
{
"code": null,
"e": 26051,
"s": 26039,
"text": "Approach 1:"
},
{
"code": null,
"e": 26117,
"s": 26051,
"text": "Use array.forEach() method to traverse every object of the array."
},
{
"code": null,
"e": 26217,
"s": 26117,
"text": "For each object use delete obj.property to delete the certain object element from array of objects."
},
{
"code": null,
"e": 26270,
"s": 26217,
"text": "Example: This example implements the above approach."
},
{
"code": "<!DOCTYPE HTML><html> <head> <title> Remove certain property for all objects in array with JavaScript. </title></head> <body style=\"text-align:center;\"> <h1 style=\"color: green\"> GeeksForGeeks </h1> <p id=\"GFG_UP\"></p> <button onclick=\"gfg_Run()\"> Click Here </button> <p id=\"GFG_DOWN\" style=\"color:green;\"> </p> <script> var el_up = document.getElementById(\"GFG_UP\"); var el_down = document.getElementById(\"GFG_DOWN\"); var arr = [{ a: 'Val_1', b: 'Val_2' }, { a: 'Val_3', b: 'Val_4' }, { a: 'Val_1', b: 'Val_2' }]; el_up.innerHTML = \"Click on the button to delete\" + \" certain property of object.<br>Array - \" + JSON.stringify(arr); function gfg_Run() { arr.forEach(function(obj) { delete obj.a }); el_down.innerHTML = JSON.stringify(arr); } </script></body> </html>",
"e": 27316,
"s": 26270,
"text": null
},
{
"code": null,
"e": 27324,
"s": 27316,
"text": "Output:"
},
{
"code": null,
"e": 27352,
"s": 27324,
"text": "Before clicking the button:"
},
{
"code": null,
"e": 27379,
"s": 27352,
"text": "After clicking the button:"
},
{
"code": null,
"e": 27391,
"s": 27379,
"text": "Approach 2:"
},
{
"code": null,
"e": 27453,
"s": 27391,
"text": "Use array.map() method to traverse every object of the array."
},
{
"code": null,
"e": 27545,
"s": 27453,
"text": "For each object use delete obj.property to delete the certain object from array of objects."
},
{
"code": null,
"e": 27598,
"s": 27545,
"text": "Example: This example implements the above approach."
},
{
"code": "<!DOCTYPE HTML><html> <head> <title> Remove certain property for all objects in array with JavaScript. </title></head> <body style=\"text-align:center;\"> <h1 style=\"color: green\"> GeeksForGeeks </h1> <p id=\"GFG_UP\"></p> <button onclick=\"gfg_Run()\"> Click Here </button> <p id=\"GFG_DOWN\"></p> <script> var el_up = document.getElementById(\"GFG_UP\"); var el_down = document.getElementById(\"GFG_DOWN\"); var arr = [{ a: 'Val_1', b: 'Val_2' }, { a: 'Val_3', b: 'Val_4' }, { a: 'Val_1', b: 'Val_2' }]; el_up.innerHTML = \"Click on the button to delete\" + \" certain property of object.<br>Array - \" + JSON.stringify(arr); function gfg_Run() { arr.map(function(obj) { delete obj.a; return obj; }); el_down.innerHTML = JSON.stringify(arr); } </script></body> </html>",
"e": 28638,
"s": 27598,
"text": null
},
{
"code": null,
"e": 28646,
"s": 28638,
"text": "Output:"
},
{
"code": null,
"e": 28677,
"s": 28646,
"text": "Before clicking on the button:"
},
{
"code": null,
"e": 28707,
"s": 28677,
"text": "After clicking on the button:"
},
{
"code": null,
"e": 28723,
"s": 28707,
"text": "JavaScript-Misc"
},
{
"code": null,
"e": 28734,
"s": 28723,
"text": "JavaScript"
},
{
"code": null,
"e": 28751,
"s": 28734,
"text": "Web Technologies"
},
{
"code": null,
"e": 28778,
"s": 28751,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 28876,
"s": 28778,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28921,
"s": 28876,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 28982,
"s": 28921,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 29054,
"s": 28982,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 29106,
"s": 29054,
"text": "How to append HTML code to a div using JavaScript ?"
},
{
"code": null,
"e": 29152,
"s": 29106,
"text": "How to Open URL in New Tab using JavaScript ?"
},
{
"code": null,
"e": 29185,
"s": 29152,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 29230,
"s": 29185,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 29273,
"s": 29230,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 29335,
"s": 29273,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
}
] |
Minimum sum of two numbers formed from digits of an array - GeeksforGeeks
|
20 Apr, 2022
Given an array of digits (values are from 0 to 9), find the minimum possible sum of two numbers formed from digits of the array. All digits of given array must be used to form the two numbers.
Examples:
Input: [6, 8, 4, 5, 2, 3]
Output: 604
The minimum sum is formed by numbers
358 and 246
Input: [5, 3, 0, 7, 4]
Output: 82
The minimum sum is formed by numbers
35 and 047
Since we want to minimize the sum of two numbers to be formed, we must divide all digits in two halves and assign half-half digits to them. We also need to make sure that the leading digits are smaller.
We build a Min Heap with the elements of the given array, which takes O(n) worst time. Now we retrieve min values (2 at a time) of array, by polling from the Priority Queue and append these two min values to our numbers, till the heap becomes empty, i.e., all the elements of array get exhausted. We return the sum of two formed numbers, which is our required answer. Overall complexity is O(nlogn) as push() operation takes O(logn) and it’s repeated n times.
C++
Java
Python3
C#
Javascript
// C++ program to find minimum sum of two numbers// formed from all digits in a given array.#include<bits/stdc++.h>using namespace std; // Returns sum of two numbers formed// from all digits in a[]int minSum(int arr[], int n){ // min Heap priority_queue <int, vector<int>, greater<int> > pq; // to store the 2 numbers formed by array elements to // minimize the required sum string num1, num2; // Adding elements in Priority Queue for(int i=0; i<n; i++) pq.push(arr[i]); // checking if the priority queue is non empty while(!pq.empty()) { // appending top of the queue to the string num1+=(48 + pq.top()); pq.pop(); if(!pq.empty()) { num2+=(48 + pq.top()); pq.pop(); } } // converting string to integer int a = atoi(num1.c_str()); int b = atoi(num2.c_str()); // returning the sum return a+b;} int main(){ int arr[] = {6, 8, 4, 5, 2, 3}; int n = sizeof(arr)/sizeof(arr[0]); cout<<minSum(arr, n)<<endl; return 0;}// Contributed By: Harshit Sidhwa
// Java program to find minimum sum of two numbers// formed from all digits in a given array.import java.util.PriorityQueue; class MinSum{ // Returns sum of two numbers formed // from all digits in a[] public static long solve(int[] a) { // min Heap PriorityQueue<Integer> pq = new PriorityQueue<Integer>(); // to store the 2 numbers formed by array elements to // minimize the required sum StringBuilder num1 = new StringBuilder(); StringBuilder num2 = new StringBuilder(); // Adding elements in Priority Queue for (int x : a) pq.add(x); // checking if the priority queue is non empty while (!pq.isEmpty()) { num1.append(pq.poll()+ ""); if (!pq.isEmpty()) num2.append(pq.poll()+ ""); } // the required sum calculated long sum = Long.parseLong(num1.toString()) + Long.parseLong(num2.toString()); return sum; } // Driver code public static void main (String[] args) { int arr[] = {6, 8, 4, 5, 2, 3}; System.out.println("The required sum is "+ solve(arr)); }}
# Python3 program to find minimum# sum of two numbers formed from# all digits in a given array.from queue import PriorityQueue # Returns sum of two numbers formed# from all digits in a[]def solve(a): # min Heap pq = PriorityQueue() # To store the 2 numbers # formed by array elements to # minimize the required sum num1 = "" num2 = "" # Adding elements in # Priority Queue for x in a: pq.put(x) # Checking if the priority # queue is non empty while not pq.empty(): num1 += str(pq.get()) if not pq.empty(): num2 += str(pq.get()) # The required sum calculated sum = int(num1) + int(num2) return sum # Driver codeif __name__=="__main__": arr = [ 6, 8, 4, 5, 2, 3 ] print("The required sum is ", solve(arr)) # This code is contributed by rutvik_56
// C# program to find minimum sum of two numbers// formed from all digits in a given array.using System;using System.Collections.Generic;class GFG{ // Returns sum of two numbers formed // from all digits in a[] public static long solve(int[] a) { // min Heap List<int> pq = new List<int>(); // to store the 2 numbers formed by array elements to // minimize the required sum string num1 = ""; string num2 = ""; // Adding elements in Priority Queue foreach(int x in a) pq.Add(x); pq.Sort(); // checking if the priority queue is non empty while (pq.Count > 0) { num1 = num1 + pq[0]; pq.RemoveAt(0); if (pq.Count > 0) { num2 = num2 + pq[0]; pq.RemoveAt(0); } } // the required sum calculated int sum = Int32.Parse(num1) + Int32.Parse(num2); return sum; } // Driver code static void Main() { int[] arr = {6, 8, 4, 5, 2, 3}; Console.WriteLine("The required sum is "+ solve(arr)); }} // This code is contributed by divyesh072019.
<script> // Javascript program to find minimum sum of two numbers// formed from all digits in a given array. // Returns sum of two numbers formed // from all digits in a[] function solve(a) { // min Heap pq=[]; // to store the 2 numbers formed by array elements to // minimize the required sum let num1=""; let num2=""; // Adding elements in Priority Queue for(let x=0;x<a.length;x++) { pq.push(a[x]); } pq.sort(function(a,b){return b-a;}); // checking if the priority queue is non empty while(pq.length!=0) { num1+=pq.pop(); if(pq.length!=0) { num2+=pq.pop(); } } // the required sum calculated let sum=parseInt(num1)+parseInt(num2); return sum; } // Driver code let arr=[6, 8, 4, 5, 2, 3]; document.write("The required sum is "+ solve(arr)); // This code is contributed by avanitrachhadiya2155 </script>
Output:
The required sum is 604
Another method: We can follow another approach also like this, as we need two numbers such that their sum is minimum, then we would also need two minimum numbers. If we arrange our array in ascending order then we can two digits that will form the smallest numbers, e.g., 2 3 4 5 6 8, now we can get two numbers starting from 2 and 3. First part is done now. Moving forward we have to form such that they would contain small digits, i.e. pick digits alternatively from array extend your two numbers. i.e. 246, 358. Now if we see analyze this, then we can pick even indexed numbers for num1 and an odd number for num2.
Below is the implementation:
C++
C
Java
Python3
C#
PHP
Javascript
// C++ program to find minimum sum of two numbers// formed from all digits in a given array.#include <bits/stdc++.h>using namespace std; // Returns sum of two numbers formed// from all digits in a[]int minSum(int a[], int n){ // sort the elements sort(a, a + n); int num1 = 0; int num2 = 0; for (int i = 0; i < n; i++) { if (i % 2 == 0) num1 = num1 * 10 + a[i]; else num2 = num2 * 10 + a[i]; } return num2 + num1;} // Driver codeint main(){ int arr[] = { 5, 3, 0, 7, 4 }; int n = sizeof(arr) / sizeof(arr[0]); cout << "The required sum is " << minSum(arr, n) << endl; return 0;} // This code is contributed by Sania Kumari Gupta
// C program to find minimum sum of two numbers// formed from all digits in a given array.#include <stdio.h>#include <stdlib.h>int cmpfunc(const void* a, const void* b){ return (*(int*)a - *(int*)b);} // Returns sum of two numbers formed// from all digits in a[]int minSum(int a[], int n){ // sort the elements qsort(a, n, sizeof(int), cmpfunc); // sort(a,a+n); int num1 = 0; int num2 = 0; for (int i = 0; i < n; i++) { if (i % 2 == 0) num1 = num1 * 10 + a[i]; else num2 = num2 * 10 + a[i]; } return num2 + num1;} // Driver codeint main(){ int arr[] = { 5, 3, 0, 7, 4 }; int n = sizeof(arr) / sizeof(arr[0]); printf("The required sum is %d", minSum(arr, n)); return 0;} // This code is contributed by Sania Kumari Gupta
import java.util.Arrays;// Java program to find minimum sum of two numbers// formed from all digits in a given array.public class AQRQ { // Returns sum of two numbers formed // from all digits in a[] static int minSum(int a[], int n) { // sort the elements Arrays.sort(a); int num1 = 0; int num2 = 0; for (int i = 0; i < n; i++) { if (i % 2 == 0) num1 = num1 * 10 + a[i]; else num2 = num2 * 10 + a[i]; } return num2 + num1; } // Driver code public static void main(String[] args) { int arr[] = { 5, 3, 0, 7, 4 }; int n = arr.length; System.out.println("The required sum is " + minSum(arr, n)); }} // This code is contributed by Sania Kumari Gupta
# Python 3 program to find minimum# sum of two numbers formed# from all digits in an given array # Returns sum of two numbers formed# from all digits in a[]def minSum(a, n): # sorted the elements a = sorted(a) num1, num2 = 0, 0 for i in range(n): if i % 2 == 0: num1 = num1 * 10 + a[i] else: num2 = num2 * 10 + a[i] return num2 + num1 # Driver codearr = [5, 3, 0, 7, 4]n = len(arr)print("The required sum is", minSum(arr, n)) # This code is contributed# by Mohit kumar 29
// C# a program to find minimum sum of two numbers//formed from all digits in a given array. using System; public class GFG{ //Returns sum of two numbers formed //from all digits in a[] static int minSum(int []a, int n){ // sort the elements Array.Sort(a); int num1 = 0; int num2 = 0; for(int i = 0;i<n;i++){ if(i%2==0) num1 = num1*10+a[i]; else num2 = num2*10+a[i]; } return num2+num1; } //Driver code static public void Main (){ int []arr = {5, 3, 0, 7, 4}; int n = arr.Length; Console.WriteLine("The required sum is " + minSum(arr, n)); }//This code is contributed by ajit. }
<?php// PHP program to find minimum sum// of two numbers formed from all// digits in a given array. // Returns sum of two numbers formed// from all digits in a[]function minSum($a, $n){ // sort the elements sort($a); $num1 = 0; $num2 = 0; for($i = 0; $i < $n; $i++) { if($i % 2 == 0) $num1 = $num1 * 10 + $a[$i]; else $num2 = $num2 * 10 + $a[$i]; } return ($num2 + $num1);} // Driver code$arr = array(5, 3, 0, 7, 4);$n = sizeof($arr);echo "The required sum is ", minSum($arr, $n), "\n"; // This Code is Contributed by ajit?>
<script> // JavaScript program to find minimum sum of two numbers // formed from all digits in a given array. // Returns sum of two numbers formed // from all digits in a[] function minSum(a, n){ // sort the elements a.sort(); let num1 = 0; let num2 = 0; for(let i = 0;i<n;i++){ if(i%2==0) num1 = num1*10+a[i]; else num2 = num2*10+a[i]; } return num2+num1; } let arr = [5, 3, 0, 7, 4]; let n = arr.length; document.write("The required sum is " + minSum(arr, n)); </script>
Output:
The required sum is 82
Time Complexity : O(nLogN)
This article is contributed by Prakhar. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
harrypotter0
pushpender673
jit_t
ukasp
mohit kumar 29
rutvik_56
khushboogoyal499
divyesh072019
mukesh07
avanitrachhadiya2155
krisania804
number-digits
Arrays
Greedy
Heap
Mathematical
Queue
Arrays
Greedy
Mathematical
Queue
Heap
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
Introduction to Arrays
Multidimensional Arrays in Java
Linear Search
Linked List vs Array
Dijkstra's shortest path algorithm | Greedy Algo-7
Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2
Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5
Write a program to print all permutations of a given string
Huffman Coding | Greedy Algo-3
|
[
{
"code": null,
"e": 26503,
"s": 26475,
"text": "\n20 Apr, 2022"
},
{
"code": null,
"e": 26696,
"s": 26503,
"text": "Given an array of digits (values are from 0 to 9), find the minimum possible sum of two numbers formed from digits of the array. All digits of given array must be used to form the two numbers."
},
{
"code": null,
"e": 26707,
"s": 26696,
"text": "Examples: "
},
{
"code": null,
"e": 26880,
"s": 26707,
"text": "Input: [6, 8, 4, 5, 2, 3]\nOutput: 604\nThe minimum sum is formed by numbers \n358 and 246\n\nInput: [5, 3, 0, 7, 4]\nOutput: 82\nThe minimum sum is formed by numbers \n35 and 047 "
},
{
"code": null,
"e": 27084,
"s": 26880,
"text": "Since we want to minimize the sum of two numbers to be formed, we must divide all digits in two halves and assign half-half digits to them. We also need to make sure that the leading digits are smaller. "
},
{
"code": null,
"e": 27545,
"s": 27084,
"text": "We build a Min Heap with the elements of the given array, which takes O(n) worst time. Now we retrieve min values (2 at a time) of array, by polling from the Priority Queue and append these two min values to our numbers, till the heap becomes empty, i.e., all the elements of array get exhausted. We return the sum of two formed numbers, which is our required answer. Overall complexity is O(nlogn) as push() operation takes O(logn) and it’s repeated n times. "
},
{
"code": null,
"e": 27549,
"s": 27545,
"text": "C++"
},
{
"code": null,
"e": 27554,
"s": 27549,
"text": "Java"
},
{
"code": null,
"e": 27562,
"s": 27554,
"text": "Python3"
},
{
"code": null,
"e": 27565,
"s": 27562,
"text": "C#"
},
{
"code": null,
"e": 27576,
"s": 27565,
"text": "Javascript"
},
{
"code": "// C++ program to find minimum sum of two numbers// formed from all digits in a given array.#include<bits/stdc++.h>using namespace std; // Returns sum of two numbers formed// from all digits in a[]int minSum(int arr[], int n){ // min Heap priority_queue <int, vector<int>, greater<int> > pq; // to store the 2 numbers formed by array elements to // minimize the required sum string num1, num2; // Adding elements in Priority Queue for(int i=0; i<n; i++) pq.push(arr[i]); // checking if the priority queue is non empty while(!pq.empty()) { // appending top of the queue to the string num1+=(48 + pq.top()); pq.pop(); if(!pq.empty()) { num2+=(48 + pq.top()); pq.pop(); } } // converting string to integer int a = atoi(num1.c_str()); int b = atoi(num2.c_str()); // returning the sum return a+b;} int main(){ int arr[] = {6, 8, 4, 5, 2, 3}; int n = sizeof(arr)/sizeof(arr[0]); cout<<minSum(arr, n)<<endl; return 0;}// Contributed By: Harshit Sidhwa",
"e": 28657,
"s": 27576,
"text": null
},
{
"code": "// Java program to find minimum sum of two numbers// formed from all digits in a given array.import java.util.PriorityQueue; class MinSum{ // Returns sum of two numbers formed // from all digits in a[] public static long solve(int[] a) { // min Heap PriorityQueue<Integer> pq = new PriorityQueue<Integer>(); // to store the 2 numbers formed by array elements to // minimize the required sum StringBuilder num1 = new StringBuilder(); StringBuilder num2 = new StringBuilder(); // Adding elements in Priority Queue for (int x : a) pq.add(x); // checking if the priority queue is non empty while (!pq.isEmpty()) { num1.append(pq.poll()+ \"\"); if (!pq.isEmpty()) num2.append(pq.poll()+ \"\"); } // the required sum calculated long sum = Long.parseLong(num1.toString()) + Long.parseLong(num2.toString()); return sum; } // Driver code public static void main (String[] args) { int arr[] = {6, 8, 4, 5, 2, 3}; System.out.println(\"The required sum is \"+ solve(arr)); }}",
"e": 29833,
"s": 28657,
"text": null
},
{
"code": "# Python3 program to find minimum# sum of two numbers formed from# all digits in a given array.from queue import PriorityQueue # Returns sum of two numbers formed# from all digits in a[]def solve(a): # min Heap pq = PriorityQueue() # To store the 2 numbers # formed by array elements to # minimize the required sum num1 = \"\" num2 = \"\" # Adding elements in # Priority Queue for x in a: pq.put(x) # Checking if the priority # queue is non empty while not pq.empty(): num1 += str(pq.get()) if not pq.empty(): num2 += str(pq.get()) # The required sum calculated sum = int(num1) + int(num2) return sum # Driver codeif __name__==\"__main__\": arr = [ 6, 8, 4, 5, 2, 3 ] print(\"The required sum is \", solve(arr)) # This code is contributed by rutvik_56",
"e": 30693,
"s": 29833,
"text": null
},
{
"code": "// C# program to find minimum sum of two numbers// formed from all digits in a given array.using System;using System.Collections.Generic;class GFG{ // Returns sum of two numbers formed // from all digits in a[] public static long solve(int[] a) { // min Heap List<int> pq = new List<int>(); // to store the 2 numbers formed by array elements to // minimize the required sum string num1 = \"\"; string num2 = \"\"; // Adding elements in Priority Queue foreach(int x in a) pq.Add(x); pq.Sort(); // checking if the priority queue is non empty while (pq.Count > 0) { num1 = num1 + pq[0]; pq.RemoveAt(0); if (pq.Count > 0) { num2 = num2 + pq[0]; pq.RemoveAt(0); } } // the required sum calculated int sum = Int32.Parse(num1) + Int32.Parse(num2); return sum; } // Driver code static void Main() { int[] arr = {6, 8, 4, 5, 2, 3}; Console.WriteLine(\"The required sum is \"+ solve(arr)); }} // This code is contributed by divyesh072019.",
"e": 31889,
"s": 30693,
"text": null
},
{
"code": "<script> // Javascript program to find minimum sum of two numbers// formed from all digits in a given array. // Returns sum of two numbers formed // from all digits in a[] function solve(a) { // min Heap pq=[]; // to store the 2 numbers formed by array elements to // minimize the required sum let num1=\"\"; let num2=\"\"; // Adding elements in Priority Queue for(let x=0;x<a.length;x++) { pq.push(a[x]); } pq.sort(function(a,b){return b-a;}); // checking if the priority queue is non empty while(pq.length!=0) { num1+=pq.pop(); if(pq.length!=0) { num2+=pq.pop(); } } // the required sum calculated let sum=parseInt(num1)+parseInt(num2); return sum; } // Driver code let arr=[6, 8, 4, 5, 2, 3]; document.write(\"The required sum is \"+ solve(arr)); // This code is contributed by avanitrachhadiya2155 </script>",
"e": 32950,
"s": 31889,
"text": null
},
{
"code": null,
"e": 32959,
"s": 32950,
"text": "Output: "
},
{
"code": null,
"e": 32983,
"s": 32959,
"text": "The required sum is 604"
},
{
"code": null,
"e": 33601,
"s": 32983,
"text": "Another method: We can follow another approach also like this, as we need two numbers such that their sum is minimum, then we would also need two minimum numbers. If we arrange our array in ascending order then we can two digits that will form the smallest numbers, e.g., 2 3 4 5 6 8, now we can get two numbers starting from 2 and 3. First part is done now. Moving forward we have to form such that they would contain small digits, i.e. pick digits alternatively from array extend your two numbers. i.e. 246, 358. Now if we see analyze this, then we can pick even indexed numbers for num1 and an odd number for num2."
},
{
"code": null,
"e": 33630,
"s": 33601,
"text": "Below is the implementation:"
},
{
"code": null,
"e": 33634,
"s": 33630,
"text": "C++"
},
{
"code": null,
"e": 33636,
"s": 33634,
"text": "C"
},
{
"code": null,
"e": 33641,
"s": 33636,
"text": "Java"
},
{
"code": null,
"e": 33649,
"s": 33641,
"text": "Python3"
},
{
"code": null,
"e": 33652,
"s": 33649,
"text": "C#"
},
{
"code": null,
"e": 33656,
"s": 33652,
"text": "PHP"
},
{
"code": null,
"e": 33667,
"s": 33656,
"text": "Javascript"
},
{
"code": "// C++ program to find minimum sum of two numbers// formed from all digits in a given array.#include <bits/stdc++.h>using namespace std; // Returns sum of two numbers formed// from all digits in a[]int minSum(int a[], int n){ // sort the elements sort(a, a + n); int num1 = 0; int num2 = 0; for (int i = 0; i < n; i++) { if (i % 2 == 0) num1 = num1 * 10 + a[i]; else num2 = num2 * 10 + a[i]; } return num2 + num1;} // Driver codeint main(){ int arr[] = { 5, 3, 0, 7, 4 }; int n = sizeof(arr) / sizeof(arr[0]); cout << \"The required sum is \" << minSum(arr, n) << endl; return 0;} // This code is contributed by Sania Kumari Gupta",
"e": 34374,
"s": 33667,
"text": null
},
{
"code": "// C program to find minimum sum of two numbers// formed from all digits in a given array.#include <stdio.h>#include <stdlib.h>int cmpfunc(const void* a, const void* b){ return (*(int*)a - *(int*)b);} // Returns sum of two numbers formed// from all digits in a[]int minSum(int a[], int n){ // sort the elements qsort(a, n, sizeof(int), cmpfunc); // sort(a,a+n); int num1 = 0; int num2 = 0; for (int i = 0; i < n; i++) { if (i % 2 == 0) num1 = num1 * 10 + a[i]; else num2 = num2 * 10 + a[i]; } return num2 + num1;} // Driver codeint main(){ int arr[] = { 5, 3, 0, 7, 4 }; int n = sizeof(arr) / sizeof(arr[0]); printf(\"The required sum is %d\", minSum(arr, n)); return 0;} // This code is contributed by Sania Kumari Gupta",
"e": 35175,
"s": 34374,
"text": null
},
{
"code": "import java.util.Arrays;// Java program to find minimum sum of two numbers// formed from all digits in a given array.public class AQRQ { // Returns sum of two numbers formed // from all digits in a[] static int minSum(int a[], int n) { // sort the elements Arrays.sort(a); int num1 = 0; int num2 = 0; for (int i = 0; i < n; i++) { if (i % 2 == 0) num1 = num1 * 10 + a[i]; else num2 = num2 * 10 + a[i]; } return num2 + num1; } // Driver code public static void main(String[] args) { int arr[] = { 5, 3, 0, 7, 4 }; int n = arr.length; System.out.println(\"The required sum is \" + minSum(arr, n)); }} // This code is contributed by Sania Kumari Gupta",
"e": 36001,
"s": 35175,
"text": null
},
{
"code": "# Python 3 program to find minimum# sum of two numbers formed# from all digits in an given array # Returns sum of two numbers formed# from all digits in a[]def minSum(a, n): # sorted the elements a = sorted(a) num1, num2 = 0, 0 for i in range(n): if i % 2 == 0: num1 = num1 * 10 + a[i] else: num2 = num2 * 10 + a[i] return num2 + num1 # Driver codearr = [5, 3, 0, 7, 4]n = len(arr)print(\"The required sum is\", minSum(arr, n)) # This code is contributed# by Mohit kumar 29",
"e": 36563,
"s": 36001,
"text": null
},
{
"code": "// C# a program to find minimum sum of two numbers//formed from all digits in a given array. using System; public class GFG{ //Returns sum of two numbers formed //from all digits in a[] static int minSum(int []a, int n){ // sort the elements Array.Sort(a); int num1 = 0; int num2 = 0; for(int i = 0;i<n;i++){ if(i%2==0) num1 = num1*10+a[i]; else num2 = num2*10+a[i]; } return num2+num1; } //Driver code static public void Main (){ int []arr = {5, 3, 0, 7, 4}; int n = arr.Length; Console.WriteLine(\"The required sum is \" + minSum(arr, n)); }//This code is contributed by ajit. }",
"e": 37248,
"s": 36563,
"text": null
},
{
"code": "<?php// PHP program to find minimum sum// of two numbers formed from all// digits in a given array. // Returns sum of two numbers formed// from all digits in a[]function minSum($a, $n){ // sort the elements sort($a); $num1 = 0; $num2 = 0; for($i = 0; $i < $n; $i++) { if($i % 2 == 0) $num1 = $num1 * 10 + $a[$i]; else $num2 = $num2 * 10 + $a[$i]; } return ($num2 + $num1);} // Driver code$arr = array(5, 3, 0, 7, 4);$n = sizeof($arr);echo \"The required sum is \", minSum($arr, $n), \"\\n\"; // This Code is Contributed by ajit?>",
"e": 37836,
"s": 37248,
"text": null
},
{
"code": "<script> // JavaScript program to find minimum sum of two numbers // formed from all digits in a given array. // Returns sum of two numbers formed // from all digits in a[] function minSum(a, n){ // sort the elements a.sort(); let num1 = 0; let num2 = 0; for(let i = 0;i<n;i++){ if(i%2==0) num1 = num1*10+a[i]; else num2 = num2*10+a[i]; } return num2+num1; } let arr = [5, 3, 0, 7, 4]; let n = arr.length; document.write(\"The required sum is \" + minSum(arr, n)); </script>",
"e": 38440,
"s": 37836,
"text": null
},
{
"code": null,
"e": 38449,
"s": 38440,
"text": "Output: "
},
{
"code": null,
"e": 38472,
"s": 38449,
"text": "The required sum is 82"
},
{
"code": null,
"e": 38499,
"s": 38472,
"text": "Time Complexity : O(nLogN)"
},
{
"code": null,
"e": 38915,
"s": 38499,
"text": "This article is contributed by Prakhar. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 38928,
"s": 38915,
"text": "harrypotter0"
},
{
"code": null,
"e": 38942,
"s": 38928,
"text": "pushpender673"
},
{
"code": null,
"e": 38948,
"s": 38942,
"text": "jit_t"
},
{
"code": null,
"e": 38954,
"s": 38948,
"text": "ukasp"
},
{
"code": null,
"e": 38969,
"s": 38954,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 38979,
"s": 38969,
"text": "rutvik_56"
},
{
"code": null,
"e": 38996,
"s": 38979,
"text": "khushboogoyal499"
},
{
"code": null,
"e": 39010,
"s": 38996,
"text": "divyesh072019"
},
{
"code": null,
"e": 39019,
"s": 39010,
"text": "mukesh07"
},
{
"code": null,
"e": 39040,
"s": 39019,
"text": "avanitrachhadiya2155"
},
{
"code": null,
"e": 39052,
"s": 39040,
"text": "krisania804"
},
{
"code": null,
"e": 39066,
"s": 39052,
"text": "number-digits"
},
{
"code": null,
"e": 39073,
"s": 39066,
"text": "Arrays"
},
{
"code": null,
"e": 39080,
"s": 39073,
"text": "Greedy"
},
{
"code": null,
"e": 39085,
"s": 39080,
"text": "Heap"
},
{
"code": null,
"e": 39098,
"s": 39085,
"text": "Mathematical"
},
{
"code": null,
"e": 39104,
"s": 39098,
"text": "Queue"
},
{
"code": null,
"e": 39111,
"s": 39104,
"text": "Arrays"
},
{
"code": null,
"e": 39118,
"s": 39111,
"text": "Greedy"
},
{
"code": null,
"e": 39131,
"s": 39118,
"text": "Mathematical"
},
{
"code": null,
"e": 39137,
"s": 39131,
"text": "Queue"
},
{
"code": null,
"e": 39142,
"s": 39137,
"text": "Heap"
},
{
"code": null,
"e": 39240,
"s": 39142,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 39308,
"s": 39240,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 39331,
"s": 39308,
"text": "Introduction to Arrays"
},
{
"code": null,
"e": 39363,
"s": 39331,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 39377,
"s": 39363,
"text": "Linear Search"
},
{
"code": null,
"e": 39398,
"s": 39377,
"text": "Linked List vs Array"
},
{
"code": null,
"e": 39449,
"s": 39398,
"text": "Dijkstra's shortest path algorithm | Greedy Algo-7"
},
{
"code": null,
"e": 39507,
"s": 39449,
"text": "Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2"
},
{
"code": null,
"e": 39558,
"s": 39507,
"text": "Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5"
},
{
"code": null,
"e": 39618,
"s": 39558,
"text": "Write a program to print all permutations of a given string"
}
] |
How to select text nodes using jQuery ? - GeeksforGeeks
|
15 Nov, 2019
Text nodes are a type of node that denotes the actual text inside an element. The textNodes of any element can be selected using jQuery by selecting all the nodes and using the filter() method to check the nodeType property.
The required element is first selected using the jQuery selector. The contents() method is used on selected elements. This method is used to return the direct children of an element including all the text and comment nodes.
The filter() method is used on these returned elements to filter only the text nodes required. The custom filter function checks if the nodeType property of the nodes return equal to the Node.TEXT_NODE value.
The “Node.TEXT_NODE” value is used to identify a text node from other nodes. Alternatively, the integer value “3” could also be used to identify a text node. The filter() method will now only return the nodes that are textNodes. Therefore this method can be used to select the textNodes of any element.
Syntax:
selectedElement = $("elementRequired").contents(); textNodes = selectedElement.filter(function () { return this.nodeType === Node.TEXT_NODE;});
Example:
<!DOCTYPE html><html> <head> <title> How to select text nodes using jQuery? </title> <script src= "https://code.jquery.com/jquery-3.3.1.min.js"> </script></head> <body> <h1 style="color: green"> GeeksforGeeks </h1> <b> How to select text nodes using jQuery? </b> <p class="example"> This is line 1<br> This is line 2<br> This is line 3 </p> <button onclick="getTextNodes()"> Click to get Text Nodes </button> <script type="text/javascript"> function getTextNodes() { selectedElement = $(".example").contents(); textNodes = selectedElement.filter(function () { return this.nodeType === Node.TEXT_NODE; }); console.log(textNodes); } </script></body> </html>
Output:
Display:
Console:
jQuery-Misc
Picked
JQuery
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
jQuery | children() with Examples
How to Show and Hide div elements using radio buttons?
How to prevent Body from scrolling when a modal is opened using jQuery ?
How to redirect to a particular section of a page using HTML or jQuery?
jQuery | ajax() Method
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": 26886,
"s": 26858,
"text": "\n15 Nov, 2019"
},
{
"code": null,
"e": 27111,
"s": 26886,
"text": "Text nodes are a type of node that denotes the actual text inside an element. The textNodes of any element can be selected using jQuery by selecting all the nodes and using the filter() method to check the nodeType property."
},
{
"code": null,
"e": 27335,
"s": 27111,
"text": "The required element is first selected using the jQuery selector. The contents() method is used on selected elements. This method is used to return the direct children of an element including all the text and comment nodes."
},
{
"code": null,
"e": 27544,
"s": 27335,
"text": "The filter() method is used on these returned elements to filter only the text nodes required. The custom filter function checks if the nodeType property of the nodes return equal to the Node.TEXT_NODE value."
},
{
"code": null,
"e": 27847,
"s": 27544,
"text": "The “Node.TEXT_NODE” value is used to identify a text node from other nodes. Alternatively, the integer value “3” could also be used to identify a text node. The filter() method will now only return the nodes that are textNodes. Therefore this method can be used to select the textNodes of any element."
},
{
"code": null,
"e": 27855,
"s": 27847,
"text": "Syntax:"
},
{
"code": "selectedElement = $(\"elementRequired\").contents(); textNodes = selectedElement.filter(function () { return this.nodeType === Node.TEXT_NODE;});",
"e": 28000,
"s": 27855,
"text": null
},
{
"code": null,
"e": 28009,
"s": 28000,
"text": "Example:"
},
{
"code": "<!DOCTYPE html><html> <head> <title> How to select text nodes using jQuery? </title> <script src= \"https://code.jquery.com/jquery-3.3.1.min.js\"> </script></head> <body> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b> How to select text nodes using jQuery? </b> <p class=\"example\"> This is line 1<br> This is line 2<br> This is line 3 </p> <button onclick=\"getTextNodes()\"> Click to get Text Nodes </button> <script type=\"text/javascript\"> function getTextNodes() { selectedElement = $(\".example\").contents(); textNodes = selectedElement.filter(function () { return this.nodeType === Node.TEXT_NODE; }); console.log(textNodes); } </script></body> </html>",
"e": 28908,
"s": 28009,
"text": null
},
{
"code": null,
"e": 28916,
"s": 28908,
"text": "Output:"
},
{
"code": null,
"e": 28925,
"s": 28916,
"text": "Display:"
},
{
"code": null,
"e": 28934,
"s": 28925,
"text": "Console:"
},
{
"code": null,
"e": 28946,
"s": 28934,
"text": "jQuery-Misc"
},
{
"code": null,
"e": 28953,
"s": 28946,
"text": "Picked"
},
{
"code": null,
"e": 28960,
"s": 28953,
"text": "JQuery"
},
{
"code": null,
"e": 28977,
"s": 28960,
"text": "Web Technologies"
},
{
"code": null,
"e": 29004,
"s": 28977,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 29102,
"s": 29004,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29136,
"s": 29102,
"text": "jQuery | children() with Examples"
},
{
"code": null,
"e": 29191,
"s": 29136,
"text": "How to Show and Hide div elements using radio buttons?"
},
{
"code": null,
"e": 29264,
"s": 29191,
"text": "How to prevent Body from scrolling when a modal is opened using jQuery ?"
},
{
"code": null,
"e": 29336,
"s": 29264,
"text": "How to redirect to a particular section of a page using HTML or jQuery?"
},
{
"code": null,
"e": 29359,
"s": 29336,
"text": "jQuery | ajax() Method"
},
{
"code": null,
"e": 29399,
"s": 29359,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 29432,
"s": 29399,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 29477,
"s": 29432,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 29520,
"s": 29477,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
What is PathVariable in the Spring Boot? - GeeksforGeeks
|
23 Nov, 2021
Java language is one of the most popular languages among all programming languages. There are several advantages of using the java programming language, whether for security purposes or building large distribution projects. One of the advantages of using JAVA is that Java tries to connect every concept in the language to the real world with the help of the concepts of classes, inheritance, polymorphism, etc.
There are several other concepts present in java that increase the user-friendly interaction between the java code and the programmer such as generic, access specifiers, annotations in java, etc these features add an extra property to the class as well method of the java program. In this article, we will discuss what is path variable is in the spring boot.
Path variable in the spring boot represents different kinds of parameters in the incoming request with the help of @pathvariable annotation.
Note: First we need to establish the spring application in our project.
Spring Initializr is a web-based tool using which we can easily generate the structure of the Spring Boot project. It also provides various different features for the projects expressed in a metadata model. This model allows us to configure the list of dependencies that are supported by JVM. Here, we will create the structure of an application using a spring initializer and then use an IDE to create a sample GET route. Therefore, to do this, the following steps are followed:
Step 1: Go to Spring Initializr
Step 2: Fill in the details as per the requirements. For this application:
Project: Maven
Language: Java
Spring Boot: 2.2.8
Packaging: JAR
Java: 8
Dependencies: Spring Web
Step 3: Click on Generate which will download the starter project.
Step 4: Extract the zip file. Now open a suitable IDE and then go to File->New->Project from existing sources->Spring-boot-app and select pom.xml. Click on import changes on prompt and wait for the project to sync as pictorially depicted below as follows:
Note: In the Import Project for Maven window, make sure you choose the same version of JDK which you selected while creating the project.
Step 5: Go to src->main->java->com.gfg.Spring.boot.app, create a java class with the name Controller and add the annotation @RestController. Now create a GET API as shown below:
Example 1: Controller.java
@RestController
// Class
public class Controller {
@GetMapping("/hello/{name}/{age}")
public void insert(@PathVariable("name") String name,
@PathVariable("age") int age) {
// Print and display name and age
System.out.println(name);
System.out.println(age);
}
}
This application is now ready to run.
Step 6: Run the SpringBootAppApplication class and wait for the Tomcat server to start.
Note: The default port of the Tomcat server is 8080 and can be changed in the application.properties file.
Step 7: Lastly now go to the browser and enter the URL localhost:8080. Observe the output and now do the same for localhost:8080/hello/Aayush/23
Output:
Aayush
23
zack_aayush
Java-Spring-Boot
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": "\n23 Nov, 2021"
},
{
"code": null,
"e": 25637,
"s": 25225,
"text": "Java language is one of the most popular languages among all programming languages. There are several advantages of using the java programming language, whether for security purposes or building large distribution projects. One of the advantages of using JAVA is that Java tries to connect every concept in the language to the real world with the help of the concepts of classes, inheritance, polymorphism, etc."
},
{
"code": null,
"e": 25996,
"s": 25637,
"text": "There are several other concepts present in java that increase the user-friendly interaction between the java code and the programmer such as generic, access specifiers, annotations in java, etc these features add an extra property to the class as well method of the java program. In this article, we will discuss what is path variable is in the spring boot."
},
{
"code": null,
"e": 26137,
"s": 25996,
"text": "Path variable in the spring boot represents different kinds of parameters in the incoming request with the help of @pathvariable annotation."
},
{
"code": null,
"e": 26209,
"s": 26137,
"text": "Note: First we need to establish the spring application in our project."
},
{
"code": null,
"e": 26689,
"s": 26209,
"text": "Spring Initializr is a web-based tool using which we can easily generate the structure of the Spring Boot project. It also provides various different features for the projects expressed in a metadata model. This model allows us to configure the list of dependencies that are supported by JVM. Here, we will create the structure of an application using a spring initializer and then use an IDE to create a sample GET route. Therefore, to do this, the following steps are followed:"
},
{
"code": null,
"e": 26721,
"s": 26689,
"text": "Step 1: Go to Spring Initializr"
},
{
"code": null,
"e": 26796,
"s": 26721,
"text": "Step 2: Fill in the details as per the requirements. For this application:"
},
{
"code": null,
"e": 26893,
"s": 26796,
"text": "Project: Maven\nLanguage: Java\nSpring Boot: 2.2.8\nPackaging: JAR\nJava: 8\nDependencies: Spring Web"
},
{
"code": null,
"e": 26960,
"s": 26893,
"text": "Step 3: Click on Generate which will download the starter project."
},
{
"code": null,
"e": 27216,
"s": 26960,
"text": "Step 4: Extract the zip file. Now open a suitable IDE and then go to File->New->Project from existing sources->Spring-boot-app and select pom.xml. Click on import changes on prompt and wait for the project to sync as pictorially depicted below as follows:"
},
{
"code": null,
"e": 27354,
"s": 27216,
"text": "Note: In the Import Project for Maven window, make sure you choose the same version of JDK which you selected while creating the project."
},
{
"code": null,
"e": 27532,
"s": 27354,
"text": "Step 5: Go to src->main->java->com.gfg.Spring.boot.app, create a java class with the name Controller and add the annotation @RestController. Now create a GET API as shown below:"
},
{
"code": null,
"e": 27559,
"s": 27532,
"text": "Example 1: Controller.java"
},
{
"code": null,
"e": 27883,
"s": 27559,
"text": "@RestController\n\n// Class\npublic class Controller {\n\n @GetMapping(\"/hello/{name}/{age}\")\n\n public void insert(@PathVariable(\"name\") String name,\n @PathVariable(\"age\") int age) {\n\n // Print and display name and age\n System.out.println(name);\n System.out.println(age);\n }\n}"
},
{
"code": null,
"e": 27922,
"s": 27883,
"text": "This application is now ready to run. "
},
{
"code": null,
"e": 28010,
"s": 27922,
"text": "Step 6: Run the SpringBootAppApplication class and wait for the Tomcat server to start."
},
{
"code": null,
"e": 28117,
"s": 28010,
"text": "Note: The default port of the Tomcat server is 8080 and can be changed in the application.properties file."
},
{
"code": null,
"e": 28262,
"s": 28117,
"text": "Step 7: Lastly now go to the browser and enter the URL localhost:8080. Observe the output and now do the same for localhost:8080/hello/Aayush/23"
},
{
"code": null,
"e": 28271,
"s": 28262,
"text": "Output: "
},
{
"code": null,
"e": 28281,
"s": 28271,
"text": "Aayush\n23"
},
{
"code": null,
"e": 28293,
"s": 28281,
"text": "zack_aayush"
},
{
"code": null,
"e": 28310,
"s": 28293,
"text": "Java-Spring-Boot"
},
{
"code": null,
"e": 28315,
"s": 28310,
"text": "Java"
},
{
"code": null,
"e": 28320,
"s": 28315,
"text": "Java"
},
{
"code": null,
"e": 28418,
"s": 28320,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28433,
"s": 28418,
"text": "Stream In Java"
},
{
"code": null,
"e": 28454,
"s": 28433,
"text": "Constructors in Java"
},
{
"code": null,
"e": 28473,
"s": 28454,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 28503,
"s": 28473,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 28549,
"s": 28503,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 28566,
"s": 28549,
"text": "Generics in Java"
},
{
"code": null,
"e": 28587,
"s": 28566,
"text": "Introduction to Java"
},
{
"code": null,
"e": 28630,
"s": 28587,
"text": "Comparator Interface in Java with Examples"
},
{
"code": null,
"e": 28666,
"s": 28630,
"text": "Internal Working of HashMap in Java"
}
] |
Vue.js | v-show directive - GeeksforGeeks
|
22 Jun, 2020
The v-show directive is a Vue.js directive used to toggle the display CSS property of a element with our data. If the data is true it will make it visible else it will make it invisible. First, we will create a div element with id as app and let’s apply the v-show directive to this element with data as a message. Now we will create this message by initializing a Vue instance with the data attribute containing either true or false.Syntax:
v-show="data"
Parameters: This directive accepts a single parameter which is the data. Example 1: This example uses VueJS to show an element with v-show.
HTML
<!DOCTYPE html><html> <head> <title> VueJS | v-show directive </title> <!-- Load Vuejs --> <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"> </script> </head> <body> <div style="text-align: center; width: 600px;"> <h1 style="color: green;"> GeeksforGeeks </h1> <b> VueJS | v-show directive </b> </div> <div id="canvas" style="border: 1px solid #000000; width: 600px; height: 200px;"> <div v-show="message" id="app"> Hello I'm visible. </div> </div> <script> var app = new Vue({ el: "#app", data: { message: true, }, }); </script> </body></html>
Output:
Example 2: This example uses VueJS to hide an element with v-show.
HTML
<!DOCTYPE html><html> <head> <title> VueJS | v-show directive </title> <!-- Load Vuejs --> <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"> </script></head> <body> <div style="text-align: center;width: 600px;"> <h1 style="color: green;"> GeeksforGeeks </h1> <b> VueJS | v-show directive </b> </div> <div id="canvas" style="border:1px solid #000000; width: 600px;height: 200px;"> <div v-show="message" id="app"> Hello I'm invisible. </div> </div> <script> var app = new Vue({ el: '#app', data: { message: false } }) </script></body> </html>
Output:
Vue.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 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": 25589,
"s": 25561,
"text": "\n22 Jun, 2020"
},
{
"code": null,
"e": 26031,
"s": 25589,
"text": "The v-show directive is a Vue.js directive used to toggle the display CSS property of a element with our data. If the data is true it will make it visible else it will make it invisible. First, we will create a div element with id as app and let’s apply the v-show directive to this element with data as a message. Now we will create this message by initializing a Vue instance with the data attribute containing either true or false.Syntax:"
},
{
"code": null,
"e": 26045,
"s": 26031,
"text": "v-show=\"data\""
},
{
"code": null,
"e": 26185,
"s": 26045,
"text": "Parameters: This directive accepts a single parameter which is the data. Example 1: This example uses VueJS to show an element with v-show."
},
{
"code": null,
"e": 26190,
"s": 26185,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <title> VueJS | v-show directive </title> <!-- Load Vuejs --> <script src=\"https://cdn.jsdelivr.net/npm/vue/dist/vue.js\"> </script> </head> <body> <div style=\"text-align: center; width: 600px;\"> <h1 style=\"color: green;\"> GeeksforGeeks </h1> <b> VueJS | v-show directive </b> </div> <div id=\"canvas\" style=\"border: 1px solid #000000; width: 600px; height: 200px;\"> <div v-show=\"message\" id=\"app\"> Hello I'm visible. </div> </div> <script> var app = new Vue({ el: \"#app\", data: { message: true, }, }); </script> </body></html>",
"e": 27081,
"s": 26190,
"text": null
},
{
"code": null,
"e": 27089,
"s": 27081,
"text": "Output:"
},
{
"code": null,
"e": 27156,
"s": 27089,
"text": "Example 2: This example uses VueJS to hide an element with v-show."
},
{
"code": null,
"e": 27161,
"s": 27156,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <title> VueJS | v-show directive </title> <!-- Load Vuejs --> <script src=\"https://cdn.jsdelivr.net/npm/vue/dist/vue.js\"> </script></head> <body> <div style=\"text-align: center;width: 600px;\"> <h1 style=\"color: green;\"> GeeksforGeeks </h1> <b> VueJS | v-show directive </b> </div> <div id=\"canvas\" style=\"border:1px solid #000000; width: 600px;height: 200px;\"> <div v-show=\"message\" id=\"app\"> Hello I'm invisible. </div> </div> <script> var app = new Vue({ el: '#app', data: { message: false } }) </script></body> </html>",
"e": 27925,
"s": 27161,
"text": null
},
{
"code": null,
"e": 27933,
"s": 27925,
"text": "Output:"
},
{
"code": null,
"e": 27940,
"s": 27933,
"text": "Vue.JS"
},
{
"code": null,
"e": 27951,
"s": 27940,
"text": "JavaScript"
},
{
"code": null,
"e": 27968,
"s": 27951,
"text": "Web Technologies"
},
{
"code": null,
"e": 28066,
"s": 27968,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28106,
"s": 28066,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 28151,
"s": 28106,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 28212,
"s": 28151,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 28284,
"s": 28212,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 28336,
"s": 28284,
"text": "How to append HTML code to a div using JavaScript ?"
},
{
"code": null,
"e": 28376,
"s": 28336,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 28409,
"s": 28376,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 28454,
"s": 28409,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 28497,
"s": 28454,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
Understanding File System - GeeksforGeeks
|
03 Mar, 2020
Prerequisite – File Systems in Operating System
Files and folders are the non-detachable part of human life. We daily go through these two name and use them unknowingly. These files do have different types, that has been evolved as the requirement of the user and developers changed. Some tech giants build their own file system to increase the market of their products, they also did changes and enhanced the technology of storing file on any kind of storage.
Some of the most popular file storage systems are: –
(i). FAT
(i). NTFS
(i). HFS
(i). EXT
These are explained as following below.
(i). FAT (File Allocation Table):FAT stands for File Allocation Table and this is called so because it allocates different file and folders using tables. This was originally designed to handle small file systems and disks. This system majorly has three variant FAT12, FAT16 and FAT32 which were introduced in 1980, 1984 and 1996 respectively.These variant have their own pros and cons, like FAT32 (mostly used in pen drive and micro SD). It could store or copy a file with max size of 4GB (size of a single file to be stored) if the size of file exceeds 4GB it won’t copy on storage media, but its partition size was up to 8TB(size of partition on which FAT could be applied).Figure – FAT File SystemThis file system was used by windows in its initial time, now windows has switched to NTFS which is also a file system of its own kind, we will learn about it.
These variant have their own pros and cons, like FAT32 (mostly used in pen drive and micro SD). It could store or copy a file with max size of 4GB (size of a single file to be stored) if the size of file exceeds 4GB it won’t copy on storage media, but its partition size was up to 8TB(size of partition on which FAT could be applied).
This file system was used by windows in its initial time, now windows has switched to NTFS which is also a file system of its own kind, we will learn about it.
(ii). NTFS (New Technology File System):Windows NT has come with a new file system called NTFS in 1993. This stands for New Technology File System. This was an enhanced and more advanced version of FAT systems. All Windows installation is done on NTFS, it first formats the storage in NFTS format and then install on it. Mostly NTFS is done on internal drives.This has no file size limits and no partition or volume limits. Theoretically up to 16 EiB size of a single file.Figure – NTFS File SystemJournaling – This technique records the metadata and its changes in the volume or partition.Transactions – This function enable files and folders to be recreated, renamed, deleted and many more without affecting others.
This has no file size limits and no partition or volume limits. Theoretically up to 16 EiB size of a single file.
Journaling – This technique records the metadata and its changes in the volume or partition.
Transactions – This function enable files and folders to be recreated, renamed, deleted and many more without affecting others.
(iii). HFS (Hierarchical File System):HFS stands for Hierarchical File System, as the name suggests us this is a hierarchy of files and folders. This is especially designed for mac OS by Apple. The higher version which is in market is AHFS Apple Hierarchical File System. This was originally and initially designed for medial like floppy and HDD, at some extent use on CD – Rom as read only.Figure – HFS File SystemMax file size = 2GB
Max volume size = 2TB
Max file size = 2GB
Max volume size = 2TB
(iv). EXT (Extended File System):Originally developed for UNIX and LINUX like Operating Systems. Its first variant came into market in 1992.Variant by variant this has overcome the limitations like size of single file, size of volume, number of files in a folder or directory. We have many software which could help in developing ext2 environment on Windows OS.Figure – ext File SystemMax file size EXT4 = 16TB
Max volume size EXT4 = 50TB
Max file size EXT4 = 16TB
Max volume size EXT4 = 50TB
Which is the best File System ?Quality depends on its use cases, as we know in computer science world there is no best programming language similarly there is no best file system but has different implementations. Linux is most compatible with ext, Windows is with NTFS and FAT and Mac OS with HFS, AHFS.
How to change File System of storage devices like pen drive and micro SD ?There are two ways:
Formatting the drive, choose file system – you would lost all your data.Using some software – you won’t lose any data but have to install some software which could be paid or free.
Formatting the drive, choose file system – you would lost all your data.
Using some software – you won’t lose any data but have to install some software which could be paid or free.
GATE CS
Operating Systems
Operating Systems
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Differences between IPv4 and IPv6
Preemptive and Non-Preemptive Scheduling
Difference between Clustered and Non-clustered index
Phases of a Compiler
Three address code in Compiler
Banker's Algorithm in Operating System
Program for FCFS CPU Scheduling | Set 1
Paging in Operating System
Introduction of Deadlock in Operating System
Program for Round Robin scheduling | Set 1
|
[
{
"code": null,
"e": 25627,
"s": 25599,
"text": "\n03 Mar, 2020"
},
{
"code": null,
"e": 25675,
"s": 25627,
"text": "Prerequisite – File Systems in Operating System"
},
{
"code": null,
"e": 26088,
"s": 25675,
"text": "Files and folders are the non-detachable part of human life. We daily go through these two name and use them unknowingly. These files do have different types, that has been evolved as the requirement of the user and developers changed. Some tech giants build their own file system to increase the market of their products, they also did changes and enhanced the technology of storing file on any kind of storage."
},
{
"code": null,
"e": 26141,
"s": 26088,
"text": "Some of the most popular file storage systems are: –"
},
{
"code": null,
"e": 26179,
"s": 26141,
"text": "(i). FAT\n(i). NTFS\n(i). HFS\n(i). EXT "
},
{
"code": null,
"e": 26219,
"s": 26179,
"text": "These are explained as following below."
},
{
"code": null,
"e": 27079,
"s": 26219,
"text": "(i). FAT (File Allocation Table):FAT stands for File Allocation Table and this is called so because it allocates different file and folders using tables. This was originally designed to handle small file systems and disks. This system majorly has three variant FAT12, FAT16 and FAT32 which were introduced in 1980, 1984 and 1996 respectively.These variant have their own pros and cons, like FAT32 (mostly used in pen drive and micro SD). It could store or copy a file with max size of 4GB (size of a single file to be stored) if the size of file exceeds 4GB it won’t copy on storage media, but its partition size was up to 8TB(size of partition on which FAT could be applied).Figure – FAT File SystemThis file system was used by windows in its initial time, now windows has switched to NTFS which is also a file system of its own kind, we will learn about it."
},
{
"code": null,
"e": 27414,
"s": 27079,
"text": "These variant have their own pros and cons, like FAT32 (mostly used in pen drive and micro SD). It could store or copy a file with max size of 4GB (size of a single file to be stored) if the size of file exceeds 4GB it won’t copy on storage media, but its partition size was up to 8TB(size of partition on which FAT could be applied)."
},
{
"code": null,
"e": 27574,
"s": 27414,
"text": "This file system was used by windows in its initial time, now windows has switched to NTFS which is also a file system of its own kind, we will learn about it."
},
{
"code": null,
"e": 28292,
"s": 27574,
"text": "(ii). NTFS (New Technology File System):Windows NT has come with a new file system called NTFS in 1993. This stands for New Technology File System. This was an enhanced and more advanced version of FAT systems. All Windows installation is done on NTFS, it first formats the storage in NFTS format and then install on it. Mostly NTFS is done on internal drives.This has no file size limits and no partition or volume limits. Theoretically up to 16 EiB size of a single file.Figure – NTFS File SystemJournaling – This technique records the metadata and its changes in the volume or partition.Transactions – This function enable files and folders to be recreated, renamed, deleted and many more without affecting others."
},
{
"code": null,
"e": 28406,
"s": 28292,
"text": "This has no file size limits and no partition or volume limits. Theoretically up to 16 EiB size of a single file."
},
{
"code": null,
"e": 28499,
"s": 28406,
"text": "Journaling – This technique records the metadata and its changes in the volume or partition."
},
{
"code": null,
"e": 28627,
"s": 28499,
"text": "Transactions – This function enable files and folders to be recreated, renamed, deleted and many more without affecting others."
},
{
"code": null,
"e": 29085,
"s": 28627,
"text": "(iii). HFS (Hierarchical File System):HFS stands for Hierarchical File System, as the name suggests us this is a hierarchy of files and folders. This is especially designed for mac OS by Apple. The higher version which is in market is AHFS Apple Hierarchical File System. This was originally and initially designed for medial like floppy and HDD, at some extent use on CD – Rom as read only.Figure – HFS File SystemMax file size = 2GB\nMax volume size = 2TB "
},
{
"code": null,
"e": 29128,
"s": 29085,
"text": "Max file size = 2GB\nMax volume size = 2TB "
},
{
"code": null,
"e": 29568,
"s": 29128,
"text": "(iv). EXT (Extended File System):Originally developed for UNIX and LINUX like Operating Systems. Its first variant came into market in 1992.Variant by variant this has overcome the limitations like size of single file, size of volume, number of files in a folder or directory. We have many software which could help in developing ext2 environment on Windows OS.Figure – ext File SystemMax file size EXT4 = 16TB\nMax volume size EXT4 = 50TB "
},
{
"code": null,
"e": 29623,
"s": 29568,
"text": "Max file size EXT4 = 16TB\nMax volume size EXT4 = 50TB "
},
{
"code": null,
"e": 29928,
"s": 29623,
"text": "Which is the best File System ?Quality depends on its use cases, as we know in computer science world there is no best programming language similarly there is no best file system but has different implementations. Linux is most compatible with ext, Windows is with NTFS and FAT and Mac OS with HFS, AHFS."
},
{
"code": null,
"e": 30022,
"s": 29928,
"text": "How to change File System of storage devices like pen drive and micro SD ?There are two ways:"
},
{
"code": null,
"e": 30203,
"s": 30022,
"text": "Formatting the drive, choose file system – you would lost all your data.Using some software – you won’t lose any data but have to install some software which could be paid or free."
},
{
"code": null,
"e": 30276,
"s": 30203,
"text": "Formatting the drive, choose file system – you would lost all your data."
},
{
"code": null,
"e": 30385,
"s": 30276,
"text": "Using some software – you won’t lose any data but have to install some software which could be paid or free."
},
{
"code": null,
"e": 30393,
"s": 30385,
"text": "GATE CS"
},
{
"code": null,
"e": 30411,
"s": 30393,
"text": "Operating Systems"
},
{
"code": null,
"e": 30429,
"s": 30411,
"text": "Operating Systems"
},
{
"code": null,
"e": 30527,
"s": 30429,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30561,
"s": 30527,
"text": "Differences between IPv4 and IPv6"
},
{
"code": null,
"e": 30602,
"s": 30561,
"text": "Preemptive and Non-Preemptive Scheduling"
},
{
"code": null,
"e": 30655,
"s": 30602,
"text": "Difference between Clustered and Non-clustered index"
},
{
"code": null,
"e": 30676,
"s": 30655,
"text": "Phases of a Compiler"
},
{
"code": null,
"e": 30707,
"s": 30676,
"text": "Three address code in Compiler"
},
{
"code": null,
"e": 30746,
"s": 30707,
"text": "Banker's Algorithm in Operating System"
},
{
"code": null,
"e": 30786,
"s": 30746,
"text": "Program for FCFS CPU Scheduling | Set 1"
},
{
"code": null,
"e": 30813,
"s": 30786,
"text": "Paging in Operating System"
},
{
"code": null,
"e": 30858,
"s": 30813,
"text": "Introduction of Deadlock in Operating System"
}
] |
Instruction Word Size in Microprocessor - GeeksforGeeks
|
21 Aug, 2019
The 8085 instruction set is classified into 3 categories by considering the length of the instructions. In 8085, the length is measured in terms of “byte” rather then “word” because 8085 microprocessor has 8-bit data bus. Three types of instruction are: 1-byte instruction, 2-byte instruction, and 3-byte instruction.
1. One-byte instructions –In 1-byte instruction, the opcode and the operand of an instruction are represented in one byte.
Example-1:Task- Copy the contents of accumulator in register B.Mnemonic- MOV B, A
Opcode- MOV
Operand- B, A
Hex Code- 47H
Binary code- 0100 0111
Mnemonic- MOV B, A
Opcode- MOV
Operand- B, A
Hex Code- 47H
Binary code- 0100 0111
Example-2:Task- Add the contents of accumulator to the contents of register B. Mnemonic- ADD B
Opcode- ADD
Operand- B
Hex Code- 80H
Binary code- 1000 0000
Mnemonic- ADD B
Opcode- ADD
Operand- B
Hex Code- 80H
Binary code- 1000 0000
Example-3:Task- Invert (complement) each bit in the accumulator.Mnemonic- CMA
Opcode- CMA
Operand- NA
Hex Code- 2FH
Binary code- 0010 1111
Mnemonic- CMA
Opcode- CMA
Operand- NA
Hex Code- 2FH
Binary code- 0010 1111
Note – The length of these instructions is 8-bit; each requires one memory location. The mnemonic is always followed by a letter (or two letters) representing the registers (such as A, B, C, D, E, H, L and SP).
2. Two-byte instructions –Two-byte instruction is the type of instruction in which the first 8 bits indicates the opcode and the next 8 bits indicates the operand.
Example-1:Task- Load the hexadecimal data 32H in the accumulator.Mnemonic- MVI A, 32H
Opcode- MVI
Operand- A, 32H
Hex Code- 3E
32
Binary code- 0011 1110
0011 0010
Mnemonic- MVI A, 32H
Opcode- MVI
Operand- A, 32H
Hex Code- 3E
32
Binary code- 0011 1110
0011 0010
Example-2:Task- Load the hexadecimal data F2H in the register B.Mnemonic- MVI B, F2H
Opcode- MVI
Operand- B, F2H
Hex Code- 06
F2
Binary code- 0000 0110
1111 0010
Mnemonic- MVI B, F2H
Opcode- MVI
Operand- B, F2H
Hex Code- 06
F2
Binary code- 0000 0110
1111 0010
Note – This type of instructions need two bytes to store the binary codes. The mnemonic is always followed by 8-bit (byte) data.
3. Three-byte instructions –Three-byte instruction is the type of instruction in which the first 8 bits indicates the opcode and the next two bytes specify the 16-bit address. The low-order address is represented in second byte and the high-order address is represented in the third byte.
Example-1:Task- Load contents of memory 2050H in the accumulator.Mnemonic- LDA 2050H
Opcode- LDA
Operand- 2050H
Hex Code- 3A
50
20
Binary code- 0011 1010
0101 0000
0010 0000
Mnemonic- LDA 2050H
Opcode- LDA
Operand- 2050H
Hex Code- 3A
50
20
Binary code- 0011 1010
0101 0000
0010 0000
Example-2:Task- Transfer the program sequence to the memory location 2050H.Mnemonic- JMP 2085H
Opcode- JMP
Operand- 2085H
Hex Code- C3
85
20
Binary code- 1100 0011
1000 0101
0010 0000
Mnemonic- JMP 2085H
Opcode- JMP
Operand- 2085H
Hex Code- C3
85
20
Binary code- 1100 0011
1000 0101
0010 0000
Note – These instructions would require three memory locations to store the binary codes. The mnemonic is always followed by 16-bit (or adr).
microprocessor
Computer Organization & Architecture
GATE CS
microprocessor
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Logical and Physical Address in Operating System
Computer Organization and Architecture | Pipelining | Set 1 (Execution, Stages and Throughput)
Memory Hierarchy Design and its Characteristics
Computer Organization | RISC and CISC
Direct Access Media (DMA) Controller in Computer Architecture
Layers of OSI Model
ACID Properties in DBMS
TCP/IP Model
Types of Operating Systems
Normal Forms in DBMS
|
[
{
"code": null,
"e": 25731,
"s": 25703,
"text": "\n21 Aug, 2019"
},
{
"code": null,
"e": 26049,
"s": 25731,
"text": "The 8085 instruction set is classified into 3 categories by considering the length of the instructions. In 8085, the length is measured in terms of “byte” rather then “word” because 8085 microprocessor has 8-bit data bus. Three types of instruction are: 1-byte instruction, 2-byte instruction, and 3-byte instruction."
},
{
"code": null,
"e": 26172,
"s": 26049,
"text": "1. One-byte instructions –In 1-byte instruction, the opcode and the operand of an instruction are represented in one byte."
},
{
"code": null,
"e": 26318,
"s": 26172,
"text": "Example-1:Task- Copy the contents of accumulator in register B.Mnemonic- MOV B, A\nOpcode- MOV\nOperand- B, A\nHex Code- 47H\nBinary code- 0100 0111 "
},
{
"code": null,
"e": 26401,
"s": 26318,
"text": "Mnemonic- MOV B, A\nOpcode- MOV\nOperand- B, A\nHex Code- 47H\nBinary code- 0100 0111 "
},
{
"code": null,
"e": 26557,
"s": 26401,
"text": "Example-2:Task- Add the contents of accumulator to the contents of register B. Mnemonic- ADD B\nOpcode- ADD\nOperand- B\nHex Code- 80H\nBinary code- 1000 0000 "
},
{
"code": null,
"e": 26635,
"s": 26557,
"text": " Mnemonic- ADD B\nOpcode- ADD\nOperand- B\nHex Code- 80H\nBinary code- 1000 0000 "
},
{
"code": null,
"e": 26776,
"s": 26635,
"text": "Example-3:Task- Invert (complement) each bit in the accumulator.Mnemonic- CMA\nOpcode- CMA\nOperand- NA\nHex Code- 2FH\nBinary code- 0010 1111 "
},
{
"code": null,
"e": 26853,
"s": 26776,
"text": "Mnemonic- CMA\nOpcode- CMA\nOperand- NA\nHex Code- 2FH\nBinary code- 0010 1111 "
},
{
"code": null,
"e": 27064,
"s": 26853,
"text": "Note – The length of these instructions is 8-bit; each requires one memory location. The mnemonic is always followed by a letter (or two letters) representing the registers (such as A, B, C, D, E, H, L and SP)."
},
{
"code": null,
"e": 27228,
"s": 27064,
"text": "2. Two-byte instructions –Two-byte instruction is the type of instruction in which the first 8 bits indicates the opcode and the next 8 bits indicates the operand."
},
{
"code": null,
"e": 27392,
"s": 27228,
"text": "Example-1:Task- Load the hexadecimal data 32H in the accumulator.Mnemonic- MVI A, 32H\nOpcode- MVI\nOperand- A, 32H\nHex Code- 3E\n32\nBinary code- 0011 1110\n0011 0010 "
},
{
"code": null,
"e": 27491,
"s": 27392,
"text": "Mnemonic- MVI A, 32H\nOpcode- MVI\nOperand- A, 32H\nHex Code- 3E\n32\nBinary code- 0011 1110\n0011 0010 "
},
{
"code": null,
"e": 27654,
"s": 27491,
"text": "Example-2:Task- Load the hexadecimal data F2H in the register B.Mnemonic- MVI B, F2H\nOpcode- MVI\nOperand- B, F2H\nHex Code- 06\nF2\nBinary code- 0000 0110\n1111 0010 "
},
{
"code": null,
"e": 27753,
"s": 27654,
"text": "Mnemonic- MVI B, F2H\nOpcode- MVI\nOperand- B, F2H\nHex Code- 06\nF2\nBinary code- 0000 0110\n1111 0010 "
},
{
"code": null,
"e": 27882,
"s": 27753,
"text": "Note – This type of instructions need two bytes to store the binary codes. The mnemonic is always followed by 8-bit (byte) data."
},
{
"code": null,
"e": 28171,
"s": 27882,
"text": "3. Three-byte instructions –Three-byte instruction is the type of instruction in which the first 8 bits indicates the opcode and the next two bytes specify the 16-bit address. The low-order address is represented in second byte and the high-order address is represented in the third byte."
},
{
"code": null,
"e": 28346,
"s": 28171,
"text": "Example-1:Task- Load contents of memory 2050H in the accumulator.Mnemonic- LDA 2050H\nOpcode- LDA\nOperand- 2050H\nHex Code- 3A\n50\n20\nBinary code- 0011 1010\n0101 0000\n0010 0000 "
},
{
"code": null,
"e": 28456,
"s": 28346,
"text": "Mnemonic- LDA 2050H\nOpcode- LDA\nOperand- 2050H\nHex Code- 3A\n50\n20\nBinary code- 0011 1010\n0101 0000\n0010 0000 "
},
{
"code": null,
"e": 28641,
"s": 28456,
"text": "Example-2:Task- Transfer the program sequence to the memory location 2050H.Mnemonic- JMP 2085H\nOpcode- JMP\nOperand- 2085H\nHex Code- C3\n85\n20\nBinary code- 1100 0011\n1000 0101\n0010 0000 "
},
{
"code": null,
"e": 28751,
"s": 28641,
"text": "Mnemonic- JMP 2085H\nOpcode- JMP\nOperand- 2085H\nHex Code- C3\n85\n20\nBinary code- 1100 0011\n1000 0101\n0010 0000 "
},
{
"code": null,
"e": 28893,
"s": 28751,
"text": "Note – These instructions would require three memory locations to store the binary codes. The mnemonic is always followed by 16-bit (or adr)."
},
{
"code": null,
"e": 28908,
"s": 28893,
"text": "microprocessor"
},
{
"code": null,
"e": 28945,
"s": 28908,
"text": "Computer Organization & Architecture"
},
{
"code": null,
"e": 28953,
"s": 28945,
"text": "GATE CS"
},
{
"code": null,
"e": 28968,
"s": 28953,
"text": "microprocessor"
},
{
"code": null,
"e": 29066,
"s": 28968,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29115,
"s": 29066,
"text": "Logical and Physical Address in Operating System"
},
{
"code": null,
"e": 29210,
"s": 29115,
"text": "Computer Organization and Architecture | Pipelining | Set 1 (Execution, Stages and Throughput)"
},
{
"code": null,
"e": 29258,
"s": 29210,
"text": "Memory Hierarchy Design and its Characteristics"
},
{
"code": null,
"e": 29296,
"s": 29258,
"text": "Computer Organization | RISC and CISC"
},
{
"code": null,
"e": 29358,
"s": 29296,
"text": "Direct Access Media (DMA) Controller in Computer Architecture"
},
{
"code": null,
"e": 29378,
"s": 29358,
"text": "Layers of OSI Model"
},
{
"code": null,
"e": 29402,
"s": 29378,
"text": "ACID Properties in DBMS"
},
{
"code": null,
"e": 29415,
"s": 29402,
"text": "TCP/IP Model"
},
{
"code": null,
"e": 29442,
"s": 29415,
"text": "Types of Operating Systems"
}
] |
Burrows - Wheeler Data Transform Algorithm - GeeksforGeeks
|
08 Aug, 2019
What is the Burrows-Wheeler Transform?The BWT is a data transformation algorithm that restructures data in such a way that the transformed message is more compressible. Technically, it is a lexicographical reversible permutation of the characters of a string. It is first of the three steps to be performed in succession while implementing the Burrows-Wheeler Data Compression algorithm that forms the basis of the Unix compression utility bzip2.
Why BWT? The main idea behind it.The most important application of BWT is found in biological sciences where genomes(long strings written in A, C, T, G alphabets) don’t have many runs but they do have many repeats.The idea of the BWT is to build an array whose rows are all cyclic shifts of the input string in dictionary order and return the last column of the array that tends to have long runs of identical characters. The benefit of this is that once the characters have been clustered together, they effectively have an ordering, which can make our string more compressible for other algorithms like run-length encoding and Huffman Coding.The remarkable thing about BWT is that this particular transform is reversible with minimal data overhead.
Steps involved in BWT algorithmLet’s take the word “banana$” as an example.
Step 1: Form all cyclic rotations of the given text. banana$
$ b $banana
a a a$banan
Cyclic rotations ----------> na$bana
n n ana$ban
a nana$ba
anana$b
banana$
$ b $banana
a a a$banan
Cyclic rotations ----------> na$bana
n n ana$ban
a nana$ba
anana$b
Step 2: The next step is to sort the rotations lexicographically. The ‘$’ sign is viewed as first letter lexicographically, even before ‘a’.banana$ $banana
$banana a$banan
a$banan Sorting ana$ban
na$bana ----------> anana$b
ana$ban alphabetically banana$
nana$ba na$bana
anana$b nana$ba
banana$ $banana
$banana a$banan
a$banan Sorting ana$ban
na$bana ----------> anana$b
ana$ban alphabetically banana$
nana$ba na$bana
anana$b nana$ba
Step 3: The last column is what we output as BWT.BWT(banana$) = annb$aa
BWT(banana$) = annb$aa
Examples:
Input: text = “banana$”Output: Burrows-Wheeler Transform = “annb$aa”
Input: text = “abracadabra$”Output: Burrows-Wheeler Transform = “ard$rcaaaabb”
Why last column is considered BWT?
The last column has a better symbol clustering than any other columns.If we only have BWT of our string, we can recover the rest of the cyclic rotations entirely. The rest of the columns don’t possess this characteristic which is highly important while computing the inverse of BWT.
The last column has a better symbol clustering than any other columns.
If we only have BWT of our string, we can recover the rest of the cyclic rotations entirely. The rest of the columns don’t possess this characteristic which is highly important while computing the inverse of BWT.
Why ‘$’ sign is embedded in the text?We can compute BWT even if our text is not concatenated with any EOF character (‘$’ here). The implication of ‘$’ sign comes while computing the inverse of BWT.
Way of implementation
Let’s instantiate “banana$” as our input_text and instantiate character array bwt_arr for our output.Let’s get all the suffixes of “banana$” and compute it’s suffix_arr to store index of each suffix.0 banana$ 6 $
1 anana$ 5 a$
2 nana$ Sorting 3 ana$
3 ana$ ----------> 1 anana$
4 na$ alphabetically 0 banana$
5 a$ 4 na$
6 $ 2 nana$
Iterating over the suffix_arr, let’s now add to our output array bwt_arr, the last character of each rotation.The last character of each rotation of input_text starting at the position denoted by the current value in the suffix array can be calculated with input_text[(suffix_arr[i] – 1 + n ) % n], where n is the number of elements in the suffix_arr.bwt_arr[0]
= input_text[(suffix_arr[0] - 1 + 7) % 7]
= input_text[5]
= a
bwt_arr[1]
= input_text[(suffix_arr[1] - 1 + 7) % 7]
= input_text[4]
= n
Let’s instantiate “banana$” as our input_text and instantiate character array bwt_arr for our output.
Let’s get all the suffixes of “banana$” and compute it’s suffix_arr to store index of each suffix.0 banana$ 6 $
1 anana$ 5 a$
2 nana$ Sorting 3 ana$
3 ana$ ----------> 1 anana$
4 na$ alphabetically 0 banana$
5 a$ 4 na$
6 $ 2 nana$
0 banana$ 6 $
1 anana$ 5 a$
2 nana$ Sorting 3 ana$
3 ana$ ----------> 1 anana$
4 na$ alphabetically 0 banana$
5 a$ 4 na$
6 $ 2 nana$
Iterating over the suffix_arr, let’s now add to our output array bwt_arr, the last character of each rotation.
The last character of each rotation of input_text starting at the position denoted by the current value in the suffix array can be calculated with input_text[(suffix_arr[i] – 1 + n ) % n], where n is the number of elements in the suffix_arr.bwt_arr[0]
= input_text[(suffix_arr[0] - 1 + 7) % 7]
= input_text[5]
= a
bwt_arr[1]
= input_text[(suffix_arr[1] - 1 + 7) % 7]
= input_text[4]
= n
bwt_arr[0]
= input_text[(suffix_arr[0] - 1 + 7) % 7]
= input_text[5]
= a
bwt_arr[1]
= input_text[(suffix_arr[1] - 1 + 7) % 7]
= input_text[4]
= n
Following is the code for the way of implementation explained above
// C program to find Burrows Wheeler transform// of a given text #include <stdio.h>#include <stdlib.h>#include <string.h> // Structure to store data of a rotationstruct rotation { int index; char* suffix;}; // Compares the rotations and// sorts the rotations alphabeticallyint cmpfunc(const void* x, const void* y){ struct rotation* rx = (struct rotation*)x; struct rotation* ry = (struct rotation*)y; return strcmp(rx->suffix, ry->suffix);} // Takes text to be transformed and its length as// arguments and returns the corresponding suffix arrayint* computeSuffixArray(char* input_text, int len_text){ // Array of structures to store rotations and // their indexes struct rotation suff[len_text]; // Structure is needed to maintain old indexes of // rotations after sorting them for (int i = 0; i < len_text; i++) { suff[i].index = i; suff[i].suffix = (input_text + i); } // Sorts rotations using comparison // function defined above qsort(suff, len_text, sizeof(struct rotation), cmpfunc); // Stores the indexes of sorted rotations int* suffix_arr = (int*)malloc(len_text * sizeof(int)); for (int i = 0; i < len_text; i++) suffix_arr[i] = suff[i].index; // Returns the computed suffix array return suffix_arr;} // Takes suffix array and its size// as arguments and returns the// Burrows - Wheeler Transform of given textchar* findLastChar(char* input_text, int* suffix_arr, int n){ // Iterates over the suffix array to find // the last char of each cyclic rotation char* bwt_arr = (char*)malloc(n * sizeof(char)); int i; for (i = 0; i < n; i++) { // Computes the last char which is given by // input_text[(suffix_arr[i] + n - 1) % n] int j = suffix_arr[i] - 1; if (j < 0) j = j + n; bwt_arr[i] = input_text[j]; } bwt_arr[i] = '\0'; // Returns the computed Burrows - Wheeler Transform return bwt_arr;} // Driver program to test functions aboveint main(){ char input_text[] = "banana$"; int len_text = strlen(input_text); // Computes the suffix array of our text int* suffix_arr = computeSuffixArray(input_text, len_text); // Adds to the output array the last char // of each rotation char* bwt_arr = findLastChar(input_text, suffix_arr, len_text); printf("Input text : %s\n", input_text); printf("Burrows - Wheeler Transform : %s\n", bwt_arr); return 0;}
Input text : banana$
Burrows - Wheeler Transform : annb$aa
Time Complexity: O(Logn). This is because of the method used above to build suffix array which has O(Logn) time complexity, due to O(n) time for strings comparisons in O(nLogn) sorting algorithm.
Exercise:
Compute suffix array in O(nLogn) time and then implement BWT.Implement Inverse of Burrows-Wheeler Transform.
Compute suffix array in O(nLogn) time and then implement BWT.
Implement Inverse of Burrows-Wheeler Transform.
This article is contributed by Anureet Kaur. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Suffix-Array
Advanced Data Structure
Strings
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Decision Tree Introduction with example
AVL Tree | Set 2 (Deletion)
Ordered Set and GNU C++ PBDS
Red-Black Tree | Set 2 (Insert)
Disjoint Set Data Structures
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": 26073,
"s": 26045,
"text": "\n08 Aug, 2019"
},
{
"code": null,
"e": 26520,
"s": 26073,
"text": "What is the Burrows-Wheeler Transform?The BWT is a data transformation algorithm that restructures data in such a way that the transformed message is more compressible. Technically, it is a lexicographical reversible permutation of the characters of a string. It is first of the three steps to be performed in succession while implementing the Burrows-Wheeler Data Compression algorithm that forms the basis of the Unix compression utility bzip2."
},
{
"code": null,
"e": 27271,
"s": 26520,
"text": "Why BWT? The main idea behind it.The most important application of BWT is found in biological sciences where genomes(long strings written in A, C, T, G alphabets) don’t have many runs but they do have many repeats.The idea of the BWT is to build an array whose rows are all cyclic shifts of the input string in dictionary order and return the last column of the array that tends to have long runs of identical characters. The benefit of this is that once the characters have been clustered together, they effectively have an ordering, which can make our string more compressible for other algorithms like run-length encoding and Huffman Coding.The remarkable thing about BWT is that this particular transform is reversible with minimal data overhead."
},
{
"code": null,
"e": 27347,
"s": 27271,
"text": "Steps involved in BWT algorithmLet’s take the word “banana$” as an example."
},
{
"code": null,
"e": 27718,
"s": 27347,
"text": "Step 1: Form all cyclic rotations of the given text. banana$ \n $ b $banana \n a a a$banan\n Cyclic rotations ----------> na$bana\n n n ana$ban \n a nana$ba\n anana$b\n"
},
{
"code": null,
"e": 28037,
"s": 27718,
"text": " banana$ \n $ b $banana \n a a a$banan\n Cyclic rotations ----------> na$bana\n n n ana$ban \n a nana$ba\n anana$b\n"
},
{
"code": null,
"e": 28424,
"s": 28037,
"text": "Step 2: The next step is to sort the rotations lexicographically. The ‘$’ sign is viewed as first letter lexicographically, even before ‘a’.banana$ $banana\n$banana a$banan\na$banan Sorting ana$ban\nna$bana ----------> anana$b \nana$ban alphabetically banana$\nnana$ba na$bana\nanana$b nana$ba\n"
},
{
"code": null,
"e": 28671,
"s": 28424,
"text": "banana$ $banana\n$banana a$banan\na$banan Sorting ana$ban\nna$bana ----------> anana$b \nana$ban alphabetically banana$\nnana$ba na$bana\nanana$b nana$ba\n"
},
{
"code": null,
"e": 28744,
"s": 28671,
"text": "Step 3: The last column is what we output as BWT.BWT(banana$) = annb$aa\n"
},
{
"code": null,
"e": 28768,
"s": 28744,
"text": "BWT(banana$) = annb$aa\n"
},
{
"code": null,
"e": 28778,
"s": 28768,
"text": "Examples:"
},
{
"code": null,
"e": 28847,
"s": 28778,
"text": "Input: text = “banana$”Output: Burrows-Wheeler Transform = “annb$aa”"
},
{
"code": null,
"e": 28926,
"s": 28847,
"text": "Input: text = “abracadabra$”Output: Burrows-Wheeler Transform = “ard$rcaaaabb”"
},
{
"code": null,
"e": 28961,
"s": 28926,
"text": "Why last column is considered BWT?"
},
{
"code": null,
"e": 29244,
"s": 28961,
"text": "The last column has a better symbol clustering than any other columns.If we only have BWT of our string, we can recover the rest of the cyclic rotations entirely. The rest of the columns don’t possess this characteristic which is highly important while computing the inverse of BWT."
},
{
"code": null,
"e": 29315,
"s": 29244,
"text": "The last column has a better symbol clustering than any other columns."
},
{
"code": null,
"e": 29528,
"s": 29315,
"text": "If we only have BWT of our string, we can recover the rest of the cyclic rotations entirely. The rest of the columns don’t possess this characteristic which is highly important while computing the inverse of BWT."
},
{
"code": null,
"e": 29726,
"s": 29528,
"text": "Why ‘$’ sign is embedded in the text?We can compute BWT even if our text is not concatenated with any EOF character (‘$’ here). The implication of ‘$’ sign comes while computing the inverse of BWT."
},
{
"code": null,
"e": 29748,
"s": 29726,
"text": "Way of implementation"
},
{
"code": null,
"e": 30690,
"s": 29748,
"text": "Let’s instantiate “banana$” as our input_text and instantiate character array bwt_arr for our output.Let’s get all the suffixes of “banana$” and compute it’s suffix_arr to store index of each suffix.0 banana$ 6 $ \n1 anana$ 5 a$\n2 nana$ Sorting 3 ana$\n3 ana$ ----------> 1 anana$\n4 na$ alphabetically 0 banana$\n5 a$ 4 na$\n6 $ 2 nana$\nIterating over the suffix_arr, let’s now add to our output array bwt_arr, the last character of each rotation.The last character of each rotation of input_text starting at the position denoted by the current value in the suffix array can be calculated with input_text[(suffix_arr[i] – 1 + n ) % n], where n is the number of elements in the suffix_arr.bwt_arr[0] \n = input_text[(suffix_arr[0] - 1 + 7) % 7] \n = input_text[5] \n = a\nbwt_arr[1] \n = input_text[(suffix_arr[1] - 1 + 7) % 7] \n = input_text[4] \n = n\n"
},
{
"code": null,
"e": 30792,
"s": 30690,
"text": "Let’s instantiate “banana$” as our input_text and instantiate character array bwt_arr for our output."
},
{
"code": null,
"e": 31118,
"s": 30792,
"text": "Let’s get all the suffixes of “banana$” and compute it’s suffix_arr to store index of each suffix.0 banana$ 6 $ \n1 anana$ 5 a$\n2 nana$ Sorting 3 ana$\n3 ana$ ----------> 1 anana$\n4 na$ alphabetically 0 banana$\n5 a$ 4 na$\n6 $ 2 nana$\n"
},
{
"code": null,
"e": 31346,
"s": 31118,
"text": "0 banana$ 6 $ \n1 anana$ 5 a$\n2 nana$ Sorting 3 ana$\n3 ana$ ----------> 1 anana$\n4 na$ alphabetically 0 banana$\n5 a$ 4 na$\n6 $ 2 nana$\n"
},
{
"code": null,
"e": 31457,
"s": 31346,
"text": "Iterating over the suffix_arr, let’s now add to our output array bwt_arr, the last character of each rotation."
},
{
"code": null,
"e": 31863,
"s": 31457,
"text": "The last character of each rotation of input_text starting at the position denoted by the current value in the suffix array can be calculated with input_text[(suffix_arr[i] – 1 + n ) % n], where n is the number of elements in the suffix_arr.bwt_arr[0] \n = input_text[(suffix_arr[0] - 1 + 7) % 7] \n = input_text[5] \n = a\nbwt_arr[1] \n = input_text[(suffix_arr[1] - 1 + 7) % 7] \n = input_text[4] \n = n\n"
},
{
"code": null,
"e": 32028,
"s": 31863,
"text": "bwt_arr[0] \n = input_text[(suffix_arr[0] - 1 + 7) % 7] \n = input_text[5] \n = a\nbwt_arr[1] \n = input_text[(suffix_arr[1] - 1 + 7) % 7] \n = input_text[4] \n = n\n"
},
{
"code": null,
"e": 32096,
"s": 32028,
"text": "Following is the code for the way of implementation explained above"
},
{
"code": "// C program to find Burrows Wheeler transform// of a given text #include <stdio.h>#include <stdlib.h>#include <string.h> // Structure to store data of a rotationstruct rotation { int index; char* suffix;}; // Compares the rotations and// sorts the rotations alphabeticallyint cmpfunc(const void* x, const void* y){ struct rotation* rx = (struct rotation*)x; struct rotation* ry = (struct rotation*)y; return strcmp(rx->suffix, ry->suffix);} // Takes text to be transformed and its length as// arguments and returns the corresponding suffix arrayint* computeSuffixArray(char* input_text, int len_text){ // Array of structures to store rotations and // their indexes struct rotation suff[len_text]; // Structure is needed to maintain old indexes of // rotations after sorting them for (int i = 0; i < len_text; i++) { suff[i].index = i; suff[i].suffix = (input_text + i); } // Sorts rotations using comparison // function defined above qsort(suff, len_text, sizeof(struct rotation), cmpfunc); // Stores the indexes of sorted rotations int* suffix_arr = (int*)malloc(len_text * sizeof(int)); for (int i = 0; i < len_text; i++) suffix_arr[i] = suff[i].index; // Returns the computed suffix array return suffix_arr;} // Takes suffix array and its size// as arguments and returns the// Burrows - Wheeler Transform of given textchar* findLastChar(char* input_text, int* suffix_arr, int n){ // Iterates over the suffix array to find // the last char of each cyclic rotation char* bwt_arr = (char*)malloc(n * sizeof(char)); int i; for (i = 0; i < n; i++) { // Computes the last char which is given by // input_text[(suffix_arr[i] + n - 1) % n] int j = suffix_arr[i] - 1; if (j < 0) j = j + n; bwt_arr[i] = input_text[j]; } bwt_arr[i] = '\\0'; // Returns the computed Burrows - Wheeler Transform return bwt_arr;} // Driver program to test functions aboveint main(){ char input_text[] = \"banana$\"; int len_text = strlen(input_text); // Computes the suffix array of our text int* suffix_arr = computeSuffixArray(input_text, len_text); // Adds to the output array the last char // of each rotation char* bwt_arr = findLastChar(input_text, suffix_arr, len_text); printf(\"Input text : %s\\n\", input_text); printf(\"Burrows - Wheeler Transform : %s\\n\", bwt_arr); return 0;}",
"e": 34620,
"s": 32096,
"text": null
},
{
"code": null,
"e": 34680,
"s": 34620,
"text": "Input text : banana$\nBurrows - Wheeler Transform : annb$aa\n"
},
{
"code": null,
"e": 34876,
"s": 34680,
"text": "Time Complexity: O(Logn). This is because of the method used above to build suffix array which has O(Logn) time complexity, due to O(n) time for strings comparisons in O(nLogn) sorting algorithm."
},
{
"code": null,
"e": 34886,
"s": 34876,
"text": "Exercise:"
},
{
"code": null,
"e": 34995,
"s": 34886,
"text": "Compute suffix array in O(nLogn) time and then implement BWT.Implement Inverse of Burrows-Wheeler Transform."
},
{
"code": null,
"e": 35057,
"s": 34995,
"text": "Compute suffix array in O(nLogn) time and then implement BWT."
},
{
"code": null,
"e": 35105,
"s": 35057,
"text": "Implement Inverse of Burrows-Wheeler Transform."
},
{
"code": null,
"e": 35405,
"s": 35105,
"text": "This article is contributed by Anureet Kaur. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 35530,
"s": 35405,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 35543,
"s": 35530,
"text": "Suffix-Array"
},
{
"code": null,
"e": 35567,
"s": 35543,
"text": "Advanced Data Structure"
},
{
"code": null,
"e": 35575,
"s": 35567,
"text": "Strings"
},
{
"code": null,
"e": 35583,
"s": 35575,
"text": "Strings"
},
{
"code": null,
"e": 35681,
"s": 35583,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 35721,
"s": 35681,
"text": "Decision Tree Introduction with example"
},
{
"code": null,
"e": 35749,
"s": 35721,
"text": "AVL Tree | Set 2 (Deletion)"
},
{
"code": null,
"e": 35778,
"s": 35749,
"text": "Ordered Set and GNU C++ PBDS"
},
{
"code": null,
"e": 35810,
"s": 35778,
"text": "Red-Black Tree | Set 2 (Insert)"
},
{
"code": null,
"e": 35839,
"s": 35810,
"text": "Disjoint Set Data Structures"
},
{
"code": null,
"e": 35885,
"s": 35839,
"text": "Write a program to reverse an array or string"
},
{
"code": null,
"e": 35910,
"s": 35885,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 35970,
"s": 35910,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 35985,
"s": 35970,
"text": "C++ Data Types"
}
] |
Java | How to create your own Helper Class? - GeeksforGeeks
|
11 Feb, 2018
Helper Class is a Java class which includes basic error handling, some helper functions etc. Helper class contains functions that help in assisting the program. This Class intends to give quick implementation of basic functions such that programmers do not have to implement again and again. It is easy to Access as all the member functions are static that is it can be accessed from anywhere. It implements the most commonly used functions excluding the functions that are already present in java library.
Different helper class contains different methods depending upon the need of the program.
Recommendation : Make a package for this class naming HelperClass and import in your java code
Below is an example of helperclass.
// Example for helper class import java.lang.*;import java.util.*; class HelperClass { // to check whether integer is greater than 0 or not // usually used when we have to input a whole number // like taking input of number of test cases etc public static boolean isValidInteger(int test) { return (test >= 0); } // to check whether integer is greater than the lower // bound and lower than the highest bound. public static boolean isValidInteger(int test, int low, int high) { return (test >= low && test <= high); } // used when we want the user to input the number // exactly greater than the lower bound public static int getInRange(int low) { Scanner sc = new Scanner(System.in); int test; do { test = sc.nextInt(); } while (test < low); return test; } // used when we want the user to input the number // exactly greater than lower bound and lower than // the highest bound public static int getInRange(int low, int high) { Scanner sc = new Scanner(System.in); int test; do { test = sc.nextInt(); } while (test < low || test > high); return test; } // to check whether an array contains any negative value public static boolean validatePositiveArray(int[] array, int n) { for (int i = 0; i < n; i++) if (array[i] < 0) return false; return true; } // to check whether an array contains any positive value public static boolean validateNegativeArray(int[] array, int n) { for (int i = 0; i < n; i++) if (array[i] > 0) return false; return true; } // check whether every element in the array is greater // than the lower bound public static boolean checkRangeArray(int[] array, int n, int low) { for (int i = 0; i < n; i++) if (array[i] < low) return false; return true; } // check whether every element in the array is greater // than the lower bound and lower than the highest bound public static boolean checkRangeArray(int[] array, int n, int low, int high) { for (int i = 0; i < n; i++) if (array[i] < low || array[i] > high) return false; return true; } // check whether two given sets as "arrays" are equal or not public static boolean isEqualSets(int[] array1, int n, int[] array2, int m) { if (n != m) return false; HashMap<Integer, Integer> Map = new HashMap<Integer, Integer>(); for (int i = 0; i < n; i++) Map.put(new Integer(array1[i]), new Integer(1)); for (int i = 0; i < m; i++) Map.put(new Integer(array2[i]), new Integer(0)); for (int i = 0; i < n; i++) if (Map.get(array1[i]) == 1) return false; return true; } // calculating factorial of a number public static String factorial(int n) { String fact = new String(""); int res[] = new int[500]; res[0] = 1; int res_size = 1; for (int x = 2; x <= n; x++) res_size = multiply(x, res, res_size); for (int i = res_size - 1; i >= 0; i--) fact += Integer.toString(res[i]); return fact; } // Multiply x with res[0..res_size-1] public static int multiply(int x, int res[], int res_size) { int carry = 0; for (int i = 0; i < res_size; i++) { int prod = res[i] * x + carry; res[i] = prod % 10; carry = prod / 10; } while (carry != 0) { res[res_size] = carry % 10; carry = carry / 10; res_size++; } return res_size; } // Checks whether the given number is prime or not public static boolean isPrime(int n) { if (n == 2) return true; int squareRoot = (int)Math.sqrt(n); for (int i = 1; i <= squareRoot; i++) if (n % i == 0 && i != 1) return false; return true; } // Returns nthPrimeNumber public static int nthPrimeNumber(int n) { int k = 0; for (int i = 2;; i++) { if (isPrime(i)) k++; if (k == n) return i; } } // check whether the given string is palindrome or not public static boolean isPalindrome(String test) { int length = test.length(); for (int i = 0; i <= (test.length()) / 2; i++) if (test.charAt(i) != test.charAt(length - i - 1)) return false; return true; } // check whether two strings are anagram or not public static boolean isAnagram(String s1, String s2) { // Removing all white spaces from s1 and s2 String copyOfs1 = s1.replaceAll("\\s", ""); String copyOfs2 = s2.replaceAll("\\s", ""); if (copyOfs1.length() != copyOfs2.length()) return false; // Changing the case of characters of both copyOfs1 and // copyOfs2 and converting them to char array char[] s1Array = copyOfs1.toLowerCase().toCharArray(); char[] s2Array = copyOfs2.toLowerCase().toCharArray(); // Sorting both s1Array and s2Array Arrays.sort(s1Array); Arrays.sort(s2Array); // Checking whether s1Array and s2Array are equal return (Arrays.equals(s1Array, s2Array)); } } /*** end of helperClass **/ class Test { public static void main(String[] args) { int n = -5; if (HelperClass.isValidInteger(n)) System.out.println("True"); else System.out.println("False"); String str = "madam"; if (HelperClass.isPalindrome(str)) System.out.println("True"); else System.out.println("False"); }}
False
True
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
Internal Working of HashMap in Java
Introduction to Java
Comparator Interface in Java with Examples
PriorityQueue in Java
|
[
{
"code": null,
"e": 25237,
"s": 25209,
"text": "\n11 Feb, 2018"
},
{
"code": null,
"e": 25744,
"s": 25237,
"text": "Helper Class is a Java class which includes basic error handling, some helper functions etc. Helper class contains functions that help in assisting the program. This Class intends to give quick implementation of basic functions such that programmers do not have to implement again and again. It is easy to Access as all the member functions are static that is it can be accessed from anywhere. It implements the most commonly used functions excluding the functions that are already present in java library."
},
{
"code": null,
"e": 25834,
"s": 25744,
"text": "Different helper class contains different methods depending upon the need of the program."
},
{
"code": null,
"e": 25929,
"s": 25834,
"text": "Recommendation : Make a package for this class naming HelperClass and import in your java code"
},
{
"code": null,
"e": 25965,
"s": 25929,
"text": "Below is an example of helperclass."
},
{
"code": "// Example for helper class import java.lang.*;import java.util.*; class HelperClass { // to check whether integer is greater than 0 or not // usually used when we have to input a whole number // like taking input of number of test cases etc public static boolean isValidInteger(int test) { return (test >= 0); } // to check whether integer is greater than the lower // bound and lower than the highest bound. public static boolean isValidInteger(int test, int low, int high) { return (test >= low && test <= high); } // used when we want the user to input the number // exactly greater than the lower bound public static int getInRange(int low) { Scanner sc = new Scanner(System.in); int test; do { test = sc.nextInt(); } while (test < low); return test; } // used when we want the user to input the number // exactly greater than lower bound and lower than // the highest bound public static int getInRange(int low, int high) { Scanner sc = new Scanner(System.in); int test; do { test = sc.nextInt(); } while (test < low || test > high); return test; } // to check whether an array contains any negative value public static boolean validatePositiveArray(int[] array, int n) { for (int i = 0; i < n; i++) if (array[i] < 0) return false; return true; } // to check whether an array contains any positive value public static boolean validateNegativeArray(int[] array, int n) { for (int i = 0; i < n; i++) if (array[i] > 0) return false; return true; } // check whether every element in the array is greater // than the lower bound public static boolean checkRangeArray(int[] array, int n, int low) { for (int i = 0; i < n; i++) if (array[i] < low) return false; return true; } // check whether every element in the array is greater // than the lower bound and lower than the highest bound public static boolean checkRangeArray(int[] array, int n, int low, int high) { for (int i = 0; i < n; i++) if (array[i] < low || array[i] > high) return false; return true; } // check whether two given sets as \"arrays\" are equal or not public static boolean isEqualSets(int[] array1, int n, int[] array2, int m) { if (n != m) return false; HashMap<Integer, Integer> Map = new HashMap<Integer, Integer>(); for (int i = 0; i < n; i++) Map.put(new Integer(array1[i]), new Integer(1)); for (int i = 0; i < m; i++) Map.put(new Integer(array2[i]), new Integer(0)); for (int i = 0; i < n; i++) if (Map.get(array1[i]) == 1) return false; return true; } // calculating factorial of a number public static String factorial(int n) { String fact = new String(\"\"); int res[] = new int[500]; res[0] = 1; int res_size = 1; for (int x = 2; x <= n; x++) res_size = multiply(x, res, res_size); for (int i = res_size - 1; i >= 0; i--) fact += Integer.toString(res[i]); return fact; } // Multiply x with res[0..res_size-1] public static int multiply(int x, int res[], int res_size) { int carry = 0; for (int i = 0; i < res_size; i++) { int prod = res[i] * x + carry; res[i] = prod % 10; carry = prod / 10; } while (carry != 0) { res[res_size] = carry % 10; carry = carry / 10; res_size++; } return res_size; } // Checks whether the given number is prime or not public static boolean isPrime(int n) { if (n == 2) return true; int squareRoot = (int)Math.sqrt(n); for (int i = 1; i <= squareRoot; i++) if (n % i == 0 && i != 1) return false; return true; } // Returns nthPrimeNumber public static int nthPrimeNumber(int n) { int k = 0; for (int i = 2;; i++) { if (isPrime(i)) k++; if (k == n) return i; } } // check whether the given string is palindrome or not public static boolean isPalindrome(String test) { int length = test.length(); for (int i = 0; i <= (test.length()) / 2; i++) if (test.charAt(i) != test.charAt(length - i - 1)) return false; return true; } // check whether two strings are anagram or not public static boolean isAnagram(String s1, String s2) { // Removing all white spaces from s1 and s2 String copyOfs1 = s1.replaceAll(\"\\\\s\", \"\"); String copyOfs2 = s2.replaceAll(\"\\\\s\", \"\"); if (copyOfs1.length() != copyOfs2.length()) return false; // Changing the case of characters of both copyOfs1 and // copyOfs2 and converting them to char array char[] s1Array = copyOfs1.toLowerCase().toCharArray(); char[] s2Array = copyOfs2.toLowerCase().toCharArray(); // Sorting both s1Array and s2Array Arrays.sort(s1Array); Arrays.sort(s2Array); // Checking whether s1Array and s2Array are equal return (Arrays.equals(s1Array, s2Array)); } } /*** end of helperClass **/ class Test { public static void main(String[] args) { int n = -5; if (HelperClass.isValidInteger(n)) System.out.println(\"True\"); else System.out.println(\"False\"); String str = \"madam\"; if (HelperClass.isPalindrome(str)) System.out.println(\"True\"); else System.out.println(\"False\"); }}",
"e": 32345,
"s": 25965,
"text": null
},
{
"code": null,
"e": 32357,
"s": 32345,
"text": "False\nTrue\n"
},
{
"code": null,
"e": 32362,
"s": 32357,
"text": "Java"
},
{
"code": null,
"e": 32367,
"s": 32362,
"text": "Java"
},
{
"code": null,
"e": 32465,
"s": 32367,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32480,
"s": 32465,
"text": "Stream In Java"
},
{
"code": null,
"e": 32501,
"s": 32480,
"text": "Constructors in Java"
},
{
"code": null,
"e": 32520,
"s": 32501,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 32550,
"s": 32520,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 32596,
"s": 32550,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 32613,
"s": 32596,
"text": "Generics in Java"
},
{
"code": null,
"e": 32649,
"s": 32613,
"text": "Internal Working of HashMap in Java"
},
{
"code": null,
"e": 32670,
"s": 32649,
"text": "Introduction to Java"
},
{
"code": null,
"e": 32713,
"s": 32670,
"text": "Comparator Interface in Java with Examples"
}
] |
Java - Current Date and Time - GeeksforGeeks
|
13 May, 2022
In Java, there is a built-in class known as the Date class and we can import java.time package to work with date and time API. Here we are supposed to print current date and time. There can be multiple ways to print the current date and time.
Using Date ClassUsing get() method of Calendar classUsing calendar and formatter class to print the current dates in a specific format.
Using Date Class
Using get() method of Calendar class
Using calendar and formatter class to print the current dates in a specific format.
Method 1: Using Date Class
Example:
Java
// Java Program to Display Current Date and Time// Using Date class // Importing required classesimport java.util.*; // Classpublic class GFG { // Main driver method public static void main(String[] args) { // Creating object of date class Date d1 = new Date(); // Printing the value stored in above object System.out.println("Current date is " + d1); }}
Current date is Thu Mar 31 01:14:28 UTC 2022
Method 2: Using get() method of Calendar class
getInstance() method is generally used to get the time, date or any required some belonging to Calendar year.
Tip: Whenever we require anyrhing belonging to Calendar, Calendar class is one of naive base for sure approach to deal with dae and time instances.
Example:
Java
// Java Program to Illustrate getinstance() Method// of Calendar Class // Importing required classesimport java.util.*; // Classclass GFG { // Main driver method public static void main(String[] args) { // Creating an object of Calendar class Calendar c = Calendar.getInstance(); // Print corresponding instances by passing // required some as in arguments System.out.println("Day of week : " + c.get(Calendar.DAY_OF_WEEK)); System.out.println("Day of year : " + c.get(Calendar.DAY_OF_YEAR)); System.out.println("Week in Month : " + c.get(Calendar.WEEK_OF_MONTH)); System.out.println("Week in Year : " + c.get(Calendar.WEEK_OF_YEAR)); System.out.println( "Day of Week in Month : " + c.get(Calendar.DAY_OF_WEEK_IN_MONTH)); System.out.println("Hour : " + c.get(Calendar.HOUR)); System.out.println("Minute : " + c.get(Calendar.MINUTE)); System.out.println("Second : " + c.get(Calendar.SECOND)); System.out.println("AM or PM : " + c.get(Calendar.AM_PM)); System.out.println("Hour (24-hour clock) : " + c.get(Calendar.HOUR_OF_DAY)); }}
Day of week : 7
Day of year : 83
Week in Month : 4
Week in Year : 12
Day of Week in Month : 4
Hour : 6
Minute : 22
Second : 48
AM or PM : 1
Hour (24-hour clock) : 18
Method 3: Using calendar and formatter class to print the current dates in a specific format.
Example:
Java
// Java Program to Demonstrate Working of SimpleDateFormat// Class // Importing required classesimport java.text.ParseException;import java.text.SimpleDateFormat;import java.util.Date; // Classclass GFG { // Main driver method public static void main(String args[]) throws ParseException { // Formatting as per given pattern in the argument SimpleDateFormat ft = new SimpleDateFormat("dd-MM-yyyy"); String str = ft.format(new Date()); // Printing the formatted date System.out.println("Formatted Date : " + str); // Parsing a custom string str = "02/18/1995"; ft = new SimpleDateFormat("MM/dd/yyyy"); Date date = ft.parse(str); // Printing date as per parsed string on console System.out.println("Parsed Date : " + date); }}
Formatted Date : 31-03-2022
Parsed Date : Sat Feb 18 00:00:00 UTC 1995
Akanksha_Rai
clintra
solankimayank
sagartomar9927
date-time-program
Java-Date-Time
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": 25250,
"s": 25222,
"text": "\n13 May, 2022"
},
{
"code": null,
"e": 25493,
"s": 25250,
"text": "In Java, there is a built-in class known as the Date class and we can import java.time package to work with date and time API. Here we are supposed to print current date and time. There can be multiple ways to print the current date and time."
},
{
"code": null,
"e": 25630,
"s": 25493,
"text": "Using Date ClassUsing get() method of Calendar classUsing calendar and formatter class to print the current dates in a specific format. "
},
{
"code": null,
"e": 25647,
"s": 25630,
"text": "Using Date Class"
},
{
"code": null,
"e": 25684,
"s": 25647,
"text": "Using get() method of Calendar class"
},
{
"code": null,
"e": 25769,
"s": 25684,
"text": "Using calendar and formatter class to print the current dates in a specific format. "
},
{
"code": null,
"e": 25796,
"s": 25769,
"text": "Method 1: Using Date Class"
},
{
"code": null,
"e": 25805,
"s": 25796,
"text": "Example:"
},
{
"code": null,
"e": 25810,
"s": 25805,
"text": "Java"
},
{
"code": "// Java Program to Display Current Date and Time// Using Date class // Importing required classesimport java.util.*; // Classpublic class GFG { // Main driver method public static void main(String[] args) { // Creating object of date class Date d1 = new Date(); // Printing the value stored in above object System.out.println(\"Current date is \" + d1); }}",
"e": 26207,
"s": 25810,
"text": null
},
{
"code": null,
"e": 26252,
"s": 26207,
"text": "Current date is Thu Mar 31 01:14:28 UTC 2022"
},
{
"code": null,
"e": 26299,
"s": 26252,
"text": "Method 2: Using get() method of Calendar class"
},
{
"code": null,
"e": 26409,
"s": 26299,
"text": "getInstance() method is generally used to get the time, date or any required some belonging to Calendar year."
},
{
"code": null,
"e": 26557,
"s": 26409,
"text": "Tip: Whenever we require anyrhing belonging to Calendar, Calendar class is one of naive base for sure approach to deal with dae and time instances."
},
{
"code": null,
"e": 26566,
"s": 26557,
"text": "Example:"
},
{
"code": null,
"e": 26571,
"s": 26566,
"text": "Java"
},
{
"code": "// Java Program to Illustrate getinstance() Method// of Calendar Class // Importing required classesimport java.util.*; // Classclass GFG { // Main driver method public static void main(String[] args) { // Creating an object of Calendar class Calendar c = Calendar.getInstance(); // Print corresponding instances by passing // required some as in arguments System.out.println(\"Day of week : \" + c.get(Calendar.DAY_OF_WEEK)); System.out.println(\"Day of year : \" + c.get(Calendar.DAY_OF_YEAR)); System.out.println(\"Week in Month : \" + c.get(Calendar.WEEK_OF_MONTH)); System.out.println(\"Week in Year : \" + c.get(Calendar.WEEK_OF_YEAR)); System.out.println( \"Day of Week in Month : \" + c.get(Calendar.DAY_OF_WEEK_IN_MONTH)); System.out.println(\"Hour : \" + c.get(Calendar.HOUR)); System.out.println(\"Minute : \" + c.get(Calendar.MINUTE)); System.out.println(\"Second : \" + c.get(Calendar.SECOND)); System.out.println(\"AM or PM : \" + c.get(Calendar.AM_PM)); System.out.println(\"Hour (24-hour clock) : \" + c.get(Calendar.HOUR_OF_DAY)); }}",
"e": 27979,
"s": 26571,
"text": null
},
{
"code": null,
"e": 28145,
"s": 27979,
"text": "Day of week : 7\nDay of year : 83\nWeek in Month : 4\nWeek in Year : 12\nDay of Week in Month : 4\nHour : 6\nMinute : 22\nSecond : 48\nAM or PM : 1\nHour (24-hour clock) : 18"
},
{
"code": null,
"e": 28241,
"s": 28147,
"text": "Method 3: Using calendar and formatter class to print the current dates in a specific format."
},
{
"code": null,
"e": 28250,
"s": 28241,
"text": "Example:"
},
{
"code": null,
"e": 28255,
"s": 28250,
"text": "Java"
},
{
"code": "// Java Program to Demonstrate Working of SimpleDateFormat// Class // Importing required classesimport java.text.ParseException;import java.text.SimpleDateFormat;import java.util.Date; // Classclass GFG { // Main driver method public static void main(String args[]) throws ParseException { // Formatting as per given pattern in the argument SimpleDateFormat ft = new SimpleDateFormat(\"dd-MM-yyyy\"); String str = ft.format(new Date()); // Printing the formatted date System.out.println(\"Formatted Date : \" + str); // Parsing a custom string str = \"02/18/1995\"; ft = new SimpleDateFormat(\"MM/dd/yyyy\"); Date date = ft.parse(str); // Printing date as per parsed string on console System.out.println(\"Parsed Date : \" + date); }}",
"e": 29093,
"s": 28255,
"text": null
},
{
"code": null,
"e": 29164,
"s": 29093,
"text": "Formatted Date : 31-03-2022\nParsed Date : Sat Feb 18 00:00:00 UTC 1995"
},
{
"code": null,
"e": 29177,
"s": 29164,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 29185,
"s": 29177,
"text": "clintra"
},
{
"code": null,
"e": 29199,
"s": 29185,
"text": "solankimayank"
},
{
"code": null,
"e": 29214,
"s": 29199,
"text": "sagartomar9927"
},
{
"code": null,
"e": 29232,
"s": 29214,
"text": "date-time-program"
},
{
"code": null,
"e": 29247,
"s": 29232,
"text": "Java-Date-Time"
},
{
"code": null,
"e": 29252,
"s": 29247,
"text": "Java"
},
{
"code": null,
"e": 29257,
"s": 29252,
"text": "Java"
},
{
"code": null,
"e": 29355,
"s": 29257,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29370,
"s": 29355,
"text": "Stream In Java"
},
{
"code": null,
"e": 29391,
"s": 29370,
"text": "Constructors in Java"
},
{
"code": null,
"e": 29410,
"s": 29391,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 29440,
"s": 29410,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 29486,
"s": 29440,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 29503,
"s": 29486,
"text": "Generics in Java"
},
{
"code": null,
"e": 29524,
"s": 29503,
"text": "Introduction to Java"
},
{
"code": null,
"e": 29567,
"s": 29524,
"text": "Comparator Interface in Java with Examples"
},
{
"code": null,
"e": 29603,
"s": 29567,
"text": "Internal Working of HashMap in Java"
}
] |
Python Program for Dijkstra’s shortest path algorithm | Greedy Algo-7
|
24 Feb, 2022
Given a graph and a source vertex in the graph, find the shortest paths from source to all vertices in the given graph.Dijkstra’s algorithm is very similar to Prim’s algorithm for minimum spanning tree. Like Prim’s MST, we generate an SPT (shortest path tree) with a given source as root. We maintain two sets, one set contains vertices included in the shortest-path tree, another set includes vertices not yet included in the shortest-path tree. At every step of the algorithm, we find a vertex that is in the other set (set of not yet included) and has a minimum distance from the source.Below are the detailed steps used in Dijkstra’s algorithm to find the shortest path from a single source vertex to all other vertices in the given graph. Algorithm 1) Create a set sptSet (shortest path tree set) that keeps track of vertices included in shortest path tree, i.e., whose minimum distance from source is calculated and finalized. Initially, this set is empty. 2) Assign a distance value to all vertices in the input graph. Initialize all distance values as INFINITE. Assign distance value as 0 for the source vertex so that it is picked first. 3) While sptSet doesn’t include all vertices:
Pick a vertex u which is not there in sptSet and has minimum distance value.
Include u to sptSet.
Update distance value of all adjacent vertices of u. To update the distance values, iterate through all adjacent vertices. For every adjacent vertex v, if the sum of a distance value of u (from source) and weight of edge u-v, is less than the distance value of v, then update the distance value of v.
Python3
# Python program for Dijkstra's single# source shortest path algorithm. The program is# for adjacency matrix representation of the graphclass Graph(): def __init__(self, vertices): self.V = vertices self.graph = [[0 for column in range(vertices)] for row in range(vertices)] def printSolution(self, dist): print("Vertex \t Distance from Source") for node in range(self.V): print(node, "\t\t", dist[node]) # A utility function to find the vertex with # minimum distance value, from the set of vertices # not yet included in shortest path tree def minDistance(self, dist, sptSet): # Initialize minimum distance for next node min = 1e7 # Search not nearest vertex not in the # shortest path tree for v in range(self.V): if dist[v] < min and sptSet[v] == False: min = dist[v] min_index = v return min_index # Function that implements Dijkstra's single source # shortest path algorithm for a graph represented # using adjacency matrix representation def dijkstra(self, src): dist = [1e7] * self.V dist[src] = 0 sptSet = [False] * self.V for cout in range(self.V): # Pick the minimum distance vertex from # the set of vertices not yet processed. # u is always equal to src in first iteration u = self.minDistance(dist, sptSet) # Put the minimum distance vertex in the # shortest path tree sptSet[u] = True # Update dist value of the adjacent vertices # of the picked vertex only if the current # distance is greater than new distance and # the vertex in not in the shortest path tree for v in range(self.V): if (self.graph[u][v] > 0 and sptSet[v] == False and dist[v] > dist[u] + self.graph[u][v]): dist[v] = dist[u] + self.graph[u][v] self.printSolution(dist) # Driver programg = Graph(9)g.graph = [[0, 4, 0, 0, 0, 0, 0, 8, 0], [4, 0, 8, 0, 0, 0, 0, 11, 0], [0, 8, 0, 7, 0, 4, 0, 0, 2], [0, 0, 7, 0, 9, 14, 0, 0, 0], [0, 0, 0, 9, 0, 10, 0, 0, 0], [0, 0, 4, 14, 10, 0, 2, 0, 0], [0, 0, 0, 0, 0, 2, 0, 1, 6], [8, 11, 0, 0, 0, 0, 1, 0, 7], [0, 0, 2, 0, 0, 0, 6, 7, 0] ] g.dijkstra(0) # This code is contributed by Divyanshu Mehta
Vertex Distance from Source
0 0
1 4
2 12
3 19
4 21
5 11
6 9
7 8
8 14
Please refer complete article on Dijkstra’s shortest path algorithm | Greedy Algo-7 for more details!
subhramanyasadhwani
preyash2047
arorakashish0911
sumitgumber28
rajeev0719singh
amartyaghoshgfg
piyushyadav11102002
Dijkstra
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary
Python Program for Fibonacci numbers
Python program to check whether a number is Prime or not
Python program to add two numbers
Python Program for Binary Search (Recursive and Iterative)
Python Program for factorial of a number
Python program to find second largest number in a list
Iterate over characters of a string in Python
Python | Convert set into a list
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n24 Feb, 2022"
},
{
"code": null,
"e": 1246,
"s": 52,
"text": "Given a graph and a source vertex in the graph, find the shortest paths from source to all vertices in the given graph.Dijkstra’s algorithm is very similar to Prim’s algorithm for minimum spanning tree. Like Prim’s MST, we generate an SPT (shortest path tree) with a given source as root. We maintain two sets, one set contains vertices included in the shortest-path tree, another set includes vertices not yet included in the shortest-path tree. At every step of the algorithm, we find a vertex that is in the other set (set of not yet included) and has a minimum distance from the source.Below are the detailed steps used in Dijkstra’s algorithm to find the shortest path from a single source vertex to all other vertices in the given graph. Algorithm 1) Create a set sptSet (shortest path tree set) that keeps track of vertices included in shortest path tree, i.e., whose minimum distance from source is calculated and finalized. Initially, this set is empty. 2) Assign a distance value to all vertices in the input graph. Initialize all distance values as INFINITE. Assign distance value as 0 for the source vertex so that it is picked first. 3) While sptSet doesn’t include all vertices: "
},
{
"code": null,
"e": 1323,
"s": 1246,
"text": "Pick a vertex u which is not there in sptSet and has minimum distance value."
},
{
"code": null,
"e": 1344,
"s": 1323,
"text": "Include u to sptSet."
},
{
"code": null,
"e": 1645,
"s": 1344,
"text": "Update distance value of all adjacent vertices of u. To update the distance values, iterate through all adjacent vertices. For every adjacent vertex v, if the sum of a distance value of u (from source) and weight of edge u-v, is less than the distance value of v, then update the distance value of v."
},
{
"code": null,
"e": 1653,
"s": 1645,
"text": "Python3"
},
{
"code": "# Python program for Dijkstra's single# source shortest path algorithm. The program is# for adjacency matrix representation of the graphclass Graph(): def __init__(self, vertices): self.V = vertices self.graph = [[0 for column in range(vertices)] for row in range(vertices)] def printSolution(self, dist): print(\"Vertex \\t Distance from Source\") for node in range(self.V): print(node, \"\\t\\t\", dist[node]) # A utility function to find the vertex with # minimum distance value, from the set of vertices # not yet included in shortest path tree def minDistance(self, dist, sptSet): # Initialize minimum distance for next node min = 1e7 # Search not nearest vertex not in the # shortest path tree for v in range(self.V): if dist[v] < min and sptSet[v] == False: min = dist[v] min_index = v return min_index # Function that implements Dijkstra's single source # shortest path algorithm for a graph represented # using adjacency matrix representation def dijkstra(self, src): dist = [1e7] * self.V dist[src] = 0 sptSet = [False] * self.V for cout in range(self.V): # Pick the minimum distance vertex from # the set of vertices not yet processed. # u is always equal to src in first iteration u = self.minDistance(dist, sptSet) # Put the minimum distance vertex in the # shortest path tree sptSet[u] = True # Update dist value of the adjacent vertices # of the picked vertex only if the current # distance is greater than new distance and # the vertex in not in the shortest path tree for v in range(self.V): if (self.graph[u][v] > 0 and sptSet[v] == False and dist[v] > dist[u] + self.graph[u][v]): dist[v] = dist[u] + self.graph[u][v] self.printSolution(dist) # Driver programg = Graph(9)g.graph = [[0, 4, 0, 0, 0, 0, 0, 8, 0], [4, 0, 8, 0, 0, 0, 0, 11, 0], [0, 8, 0, 7, 0, 4, 0, 0, 2], [0, 0, 7, 0, 9, 14, 0, 0, 0], [0, 0, 0, 9, 0, 10, 0, 0, 0], [0, 0, 4, 14, 10, 0, 2, 0, 0], [0, 0, 0, 0, 0, 2, 0, 1, 6], [8, 11, 0, 0, 0, 0, 1, 0, 7], [0, 0, 2, 0, 0, 0, 6, 7, 0] ] g.dijkstra(0) # This code is contributed by Divyanshu Mehta",
"e": 4188,
"s": 1653,
"text": null
},
{
"code": null,
"e": 4344,
"s": 4188,
"text": "Vertex Distance from Source\n0 0\n1 4\n2 12\n3 19\n4 21\n5 11\n6 9\n7 8\n8 14\n"
},
{
"code": null,
"e": 4446,
"s": 4344,
"text": "Please refer complete article on Dijkstra’s shortest path algorithm | Greedy Algo-7 for more details!"
},
{
"code": null,
"e": 4466,
"s": 4446,
"text": "subhramanyasadhwani"
},
{
"code": null,
"e": 4478,
"s": 4466,
"text": "preyash2047"
},
{
"code": null,
"e": 4495,
"s": 4478,
"text": "arorakashish0911"
},
{
"code": null,
"e": 4509,
"s": 4495,
"text": "sumitgumber28"
},
{
"code": null,
"e": 4525,
"s": 4509,
"text": "rajeev0719singh"
},
{
"code": null,
"e": 4541,
"s": 4525,
"text": "amartyaghoshgfg"
},
{
"code": null,
"e": 4561,
"s": 4541,
"text": "piyushyadav11102002"
},
{
"code": null,
"e": 4570,
"s": 4561,
"text": "Dijkstra"
},
{
"code": null,
"e": 4586,
"s": 4570,
"text": "Python Programs"
},
{
"code": null,
"e": 4684,
"s": 4586,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4722,
"s": 4684,
"text": "Python | Convert a list to dictionary"
},
{
"code": null,
"e": 4771,
"s": 4722,
"text": "Python | Convert string dictionary to dictionary"
},
{
"code": null,
"e": 4808,
"s": 4771,
"text": "Python Program for Fibonacci numbers"
},
{
"code": null,
"e": 4865,
"s": 4808,
"text": "Python program to check whether a number is Prime or not"
},
{
"code": null,
"e": 4899,
"s": 4865,
"text": "Python program to add two numbers"
},
{
"code": null,
"e": 4958,
"s": 4899,
"text": "Python Program for Binary Search (Recursive and Iterative)"
},
{
"code": null,
"e": 4999,
"s": 4958,
"text": "Python Program for factorial of a number"
},
{
"code": null,
"e": 5054,
"s": 4999,
"text": "Python program to find second largest number in a list"
},
{
"code": null,
"e": 5100,
"s": 5054,
"text": "Iterate over characters of a string in Python"
}
] |
Parenthesis Checker | Practice | GeeksforGeeks
|
Given an expression string x. Examine whether the pairs and the orders of “{“,”}”,”(“,”)”,”[“,”]” are correct in exp.
For example, the function should return 'true' for exp = “[()]{}{[()()]()}” and 'false' for exp = “[(])”.
Example 1:
Input:
{([])}
Output:
true
Explanation:
{ ( [ ] ) }. Same colored brackets can form
balaced pairs, with 0 number of
unbalanced bracket.
Example 2:
Input:
()
Output:
true
Explanation:
(). Same bracket can form balanced pairs,
and here only 1 type of bracket is
present and in balanced way.
Example 3:
Input:
([]
Output:
false
Explanation:
([]. Here square bracket is balanced but
the small bracket is not balanced and
Hence , the output will be unbalanced.
Your Task:
This is a function problem. You only need to complete the function ispar() that takes a string as a parameter and returns a boolean value true if brackets are balanced else returns false. The printing is done automatically by the driver code.
Expected Time Complexity: O(|x|)
Expected Auixilliary Space: O(|x|)
Constraints:
1 ≤ |x| ≤ 32000
Note: The drive code prints "balanced" if function return true, otherwise it prints "not balanced".
0
kishor38681 day ago
Pyhton Solution
def ispar(self,x): l=[] for i in range(len(x)): if x[i] in '({[': l.append(x[i]) if x[i]==')': if len(l)==0: return False if l[-1]=='(': l.pop() else: return False if x[i]=='}': if len(l)==0: return False if l[-1]=='{': l.pop() else: return False if x[i]==']': if len(l)==0: return False if l[-1]=='[': l.pop() else: return False if len(l)==0: return True else: return False
0
bhardw022 days ago
Very simple python code:
def ispar(self,x):
arr = [i for i in x]
s=[]
for i in range(0,len(arr),1):
if arr[i] == '(' or arr[i] == '{' or arr[i] == '[':
s.append(arr[i])
elif arr[i] == ')':
if len(s) == 0:
return False
else:
top = s.pop()
if top != '(':
return False
elif arr[i] == '}':
if len(s) == 0:
return False
else:
top = s.pop()
if top != '{':
return False
elif arr[i] == ']':
if len(s) == 0:
return False
else:
top = s.pop()
if top != '[':
return False
if len(s) >0:
return False
else:
return True
0
ygoel852 days ago
Python code: Time take(0.02 sec)
def ispar(self,x):
# code here
left='{(['
right='})]'
stack=[]
for bracket in x:
if bracket in left:
stack.append(bracket)
elif bracket in right:
if(len(stack)==0):
return False
if(right.index(bracket)!=left.index(stack.pop())):
return False
if(len(stack)!=0):
return False
else:
return True
0
protiks8903 days ago
def ispar(self,x): # code here while True: if '{}' in x: x=x.replace('{}','') elif '()' in x: x=x.replace('()','') elif '[]' in x: x=x.replace('[]','') else: return not x
0
1912100293 days ago
bool ispar(string x)
{
int n = x.length();
stack<int> s;
map<int, int> m = {
{ '(', 1 },
{ '[', 2 },
{ '{', 3 },
{ ')', -1 },
{ ']', -2 },
{ '}', -3 }
};
bool valid = true;
for (char c : x) {
if (m[c] > 0) s.push(m[c]);
else if (!s.empty()) {
int t = s.top();
s.pop();
if (t != -m[c]) {
valid = false;
break;
}
} else valid = false;
}
if (!s.empty()) valid = false;
return valid;
}
+1
sunnychaware3 days ago
// utility function for checking if the
// left and right paranthesis matches.
bool match(char a, char b){
if(a=='{' && b=='}' ||
a=='(' && b==')' ||
a=='[' && b==']') return true;
else return false;
}
// main function
bool ispar(string x)
{
if(x.length()&1)return false;
stack<char> s;
for(int i=0;i<x.length();i++){
if(x[i]=='{' || x[i]=='(' || x[i]=='['){
s.push(x[i]);
}
else{
if(s.empty())return false;
if(match(s.top(),x[i]))s.pop();
else return false;
}
}
if(!s.empty())return false;
else return true;
}
+1
takshat013 days ago
bool ispar(string x)
{
// Your code here
int len=x.length();
if(len&1){
return false;
}
stack<char> s;
for(int i=0; i<len; i++){
if(x[i]=='{' || x[i]=='[' || x[i]=='('){
s.push(x[i]);
}
else if(!s.empty() &&((x[i]=='}' && s.top()=='{') || (x[i]==']' && s.top()=='[') || (x[i]==')' && s.top()=='('))){
s.pop();
}
else{
return false;
}
}
if(s.empty()){
return true;
}
return false;
}
+1
thecodebuilder4 days ago
Approach -
Use a stack to store open braces and whenever the correct closing brace is encountered, pop from stack. If at last, stack is not empty, it means there is an extra opening or closing brace or order of braces is wrong. Thus, it is unbalanced.
Algo -
Traverse the given string character by character.
IF (stack is not empty) AND ((top element of stack is ‘(’ AND current string element is ‘)’) OR (top element of stack is ‘{’ AND current string element is ‘}’) OR (top element of stack is ‘[’ AND current string element is ‘]’)) pop the top element from stack, else push it to stack.
If stack is empty at end, return true else false.
Code -
bool ispar(string x)
{
// Your code here
stack<char> st;
for(int i=0;i<x.length();i++){
if(!st.empty() && (( st.top() =='(' && x[i]==')' ) || ( st.top()=='{' && x[i]=='}' ) || ( st.top()=='[' && x[i]==']' )))
st.pop();
else
st.push(x[i]);
}
return st.empty()?true:false;
}
0
byadwalnaveen12284 days ago
class Solution{ public: //Function to check if brackets are balanced or not. bool ispar(string x) { // Your code here stack<char> temp; for(int i=0;i<x.length();i++) { if(temp.empty()) { temp.push(x[i]); } else if((temp.top()=='('&& x[i]==')') || (temp.top()=='{' && x[i]=='}') || (temp.top()=='[' && x[i]==']')) { temp.pop(); } else { temp.push(x[i]); } } if(temp.empty()) { return true; } return false; }
};
0
luvgupta76694 days ago
Simple Working Best Java Solution Using Stack | O(N)-
static boolean ispar(String x) {
Stack<Character> st = new Stack<>();
for (int i=0; i< x.length(); i++) {
char ch = x.charAt(i);
if (ch == '{') {
st.push('}');
} else if (ch == '[') {
st.push(']');
} else if (ch == '(') {
st.push(')');
} else if (st.isEmpty() || st.pop()!=ch) {
return false;
}
}
return st.isEmpty();
}
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
want to view the editorial?
Login to access your submissions.
Problem
Contest
Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested
against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code.
On submission, your code is tested against multiple test cases consisting of all
possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as
the final solution code.
You can view the solutions submitted by other users from the submission tab.
Make sure you are not using ad-blockers.
Disable browser extensions.
We recommend using latest version of your browser for best experience.
Avoid using static/global variables in coding problems as your code is tested
against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases in coding problems does not guarantee the
correctness of code. On submission, your code is tested against multiple test cases
consisting of all possible corner cases and stress constraints.
|
[
{
"code": null,
"e": 462,
"s": 238,
"text": "Given an expression string x. Examine whether the pairs and the orders of “{“,”}”,”(“,”)”,”[“,”]” are correct in exp.\nFor example, the function should return 'true' for exp = “[()]{}{[()()]()}” and 'false' for exp = “[(])”."
},
{
"code": null,
"e": 473,
"s": 462,
"text": "Example 1:"
},
{
"code": null,
"e": 614,
"s": 473,
"text": "Input:\n{([])}\nOutput: \ntrue\nExplanation: \n{ ( [ ] ) }. Same colored brackets can form \nbalaced pairs, with 0 number of \nunbalanced bracket.\n"
},
{
"code": null,
"e": 625,
"s": 614,
"text": "Example 2:"
},
{
"code": null,
"e": 773,
"s": 625,
"text": "Input: \n()\nOutput: \ntrue\nExplanation: \n(). Same bracket can form balanced pairs, \nand here only 1 type of bracket is \npresent and in balanced way.\n"
},
{
"code": null,
"e": 784,
"s": 773,
"text": "Example 3:"
},
{
"code": null,
"e": 945,
"s": 784,
"text": "Input: \n([]\nOutput: \nfalse\nExplanation: \n([]. Here square bracket is balanced but \nthe small bracket is not balanced and \nHence , the output will be unbalanced."
},
{
"code": null,
"e": 1298,
"s": 945,
"text": "Your Task:\nThis is a function problem. You only need to complete the function ispar() that takes a string as a parameter and returns a boolean value true if brackets are balanced else returns false. The printing is done automatically by the driver code.\n\nExpected Time Complexity: O(|x|)\nExpected Auixilliary Space: O(|x|)\n\nConstraints:\n1 ≤ |x| ≤ 32000"
},
{
"code": null,
"e": 1398,
"s": 1298,
"text": "Note: The drive code prints \"balanced\" if function return true, otherwise it prints \"not balanced\"."
},
{
"code": null,
"e": 1400,
"s": 1398,
"text": "0"
},
{
"code": null,
"e": 1420,
"s": 1400,
"text": "kishor38681 day ago"
},
{
"code": null,
"e": 1439,
"s": 1420,
"text": "Pyhton Solution "
},
{
"code": null,
"e": 2201,
"s": 1439,
"text": " def ispar(self,x): l=[] for i in range(len(x)): if x[i] in '({[': l.append(x[i]) if x[i]==')': if len(l)==0: return False if l[-1]=='(': l.pop() else: return False if x[i]=='}': if len(l)==0: return False if l[-1]=='{': l.pop() else: return False if x[i]==']': if len(l)==0: return False if l[-1]=='[': l.pop() else: return False if len(l)==0: return True else: return False"
},
{
"code": null,
"e": 2203,
"s": 2201,
"text": "0"
},
{
"code": null,
"e": 2222,
"s": 2203,
"text": "bhardw022 days ago"
},
{
"code": null,
"e": 2247,
"s": 2222,
"text": "Very simple python code:"
},
{
"code": null,
"e": 3203,
"s": 2247,
"text": "def ispar(self,x):\n arr = [i for i in x]\n s=[]\n for i in range(0,len(arr),1):\n if arr[i] == '(' or arr[i] == '{' or arr[i] == '[':\n s.append(arr[i])\n elif arr[i] == ')':\n if len(s) == 0:\n return False\n else:\n top = s.pop()\n if top != '(':\n return False\n elif arr[i] == '}':\n if len(s) == 0:\n return False\n else:\n top = s.pop()\n if top != '{':\n return False\n elif arr[i] == ']':\n if len(s) == 0:\n return False\n else:\n top = s.pop()\n if top != '[':\n return False\n if len(s) >0:\n return False\n else:\n return True"
},
{
"code": null,
"e": 3205,
"s": 3203,
"text": "0"
},
{
"code": null,
"e": 3223,
"s": 3205,
"text": "ygoel852 days ago"
},
{
"code": null,
"e": 3260,
"s": 3223,
"text": " Python code: Time take(0.02 sec)"
},
{
"code": null,
"e": 3736,
"s": 3260,
"text": "def ispar(self,x):\n # code here\n left='{(['\n right='})]'\n stack=[]\n for bracket in x:\n if bracket in left:\n stack.append(bracket)\n elif bracket in right:\n if(len(stack)==0):\n return False\n if(right.index(bracket)!=left.index(stack.pop())):\n return False\n \n if(len(stack)!=0):\n return False\n else:\n return True"
},
{
"code": null,
"e": 3738,
"s": 3736,
"text": "0"
},
{
"code": null,
"e": 3759,
"s": 3738,
"text": "protiks8903 days ago"
},
{
"code": null,
"e": 4049,
"s": 3759,
"text": "def ispar(self,x): # code here while True: if '{}' in x: x=x.replace('{}','') elif '()' in x: x=x.replace('()','') elif '[]' in x: x=x.replace('[]','') else: return not x "
},
{
"code": null,
"e": 4051,
"s": 4049,
"text": "0"
},
{
"code": null,
"e": 4071,
"s": 4051,
"text": "1912100293 days ago"
},
{
"code": null,
"e": 4656,
"s": 4071,
"text": "bool ispar(string x)\n{\n int n = x.length();\n stack<int> s;\n map<int, int> m = {\n { '(', 1 },\n { '[', 2 },\n { '{', 3 },\n { ')', -1 },\n { ']', -2 },\n { '}', -3 }\n };\n \n bool valid = true;\n for (char c : x) {\n if (m[c] > 0) s.push(m[c]);\n else if (!s.empty()) {\n int t = s.top();\n s.pop();\n if (t != -m[c]) {\n valid = false;\n break;\n }\n } else valid = false;\n }\n \n if (!s.empty()) valid = false;\n \n return valid;\n}"
},
{
"code": null,
"e": 4659,
"s": 4656,
"text": "+1"
},
{
"code": null,
"e": 4682,
"s": 4659,
"text": "sunnychaware3 days ago"
},
{
"code": null,
"e": 5414,
"s": 4682,
"text": "// utility function for checking if the \n// left and right paranthesis matches. \nbool match(char a, char b){\n \n if(a=='{' && b=='}' ||\n a=='(' && b==')' ||\n a=='[' && b==']') return true;\n else return false;\n }\n// main function\n bool ispar(string x)\n {\n if(x.length()&1)return false;\n stack<char> s;\n for(int i=0;i<x.length();i++){\n if(x[i]=='{' || x[i]=='(' || x[i]=='['){\n s.push(x[i]);\n }\n else{\n if(s.empty())return false;\n if(match(s.top(),x[i]))s.pop();\n else return false;\n }\n }\n if(!s.empty())return false;\n else return true;\n }"
},
{
"code": null,
"e": 5417,
"s": 5414,
"text": "+1"
},
{
"code": null,
"e": 5437,
"s": 5417,
"text": "takshat013 days ago"
},
{
"code": null,
"e": 6056,
"s": 5437,
"text": " bool ispar(string x)\n {\n // Your code here\n int len=x.length();\n if(len&1){\n return false;\n }\n \n stack<char> s;\n for(int i=0; i<len; i++){\n if(x[i]=='{' || x[i]=='[' || x[i]=='('){\n s.push(x[i]);\n }\n else if(!s.empty() &&((x[i]=='}' && s.top()=='{') || (x[i]==']' && s.top()=='[') || (x[i]==')' && s.top()=='('))){\n s.pop();\n }\n else{\n return false;\n }\n }\n \n if(s.empty()){\n return true;\n }\n \n return false;\n }"
},
{
"code": null,
"e": 6059,
"s": 6056,
"text": "+1"
},
{
"code": null,
"e": 6084,
"s": 6059,
"text": "thecodebuilder4 days ago"
},
{
"code": null,
"e": 6095,
"s": 6084,
"text": "Approach -"
},
{
"code": null,
"e": 6336,
"s": 6095,
"text": "Use a stack to store open braces and whenever the correct closing brace is encountered, pop from stack. If at last, stack is not empty, it means there is an extra opening or closing brace or order of braces is wrong. Thus, it is unbalanced."
},
{
"code": null,
"e": 6345,
"s": 6338,
"text": "Algo -"
},
{
"code": null,
"e": 6395,
"s": 6345,
"text": "Traverse the given string character by character."
},
{
"code": null,
"e": 6678,
"s": 6395,
"text": "IF (stack is not empty) AND ((top element of stack is ‘(’ AND current string element is ‘)’) OR (top element of stack is ‘{’ AND current string element is ‘}’) OR (top element of stack is ‘[’ AND current string element is ‘]’)) pop the top element from stack, else push it to stack."
},
{
"code": null,
"e": 6728,
"s": 6678,
"text": "If stack is empty at end, return true else false."
},
{
"code": null,
"e": 6735,
"s": 6728,
"text": "Code -"
},
{
"code": null,
"e": 7121,
"s": 6735,
"text": "bool ispar(string x)\n {\n // Your code here\n stack<char> st;\n for(int i=0;i<x.length();i++){\n if(!st.empty() && (( st.top() =='(' && x[i]==')' ) || ( st.top()=='{' && x[i]=='}' ) || ( st.top()=='[' && x[i]==']' )))\n st.pop();\n \n else\n st.push(x[i]);\n }\n return st.empty()?true:false;\n }"
},
{
"code": null,
"e": 7125,
"s": 7123,
"text": "0"
},
{
"code": null,
"e": 7153,
"s": 7125,
"text": "byadwalnaveen12284 days ago"
},
{
"code": null,
"e": 7803,
"s": 7153,
"text": "class Solution{ public: //Function to check if brackets are balanced or not. bool ispar(string x) { // Your code here stack<char> temp; for(int i=0;i<x.length();i++) { if(temp.empty()) { temp.push(x[i]); } else if((temp.top()=='('&& x[i]==')') || (temp.top()=='{' && x[i]=='}') || (temp.top()=='[' && x[i]==']')) { temp.pop(); } else { temp.push(x[i]); } } if(temp.empty()) { return true; } return false; }"
},
{
"code": null,
"e": 7806,
"s": 7803,
"text": "};"
},
{
"code": null,
"e": 7808,
"s": 7806,
"text": "0"
},
{
"code": null,
"e": 7831,
"s": 7808,
"text": "luvgupta76694 days ago"
},
{
"code": null,
"e": 7885,
"s": 7831,
"text": "Simple Working Best Java Solution Using Stack | O(N)-"
},
{
"code": null,
"e": 8399,
"s": 7887,
"text": " static boolean ispar(String x) {\n Stack<Character> st = new Stack<>();\n for (int i=0; i< x.length(); i++) {\n char ch = x.charAt(i);\n if (ch == '{') {\n st.push('}'); \n } else if (ch == '[') { \n st.push(']'); \n } else if (ch == '(') {\n st.push(')'); \n } else if (st.isEmpty() || st.pop()!=ch) {\n return false;\n }\n }\n return st.isEmpty();\n }"
},
{
"code": null,
"e": 8547,
"s": 8401,
"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": 8583,
"s": 8547,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 8593,
"s": 8583,
"text": "\nProblem\n"
},
{
"code": null,
"e": 8603,
"s": 8593,
"text": "\nContest\n"
},
{
"code": null,
"e": 8666,
"s": 8603,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 8851,
"s": 8666,
"text": "Avoid using static/global variables in your code as your code is tested \n against multiple test cases and these tend to retain their previous values."
},
{
"code": null,
"e": 9135,
"s": 8851,
"text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code.\n On submission, your code is tested against multiple test cases consisting of all\n possible corner cases and stress constraints."
},
{
"code": null,
"e": 9281,
"s": 9135,
"text": "You can access the hints to get an idea about what is expected of you as well as\n the final solution code."
},
{
"code": null,
"e": 9358,
"s": 9281,
"text": "You can view the solutions submitted by other users from the submission tab."
},
{
"code": null,
"e": 9399,
"s": 9358,
"text": "Make sure you are not using ad-blockers."
},
{
"code": null,
"e": 9427,
"s": 9399,
"text": "Disable browser extensions."
},
{
"code": null,
"e": 9498,
"s": 9427,
"text": "We recommend using latest version of your browser for best experience."
},
{
"code": null,
"e": 9685,
"s": 9498,
"text": "Avoid using static/global variables in coding problems as your code is tested \n against multiple test cases and these tend to retain their previous values."
}
] |
pwd module in Python
|
02 Aug, 2019
pwd module in Python provides access to the Unix user account and password database. Each entry stored in Unix user account and password database is reported as a tuple-like object whose attributes are similar as the members of passwd structure defined in <pwd.h> header file.
Following are the attributes of the tuple-like object which represents the entries stored in Unix user account and password database:
Note: pwd module is a UNIX specific service. So, all method of this module is available on UNIX versions only.
pwd module defines following three methods:
pwd.getpwuid() method
pwd.getpwnam() method
pwd.getpwall() method
pwd.getpwnam() method in Python is used to get the password database entry for the specified user id.
Syntax: pwd.getpwuid(uid)
Parameter:uid: A numeric value representing the user id for which password database entry is required.
Return type: This method returns a tuple-like object of class ‘pwd.struct_passwd’ which represents the password database entry for the specified user id.
Code: Use of pwd.getpwuid() method
# Python program to explain pwd.getpwuid() method # importing pwd module import pwd # User iduid = 1000 # Get the password # database entry for the# specified user id# using pwd.getpwuid() methodentry = pwd.getpwuid(uid) # Print the retrieved entryprint("Password database entry for user id : % d:" % uid)print(entry) # User iduid = 0 # Get the password # database entry for the# specified user id# using pwd.getpwuid() methodentry = pwd.getpwuid(uid) # Print the retrieved entryprint("Password database entry for user id : % d:" % uid)print(entry)
Password database entry for user id : 1000
pwd.struct_passwd(pw_name='ihritik', pw_passwd='x', pw_uid=1000, pw_gid=1000,
pw_gecos='Hritik,,, ', pw_dir='/home/ihritik', pw_shell='/bin/bash')
Password database entry for user id : 0
pwd.struct_passwd(pw_name='root', pw_passwd='x', pw_uid=0, pw_gid=0, pw_gecos='root',
pw_dir='/root', pw_shell='/bin/bash')
pwd.getpwnam() method in Python is used to get the password database entry for the specified user name
Syntax: pwd.getpwnam(name)
Parameter:name: A string value representing the user name for which password database entry is required.
Return type: This method returns a tuple-like object of class ‘pwd.struct_passwd’ which represents the password database entry for the specified name.
Code: Use of pwd.getpwnam() method
# Python program to explain pwd.getpwnam() method # importing pwd module import pwd # User namename = "ihritik" # Get the password # database entry for the# specified username# using pwd.getpwnam() methodentry = pwd.getpwnam(name) # Print the retrieved entryprint("Password database entry for '% s':" % name)print(entry) # User namename = "root" # Get the password # database entry for the# specified username# using pwd.getpwnam() methodentry = pwd.getpwnam(name) # Print the retrieved entryprint("\nPassword database entry for '% s':" % name)print(entry)
Password database entry for 'ihritik':
pwd.struct_passwd(pw_name='ihritik', pw_passwd='x', pw_uid=1000, pw_gid=1000,
pw_gecos='Hritik,,, ', pw_dir='/home/ihritik', pw_shell='/bin/bash')
Password database entry for 'root':
pwd.struct_passwd(pw_name='root', pw_passwd='x', pw_uid=0, pw_gid=0, pw_gecos='root',
pw_dir='/root', pw_shell='/bin/bash')
pwd.getpwall() method in Python is used to get the list of all available entries stored in password database.
Syntax: pwd.getpwall()
Parameter: No parameter is required.
Return type: This method returns a list of tuple-like object of class ‘pwd.struct_passwd’ whose elements represent all available entries stored in password database.
Code: Use of pwd.getpwall() method
# Python program to explain pwd.getpwall() method # importing pwd module import pwd # Get the list # of all available password# database entries using# pwd.getpwall() methodentries = pwd.getpwall() # Print the list print("Password database entries:")for row in entries: print(row)
Password database entries:pwd.struct_passwd(pw_name=’root’, pw_passwd=’x’, pw_uid=0, pw_gid=0, pw_gecos=’root’, pw_dir=’/root’, pw_shell=’/bin/bash’)pwd.struct_passwd(pw_name=’daemon’, pw_passwd=’x’, pw_uid=1, pw_gid=1, pw_gecos=’daemon’, pw_dir=’/usr/sbin’, pw_shell=’/usr/sbin/nologin’)pwd.struct_passwd(pw_name=’bin’, pw_passwd=’x’, pw_uid=2, pw_gid=2, pw_gecos=’bin’, pw_dir=’/bin’, pw_shell=’/usr/sbin/nologin’)pwd.struct_passwd(pw_name=’sys’, pw_passwd=’x’, pw_uid=3, pw_gid=3, pw_gecos=’sys’, pw_dir=’/dev’, pw_shell=’/usr/sbin/nologin’)pwd.struct_passwd(pw_name=’sync’, pw_passwd=’x’, pw_uid=4, pw_gid=65534, pw_gecos=’sync’, pw_dir=’/bin’, pw_shell=’/bin/sync’)pwd.struct_passwd(pw_name=’games’, pw_passwd=’x’, pw_uid=5, pw_gid=60, pw_gecos=’games’, pw_dir=’/usr/games’, pw_shell=’/usr/sbin/nologin’)pwd.struct_passwd(pw_name=’man’, pw_passwd=’x’, pw_uid=6, pw_gid=12, pw_gecos=’man’, pw_dir=’/var/cache/man’, pw_shell=’/usr/sbin/nologin’)pwd.struct_passwd(pw_name=’lp’, pw_passwd=’x’, pw_uid=7, pw_gid=7, pw_gecos=’lp’, pw_dir=’/var/spool/lpd’, pw_shell=’/usr/sbin/nologin’)pwd.struct_passwd(pw_name=’mail’, pw_passwd=’x’, pw_uid=8, pw_gid=8, pw_gecos=’mail’, pw_dir=’/var/mail’, pw_shell=’/usr/sbin/nologin’)pwd.struct_passwd(pw_name=’news’, pw_passwd=’x’, pw_uid=9, pw_gid=9, pw_gecos=’news’, pw_dir=’/var/spool/news’, pw_shell=’/usr/sbin/nologin’)pwd.struct_passwd(pw_name=’uucp’, pw_passwd=’x’, pw_uid=10, pw_gid=10, pw_gecos=’uucp’, pw_dir=’/var/spool/uucp’, pw_shell=’/usr/sbin/nologin’)pwd.struct_passwd(pw_name=’proxy’, pw_passwd=’x’, pw_uid=13, pw_gid=13, pw_gecos=’proxy’, pw_dir=’/bin’, pw_shell=’/usr/sbin/nologin’)pwd.struct_passwd(pw_name=’www-data’, pw_passwd=’x’, pw_uid=33, pw_gid=33, pw_gecos=’www-data’, pw_dir=’/var/www’, pw_shell=’/usr/sbin/nologin’)pwd.struct_passwd(pw_name=’backup’, pw_passwd=’x’, pw_uid=34, pw_gid=34, pw_gecos=’backup’, pw_dir=’/var/backups’, pw_shell=’/usr/sbin/nologin’)pwd.struct_passwd(pw_name=’list’, pw_passwd=’x’, pw_uid=38, pw_gid=38, pw_gecos=’Mailing List Manager’, pw_dir=’/var/list’, pw_shell=’/usr/sbin/nologin’)pwd.struct_passwd(pw_name=’irc’, pw_passwd=’x’, pw_uid=39, pw_gid=39, pw_gecos=’ircd’, pw_dir=’/var/run/ircd’, pw_shell=’/usr/sbin/nologin’)pwd.struct_passwd(pw_name=’gnats’, pw_passwd=’x’, pw_uid=41, pw_gid=41, pw_gecos=’Gnats Bug-Reporting System (admin)’, pw_dir=’/var/lib/gnats’, pw_shell=’/usr/sbin/nologin’)pwd.struct_passwd(pw_name=’nobody’, pw_passwd=’x’, pw_uid=65534, pw_gid=65534, pw_gecos=’nobody’, pw_dir=’/nonexistent’, pw_shell=’/usr/sbin/nologin’)pwd.struct_passwd(pw_name=’systemd-timesync’, pw_passwd=’x’, pw_uid=100, pw_gid=102, pw_gecos=’systemd Time Synchronization,,, ‘, pw_dir=’/run/systemd’, pw_shell=’/bin/false’)pwd.struct_passwd(pw_name=’systemd-network’, pw_passwd=’x’, pw_uid=101, pw_gid=103, pw_gecos=’systemd Network Management,,, ‘, pw_dir=’/run/systemd/netif’, pw_shell=’/bin/false’)pwd.struct_passwd(pw_name=’systemd-resolve’, pw_passwd=’x’, pw_uid=102, pw_gid=104, pw_gecos=’systemd Resolver,,, ‘, pw_dir=’/run/systemd/resolve’, pw_shell=’/bin/false’)pwd.struct_passwd(pw_name=’systemd-bus-proxy’, pw_passwd=’x’, pw_uid=103, pw_gid=105, pw_gecos=’systemd Bus Proxy,,, ‘, pw_dir=’/run/systemd’, pw_shell=’/bin/false’)pwd.struct_passwd(pw_name=’syslog’, pw_passwd=’x’, pw_uid=104, pw_gid=108, pw_gecos=”, pw_dir=’/home/syslog’, pw_shell=’/bin/false’)pwd.struct_passwd(pw_name=’messagebus’, pw_passwd=’x’, pw_uid=105, pw_gid=109, pw_gecos=”, pw_dir=’/var/run/dbus’, pw_shell=’/bin/false’)pwd.struct_passwd(pw_name=’_apt’, pw_passwd=’x’, pw_uid=106, pw_gid=65534, pw_gecos=”, pw_dir=’/nonexistent’, pw_shell=’/bin/false’)pwd.struct_passwd(pw_name=’uuidd’, pw_passwd=’x’, pw_uid=107, pw_gid=113, pw_gecos=”, pw_dir=’/run/uuidd’, pw_shell=’/bin/false’)pwd.struct_passwd(pw_name=’rtkit’, pw_passwd=’x’, pw_uid=108, pw_gid=114, pw_gecos=’RealtimeKit,,, ‘, pw_dir=’/proc’, pw_shell=’/bin/false’)pwd.struct_passwd(pw_name=’avahi-autoipd’, pw_passwd=’x’, pw_uid=109, pw_gid=115, pw_gecos=’Avahi autoip daemon,,, ‘, pw_dir=’/var/lib/avahi-autoipd’, pw_shell=’/bin/false’)pwd.struct_passwd(pw_name=’usbmux’, pw_passwd=’x’, pw_uid=110, pw_gid=46, pw_gecos=’usbmux daemon,,, ‘, pw_dir=’/var/lib/usbmux’, pw_shell=’/bin/false’)pwd.struct_passwd(pw_name=’dnsmasq’, pw_passwd=’x’, pw_uid=111, pw_gid=65534, pw_gecos=’dnsmasq,,, ‘, pw_dir=’/var/lib/misc’, pw_shell=’/bin/false’)pwd.struct_passwd(pw_name=’whoopsie’, pw_passwd=’x’, pw_uid=112, pw_gid=119, pw_gecos=”, pw_dir=’/nonexistent’, pw_shell=’/bin/false’)pwd.struct_passwd(pw_name=’kernoops’, pw_passwd=’x’, pw_uid=113, pw_gid=65534, pw_gecos=’Kernel Oops Tracking Daemon,,, ‘, pw_dir=’/’, pw_shell=’/bin/false’)pwd.struct_passwd(pw_name=’speech-dispatcher’, pw_passwd=’x’, pw_uid=114, pw_gid=29, pw_gecos=’Speech Dispatcher,,, ‘, pw_dir=’/var/run/speech-dispatcher’, pw_shell=’/bin/false’)pwd.struct_passwd(pw_name=’avahi’, pw_passwd=’x’, pw_uid=115, pw_gid=120, pw_gecos=’Avahi mDNS daemon,,, ‘, pw_dir=’/var/run/avahi-daemon’, pw_shell=’/bin/false’)pwd.struct_passwd(pw_name=’saned’, pw_passwd=’x’, pw_uid=116, pw_gid=122, pw_gecos=”, pw_dir=’/var/lib/saned’, pw_shell=’/bin/false’)pwd.struct_passwd(pw_name=’pulse’, pw_passwd=’x’, pw_uid=117, pw_gid=123, pw_gecos=’PulseAudio daemon,,, ‘, pw_dir=’/var/run/pulse’, pw_shell=’/bin/false’)pwd.struct_passwd(pw_name=’colord’, pw_passwd=’x’, pw_uid=118, pw_gid=125, pw_gecos=’colord colour management daemon,,, ‘, pw_dir=’/var/lib/colord’, pw_shell=’/bin/false’)pwd.struct_passwd(pw_name=’hplip’, pw_passwd=’x’, pw_uid=119, pw_gid=7, pw_gecos=’HPLIP system user,,, ‘, pw_dir=’/var/run/hplip’, pw_shell=’/bin/false’)pwd.struct_passwd(pw_name=’geoclue’, pw_passwd=’x’, pw_uid=120, pw_gid=126, pw_gecos=”, pw_dir=’/var/lib/geoclue’, pw_shell=’/bin/false’)pwd.struct_passwd(pw_name=’gdm’, pw_passwd=’x’, pw_uid=121, pw_gid=127, pw_gecos=’Gnome Display Manager’, pw_dir=’/var/lib/gdm3′, pw_shell=’/bin/false’)pwd.struct_passwd(pw_name=’ihritik’, pw_passwd=’x’, pw_uid=1000, pw_gid=1000, pw_gecos=’Hritik,,, ‘, pw_dir=’/home/ihritik’, pw_shell=’/bin/bash’)pwd.struct_passwd(pw_name=’sshd’, pw_passwd=’x’, pw_uid=122, pw_gid=65534, pw_gecos=”, pw_dir=’/run/sshd’, pw_shell=’/usr/sbin/nologin’)pwd.struct_passwd(pw_name=’master’, pw_passwd=’x’, pw_uid=1001, pw_gid=1002, pw_gecos=’,,, ‘, pw_dir=’/home/master’, pw_shell=’/bin/bash’)
python-modules
python-utility
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Python OOPs Concepts
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n02 Aug, 2019"
},
{
"code": null,
"e": 305,
"s": 28,
"text": "pwd module in Python provides access to the Unix user account and password database. Each entry stored in Unix user account and password database is reported as a tuple-like object whose attributes are similar as the members of passwd structure defined in <pwd.h> header file."
},
{
"code": null,
"e": 439,
"s": 305,
"text": "Following are the attributes of the tuple-like object which represents the entries stored in Unix user account and password database:"
},
{
"code": null,
"e": 550,
"s": 439,
"text": "Note: pwd module is a UNIX specific service. So, all method of this module is available on UNIX versions only."
},
{
"code": null,
"e": 594,
"s": 550,
"text": "pwd module defines following three methods:"
},
{
"code": null,
"e": 616,
"s": 594,
"text": "pwd.getpwuid() method"
},
{
"code": null,
"e": 638,
"s": 616,
"text": "pwd.getpwnam() method"
},
{
"code": null,
"e": 660,
"s": 638,
"text": "pwd.getpwall() method"
},
{
"code": null,
"e": 762,
"s": 660,
"text": "pwd.getpwnam() method in Python is used to get the password database entry for the specified user id."
},
{
"code": null,
"e": 788,
"s": 762,
"text": "Syntax: pwd.getpwuid(uid)"
},
{
"code": null,
"e": 891,
"s": 788,
"text": "Parameter:uid: A numeric value representing the user id for which password database entry is required."
},
{
"code": null,
"e": 1045,
"s": 891,
"text": "Return type: This method returns a tuple-like object of class ‘pwd.struct_passwd’ which represents the password database entry for the specified user id."
},
{
"code": null,
"e": 1080,
"s": 1045,
"text": "Code: Use of pwd.getpwuid() method"
},
{
"code": "# Python program to explain pwd.getpwuid() method # importing pwd module import pwd # User iduid = 1000 # Get the password # database entry for the# specified user id# using pwd.getpwuid() methodentry = pwd.getpwuid(uid) # Print the retrieved entryprint(\"Password database entry for user id : % d:\" % uid)print(entry) # User iduid = 0 # Get the password # database entry for the# specified user id# using pwd.getpwuid() methodentry = pwd.getpwuid(uid) # Print the retrieved entryprint(\"Password database entry for user id : % d:\" % uid)print(entry)",
"e": 1638,
"s": 1080,
"text": null
},
{
"code": null,
"e": 1994,
"s": 1638,
"text": "Password database entry for user id : 1000\npwd.struct_passwd(pw_name='ihritik', pw_passwd='x', pw_uid=1000, pw_gid=1000,\npw_gecos='Hritik,,, ', pw_dir='/home/ihritik', pw_shell='/bin/bash')\n\nPassword database entry for user id : 0\npwd.struct_passwd(pw_name='root', pw_passwd='x', pw_uid=0, pw_gid=0, pw_gecos='root',\npw_dir='/root', pw_shell='/bin/bash')\n"
},
{
"code": null,
"e": 2097,
"s": 1994,
"text": "pwd.getpwnam() method in Python is used to get the password database entry for the specified user name"
},
{
"code": null,
"e": 2124,
"s": 2097,
"text": "Syntax: pwd.getpwnam(name)"
},
{
"code": null,
"e": 2229,
"s": 2124,
"text": "Parameter:name: A string value representing the user name for which password database entry is required."
},
{
"code": null,
"e": 2380,
"s": 2229,
"text": "Return type: This method returns a tuple-like object of class ‘pwd.struct_passwd’ which represents the password database entry for the specified name."
},
{
"code": null,
"e": 2415,
"s": 2380,
"text": "Code: Use of pwd.getpwnam() method"
},
{
"code": "# Python program to explain pwd.getpwnam() method # importing pwd module import pwd # User namename = \"ihritik\" # Get the password # database entry for the# specified username# using pwd.getpwnam() methodentry = pwd.getpwnam(name) # Print the retrieved entryprint(\"Password database entry for '% s':\" % name)print(entry) # User namename = \"root\" # Get the password # database entry for the# specified username# using pwd.getpwnam() methodentry = pwd.getpwnam(name) # Print the retrieved entryprint(\"\\nPassword database entry for '% s':\" % name)print(entry)",
"e": 2983,
"s": 2415,
"text": null
},
{
"code": null,
"e": 3331,
"s": 2983,
"text": "Password database entry for 'ihritik':\npwd.struct_passwd(pw_name='ihritik', pw_passwd='x', pw_uid=1000, pw_gid=1000,\npw_gecos='Hritik,,, ', pw_dir='/home/ihritik', pw_shell='/bin/bash')\n\nPassword database entry for 'root':\npwd.struct_passwd(pw_name='root', pw_passwd='x', pw_uid=0, pw_gid=0, pw_gecos='root',\npw_dir='/root', pw_shell='/bin/bash')\n"
},
{
"code": null,
"e": 3441,
"s": 3331,
"text": "pwd.getpwall() method in Python is used to get the list of all available entries stored in password database."
},
{
"code": null,
"e": 3464,
"s": 3441,
"text": "Syntax: pwd.getpwall()"
},
{
"code": null,
"e": 3501,
"s": 3464,
"text": "Parameter: No parameter is required."
},
{
"code": null,
"e": 3667,
"s": 3501,
"text": "Return type: This method returns a list of tuple-like object of class ‘pwd.struct_passwd’ whose elements represent all available entries stored in password database."
},
{
"code": null,
"e": 3702,
"s": 3667,
"text": "Code: Use of pwd.getpwall() method"
},
{
"code": "# Python program to explain pwd.getpwall() method # importing pwd module import pwd # Get the list # of all available password# database entries using# pwd.getpwall() methodentries = pwd.getpwall() # Print the list print(\"Password database entries:\")for row in entries: print(row)",
"e": 3995,
"s": 3702,
"text": null
},
{
"code": null,
"e": 10320,
"s": 3995,
"text": "Password database entries:pwd.struct_passwd(pw_name=’root’, pw_passwd=’x’, pw_uid=0, pw_gid=0, pw_gecos=’root’, pw_dir=’/root’, pw_shell=’/bin/bash’)pwd.struct_passwd(pw_name=’daemon’, pw_passwd=’x’, pw_uid=1, pw_gid=1, pw_gecos=’daemon’, pw_dir=’/usr/sbin’, pw_shell=’/usr/sbin/nologin’)pwd.struct_passwd(pw_name=’bin’, pw_passwd=’x’, pw_uid=2, pw_gid=2, pw_gecos=’bin’, pw_dir=’/bin’, pw_shell=’/usr/sbin/nologin’)pwd.struct_passwd(pw_name=’sys’, pw_passwd=’x’, pw_uid=3, pw_gid=3, pw_gecos=’sys’, pw_dir=’/dev’, pw_shell=’/usr/sbin/nologin’)pwd.struct_passwd(pw_name=’sync’, pw_passwd=’x’, pw_uid=4, pw_gid=65534, pw_gecos=’sync’, pw_dir=’/bin’, pw_shell=’/bin/sync’)pwd.struct_passwd(pw_name=’games’, pw_passwd=’x’, pw_uid=5, pw_gid=60, pw_gecos=’games’, pw_dir=’/usr/games’, pw_shell=’/usr/sbin/nologin’)pwd.struct_passwd(pw_name=’man’, pw_passwd=’x’, pw_uid=6, pw_gid=12, pw_gecos=’man’, pw_dir=’/var/cache/man’, pw_shell=’/usr/sbin/nologin’)pwd.struct_passwd(pw_name=’lp’, pw_passwd=’x’, pw_uid=7, pw_gid=7, pw_gecos=’lp’, pw_dir=’/var/spool/lpd’, pw_shell=’/usr/sbin/nologin’)pwd.struct_passwd(pw_name=’mail’, pw_passwd=’x’, pw_uid=8, pw_gid=8, pw_gecos=’mail’, pw_dir=’/var/mail’, pw_shell=’/usr/sbin/nologin’)pwd.struct_passwd(pw_name=’news’, pw_passwd=’x’, pw_uid=9, pw_gid=9, pw_gecos=’news’, pw_dir=’/var/spool/news’, pw_shell=’/usr/sbin/nologin’)pwd.struct_passwd(pw_name=’uucp’, pw_passwd=’x’, pw_uid=10, pw_gid=10, pw_gecos=’uucp’, pw_dir=’/var/spool/uucp’, pw_shell=’/usr/sbin/nologin’)pwd.struct_passwd(pw_name=’proxy’, pw_passwd=’x’, pw_uid=13, pw_gid=13, pw_gecos=’proxy’, pw_dir=’/bin’, pw_shell=’/usr/sbin/nologin’)pwd.struct_passwd(pw_name=’www-data’, pw_passwd=’x’, pw_uid=33, pw_gid=33, pw_gecos=’www-data’, pw_dir=’/var/www’, pw_shell=’/usr/sbin/nologin’)pwd.struct_passwd(pw_name=’backup’, pw_passwd=’x’, pw_uid=34, pw_gid=34, pw_gecos=’backup’, pw_dir=’/var/backups’, pw_shell=’/usr/sbin/nologin’)pwd.struct_passwd(pw_name=’list’, pw_passwd=’x’, pw_uid=38, pw_gid=38, pw_gecos=’Mailing List Manager’, pw_dir=’/var/list’, pw_shell=’/usr/sbin/nologin’)pwd.struct_passwd(pw_name=’irc’, pw_passwd=’x’, pw_uid=39, pw_gid=39, pw_gecos=’ircd’, pw_dir=’/var/run/ircd’, pw_shell=’/usr/sbin/nologin’)pwd.struct_passwd(pw_name=’gnats’, pw_passwd=’x’, pw_uid=41, pw_gid=41, pw_gecos=’Gnats Bug-Reporting System (admin)’, pw_dir=’/var/lib/gnats’, pw_shell=’/usr/sbin/nologin’)pwd.struct_passwd(pw_name=’nobody’, pw_passwd=’x’, pw_uid=65534, pw_gid=65534, pw_gecos=’nobody’, pw_dir=’/nonexistent’, pw_shell=’/usr/sbin/nologin’)pwd.struct_passwd(pw_name=’systemd-timesync’, pw_passwd=’x’, pw_uid=100, pw_gid=102, pw_gecos=’systemd Time Synchronization,,, ‘, pw_dir=’/run/systemd’, pw_shell=’/bin/false’)pwd.struct_passwd(pw_name=’systemd-network’, pw_passwd=’x’, pw_uid=101, pw_gid=103, pw_gecos=’systemd Network Management,,, ‘, pw_dir=’/run/systemd/netif’, pw_shell=’/bin/false’)pwd.struct_passwd(pw_name=’systemd-resolve’, pw_passwd=’x’, pw_uid=102, pw_gid=104, pw_gecos=’systemd Resolver,,, ‘, pw_dir=’/run/systemd/resolve’, pw_shell=’/bin/false’)pwd.struct_passwd(pw_name=’systemd-bus-proxy’, pw_passwd=’x’, pw_uid=103, pw_gid=105, pw_gecos=’systemd Bus Proxy,,, ‘, pw_dir=’/run/systemd’, pw_shell=’/bin/false’)pwd.struct_passwd(pw_name=’syslog’, pw_passwd=’x’, pw_uid=104, pw_gid=108, pw_gecos=”, pw_dir=’/home/syslog’, pw_shell=’/bin/false’)pwd.struct_passwd(pw_name=’messagebus’, pw_passwd=’x’, pw_uid=105, pw_gid=109, pw_gecos=”, pw_dir=’/var/run/dbus’, pw_shell=’/bin/false’)pwd.struct_passwd(pw_name=’_apt’, pw_passwd=’x’, pw_uid=106, pw_gid=65534, pw_gecos=”, pw_dir=’/nonexistent’, pw_shell=’/bin/false’)pwd.struct_passwd(pw_name=’uuidd’, pw_passwd=’x’, pw_uid=107, pw_gid=113, pw_gecos=”, pw_dir=’/run/uuidd’, pw_shell=’/bin/false’)pwd.struct_passwd(pw_name=’rtkit’, pw_passwd=’x’, pw_uid=108, pw_gid=114, pw_gecos=’RealtimeKit,,, ‘, pw_dir=’/proc’, pw_shell=’/bin/false’)pwd.struct_passwd(pw_name=’avahi-autoipd’, pw_passwd=’x’, pw_uid=109, pw_gid=115, pw_gecos=’Avahi autoip daemon,,, ‘, pw_dir=’/var/lib/avahi-autoipd’, pw_shell=’/bin/false’)pwd.struct_passwd(pw_name=’usbmux’, pw_passwd=’x’, pw_uid=110, pw_gid=46, pw_gecos=’usbmux daemon,,, ‘, pw_dir=’/var/lib/usbmux’, pw_shell=’/bin/false’)pwd.struct_passwd(pw_name=’dnsmasq’, pw_passwd=’x’, pw_uid=111, pw_gid=65534, pw_gecos=’dnsmasq,,, ‘, pw_dir=’/var/lib/misc’, pw_shell=’/bin/false’)pwd.struct_passwd(pw_name=’whoopsie’, pw_passwd=’x’, pw_uid=112, pw_gid=119, pw_gecos=”, pw_dir=’/nonexistent’, pw_shell=’/bin/false’)pwd.struct_passwd(pw_name=’kernoops’, pw_passwd=’x’, pw_uid=113, pw_gid=65534, pw_gecos=’Kernel Oops Tracking Daemon,,, ‘, pw_dir=’/’, pw_shell=’/bin/false’)pwd.struct_passwd(pw_name=’speech-dispatcher’, pw_passwd=’x’, pw_uid=114, pw_gid=29, pw_gecos=’Speech Dispatcher,,, ‘, pw_dir=’/var/run/speech-dispatcher’, pw_shell=’/bin/false’)pwd.struct_passwd(pw_name=’avahi’, pw_passwd=’x’, pw_uid=115, pw_gid=120, pw_gecos=’Avahi mDNS daemon,,, ‘, pw_dir=’/var/run/avahi-daemon’, pw_shell=’/bin/false’)pwd.struct_passwd(pw_name=’saned’, pw_passwd=’x’, pw_uid=116, pw_gid=122, pw_gecos=”, pw_dir=’/var/lib/saned’, pw_shell=’/bin/false’)pwd.struct_passwd(pw_name=’pulse’, pw_passwd=’x’, pw_uid=117, pw_gid=123, pw_gecos=’PulseAudio daemon,,, ‘, pw_dir=’/var/run/pulse’, pw_shell=’/bin/false’)pwd.struct_passwd(pw_name=’colord’, pw_passwd=’x’, pw_uid=118, pw_gid=125, pw_gecos=’colord colour management daemon,,, ‘, pw_dir=’/var/lib/colord’, pw_shell=’/bin/false’)pwd.struct_passwd(pw_name=’hplip’, pw_passwd=’x’, pw_uid=119, pw_gid=7, pw_gecos=’HPLIP system user,,, ‘, pw_dir=’/var/run/hplip’, pw_shell=’/bin/false’)pwd.struct_passwd(pw_name=’geoclue’, pw_passwd=’x’, pw_uid=120, pw_gid=126, pw_gecos=”, pw_dir=’/var/lib/geoclue’, pw_shell=’/bin/false’)pwd.struct_passwd(pw_name=’gdm’, pw_passwd=’x’, pw_uid=121, pw_gid=127, pw_gecos=’Gnome Display Manager’, pw_dir=’/var/lib/gdm3′, pw_shell=’/bin/false’)pwd.struct_passwd(pw_name=’ihritik’, pw_passwd=’x’, pw_uid=1000, pw_gid=1000, pw_gecos=’Hritik,,, ‘, pw_dir=’/home/ihritik’, pw_shell=’/bin/bash’)pwd.struct_passwd(pw_name=’sshd’, pw_passwd=’x’, pw_uid=122, pw_gid=65534, pw_gecos=”, pw_dir=’/run/sshd’, pw_shell=’/usr/sbin/nologin’)pwd.struct_passwd(pw_name=’master’, pw_passwd=’x’, pw_uid=1001, pw_gid=1002, pw_gecos=’,,, ‘, pw_dir=’/home/master’, pw_shell=’/bin/bash’)"
},
{
"code": null,
"e": 10335,
"s": 10320,
"text": "python-modules"
},
{
"code": null,
"e": 10350,
"s": 10335,
"text": "python-utility"
},
{
"code": null,
"e": 10357,
"s": 10350,
"text": "Python"
},
{
"code": null,
"e": 10455,
"s": 10357,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 10473,
"s": 10455,
"text": "Python Dictionary"
},
{
"code": null,
"e": 10515,
"s": 10473,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 10537,
"s": 10515,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 10572,
"s": 10537,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 10598,
"s": 10572,
"text": "Python String | replace()"
},
{
"code": null,
"e": 10630,
"s": 10598,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 10659,
"s": 10630,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 10686,
"s": 10659,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 10716,
"s": 10686,
"text": "Iterate over a list in Python"
}
] |
Django Templates
|
27 Sep, 2021
Templates are the third and most important part of Django’s MVT Structure. A template in Django is basically written in HTML, CSS, and Javascript in a .html file. Django framework efficiently handles and generates dynamically HTML web pages that are visible to the end-user. Django mainly functions with a backend so, in order to provide a frontend and provide a layout to our website, we use templates. There are two methods of adding the template to our website depending on our needs.We can use a single template directory which will be spread over the entire project. For each app of our project, we can create a different template directory.
For our current project, we will create a single template directory that will be spread over the entire project for simplicity. App-level templates are generally used in big projects or in case we want to provide a different layout to each component of our webpage.
Django Templates can be configured in app_name/settings.py,
Python3
TEMPLATES = [ { # Template backend to be used, For example Jinja 'BACKEND': 'django.template.backends.django.DjangoTemplates', # Directories for templates 'DIRS': [], 'APP_DIRS': True, # options to configure 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, },]
Illustration of How to use templates in Django using an Example Project. Templates not only show static data but also the data from different databases connected to the application through a context dictionary. Consider a project named geeksforgeeks having an app named geeks.
Refer to the following articles to check how to create a project and an app in Django.
How to Create a Basic Project using MVT in Django?
How to Create an App in Django ?
To render a template one needs a view and a URL mapped to that view. Let’s begin by creating a view in geeks/views.py,
Python3
# import Http Response from djangofrom django.shortcuts import render # create a functiondef geeks_view(request): # create a dictionary to pass # data to the template context ={ "data":"Gfg is the best", "list":[1, 2, 3, 4, 5, 6, 7, 8, 9, 10] } # return response with template and context return render(request, "geeks.html", context)
Now we need to map a URL to render this view,
Python3
from django.urls import path # importing views from views..pyfrom .views import geeks_view urlpatterns = [ path('', geeks_view),]
Finally create a template in templates/geeks.html,
HTML
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Homepage</title></head><body> <h1>Welcome to Geeksforgeeks.</h1> <p> Data is {{ data }}</p> <h4>List is </h4> <ul> {% for i in list %} <li>{{ i }}</li> {% endfor %}</body></html>
Let’s check if it is working,
This is one of the most important facilities provided by Django Templates. A Django template is a text document or a Python string marked-up using the Django template language. Some constructs are recognized and interpreted by the template engine. The main ones are variables and tags. As we used for the loop in the above example, we used it as a tag. similarly, we can use various other conditions such as if, else, if-else, empty, etc. The main characteristics of Django Template language are Variables, Tags, Filters, and Comments.
Variables output a value from the context, which is a dict-like object mapping keys to values. The context object we sent from the view can be accessed in the template using variables of Django Template.
Syntax
{{ variable_name }}
ExampleVariables are surrounded by {{ and }} like this:
My first name is {{ first_name }}. My last name is {{ last_name }}.
With a context of {‘first_name’: ‘Naveen’, ‘last_name’: ‘Arora’}, this template renders to:
My first name is Naveen. My last name is Arora.
To know more about Django Template Variables visit – variables – Django Templates
Tags provide arbitrary logic in the rendering process. For example, a tag can output content, serve as a control structure e.g. an “if” statement or a “for” loop, grab content from a database, or even enable access to other template tags.
Syntax
{% tag_name %}
Example
Tags are surrounded by {% and %} like this:
{% csrf_token %}
Most tags accept arguments, for example :
{% cycle 'odd' 'even' %}
Django Template Engine provides filters that are used to transform the values of variables and tag arguments. We have already discussed major Django Template Tags. Tags can’t modify the value of a variable whereas filters can be used for incrementing the value of a variable or modifying it to one’s own need.
Syntax
{{ variable_name | filter_name }}
Filters can be “chained.” The output of one filter is applied to the next. {{ text|escape|linebreaks }} is a common idiom for escaping text contents, then converting line breaks to <p> tags.
Example
{{ value | length }}
If value is [‘a’, ‘b’, ‘c’, ‘d’], the output will be 4.
Template ignores everything between {% comment %} and {% end comment %}. An optional note may be inserted in the first tag. For example, this is useful when commenting out code for documenting why the code was disabled.
Syntax
{% comment 'comment_name' %}
{% endcomment %}
Example :
{% comment "Optional note" %}
Commented out text with {{ create_date|date:"c" }}
{% endcomment %}
To know more about using comments in Templates, visit comment – Django template tags
The most powerful and thus the most complex part of Django’s template engine is template inheritance. Template inheritance allows you to build a base “skeleton” template that contains all the common elements of your site and defines blocks that child templates can override. extends tag is used for the inheritance of templates in Django. One needs to repeat the same code again and again. Using extends we can inherit templates as well as variables.
Syntax
{% extends 'template_name.html' %}
Example :assume the following directory structure:
dir1/
template.html
base2.html
my/
base3.html
base1.html
In template.html, the following paths would be valid:
HTML
{% extends "./base2.html" %}{% extends "../base1.html" %}{% extends "./my/base3.html" %}
To know more about Template inheritance and extends, visit extends – Django Template Tags
kk9826225
kumaripunam984122
sweetyty
Django-templates
Python Django
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Read JSON file using Python
Python map() function
Adding new column to existing DataFrame in Pandas
How to get column names in Pandas dataframe
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 ?
Iterate over a list in Python
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n27 Sep, 2021"
},
{
"code": null,
"e": 699,
"s": 52,
"text": "Templates are the third and most important part of Django’s MVT Structure. A template in Django is basically written in HTML, CSS, and Javascript in a .html file. Django framework efficiently handles and generates dynamically HTML web pages that are visible to the end-user. Django mainly functions with a backend so, in order to provide a frontend and provide a layout to our website, we use templates. There are two methods of adding the template to our website depending on our needs.We can use a single template directory which will be spread over the entire project. For each app of our project, we can create a different template directory."
},
{
"code": null,
"e": 965,
"s": 699,
"text": "For our current project, we will create a single template directory that will be spread over the entire project for simplicity. App-level templates are generally used in big projects or in case we want to provide a different layout to each component of our webpage."
},
{
"code": null,
"e": 1027,
"s": 965,
"text": "Django Templates can be configured in app_name/settings.py, "
},
{
"code": null,
"e": 1035,
"s": 1027,
"text": "Python3"
},
{
"code": "TEMPLATES = [ { # Template backend to be used, For example Jinja 'BACKEND': 'django.template.backends.django.DjangoTemplates', # Directories for templates 'DIRS': [], 'APP_DIRS': True, # options to configure 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, },]",
"e": 1627,
"s": 1035,
"text": null
},
{
"code": null,
"e": 1905,
"s": 1627,
"text": "Illustration of How to use templates in Django using an Example Project. Templates not only show static data but also the data from different databases connected to the application through a context dictionary. Consider a project named geeksforgeeks having an app named geeks. "
},
{
"code": null,
"e": 1993,
"s": 1905,
"text": "Refer to the following articles to check how to create a project and an app in Django. "
},
{
"code": null,
"e": 2044,
"s": 1993,
"text": "How to Create a Basic Project using MVT in Django?"
},
{
"code": null,
"e": 2077,
"s": 2044,
"text": "How to Create an App in Django ?"
},
{
"code": null,
"e": 2198,
"s": 2077,
"text": "To render a template one needs a view and a URL mapped to that view. Let’s begin by creating a view in geeks/views.py, "
},
{
"code": null,
"e": 2206,
"s": 2198,
"text": "Python3"
},
{
"code": "# import Http Response from djangofrom django.shortcuts import render # create a functiondef geeks_view(request): # create a dictionary to pass # data to the template context ={ \"data\":\"Gfg is the best\", \"list\":[1, 2, 3, 4, 5, 6, 7, 8, 9, 10] } # return response with template and context return render(request, \"geeks.html\", context)",
"e": 2574,
"s": 2206,
"text": null
},
{
"code": null,
"e": 2621,
"s": 2574,
"text": "Now we need to map a URL to render this view, "
},
{
"code": null,
"e": 2629,
"s": 2621,
"text": "Python3"
},
{
"code": "from django.urls import path # importing views from views..pyfrom .views import geeks_view urlpatterns = [ path('', geeks_view),]",
"e": 2762,
"s": 2629,
"text": null
},
{
"code": null,
"e": 2814,
"s": 2762,
"text": "Finally create a template in templates/geeks.html, "
},
{
"code": null,
"e": 2819,
"s": 2814,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"><head> <meta charset=\"UTF-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"> <meta http-equiv=\"X-UA-Compatible\" content=\"ie=edge\"> <title>Homepage</title></head><body> <h1>Welcome to Geeksforgeeks.</h1> <p> Data is {{ data }}</p> <h4>List is </h4> <ul> {% for i in list %} <li>{{ i }}</li> {% endfor %}</body></html>",
"e": 3232,
"s": 2819,
"text": null
},
{
"code": null,
"e": 3263,
"s": 3232,
"text": "Let’s check if it is working, "
},
{
"code": null,
"e": 3800,
"s": 3263,
"text": "This is one of the most important facilities provided by Django Templates. A Django template is a text document or a Python string marked-up using the Django template language. Some constructs are recognized and interpreted by the template engine. The main ones are variables and tags. As we used for the loop in the above example, we used it as a tag. similarly, we can use various other conditions such as if, else, if-else, empty, etc. The main characteristics of Django Template language are Variables, Tags, Filters, and Comments. "
},
{
"code": null,
"e": 4005,
"s": 3800,
"text": "Variables output a value from the context, which is a dict-like object mapping keys to values. The context object we sent from the view can be accessed in the template using variables of Django Template. "
},
{
"code": null,
"e": 4012,
"s": 4005,
"text": "Syntax"
},
{
"code": null,
"e": 4032,
"s": 4012,
"text": "{{ variable_name }}"
},
{
"code": null,
"e": 4090,
"s": 4032,
"text": "ExampleVariables are surrounded by {{ and }} like this: "
},
{
"code": null,
"e": 4159,
"s": 4090,
"text": "My first name is {{ first_name }}. My last name is {{ last_name }}. "
},
{
"code": null,
"e": 4252,
"s": 4159,
"text": "With a context of {‘first_name’: ‘Naveen’, ‘last_name’: ‘Arora’}, this template renders to: "
},
{
"code": null,
"e": 4300,
"s": 4252,
"text": "My first name is Naveen. My last name is Arora."
},
{
"code": null,
"e": 4383,
"s": 4300,
"text": "To know more about Django Template Variables visit – variables – Django Templates "
},
{
"code": null,
"e": 4622,
"s": 4383,
"text": "Tags provide arbitrary logic in the rendering process. For example, a tag can output content, serve as a control structure e.g. an “if” statement or a “for” loop, grab content from a database, or even enable access to other template tags."
},
{
"code": null,
"e": 4629,
"s": 4622,
"text": "Syntax"
},
{
"code": null,
"e": 4644,
"s": 4629,
"text": "{% tag_name %}"
},
{
"code": null,
"e": 4652,
"s": 4644,
"text": "Example"
},
{
"code": null,
"e": 4696,
"s": 4652,
"text": "Tags are surrounded by {% and %} like this:"
},
{
"code": null,
"e": 4713,
"s": 4696,
"text": "{% csrf_token %}"
},
{
"code": null,
"e": 4756,
"s": 4713,
"text": "Most tags accept arguments, for example : "
},
{
"code": null,
"e": 4783,
"s": 4756,
"text": "{% cycle 'odd' 'even' %}\n "
},
{
"code": null,
"e": 5094,
"s": 4783,
"text": "Django Template Engine provides filters that are used to transform the values of variables and tag arguments. We have already discussed major Django Template Tags. Tags can’t modify the value of a variable whereas filters can be used for incrementing the value of a variable or modifying it to one’s own need. "
},
{
"code": null,
"e": 5101,
"s": 5094,
"text": "Syntax"
},
{
"code": null,
"e": 5135,
"s": 5101,
"text": "{{ variable_name | filter_name }}"
},
{
"code": null,
"e": 5327,
"s": 5135,
"text": "Filters can be “chained.” The output of one filter is applied to the next. {{ text|escape|linebreaks }} is a common idiom for escaping text contents, then converting line breaks to <p> tags. "
},
{
"code": null,
"e": 5335,
"s": 5327,
"text": "Example"
},
{
"code": null,
"e": 5356,
"s": 5335,
"text": "{{ value | length }}"
},
{
"code": null,
"e": 5413,
"s": 5356,
"text": "If value is [‘a’, ‘b’, ‘c’, ‘d’], the output will be 4. "
},
{
"code": null,
"e": 5634,
"s": 5413,
"text": "Template ignores everything between {% comment %} and {% end comment %}. An optional note may be inserted in the first tag. For example, this is useful when commenting out code for documenting why the code was disabled. "
},
{
"code": null,
"e": 5641,
"s": 5634,
"text": "Syntax"
},
{
"code": null,
"e": 5687,
"s": 5641,
"text": "{% comment 'comment_name' %}\n{% endcomment %}"
},
{
"code": null,
"e": 5697,
"s": 5687,
"text": "Example :"
},
{
"code": null,
"e": 5799,
"s": 5697,
"text": "{% comment \"Optional note\" %}\n Commented out text with {{ create_date|date:\"c\" }}\n{% endcomment %}"
},
{
"code": null,
"e": 5885,
"s": 5799,
"text": "To know more about using comments in Templates, visit comment – Django template tags "
},
{
"code": null,
"e": 6336,
"s": 5885,
"text": "The most powerful and thus the most complex part of Django’s template engine is template inheritance. Template inheritance allows you to build a base “skeleton” template that contains all the common elements of your site and defines blocks that child templates can override. extends tag is used for the inheritance of templates in Django. One needs to repeat the same code again and again. Using extends we can inherit templates as well as variables."
},
{
"code": null,
"e": 6343,
"s": 6336,
"text": "Syntax"
},
{
"code": null,
"e": 6379,
"s": 6343,
"text": "{% extends 'template_name.html' %} "
},
{
"code": null,
"e": 6430,
"s": 6379,
"text": "Example :assume the following directory structure:"
},
{
"code": null,
"e": 6507,
"s": 6430,
"text": "dir1/\n template.html\n base2.html\n my/\n base3.html\nbase1.html"
},
{
"code": null,
"e": 6562,
"s": 6507,
"text": "In template.html, the following paths would be valid: "
},
{
"code": null,
"e": 6567,
"s": 6562,
"text": "HTML"
},
{
"code": "{% extends \"./base2.html\" %}{% extends \"../base1.html\" %}{% extends \"./my/base3.html\" %}",
"e": 6656,
"s": 6567,
"text": null
},
{
"code": null,
"e": 6748,
"s": 6656,
"text": "To know more about Template inheritance and extends, visit extends – Django Template Tags "
},
{
"code": null,
"e": 6758,
"s": 6748,
"text": "kk9826225"
},
{
"code": null,
"e": 6776,
"s": 6758,
"text": "kumaripunam984122"
},
{
"code": null,
"e": 6785,
"s": 6776,
"text": "sweetyty"
},
{
"code": null,
"e": 6802,
"s": 6785,
"text": "Django-templates"
},
{
"code": null,
"e": 6816,
"s": 6802,
"text": "Python Django"
},
{
"code": null,
"e": 6823,
"s": 6816,
"text": "Python"
},
{
"code": null,
"e": 6921,
"s": 6823,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 6949,
"s": 6921,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 6971,
"s": 6949,
"text": "Python map() function"
},
{
"code": null,
"e": 7021,
"s": 6971,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 7065,
"s": 7021,
"text": "How to get column names in Pandas dataframe"
},
{
"code": null,
"e": 7107,
"s": 7065,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 7129,
"s": 7107,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 7164,
"s": 7129,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 7190,
"s": 7164,
"text": "Python String | replace()"
},
{
"code": null,
"e": 7222,
"s": 7190,
"text": "How to Install PIP on Windows ?"
}
] |
Difference between DOM parentNode and parentElement in JavaScript
|
16 Oct, 2019
parentNode:The parent node property is read only property which returns us the name of the parent node of the selected node as a node object. The Node object represents a single node in the document tree and a node can be an element node, text node or more.Syntax:node.parentNodeReturn Value: The parent node property returns the parent node object if present or else it will return “null”.Example:<!DOCTYPE html><html> <body> <!--setting styles for our document--> <style> p { color: green; } </style> <p>GeeksForGeeks</p> <div> <p id="gfg">Click the button to get the node name of the parent node.</p> <!--here 'p' element is inside 'div' element meaning that 'div' is the parent of 'p' element here--> </div> <button onclick="myParentNode()">Try it</button> <p id="text"></p> <script> function myParentNode() { var geek = document.getElementById("gfg").parentNode.nodeName; /*appending parent node to the 'p' element with id named text*/ document.getElementById("text").innerHTML = geek; } </script> </body> </html>Output:
Syntax:
node.parentNode
Return Value: The parent node property returns the parent node object if present or else it will return “null”.
Example:
<!DOCTYPE html><html> <body> <!--setting styles for our document--> <style> p { color: green; } </style> <p>GeeksForGeeks</p> <div> <p id="gfg">Click the button to get the node name of the parent node.</p> <!--here 'p' element is inside 'div' element meaning that 'div' is the parent of 'p' element here--> </div> <button onclick="myParentNode()">Try it</button> <p id="text"></p> <script> function myParentNode() { var geek = document.getElementById("gfg").parentNode.nodeName; /*appending parent node to the 'p' element with id named text*/ document.getElementById("text").innerHTML = geek; } </script> </body> </html>
Output:
parentElement:The parent element is read only property which returns the parent element of the selected element.The element object represents an HTML element, like P, DIV, etc.Syntax:node.parentElementReturn Value: The parentElement property returns an element object representing parent element if present or else it will return null.Example:<!DOCTYPE html><html> <body> <!--setting styles for our document--> <style> p, ol { color: green; } </style> <p>GeeksForGeeks Courses</p> <ol> <li id="geek">DSA</li> <li>Interview Preparation</li> <li>Geeks Classes</li> </ol> <p>Click the button to get the node name of the parent element</p> <button onclick="myParentElement()"> Click to know the parent element </button> <!--here 'li' element is inside 'ol' element meaning that 'ol' is the parent of 'li' element here--> <p id="gfg"></p> <script> function myParentElement() { var text = document.getElementById( "geek").parentElement.nodeName; document.getElementById("gfg").innerHTML = text; } </script> </body> </html>Output:Difference:Parent Element returns null if the parent is not an element node, that is the main difference between parentElement and parentNode. In many cases one can use anyone of them, in most cases, they are the same. For instance:// returns the document node
document.documentElement.parentNode;
// returns null
document.documentElement.parentElement;
The HTML element (document.documentElement) doesn’t have a parent that is an element, it is a node, therefore, the parent element is null.Supported Browsers: The browsers supported by parentNode and DOM parentElement property are listed below:Google ChromeInternet ExplorerFirefoxApple SafariOperaMy Personal Notes
arrow_drop_upSave
Syntax:
node.parentElement
Return Value: The parentElement property returns an element object representing parent element if present or else it will return null.
Example:
<!DOCTYPE html><html> <body> <!--setting styles for our document--> <style> p, ol { color: green; } </style> <p>GeeksForGeeks Courses</p> <ol> <li id="geek">DSA</li> <li>Interview Preparation</li> <li>Geeks Classes</li> </ol> <p>Click the button to get the node name of the parent element</p> <button onclick="myParentElement()"> Click to know the parent element </button> <!--here 'li' element is inside 'ol' element meaning that 'ol' is the parent of 'li' element here--> <p id="gfg"></p> <script> function myParentElement() { var text = document.getElementById( "geek").parentElement.nodeName; document.getElementById("gfg").innerHTML = text; } </script> </body> </html>
Output:
Difference:Parent Element returns null if the parent is not an element node, that is the main difference between parentElement and parentNode. In many cases one can use anyone of them, in most cases, they are the same. For instance:
// returns the document node
document.documentElement.parentNode;
// returns null
document.documentElement.parentElement;
The HTML element (document.documentElement) doesn’t have a parent that is an element, it is a node, therefore, the parent element is null.
Supported Browsers: The browsers supported by parentNode and DOM parentElement property are listed below:
Google Chrome
Internet Explorer
Firefox
Apple Safari
Opera
JavaScript-Misc
Picked
JavaScript
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Remove elements from a JavaScript Array
Difference Between PUT and PATCH Request
Roadmap to Learn JavaScript For Beginners
JavaScript | Promises
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n16 Oct, 2019"
},
{
"code": null,
"e": 1217,
"s": 28,
"text": "parentNode:The parent node property is read only property which returns us the name of the parent node of the selected node as a node object. The Node object represents a single node in the document tree and a node can be an element node, text node or more.Syntax:node.parentNodeReturn Value: The parent node property returns the parent node object if present or else it will return “null”.Example:<!DOCTYPE html><html> <body> <!--setting styles for our document--> <style> p { color: green; } </style> <p>GeeksForGeeks</p> <div> <p id=\"gfg\">Click the button to get the node name of the parent node.</p> <!--here 'p' element is inside 'div' element meaning that 'div' is the parent of 'p' element here--> </div> <button onclick=\"myParentNode()\">Try it</button> <p id=\"text\"></p> <script> function myParentNode() { var geek = document.getElementById(\"gfg\").parentNode.nodeName; /*appending parent node to the 'p' element with id named text*/ document.getElementById(\"text\").innerHTML = geek; } </script> </body> </html>Output:"
},
{
"code": null,
"e": 1225,
"s": 1217,
"text": "Syntax:"
},
{
"code": null,
"e": 1241,
"s": 1225,
"text": "node.parentNode"
},
{
"code": null,
"e": 1353,
"s": 1241,
"text": "Return Value: The parent node property returns the parent node object if present or else it will return “null”."
},
{
"code": null,
"e": 1362,
"s": 1353,
"text": "Example:"
},
{
"code": "<!DOCTYPE html><html> <body> <!--setting styles for our document--> <style> p { color: green; } </style> <p>GeeksForGeeks</p> <div> <p id=\"gfg\">Click the button to get the node name of the parent node.</p> <!--here 'p' element is inside 'div' element meaning that 'div' is the parent of 'p' element here--> </div> <button onclick=\"myParentNode()\">Try it</button> <p id=\"text\"></p> <script> function myParentNode() { var geek = document.getElementById(\"gfg\").parentNode.nodeName; /*appending parent node to the 'p' element with id named text*/ document.getElementById(\"text\").innerHTML = geek; } </script> </body> </html>",
"e": 2146,
"s": 1362,
"text": null
},
{
"code": null,
"e": 2154,
"s": 2146,
"text": "Output:"
},
{
"code": null,
"e": 4037,
"s": 2154,
"text": "parentElement:The parent element is read only property which returns the parent element of the selected element.The element object represents an HTML element, like P, DIV, etc.Syntax:node.parentElementReturn Value: The parentElement property returns an element object representing parent element if present or else it will return null.Example:<!DOCTYPE html><html> <body> <!--setting styles for our document--> <style> p, ol { color: green; } </style> <p>GeeksForGeeks Courses</p> <ol> <li id=\"geek\">DSA</li> <li>Interview Preparation</li> <li>Geeks Classes</li> </ol> <p>Click the button to get the node name of the parent element</p> <button onclick=\"myParentElement()\"> Click to know the parent element </button> <!--here 'li' element is inside 'ol' element meaning that 'ol' is the parent of 'li' element here--> <p id=\"gfg\"></p> <script> function myParentElement() { var text = document.getElementById( \"geek\").parentElement.nodeName; document.getElementById(\"gfg\").innerHTML = text; } </script> </body> </html>Output:Difference:Parent Element returns null if the parent is not an element node, that is the main difference between parentElement and parentNode. In many cases one can use anyone of them, in most cases, they are the same. For instance:// returns the document node\ndocument.documentElement.parentNode; \n\n// returns null\ndocument.documentElement.parentElement; \nThe HTML element (document.documentElement) doesn’t have a parent that is an element, it is a node, therefore, the parent element is null.Supported Browsers: The browsers supported by parentNode and DOM parentElement property are listed below:Google ChromeInternet ExplorerFirefoxApple SafariOperaMy Personal Notes\narrow_drop_upSave"
},
{
"code": null,
"e": 4045,
"s": 4037,
"text": "Syntax:"
},
{
"code": null,
"e": 4064,
"s": 4045,
"text": "node.parentElement"
},
{
"code": null,
"e": 4199,
"s": 4064,
"text": "Return Value: The parentElement property returns an element object representing parent element if present or else it will return null."
},
{
"code": null,
"e": 4208,
"s": 4199,
"text": "Example:"
},
{
"code": "<!DOCTYPE html><html> <body> <!--setting styles for our document--> <style> p, ol { color: green; } </style> <p>GeeksForGeeks Courses</p> <ol> <li id=\"geek\">DSA</li> <li>Interview Preparation</li> <li>Geeks Classes</li> </ol> <p>Click the button to get the node name of the parent element</p> <button onclick=\"myParentElement()\"> Click to know the parent element </button> <!--here 'li' element is inside 'ol' element meaning that 'ol' is the parent of 'li' element here--> <p id=\"gfg\"></p> <script> function myParentElement() { var text = document.getElementById( \"geek\").parentElement.nodeName; document.getElementById(\"gfg\").innerHTML = text; } </script> </body> </html>",
"e": 5052,
"s": 4208,
"text": null
},
{
"code": null,
"e": 5060,
"s": 5052,
"text": "Output:"
},
{
"code": null,
"e": 5293,
"s": 5060,
"text": "Difference:Parent Element returns null if the parent is not an element node, that is the main difference between parentElement and parentNode. In many cases one can use anyone of them, in most cases, they are the same. For instance:"
},
{
"code": null,
"e": 5419,
"s": 5293,
"text": "// returns the document node\ndocument.documentElement.parentNode; \n\n// returns null\ndocument.documentElement.parentElement; \n"
},
{
"code": null,
"e": 5558,
"s": 5419,
"text": "The HTML element (document.documentElement) doesn’t have a parent that is an element, it is a node, therefore, the parent element is null."
},
{
"code": null,
"e": 5664,
"s": 5558,
"text": "Supported Browsers: The browsers supported by parentNode and DOM parentElement property are listed below:"
},
{
"code": null,
"e": 5678,
"s": 5664,
"text": "Google Chrome"
},
{
"code": null,
"e": 5696,
"s": 5678,
"text": "Internet Explorer"
},
{
"code": null,
"e": 5704,
"s": 5696,
"text": "Firefox"
},
{
"code": null,
"e": 5717,
"s": 5704,
"text": "Apple Safari"
},
{
"code": null,
"e": 5723,
"s": 5717,
"text": "Opera"
},
{
"code": null,
"e": 5739,
"s": 5723,
"text": "JavaScript-Misc"
},
{
"code": null,
"e": 5746,
"s": 5739,
"text": "Picked"
},
{
"code": null,
"e": 5757,
"s": 5746,
"text": "JavaScript"
},
{
"code": null,
"e": 5774,
"s": 5757,
"text": "Web Technologies"
},
{
"code": null,
"e": 5801,
"s": 5774,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 5899,
"s": 5801,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5960,
"s": 5899,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 6000,
"s": 5960,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 6041,
"s": 6000,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 6083,
"s": 6041,
"text": "Roadmap to Learn JavaScript For Beginners"
},
{
"code": null,
"e": 6105,
"s": 6083,
"text": "JavaScript | Promises"
},
{
"code": null,
"e": 6138,
"s": 6105,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 6200,
"s": 6138,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 6261,
"s": 6200,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 6311,
"s": 6261,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
JavaScript String with Quotes
|
31 Oct, 2021
Strings are the sequence of characters, symbols, and numbers. In JavaScript, the user can write strings either in ‘single quote‘ or in “double quote“. However, both print the same result on the terminal.
'GeeksforGeeks' === "GeeksforGeeks"
In some cases, users may need to print some part of the string with the quotes. For example, I’m, Hello “Geeks”, or It’s an apple, etc. In this situation, users have to use the single quote and double quote carefully. In this tutorial, the user will learn to write the string with quotation marks.
How simple string works in JavaScript?
As mentioned in the above section, the user gets the same output either it writes the string in a single quote or double quote. Users can see the example code below.
Example:
Javascript
<script>// String with double quotesvar string1 = "Hello Geeks!!!" // String with single quotesvar string2 = 'You are on GeeksforGeeks!' console.log(string1)console.log(string2)</script>
Output:
Hello Geeks!!!
You are on GeeksforGeeks!
How user can add the quotes inside the string?
There are several ways to write a string with a quotation mark.
Approach 1: One can use the backslash (\) inside the string to escape from the quotation mark. They will need to follow the below example to follow this method.
Syntax:
var string = "I\'m user of GeeksForGeeks."
Example:
Javascript
<script>var string1 = "I\'m user of GeeksForGeeks."var string2 = 'I\'m user of GeeksForGeeks.'var string3 = 'Hello \'Geeks\''var string4 = "Hello \'Geeks\'" console.log(string1)console.log(string2)console.log(string3)console.log(string4)</script>
Output:
I'm user of GeeksForGeeks.
I'm user of GeeksForGeeks.
Hello 'Geeks'
Hello 'Geeks'
Approach 2: One can write strings using alternative quotes. Users need to use single quotes inside the string if they have written string in double quotes and vice-versa.
Syntax:
var string1 = "Hello 'Geeks'"
var strign2 = 'Hello "Geeks"'
Example:
Javascript
<script>var string1 = "I'm user of GeeksForGeeks."var string2 = 'I"m user of GeeksForGeeks.'var string3 = 'Hello "Geeks"'var string4 = "Hello 'Geeks'" console.log(string1)console.log(string2)console.log(string3)console.log(string4)</script>
Output:
I'm user of GeeksForGeeks."
I"m user of GeeksForGeeks.'
Hello "Geeks"
Hello 'Geeks'
JavaScript-Questions
javascript-string
Picked
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Remove elements from a JavaScript Array
Roadmap to Learn JavaScript For Beginners
Difference Between PUT and PATCH Request
JavaScript | Promises
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n31 Oct, 2021"
},
{
"code": null,
"e": 258,
"s": 54,
"text": "Strings are the sequence of characters, symbols, and numbers. In JavaScript, the user can write strings either in ‘single quote‘ or in “double quote“. However, both print the same result on the terminal."
},
{
"code": null,
"e": 294,
"s": 258,
"text": "'GeeksforGeeks' === \"GeeksforGeeks\""
},
{
"code": null,
"e": 592,
"s": 294,
"text": "In some cases, users may need to print some part of the string with the quotes. For example, I’m, Hello “Geeks”, or It’s an apple, etc. In this situation, users have to use the single quote and double quote carefully. In this tutorial, the user will learn to write the string with quotation marks."
},
{
"code": null,
"e": 631,
"s": 592,
"text": "How simple string works in JavaScript?"
},
{
"code": null,
"e": 797,
"s": 631,
"text": "As mentioned in the above section, the user gets the same output either it writes the string in a single quote or double quote. Users can see the example code below."
},
{
"code": null,
"e": 806,
"s": 797,
"text": "Example:"
},
{
"code": null,
"e": 817,
"s": 806,
"text": "Javascript"
},
{
"code": "<script>// String with double quotesvar string1 = \"Hello Geeks!!!\" // String with single quotesvar string2 = 'You are on GeeksforGeeks!' console.log(string1)console.log(string2)</script>",
"e": 1006,
"s": 817,
"text": null
},
{
"code": null,
"e": 1014,
"s": 1006,
"text": "Output:"
},
{
"code": null,
"e": 1055,
"s": 1014,
"text": "Hello Geeks!!!\nYou are on GeeksforGeeks!"
},
{
"code": null,
"e": 1102,
"s": 1055,
"text": "How user can add the quotes inside the string?"
},
{
"code": null,
"e": 1167,
"s": 1102,
"text": "There are several ways to write a string with a quotation mark. "
},
{
"code": null,
"e": 1328,
"s": 1167,
"text": "Approach 1: One can use the backslash (\\) inside the string to escape from the quotation mark. They will need to follow the below example to follow this method."
},
{
"code": null,
"e": 1336,
"s": 1328,
"text": "Syntax:"
},
{
"code": null,
"e": 1379,
"s": 1336,
"text": "var string = \"I\\'m user of GeeksForGeeks.\""
},
{
"code": null,
"e": 1390,
"s": 1381,
"text": "Example:"
},
{
"code": null,
"e": 1401,
"s": 1390,
"text": "Javascript"
},
{
"code": "<script>var string1 = \"I\\'m user of GeeksForGeeks.\"var string2 = 'I\\'m user of GeeksForGeeks.'var string3 = 'Hello \\'Geeks\\''var string4 = \"Hello \\'Geeks\\'\" console.log(string1)console.log(string2)console.log(string3)console.log(string4)</script>",
"e": 1649,
"s": 1401,
"text": null
},
{
"code": null,
"e": 1657,
"s": 1649,
"text": "Output:"
},
{
"code": null,
"e": 1739,
"s": 1657,
"text": "I'm user of GeeksForGeeks.\nI'm user of GeeksForGeeks.\nHello 'Geeks'\nHello 'Geeks'"
},
{
"code": null,
"e": 1910,
"s": 1739,
"text": "Approach 2: One can write strings using alternative quotes. Users need to use single quotes inside the string if they have written string in double quotes and vice-versa."
},
{
"code": null,
"e": 1918,
"s": 1910,
"text": "Syntax:"
},
{
"code": null,
"e": 1978,
"s": 1918,
"text": "var string1 = \"Hello 'Geeks'\"\nvar strign2 = 'Hello \"Geeks\"'"
},
{
"code": null,
"e": 1987,
"s": 1978,
"text": "Example:"
},
{
"code": null,
"e": 1998,
"s": 1987,
"text": "Javascript"
},
{
"code": "<script>var string1 = \"I'm user of GeeksForGeeks.\"var string2 = 'I\"m user of GeeksForGeeks.'var string3 = 'Hello \"Geeks\"'var string4 = \"Hello 'Geeks'\" console.log(string1)console.log(string2)console.log(string3)console.log(string4)</script>",
"e": 2240,
"s": 1998,
"text": null
},
{
"code": null,
"e": 2248,
"s": 2240,
"text": "Output:"
},
{
"code": null,
"e": 2332,
"s": 2248,
"text": "I'm user of GeeksForGeeks.\"\nI\"m user of GeeksForGeeks.'\nHello \"Geeks\"\nHello 'Geeks'"
},
{
"code": null,
"e": 2353,
"s": 2332,
"text": "JavaScript-Questions"
},
{
"code": null,
"e": 2371,
"s": 2353,
"text": "javascript-string"
},
{
"code": null,
"e": 2378,
"s": 2371,
"text": "Picked"
},
{
"code": null,
"e": 2389,
"s": 2378,
"text": "JavaScript"
},
{
"code": null,
"e": 2406,
"s": 2389,
"text": "Web Technologies"
},
{
"code": null,
"e": 2504,
"s": 2406,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2565,
"s": 2504,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 2605,
"s": 2565,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 2647,
"s": 2605,
"text": "Roadmap to Learn JavaScript For Beginners"
},
{
"code": null,
"e": 2688,
"s": 2647,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 2710,
"s": 2688,
"text": "JavaScript | Promises"
},
{
"code": null,
"e": 2743,
"s": 2710,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 2805,
"s": 2743,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 2866,
"s": 2805,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 2916,
"s": 2866,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
Check whether an array can be made strictly decreasing by modifying at most one element
|
05 Nov, 2021
Given an array arr[] of positive integers, the task is to find whether it is possible to make this array strictly decreasing by modifying at most one element.Examples:
Input: arr[] = {12, 9, 10, 5, 2} Output: Yes {12, 11, 10, 5, 2} is one of the valid solutions.Input: arr[] = {1, 2, 3, 4} Output: No
Approach: For every element arr[i], if it is greater than both arr[i – 1] and arr[i + 1] or it is smaller than both arr[i – 1] and arr[i + 1] then arr[i] needs to be modified. i.e arr[i] = (arr[i – 1] + arr[i + 1]) / 2. If after modification, arr[i] = arr[i – 1] or arr[i + 1] then the array cannot be made strictly decreasing without affecting at most one element else count all such modifications, if the count of modifications in the end is less than or equal to 1 then print Yes else print No.Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function that returns true if the array// can be made strictly decreasing// with at most one changebool check(vector<int> arr, int n){ // To store the number of modifications // required to make the array // strictly decreasing int modify = 0; // Check whether the last element needs // to be modify or not if (arr[n - 1] >= arr[n - 2]) { arr[n - 1] = arr[n - 2] - 1; modify++; } // Check whether the first element needs // to be modify or not if (arr[0] <= arr[1]) { arr[0] = arr[1] + 1; modify++; } // Loop from 2nd element to the 2nd last element for (int i = n - 2; i > 0; i--) { // Check whether arr[i] needs to be modified if ((arr[i - 1] <= arr[i] && arr[i + 1] <= arr[i]) || (arr[i - 1] >= arr[i] && arr[i + 1] >= arr[i])) { // Modifying arr[i] arr[i] = (arr[i - 1] + arr[i + 1]) / 2; modify++; // Check if arr[i] is equal to any of // arr[i-1] or arr[i+1] if (arr[i] == arr[i - 1] || arr[i] == arr[i + 1]) return false; } } // If more than 1 modification is required if (modify > 1) return false; return true;} // Driver codeint main(){ vector<int> arr = { 10, 5, 11, 2 }; int n = arr.size(); if (check(arr, n)) cout << "Yes"; else cout << "No"; return 0;}
// Java implementation of the approachclass GFG { // Function that returns true if the array // can be made strictly decreasing // with at most one change public static boolean check(int[] arr, int n) { // To store the number of modifications // required to make the array // strictly decreasing int modify = 0; // Check whether the last element needs // to be modify or not if (arr[n - 1] >= arr[n - 2]) { arr[n - 1] = arr[n - 2] - 1; modify++; } // Check whether the first element needs // to be modify or not if (arr[0] <= arr[1]) { arr[0] = arr[1] + 1; modify++; } // Loop from 2nd element to the 2nd last element for (int i = n - 2; i > 0; i--) { // Check whether arr[i] needs to be modified if ((arr[i - 1] <= arr[i] && arr[i + 1] <= arr[i]) || (arr[i - 1] >= arr[i] && arr[i + 1] >= arr[i])) { // Modifying arr[i] arr[i] = (arr[i - 1] + arr[i + 1]) / 2; modify++; // Check if arr[i] is equal to any of // arr[i-1] or arr[i+1] if (arr[i] == arr[i - 1] || arr[i] == arr[i + 1]) return false; } } // If more than 1 modification is required if (modify > 1) return false; return true; } // Driver code public static void main(String[] args) { int[] arr = { 10, 5, 11, 3 }; int n = arr.length; if (check(arr, n)) System.out.print("Yes"); else System.out.print("No"); }}
# Python3 implementation of the approach # Function that returns true if the array# can be made strictly decreasing# with at most one changedef check(arr, n): modify = 0 # Check whether the last element needs # to be modify or not if (arr[n - 1] >= arr[n - 2]): arr[n-1] = arr[n-2] - 1 modify += 1 # Check whether the first element needs # to be modify or not if (arr[0] <= arr[1]): arr[0] = arr[1] + 1 modify += 1 # Loop from 2nd element to the 2nd last element for i in range(n-2, 0, -1): # Check whether arr[i] needs to be modified if (arr[i - 1] <= arr[i] and arr[i + 1] <= arr[i]) or \ (arr[i - 1] >= arr[i] and arr[i + 1] >= arr[i]): # Modifying arr[i] arr[i] = (arr[i - 1] + arr[i + 1]) // 2 modify += 1 # Check if arr[i] is equal to any of # arr[i-1] or arr[i + 1] if (arr[i] == arr[i - 1] or arr[i] == arr[i + 1]): return False # If more than 1 modification is required if (modify > 1): return False return True # Driver codeif __name__ == "__main__": arr = [10, 5, 11, 3] n = len(arr) if (check(arr, n)): print("Yes") else: print("No")
// C# implementation of the approachusing System; class GFG{ // Function that returns true if the array // can be made strictly decreasing // with at most one change public static bool check(int[]arr, int n) { // To store the number of modifications // required to make the array // strictly decreasing int modify = 0; // Check whether the last element needs // to be modify or not if (arr[n - 1] >= arr[n - 2]) { arr[n - 1] = arr[n - 2] - 1; modify++; } // Check whether the first element needs // to be modify or not if (arr[0] <= arr[1]) { arr[0] = arr[1] + 1; modify++; } // Loop from 2nd element to the 2nd last element for (int i = n - 2; i > 0; i--) { // Check whether arr[i] needs to be modified if ((arr[i - 1] <= arr[i] && arr[i + 1] <= arr[i]) || (arr[i - 1] >= arr[i] && arr[i + 1] >= arr[i])) { // Modifying arr[i] arr[i] = (arr[i - 1] + arr[i + 1]) / 2; modify++; // Check if arr[i] is equal to any of // arr[i-1] or arr[i+1] if (arr[i] == arr[i - 1] || arr[i] == arr[i + 1]) return false; } } // If more than 1 modification is required if (modify > 1) return false; return true; } // Driver code static public void Main () { int[]arr = { 10, 5, 11, 3 }; int n = arr.Length; if (check(arr, n)) Console.Write("Yes"); else Console.Write("No"); }} // This code is contributed by ajit.
<script> // Javascript implementation of the approach // Function that returns true if the array // can be made strictly decreasing // with at most one change function check(arr, n) { // To store the number of modifications // required to make the array // strictly decreasing let modify = 0; // Check whether the last element needs // to be modify or not if (arr[n - 1] >= arr[n - 2]) { arr[n - 1] = arr[n - 2] - 1; modify++; } // Check whether the first element needs // to be modify or not if (arr[0] <= arr[1]) { arr[0] = arr[1] + 1; modify++; } // Loop from 2nd element to the 2nd last element for (let i = n - 2; i > 0; i--) { // Check whether arr[i] needs to be modified if ((arr[i - 1] <= arr[i] && arr[i + 1] <= arr[i]) || (arr[i - 1] >= arr[i] && arr[i + 1] >= arr[i])) { // Modifying arr[i] arr[i] = parseInt((arr[i - 1] + arr[i + 1]) / 2, 10); modify++; // Check if arr[i] is equal to any of // arr[i-1] or arr[i+1] if (arr[i] == arr[i - 1] || arr[i] == arr[i + 1]) return false; } } // If more than 1 modification is required if (modify > 1) return false; return true; } let arr = [ 10, 5, 11, 3 ]; let n = arr.length; if (check(arr, n)) document.write("Yes"); else document.write("No"); </script>
Yes
Time Complexity: O(N)Auxiliary Space: O(1)
jit_t
jinangs23
divyesh072019
pankajsharmagfg
ashutoshsinghgeeksforgeeks
Algorithms
Arrays
Sorting
Arrays
Sorting
Algorithms
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n05 Nov, 2021"
},
{
"code": null,
"e": 223,
"s": 54,
"text": "Given an array arr[] of positive integers, the task is to find whether it is possible to make this array strictly decreasing by modifying at most one element.Examples: "
},
{
"code": null,
"e": 357,
"s": 223,
"text": "Input: arr[] = {12, 9, 10, 5, 2} Output: Yes {12, 11, 10, 5, 2} is one of the valid solutions.Input: arr[] = {1, 2, 3, 4} Output: No "
},
{
"code": null,
"e": 906,
"s": 357,
"text": "Approach: For every element arr[i], if it is greater than both arr[i – 1] and arr[i + 1] or it is smaller than both arr[i – 1] and arr[i + 1] then arr[i] needs to be modified. i.e arr[i] = (arr[i – 1] + arr[i + 1]) / 2. If after modification, arr[i] = arr[i – 1] or arr[i + 1] then the array cannot be made strictly decreasing without affecting at most one element else count all such modifications, if the count of modifications in the end is less than or equal to 1 then print Yes else print No.Below is the implementation of the above approach: "
},
{
"code": null,
"e": 910,
"s": 906,
"text": "C++"
},
{
"code": null,
"e": 915,
"s": 910,
"text": "Java"
},
{
"code": null,
"e": 923,
"s": 915,
"text": "Python3"
},
{
"code": null,
"e": 926,
"s": 923,
"text": "C#"
},
{
"code": null,
"e": 937,
"s": 926,
"text": "Javascript"
},
{
"code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function that returns true if the array// can be made strictly decreasing// with at most one changebool check(vector<int> arr, int n){ // To store the number of modifications // required to make the array // strictly decreasing int modify = 0; // Check whether the last element needs // to be modify or not if (arr[n - 1] >= arr[n - 2]) { arr[n - 1] = arr[n - 2] - 1; modify++; } // Check whether the first element needs // to be modify or not if (arr[0] <= arr[1]) { arr[0] = arr[1] + 1; modify++; } // Loop from 2nd element to the 2nd last element for (int i = n - 2; i > 0; i--) { // Check whether arr[i] needs to be modified if ((arr[i - 1] <= arr[i] && arr[i + 1] <= arr[i]) || (arr[i - 1] >= arr[i] && arr[i + 1] >= arr[i])) { // Modifying arr[i] arr[i] = (arr[i - 1] + arr[i + 1]) / 2; modify++; // Check if arr[i] is equal to any of // arr[i-1] or arr[i+1] if (arr[i] == arr[i - 1] || arr[i] == arr[i + 1]) return false; } } // If more than 1 modification is required if (modify > 1) return false; return true;} // Driver codeint main(){ vector<int> arr = { 10, 5, 11, 2 }; int n = arr.size(); if (check(arr, n)) cout << \"Yes\"; else cout << \"No\"; return 0;}",
"e": 2431,
"s": 937,
"text": null
},
{
"code": "// Java implementation of the approachclass GFG { // Function that returns true if the array // can be made strictly decreasing // with at most one change public static boolean check(int[] arr, int n) { // To store the number of modifications // required to make the array // strictly decreasing int modify = 0; // Check whether the last element needs // to be modify or not if (arr[n - 1] >= arr[n - 2]) { arr[n - 1] = arr[n - 2] - 1; modify++; } // Check whether the first element needs // to be modify or not if (arr[0] <= arr[1]) { arr[0] = arr[1] + 1; modify++; } // Loop from 2nd element to the 2nd last element for (int i = n - 2; i > 0; i--) { // Check whether arr[i] needs to be modified if ((arr[i - 1] <= arr[i] && arr[i + 1] <= arr[i]) || (arr[i - 1] >= arr[i] && arr[i + 1] >= arr[i])) { // Modifying arr[i] arr[i] = (arr[i - 1] + arr[i + 1]) / 2; modify++; // Check if arr[i] is equal to any of // arr[i-1] or arr[i+1] if (arr[i] == arr[i - 1] || arr[i] == arr[i + 1]) return false; } } // If more than 1 modification is required if (modify > 1) return false; return true; } // Driver code public static void main(String[] args) { int[] arr = { 10, 5, 11, 3 }; int n = arr.length; if (check(arr, n)) System.out.print(\"Yes\"); else System.out.print(\"No\"); }}",
"e": 4132,
"s": 2431,
"text": null
},
{
"code": "# Python3 implementation of the approach # Function that returns true if the array# can be made strictly decreasing# with at most one changedef check(arr, n): modify = 0 # Check whether the last element needs # to be modify or not if (arr[n - 1] >= arr[n - 2]): arr[n-1] = arr[n-2] - 1 modify += 1 # Check whether the first element needs # to be modify or not if (arr[0] <= arr[1]): arr[0] = arr[1] + 1 modify += 1 # Loop from 2nd element to the 2nd last element for i in range(n-2, 0, -1): # Check whether arr[i] needs to be modified if (arr[i - 1] <= arr[i] and arr[i + 1] <= arr[i]) or \\ (arr[i - 1] >= arr[i] and arr[i + 1] >= arr[i]): # Modifying arr[i] arr[i] = (arr[i - 1] + arr[i + 1]) // 2 modify += 1 # Check if arr[i] is equal to any of # arr[i-1] or arr[i + 1] if (arr[i] == arr[i - 1] or arr[i] == arr[i + 1]): return False # If more than 1 modification is required if (modify > 1): return False return True # Driver codeif __name__ == \"__main__\": arr = [10, 5, 11, 3] n = len(arr) if (check(arr, n)): print(\"Yes\") else: print(\"No\")",
"e": 5408,
"s": 4132,
"text": null
},
{
"code": "// C# implementation of the approachusing System; class GFG{ // Function that returns true if the array // can be made strictly decreasing // with at most one change public static bool check(int[]arr, int n) { // To store the number of modifications // required to make the array // strictly decreasing int modify = 0; // Check whether the last element needs // to be modify or not if (arr[n - 1] >= arr[n - 2]) { arr[n - 1] = arr[n - 2] - 1; modify++; } // Check whether the first element needs // to be modify or not if (arr[0] <= arr[1]) { arr[0] = arr[1] + 1; modify++; } // Loop from 2nd element to the 2nd last element for (int i = n - 2; i > 0; i--) { // Check whether arr[i] needs to be modified if ((arr[i - 1] <= arr[i] && arr[i + 1] <= arr[i]) || (arr[i - 1] >= arr[i] && arr[i + 1] >= arr[i])) { // Modifying arr[i] arr[i] = (arr[i - 1] + arr[i + 1]) / 2; modify++; // Check if arr[i] is equal to any of // arr[i-1] or arr[i+1] if (arr[i] == arr[i - 1] || arr[i] == arr[i + 1]) return false; } } // If more than 1 modification is required if (modify > 1) return false; return true; } // Driver code static public void Main () { int[]arr = { 10, 5, 11, 3 }; int n = arr.Length; if (check(arr, n)) Console.Write(\"Yes\"); else Console.Write(\"No\"); }} // This code is contributed by ajit.",
"e": 7170,
"s": 5408,
"text": null
},
{
"code": "<script> // Javascript implementation of the approach // Function that returns true if the array // can be made strictly decreasing // with at most one change function check(arr, n) { // To store the number of modifications // required to make the array // strictly decreasing let modify = 0; // Check whether the last element needs // to be modify or not if (arr[n - 1] >= arr[n - 2]) { arr[n - 1] = arr[n - 2] - 1; modify++; } // Check whether the first element needs // to be modify or not if (arr[0] <= arr[1]) { arr[0] = arr[1] + 1; modify++; } // Loop from 2nd element to the 2nd last element for (let i = n - 2; i > 0; i--) { // Check whether arr[i] needs to be modified if ((arr[i - 1] <= arr[i] && arr[i + 1] <= arr[i]) || (arr[i - 1] >= arr[i] && arr[i + 1] >= arr[i])) { // Modifying arr[i] arr[i] = parseInt((arr[i - 1] + arr[i + 1]) / 2, 10); modify++; // Check if arr[i] is equal to any of // arr[i-1] or arr[i+1] if (arr[i] == arr[i - 1] || arr[i] == arr[i + 1]) return false; } } // If more than 1 modification is required if (modify > 1) return false; return true; } let arr = [ 10, 5, 11, 3 ]; let n = arr.length; if (check(arr, n)) document.write(\"Yes\"); else document.write(\"No\"); </script>",
"e": 8823,
"s": 7170,
"text": null
},
{
"code": null,
"e": 8827,
"s": 8823,
"text": "Yes"
},
{
"code": null,
"e": 8872,
"s": 8829,
"text": "Time Complexity: O(N)Auxiliary Space: O(1)"
},
{
"code": null,
"e": 8878,
"s": 8872,
"text": "jit_t"
},
{
"code": null,
"e": 8888,
"s": 8878,
"text": "jinangs23"
},
{
"code": null,
"e": 8902,
"s": 8888,
"text": "divyesh072019"
},
{
"code": null,
"e": 8918,
"s": 8902,
"text": "pankajsharmagfg"
},
{
"code": null,
"e": 8945,
"s": 8918,
"text": "ashutoshsinghgeeksforgeeks"
},
{
"code": null,
"e": 8956,
"s": 8945,
"text": "Algorithms"
},
{
"code": null,
"e": 8963,
"s": 8956,
"text": "Arrays"
},
{
"code": null,
"e": 8971,
"s": 8963,
"text": "Sorting"
},
{
"code": null,
"e": 8978,
"s": 8971,
"text": "Arrays"
},
{
"code": null,
"e": 8986,
"s": 8978,
"text": "Sorting"
},
{
"code": null,
"e": 8997,
"s": 8986,
"text": "Algorithms"
}
] |
Middle of three using minimum comparisons
|
07 Jul, 2022
Given three distinct numbers a, b and c find the number with a value in middle.
Examples:
Input : a = 20, b = 30, c = 40
Output : 30
Input : a = 12, n = 32, c = 11
Output : 12
Simple Approach:
C++
Java
Python3
C#
PHP
Javascript
// CPP program to find middle of three distinct// numbers#include <bits/stdc++.h>using namespace std; int middleOfThree(int a, int b, int c){ // Checking for b if ((a < b && b < c) || (c < b && b < a)) return b; // Checking for a else if ((b < a && a < c) || (c < a && a < b)) return a; else return c;} // Driver Codeint main(){ int a = 20, b = 30, c = 40; cout << middleOfThree(a, b, c); return 0;}
// Java program to find middle of// three distinct numbersimport java.util.*; class Middle{ // Function to find the middle of three number public static int middleOfThree(int a, int b, int c) { // Checking for b if ((a < b && b < c) || (c < b && b < a)) return b; // Checking for a else if ((b < a && a < c) || (c < a && a < b)) return a; else return c; } // driver code public static void main(String[] args) { int a = 20, b = 30, c = 40; System.out.println( middleOfThree(a, b, c) ); }} // This code is contributed by rishabh_jain
# Python3 program to find middle# of three distinct numbers def middleOfThree(a, b, c): # Checking for b if ((a < b and b < c) or (c < b and b < a)) : return b; # Checking for a if ((b < a and a < c) or (c < a and a < b)) : return a; else : return c # Driver Codea = 20b = 30c = 40print(middleOfThree(a, b, c)) # This code is contributed by rishabh_jain
// C# program to find middle of// three distinct numbersusing System; class Middle{ // Function to find the middle of three number public static int middleOfThree(int a, int b, int c) { // Checking for b if ((a < b && b < c) || (c < b && b < a)) return b; // Checking for a else if ((b < a && a < c) || (c < a && a < b)) return a; else return c; } // Driver code public static void Main() { int a = 20, b = 30, c = 40; Console.WriteLine( middleOfThree(a, b, c) ); }} // This code is contributed by vt_m
<?php// PHP program to find middle// of three distinct numbers function middleOfThree($a, $b, $c){ // Checking for b if (($a < $b && $b < $c) or ($c < $b && $b < $a)) return $b; // Checking for a else if (($b < $a and $a < $c) or ($c < $a and $a < $b)) return $a; else return $c;} // Driver Code $a = 20; $b = 30; $c = 40; echo middleOfThree($a, $b, $c); // This code is contributed by anuj_67.?>
<script> // Javascript program to find middle of three distinct// numbers function middleOfThree( a, b, c){ // Checking for b if ((a < b && b < c) || (c < b && b < a)) return b; // Checking for a else if ((b < a && a < c) || (c < a && a < b)) return a; else return c;} // driver code let a = 20, b = 30, c = 40; document.write(middleOfThree(a, b, c)); </script>
30
Time Complexity: O(1)Auxiliary Space: O(1)
But approach used above is not efficient because of extra comparisons, which can be easily minimized. In case first part is false, it will execute remaining half to check the condition. This problem remains same if we are checking for a also.
Better Approach (Needs less comparison):
C++
Java
Python3
C#
PHP
Javascript
// CPP program to find middle of three distinct// numbers#include <bits/stdc++.h>using namespace std; // Function to find the middle of three numbersint middleOfThree(int a, int b, int c){ // Compare each three number to find middle // number. Enter only if a > b if (a > b) { if (b > c) return b; else if (a > c) return c; else return a; } else { // Decided a is not greater than b. if (a > c) return a; else if (b > c) return c; else return b; }} // Driver Codeint main(){ int a = 20, b = 30, c = 40; cout << middleOfThree(a, b, c); return 0;}
// Java program to find middle of// three distinct numbersimport java.util.*; class Middle{ // Function to find the middle of three number public static int middleOfThree(int a, int b, int c) { // Compare each three number to find // middle number. Enter only if a > b if (a > b) { if (b > c) return b; else if (a > c) return c; else return a; } else { // Decided a is not greater than b. if (a > c) return a; else if (b > c) return c; else return b; } } // driver code public static void main(String[] args) { int a = 20, b = 30, c = 40; System.out.println(middleOfThree(a, b, c)); }} // This code is contributed by rishabh_jain
# Python3 program to find middle# of three distinct numbers # Function to find the middle of three numbersdef middleOfThree(a, b, c) : # Compare each three number to find # middle number. Enter only if a > b if a > b : if (b > c): return b elif (a > c) : return c else : return a else: # Decided a is not greater than b. if (a > c) : return a elif (b > c) : return c else : return b # Driver Codea = 20b = 30c = 40print( middleOfThree(a, b, c) ) # This code is contributed by rishabh_jain
// C# program to find middle of// three distinct numbersusing System; class Middle{ // Function to find the middle of three number public static int middleOfThree(int a, int b, int c) { // Compare each three number to find // middle number. Enter only if a > b if (a > b) { if (b > c) return b; else if (a > c) return c; else return a; } else { // Decided a is not greater than b. if (a > c) return a; else if (b > c) return c; else return b; } } // Driver code public static void Main() { int a = 20, b = 30, c = 40; Console.WriteLine(middleOfThree(a, b, c)); }} // This code is contributed by vt_m
<?php// PHP program to find middle// of three distinct numbers // Function to find the middle// of three numbersfunction middleOfThree( $a, $b, $c){ // Compare each three number // to find middle number. // Enter only if a > b if ($a > $b) { if ($b > $c) return $b; else if ($a > $c) return $c; else return $a; } else { // Decided a is not // greater than b. if ($a > $c) return $a; else if ($b > $c) return $c; else return $b; }} // Driver Code $a = 20; $b = 30; $c = 40; echo middleOfThree($a, $b, $c); // This code is contributed by anuj_67.?>
<script> // Javascript program to find middle of three distinct numbers // Function to find the middle of three number function middleOfThree(a, b, c) { // Compare each three number to find // middle number. Enter only if a > b if (a > b) { if (b > c) return b; else if (a > c) return c; else return a; } else { // Decided a is not greater than b. if (a > c) return a; else if (b > c) return c; else return b; } } let a = 20, b = 30, c = 40; document.write(middleOfThree(a, b, c)); // This code is contributed by divyesh072019.</script>
30
Time Complexity: O(1)Auxiliary Space: O(1)This approach is efficient and having less number of comparisons. Outer IF loop will only be executed if a > b otherwise, outer ELSE will be executed.
Other Efficient Approach:
This approach is condensed version of the 1st approach.
(a>b and b>c) or (a<b and b<c) can also be decoded as a-b>0, b-c>0 or a-b<0,b-c<0 means the difference of a, b and b, c should be of same sign. So let x = a-b and y = b-c and if x, y have same sign then their result will be always positive. So b is middle element.
Similarly we can check for c and a.
let z = c – a and if (b < a and a < c) or (c < a and a < b) can be decoded as a-b>0 , c-a>0 or a-b < 0, c-a<0 means x*z > 0. So the middle element will be a.
C++
Java
Python3
C#
PHP
Javascript
// CPP program to find middle of three distinct// numbers#include <bits/stdc++.h>using namespace std; // Function to find the middle of three numberint middleOfThree(int a, int b, int c){ // x is positive if a is greater than b. // x is negative if b is greater than a. int x = a - b; int y = b - c; // Similar to x int z = a - c; // Similar to x and y. // Checking if b is middle (x and y both // are positive) if (x * y > 0) return b; // Checking if c is middle (x and z both // are positive) else if (x * z > 0) return c; else return a;} // Driver Codeint main(){ int a = 20, b = 30, c = 40; cout << middleOfThree(a, b, c); return 0;}
//java program to find middle of three distinct// numbersimport java.util.*; class Middle{ // Function to find the middle of three number public static int middleOfThree(int a, int b, int c) { // x is positive if a is greater than b. // x is negative if b is greater than a. int x = a - b; int y = b - c; // Similar to x int z = a - c; // Similar to x and y. // Checking if b is middle (x and y // both are positive) if (x * y > 0) return b; // Checking if c is middle (x and z // both are positive) else if (x * z > 0) return c; else return a; } // driver code public static void main(String[] args) { int a = 20, b = 30, c = 40; System.out.println( middleOfThree(a, b, c) ); }} // This code is contributed by rishabh_jain
# Python3 program to find middle# of three distinct numbers # Function to find the middle of three numberdef middleOfThree(a, b, c) : # x is positive if a is greater than b. # x is negative if b is greater than a. x = a - b # Similar to x y = b - c # Similar to x and y. z = a - c # Checking if b is middle (x and y # both are positive) if x * y > 0: return b # Checking if c is middle (x and z # both are positive) elif (x * z > 0) : return c else : return a # Driver Codea = 20b = 30c = 40print(middleOfThree(a, b, c)) # This code is contributed by rishabh_jain
//C# program to find middle of three distinct// numbersusing System; class Middle{ // Function to find the middle of three number public static int middleOfThree(int a, int b, int c) { // x is positive if a is greater than b. // x is negative if b is greater than a. int x = a - b; // Similar to x int y = b - c; // Similar to x and y. int z = a - c; // Checking if b is middle (x and y // both are positive) if (x * y > 0) return b; // Checking if c is middle (x and z // both are positive) else if (x * z > 0) return c; else return a; } // Driver code public static void Main() { int a = 20, b = 30, c = 40; Console.WriteLine( middleOfThree(a, b, c) ); }} // This code is contributed by vt_m
<?php// PHP program to find middle// of three distinct numbers // Function to find the// middle of three numberfunction middleOfThree($a, $b, $c){ // x is positive if a // is greater than b. // x is negative if b // is greater than a. $x = $a - $b; // Similar to x $y = $b - $c; // Similar to x and y. $z = $a - $c; // Checking if b is // middle (x and y both // are positive) if ($x * $y > 0) return $b; // Checking if c is // middle (x and z both // are positive) else if ($x * $z > 0) return $c; else return $a;} // Driver Code $a = 20; $b = 30; $c = 40; echo middleOfThree($a, $b, $c); // This code is contributed by anuj_67.?>
<script> // javascript program to find middle of// three distinct numbers // Function to find the middle of three number function middleOfThree(a, b, c) { // x is positive if a is greater than b. // x is negative if b is greater than a. let x = a - b; let y = b - c; // Similar to x let z = a - c; // Similar to x and y. // Checking if b is middle (x and y // both are positive) if (x * y > 0) return b; // Checking if c is middle (x and z // both are positive) else if (x * z > 0) return c; else return a; } // Driver code let a = 20, b = 30, c = 40; document.write( middleOfThree(a, b, c) ); </script>
30
Time Complexity: O(1)Auxiliary Space: O(1)
vt_m
jana_sayantan
susmitakundugoaldanga
divyesh072019
singhh3010
ashutoshkatkam
manojkumarmanusai
C++
Searching
Technical Scripter
Searching
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Sorting a vector in C++
Polymorphism in C++
Friend class and function in C++
std::string class in C++
Pair in C++ Standard Template Library (STL)
Binary Search
Maximum and minimum of an array using minimum number of comparisons
Linear Search
K'th Smallest/Largest Element in Unsorted Array | Set 1
Search an element in a sorted and rotated array
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n07 Jul, 2022"
},
{
"code": null,
"e": 132,
"s": 52,
"text": "Given three distinct numbers a, b and c find the number with a value in middle."
},
{
"code": null,
"e": 142,
"s": 132,
"text": "Examples:"
},
{
"code": null,
"e": 229,
"s": 142,
"text": "Input : a = 20, b = 30, c = 40\nOutput : 30\n\nInput : a = 12, n = 32, c = 11\nOutput : 12"
},
{
"code": null,
"e": 246,
"s": 229,
"text": "Simple Approach:"
},
{
"code": null,
"e": 250,
"s": 246,
"text": "C++"
},
{
"code": null,
"e": 255,
"s": 250,
"text": "Java"
},
{
"code": null,
"e": 263,
"s": 255,
"text": "Python3"
},
{
"code": null,
"e": 266,
"s": 263,
"text": "C#"
},
{
"code": null,
"e": 270,
"s": 266,
"text": "PHP"
},
{
"code": null,
"e": 281,
"s": 270,
"text": "Javascript"
},
{
"code": "// CPP program to find middle of three distinct// numbers#include <bits/stdc++.h>using namespace std; int middleOfThree(int a, int b, int c){ // Checking for b if ((a < b && b < c) || (c < b && b < a)) return b; // Checking for a else if ((b < a && a < c) || (c < a && a < b)) return a; else return c;} // Driver Codeint main(){ int a = 20, b = 30, c = 40; cout << middleOfThree(a, b, c); return 0;}",
"e": 726,
"s": 281,
"text": null
},
{
"code": "// Java program to find middle of// three distinct numbersimport java.util.*; class Middle{ // Function to find the middle of three number public static int middleOfThree(int a, int b, int c) { // Checking for b if ((a < b && b < c) || (c < b && b < a)) return b; // Checking for a else if ((b < a && a < c) || (c < a && a < b)) return a; else return c; } // driver code public static void main(String[] args) { int a = 20, b = 30, c = 40; System.out.println( middleOfThree(a, b, c) ); }} // This code is contributed by rishabh_jain",
"e": 1407,
"s": 726,
"text": null
},
{
"code": "# Python3 program to find middle# of three distinct numbers def middleOfThree(a, b, c): # Checking for b if ((a < b and b < c) or (c < b and b < a)) : return b; # Checking for a if ((b < a and a < c) or (c < a and a < b)) : return a; else : return c # Driver Codea = 20b = 30c = 40print(middleOfThree(a, b, c)) # This code is contributed by rishabh_jain",
"e": 1804,
"s": 1407,
"text": null
},
{
"code": "// C# program to find middle of// three distinct numbersusing System; class Middle{ // Function to find the middle of three number public static int middleOfThree(int a, int b, int c) { // Checking for b if ((a < b && b < c) || (c < b && b < a)) return b; // Checking for a else if ((b < a && a < c) || (c < a && a < b)) return a; else return c; } // Driver code public static void Main() { int a = 20, b = 30, c = 40; Console.WriteLine( middleOfThree(a, b, c) ); }} // This code is contributed by vt_m",
"e": 2451,
"s": 1804,
"text": null
},
{
"code": "<?php// PHP program to find middle// of three distinct numbers function middleOfThree($a, $b, $c){ // Checking for b if (($a < $b && $b < $c) or ($c < $b && $b < $a)) return $b; // Checking for a else if (($b < $a and $a < $c) or ($c < $a and $a < $b)) return $a; else return $c;} // Driver Code $a = 20; $b = 30; $c = 40; echo middleOfThree($a, $b, $c); // This code is contributed by anuj_67.?>",
"e": 2918,
"s": 2451,
"text": null
},
{
"code": "<script> // Javascript program to find middle of three distinct// numbers function middleOfThree( a, b, c){ // Checking for b if ((a < b && b < c) || (c < b && b < a)) return b; // Checking for a else if ((b < a && a < c) || (c < a && a < b)) return a; else return c;} // driver code let a = 20, b = 30, c = 40; document.write(middleOfThree(a, b, c)); </script>",
"e": 3332,
"s": 2918,
"text": null
},
{
"code": null,
"e": 3335,
"s": 3332,
"text": "30"
},
{
"code": null,
"e": 3378,
"s": 3335,
"text": "Time Complexity: O(1)Auxiliary Space: O(1)"
},
{
"code": null,
"e": 3622,
"s": 3378,
"text": "But approach used above is not efficient because of extra comparisons, which can be easily minimized. In case first part is false, it will execute remaining half to check the condition. This problem remains same if we are checking for a also. "
},
{
"code": null,
"e": 3663,
"s": 3622,
"text": "Better Approach (Needs less comparison):"
},
{
"code": null,
"e": 3667,
"s": 3663,
"text": "C++"
},
{
"code": null,
"e": 3672,
"s": 3667,
"text": "Java"
},
{
"code": null,
"e": 3680,
"s": 3672,
"text": "Python3"
},
{
"code": null,
"e": 3683,
"s": 3680,
"text": "C#"
},
{
"code": null,
"e": 3687,
"s": 3683,
"text": "PHP"
},
{
"code": null,
"e": 3698,
"s": 3687,
"text": "Javascript"
},
{
"code": "// CPP program to find middle of three distinct// numbers#include <bits/stdc++.h>using namespace std; // Function to find the middle of three numbersint middleOfThree(int a, int b, int c){ // Compare each three number to find middle // number. Enter only if a > b if (a > b) { if (b > c) return b; else if (a > c) return c; else return a; } else { // Decided a is not greater than b. if (a > c) return a; else if (b > c) return c; else return b; }} // Driver Codeint main(){ int a = 20, b = 30, c = 40; cout << middleOfThree(a, b, c); return 0;}",
"e": 4392,
"s": 3698,
"text": null
},
{
"code": "// Java program to find middle of// three distinct numbersimport java.util.*; class Middle{ // Function to find the middle of three number public static int middleOfThree(int a, int b, int c) { // Compare each three number to find // middle number. Enter only if a > b if (a > b) { if (b > c) return b; else if (a > c) return c; else return a; } else { // Decided a is not greater than b. if (a > c) return a; else if (b > c) return c; else return b; } } // driver code public static void main(String[] args) { int a = 20, b = 30, c = 40; System.out.println(middleOfThree(a, b, c)); }} // This code is contributed by rishabh_jain",
"e": 5331,
"s": 4392,
"text": null
},
{
"code": "# Python3 program to find middle# of three distinct numbers # Function to find the middle of three numbersdef middleOfThree(a, b, c) : # Compare each three number to find # middle number. Enter only if a > b if a > b : if (b > c): return b elif (a > c) : return c else : return a else: # Decided a is not greater than b. if (a > c) : return a elif (b > c) : return c else : return b # Driver Codea = 20b = 30c = 40print( middleOfThree(a, b, c) ) # This code is contributed by rishabh_jain",
"e": 5952,
"s": 5331,
"text": null
},
{
"code": "// C# program to find middle of// three distinct numbersusing System; class Middle{ // Function to find the middle of three number public static int middleOfThree(int a, int b, int c) { // Compare each three number to find // middle number. Enter only if a > b if (a > b) { if (b > c) return b; else if (a > c) return c; else return a; } else { // Decided a is not greater than b. if (a > c) return a; else if (b > c) return c; else return b; } } // Driver code public static void Main() { int a = 20, b = 30, c = 40; Console.WriteLine(middleOfThree(a, b, c)); }} // This code is contributed by vt_m",
"e": 6861,
"s": 5952,
"text": null
},
{
"code": "<?php// PHP program to find middle// of three distinct numbers // Function to find the middle// of three numbersfunction middleOfThree( $a, $b, $c){ // Compare each three number // to find middle number. // Enter only if a > b if ($a > $b) { if ($b > $c) return $b; else if ($a > $c) return $c; else return $a; } else { // Decided a is not // greater than b. if ($a > $c) return $a; else if ($b > $c) return $c; else return $b; }} // Driver Code $a = 20; $b = 30; $c = 40; echo middleOfThree($a, $b, $c); // This code is contributed by anuj_67.?>",
"e": 7584,
"s": 6861,
"text": null
},
{
"code": "<script> // Javascript program to find middle of three distinct numbers // Function to find the middle of three number function middleOfThree(a, b, c) { // Compare each three number to find // middle number. Enter only if a > b if (a > b) { if (b > c) return b; else if (a > c) return c; else return a; } else { // Decided a is not greater than b. if (a > c) return a; else if (b > c) return c; else return b; } } let a = 20, b = 30, c = 40; document.write(middleOfThree(a, b, c)); // This code is contributed by divyesh072019.</script>",
"e": 8383,
"s": 7584,
"text": null
},
{
"code": null,
"e": 8386,
"s": 8383,
"text": "30"
},
{
"code": null,
"e": 8580,
"s": 8386,
"text": "Time Complexity: O(1)Auxiliary Space: O(1)This approach is efficient and having less number of comparisons. Outer IF loop will only be executed if a > b otherwise, outer ELSE will be executed. "
},
{
"code": null,
"e": 8606,
"s": 8580,
"text": "Other Efficient Approach:"
},
{
"code": null,
"e": 8662,
"s": 8606,
"text": "This approach is condensed version of the 1st approach."
},
{
"code": null,
"e": 8927,
"s": 8662,
"text": "(a>b and b>c) or (a<b and b<c) can also be decoded as a-b>0, b-c>0 or a-b<0,b-c<0 means the difference of a, b and b, c should be of same sign. So let x = a-b and y = b-c and if x, y have same sign then their result will be always positive. So b is middle element."
},
{
"code": null,
"e": 8963,
"s": 8927,
"text": "Similarly we can check for c and a."
},
{
"code": null,
"e": 9122,
"s": 8963,
"text": "let z = c – a and if (b < a and a < c) or (c < a and a < b) can be decoded as a-b>0 , c-a>0 or a-b < 0, c-a<0 means x*z > 0. So the middle element will be a."
},
{
"code": null,
"e": 9126,
"s": 9122,
"text": "C++"
},
{
"code": null,
"e": 9131,
"s": 9126,
"text": "Java"
},
{
"code": null,
"e": 9139,
"s": 9131,
"text": "Python3"
},
{
"code": null,
"e": 9142,
"s": 9139,
"text": "C#"
},
{
"code": null,
"e": 9146,
"s": 9142,
"text": "PHP"
},
{
"code": null,
"e": 9157,
"s": 9146,
"text": "Javascript"
},
{
"code": "// CPP program to find middle of three distinct// numbers#include <bits/stdc++.h>using namespace std; // Function to find the middle of three numberint middleOfThree(int a, int b, int c){ // x is positive if a is greater than b. // x is negative if b is greater than a. int x = a - b; int y = b - c; // Similar to x int z = a - c; // Similar to x and y. // Checking if b is middle (x and y both // are positive) if (x * y > 0) return b; // Checking if c is middle (x and z both // are positive) else if (x * z > 0) return c; else return a;} // Driver Codeint main(){ int a = 20, b = 30, c = 40; cout << middleOfThree(a, b, c); return 0;}",
"e": 9866,
"s": 9157,
"text": null
},
{
"code": "//java program to find middle of three distinct// numbersimport java.util.*; class Middle{ // Function to find the middle of three number public static int middleOfThree(int a, int b, int c) { // x is positive if a is greater than b. // x is negative if b is greater than a. int x = a - b; int y = b - c; // Similar to x int z = a - c; // Similar to x and y. // Checking if b is middle (x and y // both are positive) if (x * y > 0) return b; // Checking if c is middle (x and z // both are positive) else if (x * z > 0) return c; else return a; } // driver code public static void main(String[] args) { int a = 20, b = 30, c = 40; System.out.println( middleOfThree(a, b, c) ); }} // This code is contributed by rishabh_jain",
"e": 10796,
"s": 9866,
"text": null
},
{
"code": "# Python3 program to find middle# of three distinct numbers # Function to find the middle of three numberdef middleOfThree(a, b, c) : # x is positive if a is greater than b. # x is negative if b is greater than a. x = a - b # Similar to x y = b - c # Similar to x and y. z = a - c # Checking if b is middle (x and y # both are positive) if x * y > 0: return b # Checking if c is middle (x and z # both are positive) elif (x * z > 0) : return c else : return a # Driver Codea = 20b = 30c = 40print(middleOfThree(a, b, c)) # This code is contributed by rishabh_jain",
"e": 11436,
"s": 10796,
"text": null
},
{
"code": "//C# program to find middle of three distinct// numbersusing System; class Middle{ // Function to find the middle of three number public static int middleOfThree(int a, int b, int c) { // x is positive if a is greater than b. // x is negative if b is greater than a. int x = a - b; // Similar to x int y = b - c; // Similar to x and y. int z = a - c; // Checking if b is middle (x and y // both are positive) if (x * y > 0) return b; // Checking if c is middle (x and z // both are positive) else if (x * z > 0) return c; else return a; } // Driver code public static void Main() { int a = 20, b = 30, c = 40; Console.WriteLine( middleOfThree(a, b, c) ); }} // This code is contributed by vt_m",
"e": 12364,
"s": 11436,
"text": null
},
{
"code": "<?php// PHP program to find middle// of three distinct numbers // Function to find the// middle of three numberfunction middleOfThree($a, $b, $c){ // x is positive if a // is greater than b. // x is negative if b // is greater than a. $x = $a - $b; // Similar to x $y = $b - $c; // Similar to x and y. $z = $a - $c; // Checking if b is // middle (x and y both // are positive) if ($x * $y > 0) return $b; // Checking if c is // middle (x and z both // are positive) else if ($x * $z > 0) return $c; else return $a;} // Driver Code $a = 20; $b = 30; $c = 40; echo middleOfThree($a, $b, $c); // This code is contributed by anuj_67.?>",
"e": 13100,
"s": 12364,
"text": null
},
{
"code": "<script> // javascript program to find middle of// three distinct numbers // Function to find the middle of three number function middleOfThree(a, b, c) { // x is positive if a is greater than b. // x is negative if b is greater than a. let x = a - b; let y = b - c; // Similar to x let z = a - c; // Similar to x and y. // Checking if b is middle (x and y // both are positive) if (x * y > 0) return b; // Checking if c is middle (x and z // both are positive) else if (x * z > 0) return c; else return a; } // Driver code let a = 20, b = 30, c = 40; document.write( middleOfThree(a, b, c) ); </script>",
"e": 13861,
"s": 13100,
"text": null
},
{
"code": null,
"e": 13864,
"s": 13861,
"text": "30"
},
{
"code": null,
"e": 13907,
"s": 13864,
"text": "Time Complexity: O(1)Auxiliary Space: O(1)"
},
{
"code": null,
"e": 13912,
"s": 13907,
"text": "vt_m"
},
{
"code": null,
"e": 13926,
"s": 13912,
"text": "jana_sayantan"
},
{
"code": null,
"e": 13948,
"s": 13926,
"text": "susmitakundugoaldanga"
},
{
"code": null,
"e": 13962,
"s": 13948,
"text": "divyesh072019"
},
{
"code": null,
"e": 13973,
"s": 13962,
"text": "singhh3010"
},
{
"code": null,
"e": 13988,
"s": 13973,
"text": "ashutoshkatkam"
},
{
"code": null,
"e": 14006,
"s": 13988,
"text": "manojkumarmanusai"
},
{
"code": null,
"e": 14010,
"s": 14006,
"text": "C++"
},
{
"code": null,
"e": 14020,
"s": 14010,
"text": "Searching"
},
{
"code": null,
"e": 14039,
"s": 14020,
"text": "Technical Scripter"
},
{
"code": null,
"e": 14049,
"s": 14039,
"text": "Searching"
},
{
"code": null,
"e": 14053,
"s": 14049,
"text": "CPP"
},
{
"code": null,
"e": 14151,
"s": 14053,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 14175,
"s": 14151,
"text": "Sorting a vector in C++"
},
{
"code": null,
"e": 14195,
"s": 14175,
"text": "Polymorphism in C++"
},
{
"code": null,
"e": 14228,
"s": 14195,
"text": "Friend class and function in C++"
},
{
"code": null,
"e": 14253,
"s": 14228,
"text": "std::string class in C++"
},
{
"code": null,
"e": 14297,
"s": 14253,
"text": "Pair in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 14311,
"s": 14297,
"text": "Binary Search"
},
{
"code": null,
"e": 14379,
"s": 14311,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 14393,
"s": 14379,
"text": "Linear Search"
},
{
"code": null,
"e": 14449,
"s": 14393,
"text": "K'th Smallest/Largest Element in Unsorted Array | Set 1"
}
] |
Select top in MS SQL Server
|
09 Jul, 2020
Prerequisite – Select in MS SQL ServerSuppose that a user wants to extract the top students from the whole institution but has to use some complex queries to extract the data. To avoid complexity, the user can use ‘Select Top’.‘Select Top’ extracts the limited number of rows. This results in accurate data along with less time consumption.
Syntax –
select top (expression) [percent] [with ties]
from table_name
order by column_name
Analyzing the Syntax –
Top is a keyword that extracts the data from the top of the list.
Expression is the data that is to be extracted from the table.
Percent is the number of rows that need to be extracted from the table.
With Ties returns the rows that share the same values with the last row. In some cases, more rows can be retrieved.
The order by clause is used for arranging the data in a chronological order. It is mandatory to use this clause in syntax otherwise, it results in an error.
Example –If a user wants to extract the top 5 students of an institution, the query is written as –
select top 5 name rollnumber gpa
from student
order by name ASC
Output –
This way the desired data can be extracted. The last row student has a gpa of 7.7 and if there are a few more students that share the same numbers, the query must be written as –
select top 8 with ties
name rollnumber gpa
from student
order by name ASC
Output –
ASC arranges the data from ascending to descending order. DESC can be used if the data has to be arranged from descending to ascending order.
DBMS-SQL
mysql
DBMS
SQL
DBMS
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n09 Jul, 2020"
},
{
"code": null,
"e": 369,
"s": 28,
"text": "Prerequisite – Select in MS SQL ServerSuppose that a user wants to extract the top students from the whole institution but has to use some complex queries to extract the data. To avoid complexity, the user can use ‘Select Top’.‘Select Top’ extracts the limited number of rows. This results in accurate data along with less time consumption."
},
{
"code": null,
"e": 378,
"s": 369,
"text": "Syntax –"
},
{
"code": null,
"e": 463,
"s": 378,
"text": "select top (expression) [percent] [with ties]\nfrom table_name \norder by column_name "
},
{
"code": null,
"e": 486,
"s": 463,
"text": "Analyzing the Syntax –"
},
{
"code": null,
"e": 552,
"s": 486,
"text": "Top is a keyword that extracts the data from the top of the list."
},
{
"code": null,
"e": 615,
"s": 552,
"text": "Expression is the data that is to be extracted from the table."
},
{
"code": null,
"e": 687,
"s": 615,
"text": "Percent is the number of rows that need to be extracted from the table."
},
{
"code": null,
"e": 803,
"s": 687,
"text": "With Ties returns the rows that share the same values with the last row. In some cases, more rows can be retrieved."
},
{
"code": null,
"e": 960,
"s": 803,
"text": "The order by clause is used for arranging the data in a chronological order. It is mandatory to use this clause in syntax otherwise, it results in an error."
},
{
"code": null,
"e": 1060,
"s": 960,
"text": "Example –If a user wants to extract the top 5 students of an institution, the query is written as –"
},
{
"code": null,
"e": 1126,
"s": 1060,
"text": "select top 5 name rollnumber gpa\nfrom student \norder by name ASC\n"
},
{
"code": null,
"e": 1135,
"s": 1126,
"text": "Output –"
},
{
"code": null,
"e": 1314,
"s": 1135,
"text": "This way the desired data can be extracted. The last row student has a gpa of 7.7 and if there are a few more students that share the same numbers, the query must be written as –"
},
{
"code": null,
"e": 1389,
"s": 1314,
"text": "select top 8 with ties\nname rollnumber gpa\nfrom student\norder by name ASC\n"
},
{
"code": null,
"e": 1398,
"s": 1389,
"text": "Output –"
},
{
"code": null,
"e": 1540,
"s": 1398,
"text": "ASC arranges the data from ascending to descending order. DESC can be used if the data has to be arranged from descending to ascending order."
},
{
"code": null,
"e": 1549,
"s": 1540,
"text": "DBMS-SQL"
},
{
"code": null,
"e": 1555,
"s": 1549,
"text": "mysql"
},
{
"code": null,
"e": 1560,
"s": 1555,
"text": "DBMS"
},
{
"code": null,
"e": 1564,
"s": 1560,
"text": "SQL"
},
{
"code": null,
"e": 1569,
"s": 1564,
"text": "DBMS"
},
{
"code": null,
"e": 1573,
"s": 1569,
"text": "SQL"
}
] |
Perl | sprintf() Function
|
07 May, 2019
sprintf() function in Perl uses Format provided by the user to return the formatted string with the use of the values in the list. This function is identical to printf but it returns the formatted string instead of printing it.
Syntax: sprintf Format, List
Returns: a formatted scalar string
Example 1:
#!/usr/bin/perl -w # Formatting the string using sprintf$text1 = sprintf("%8s", 'Geeks');$text2 = sprintf("%-8s", 'Geeks'); # Printing the formatted stringprint "$text1\n$text2";
Geeks
Geeks
Example 2:
#!/usr/bin/perl -w # Formatting the string using sprintf$text1 = sprintf("%03d", '7');$text2 = sprintf("%03d", '123');$text3 = sprintf("%04d", '123'); # Printing the formatted stringprint "$text1\n$text2\n$text3";
007
123
0123
Perl-function
Perl-String-Functions
Perl
Perl
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Perl Tutorial - Learn Perl With Examples
Perl | Basic Syntax of a Perl Program
Perl | ne operator
Perl | Opening and Reading a File
Perl | Writing to a File
Perl | File Handling Introduction
Perl | Decision Making (if, if-else, Nested–if, if-elsif ladder, unless, unless-else, unless-elsif)
Perl | Multidimensional Hashes
Perl | Data Types
Perl | CGI Programming
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n07 May, 2019"
},
{
"code": null,
"e": 281,
"s": 53,
"text": "sprintf() function in Perl uses Format provided by the user to return the formatted string with the use of the values in the list. This function is identical to printf but it returns the formatted string instead of printing it."
},
{
"code": null,
"e": 310,
"s": 281,
"text": "Syntax: sprintf Format, List"
},
{
"code": null,
"e": 345,
"s": 310,
"text": "Returns: a formatted scalar string"
},
{
"code": null,
"e": 356,
"s": 345,
"text": "Example 1:"
},
{
"code": "#!/usr/bin/perl -w # Formatting the string using sprintf$text1 = sprintf(\"%8s\", 'Geeks');$text2 = sprintf(\"%-8s\", 'Geeks'); # Printing the formatted stringprint \"$text1\\n$text2\";",
"e": 537,
"s": 356,
"text": null
},
{
"code": null,
"e": 566,
"s": 537,
"text": " Geeks\nGeeks \n"
},
{
"code": null,
"e": 577,
"s": 566,
"text": "Example 2:"
},
{
"code": "#!/usr/bin/perl -w # Formatting the string using sprintf$text1 = sprintf(\"%03d\", '7');$text2 = sprintf(\"%03d\", '123');$text3 = sprintf(\"%04d\", '123'); # Printing the formatted stringprint \"$text1\\n$text2\\n$text3\";",
"e": 793,
"s": 577,
"text": null
},
{
"code": null,
"e": 807,
"s": 793,
"text": "007\n123\n0123\n"
},
{
"code": null,
"e": 821,
"s": 807,
"text": "Perl-function"
},
{
"code": null,
"e": 843,
"s": 821,
"text": "Perl-String-Functions"
},
{
"code": null,
"e": 848,
"s": 843,
"text": "Perl"
},
{
"code": null,
"e": 853,
"s": 848,
"text": "Perl"
},
{
"code": null,
"e": 951,
"s": 853,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 992,
"s": 951,
"text": "Perl Tutorial - Learn Perl With Examples"
},
{
"code": null,
"e": 1030,
"s": 992,
"text": "Perl | Basic Syntax of a Perl Program"
},
{
"code": null,
"e": 1049,
"s": 1030,
"text": "Perl | ne operator"
},
{
"code": null,
"e": 1083,
"s": 1049,
"text": "Perl | Opening and Reading a File"
},
{
"code": null,
"e": 1108,
"s": 1083,
"text": "Perl | Writing to a File"
},
{
"code": null,
"e": 1142,
"s": 1108,
"text": "Perl | File Handling Introduction"
},
{
"code": null,
"e": 1242,
"s": 1142,
"text": "Perl | Decision Making (if, if-else, Nested–if, if-elsif ladder, unless, unless-else, unless-elsif)"
},
{
"code": null,
"e": 1273,
"s": 1242,
"text": "Perl | Multidimensional Hashes"
},
{
"code": null,
"e": 1291,
"s": 1273,
"text": "Perl | Data Types"
}
] |
Espionage – Network Packet And Traffic Interceptor
|
12 Jan, 2022
Espionage is a free and open-source tool available on GitHub. This is a free tool that can be downloaded and installed free of cost. Espionage is a network sniffer. Espionage performs sniffing on data packets of the network. Espionage is used to intercept data packets at the time when data is passed through the network interface card. Espionage can be used to analyze the network with both normal and verbose analysis. Espionage is used to reveal packet direction, protocols, flags, etc. Espionage supports all IPv4, TCP/UDP, ICMP, and HTTP protocols. Espionage is developed in the python language. You must have python language installed in your kali Linux operating system in order to use the tool. Espionage can be used to spoof ARP.
Step 1: Use the following command to install the tool from GitHub.
git clone https://www.github.com/josh0xA/Espionage.git
Step 2: The tool has been downloaded now use the following command to install the dependencies of the tool.
sudo python3 -m pip install -r requirements.txt
Step 3: Now use the following command to run the tool.
sudo python3 espionage.py --help
The tool is running successfully. Now we will see examples to use the tool.
Example 1: Use the espionage tool to execute a clean packet sniff and save the output to the pcap file provided by the user.
performs
The tool perform clean packet sniffing.
Example 2: Use the espionage tool to execute a more detailed (verbose) IPV4 packet sniff.
sudo python3 espionage.py –verbose –iface wlan0 -f capture_output.pcap
The tool performs clean packet sniffing on IPV4.
adnanirshad158
Kali-Linux
Linux-Tools
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Docker - COPY Instruction
scp command in Linux with Examples
chown command in Linux with Examples
SED command in Linux | Set 2
mv command in Linux with examples
nohup Command in Linux with Examples
chmod command in Linux with examples
Introduction to Linux Operating System
Array Basics in Shell Scripting | Set 1
Basic Operators in Shell Scripting
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n12 Jan, 2022"
},
{
"code": null,
"e": 768,
"s": 28,
"text": "Espionage is a free and open-source tool available on GitHub. This is a free tool that can be downloaded and installed free of cost. Espionage is a network sniffer. Espionage performs sniffing on data packets of the network. Espionage is used to intercept data packets at the time when data is passed through the network interface card. Espionage can be used to analyze the network with both normal and verbose analysis. Espionage is used to reveal packet direction, protocols, flags, etc. Espionage supports all IPv4, TCP/UDP, ICMP, and HTTP protocols. Espionage is developed in the python language. You must have python language installed in your kali Linux operating system in order to use the tool. Espionage can be used to spoof ARP."
},
{
"code": null,
"e": 835,
"s": 768,
"text": "Step 1: Use the following command to install the tool from GitHub."
},
{
"code": null,
"e": 890,
"s": 835,
"text": "git clone https://www.github.com/josh0xA/Espionage.git"
},
{
"code": null,
"e": 998,
"s": 890,
"text": "Step 2: The tool has been downloaded now use the following command to install the dependencies of the tool."
},
{
"code": null,
"e": 1046,
"s": 998,
"text": "sudo python3 -m pip install -r requirements.txt"
},
{
"code": null,
"e": 1101,
"s": 1046,
"text": "Step 3: Now use the following command to run the tool."
},
{
"code": null,
"e": 1134,
"s": 1101,
"text": "sudo python3 espionage.py --help"
},
{
"code": null,
"e": 1211,
"s": 1134,
"text": "The tool is running successfully. Now we will see examples to use the tool."
},
{
"code": null,
"e": 1336,
"s": 1211,
"text": "Example 1: Use the espionage tool to execute a clean packet sniff and save the output to the pcap file provided by the user."
},
{
"code": null,
"e": 1345,
"s": 1336,
"text": "performs"
},
{
"code": null,
"e": 1385,
"s": 1345,
"text": "The tool perform clean packet sniffing."
},
{
"code": null,
"e": 1476,
"s": 1385,
"text": "Example 2: Use the espionage tool to execute a more detailed (verbose) IPV4 packet sniff."
},
{
"code": null,
"e": 1547,
"s": 1476,
"text": "sudo python3 espionage.py –verbose –iface wlan0 -f capture_output.pcap"
},
{
"code": null,
"e": 1596,
"s": 1547,
"text": "The tool performs clean packet sniffing on IPV4."
},
{
"code": null,
"e": 1611,
"s": 1596,
"text": "adnanirshad158"
},
{
"code": null,
"e": 1622,
"s": 1611,
"text": "Kali-Linux"
},
{
"code": null,
"e": 1634,
"s": 1622,
"text": "Linux-Tools"
},
{
"code": null,
"e": 1645,
"s": 1634,
"text": "Linux-Unix"
},
{
"code": null,
"e": 1743,
"s": 1645,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1769,
"s": 1743,
"text": "Docker - COPY Instruction"
},
{
"code": null,
"e": 1804,
"s": 1769,
"text": "scp command in Linux with Examples"
},
{
"code": null,
"e": 1841,
"s": 1804,
"text": "chown command in Linux with Examples"
},
{
"code": null,
"e": 1870,
"s": 1841,
"text": "SED command in Linux | Set 2"
},
{
"code": null,
"e": 1904,
"s": 1870,
"text": "mv command in Linux with examples"
},
{
"code": null,
"e": 1941,
"s": 1904,
"text": "nohup Command in Linux with Examples"
},
{
"code": null,
"e": 1978,
"s": 1941,
"text": "chmod command in Linux with examples"
},
{
"code": null,
"e": 2017,
"s": 1978,
"text": "Introduction to Linux Operating System"
},
{
"code": null,
"e": 2057,
"s": 2017,
"text": "Array Basics in Shell Scripting | Set 1"
}
] |
How to add a patch in a plot in Python ?
|
16 Mar, 2021
Matplotlib is an amazing visualization library in Python for 2D plots of arrays. Matplotlib is a multi-platform data visualization library built on NumPy arrays and designed to work with the broader SciPy stack. The Axes Class contains most of the figure elements: Axis, Tick, Line2D, Text, Polygon, etc., and sets the coordinate system. And the instances of Axes supports callbacks through a callbacks attribute. The Matplotlib.axes.Axes.add_patch() method in the axes module of matplotlib library is used to add a Patch to the axes’ patches; return the patch.
Syntax: Axes.add_patch(self, p)
Parameters: This method accepts the following parameters.
line: This parameter is the Patch to the axes’ patches.
Return value: This method returns the Patch.
Below are various examples that depict how to add a patch in a plot in Python:
Example 1:
Python3
# import modulesimport numpy as np import matplotlib.pyplot as plt # adjust figure and assign coordinatesy, x = np.mgrid[:5, 1:6] poly_coords = [(25, 75), (25, 75), (25, 75), (25, 75)]fig, ax = plt.subplots() # depict illustrationcells = ax.plot(x, y, x + y) ax.add_patch(plt.Polygon(poly_coords)) plt.show()
Output:
Example 2:
Python3
# import modulesimport matplotlib.path as mpathimport matplotlib.patches as mpatchesimport matplotlib.pyplot as plt Path = mpath.Path # adjust figure and assign coordinatesfig, ax = plt.subplots()pp = mpatches.PathPatch(Path([(0, 0), (10, 5), (10, 10), (20, 10)], [Path.MOVETO, Path.CURVE3, Path.CURVE3, Path.CLOSEPOLY]), transform=ax.transData) # depict illustrationax.add_patch(pp)plt.show()
Output:
Example 3:
Python3
# import modulesimport matplotlib.path as mpathimport matplotlib.patches as mpatchesimport matplotlib.pyplot as plt # adjust figure and assign coordinatesfig = plt.figure()ax = fig.add_subplot(1, 1, 1) pp1 = plt.Rectangle((0.2, 0.75), 0.4, 0.15) pp2 = plt.Circle((0.7, 0.2), 0.15) pp3 = plt.Polygon([[0.15, 0.15], [0.35, 0.4], [0.2, 0.6]]) # depict illustrationsax.add_patch(pp1)ax.add_patch(pp2)ax.add_patch(pp3)
Output:
Example 4:
Python3
# import modulefrom matplotlib.patches import PathPatchfrom matplotlib.path import Pathimport matplotlib.pyplot as pltimport numpy as np # assign coordinatescoord = [(0, 20), (20, 20), (20, 20), (20, 20), (10, 10), (10, 10), (5, 5), (15, 5), (0, 0)] instn = [Path.MOVETO, Path.LINETO, Path.LINETO, Path.LINETO, Path.CLOSEPOLY, Path.MOVETO, Path.LINETO, Path.LINETO, Path.CLOSEPOLY] # adjust figurecoord = np.array(coord, float)path = Path(coord, instn)pathpatch = PathPatch(path)fig, ax = plt.subplots()ax.add_patch(pathpatch) # depict illustrationax.autoscale_view()plt.show()
Output:
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python | os.path.join() method
Introduction To PYTHON
Python OOPs Concepts
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
Create a directory in Python
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n16 Mar, 2021"
},
{
"code": null,
"e": 590,
"s": 28,
"text": "Matplotlib is an amazing visualization library in Python for 2D plots of arrays. Matplotlib is a multi-platform data visualization library built on NumPy arrays and designed to work with the broader SciPy stack. The Axes Class contains most of the figure elements: Axis, Tick, Line2D, Text, Polygon, etc., and sets the coordinate system. And the instances of Axes supports callbacks through a callbacks attribute. The Matplotlib.axes.Axes.add_patch() method in the axes module of matplotlib library is used to add a Patch to the axes’ patches; return the patch."
},
{
"code": null,
"e": 622,
"s": 590,
"text": "Syntax: Axes.add_patch(self, p)"
},
{
"code": null,
"e": 680,
"s": 622,
"text": "Parameters: This method accepts the following parameters."
},
{
"code": null,
"e": 736,
"s": 680,
"text": "line: This parameter is the Patch to the axes’ patches."
},
{
"code": null,
"e": 781,
"s": 736,
"text": "Return value: This method returns the Patch."
},
{
"code": null,
"e": 860,
"s": 781,
"text": "Below are various examples that depict how to add a patch in a plot in Python:"
},
{
"code": null,
"e": 871,
"s": 860,
"text": "Example 1:"
},
{
"code": null,
"e": 879,
"s": 871,
"text": "Python3"
},
{
"code": "# import modulesimport numpy as np import matplotlib.pyplot as plt # adjust figure and assign coordinatesy, x = np.mgrid[:5, 1:6] poly_coords = [(25, 75), (25, 75), (25, 75), (25, 75)]fig, ax = plt.subplots() # depict illustrationcells = ax.plot(x, y, x + y) ax.add_patch(plt.Polygon(poly_coords)) plt.show() ",
"e": 1195,
"s": 879,
"text": null
},
{
"code": null,
"e": 1203,
"s": 1195,
"text": "Output:"
},
{
"code": null,
"e": 1214,
"s": 1203,
"text": "Example 2:"
},
{
"code": null,
"e": 1222,
"s": 1214,
"text": "Python3"
},
{
"code": "# import modulesimport matplotlib.path as mpathimport matplotlib.patches as mpatchesimport matplotlib.pyplot as plt Path = mpath.Path # adjust figure and assign coordinatesfig, ax = plt.subplots()pp = mpatches.PathPatch(Path([(0, 0), (10, 5), (10, 10), (20, 10)], [Path.MOVETO, Path.CURVE3, Path.CURVE3, Path.CLOSEPOLY]), transform=ax.transData) # depict illustrationax.add_patch(pp)plt.show()",
"e": 1699,
"s": 1222,
"text": null
},
{
"code": null,
"e": 1707,
"s": 1699,
"text": "Output:"
},
{
"code": null,
"e": 1718,
"s": 1707,
"text": "Example 3:"
},
{
"code": null,
"e": 1726,
"s": 1718,
"text": "Python3"
},
{
"code": "# import modulesimport matplotlib.path as mpathimport matplotlib.patches as mpatchesimport matplotlib.pyplot as plt # adjust figure and assign coordinatesfig = plt.figure()ax = fig.add_subplot(1, 1, 1) pp1 = plt.Rectangle((0.2, 0.75), 0.4, 0.15) pp2 = plt.Circle((0.7, 0.2), 0.15) pp3 = plt.Polygon([[0.15, 0.15], [0.35, 0.4], [0.2, 0.6]]) # depict illustrationsax.add_patch(pp1)ax.add_patch(pp2)ax.add_patch(pp3)",
"e": 2200,
"s": 1726,
"text": null
},
{
"code": null,
"e": 2208,
"s": 2200,
"text": "Output:"
},
{
"code": null,
"e": 2219,
"s": 2208,
"text": "Example 4:"
},
{
"code": null,
"e": 2227,
"s": 2219,
"text": "Python3"
},
{
"code": "# import modulefrom matplotlib.patches import PathPatchfrom matplotlib.path import Pathimport matplotlib.pyplot as pltimport numpy as np # assign coordinatescoord = [(0, 20), (20, 20), (20, 20), (20, 20), (10, 10), (10, 10), (5, 5), (15, 5), (0, 0)] instn = [Path.MOVETO, Path.LINETO, Path.LINETO, Path.LINETO, Path.CLOSEPOLY, Path.MOVETO, Path.LINETO, Path.LINETO, Path.CLOSEPOLY] # adjust figurecoord = np.array(coord, float)path = Path(coord, instn)pathpatch = PathPatch(path)fig, ax = plt.subplots()ax.add_patch(pathpatch) # depict illustrationax.autoscale_view()plt.show()",
"e": 2841,
"s": 2227,
"text": null
},
{
"code": null,
"e": 2849,
"s": 2841,
"text": "Output:"
},
{
"code": null,
"e": 2867,
"s": 2849,
"text": "Python-matplotlib"
},
{
"code": null,
"e": 2874,
"s": 2867,
"text": "Python"
},
{
"code": null,
"e": 2972,
"s": 2874,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3004,
"s": 2972,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 3031,
"s": 3004,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 3062,
"s": 3031,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 3085,
"s": 3062,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 3106,
"s": 3085,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 3162,
"s": 3106,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 3204,
"s": 3162,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 3246,
"s": 3204,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 3285,
"s": 3246,
"text": "Python | Get unique values from a list"
}
] |
Construct a Doubly linked linked list from 2D Matrix
|
15 Jun, 2022
Given a 2D matrix, the task is to convert it into a doubly-linked list with four pointers that are next, previous, up, and down, each node of this list should be connected to its next, previous, up, and down nodes.Examples:
Input: 2D matrix
1 2 3
4 5 6
7 8 9
Output:
Approach: The main idea is to construct a new node for every element of the matrix and recursively create it’s up, down, previous and next nodes and change the pointer of previous and up pointers respectively.Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program to construct a Doubly// linked linked list from 2D Matrix #include <iostream>using namespace std; // define dimension of matrix#define dim 3 // struct node of doubly linked// list with four pointer// next, prev, up, downstruct Node { int data; Node* next; Node* prev; Node* up; Node* down;}; // function to create a new nodeNode* createNode(int data){ Node* temp = new Node(); temp->data = data; temp->next = NULL; temp->prev = NULL; temp->up = NULL; temp->down = NULL; return temp;} // function to construct the// doubly linked listNode* constructDoublyListUtil( int mtrx[][dim], int i, int j, Node* curr){ if (i >= dim || j >= dim) { return NULL; } // Create Node with value contain // in matrix at index (i, j) Node* temp = createNode(mtrx[i][j]); // Assign address of curr into // the prev pointer of temp temp->prev = curr; // Assign address of curr into // the up pointer of temp temp->up = curr; // Recursive call for next pointer temp->next = constructDoublyListUtil( mtrx, i, j + 1, temp); // Recursive call for down pointer temp->down = constructDoublyListUtil( mtrx, i + 1, j, temp); // Return newly constructed node // whose all four node connected // at it's appropriate position return temp;} // Function to construct the doubly linked listNode* constructDoublyList(int mtrx[][dim]){ // function call for construct // the doubly linked list return constructDoublyListUtil( mtrx, 0, 0, NULL);} // function for displaying// doubly linked list datavoid display(Node* head){ // pointer to move right Node* rPtr; // pointer to move down Node* dPtr = head; // loop till node->down is not NULL while (dPtr) { rPtr = dPtr; // loop till node->right is not NULL while (rPtr) { cout << rPtr->data << " "; rPtr = rPtr->next; } cout << "\n"; dPtr = dPtr->down; }} // driver codeint main(){ // initialise matrix int mtrx[dim][dim] = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } }; Node* list = constructDoublyList(mtrx); display(list); return 0;}
// Java program to construct a Doubly// linked linked list from 2D Matriximport java.util.*; class GFG{ // define dimension of matrix static int dim= 3; // struct node of doubly linked // list with four pointer // next, prev, up, down static class Node { int data; Node next; Node prev; Node up; Node down; }; // function to create a new node static Node createNode(int data) { Node temp = new Node(); temp.data = data; temp.next = null; temp.prev = null; temp.up = null; temp.down = null; return temp; } // function to construct the // doubly linked list static Node constructDoublyListUtil(int mtrx[][],int i, int j,Node curr) { if (i >= dim || j >= dim) { return null; } // Create Node with value contain // in matrix at index (i, j) Node temp = createNode(mtrx[i][j]); // Assign address of curr into // the prev pointer of temp temp.prev = curr; // Assign address of curr into // the up pointer of temp temp.up = curr; // Recursive call for next pointer temp.next = constructDoublyListUtil(mtrx, i, j + 1, temp); // Recursive call for down pointer temp.down= constructDoublyListUtil(mtrx, i + 1, j, temp); // Return newly constructed node // whose all four node connected // at it's appropriate position return temp; } // Function to construct the doubly linked list static Node constructDoublyList(int mtrx[][]) { // function call for construct // the doubly linked list return constructDoublyListUtil(mtrx, 0, 0, null); } // function for displaying // doubly linked list data static void display(Node head) { // pointer to move right Node rPtr; // pointer to move down Node dPtr = head; // loop till node.down is not null while (dPtr != null) { rPtr = dPtr; // loop till node.right is not null while (rPtr!=null) { System.out.print(rPtr.data+" "); rPtr = rPtr.next; } System.out.print("\n"); dPtr = dPtr.down; } } // driver code public static void main(String args[]) { // initialise matrix int mtrx[][] = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } }; Node list = constructDoublyList(mtrx); display(list); }} // This code is contributed by AbhiThakur
# Python3 program to construct# a Doubly linked linked list# from 2D Matrix # define dimension of matrixdim = 3 # struct node of doubly linked# list with four pointer# next, prev, up, downclass Node: def __init__(self, data): self.data = data self.prev = None self.up = None self.down = None self.next = None # function to create a# new nodedef createNode(data): temp = Node(data); return temp; # function to construct the# doubly linked listdef constructDoublyListUtil(mtrx, i, j, curr): if (i >= dim or j >= dim): return None; # Create Node with value # contain in matrix at # index (i, j) temp = createNode(mtrx[i][j]); # Assign address of curr into # the prev pointer of temp temp.prev = curr; # Assign address of curr into # the up pointer of temp temp.up = curr; # Recursive call for next # pointer temp.next= constructDoublyListUtil(mtrx, i, j + 1, temp); # Recursive call for down pointer temp.down= constructDoublyListUtil(mtrx, i + 1, j, temp); # Return newly constructed node # whose all four node connected # at it's appropriate position return temp; # Function to construct the# doubly linked listdef constructDoublyList(mtrx): # function call for construct # the doubly linked list return constructDoublyListUtil(mtrx, 0, 0, None); # function for displaying# doubly linked list datadef display(head): # pointer to move right rPtr = None # pointer to move down dPtr = head; # loop till node->down # is not NULL while (dPtr != None): rPtr = dPtr; # loop till node->right # is not NULL while (rPtr != None): print(rPtr.data, end = ' ') rPtr = rPtr.next; print() dPtr = dPtr.down; # Driver codeif __name__=="__main__": # initialise matrix mtrx =[[1, 2, 3], [4, 5, 6], [7, 8, 9]] list = constructDoublyList(mtrx); display(list); # This code is contributed by Rutvik_56
// C# program to construct a Doubly// linked linked list from 2D Matrixusing System; class GFG{ // define dimension of matrix static int dim= 3; // struct node of doubly linked // list with four pointer // next, prev, up, down public class Node { public int data; public Node next, prev, up, down; }; // function to create a new node static Node createNode(int data) { Node temp = new Node(); temp.data = data; temp.next = null; temp.prev = null; temp.up = null; temp.down = null; return temp; } // function to construct the // doubly linked list static Node constructDoublyListUtil(int[,] mtrx,int i, int j,Node curr) { if (i >= dim || j >= dim) { return null; } // Create Node with value contain // in matrix at index (i, j) Node temp = createNode(mtrx[i,j]); // Assign address of curr into // the prev pointer of temp temp.prev = curr; // Assign address of curr into // the up pointer of temp temp.up = curr; // Recursive call for next pointer temp.next = constructDoublyListUtil(mtrx, i, j + 1, temp); // Recursive call for down pointer temp.down= constructDoublyListUtil(mtrx, i + 1, j, temp); // Return newly constructed node // whose all four node connected // at it's appropriate position return temp; } // Function to construct the doubly linked list static Node constructDoublyList(int[,] mtrx) { // function call for construct // the doubly linked list return constructDoublyListUtil(mtrx, 0, 0, null); } // function for displaying // doubly linked list data static void display(Node head) { // pointer to move right Node rPtr; // pointer to move down Node dPtr = head; // loop till node.down is not null while (dPtr != null) { rPtr = dPtr; // loop till node.right is not null while (rPtr!=null) { Console.Write(rPtr.data+" "); rPtr = rPtr.next; } Console.Write("\n"); dPtr = dPtr.down; } } // driver code public static void Main() { // initialise matrix int[,] mtrx = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } }; Node list = constructDoublyList(mtrx); display(list); }} // This code is contributed by AbhiThakur
<script>// javascript program to construct a Doubly// linked linked list from 2D Matrix // define dimension of matrix var dim = 3; // struct node of doubly linked // list with four pointer // next, prev, up, down class Node { constructor() { this.data = 0; this.next = null; this.prev = null; this.up = null; this.down = null; } } // function to create a new node function createNode(data) { temp = new Node(); temp.data = data; temp.next = null; temp.prev = null; temp.up = null; temp.down = null; return temp; } // function to construct the // doubly linked list function constructDoublyListUtil(mtrx, i , j, curr) { if (i >= dim || j >= dim) { return null; } // Create Node with value contain // in matrix at index (i, j) var temp = createNode(mtrx[i][j]); // Assign address of curr into // the prev pointer of temp temp.prev = curr; // Assign address of curr into // the up pointer of temp temp.up = curr; // Recursive call for next pointer temp.next = constructDoublyListUtil(mtrx, i, j + 1, temp); // Recursive call for down pointer temp.down= constructDoublyListUtil(mtrx, i + 1, j, temp); // Return newly constructed node // whose all four node connected // at it's appropriate position return temp; } // Function to construct the doubly linked list function constructDoublyList(mtrx) { // function call for construct // the doubly linked list return constructDoublyListUtil(mtrx, 0, 0, null); } // function for displaying // doubly linked list data function display( head) { // pointer to move right rPtr = null; // pointer to move down dPtr = head; // loop till node.down is not null while (dPtr != null) { rPtr = dPtr; // loop till node.right is not null while (rPtr != null) { document.write(rPtr.data + " "); rPtr = rPtr.next; } document.write("<br/>"); dPtr = dPtr.down; } } // driver code // initialise matrix var mtrx = [ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ] ]; var list = constructDoublyList(mtrx); display(list); // This code is contributed by todaysgaurav</script>
1 2 3
4 5 6
7 8 9
Method 2 – Iterative Approach
We will make use of dummy nodes to mark the start of up and prev pointers. Also in the above approach, we are creating so many extra nodes, here we will not be creating many extra nodes.
This approach performs better in the case of a large 2D Matrix, as it does not gets overhead recursion calls.
C++
Java
Python3
C#
Javascript
#include<bits/stdc++.h>using namespace std;struct Node { int data; // To hold the value of matrix // 4 pointers for left, right, up, down for markings. Node* left; Node* right; Node* up; Node* down; Node(int x) : data(x) , left(NULL) , right(NULL) , up(NULL) , down(NULL) {}}; void print(Node* head) { // Require 2 pointers, downptr and rightptr, for rows and columns. Node* downptr = head; Node* rightptr; while (downptr) { rightptr = downptr; while (rightptr) { cout << (rightptr->data) << " "; rightptr = rightptr->right; } cout << "\n"; downptr = downptr->down; }}//Driver Codeint main() { int mat[3][3] = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } }; int n = 3, m = 3; Node* head_main = NULL; // head of our final modified doubly linked list from 2d matrix. Node* prev, *upper = new Node(-1); // dummy node to mark start of up pointer. for (int i = 0; i < n; i++) { Node* head_row; //row-wise head of list. Node *prev = new Node(-1); // dummy node to mark start of left pointer. for (int j = 0; j < m; j++) { Node* temp = new Node(mat[i][j]); if (j == 0) head_row = temp; if (i == 0 && j == 0) head_main = temp; temp->left = prev; prev->right = temp; if (i == n - 1) temp->down = NULL; //This is only used for 1st row. if (!upper->right) { upper->right = new Node(-1); } upper = upper->right; temp->up = upper; upper->down = temp; prev = temp; if (j == m - 1) prev->right = NULL; } upper = head_row->left; } print(head_main); return 0;}
import java.util.*; public class Main { static class Node { int data; // To hold the value of matrix // 4 pointers for left, right, up, down for // markings. Node left; Node right; Node up; Node down; Node(int x) { data = x; left = null; right = null; up = null; down = null; } } public static void print(Node head) { // Require 2 pointers, downptr and rightptr, for // rows and columns. Node downptr = head; Node rightptr; while (downptr != null) { rightptr = downptr; while (rightptr != null) { System.out.print(rightptr.data + " "); rightptr = rightptr.right; } System.out.println(); downptr = downptr.down; } } public static void main(String[] args) { int[][] mat = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } }; int n = 3, m = 3; Node head_main = null; // head of our final modified doubly // linked list from 2d matrix. Node prev, upper = new Node(-1); // dummy node to mark // start of up pointer. for (int i = 0; i < n; i++) { Node head_row = new Node(-1); // row-wise head of list. prev = new Node(-1); // dummy node to mark start // of left pointer. for (int j = 0; j < m; j++) { Node temp = new Node(mat[i][j]); if (j == 0) head_row = temp; if (i == 0 && j == 0) head_main = temp; temp.left = prev; prev.right = temp; if (i == n - 1) temp.down = null; // This is only used for 1st row. if (upper.right == null) upper.right = new Node(-1); upper = upper.right; temp.up = upper; upper.down = temp; prev = temp; if (j == m - 1) prev.right = null; } upper = head_row.left; } print(head_main); }} // This code is contributed by Tapesh(tapeshdua420)
# Python implementation of construction# of a Doubly linked linked list from 2D Matrix class Node: def __init__(self, data): self.data = data # To hold the value of matrix # 4 pointers for left, right, up, down for markings. self.left = None self.right = None self.up = None self.down = None def printList(head): # 4 pointers for left, right, up, down for markings. downptr = head rightptr = None while downptr != None: rightptr = downptr while rightptr != None: print(rightptr.data, end=" ") rightptr = rightptr.right print() downptr = downptr.down if __name__ == "__main__": mat = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ] n = 3 m = 3 # head of our final modified doubly linked list from 2d matrix. head_main = None prev = None upper = Node(-1) # dummy node to mark start of up pointer. for i in range(n): head_row = None # row-wise head of list. prev = Node(-1) # dummy node to mark start of left pointer. for j in range(m): temp = Node(mat[i][j]) if j == 0: head_row = temp if i == 0 and j == 0: head_main = temp temp.left = prev prev.right = temp if i == n-1: temp.down = None # This is only used for 1st row. if upper.right == None: upper.right = Node(-1) upper = upper.right temp.up = upper upper.down = temp prev = temp if j == m-1: prev.right = None upper = head_row.left printList(head_main) # This code is contributed by Tapesh (tapeshdua420)
// C# implementation of construction// of a Doubly linked linked list from 2D Matrixusing System; class Program { // Driver Code static void Main(string[] args) { int[, ] mat = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } }; int n = 3, m = 3; Node head_main = null; // head of our final modified doubly // linked list from 2d matrix. Node prev, upper = new Node(-1); // dummy node to mark // start of up pointer. for (int i = 0; i < n; i++) { Node head_row = new Node(-1); // row-wise head of list. prev = new Node(-1); // dummy node to mark start // of left pointer. for (int j = 0; j < m; j++) { Node temp = new Node(mat[i, j]); if (j == 0) head_row = temp; if (i == 0 && j == 0) head_main = temp; temp.left = prev; prev.right = temp; if (i == n - 1) temp.down = null; // This is only used for 1st row. if (upper.right == null) upper.right = new Node(-1); upper = upper.right; temp.up = upper; upper.down = temp; prev = temp; if (j == m - 1) prev.right = null; } upper = head_row.left; } print(head_main); } public static void print(Node head) { // Require 2 pointers, downptr and rightptr, for // rows and columns. Node downptr = head; Node rightptr; while (downptr != null) { rightptr = downptr; while (rightptr != null) { Console.Write(rightptr.data + " "); rightptr = rightptr.right; } Console.WriteLine(); downptr = downptr.down; } }}class Node { public int data; // To hold the value of matrix // 4 pointers for left, right, up, down for markings. public Node left; public Node right; public Node up; public Node down; public Node(int x) { data = x; left = null; right = null; up = null; down = null; }} // This code is contributed by Tapesh(tapeshdua420)
<script> // JavaScript implementation of construction// of a Doubly linked linked list from 2D Matrixclass Node { // To hold the value of matrix // 4 pointers for left, right, up, down for markings. constructor(x) { this.data = x; this.left = null; this.right = null; this.up = null; this.down = null; }} function print(head){ // Require 2 pointers, downptr and rightptr, for rows and columns. let downptr = head; let rightptr; while (downptr) { rightptr = downptr; while (rightptr) { document.write(rightptr.data," "); rightptr = rightptr.right; } document.write("</br>"); downptr = downptr.down; }} // Driver Codelet mat = [ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ]];let n = 3, m = 3; let head_main = null; // head of our final modified doubly linked list from 2d matrix.let prev, upper = new Node(-1); // dummy node to mark start of up pointer.for (let i = 0; i < n; i++) { let head_row; //row-wise head of list. let prev = new Node(-1); // dummy node to mark start of left pointer. for (let j = 0; j < m; j++) { let temp = new Node(mat[i][j]); if (j == 0) head_row = temp; if (i == 0 && j == 0) head_main = temp; temp.left = prev; prev.right = temp; if (i == n - 1) temp.down = null; //This is only used for 1st row. if (!upper.right) { upper.right = new Node(-1); } upper = upper.right; temp.up = upper; upper.down = temp; prev = temp; if (j == m - 1) prev.right = null; } upper = head_row.left;}print(head_main) // This code is contributed by shinjanpatra </script>
Output:
1 2 3
4 5 6
7 8 9
Time Complexity: O(n*m) where n represents the number of rows, m represents the number of columns in our matrix.
Space Complexity: O(1) constant extra space.
abhaysingh290895
rutvik_56
todaysgaurav
simranarora5sos
abhitiwari9876at
shinjanpatra
tapeshdua420
doubly linked list
Backtracking
Linked List
Matrix
Recursion
Linked List
Recursion
Matrix
Backtracking
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n15 Jun, 2022"
},
{
"code": null,
"e": 278,
"s": 54,
"text": "Given a 2D matrix, the task is to convert it into a doubly-linked list with four pointers that are next, previous, up, and down, each node of this list should be connected to its next, previous, up, and down nodes.Examples:"
},
{
"code": null,
"e": 322,
"s": 278,
"text": "Input: 2D matrix \n1 2 3\n4 5 6\n7 8 9\nOutput:"
},
{
"code": null,
"e": 584,
"s": 322,
"text": "Approach: The main idea is to construct a new node for every element of the matrix and recursively create it’s up, down, previous and next nodes and change the pointer of previous and up pointers respectively.Below is the implementation of the above approach: "
},
{
"code": null,
"e": 588,
"s": 584,
"text": "C++"
},
{
"code": null,
"e": 593,
"s": 588,
"text": "Java"
},
{
"code": null,
"e": 601,
"s": 593,
"text": "Python3"
},
{
"code": null,
"e": 604,
"s": 601,
"text": "C#"
},
{
"code": null,
"e": 615,
"s": 604,
"text": "Javascript"
},
{
"code": "// C++ program to construct a Doubly// linked linked list from 2D Matrix #include <iostream>using namespace std; // define dimension of matrix#define dim 3 // struct node of doubly linked// list with four pointer// next, prev, up, downstruct Node { int data; Node* next; Node* prev; Node* up; Node* down;}; // function to create a new nodeNode* createNode(int data){ Node* temp = new Node(); temp->data = data; temp->next = NULL; temp->prev = NULL; temp->up = NULL; temp->down = NULL; return temp;} // function to construct the// doubly linked listNode* constructDoublyListUtil( int mtrx[][dim], int i, int j, Node* curr){ if (i >= dim || j >= dim) { return NULL; } // Create Node with value contain // in matrix at index (i, j) Node* temp = createNode(mtrx[i][j]); // Assign address of curr into // the prev pointer of temp temp->prev = curr; // Assign address of curr into // the up pointer of temp temp->up = curr; // Recursive call for next pointer temp->next = constructDoublyListUtil( mtrx, i, j + 1, temp); // Recursive call for down pointer temp->down = constructDoublyListUtil( mtrx, i + 1, j, temp); // Return newly constructed node // whose all four node connected // at it's appropriate position return temp;} // Function to construct the doubly linked listNode* constructDoublyList(int mtrx[][dim]){ // function call for construct // the doubly linked list return constructDoublyListUtil( mtrx, 0, 0, NULL);} // function for displaying// doubly linked list datavoid display(Node* head){ // pointer to move right Node* rPtr; // pointer to move down Node* dPtr = head; // loop till node->down is not NULL while (dPtr) { rPtr = dPtr; // loop till node->right is not NULL while (rPtr) { cout << rPtr->data << \" \"; rPtr = rPtr->next; } cout << \"\\n\"; dPtr = dPtr->down; }} // driver codeint main(){ // initialise matrix int mtrx[dim][dim] = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } }; Node* list = constructDoublyList(mtrx); display(list); return 0;}",
"e": 2873,
"s": 615,
"text": null
},
{
"code": "// Java program to construct a Doubly// linked linked list from 2D Matriximport java.util.*; class GFG{ // define dimension of matrix static int dim= 3; // struct node of doubly linked // list with four pointer // next, prev, up, down static class Node { int data; Node next; Node prev; Node up; Node down; }; // function to create a new node static Node createNode(int data) { Node temp = new Node(); temp.data = data; temp.next = null; temp.prev = null; temp.up = null; temp.down = null; return temp; } // function to construct the // doubly linked list static Node constructDoublyListUtil(int mtrx[][],int i, int j,Node curr) { if (i >= dim || j >= dim) { return null; } // Create Node with value contain // in matrix at index (i, j) Node temp = createNode(mtrx[i][j]); // Assign address of curr into // the prev pointer of temp temp.prev = curr; // Assign address of curr into // the up pointer of temp temp.up = curr; // Recursive call for next pointer temp.next = constructDoublyListUtil(mtrx, i, j + 1, temp); // Recursive call for down pointer temp.down= constructDoublyListUtil(mtrx, i + 1, j, temp); // Return newly constructed node // whose all four node connected // at it's appropriate position return temp; } // Function to construct the doubly linked list static Node constructDoublyList(int mtrx[][]) { // function call for construct // the doubly linked list return constructDoublyListUtil(mtrx, 0, 0, null); } // function for displaying // doubly linked list data static void display(Node head) { // pointer to move right Node rPtr; // pointer to move down Node dPtr = head; // loop till node.down is not null while (dPtr != null) { rPtr = dPtr; // loop till node.right is not null while (rPtr!=null) { System.out.print(rPtr.data+\" \"); rPtr = rPtr.next; } System.out.print(\"\\n\"); dPtr = dPtr.down; } } // driver code public static void main(String args[]) { // initialise matrix int mtrx[][] = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } }; Node list = constructDoublyList(mtrx); display(list); }} // This code is contributed by AbhiThakur",
"e": 5597,
"s": 2873,
"text": null
},
{
"code": "# Python3 program to construct# a Doubly linked linked list# from 2D Matrix # define dimension of matrixdim = 3 # struct node of doubly linked# list with four pointer# next, prev, up, downclass Node: def __init__(self, data): self.data = data self.prev = None self.up = None self.down = None self.next = None # function to create a# new nodedef createNode(data): temp = Node(data); return temp; # function to construct the# doubly linked listdef constructDoublyListUtil(mtrx, i, j, curr): if (i >= dim or j >= dim): return None; # Create Node with value # contain in matrix at # index (i, j) temp = createNode(mtrx[i][j]); # Assign address of curr into # the prev pointer of temp temp.prev = curr; # Assign address of curr into # the up pointer of temp temp.up = curr; # Recursive call for next # pointer temp.next= constructDoublyListUtil(mtrx, i, j + 1, temp); # Recursive call for down pointer temp.down= constructDoublyListUtil(mtrx, i + 1, j, temp); # Return newly constructed node # whose all four node connected # at it's appropriate position return temp; # Function to construct the# doubly linked listdef constructDoublyList(mtrx): # function call for construct # the doubly linked list return constructDoublyListUtil(mtrx, 0, 0, None); # function for displaying# doubly linked list datadef display(head): # pointer to move right rPtr = None # pointer to move down dPtr = head; # loop till node->down # is not NULL while (dPtr != None): rPtr = dPtr; # loop till node->right # is not NULL while (rPtr != None): print(rPtr.data, end = ' ') rPtr = rPtr.next; print() dPtr = dPtr.down; # Driver codeif __name__==\"__main__\": # initialise matrix mtrx =[[1, 2, 3], [4, 5, 6], [7, 8, 9]] list = constructDoublyList(mtrx); display(list); # This code is contributed by Rutvik_56",
"e": 7967,
"s": 5597,
"text": null
},
{
"code": "// C# program to construct a Doubly// linked linked list from 2D Matrixusing System; class GFG{ // define dimension of matrix static int dim= 3; // struct node of doubly linked // list with four pointer // next, prev, up, down public class Node { public int data; public Node next, prev, up, down; }; // function to create a new node static Node createNode(int data) { Node temp = new Node(); temp.data = data; temp.next = null; temp.prev = null; temp.up = null; temp.down = null; return temp; } // function to construct the // doubly linked list static Node constructDoublyListUtil(int[,] mtrx,int i, int j,Node curr) { if (i >= dim || j >= dim) { return null; } // Create Node with value contain // in matrix at index (i, j) Node temp = createNode(mtrx[i,j]); // Assign address of curr into // the prev pointer of temp temp.prev = curr; // Assign address of curr into // the up pointer of temp temp.up = curr; // Recursive call for next pointer temp.next = constructDoublyListUtil(mtrx, i, j + 1, temp); // Recursive call for down pointer temp.down= constructDoublyListUtil(mtrx, i + 1, j, temp); // Return newly constructed node // whose all four node connected // at it's appropriate position return temp; } // Function to construct the doubly linked list static Node constructDoublyList(int[,] mtrx) { // function call for construct // the doubly linked list return constructDoublyListUtil(mtrx, 0, 0, null); } // function for displaying // doubly linked list data static void display(Node head) { // pointer to move right Node rPtr; // pointer to move down Node dPtr = head; // loop till node.down is not null while (dPtr != null) { rPtr = dPtr; // loop till node.right is not null while (rPtr!=null) { Console.Write(rPtr.data+\" \"); rPtr = rPtr.next; } Console.Write(\"\\n\"); dPtr = dPtr.down; } } // driver code public static void Main() { // initialise matrix int[,] mtrx = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } }; Node list = constructDoublyList(mtrx); display(list); }} // This code is contributed by AbhiThakur",
"e": 10638,
"s": 7967,
"text": null
},
{
"code": "<script>// javascript program to construct a Doubly// linked linked list from 2D Matrix // define dimension of matrix var dim = 3; // struct node of doubly linked // list with four pointer // next, prev, up, down class Node { constructor() { this.data = 0; this.next = null; this.prev = null; this.up = null; this.down = null; } } // function to create a new node function createNode(data) { temp = new Node(); temp.data = data; temp.next = null; temp.prev = null; temp.up = null; temp.down = null; return temp; } // function to construct the // doubly linked list function constructDoublyListUtil(mtrx, i , j, curr) { if (i >= dim || j >= dim) { return null; } // Create Node with value contain // in matrix at index (i, j) var temp = createNode(mtrx[i][j]); // Assign address of curr into // the prev pointer of temp temp.prev = curr; // Assign address of curr into // the up pointer of temp temp.up = curr; // Recursive call for next pointer temp.next = constructDoublyListUtil(mtrx, i, j + 1, temp); // Recursive call for down pointer temp.down= constructDoublyListUtil(mtrx, i + 1, j, temp); // Return newly constructed node // whose all four node connected // at it's appropriate position return temp; } // Function to construct the doubly linked list function constructDoublyList(mtrx) { // function call for construct // the doubly linked list return constructDoublyListUtil(mtrx, 0, 0, null); } // function for displaying // doubly linked list data function display( head) { // pointer to move right rPtr = null; // pointer to move down dPtr = head; // loop till node.down is not null while (dPtr != null) { rPtr = dPtr; // loop till node.right is not null while (rPtr != null) { document.write(rPtr.data + \" \"); rPtr = rPtr.next; } document.write(\"<br/>\"); dPtr = dPtr.down; } } // driver code // initialise matrix var mtrx = [ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ] ]; var list = constructDoublyList(mtrx); display(list); // This code is contributed by todaysgaurav</script>",
"e": 13329,
"s": 10638,
"text": null
},
{
"code": null,
"e": 13349,
"s": 13329,
"text": "1 2 3 \n4 5 6 \n7 8 9"
},
{
"code": null,
"e": 13381,
"s": 13351,
"text": "Method 2 – Iterative Approach"
},
{
"code": null,
"e": 13568,
"s": 13381,
"text": "We will make use of dummy nodes to mark the start of up and prev pointers. Also in the above approach, we are creating so many extra nodes, here we will not be creating many extra nodes."
},
{
"code": null,
"e": 13678,
"s": 13568,
"text": "This approach performs better in the case of a large 2D Matrix, as it does not gets overhead recursion calls."
},
{
"code": null,
"e": 13682,
"s": 13678,
"text": "C++"
},
{
"code": null,
"e": 13687,
"s": 13682,
"text": "Java"
},
{
"code": null,
"e": 13695,
"s": 13687,
"text": "Python3"
},
{
"code": null,
"e": 13698,
"s": 13695,
"text": "C#"
},
{
"code": null,
"e": 13709,
"s": 13698,
"text": "Javascript"
},
{
"code": "#include<bits/stdc++.h>using namespace std;struct Node { int data; // To hold the value of matrix // 4 pointers for left, right, up, down for markings. Node* left; Node* right; Node* up; Node* down; Node(int x) : data(x) , left(NULL) , right(NULL) , up(NULL) , down(NULL) {}}; void print(Node* head) { // Require 2 pointers, downptr and rightptr, for rows and columns. Node* downptr = head; Node* rightptr; while (downptr) { rightptr = downptr; while (rightptr) { cout << (rightptr->data) << \" \"; rightptr = rightptr->right; } cout << \"\\n\"; downptr = downptr->down; }}//Driver Codeint main() { int mat[3][3] = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } }; int n = 3, m = 3; Node* head_main = NULL; // head of our final modified doubly linked list from 2d matrix. Node* prev, *upper = new Node(-1); // dummy node to mark start of up pointer. for (int i = 0; i < n; i++) { Node* head_row; //row-wise head of list. Node *prev = new Node(-1); // dummy node to mark start of left pointer. for (int j = 0; j < m; j++) { Node* temp = new Node(mat[i][j]); if (j == 0) head_row = temp; if (i == 0 && j == 0) head_main = temp; temp->left = prev; prev->right = temp; if (i == n - 1) temp->down = NULL; //This is only used for 1st row. if (!upper->right) { upper->right = new Node(-1); } upper = upper->right; temp->up = upper; upper->down = temp; prev = temp; if (j == m - 1) prev->right = NULL; } upper = head_row->left; } print(head_main); return 0;}",
"e": 15506,
"s": 13709,
"text": null
},
{
"code": "import java.util.*; public class Main { static class Node { int data; // To hold the value of matrix // 4 pointers for left, right, up, down for // markings. Node left; Node right; Node up; Node down; Node(int x) { data = x; left = null; right = null; up = null; down = null; } } public static void print(Node head) { // Require 2 pointers, downptr and rightptr, for // rows and columns. Node downptr = head; Node rightptr; while (downptr != null) { rightptr = downptr; while (rightptr != null) { System.out.print(rightptr.data + \" \"); rightptr = rightptr.right; } System.out.println(); downptr = downptr.down; } } public static void main(String[] args) { int[][] mat = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } }; int n = 3, m = 3; Node head_main = null; // head of our final modified doubly // linked list from 2d matrix. Node prev, upper = new Node(-1); // dummy node to mark // start of up pointer. for (int i = 0; i < n; i++) { Node head_row = new Node(-1); // row-wise head of list. prev = new Node(-1); // dummy node to mark start // of left pointer. for (int j = 0; j < m; j++) { Node temp = new Node(mat[i][j]); if (j == 0) head_row = temp; if (i == 0 && j == 0) head_main = temp; temp.left = prev; prev.right = temp; if (i == n - 1) temp.down = null; // This is only used for 1st row. if (upper.right == null) upper.right = new Node(-1); upper = upper.right; temp.up = upper; upper.down = temp; prev = temp; if (j == m - 1) prev.right = null; } upper = head_row.left; } print(head_main); }} // This code is contributed by Tapesh(tapeshdua420)",
"e": 17871,
"s": 15506,
"text": null
},
{
"code": "# Python implementation of construction# of a Doubly linked linked list from 2D Matrix class Node: def __init__(self, data): self.data = data # To hold the value of matrix # 4 pointers for left, right, up, down for markings. self.left = None self.right = None self.up = None self.down = None def printList(head): # 4 pointers for left, right, up, down for markings. downptr = head rightptr = None while downptr != None: rightptr = downptr while rightptr != None: print(rightptr.data, end=\" \") rightptr = rightptr.right print() downptr = downptr.down if __name__ == \"__main__\": mat = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ] n = 3 m = 3 # head of our final modified doubly linked list from 2d matrix. head_main = None prev = None upper = Node(-1) # dummy node to mark start of up pointer. for i in range(n): head_row = None # row-wise head of list. prev = Node(-1) # dummy node to mark start of left pointer. for j in range(m): temp = Node(mat[i][j]) if j == 0: head_row = temp if i == 0 and j == 0: head_main = temp temp.left = prev prev.right = temp if i == n-1: temp.down = None # This is only used for 1st row. if upper.right == None: upper.right = Node(-1) upper = upper.right temp.up = upper upper.down = temp prev = temp if j == m-1: prev.right = None upper = head_row.left printList(head_main) # This code is contributed by Tapesh (tapeshdua420)",
"e": 19633,
"s": 17871,
"text": null
},
{
"code": "// C# implementation of construction// of a Doubly linked linked list from 2D Matrixusing System; class Program { // Driver Code static void Main(string[] args) { int[, ] mat = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } }; int n = 3, m = 3; Node head_main = null; // head of our final modified doubly // linked list from 2d matrix. Node prev, upper = new Node(-1); // dummy node to mark // start of up pointer. for (int i = 0; i < n; i++) { Node head_row = new Node(-1); // row-wise head of list. prev = new Node(-1); // dummy node to mark start // of left pointer. for (int j = 0; j < m; j++) { Node temp = new Node(mat[i, j]); if (j == 0) head_row = temp; if (i == 0 && j == 0) head_main = temp; temp.left = prev; prev.right = temp; if (i == n - 1) temp.down = null; // This is only used for 1st row. if (upper.right == null) upper.right = new Node(-1); upper = upper.right; temp.up = upper; upper.down = temp; prev = temp; if (j == m - 1) prev.right = null; } upper = head_row.left; } print(head_main); } public static void print(Node head) { // Require 2 pointers, downptr and rightptr, for // rows and columns. Node downptr = head; Node rightptr; while (downptr != null) { rightptr = downptr; while (rightptr != null) { Console.Write(rightptr.data + \" \"); rightptr = rightptr.right; } Console.WriteLine(); downptr = downptr.down; } }}class Node { public int data; // To hold the value of matrix // 4 pointers for left, right, up, down for markings. public Node left; public Node right; public Node up; public Node down; public Node(int x) { data = x; left = null; right = null; up = null; down = null; }} // This code is contributed by Tapesh(tapeshdua420)",
"e": 21611,
"s": 19633,
"text": null
},
{
"code": "<script> // JavaScript implementation of construction// of a Doubly linked linked list from 2D Matrixclass Node { // To hold the value of matrix // 4 pointers for left, right, up, down for markings. constructor(x) { this.data = x; this.left = null; this.right = null; this.up = null; this.down = null; }} function print(head){ // Require 2 pointers, downptr and rightptr, for rows and columns. let downptr = head; let rightptr; while (downptr) { rightptr = downptr; while (rightptr) { document.write(rightptr.data,\" \"); rightptr = rightptr.right; } document.write(\"</br>\"); downptr = downptr.down; }} // Driver Codelet mat = [ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ]];let n = 3, m = 3; let head_main = null; // head of our final modified doubly linked list from 2d matrix.let prev, upper = new Node(-1); // dummy node to mark start of up pointer.for (let i = 0; i < n; i++) { let head_row; //row-wise head of list. let prev = new Node(-1); // dummy node to mark start of left pointer. for (let j = 0; j < m; j++) { let temp = new Node(mat[i][j]); if (j == 0) head_row = temp; if (i == 0 && j == 0) head_main = temp; temp.left = prev; prev.right = temp; if (i == n - 1) temp.down = null; //This is only used for 1st row. if (!upper.right) { upper.right = new Node(-1); } upper = upper.right; temp.up = upper; upper.down = temp; prev = temp; if (j == m - 1) prev.right = null; } upper = head_row.left;}print(head_main) // This code is contributed by shinjanpatra </script>",
"e": 23363,
"s": 21611,
"text": null
},
{
"code": null,
"e": 23371,
"s": 23363,
"text": "Output:"
},
{
"code": null,
"e": 23392,
"s": 23371,
"text": "1 2 3 \n4 5 6 \n7 8 9 "
},
{
"code": null,
"e": 23506,
"s": 23392,
"text": "Time Complexity: O(n*m) where n represents the number of rows, m represents the number of columns in our matrix. "
},
{
"code": null,
"e": 23551,
"s": 23506,
"text": "Space Complexity: O(1) constant extra space."
},
{
"code": null,
"e": 23568,
"s": 23551,
"text": "abhaysingh290895"
},
{
"code": null,
"e": 23578,
"s": 23568,
"text": "rutvik_56"
},
{
"code": null,
"e": 23591,
"s": 23578,
"text": "todaysgaurav"
},
{
"code": null,
"e": 23607,
"s": 23591,
"text": "simranarora5sos"
},
{
"code": null,
"e": 23624,
"s": 23607,
"text": "abhitiwari9876at"
},
{
"code": null,
"e": 23637,
"s": 23624,
"text": "shinjanpatra"
},
{
"code": null,
"e": 23650,
"s": 23637,
"text": "tapeshdua420"
},
{
"code": null,
"e": 23669,
"s": 23650,
"text": "doubly linked list"
},
{
"code": null,
"e": 23682,
"s": 23669,
"text": "Backtracking"
},
{
"code": null,
"e": 23694,
"s": 23682,
"text": "Linked List"
},
{
"code": null,
"e": 23701,
"s": 23694,
"text": "Matrix"
},
{
"code": null,
"e": 23711,
"s": 23701,
"text": "Recursion"
},
{
"code": null,
"e": 23723,
"s": 23711,
"text": "Linked List"
},
{
"code": null,
"e": 23733,
"s": 23723,
"text": "Recursion"
},
{
"code": null,
"e": 23740,
"s": 23733,
"text": "Matrix"
},
{
"code": null,
"e": 23753,
"s": 23740,
"text": "Backtracking"
}
] |
AngularJS | ng-pattern Directive - GeeksforGeeks
|
29 Mar, 2019
The ng-pattern Directive in AngularJS is used to add up pattern (regex pattern) validator to ngModel on input HTML element. It is used to set the pattern validation error key if input field data does not match a RegExp that is found by evaluating the Angular expression specified in the ngpattern attribute value.
Syntax:
<element ng-pattern="expression"> Contents... </element>
Example 1: This example uses ng-pattern Directive to check the password pattern.
<!DOCTYPE html><html> <head> <title>ng-pattern Directive</title> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.2/angular.min.js"> </script> <style> .red { color:red } .green { color:green } </style></head> <body ng-app="app" style="text-align:center"> <h1 style="color:green;">GeeksforGeeks</h1> <h2 style="">ng-pattern Directive</h2> <div ng-controller="geek"> <ng-form name="pass"> Password:<input type="password" ng-model="password" name="password" ng-pattern="re" /><br> <span ng-show="pass.password.$error.pattern" style="color:red"> Not valid password. </span><br> Confirm: <input type="password" ng-model="repass" ng-keyup="compare(repass)" name="repass" ng-pattern="re" /><br> <span ng-show="isconfirm || pass.repass.$dirty " ng-class="{true:'green',false:'red'}[isconfirm]"> Password {{isconfirm==true?'':'not'}} match </span> </ng-form> </div> <script> var app = angular.module("app", []); app.controller('geek', ['$scope', function ($scope) { $scope.re = /^[a-zA-Z]\w{3,14}$/; $scope.compare = function (repass) { $scope.isconfirm = $scope.password == repass ? true : false; } }]); </script></body> </html>
Output:
Invalid Input:
Input doesn’t Match:
Valid Input:
Example 2: This example shows error if the input is anything other than number.
<!DOCTYPE html><html> <head> <title>ng-pattern Directive</title> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.2/angular.min.js"> </script> </head> <body ng-app="app" style="text-align:center"> <h1 style="color:green;">GeeksforGeeks</h1> <h2 style="">ng-pattern Directive</h2> <div ng-controller="geek"> <ng-form name="num"> Input Number: <input type="text" ng-model="number" name="number" ng-pattern="re" /><br /> <span ng-show="num.number.$error.pattern" style="color:red"> Input is not valid. </span> </ng-form> </div> <script> var app = angular.module("app", []); app.controller('geek', ['$scope', function ($scope) { $scope.re = /^[0-9]{1,6}$/; }]); </script></body> </html>
Output:
Input is text:
Input is number:
AngularJS-Directives
AngularJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Top 10 Angular Libraries For Web Developers
How to use <mat-chip-list> and <mat-chip> in Angular Material ?
How to make a Bootstrap Modal Popup in Angular 9/8 ?
Angular 10 (blur) Event
Angular PrimeNG Dropdown Component
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
|
[
{
"code": null,
"e": 25134,
"s": 25106,
"text": "\n29 Mar, 2019"
},
{
"code": null,
"e": 25448,
"s": 25134,
"text": "The ng-pattern Directive in AngularJS is used to add up pattern (regex pattern) validator to ngModel on input HTML element. It is used to set the pattern validation error key if input field data does not match a RegExp that is found by evaluating the Angular expression specified in the ngpattern attribute value."
},
{
"code": null,
"e": 25456,
"s": 25448,
"text": "Syntax:"
},
{
"code": null,
"e": 25513,
"s": 25456,
"text": "<element ng-pattern=\"expression\"> Contents... </element>"
},
{
"code": null,
"e": 25594,
"s": 25513,
"text": "Example 1: This example uses ng-pattern Directive to check the password pattern."
},
{
"code": "<!DOCTYPE html><html> <head> <title>ng-pattern Directive</title> <script src=\"https://ajax.googleapis.com/ajax/libs/angularjs/1.4.2/angular.min.js\"> </script> <style> .red { color:red } .green { color:green } </style></head> <body ng-app=\"app\" style=\"text-align:center\"> <h1 style=\"color:green;\">GeeksforGeeks</h1> <h2 style=\"\">ng-pattern Directive</h2> <div ng-controller=\"geek\"> <ng-form name=\"pass\"> Password:<input type=\"password\" ng-model=\"password\" name=\"password\" ng-pattern=\"re\" /><br> <span ng-show=\"pass.password.$error.pattern\" style=\"color:red\"> Not valid password. </span><br> Confirm: <input type=\"password\" ng-model=\"repass\" ng-keyup=\"compare(repass)\" name=\"repass\" ng-pattern=\"re\" /><br> <span ng-show=\"isconfirm || pass.repass.$dirty \" ng-class=\"{true:'green',false:'red'}[isconfirm]\"> Password {{isconfirm==true?'':'not'}} match </span> </ng-form> </div> <script> var app = angular.module(\"app\", []); app.controller('geek', ['$scope', function ($scope) { $scope.re = /^[a-zA-Z]\\w{3,14}$/; $scope.compare = function (repass) { $scope.isconfirm = $scope.password == repass ? true : false; } }]); </script></body> </html> ",
"e": 27214,
"s": 25594,
"text": null
},
{
"code": null,
"e": 27222,
"s": 27214,
"text": "Output:"
},
{
"code": null,
"e": 27237,
"s": 27222,
"text": "Invalid Input:"
},
{
"code": null,
"e": 27258,
"s": 27237,
"text": "Input doesn’t Match:"
},
{
"code": null,
"e": 27271,
"s": 27258,
"text": "Valid Input:"
},
{
"code": null,
"e": 27351,
"s": 27271,
"text": "Example 2: This example shows error if the input is anything other than number."
},
{
"code": "<!DOCTYPE html><html> <head> <title>ng-pattern Directive</title> <script src=\"https://ajax.googleapis.com/ajax/libs/angularjs/1.4.2/angular.min.js\"> </script> </head> <body ng-app=\"app\" style=\"text-align:center\"> <h1 style=\"color:green;\">GeeksforGeeks</h1> <h2 style=\"\">ng-pattern Directive</h2> <div ng-controller=\"geek\"> <ng-form name=\"num\"> Input Number: <input type=\"text\" ng-model=\"number\" name=\"number\" ng-pattern=\"re\" /><br /> <span ng-show=\"num.number.$error.pattern\" style=\"color:red\"> Input is not valid. </span> </ng-form> </div> <script> var app = angular.module(\"app\", []); app.controller('geek', ['$scope', function ($scope) { $scope.re = /^[0-9]{1,6}$/; }]); </script></body> </html> ",
"e": 28253,
"s": 27351,
"text": null
},
{
"code": null,
"e": 28261,
"s": 28253,
"text": "Output:"
},
{
"code": null,
"e": 28276,
"s": 28261,
"text": "Input is text:"
},
{
"code": null,
"e": 28293,
"s": 28276,
"text": "Input is number:"
},
{
"code": null,
"e": 28314,
"s": 28293,
"text": "AngularJS-Directives"
},
{
"code": null,
"e": 28324,
"s": 28314,
"text": "AngularJS"
},
{
"code": null,
"e": 28341,
"s": 28324,
"text": "Web Technologies"
},
{
"code": null,
"e": 28439,
"s": 28341,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28448,
"s": 28439,
"text": "Comments"
},
{
"code": null,
"e": 28461,
"s": 28448,
"text": "Old Comments"
},
{
"code": null,
"e": 28505,
"s": 28461,
"text": "Top 10 Angular Libraries For Web Developers"
},
{
"code": null,
"e": 28569,
"s": 28505,
"text": "How to use <mat-chip-list> and <mat-chip> in Angular Material ?"
},
{
"code": null,
"e": 28622,
"s": 28569,
"text": "How to make a Bootstrap Modal Popup in Angular 9/8 ?"
},
{
"code": null,
"e": 28646,
"s": 28622,
"text": "Angular 10 (blur) Event"
},
{
"code": null,
"e": 28681,
"s": 28646,
"text": "Angular PrimeNG Dropdown Component"
},
{
"code": null,
"e": 28723,
"s": 28681,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 28756,
"s": 28723,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 28799,
"s": 28756,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 28861,
"s": 28799,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
}
] |
An Overview Of Julia’s Operators. A quick look at all of the operators... | by Emmett Boudreau | Towards Data Science
|
For those interested in Julia, the world of Julia can be a confusing and scary one to enter. This is not only true of the methodology that Julia is normally written with, utilizing different programming concepts like multiple dispatch, but this is also true for more basic mathematical functions, such as addition or subtraction.
One of the most essential things to learn when picking up a new programming language is almost certainly the operators in that language. Julia has some pretty unique operators that are not all necessarily standardized across the entire scope of programming computers. With that in mind, let us take a look at some of these operators and what their function is in the language.
The most important and foundational operators in Julia are the arithmetic operators. These operators are used for assertion and mathematical expression in Julia, performing the exact arithmetic associated with the char used to represent the operator in Julia.
The assertion operator is one operator that most programmers are likely familiar with. This is represented by the = sign, and is typically used to set variable aliases equal to some sort of type.
The unary plus is the typical use of the addition operator, only placed on one variable. This will perform the identity operation. The identity operation is the operation which represents a combination of a given quantity and another quantity where the quantity remains static. For example, the additive identity is 0 since x + 0 = 0 + x = x. This is represented in Julia as a unary operator, which means that it is only used on one argument. We can call it by using the + char immediately before a variable call, like so:
+x
The unary minus operator is represented the same way as the unary plus operator. However, this operator performs dramatically different arithmetic. This operator is used to map values to their additive inverse. This basically just means that it negates the number. In other words, in Julia we can use the unary minus in order to represent a negative — which I think is natural and cool. This really plays into their “ just like in the papers” methodology, which I think is cool.
-x
Binary plus performs normal addition.
x + y
Binary minus performs normal subtraction.
x - y
The times operator is used to perform normal multiplication.
x * y
Who would have thought? The division operator is used to perform division!
x / y
This operator will perform division, but will always return a rounded integer:
x ÷ y
I think that this one is pretty useless, as I do not know what numpad keys to press to create that symbol, and you can simply use the round() method in order to get a float into an integer.
The inverse divide operator divides the second provided argument by the first, rather than the opposite.
x \ y
The power operator in Julia is ^, which always leaves me confused whenever I work with Python and try to call the Xor operator, ^, thinking it is going to give me an exponent.
x ^ 2
The remainder operator will return the remainder of division between two arguments.
x % y
Though not very exciting, boolean operators are also pretty important. These operators are meant to be used exclusively on bool types, as one might expect. Bare with me, I understand that most likely know all of the operators that we have looked at so far, but to get to the real meat of the Julian operators we must first go through the relatively rudimentary stuff.
The negation operator is another unary operator that will change the value of a given boolean to the opposite. It is represented with an explanation point.
!x
The boolean and operator is ripped straight from Bash in Julia. It is represented as &&.
x && y
The other conjunction operator is the or operator, which is represented with ||.
In computer programming, a bitwise operation operates on a bit string, a bit array or a binary numeral at the level of its individual bits. This usually just means that the operators are used to change individual bits in an operator.
The bitwise not operator is represented with ~, and is a unary operator.
~100
The bitwise and operator is represented with an amperstand, and is a binary operator.
x & y
The bitwise or operator is represented with a tube, |, and is also a binary operator.
x | y
Bitwise xor is represented with this thing ⊻, but you can also use the xor() method, which is what I usually do.
x ⊻ y
The logical shift right operator is represented with three right arrows, and is a binary operator.
x >>> y
The arithmetical shift right is represented with only two right arrows, and is also a binary operator.
x >> y
Both logical and arithmetical shifts left are combined into only two arrows going left. This is of course a binary operator, as well.
x << y
Every binary bitwise or arithmetic operator in the Julia language comes with an updating counter-part. These operators are used to update variable aliases with new types. The updating versions of the operators we just went over are
+= -= *= /= \= ÷= %= ^= &= |= ⊻= >>>= >>= <<=
The last form of basic operators are the vectorized versions of the any binary arithmetic operation. This is represented by a dot in front of the operator. These are of course meant to be used on an iterable vector or array. The vectorized versions of these operators are as follows:
.+ .- .* ./ .\ .% .^
Comparison operators are used to return a boolean type from two arguments based on some condition. This condition can be numerical, equality, or even more.
The equality operator returns true if the values are equal.
x == y
The inequality operator returns true if the values are not equal.
x != y
The less than operator returns true if the first argument is less than the second argument.
x < y
The greater than operator returns true if the second argument is less than the first argument.
x > y
We can make both the less than and greater than operators become less than or equal to and greater than or equal to operators by simply adding an equals sign after the operator.
x >= yy <= x
Unfortunately the most exciting on this list is the sub-type operator. The sub-type operator has two uses. It is a binary operator that takes types. This operator is represented with <:. The first use is to assert a sub-type to any abstract type. For example,
abstract type AbstractTuber endstruct Potato <: AbstractTuber data::Array end
This operator can also be used to return a boolean for comparisons, hence why it is in this section:
x <: y
We can pretend that this operator means “ is a sub-type of.” If you would like to read more about sub-types in Julia as a general concept, and the usage of this operator for type hierarchies in Julia, I wrote an entire article on it you can check out here:
towardsdatascience.com
I decided to write this article because the Julia language does have some notable differences between a lot of other competing languages in its domain. It can often get confusing when switching from language to language and working with different operators, and furthermore it might be nice for newer programmers to be aware of all the operators in their language. As boring as this was to write, I do think it might be helpful for anyone coming into Julia with the intention of learning the language. Thank you very much for reading my article, I appreciate it!
|
[
{
"code": null,
"e": 501,
"s": 171,
"text": "For those interested in Julia, the world of Julia can be a confusing and scary one to enter. This is not only true of the methodology that Julia is normally written with, utilizing different programming concepts like multiple dispatch, but this is also true for more basic mathematical functions, such as addition or subtraction."
},
{
"code": null,
"e": 878,
"s": 501,
"text": "One of the most essential things to learn when picking up a new programming language is almost certainly the operators in that language. Julia has some pretty unique operators that are not all necessarily standardized across the entire scope of programming computers. With that in mind, let us take a look at some of these operators and what their function is in the language."
},
{
"code": null,
"e": 1138,
"s": 878,
"text": "The most important and foundational operators in Julia are the arithmetic operators. These operators are used for assertion and mathematical expression in Julia, performing the exact arithmetic associated with the char used to represent the operator in Julia."
},
{
"code": null,
"e": 1334,
"s": 1138,
"text": "The assertion operator is one operator that most programmers are likely familiar with. This is represented by the = sign, and is typically used to set variable aliases equal to some sort of type."
},
{
"code": null,
"e": 1857,
"s": 1334,
"text": "The unary plus is the typical use of the addition operator, only placed on one variable. This will perform the identity operation. The identity operation is the operation which represents a combination of a given quantity and another quantity where the quantity remains static. For example, the additive identity is 0 since x + 0 = 0 + x = x. This is represented in Julia as a unary operator, which means that it is only used on one argument. We can call it by using the + char immediately before a variable call, like so:"
},
{
"code": null,
"e": 1860,
"s": 1857,
"text": "+x"
},
{
"code": null,
"e": 2339,
"s": 1860,
"text": "The unary minus operator is represented the same way as the unary plus operator. However, this operator performs dramatically different arithmetic. This operator is used to map values to their additive inverse. This basically just means that it negates the number. In other words, in Julia we can use the unary minus in order to represent a negative — which I think is natural and cool. This really plays into their “ just like in the papers” methodology, which I think is cool."
},
{
"code": null,
"e": 2342,
"s": 2339,
"text": "-x"
},
{
"code": null,
"e": 2380,
"s": 2342,
"text": "Binary plus performs normal addition."
},
{
"code": null,
"e": 2386,
"s": 2380,
"text": "x + y"
},
{
"code": null,
"e": 2428,
"s": 2386,
"text": "Binary minus performs normal subtraction."
},
{
"code": null,
"e": 2434,
"s": 2428,
"text": "x - y"
},
{
"code": null,
"e": 2495,
"s": 2434,
"text": "The times operator is used to perform normal multiplication."
},
{
"code": null,
"e": 2501,
"s": 2495,
"text": "x * y"
},
{
"code": null,
"e": 2576,
"s": 2501,
"text": "Who would have thought? The division operator is used to perform division!"
},
{
"code": null,
"e": 2582,
"s": 2576,
"text": "x / y"
},
{
"code": null,
"e": 2661,
"s": 2582,
"text": "This operator will perform division, but will always return a rounded integer:"
},
{
"code": null,
"e": 2667,
"s": 2661,
"text": "x ÷ y"
},
{
"code": null,
"e": 2857,
"s": 2667,
"text": "I think that this one is pretty useless, as I do not know what numpad keys to press to create that symbol, and you can simply use the round() method in order to get a float into an integer."
},
{
"code": null,
"e": 2962,
"s": 2857,
"text": "The inverse divide operator divides the second provided argument by the first, rather than the opposite."
},
{
"code": null,
"e": 2968,
"s": 2962,
"text": "x \\ y"
},
{
"code": null,
"e": 3144,
"s": 2968,
"text": "The power operator in Julia is ^, which always leaves me confused whenever I work with Python and try to call the Xor operator, ^, thinking it is going to give me an exponent."
},
{
"code": null,
"e": 3150,
"s": 3144,
"text": "x ^ 2"
},
{
"code": null,
"e": 3234,
"s": 3150,
"text": "The remainder operator will return the remainder of division between two arguments."
},
{
"code": null,
"e": 3240,
"s": 3234,
"text": "x % y"
},
{
"code": null,
"e": 3608,
"s": 3240,
"text": "Though not very exciting, boolean operators are also pretty important. These operators are meant to be used exclusively on bool types, as one might expect. Bare with me, I understand that most likely know all of the operators that we have looked at so far, but to get to the real meat of the Julian operators we must first go through the relatively rudimentary stuff."
},
{
"code": null,
"e": 3764,
"s": 3608,
"text": "The negation operator is another unary operator that will change the value of a given boolean to the opposite. It is represented with an explanation point."
},
{
"code": null,
"e": 3767,
"s": 3764,
"text": "!x"
},
{
"code": null,
"e": 3856,
"s": 3767,
"text": "The boolean and operator is ripped straight from Bash in Julia. It is represented as &&."
},
{
"code": null,
"e": 3863,
"s": 3856,
"text": "x && y"
},
{
"code": null,
"e": 3944,
"s": 3863,
"text": "The other conjunction operator is the or operator, which is represented with ||."
},
{
"code": null,
"e": 4178,
"s": 3944,
"text": "In computer programming, a bitwise operation operates on a bit string, a bit array or a binary numeral at the level of its individual bits. This usually just means that the operators are used to change individual bits in an operator."
},
{
"code": null,
"e": 4251,
"s": 4178,
"text": "The bitwise not operator is represented with ~, and is a unary operator."
},
{
"code": null,
"e": 4256,
"s": 4251,
"text": "~100"
},
{
"code": null,
"e": 4342,
"s": 4256,
"text": "The bitwise and operator is represented with an amperstand, and is a binary operator."
},
{
"code": null,
"e": 4348,
"s": 4342,
"text": "x & y"
},
{
"code": null,
"e": 4434,
"s": 4348,
"text": "The bitwise or operator is represented with a tube, |, and is also a binary operator."
},
{
"code": null,
"e": 4440,
"s": 4434,
"text": "x | y"
},
{
"code": null,
"e": 4553,
"s": 4440,
"text": "Bitwise xor is represented with this thing ⊻, but you can also use the xor() method, which is what I usually do."
},
{
"code": null,
"e": 4559,
"s": 4553,
"text": "x ⊻ y"
},
{
"code": null,
"e": 4658,
"s": 4559,
"text": "The logical shift right operator is represented with three right arrows, and is a binary operator."
},
{
"code": null,
"e": 4666,
"s": 4658,
"text": "x >>> y"
},
{
"code": null,
"e": 4769,
"s": 4666,
"text": "The arithmetical shift right is represented with only two right arrows, and is also a binary operator."
},
{
"code": null,
"e": 4776,
"s": 4769,
"text": "x >> y"
},
{
"code": null,
"e": 4910,
"s": 4776,
"text": "Both logical and arithmetical shifts left are combined into only two arrows going left. This is of course a binary operator, as well."
},
{
"code": null,
"e": 4917,
"s": 4910,
"text": "x << y"
},
{
"code": null,
"e": 5149,
"s": 4917,
"text": "Every binary bitwise or arithmetic operator in the Julia language comes with an updating counter-part. These operators are used to update variable aliases with new types. The updating versions of the operators we just went over are"
},
{
"code": null,
"e": 5208,
"s": 5149,
"text": "+= -= *= /= \\= ÷= %= ^= &= |= ⊻= >>>= >>= <<="
},
{
"code": null,
"e": 5492,
"s": 5208,
"text": "The last form of basic operators are the vectorized versions of the any binary arithmetic operation. This is represented by a dot in front of the operator. These are of course meant to be used on an iterable vector or array. The vectorized versions of these operators are as follows:"
},
{
"code": null,
"e": 5513,
"s": 5492,
"text": ".+ .- .* ./ .\\ .% .^"
},
{
"code": null,
"e": 5669,
"s": 5513,
"text": "Comparison operators are used to return a boolean type from two arguments based on some condition. This condition can be numerical, equality, or even more."
},
{
"code": null,
"e": 5729,
"s": 5669,
"text": "The equality operator returns true if the values are equal."
},
{
"code": null,
"e": 5736,
"s": 5729,
"text": "x == y"
},
{
"code": null,
"e": 5802,
"s": 5736,
"text": "The inequality operator returns true if the values are not equal."
},
{
"code": null,
"e": 5809,
"s": 5802,
"text": "x != y"
},
{
"code": null,
"e": 5901,
"s": 5809,
"text": "The less than operator returns true if the first argument is less than the second argument."
},
{
"code": null,
"e": 5907,
"s": 5901,
"text": "x < y"
},
{
"code": null,
"e": 6002,
"s": 5907,
"text": "The greater than operator returns true if the second argument is less than the first argument."
},
{
"code": null,
"e": 6008,
"s": 6002,
"text": "x > y"
},
{
"code": null,
"e": 6186,
"s": 6008,
"text": "We can make both the less than and greater than operators become less than or equal to and greater than or equal to operators by simply adding an equals sign after the operator."
},
{
"code": null,
"e": 6199,
"s": 6186,
"text": "x >= yy <= x"
},
{
"code": null,
"e": 6459,
"s": 6199,
"text": "Unfortunately the most exciting on this list is the sub-type operator. The sub-type operator has two uses. It is a binary operator that takes types. This operator is represented with <:. The first use is to assert a sub-type to any abstract type. For example,"
},
{
"code": null,
"e": 6537,
"s": 6459,
"text": "abstract type AbstractTuber endstruct Potato <: AbstractTuber data::Array end"
},
{
"code": null,
"e": 6638,
"s": 6537,
"text": "This operator can also be used to return a boolean for comparisons, hence why it is in this section:"
},
{
"code": null,
"e": 6645,
"s": 6638,
"text": "x <: y"
},
{
"code": null,
"e": 6902,
"s": 6645,
"text": "We can pretend that this operator means “ is a sub-type of.” If you would like to read more about sub-types in Julia as a general concept, and the usage of this operator for type hierarchies in Julia, I wrote an entire article on it you can check out here:"
},
{
"code": null,
"e": 6925,
"s": 6902,
"text": "towardsdatascience.com"
}
] |
Optimize Warehouse Value Added Services with Python | by Samir Saci | Towards Data Science
|
Most of the challenges faced by Distribution Centers (DC) handling Luxury Products, Garments or high-value goods are during Inbound Process.
We will take the example of a DC storing imported Luxury Bags, Garments and Shoes that need:
Machine 1 — Anti-theft tag: put a self alarm tag to protect your goods against theft in the store
Machine 2 — Labelling: print labels in the local language and perform label sewing
Machine 3 — Kitting & Repackaging: transfer your goods in the sales packaging and add Gift With Purchase (GWP), Individual Note or Certificate of Authenticity
After the completion of these 3 steps, your goods are ready to be put away in the stock area waiting to be picked for shipping to their final destinations (Store).
If your capacity of items handled by day is too low, this process can quickly become a major bottleneck.
You are an Inbound Manager of a Distribution Center (DC) for an iconic Luxury Maison focusing on Fashion, Fragrance and Watches.
You have received 600 prêt-à-porter sets (Ready-to-wear) including:
1 Female dress that requires Label Sewing and Re-packing
1 Handbag that requires Label Sewing, an Anti-theft tag and Re-packing
1 Leather Belt that requires an Anti-theft tag, Label Sewing and Re-packing
Because they are sold together, these SKU need to be ready at the same time and co-packed together to be ready for shipping to stores as soon as possible after the following steps:
Inbound Team is unloading pallets from the truck and put them in the staging area
Machine 1: Anti-theft tag — an operator put an anti-theft tag on each bag and belt
Machine 2 — Labelling: after printing in a dedicated area, labels are sewed on belts, handbags and dress
Machine 3 — Kitting & Repackaging: for each item, you need to add a certificate of authenticity, plastic protection and perform fine packing
After the re-packaging process, goods are transferred to a final staging area to wait for shipping (X-Docking Mode).
Objective: Reach maximum productivity of sets assembled per hour (sets/hour)
The Job Shop Scheduling Problem (JSSP) is an NP-hard problem defined by a set of jobs that must be executed by a set of machines in a specific order for each job.
For each of our jobs, we have defined execution time (min) and processing order of machines in the table above.
For instance, Job 2 (Handbag) is starting with Anti-theft Tags placement using Machine 1 (6 min) followed by Labels Sewing using Machine 2 (4 min), to finally end with Kitting and Packing using Machine 3 (3 min).
The machines can only execute a job at a time and once started, the machine cannot be interrupted until the completion of the assigned job.
Objective: minimize the makespan i.e the total time for completion of all jobs
i. The Naive Solution: 1 job cycle at a time
Results
Makespan: 30 min
Productivity: 2 sets/hour
Comments
This simple approach is the worst in terms of productivity. Because of the processing of job in sequence, machines stay idle (unused) quite often.
Question: What would be the result if we perform jobs in parallel?
ii. Optimal Solution: The Job Shop Scheduling Problem using Google OR-Tools
OR-Tools is an open-source collection of Google with tools for combinatorial optimization. The objective is to find the best solution out of a very large set of possible solutions.
I am a fan of this library that I have been using in several examples:
Samir Saci, Design Pathfinding Algorithm using Google AI to Improve Warehouse Productivity, Link
Samir Saci, Optimize Workforce Planning using Linear Programming with Python, Link
Let us try to use this library to find the optimal sequencing to reduce the makespan for this specific set of processes.
You can see above two graphs representing the initial solution (Naive Solution: 1 job at a time) and the Optimized Solution (Parallel Tasking).
Results
Total Makespan: 16 min (-47%)
Productivity: 3.75 sets/hour (+85%)
Idle time per cycle: 18 min (-71.4%)
The results are satisfying
I will explain now how to reach these results.
Edit: You can find a Youtube version of this article with animations in the link below.
a. Initialize your model
3 machinesTotal Time using Naive Solution: 30 min
b. Initialize variables and create sequences
c. Add Constraints and Set up the Solver
d. Solver Optimal Solution
Output -Optimal Schedule Length: 16Machine 1: job_2_1 job_3_2 [0,6] [6,10] Machine 2: job_3_1 job_1_1 job_2_2 [0,3] [3,7] [7,11] Machine 3: job_1_2 job_3_3 job_2_3 [7,10] [10,13] [13,16]
Based on this output we can draw the updated schedule:
We increased the productivity by +48% by implementing a solution for smart scheduling that use the maximum potential of our resources (Machines).
This solution was based on a simple scenario using a single line of assembly (1 Machine per Type).
Question: What could be the results with several lines?
I let you test it and share your results (or questions) in the comment area.
Can we have higher productivity by changing the conditions?
In the chart above, I have highlighted the potential additional jobs we’ve could add during the idle time:
Machine 1: 1 sequence of 4 min which equals to the time for Job 3
Machine 2: 1 sequence of 4 min which equals to the time for Job 1 and Job 2
Machine 3: 2 sequences of 4 min which equals to the time for Job 1,2 and 3
Question: What would be the average productivity if we start Jobs of Cycle n+1 during these idle sequences of Cycle n?
What would be the impact on overall productivity if we have workstations for label sewing?
towardsdatascience.com
Please feel free to contact me, I am willing to share and exchange on topics related to Data Science and Supply Chain.My Portfolio: https://samirsaci.com
[1] Google AI, Google OR-Tools Library, Link
|
[
{
"code": null,
"e": 313,
"s": 172,
"text": "Most of the challenges faced by Distribution Centers (DC) handling Luxury Products, Garments or high-value goods are during Inbound Process."
},
{
"code": null,
"e": 406,
"s": 313,
"text": "We will take the example of a DC storing imported Luxury Bags, Garments and Shoes that need:"
},
{
"code": null,
"e": 504,
"s": 406,
"text": "Machine 1 — Anti-theft tag: put a self alarm tag to protect your goods against theft in the store"
},
{
"code": null,
"e": 587,
"s": 504,
"text": "Machine 2 — Labelling: print labels in the local language and perform label sewing"
},
{
"code": null,
"e": 746,
"s": 587,
"text": "Machine 3 — Kitting & Repackaging: transfer your goods in the sales packaging and add Gift With Purchase (GWP), Individual Note or Certificate of Authenticity"
},
{
"code": null,
"e": 910,
"s": 746,
"text": "After the completion of these 3 steps, your goods are ready to be put away in the stock area waiting to be picked for shipping to their final destinations (Store)."
},
{
"code": null,
"e": 1015,
"s": 910,
"text": "If your capacity of items handled by day is too low, this process can quickly become a major bottleneck."
},
{
"code": null,
"e": 1144,
"s": 1015,
"text": "You are an Inbound Manager of a Distribution Center (DC) for an iconic Luxury Maison focusing on Fashion, Fragrance and Watches."
},
{
"code": null,
"e": 1214,
"s": 1144,
"text": "You have received 600 prêt-à-porter sets (Ready-to-wear) including:"
},
{
"code": null,
"e": 1271,
"s": 1214,
"text": "1 Female dress that requires Label Sewing and Re-packing"
},
{
"code": null,
"e": 1342,
"s": 1271,
"text": "1 Handbag that requires Label Sewing, an Anti-theft tag and Re-packing"
},
{
"code": null,
"e": 1418,
"s": 1342,
"text": "1 Leather Belt that requires an Anti-theft tag, Label Sewing and Re-packing"
},
{
"code": null,
"e": 1599,
"s": 1418,
"text": "Because they are sold together, these SKU need to be ready at the same time and co-packed together to be ready for shipping to stores as soon as possible after the following steps:"
},
{
"code": null,
"e": 1681,
"s": 1599,
"text": "Inbound Team is unloading pallets from the truck and put them in the staging area"
},
{
"code": null,
"e": 1764,
"s": 1681,
"text": "Machine 1: Anti-theft tag — an operator put an anti-theft tag on each bag and belt"
},
{
"code": null,
"e": 1869,
"s": 1764,
"text": "Machine 2 — Labelling: after printing in a dedicated area, labels are sewed on belts, handbags and dress"
},
{
"code": null,
"e": 2010,
"s": 1869,
"text": "Machine 3 — Kitting & Repackaging: for each item, you need to add a certificate of authenticity, plastic protection and perform fine packing"
},
{
"code": null,
"e": 2127,
"s": 2010,
"text": "After the re-packaging process, goods are transferred to a final staging area to wait for shipping (X-Docking Mode)."
},
{
"code": null,
"e": 2204,
"s": 2127,
"text": "Objective: Reach maximum productivity of sets assembled per hour (sets/hour)"
},
{
"code": null,
"e": 2367,
"s": 2204,
"text": "The Job Shop Scheduling Problem (JSSP) is an NP-hard problem defined by a set of jobs that must be executed by a set of machines in a specific order for each job."
},
{
"code": null,
"e": 2479,
"s": 2367,
"text": "For each of our jobs, we have defined execution time (min) and processing order of machines in the table above."
},
{
"code": null,
"e": 2692,
"s": 2479,
"text": "For instance, Job 2 (Handbag) is starting with Anti-theft Tags placement using Machine 1 (6 min) followed by Labels Sewing using Machine 2 (4 min), to finally end with Kitting and Packing using Machine 3 (3 min)."
},
{
"code": null,
"e": 2832,
"s": 2692,
"text": "The machines can only execute a job at a time and once started, the machine cannot be interrupted until the completion of the assigned job."
},
{
"code": null,
"e": 2911,
"s": 2832,
"text": "Objective: minimize the makespan i.e the total time for completion of all jobs"
},
{
"code": null,
"e": 2956,
"s": 2911,
"text": "i. The Naive Solution: 1 job cycle at a time"
},
{
"code": null,
"e": 2964,
"s": 2956,
"text": "Results"
},
{
"code": null,
"e": 2981,
"s": 2964,
"text": "Makespan: 30 min"
},
{
"code": null,
"e": 3007,
"s": 2981,
"text": "Productivity: 2 sets/hour"
},
{
"code": null,
"e": 3016,
"s": 3007,
"text": "Comments"
},
{
"code": null,
"e": 3163,
"s": 3016,
"text": "This simple approach is the worst in terms of productivity. Because of the processing of job in sequence, machines stay idle (unused) quite often."
},
{
"code": null,
"e": 3230,
"s": 3163,
"text": "Question: What would be the result if we perform jobs in parallel?"
},
{
"code": null,
"e": 3306,
"s": 3230,
"text": "ii. Optimal Solution: The Job Shop Scheduling Problem using Google OR-Tools"
},
{
"code": null,
"e": 3487,
"s": 3306,
"text": "OR-Tools is an open-source collection of Google with tools for combinatorial optimization. The objective is to find the best solution out of a very large set of possible solutions."
},
{
"code": null,
"e": 3558,
"s": 3487,
"text": "I am a fan of this library that I have been using in several examples:"
},
{
"code": null,
"e": 3655,
"s": 3558,
"text": "Samir Saci, Design Pathfinding Algorithm using Google AI to Improve Warehouse Productivity, Link"
},
{
"code": null,
"e": 3738,
"s": 3655,
"text": "Samir Saci, Optimize Workforce Planning using Linear Programming with Python, Link"
},
{
"code": null,
"e": 3859,
"s": 3738,
"text": "Let us try to use this library to find the optimal sequencing to reduce the makespan for this specific set of processes."
},
{
"code": null,
"e": 4003,
"s": 3859,
"text": "You can see above two graphs representing the initial solution (Naive Solution: 1 job at a time) and the Optimized Solution (Parallel Tasking)."
},
{
"code": null,
"e": 4011,
"s": 4003,
"text": "Results"
},
{
"code": null,
"e": 4041,
"s": 4011,
"text": "Total Makespan: 16 min (-47%)"
},
{
"code": null,
"e": 4077,
"s": 4041,
"text": "Productivity: 3.75 sets/hour (+85%)"
},
{
"code": null,
"e": 4114,
"s": 4077,
"text": "Idle time per cycle: 18 min (-71.4%)"
},
{
"code": null,
"e": 4141,
"s": 4114,
"text": "The results are satisfying"
},
{
"code": null,
"e": 4188,
"s": 4141,
"text": "I will explain now how to reach these results."
},
{
"code": null,
"e": 4276,
"s": 4188,
"text": "Edit: You can find a Youtube version of this article with animations in the link below."
},
{
"code": null,
"e": 4301,
"s": 4276,
"text": "a. Initialize your model"
},
{
"code": null,
"e": 4351,
"s": 4301,
"text": "3 machinesTotal Time using Naive Solution: 30 min"
},
{
"code": null,
"e": 4396,
"s": 4351,
"text": "b. Initialize variables and create sequences"
},
{
"code": null,
"e": 4437,
"s": 4396,
"text": "c. Add Constraints and Set up the Solver"
},
{
"code": null,
"e": 4464,
"s": 4437,
"text": "d. Solver Optimal Solution"
},
{
"code": null,
"e": 4723,
"s": 4464,
"text": "Output -Optimal Schedule Length: 16Machine 1: job_2_1 job_3_2 [0,6] [6,10] Machine 2: job_3_1 job_1_1 job_2_2 [0,3] [3,7] [7,11] Machine 3: job_1_2 job_3_3 job_2_3 [7,10] [10,13] [13,16]"
},
{
"code": null,
"e": 4778,
"s": 4723,
"text": "Based on this output we can draw the updated schedule:"
},
{
"code": null,
"e": 4924,
"s": 4778,
"text": "We increased the productivity by +48% by implementing a solution for smart scheduling that use the maximum potential of our resources (Machines)."
},
{
"code": null,
"e": 5023,
"s": 4924,
"text": "This solution was based on a simple scenario using a single line of assembly (1 Machine per Type)."
},
{
"code": null,
"e": 5079,
"s": 5023,
"text": "Question: What could be the results with several lines?"
},
{
"code": null,
"e": 5156,
"s": 5079,
"text": "I let you test it and share your results (or questions) in the comment area."
},
{
"code": null,
"e": 5216,
"s": 5156,
"text": "Can we have higher productivity by changing the conditions?"
},
{
"code": null,
"e": 5323,
"s": 5216,
"text": "In the chart above, I have highlighted the potential additional jobs we’ve could add during the idle time:"
},
{
"code": null,
"e": 5389,
"s": 5323,
"text": "Machine 1: 1 sequence of 4 min which equals to the time for Job 3"
},
{
"code": null,
"e": 5465,
"s": 5389,
"text": "Machine 2: 1 sequence of 4 min which equals to the time for Job 1 and Job 2"
},
{
"code": null,
"e": 5540,
"s": 5465,
"text": "Machine 3: 2 sequences of 4 min which equals to the time for Job 1,2 and 3"
},
{
"code": null,
"e": 5659,
"s": 5540,
"text": "Question: What would be the average productivity if we start Jobs of Cycle n+1 during these idle sequences of Cycle n?"
},
{
"code": null,
"e": 5750,
"s": 5659,
"text": "What would be the impact on overall productivity if we have workstations for label sewing?"
},
{
"code": null,
"e": 5773,
"s": 5750,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 5927,
"s": 5773,
"text": "Please feel free to contact me, I am willing to share and exchange on topics related to Data Science and Supply Chain.My Portfolio: https://samirsaci.com"
}
] |
Python PostgreSQL - Drop Table
|
You can drop a table from PostgreSQL database using the DROP TABLE statement.
Following is the syntax of the DROP TABLE statement in PostgreSQL −
DROP TABLE table_name;
Assume we have created two tables with name CRICKETERS and EMPLOYEES using the following queries −
postgres=# CREATE TABLE CRICKETERS (
First_Name VARCHAR(255), Last_Name VARCHAR(255), Age int,
Place_Of_Birth VARCHAR(255), Country VARCHAR(255)
);
CREATE TABLE
postgres=#
postgres=# CREATE TABLE EMPLOYEE(
FIRST_NAME CHAR(20) NOT NULL, LAST_NAME CHAR(20),
AGE INT, SEX CHAR(1), INCOME FLOAT
);
CREATE TABLE
postgres=#
Now if you verify the list of tables using the “\dt” command, you can see the above created tables as −
postgres=# \dt;
List of relations
Schema | Name | Type | Owner
--------+------------+-------+----------
public | cricketers | table | postgres
public | employee | table | postgres
(2 rows)
postgres=#
Following statement deletes the table named Employee from the database −
postgres=# DROP table employee;
DROP TABLE
Since you have deleted the Employee table, if you retrieve the list of tables again, you can observe only one table in it.
postgres=# \dt;
List of relations
Schema | Name | Type | Owner
--------+------------+-------+----------
public | cricketers | table | postgres
(1 row)
postgres=#
If you try to delete the Employee table again, since you have already deleted it, you will get an error saying “table does not exist” as shown below −
postgres=# DROP table employee;
ERROR: table "employee" does not exist
postgres=#
To resolve this, you can use the IF EXISTS clause along with the DELTE statement. This removes the table if it exists else skips the DLETE operation.
postgres=# DROP table IF EXISTS employee;
NOTICE: table "employee" does not exist, skipping
DROP TABLE
postgres=#
You can drop a table whenever you need to, using the DROP statement. But you need to be very careful while deleting any existing table because the data lost will not be recovered after deleting a table.
import psycopg2
#establishing the connection
conn = psycopg2.connect(database="mydb", user='postgres', password='password', host='127.0.0.1', port= '5432')
#Setting auto commit false
conn.autocommit = True
#Creating a cursor object using the cursor() method
cursor = conn.cursor()
#Doping EMPLOYEE table if already exists
cursor.execute("DROP TABLE emp")
print("Table dropped... ")
#Commit your changes in the database
conn.commit()
#Closing the connection
conn.close()
#Table dropped...
187 Lectures
17.5 hours
Malhar Lathkar
55 Lectures
8 hours
Arnab Chakraborty
136 Lectures
11 hours
In28Minutes Official
75 Lectures
13 hours
Eduonix Learning Solutions
70 Lectures
8.5 hours
Lets Kode It
63 Lectures
6 hours
Abhilash Nelson
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2168,
"s": 2090,
"text": "You can drop a table from PostgreSQL database using the DROP TABLE statement."
},
{
"code": null,
"e": 2236,
"s": 2168,
"text": "Following is the syntax of the DROP TABLE statement in PostgreSQL −"
},
{
"code": null,
"e": 2260,
"s": 2236,
"text": "DROP TABLE table_name;\n"
},
{
"code": null,
"e": 2359,
"s": 2260,
"text": "Assume we have created two tables with name CRICKETERS and EMPLOYEES using the following queries −"
},
{
"code": null,
"e": 2691,
"s": 2359,
"text": "postgres=# CREATE TABLE CRICKETERS (\n First_Name VARCHAR(255), Last_Name VARCHAR(255), Age int, \n Place_Of_Birth VARCHAR(255), Country VARCHAR(255)\n);\nCREATE TABLE\npostgres=#\npostgres=# CREATE TABLE EMPLOYEE(\n FIRST_NAME CHAR(20) NOT NULL, LAST_NAME CHAR(20), \n AGE INT, SEX CHAR(1), INCOME FLOAT\n);\nCREATE TABLE\npostgres=#"
},
{
"code": null,
"e": 2795,
"s": 2691,
"text": "Now if you verify the list of tables using the “\\dt” command, you can see the above created tables as −"
},
{
"code": null,
"e": 3020,
"s": 2795,
"text": "postgres=# \\dt;\n List of relations\n Schema | Name | Type | Owner\n--------+------------+-------+----------\n public | cricketers | table | postgres\n public | employee | table | postgres\n(2 rows)\npostgres=#\n"
},
{
"code": null,
"e": 3093,
"s": 3020,
"text": "Following statement deletes the table named Employee from the database −"
},
{
"code": null,
"e": 3137,
"s": 3093,
"text": "postgres=# DROP table employee;\nDROP TABLE\n"
},
{
"code": null,
"e": 3260,
"s": 3137,
"text": "Since you have deleted the Employee table, if you retrieve the list of tables again, you can observe only one table in it."
},
{
"code": null,
"e": 3446,
"s": 3260,
"text": "postgres=# \\dt;\n List of relations\nSchema | Name | Type | Owner\n--------+------------+-------+----------\npublic | cricketers | table | postgres\n(1 row)\n\n\npostgres=#\n"
},
{
"code": null,
"e": 3597,
"s": 3446,
"text": "If you try to delete the Employee table again, since you have already deleted it, you will get an error saying “table does not exist” as shown below −"
},
{
"code": null,
"e": 3680,
"s": 3597,
"text": "postgres=# DROP table employee;\nERROR: table \"employee\" does not exist\npostgres=#\n"
},
{
"code": null,
"e": 3830,
"s": 3680,
"text": "To resolve this, you can use the IF EXISTS clause along with the DELTE statement. This removes the table if it exists else skips the DLETE operation."
},
{
"code": null,
"e": 3945,
"s": 3830,
"text": "postgres=# DROP table IF EXISTS employee;\nNOTICE: table \"employee\" does not exist, skipping\nDROP TABLE\npostgres=#\n"
},
{
"code": null,
"e": 4148,
"s": 3945,
"text": "You can drop a table whenever you need to, using the DROP statement. But you need to be very careful while deleting any existing table because the data lost will not be recovered after deleting a table."
},
{
"code": null,
"e": 4623,
"s": 4148,
"text": "import psycopg2\n#establishing the connection\nconn = psycopg2.connect(database=\"mydb\", user='postgres', password='password', host='127.0.0.1', port= '5432')\n\n#Setting auto commit false\nconn.autocommit = True\n\n#Creating a cursor object using the cursor() method\ncursor = conn.cursor()\n\n#Doping EMPLOYEE table if already exists\ncursor.execute(\"DROP TABLE emp\")\nprint(\"Table dropped... \")\n\n#Commit your changes in the database\nconn.commit()\n\n#Closing the connection\nconn.close()"
},
{
"code": null,
"e": 4642,
"s": 4623,
"text": "#Table dropped...\n"
},
{
"code": null,
"e": 4679,
"s": 4642,
"text": "\n 187 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 4695,
"s": 4679,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 4728,
"s": 4695,
"text": "\n 55 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 4747,
"s": 4728,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 4782,
"s": 4747,
"text": "\n 136 Lectures \n 11 hours \n"
},
{
"code": null,
"e": 4804,
"s": 4782,
"text": " In28Minutes Official"
},
{
"code": null,
"e": 4838,
"s": 4804,
"text": "\n 75 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 4866,
"s": 4838,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 4901,
"s": 4866,
"text": "\n 70 Lectures \n 8.5 hours \n"
},
{
"code": null,
"e": 4915,
"s": 4901,
"text": " Lets Kode It"
},
{
"code": null,
"e": 4948,
"s": 4915,
"text": "\n 63 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 4965,
"s": 4948,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 4972,
"s": 4965,
"text": " Print"
},
{
"code": null,
"e": 4983,
"s": 4972,
"text": " Add Notes"
}
] |
C++ Array Library - at() Function
|
The C++ function std::array::at() returns a reference to the element present at location N in given array container.
Following is the declaration for std::array::at() function form std::array header.
reference at(size_type n);
cont_referece at(size_t n) const;
N − index of an element in the array.
Returns a element present at index N in given array if N is valid index otherwise throws out_of_range exception.
If array object is const-qualified method returns const reference otherwise it returns reference.
This member function throws out_of_range expception if value of N is not valid array index.
Constant i.e. O(1)
In below example step-1 prints array contents without exception. Step-2 shows exception handling using try-catch block.
#include <iostream>
#include <array>
#include <stdexcept>
using namespace std;
int main(void) {
array<int, 5> arr = {10, 20, 30, 40, 50};
size_t i;
/* print array contents */
for (i = 0; i < 5; ++i)
cout << arr.at(i) << " ";
cout << endl;
/* generate out_of_range exception. */
try {
arr.at(10);
} catch(out_of_range e) {
cout << "out_of_range expcepiton caught for " << e.what() << endl;
}
return 0;
}
Let us compile and run the above program, this will produce the following result −
10 20 30 40 50
out_of_range expcepiton caught for array::at: __n (which is 10) >= _Nm (which is 5)
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2720,
"s": 2603,
"text": "The C++ function std::array::at() returns a reference to the element present at location N in given array container."
},
{
"code": null,
"e": 2803,
"s": 2720,
"text": "Following is the declaration for std::array::at() function form std::array header."
},
{
"code": null,
"e": 2864,
"s": 2803,
"text": "reference at(size_type n);\ncont_referece at(size_t n) const;"
},
{
"code": null,
"e": 2902,
"s": 2864,
"text": "N − index of an element in the array."
},
{
"code": null,
"e": 3015,
"s": 2902,
"text": "Returns a element present at index N in given array if N is valid index otherwise throws out_of_range exception."
},
{
"code": null,
"e": 3113,
"s": 3015,
"text": "If array object is const-qualified method returns const reference otherwise it returns reference."
},
{
"code": null,
"e": 3205,
"s": 3113,
"text": "This member function throws out_of_range expception if value of N is not valid array index."
},
{
"code": null,
"e": 3224,
"s": 3205,
"text": "Constant i.e. O(1)"
},
{
"code": null,
"e": 3344,
"s": 3224,
"text": "In below example step-1 prints array contents without exception. Step-2 shows exception handling using try-catch block."
},
{
"code": null,
"e": 3800,
"s": 3344,
"text": "#include <iostream>\n#include <array>\n#include <stdexcept>\n\nusing namespace std;\n\nint main(void) {\n array<int, 5> arr = {10, 20, 30, 40, 50};\n size_t i;\n\n /* print array contents */\n for (i = 0; i < 5; ++i)\n cout << arr.at(i) << \" \";\n cout << endl;\n\n /* generate out_of_range exception. */\n try {\n arr.at(10);\n } catch(out_of_range e) {\n cout << \"out_of_range expcepiton caught for \" << e.what() << endl;\n }\n\n return 0;\n}"
},
{
"code": null,
"e": 3883,
"s": 3800,
"text": "Let us compile and run the above program, this will produce the following result −"
},
{
"code": null,
"e": 3984,
"s": 3883,
"text": "10 20 30 40 50 \nout_of_range expcepiton caught for array::at: __n (which is 10) >= _Nm (which is 5)\n"
},
{
"code": null,
"e": 3991,
"s": 3984,
"text": " Print"
},
{
"code": null,
"e": 4002,
"s": 3991,
"text": " Add Notes"
}
] |
Choosing between TensorFlow/Keras, BigQuery ML, and AutoML Natural Language for text classification | by Lak Lakshmanan | Towards Data Science
|
Google Cloud Platform offers you three1 ways to carry out machine learning:
Keras with a TensorFlow backend to build custom, deep learning models that are trained on Cloud ML Engine
BigQuery ML to build custom ML models on structured data using just SQL
Auto ML to train state-of-the-art deep learning models on your data without writing any code
Choose between them based on your skill set, how important additional accuracy is, and how much time/effort you are willing to devote to the problem. Use BigQuery ML for quick problem formulation, experimentation, and easy, low-cost machine learning. Once you identify a viable ML problem using BQML, use Auto ML for code-free, state-of-the-art models. Hand-roll your own custom models only for problems where you have lots of data and enough time/effort to devote.
In this article, I will compare the three approaches on a text classification problem so that you can see why I’m recommending what I am recommending.
I explain the problem and the deep learning solution in detail elsewhere, so this section will be very brief.
The task is that given the title of an article, I want to be able to identify where it was published. The training dataset comes from articles posted on Hacker News (there’s a public dataset of these in BigQuery). For example, here are some of the titles whose source is GitHub:
The model code to create a Keras model that uses a word embedding layer, convolutional layers, and dropout:
model = models.Sequential()num_features = min(len(word_index) + 1, TOP_K)model.add(Embedding(input_dim=num_features, output_dim=embedding_dim, input_length=MAX_SEQUENCE_LENGTH))model.add(Dropout(rate=dropout_rate))model.add(Conv1D(filters=filters, kernel_size=kernel_size, activation='relu', bias_initializer='random_uniform', padding='same'))model.add(MaxPooling1D(pool_size=pool_size))model.add(Conv1D(filters=filters * 2, kernel_size=kernel_size, activation='relu', bias_initializer='random_uniform', padding='same'))model.add(GlobalAveragePooling1D())model.add(Dropout(rate=dropout_rate))model.add(Dense(len(CLASSES), activation='softmax'))# Compile model with learning parameters.optimizer = tf.keras.optimizers.Adam(lr=learning_rate)model.compile(optimizer=optimizer, loss='sparse_categorical_crossentropy', metrics=['acc'])estimator = tf.keras.estimator.model_to_estimator(keras_model=model, model_dir=model_dir, config=config)
This is then trained on Cloud ML Engine as shown in this Jupyter notebook:
gcloud ml-engine jobs submit training $JOBNAME \ --region=$REGION \ --module-name=trainer.task \ --package-path=${PWD}/txtclsmodel/trainer \ --job-dir=$OUTDIR \ --scale-tier=BASIC_GPU \ --runtime-version=$TFVERSION \ -- \ --output_dir=$OUTDIR \ --train_data_path=gs://${BUCKET}/txtcls/train.tsv \ --eval_data_path=gs://${BUCKET}/txtcls/eval.tsv \ --num_epochs=5
It took me a couple of days to develop the original TensorFlow model, my colleague vijaykr a day to modify it to use Keras, and maybe a day to train it and troubleshoot it.
We got about 80% accuracy. To do better, we’d probably need a lot more data (92k examples is insufficient to gain the benefits of using a custom deep learning model) and perhaps incorporate more preprocessing (such as removing stop words, stemming words, using a reusable embedding, etc.).
When using BigQuery ML, convolutional neural networks, embeddings, etc. are (not yet anyway) an option, so I dropped down to using a linear model on a bag-of-words. The point of BigQuery ML is to provide a quick, convenient way to build ML models on structured and semi-structured data.
Splitting the titles word-by-word and training a logistic regression model (i.e., a linear classifier) on the first 5 words of the title (using more words doesn’t help all that much):
#standardsqlCREATE OR REPLACE MODEL advdata.txtclassOPTIONS(model_type='logistic_reg', input_label_cols=['source'])ASWITH extracted AS (SELECT source, REGEXP_REPLACE(LOWER(REGEXP_REPLACE(title, '[^a-zA-Z0-9 $.-]', ' ')), " ", " ") AS title FROM (SELECT ARRAY_REVERSE(SPLIT(REGEXP_EXTRACT(url, '.*://(.[^/]+)/'), '.'))[OFFSET(1)] AS source, title FROM `bigquery-public-data.hacker_news.stories` WHERE REGEXP_CONTAINS(REGEXP_EXTRACT(url, '.*://(.[^/]+)/'), '.com$') AND LENGTH(title) > 10 )), ds AS (SELECT ARRAY_CONCAT(SPLIT(title, " "), ['NULL', 'NULL', 'NULL', 'NULL', 'NULL']) AS words, source FROM extractedWHERE (source = 'github' OR source = 'nytimes' OR source = 'techcrunch'))SELECT source, words[OFFSET(0)] AS word1, words[OFFSET(1)] AS word2, words[OFFSET(2)] AS word3,words[OFFSET(3)] AS word4,words[OFFSET(4)] AS word5FROM ds
This was fast. The SQL query above is the full enchilada. There is nothing more to it. The model training itself took only a few minutes. I got 78% accuracy which compares quite favorably to the 80% I got with the custom Keras CNN model.
Once trained, batch predictions using BigQuery are easy:
SELECT * FROM ML.PREDICT(MODEL advdata.txtclass,(SELECT 'government' AS word1, 'shutdown' AS word2, 'leaves' AS word3, 'workers' AS word4, 'reeling' AS word5))
Online predictions using BigQuery can be accomplished by exporting the weights into a web application.
The third option I tried is the code-free option that, nevertheless, uses state-of-the-art models and techniques underneath. Because this is a text classification problem, the Auto ML approach to use is Auto ML Natural Language.
The first step is to launch Auto ML Natural Language from the GCP web console:
Follow the prompts and a bucket will be created to hold the dataset that you will use to train the model.
Where BigQuery ML requires you to know SQL, AutoML just requires that you create a dataset in one of the formats the tool understands. The tool understands CSV files arranged as follows:
text, label
The text itself can either be a URL to a file containing the actual text (this is useful if you have multi-line text, such as reviews or entire documents) or it can be the plain text item itself. If you are providing the text item string directly, you need to put it in quotes.
So, our first step is export a CSV file from BigQuery in the right format. This was my query2:
WITH extracted AS (SELECT STRING_AGG(source,',') as source, title FROM (SELECT DISTINCT source, TRIM(LOWER(REGEXP_REPLACE(title, '[^a-zA-Z0-9 $.-]', ' '))) AS title FROM (SELECT ARRAY_REVERSE(SPLIT(REGEXP_EXTRACT(url, '.*://(.[^/]+)/'), '.'))[OFFSET(1)] AS source, title FROM `bigquery-public-data.hacker_news.stories` WHERE REGEXP_CONTAINS(REGEXP_EXTRACT(url, '.*://(.[^/]+)/'), '.com$') AND LENGTH(title) > 10 ) )GROUP BY title)SELECT title, source FROM extractedWHERE (source = 'github' OR source = 'nytimes' OR source = 'techcrunch')
Which yields the following dataset:
Note that I have stripped out punctuation and special characters. Whitespace has been trimmed, and SELECT distinct is used to used to discard duplicates and articles that appear in multiple classes (AutoML will warn you about duplicates, and can deal with multi-class labels, but removing them is cleaner).
I saved the result of the query as a table using the BigQuery UI:
and then exported the table to a CSV file:
Next step is to use the Auto ML UI to create a dataset from the CSV file on Cloud Storage:
The dataset takes about 20 minutes to ingest. At the end, we get a screen full of text items:
The current Auto ML limit is 100k rows, so our 92k dataset is definitely pushing some boundaries. A smaller dataset will get ingested faster.
Why do we have a label called “source” with only example? The CSV file had a header line (source, title) and that too has been ingested! Fortunately, AutoML allows us to edit the text items in the GUI itself. So, I deleted the extra label and its corresponding text.
Training is as easy as clicking on a button.
Auto ML then proceeds to try various embeddings, and various architectures and does hyperparameter tuning to come up with a good solution to the problem.
It takes 5 hours.
Once the model is trained, we get a bunch of evaluation statistics: precision, recall, AUC curve, etc. But we also get the actual confusion matrix from which we can compute anything else we want:
The overall accuracy is about 86% — higher even than our custom Keras CNN model. Why? Because Auto ML is able to take advantage of transfer learning from models built on Google datasets on language use, i.e. includes data that we did not have available to our Keras model. Also, because of the availability of all that data to transfer learn from, the model architecture can be more complex (read: more deep).
The trained AutoML model is already deployed and available for prediction. We can send it a request and get back the predicted source of the article:
Notice that the model is much more confident than the BQML one (although both gave the same correct answer), a confidence driven by the fact that this Auto ML model was trained on more data and is built specifically for text classification problems.
I tried another article title from today’s headlines and the model nailed it as being from TechCrunch:
While this article is primarily about text classification, the general conclusions and advice carry over to most ML problems:
Use BigQuery ML for easy, low-cost machine learning and quick experimentation to see if ML is viable on your data. Sometimes, the accuracy you get with BQML is sufficient, and you will simply stop here.
Once you identify a viable ML problem using BQML, use Auto ML for code-free, state-of-the-art models. Text classification, for example, is a very specialized field with high-dimensional inputs. So, you can do better with a customized solution (i.e., Auto ML Natural Language) than with a structured data approach that just uses bag-of-words.
Hand-roll your own custom models only for problems where you have lots of data and enough time/effort to devote. Use AutoML as a benchmark. If, you can not beat Auto ML after some reasonable effort, stop wasting time. Just go with Auto ML.
1 There are a few other ways to do machine learning on GCP. You can do xgboost or scikit-learn in ML Engine. The Deep Learning VM supports PyTorch. Spark ML works well on Cloud Dataproc. And of course, you can use Google Compute Engine or Google Kubernetes Engine and install any ML framework you want. But in this article, I’ll focus on these three.
2Thanks to Greg Mikels for improving my original AutoML query to remove duplicates and cross-posted articles.
|
[
{
"code": null,
"e": 122,
"s": 46,
"text": "Google Cloud Platform offers you three1 ways to carry out machine learning:"
},
{
"code": null,
"e": 228,
"s": 122,
"text": "Keras with a TensorFlow backend to build custom, deep learning models that are trained on Cloud ML Engine"
},
{
"code": null,
"e": 300,
"s": 228,
"text": "BigQuery ML to build custom ML models on structured data using just SQL"
},
{
"code": null,
"e": 393,
"s": 300,
"text": "Auto ML to train state-of-the-art deep learning models on your data without writing any code"
},
{
"code": null,
"e": 859,
"s": 393,
"text": "Choose between them based on your skill set, how important additional accuracy is, and how much time/effort you are willing to devote to the problem. Use BigQuery ML for quick problem formulation, experimentation, and easy, low-cost machine learning. Once you identify a viable ML problem using BQML, use Auto ML for code-free, state-of-the-art models. Hand-roll your own custom models only for problems where you have lots of data and enough time/effort to devote."
},
{
"code": null,
"e": 1010,
"s": 859,
"text": "In this article, I will compare the three approaches on a text classification problem so that you can see why I’m recommending what I am recommending."
},
{
"code": null,
"e": 1120,
"s": 1010,
"text": "I explain the problem and the deep learning solution in detail elsewhere, so this section will be very brief."
},
{
"code": null,
"e": 1399,
"s": 1120,
"text": "The task is that given the title of an article, I want to be able to identify where it was published. The training dataset comes from articles posted on Hacker News (there’s a public dataset of these in BigQuery). For example, here are some of the titles whose source is GitHub:"
},
{
"code": null,
"e": 1507,
"s": 1399,
"text": "The model code to create a Keras model that uses a word embedding layer, convolutional layers, and dropout:"
},
{
"code": null,
"e": 2712,
"s": 1507,
"text": "model = models.Sequential()num_features = min(len(word_index) + 1, TOP_K)model.add(Embedding(input_dim=num_features, output_dim=embedding_dim, input_length=MAX_SEQUENCE_LENGTH))model.add(Dropout(rate=dropout_rate))model.add(Conv1D(filters=filters, kernel_size=kernel_size, activation='relu', bias_initializer='random_uniform', padding='same'))model.add(MaxPooling1D(pool_size=pool_size))model.add(Conv1D(filters=filters * 2, kernel_size=kernel_size, activation='relu', bias_initializer='random_uniform', padding='same'))model.add(GlobalAveragePooling1D())model.add(Dropout(rate=dropout_rate))model.add(Dense(len(CLASSES), activation='softmax'))# Compile model with learning parameters.optimizer = tf.keras.optimizers.Adam(lr=learning_rate)model.compile(optimizer=optimizer, loss='sparse_categorical_crossentropy', metrics=['acc'])estimator = tf.keras.estimator.model_to_estimator(keras_model=model, model_dir=model_dir, config=config)"
},
{
"code": null,
"e": 2787,
"s": 2712,
"text": "This is then trained on Cloud ML Engine as shown in this Jupyter notebook:"
},
{
"code": null,
"e": 3149,
"s": 2787,
"text": "gcloud ml-engine jobs submit training $JOBNAME \\ --region=$REGION \\ --module-name=trainer.task \\ --package-path=${PWD}/txtclsmodel/trainer \\ --job-dir=$OUTDIR \\ --scale-tier=BASIC_GPU \\ --runtime-version=$TFVERSION \\ -- \\ --output_dir=$OUTDIR \\ --train_data_path=gs://${BUCKET}/txtcls/train.tsv \\ --eval_data_path=gs://${BUCKET}/txtcls/eval.tsv \\ --num_epochs=5"
},
{
"code": null,
"e": 3322,
"s": 3149,
"text": "It took me a couple of days to develop the original TensorFlow model, my colleague vijaykr a day to modify it to use Keras, and maybe a day to train it and troubleshoot it."
},
{
"code": null,
"e": 3612,
"s": 3322,
"text": "We got about 80% accuracy. To do better, we’d probably need a lot more data (92k examples is insufficient to gain the benefits of using a custom deep learning model) and perhaps incorporate more preprocessing (such as removing stop words, stemming words, using a reusable embedding, etc.)."
},
{
"code": null,
"e": 3899,
"s": 3612,
"text": "When using BigQuery ML, convolutional neural networks, embeddings, etc. are (not yet anyway) an option, so I dropped down to using a linear model on a bag-of-words. The point of BigQuery ML is to provide a quick, convenient way to build ML models on structured and semi-structured data."
},
{
"code": null,
"e": 4083,
"s": 3899,
"text": "Splitting the titles word-by-word and training a logistic regression model (i.e., a linear classifier) on the first 5 words of the title (using more words doesn’t help all that much):"
},
{
"code": null,
"e": 4940,
"s": 4083,
"text": "#standardsqlCREATE OR REPLACE MODEL advdata.txtclassOPTIONS(model_type='logistic_reg', input_label_cols=['source'])ASWITH extracted AS (SELECT source, REGEXP_REPLACE(LOWER(REGEXP_REPLACE(title, '[^a-zA-Z0-9 $.-]', ' ')), \" \", \" \") AS title FROM (SELECT ARRAY_REVERSE(SPLIT(REGEXP_EXTRACT(url, '.*://(.[^/]+)/'), '.'))[OFFSET(1)] AS source, title FROM `bigquery-public-data.hacker_news.stories` WHERE REGEXP_CONTAINS(REGEXP_EXTRACT(url, '.*://(.[^/]+)/'), '.com$') AND LENGTH(title) > 10 )), ds AS (SELECT ARRAY_CONCAT(SPLIT(title, \" \"), ['NULL', 'NULL', 'NULL', 'NULL', 'NULL']) AS words, source FROM extractedWHERE (source = 'github' OR source = 'nytimes' OR source = 'techcrunch'))SELECT source, words[OFFSET(0)] AS word1, words[OFFSET(1)] AS word2, words[OFFSET(2)] AS word3,words[OFFSET(3)] AS word4,words[OFFSET(4)] AS word5FROM ds"
},
{
"code": null,
"e": 5178,
"s": 4940,
"text": "This was fast. The SQL query above is the full enchilada. There is nothing more to it. The model training itself took only a few minutes. I got 78% accuracy which compares quite favorably to the 80% I got with the custom Keras CNN model."
},
{
"code": null,
"e": 5235,
"s": 5178,
"text": "Once trained, batch predictions using BigQuery are easy:"
},
{
"code": null,
"e": 5395,
"s": 5235,
"text": "SELECT * FROM ML.PREDICT(MODEL advdata.txtclass,(SELECT 'government' AS word1, 'shutdown' AS word2, 'leaves' AS word3, 'workers' AS word4, 'reeling' AS word5))"
},
{
"code": null,
"e": 5498,
"s": 5395,
"text": "Online predictions using BigQuery can be accomplished by exporting the weights into a web application."
},
{
"code": null,
"e": 5727,
"s": 5498,
"text": "The third option I tried is the code-free option that, nevertheless, uses state-of-the-art models and techniques underneath. Because this is a text classification problem, the Auto ML approach to use is Auto ML Natural Language."
},
{
"code": null,
"e": 5806,
"s": 5727,
"text": "The first step is to launch Auto ML Natural Language from the GCP web console:"
},
{
"code": null,
"e": 5912,
"s": 5806,
"text": "Follow the prompts and a bucket will be created to hold the dataset that you will use to train the model."
},
{
"code": null,
"e": 6099,
"s": 5912,
"text": "Where BigQuery ML requires you to know SQL, AutoML just requires that you create a dataset in one of the formats the tool understands. The tool understands CSV files arranged as follows:"
},
{
"code": null,
"e": 6111,
"s": 6099,
"text": "text, label"
},
{
"code": null,
"e": 6389,
"s": 6111,
"text": "The text itself can either be a URL to a file containing the actual text (this is useful if you have multi-line text, such as reviews or entire documents) or it can be the plain text item itself. If you are providing the text item string directly, you need to put it in quotes."
},
{
"code": null,
"e": 6484,
"s": 6389,
"text": "So, our first step is export a CSV file from BigQuery in the right format. This was my query2:"
},
{
"code": null,
"e": 7062,
"s": 6484,
"text": "WITH extracted AS (SELECT STRING_AGG(source,',') as source, title FROM (SELECT DISTINCT source, TRIM(LOWER(REGEXP_REPLACE(title, '[^a-zA-Z0-9 $.-]', ' '))) AS title FROM (SELECT ARRAY_REVERSE(SPLIT(REGEXP_EXTRACT(url, '.*://(.[^/]+)/'), '.'))[OFFSET(1)] AS source, title FROM `bigquery-public-data.hacker_news.stories` WHERE REGEXP_CONTAINS(REGEXP_EXTRACT(url, '.*://(.[^/]+)/'), '.com$') AND LENGTH(title) > 10 ) )GROUP BY title)SELECT title, source FROM extractedWHERE (source = 'github' OR source = 'nytimes' OR source = 'techcrunch')"
},
{
"code": null,
"e": 7098,
"s": 7062,
"text": "Which yields the following dataset:"
},
{
"code": null,
"e": 7405,
"s": 7098,
"text": "Note that I have stripped out punctuation and special characters. Whitespace has been trimmed, and SELECT distinct is used to used to discard duplicates and articles that appear in multiple classes (AutoML will warn you about duplicates, and can deal with multi-class labels, but removing them is cleaner)."
},
{
"code": null,
"e": 7471,
"s": 7405,
"text": "I saved the result of the query as a table using the BigQuery UI:"
},
{
"code": null,
"e": 7514,
"s": 7471,
"text": "and then exported the table to a CSV file:"
},
{
"code": null,
"e": 7605,
"s": 7514,
"text": "Next step is to use the Auto ML UI to create a dataset from the CSV file on Cloud Storage:"
},
{
"code": null,
"e": 7699,
"s": 7605,
"text": "The dataset takes about 20 minutes to ingest. At the end, we get a screen full of text items:"
},
{
"code": null,
"e": 7841,
"s": 7699,
"text": "The current Auto ML limit is 100k rows, so our 92k dataset is definitely pushing some boundaries. A smaller dataset will get ingested faster."
},
{
"code": null,
"e": 8108,
"s": 7841,
"text": "Why do we have a label called “source” with only example? The CSV file had a header line (source, title) and that too has been ingested! Fortunately, AutoML allows us to edit the text items in the GUI itself. So, I deleted the extra label and its corresponding text."
},
{
"code": null,
"e": 8153,
"s": 8108,
"text": "Training is as easy as clicking on a button."
},
{
"code": null,
"e": 8307,
"s": 8153,
"text": "Auto ML then proceeds to try various embeddings, and various architectures and does hyperparameter tuning to come up with a good solution to the problem."
},
{
"code": null,
"e": 8325,
"s": 8307,
"text": "It takes 5 hours."
},
{
"code": null,
"e": 8521,
"s": 8325,
"text": "Once the model is trained, we get a bunch of evaluation statistics: precision, recall, AUC curve, etc. But we also get the actual confusion matrix from which we can compute anything else we want:"
},
{
"code": null,
"e": 8931,
"s": 8521,
"text": "The overall accuracy is about 86% — higher even than our custom Keras CNN model. Why? Because Auto ML is able to take advantage of transfer learning from models built on Google datasets on language use, i.e. includes data that we did not have available to our Keras model. Also, because of the availability of all that data to transfer learn from, the model architecture can be more complex (read: more deep)."
},
{
"code": null,
"e": 9081,
"s": 8931,
"text": "The trained AutoML model is already deployed and available for prediction. We can send it a request and get back the predicted source of the article:"
},
{
"code": null,
"e": 9331,
"s": 9081,
"text": "Notice that the model is much more confident than the BQML one (although both gave the same correct answer), a confidence driven by the fact that this Auto ML model was trained on more data and is built specifically for text classification problems."
},
{
"code": null,
"e": 9434,
"s": 9331,
"text": "I tried another article title from today’s headlines and the model nailed it as being from TechCrunch:"
},
{
"code": null,
"e": 9560,
"s": 9434,
"text": "While this article is primarily about text classification, the general conclusions and advice carry over to most ML problems:"
},
{
"code": null,
"e": 9763,
"s": 9560,
"text": "Use BigQuery ML for easy, low-cost machine learning and quick experimentation to see if ML is viable on your data. Sometimes, the accuracy you get with BQML is sufficient, and you will simply stop here."
},
{
"code": null,
"e": 10105,
"s": 9763,
"text": "Once you identify a viable ML problem using BQML, use Auto ML for code-free, state-of-the-art models. Text classification, for example, is a very specialized field with high-dimensional inputs. So, you can do better with a customized solution (i.e., Auto ML Natural Language) than with a structured data approach that just uses bag-of-words."
},
{
"code": null,
"e": 10345,
"s": 10105,
"text": "Hand-roll your own custom models only for problems where you have lots of data and enough time/effort to devote. Use AutoML as a benchmark. If, you can not beat Auto ML after some reasonable effort, stop wasting time. Just go with Auto ML."
},
{
"code": null,
"e": 10696,
"s": 10345,
"text": "1 There are a few other ways to do machine learning on GCP. You can do xgboost or scikit-learn in ML Engine. The Deep Learning VM supports PyTorch. Spark ML works well on Cloud Dataproc. And of course, you can use Google Compute Engine or Google Kubernetes Engine and install any ML framework you want. But in this article, I’ll focus on these three."
}
] |
Find the two repeating elements in a given array - GeeksforGeeks
|
13 Mar, 2022
You are given an array of n+2 elements. All elements of the array are in range 1 to n. And all elements occur once except two numbers which occur twice. Find the two repeating numbers.
Example:
Input: arr = [4, 2, 4, 5, 2, 3, 1] n = 5Output:4 2Explanation:The above array has n + 2 = 7 elements with all elements occurring once except 2 and 4 which occur twice. So the output should be 4 2.
Method 1 (Basic)
Use two loops. In the outer loop, pick elements one by one and count the number of occurrences of the picked element in the inner loop. This method doesn’t use the other useful data provided in questions like range of numbers is between 1 to n and there are only two repeating elements.
C++
C
Java
Python3
C#
PHP
Javascript
// C++ program to Find the two repeating// elements in a given array#include<bits/stdc++.h>using namespace std; void printTwoRepeatNumber(int arr[], int size){ int i, j, display=0; int visited[size]; for(i = 0; i < size; i++) { if (visited[i] == 1) { continue; } int count = 0; for(j = i + 1; j < size; j++) { if(arr[i] == arr[j]) { visited[j] = 1; ++count; break; } } if ( (count > 0) && (display < 2)){ ++display; cout<<"repeating element = "<< arr[i]<<endl; } }} int main(){ int arr[] = {4, 2, 5, 2, 3, 3, 4, 4, 1, 1}; int arr_size = sizeof(arr)/sizeof(arr[0]); printTwoRepeatNumber(arr, arr_size);}
#include<stdio.h>#include<stdlib.h>void printRepeating(int arr[], int size){ int i, j; printf(" Repeating elements are "); for(i = 0; i < size-1; i++) for(j = i+1; j < size; j++) if(arr[i] == arr[j]) printf(" %d ", arr[i]);} int main(){ int arr[] = {4, 2, 4, 5, 2, 3, 1}; int arr_size = sizeof(arr)/sizeof(arr[0]); printRepeating(arr, arr_size); getchar(); return 0;}
class RepeatElement{ void printRepeating(int arr[], int size) { int i, j; System.out.println("Repeated Elements are :"); for (i = 0; i < size-1; i++) { for (j = i + 1; j < size; j++) { if (arr[i] == arr[j]) System.out.print(arr[i] + " "); } } } public static void main(String[] args) { RepeatElement repeat = new RepeatElement(); int arr[] = {4, 2, 4, 5, 2, 3, 1}; int arr_size = arr.length; repeat.printRepeating(arr, arr_size); }}
# Python3 program to Find the two# repeating elements in a given array def printRepeating(arr, size): print("Repeating elements are ", end = '') for i in range (0, size-1): for j in range (i + 1, size): if arr[i] == arr[j]: print(arr[i], end = ' ') # Driver codearr = [4, 2, 4, 5, 2, 3, 1]arr_size = len(arr)printRepeating(arr, arr_size) # This code is contributed by Smitha Dinesh Semwal
using System; class GFG{ static void printRepeating(int []arr, int size) { int i, j; Console.Write("Repeated Elements are :"); for (i = 0; i < size-1; i++) { for (j = i + 1; j < size; j++) { if (arr[i] == arr[j]) Console.Write(arr[i] + " "); } } } // driver code public static void Main() { int []arr = {4, 2, 4, 5, 2, 3, 1}; int arr_size = arr.Length; printRepeating(arr, arr_size); }} // This code is contributed by Sam007
<?php// PHP program to Find the two// repeating elements in// a given array function printRepeating($arr, $size){ $i; $j; echo " Repeating elements are "; for($i = 0; $i < $size-1; $i++) for($j = $i + 1; $j < $size; $j++) if($arr[$i] == $arr[$j]) echo $arr[$i], " ";} // Driver Code$arr = array(4, 2, 4, 5, 2, 3, 1);$arr_size = sizeof($arr, 0);printRepeating($arr, $arr_size); // This code is contributed by Ajit?>
<script> function printRepeating(arr , size) { var i, j; document.write("Repeated Elements are :"); for (i = 0; i < size-1; i++) { for (j = i + 1; j < size; j++) { if (arr[i] == arr[j]) document.write(arr[i] + " "); } } } var arr = [4, 2, 4, 5, 2, 3, 1];var arr_size = arr.length;printRepeating(arr, arr_size); // This code is contributed by 29AjayKumar</script>
Repeating elements are 4 2
Time Complexity: O(n*n) Auxiliary Space: O(1)
Method 2 (Use Count array) Traverse the array once. While traversing, keep track of count of all elements in the array using a temp array count[] of size n, when you see an element whose count is already set, print it as duplicate.This method uses the range given in the question to restrict the size of count[], but doesn’t use the data that there are only two repeating elements.
C++
C
Java
Python3
C#
PHP
Javascript
// C++ implementation of above approach#include <bits/stdc++.h>using namespace std; void printRepeating(int arr[], int size){ int *count = new int[sizeof(int)*(size - 2)]; int i; cout << " Repeating elements are "; for(i = 0; i < size; i++) { if(count[arr[i]] == 1) cout << arr[i] << " "; else count[arr[i]]++; }} // Driver codeint main(){ int arr[] = {4, 2, 4, 5, 2, 3, 1}; int arr_size = sizeof(arr)/sizeof(arr[0]); printRepeating(arr, arr_size); return 0;} // This is code is contributed by rathbhupendra
#include<stdio.h>#include<stdlib.h> void printRepeating(int arr[], int size){ int *count = (int *)calloc(sizeof(int), (size - 2)); int i; printf(" Repeating elements are "); for(i = 0; i < size; i++) { if(count[arr[i]] == 1) printf(" %d ", arr[i]); else count[arr[i]]++; } } int main(){ int arr[] = {4, 2, 4, 5, 2, 3, 1}; int arr_size = sizeof(arr)/sizeof(arr[0]); printRepeating(arr, arr_size); getchar(); return 0;}
class RepeatElement{ void printRepeating(int arr[], int size) { int count[] = new int[size]; int i; System.out.println("Repeated elements are : "); for (i = 0; i < size; i++) { if (count[arr[i]] == 1) System.out.print(arr[i] + " "); else count[arr[i]]++; } } public static void main(String[] args) { RepeatElement repeat = new RepeatElement(); int arr[] = {4, 2, 4, 5, 2, 3, 1}; int arr_size = arr.length; repeat.printRepeating(arr, arr_size); }}
# Python3 code for Find the two repeating# elements in a given array def printRepeating(arr,size) : count = [0] * size print(" Repeating elements are ",end = "") for i in range(0, size) : if(count[arr[i]] == 1) : print(arr[i], end = " ") else : count[arr[i]] = count[arr[i]] + 1 # Driver codearr = [4, 2, 4, 5, 2, 3, 1]arr_size = len(arr)printRepeating(arr, arr_size) # This code is contributed by Nikita Tiwari.
// C# program to Find the two// repeating elements in a given arrayusing System; class GFG{ static void printRepeating(int []arr, int size) { int []count = new int[size]; int i; Console.Write("Repeated elements are: "); for (i = 0; i < size; i++) { if (count[arr[i]] == 1) Console.Write(arr[i] + " "); else count[arr[i]]++; } } // driver code public static void Main() { int []arr = {4, 2, 4, 5, 2, 3, 1}; int arr_size = arr.Length; printRepeating(arr, arr_size); }} //This code is contributed by Sam007
<?php// PHP program to Find the two// repeating elements in a given arrayfunction printRepeating($arr, $size){ $count = array_fill(0, $size, 0); echo "Repeated elements are "; for ($i = 0; $i < $size; $i++) { if ($count[$arr[$i]] == 1) echo $arr[$i]." "; else $count[$arr[$i]]++; }} // Driver code$arr = array(4, 2, 4, 5, 2, 3, 1);$arr_size = count($arr); printRepeating($arr, $arr_size); // This code is contributed by mits?>
<script> // Javascript program to Find the two // repeating elements in a given array function printRepeating(arr, size) { let count = new Array(size); count.fill(0); let i; document.write("Repeating elements are "); for (i = 0; i < size; i++) { if (count[arr[i]] == 1) document.write(arr[i] + " "); else count[arr[i]]++; } } let arr = [4, 2, 4, 5, 2, 3, 1]; let arr_size = arr.length; printRepeating(arr, arr_size); </script>
Repeating elements are 4 2
Time Complexity: O(n) Auxiliary Space: O(n)
Method 3 (Make two equations)
Let the numbers which are being repeated are X and Y. We make two equations for X and Y and the simple task left is to solve the two equations. We know the sum of integers from 1 to n is n(n+1)/2 and product is n!. We calculate the sum of input array when this sum is subtracted from n(n+1)/2, we get X + Y because X and Y are the two numbers missing from set [1..n]. Similarly calculate the product of input array, when this product is divided from n!, we get X*Y. Given the sum and product of X and Y, we can find easily out X and Y.Let summation of all numbers in the array be S and product be PX + Y = S – n(n+1)/2 XY = P/n!Using the above two equations, we can find out X and Y. For array = 4 2 4 5 2 3 1, we get S = 21 and P as 960.X + Y = 21 – 15 = 6XY = 960/5! = 8X – Y = sqrt((X+Y)^2 – 4*XY) = sqrt(4) = 2Using below two equations, we easily get X = (6 + 2)/2 and Y = (6-2)/2 X + Y = 6 X – Y = 2Thanks to geek4u for suggesting this method. As pointed by Beginner, there can be an addition and multiplication overflow problem with this approach.
The methods 3 and 4 use all useful information given in the question :
C++
C
Java
Python3
C#
PHP
Javascript
#include <bits/stdc++.h>using namespace std; /* function to get factorial of n */int fact(int n); void printRepeating(int arr[], int size){ int S = 0; /* S is for sum of elements in arr[] */ int P = 1; /* P is for product of elements in arr[] */ int x, y; /* x and y are two repeating elements */ int D; /* D is for difference of x and y, i.e., x-y*/ int n = size - 2, i; /* Calculate Sum and Product of all elements in arr[] */ for(i = 0; i < size; i++) { S = S + arr[i]; P = P*arr[i]; } S = S - n*(n+1)/2; /* S is x + y now */ P = P/fact(n); /* P is x*y now */ D = sqrt(S*S - 4*P); /* D is x - y now */ x = (D + S)/2; y = (S - D)/2; cout<<"The two Repeating elements are "<<x<<" & "<<y;} int fact(int n){ return (n == 0)? 1 : n*fact(n-1);} // Driver codeint main(){ int arr[] = {4, 2, 4, 5, 2, 3, 1}; int arr_size = sizeof(arr)/sizeof(arr[0]); printRepeating(arr, arr_size); return 0;} // This code is contributed by rathbhupendra
#include<stdio.h>#include<stdlib.h>#include<math.h> /* function to get factorial of n */int fact(int n); void printRepeating(int arr[], int size){ int S = 0; /* S is for sum of elements in arr[] */ int P = 1; /* P is for product of elements in arr[] */ int x, y; /* x and y are two repeating elements */ int D; /* D is for difference of x and y, i.e., x-y*/ int n = size - 2, i; /* Calculate Sum and Product of all elements in arr[] */ for(i = 0; i < size; i++) { S = S + arr[i]; P = P*arr[i]; } S = S - n*(n+1)/2; /* S is x + y now */ P = P/fact(n); /* P is x*y now */ D = sqrt(S*S - 4*P); /* D is x - y now */ x = (D + S)/2; y = (S - D)/2; printf("The two Repeating elements are %d & %d", x, y);} int fact(int n){ return (n == 0)? 1 : n*fact(n-1);} int main(){ int arr[] = {4, 2, 4, 5, 2, 3, 1}; int arr_size = sizeof(arr)/sizeof(arr[0]); printRepeating(arr, arr_size); getchar(); return 0;}
class RepeatElement{ void printRepeating(int arr[], int size) { /* S is for sum of elements in arr[] */ int S = 0; /* P is for product of elements in arr[] */ int P = 1; /* x and y are two repeating elements */ int x, y; /* D is for difference of x and y, i.e., x-y*/ int D; int n = size - 2, i; /* Calculate Sum and Product of all elements in arr[] */ for (i = 0; i < size; i++) { S = S + arr[i]; P = P * arr[i]; } /* S is x + y now */ S = S - n * (n + 1) / 2; /* P is x*y now */ P = P / fact(n); /* D is x - y now */ D = (int) Math.sqrt(S * S - 4 * P); x = (D + S) / 2; y = (S - D) / 2; System.out.println("The two repeating elements are :"); System.out.print(x + " " + y); } int fact(int n) { return (n == 0) ? 1 : n * fact(n - 1); } public static void main(String[] args) { RepeatElement repeat = new RepeatElement(); int arr[] = {4, 2, 4, 5, 2, 3, 1}; int arr_size = arr.length; repeat.printRepeating(arr, arr_size); }} // This code has been contributed by Mayank Jaiswal
# Python3 code for Find the two repeating# elements in a given arrayimport math def printRepeating(arr, size) : # S is for sum of elements in arr[] S = 0; # P is for product of elements in arr[] P = 1; n = size - 2 # Calculate Sum and Product # of all elements in arr[] for i in range(0, size) : S = S + arr[i] P = P * arr[i] # S is x + y now S = S - n * (n + 1) // 2 # P is x*y now P = P // fact(n) # D is x - y now D = math.sqrt(S * S - 4 * P) x = (D + S) // 2 y = (S - D) // 2 print("The two Repeating elements are ", (int)(x)," & " ,(int)(y)) def fact(n) : if(n == 0) : return 1 else : return(n * fact(n - 1)) # Driver codearr = [4, 2, 4, 5, 2, 3, 1]arr_size = len(arr)printRepeating(arr, arr_size) # This code is contributed by Nikita Tiwari.
using System; class GFG{ static void printRepeating(int []arr, int size) { /* S is for sum of elements in arr[] */ int S = 0; /* P is for product of elements in arr[] */ int P = 1; /* x and y are two repeating elements */ int x, y; /* D is for difference of x and y, i.e., x-y*/ int D; int n = size - 2, i; /* Calculate Sum and Product of all elements in arr[] */ for (i = 0; i < size; i++) { S = S + arr[i]; P = P * arr[i]; } /* S is x + y now */ S = S - n * (n + 1) / 2; /* P is x*y now */ P = P / fact(n); /* D is x - y now */ D = (int) Math.Sqrt(S * S - 4 * P); x = (D + S) / 2; y = (S - D) / 2; Console.WriteLine("The two" + " repeating elements are :"); Console.Write(x + " " + y); } static int fact(int n) { return (n == 0) ? 1 : n * fact(n - 1); } // driver code public static void Main() { int []arr = {4, 2, 4, 5, 2, 3, 1}; int arr_size = arr.Length; printRepeating(arr, arr_size); }}// This code is contributed by Sam007
<?php /* function to get factorial of n */function fact($n){ return ($n == 0)? 1 : $n*fact($n-1);} function printRepeating($arr, $size){ $S = 0; /* S is for sum of elements in arr[] */ $P = 1; /* P is for product of elements in arr[] */ $x; $y; /* x and y are two repeating elements */ $D; /* D is for difference of x and y, i.e., x-y*/ $n = $size - 2; /* Calculate Sum and Product of all elements in arr[] */for($i = 0; $i < $size; $i++){ $S = $S + $arr[$i]; $P = $P*$arr[$i];} $S = $S - $n*($n+1)/2; /* S is x + y now */$P = $P/fact($n); /* P is x*y now */ $D = sqrt($S*$S - 4*$P); /* D is x - y now */ $x = ($D + $S)/2;$y = ($S - $D)/2; echo "The two Repeating elements are ".$x." & ".$y;} $arr = array(4, 2, 4, 5, 2, 3, 1);$arr_size = count($arr);printRepeating($arr, $arr_size);?>
<script> function printRepeating(arr , size) { /* S is for sum of elements in arr */ var S = 0; /* P is for product of elements in arr */ var P = 1; /* x and y are two repeating elements */ var x, y; /* D is for difference of x and y, i.e., x-y*/ var D; var n = size - 2, i; /* Calculate Sum and Product of all elements in arr */ for (i = 0; i < size; i++) { S = S + arr[i]; P = P * arr[i]; } /* S is x + y now */ S = S - n * parseInt((n + 1) / 2); /* P is x*y now */ P = parseInt(P / fact(n)); /* D is x - y now */ D = parseInt( Math.sqrt(S * S - 4 * P)); x = parseInt((D + S) / 2); y = parseInt((S - D) / 2); document.write("The two repeating elements are : "); document.write(x + " & " + y); } function fact(n) { var ans = false; if(n == 0) return 1; else return(n * fact(n - 1)); } var arr = [4, 2, 4, 5, 2, 3, 1]; var arr_size = arr.length; printRepeating(arr, arr_size); // This code is contributed by 29AjayKumar </script>
The two Repeating elements are 4 & 2
Time Complexity: O(n) Auxiliary Space: O(1)
Method 4 (Use XOR)
Thanks to neophyte for suggesting this method. The approach used here is similar to method 2 of this post. Let the repeating numbers be X and Y, if we xor all the elements in the array and all integers from 1 to n, then the result is X xor Y. The 1’s in binary representation of X xor Y is corresponding to the different bits between X and Y. Suppose that the kth bit of X xor Y is 1, we can xor all the elements in the array and all integers from 1 to n, whose kth bits are 1. The result will be one of X and Y.
C++
C
Java
Python3
C#
PHP
Javascript
#include <bits/stdc++.h>using namespace std; void printRepeating(int arr[], int size){ int Xor = arr[0]; /* Will hold Xor of all elements */ int set_bit_no; /* Will have only single set bit of Xor */ int i; int n = size - 2; int x = 0, y = 0; /* Get the Xor of all elements in arr[] and {1, 2 .. n} */ for(i = 1; i < size; i++) Xor ^= arr[i]; for(i = 1; i <= n; i++) Xor ^= i; /* Get the rightmost set bit in set_bit_no */ set_bit_no = Xor & ~(Xor-1); /* Now divide elements in two sets by comparing rightmost set bit of Xor with bit at same position in each element. */ for(i = 0; i < size; i++) { if(arr[i] & set_bit_no) x = x ^ arr[i]; /*Xor of first set in arr[] */ else y = y ^ arr[i]; /*Xor of second set in arr[] */ } for(i = 1; i <= n; i++) { if(i & set_bit_no) x = x ^ i; /*Xor of first set in arr[] and {1, 2, ...n }*/ else y = y ^ i; /*Xor of second set in arr[] and {1, 2, ...n } */ } cout<<"The two repeating elements are "<<y<<" "<<x;} // Driver codeint main(){ int arr[] = {4, 2, 4, 5, 2, 3, 1}; int arr_size = sizeof(arr)/sizeof(arr[0]); printRepeating(arr, arr_size); return 0;} // This code is contributed by rathbhupendra
void printRepeating(int arr[], int size){ int xor = arr[0]; /* Will hold xor of all elements */ int set_bit_no; /* Will have only single set bit of xor */ int i; int n = size - 2; int x = 0, y = 0; /* Get the xor of all elements in arr[] and {1, 2 .. n} */ for(i = 1; i < size; i++) xor ^= arr[i]; for(i = 1; i <= n; i++) xor ^= i; /* Get the rightmost set bit in set_bit_no */ set_bit_no = xor & ~(xor-1); /* Now divide elements in two sets by comparing rightmost set bit of xor with bit at same position in each element. */ for(i = 0; i < size; i++) { if(arr[i] & set_bit_no) x = x ^ arr[i]; /*XOR of first set in arr[] */ else y = y ^ arr[i]; /*XOR of second set in arr[] */ } for(i = 1; i <= n; i++) { if(i & set_bit_no) x = x ^ i; /*XOR of first set in arr[] and {1, 2, ...n }*/ else y = y ^ i; /*XOR of second set in arr[] and {1, 2, ...n } */ } printf("n The two repeating elements are %d & %d ", x, y);} int main(){ int arr[] = {4, 2, 4, 5, 2, 3, 1}; int arr_size = sizeof(arr)/sizeof(arr[0]); printRepeating(arr, arr_size); getchar(); return 0;}
class RepeatElement{ void printRepeating(int arr[], int size) { /* Will hold xor of all elements */ int xor = arr[0]; /* Will have only single set bit of xor */ int set_bit_no; int i; int n = size - 2; int x = 0, y = 0; /* Get the xor of all elements in arr[] and {1, 2 .. n} */ for (i = 1; i < size; i++) xor ^= arr[i]; for (i = 1; i <= n; i++) xor ^= i; /* Get the rightmost set bit in set_bit_no */ set_bit_no = (xor & ~(xor - 1)); /* Now divide elements in two sets by comparing rightmost set bit of xor with bit at same position in each element. */ for (i = 0; i < size; i++) { int a = arr[i] & set_bit_no; if (a != 0) x = x ^ arr[i]; /*XOR of first set in arr[] */ else y = y ^ arr[i]; /*XOR of second set in arr[] */ } for (i = 1; i <= n; i++) { int a = i & set_bit_no; if (a != 0) x = x ^ i; /*XOR of first set in arr[] and {1, 2, ...n }*/ else y = y ^ i; /*XOR of second set in arr[] and {1, 2, ...n } */ } System.out.println("The two reppeated elements are :"); System.out.println(x + " " + y); } /* Driver program to test the above function */ public static void main(String[] args) { RepeatElement repeat = new RepeatElement(); int arr[] = {4, 2, 4, 5, 2, 3, 1}; int arr_size = arr.length; repeat.printRepeating(arr, arr_size); }} // This code has been contributed by Mayank Jaiswal
# Python3 code to Find the# two repeating elements# in a given arraydef printRepeating(arr, size): # Will hold xor # of all elements xor = arr[0] n = size - 2 x = 0 y = 0 # Get the xor of all # elements in arr[] # and 1, 2 .. n for i in range(1 , size): xor ^= arr[i] for i in range(1 , n + 1): xor ^= i # Get the rightmost set # bit in set_bit_no set_bit_no = xor & ~(xor-1) # Now divide elements in two # sets by comparing rightmost # set bit of xor with bit at # same position in each element. for i in range(0, size): if(arr[i] & set_bit_no): # XOR of first # set in arr[] x = x ^ arr[i] else: # XOR of second # set in arr[] y = y ^ arr[i] for i in range(1 , n + 1): if(i & set_bit_no): # XOR of first set # in arr[] and # 1, 2, ...n x = x ^ i else: # XOR of second set # in arr[] and # 1, 2, ...n y = y ^ i print("The two repeating", "elements are", y, x) # Driver code arr = [4, 2, 4, 5, 2, 3, 1]arr_size = len(arr)printRepeating(arr, arr_size) # This code is contributed# by Smitha
using System; class GFG{ static void printRepeating(int []arr, int size) { /* Will hold xor of all elements */ int xor = arr[0]; /* Will have only single set bit of xor */ int set_bit_no; int i; int n = size - 2; int x = 0, y = 0; /* Get the xor of all elements in arr[] and {1, 2 .. n} */ for (i = 1; i < size; i++) xor ^= arr[i]; for (i = 1; i <= n; i++) xor ^= i; /* Get the rightmost set bit in set_bit_no */ set_bit_no = (xor & ~(xor - 1)); /* Now divide elements in two sets by comparing rightmost set bit of xor with bit at same position in each element. */ for (i = 0; i < size; i++) { int a = arr[i] & set_bit_no; if (a != 0) /* XOR of first set in arr[] */ x = x ^ arr[i]; else /* XOR of second set in arr[] */ y = y ^ arr[i]; } for (i = 1; i <= n; i++) { int a = i & set_bit_no; if (a != 0) /* XOR of first set in arr[] and {1, 2, ...n }*/ x = x ^ i; else /* XOR of second set in arr[] and {1, 2, ...n } */ y = y ^ i; } Console.WriteLine("The two" + " reppeated elements are :"); Console.Write(x + " " + y); } /* Driver program to test the above function */ public static void Main() { int []arr = {4, 2, 4, 5, 2, 3, 1}; int arr_size = arr.Length; printRepeating(arr, arr_size); }} // This code is contributed by Sam007
<?php// PHP code to Find the// two repeating elements// in a given arrayfunction printRepeating( $arr, $size){ $xor = $arr[0]; /* Will hold xor of all elements */ $set_bit_no; /* Will have only single set bit of xor */ $i; $n = $size - 2; $x = 0; $y = 0; /* Get the xor of all elements in arr[] and {1, 2 .. n} */ for($i = 1; $i < $size; $i++) $xor ^= $arr[$i]; for($i = 1; $i <= $n; $i++) $xor ^= $i; /* Get the rightmost set bit in set_bit_no */ $set_bit_no = $xor & ~($xor-1); /* Now divide elements in two sets by comparing rightmost set bit of xor with bit at same position in each element. */ for($i = 0; $i < $size; $i++) { if($arr[$i] & $set_bit_no) $x = $x ^ $arr[$i]; /*XOR of first set in arr[] */ else $y = $y ^ $arr[$i]; /*XOR of second set in arr[] */ } for($i = 1; $i <= $n; $i++) { if($i & $set_bit_no) /*XOR of first set in arr[] and {1, 2, ...n }*/ $x = $x ^ $i; else /*XOR of second set in arr[] and {1, 2, ...n } */ $y = $y ^ $i; } echo "n The two repeating elements are "; echo $y. " ".$x; } $arr = array(4, 2, 4, 5, 2, 3, 1);$arr_size = count($arr);printRepeating($arr, $arr_size); // This code has been contributed by Rajput-Ji?>
<script> function printRepeating( arr, size){ let Xor = arr[0]; /* Will hold Xor of all elements */ let set_bit_no; /* Will have only single set bit of Xor */ let i; let n = size - 2; let x = 0, y = 0; /* Get the Xor of all elements in arr[] and {1, 2 .. n} */ for(i = 1; i < size; i++) Xor ^= arr[i]; for(i = 1; i <= n; i++) Xor ^= i; /* Get the rightmost set bit in set_bit_no */ set_bit_no = Xor & ~(Xor-1); /* Now divide elements in two sets by comparing rightmost set bit of Xor with bit at same position in each element. */ for(i = 0; i < size; i++) { if(arr[i] & set_bit_no) x = x ^ arr[i]; /*Xor of first set in arr[] */ else y = y ^ arr[i]; /*Xor of second set in arr[] */ } for(i = 1; i <= n; i++) { if(i & set_bit_no) x = x ^ i; /*Xor of first set in arr[] and {1, 2, ...n }*/ else y = y ^ i; /*Xor of second set in arr[] and {1, 2, ...n } */ } document.write("The two repeating elements are "+y+" "+x);} // driver code let arr = [4, 2, 4, 5, 2, 3, 1]; let arr_size = arr.length; printRepeating(arr, arr_size); // This code is contributed by jana_sayantan.</script>
The two repeating elements are 4 2
Method 5 (Use array elements as index) Thanks to Manish K. Aasawat for suggesting this method.
Traverse the array. Do following for every index i of A[].
{
check for sign of A[abs(A[i])] ;
if positive then
make it negative by A[abs(A[i])]=-A[abs(A[i])];
else // i.e., A[abs(A[i])] is negative
this element (ith element of list) is a repetition
}
Example: A[] = {1, 1, 2, 3, 2}
i=0;
Check sign of A[abs(A[0])] which is A[1]. A[1] is positive, so make it negative.
Array now becomes {1, -1, 2, 3, 2}
i=1;
Check sign of A[abs(A[1])] which is A[1]. A[1] is negative, so A[1] is a repetition.
i=2;
Check sign of A[abs(A[2])] which is A[2]. A[2] is positive, so make it negative. '
Array now becomes {1, -1, -2, 3, 2}
i=3;
Check sign of A[abs(A[3])] which is A[3]. A[3] is positive, so make it negative.
Array now becomes {1, -1, -2, -3, 2}
i=4;
Check sign of A[abs(A[4])] which is A[2]. A[2] is negative, so A[4] is a repetition.
Note that this method modifies the original array and may not be a recommended method if we are not allowed to modify the array.
C++
C
Java
Python3
C#
PHP
Javascript
#include <bits/stdc++.h>using namespace std; void printRepeating(int arr[], int size){ int i; cout << "The repeating elements are"; for(i = 0; i < size; i++) { if(arr[abs(arr[i])] > 0) arr[abs(arr[i])] = -arr[abs(arr[i])]; else cout<<" " << abs(arr[i]) <<" "; } } // Driver codeint main(){ int arr[] = {4, 2, 4, 5, 2, 3, 1}; int arr_size = sizeof(arr)/sizeof(arr[0]); printRepeating(arr, arr_size); return 0;} // This code is contributed by rathbhupendra
#include <stdio.h>#include <stdlib.h> void printRepeating(int arr[], int size){ int i; printf("\n The repeating elements are"); for(i = 0; i < size; i++) { if(arr[abs(arr[i])] > 0) arr[abs(arr[i])] = -arr[abs(arr[i])]; else printf(" %d ", abs(arr[i])); } } int main(){ int arr[] = {4, 2, 4, 5, 2, 3, 1}; int arr_size = sizeof(arr)/sizeof(arr[0]); printRepeating(arr, arr_size); getchar(); return 0;}
class RepeatElement{ void printRepeating(int arr[], int size) { int i; System.out.println("The repeating elements are : "); for(i = 0; i < size; i++) { int abs_val = Math.abs(arr[i]); if(arr[abs_val] > 0) arr[abs_val] = -arr[abs_val]; else System.out.print(abs_val + " "); } } /* Driver program to test the above function */ public static void main(String[] args) { RepeatElement repeat = new RepeatElement(); int arr[] = {4, 2, 4, 5, 2, 3, 1}; int arr_size = arr.length; repeat.printRepeating(arr, arr_size); }} // This code has been contributed by Mayank Jaiswal
# Python3 code for Find the two repeating# elements in a given array def printRepeating(arr, size) : print(" The repeating elements are",end=" ") for i in range(0,size) : if(arr[abs(arr[i])] > 0) : arr[abs(arr[i])] = (-1) * arr[abs(arr[i])] else : print(abs(arr[i]),end = " ") # Driver codearr = [4, 2, 4, 5, 2, 3, 1]arr_size = len(arr)printRepeating(arr, arr_size) # This code is contributed by Nikita Tiwari.
// C# code for Find the two repeating// elements in a given array using System; class GFG{ static void printRepeating(int []arr, int size) { int i; Console.Write("The repeating elements are : "); for(i = 0; i < size; i++) { int abs_val = Math.Abs(arr[i]); if(arr[abs_val] > 0) arr[abs_val] = -arr[abs_val]; else Console.Write(abs_val + " "); } } /* Driver program to test the above function */ public static void Main() { int []arr = {4, 2, 4, 5, 2, 3, 1}; int arr_size = arr.Length; printRepeating(arr, arr_size); }} // This code is contributed by Sam007
<?php function printRepeating($arr, $size){ $i; echo "The repeating elements are"," "; for($i = 0; $i < $size; $i++){ if($arr[abs($arr[$i])] > 0) $arr[abs($arr[$i])] = -$arr[abs($arr[$i])]; else echo abs($arr[$i])," ";} } $arr = array (4, 2, 4, 5, 2, 3, 1); $arr_size = sizeof($arr); printRepeating($arr, $arr_size); #This code is contributed by aj_36?>
<script> function printRepeating(arr , size){ var i; document.write("The repeating elements are : "); for(i = 0; i < size; i++) { var abs_val = Math.abs(arr[i]); if(arr[abs_val] > 0)x arr[abs_val] = -arr[abs_val]; else document.write(abs_val + " "); } } /* Driver program to test the above function */ var arr = [4, 2, 4, 5, 2, 3, 1];var arr_size = arr.length;printRepeating(arr, arr_size); // This code is contributed by 29AjayKumar </script>
The repeating elements are 4 2
Method 6 (Similar to method 5)
Thanks to Vivek Kumar for suggesting this method.
The point is to increment every element at (arr[i]th-1)th index by N-1 (as the elements are present upto N-2 only) and at the same time check if element at that index when divided by (N-1) gives 2. If this is true then it means that the element has appeared twice and we can easily say that this is one of our answers. This is one of the very useful techniques when we want to calculate Frequencies of Limited Range Array Elements (see this post to know more).
This method works on the fact that the remainder of an element when divided by any number greater than that element will always give that same element. Similarly, as we are incrementing each element at (arr[i]th-1) index by N-1, so when this incremented element is divided by N-1 it will give number of times we have added N-1 to it, hence giving us the occurrence of that index (according to 1-based indexing).
Below given code applies this method:
C++
Java
Python3
C#
Javascript
#include <iostream>using namespace std; void twoRepeated(int arr[], int N){ int m = N - 1; for (int i = 0; i < N; i++) { arr[arr[i] % m - 1] += m; if ((arr[arr[i] % m - 1] / m) == 2) cout << arr[i] % m << " "; }}// Driver Codeint main(){ int arr[] = { 4, 2, 4, 5, 2, 3, 1 }; int n = sizeof(arr) / sizeof(arr[0]); cout << "The two repeating elements are "; twoRepeated(arr, n); return 0;}// This code is contributed by Kartik Singh Kushwah
import java.io.*; class GFG{ public static void twoRepeated(int arr[], int N){ int m = N - 1; for(int i = 0; i < N; i++) { arr[arr[i] % m - 1] += m; if ((arr[arr[i] % m - 1] / m) == 2) System.out.printf(arr[i] % m + " "); }} // Driver codepublic static void main(String[] args){ int arr[] = { 4, 2, 4, 5, 2, 3, 1 }; int n = 7; System.out.printf("The two repeating elements are "); twoRepeated(arr, n);}} // This code is contributed by Potta Lokesh
# Python program for the above approachdef twoRepeated(arr, N): m = N - 1 for i in range(N): arr[arr[i] % m - 1] += m if ((arr[arr[i] % m - 1] // m) == 2): print(arr[i] % m ,end= " ") # Driver Codearr = [4, 2, 4, 5, 2, 3, 1]n = len(arr)print("The two repeating elements are ", end = "")twoRepeated(arr, n) # This code is contributed by Shubham Singh
// C# program for the above approachusing System; public class GFG{public static void twoRepeated(int[] arr, int N){ int m = N - 1; for(int i = 0; i < N; i++) { arr[arr[i] % m - 1] += m; if ((arr[arr[i] % m - 1] / m) == 2) Console.Write(arr[i] % m + " "); }} // Driver codepublic static void Main(String []args){ int[] arr = { 4, 2, 4, 5, 2, 3, 1 }; int n = 7; Console.Write("The two repeating elements are "); twoRepeated(arr, n);}} // This code is contributed by splevel62.
<script> function twoRepeated(arr, N){ let m = N - 1; for(let i = 0; i < N; i++) { arr[parseInt(arr[i] % m) - 1] += m; if (parseInt(arr[parseInt(arr[i] % m) - 1] / m) == 2) document.write(parseInt(arr[i] % m) + " "); }} // Driver Codevar arr = [ 4, 2, 4, 5, 2, 3, 1 ];var n = 7;document.write("The two repeating elements are "); twoRepeated(arr, n); // This code is contributed by Potta Lokesh </script>
The two repeating elements are 4 2
Method 7The point here is to enter the array elements one by one into the unordered set. If a particular element is already present in the set it’s a repeating element.
C++
Java
Python3
C#
Javascript
// C++ program to Find the two repeating// elements in a given array#include <bits/stdc++.h>using namespace std; void printRepeating(int arr[], int size){ unordered_set<int>s; cout<<"The two Repeating elements are : "; for(int i=0;i<size;i++) { if(s.empty()==false && s.find(arr[i])!=s.end()) cout<<arr[i]<<" "; s.insert(arr[i]); }} // Driver codeint main(){ int arr[] = {4, 2, 4, 5, 2, 3, 1}; int arr_size = sizeof(arr)/sizeof(arr[0]); printRepeating(arr, arr_size); return 0;} // This code is contributed by nakul amate
// Java program to Find the two repeating// elements in a given arrayimport java.util.*;class GFG{ static void printRepeating(int arr[], int size) { HashSet<Integer>s = new HashSet<>(); System.out.print("The two Repeating elements are : "); for(int i = 0; i < size; i++) { if(!s.isEmpty() && s.contains(arr[i])) System.out.print(arr[i]+" "); s.add(arr[i]); } } // Driver code public static void main(String[] args) { int arr[] = {4, 2, 4, 5, 2, 3, 1}; int arr_size = arr.length; printRepeating(arr, arr_size); }} // This code is contributed by Rajput-Ji
# Python3 program to find the two repeating# elements in a given arraydef printRepeating(arr, size): s = set() print("The two Repeating elements are : ", end = "") for i in range(size): if (len(s) and arr[i] in s): print(arr[i], end = " ") s.add(arr[i]) # Driver codearr = [ 4, 2, 4, 5, 2, 3, 1 ]arr_size = len(arr)printRepeating(arr, arr_size) # This code is contributed by Shubham Singh
// C# program to Find the two repeating// elements in a given arrayusing System;using System.Collections.Generic; public class GFG{ static void printRepeating(int[] arr, int size) { HashSet<int>s = new HashSet<int>(); Console.Write("The two Repeating elements are : "); for(int i = 0; i < size; i++) { if(s.Count != 0 && s.Contains(arr[i])) Console.Write(arr[i] + " "); s.Add(arr[i]); } } // Driver code public static void Main() { int[] arr = {4, 2, 4, 5, 2, 3, 1}; int arr_size = arr.Length; printRepeating(arr, arr_size); }} // This code is contributed by Shubham Singh
<script> function printRepeating(arr, size){ const s = new Set(); document.write("The two repeating elements are "); for(let i = 0; i < size; i++) { if(s.size != 0 && s.has(arr[i])) document.write(arr[i] + " "); s.add(arr[i]); }} // Driver Codevar arr = [ 4, 2, 4, 5, 2, 3, 1 ];var arr_size = 7;printRepeating(arr, arr_size); // This code is contributed by Shubham Singh </script>
The two Repeating elements are : 4 2
Time Complexity: O(n)
Auxiliary Space: O(n)
Please write comments if you find the above codes/algorithms incorrect, or find better ways to solve the same problem.
jit_t
Smitha Dinesh Semwal
Mithun Kumar
29AjayKumar
Rajput-Ji
Shivi_Aggarwal
rathbhupendra
nidhi_biet
imaryan20
jana_sayantan
rameshtravel07
vimlakushwah81
sujalgupta6100
lokeshpotta20
splevel62
nakul_amate
SHUBHAMSINGH10
yaliyunus4
MakeMyTrip
Arrays
MakeMyTrip
Arrays
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Arrays in Java
Arrays in C/C++
Program for array rotation
Stack Data Structure (Introduction and Program)
Top 50 Array Coding Problems for Interviews
Write a program to reverse an array or string
Largest Sum Contiguous Subarray
Introduction to Arrays
Multidimensional Arrays in Java
|
[
{
"code": null,
"e": 41276,
"s": 41248,
"text": "\n13 Mar, 2022"
},
{
"code": null,
"e": 41462,
"s": 41276,
"text": "You are given an array of n+2 elements. All elements of the array are in range 1 to n. And all elements occur once except two numbers which occur twice. Find the two repeating numbers. "
},
{
"code": null,
"e": 41471,
"s": 41462,
"text": "Example:"
},
{
"code": null,
"e": 41668,
"s": 41471,
"text": "Input: arr = [4, 2, 4, 5, 2, 3, 1] n = 5Output:4 2Explanation:The above array has n + 2 = 7 elements with all elements occurring once except 2 and 4 which occur twice. So the output should be 4 2."
},
{
"code": null,
"e": 41686,
"s": 41668,
"text": "Method 1 (Basic) "
},
{
"code": null,
"e": 41975,
"s": 41686,
"text": "Use two loops. In the outer loop, pick elements one by one and count the number of occurrences of the picked element in the inner loop. This method doesn’t use the other useful data provided in questions like range of numbers is between 1 to n and there are only two repeating elements. "
},
{
"code": null,
"e": 41979,
"s": 41975,
"text": "C++"
},
{
"code": null,
"e": 41981,
"s": 41979,
"text": "C"
},
{
"code": null,
"e": 41986,
"s": 41981,
"text": "Java"
},
{
"code": null,
"e": 41994,
"s": 41986,
"text": "Python3"
},
{
"code": null,
"e": 41997,
"s": 41994,
"text": "C#"
},
{
"code": null,
"e": 42001,
"s": 41997,
"text": "PHP"
},
{
"code": null,
"e": 42012,
"s": 42001,
"text": "Javascript"
},
{
"code": "// C++ program to Find the two repeating// elements in a given array#include<bits/stdc++.h>using namespace std; void printTwoRepeatNumber(int arr[], int size){ int i, j, display=0; int visited[size]; for(i = 0; i < size; i++) { if (visited[i] == 1) { continue; } int count = 0; for(j = i + 1; j < size; j++) { if(arr[i] == arr[j]) { visited[j] = 1; ++count; break; } } if ( (count > 0) && (display < 2)){ ++display; cout<<\"repeating element = \"<< arr[i]<<endl; } }} int main(){ int arr[] = {4, 2, 5, 2, 3, 3, 4, 4, 1, 1}; int arr_size = sizeof(arr)/sizeof(arr[0]); printTwoRepeatNumber(arr, arr_size);}",
"e": 42765,
"s": 42012,
"text": null
},
{
"code": "#include<stdio.h>#include<stdlib.h>void printRepeating(int arr[], int size){ int i, j; printf(\" Repeating elements are \"); for(i = 0; i < size-1; i++) for(j = i+1; j < size; j++) if(arr[i] == arr[j]) printf(\" %d \", arr[i]);} int main(){ int arr[] = {4, 2, 4, 5, 2, 3, 1}; int arr_size = sizeof(arr)/sizeof(arr[0]); printRepeating(arr, arr_size); getchar(); return 0;}",
"e": 43161,
"s": 42765,
"text": null
},
{
"code": "class RepeatElement{ void printRepeating(int arr[], int size) { int i, j; System.out.println(\"Repeated Elements are :\"); for (i = 0; i < size-1; i++) { for (j = i + 1; j < size; j++) { if (arr[i] == arr[j]) System.out.print(arr[i] + \" \"); } } } public static void main(String[] args) { RepeatElement repeat = new RepeatElement(); int arr[] = {4, 2, 4, 5, 2, 3, 1}; int arr_size = arr.length; repeat.printRepeating(arr, arr_size); }}",
"e": 43743,
"s": 43161,
"text": null
},
{
"code": "# Python3 program to Find the two# repeating elements in a given array def printRepeating(arr, size): print(\"Repeating elements are \", end = '') for i in range (0, size-1): for j in range (i + 1, size): if arr[i] == arr[j]: print(arr[i], end = ' ') # Driver codearr = [4, 2, 4, 5, 2, 3, 1]arr_size = len(arr)printRepeating(arr, arr_size) # This code is contributed by Smitha Dinesh Semwal",
"e": 44200,
"s": 43743,
"text": null
},
{
"code": "using System; class GFG{ static void printRepeating(int []arr, int size) { int i, j; Console.Write(\"Repeated Elements are :\"); for (i = 0; i < size-1; i++) { for (j = i + 1; j < size; j++) { if (arr[i] == arr[j]) Console.Write(arr[i] + \" \"); } } } // driver code public static void Main() { int []arr = {4, 2, 4, 5, 2, 3, 1}; int arr_size = arr.Length; printRepeating(arr, arr_size); }} // This code is contributed by Sam007",
"e": 44796,
"s": 44200,
"text": null
},
{
"code": "<?php// PHP program to Find the two// repeating elements in// a given array function printRepeating($arr, $size){ $i; $j; echo \" Repeating elements are \"; for($i = 0; $i < $size-1; $i++) for($j = $i + 1; $j < $size; $j++) if($arr[$i] == $arr[$j]) echo $arr[$i], \" \";} // Driver Code$arr = array(4, 2, 4, 5, 2, 3, 1);$arr_size = sizeof($arr, 0);printRepeating($arr, $arr_size); // This code is contributed by Ajit?>",
"e": 45257,
"s": 44796,
"text": null
},
{
"code": "<script> function printRepeating(arr , size) { var i, j; document.write(\"Repeated Elements are :\"); for (i = 0; i < size-1; i++) { for (j = i + 1; j < size; j++) { if (arr[i] == arr[j]) document.write(arr[i] + \" \"); } } } var arr = [4, 2, 4, 5, 2, 3, 1];var arr_size = arr.length;printRepeating(arr, arr_size); // This code is contributed by 29AjayKumar</script>",
"e": 45731,
"s": 45257,
"text": null
},
{
"code": null,
"e": 45760,
"s": 45731,
"text": " Repeating elements are 4 2 "
},
{
"code": null,
"e": 45806,
"s": 45760,
"text": "Time Complexity: O(n*n) Auxiliary Space: O(1)"
},
{
"code": null,
"e": 46189,
"s": 45806,
"text": "Method 2 (Use Count array) Traverse the array once. While traversing, keep track of count of all elements in the array using a temp array count[] of size n, when you see an element whose count is already set, print it as duplicate.This method uses the range given in the question to restrict the size of count[], but doesn’t use the data that there are only two repeating elements. "
},
{
"code": null,
"e": 46193,
"s": 46189,
"text": "C++"
},
{
"code": null,
"e": 46195,
"s": 46193,
"text": "C"
},
{
"code": null,
"e": 46200,
"s": 46195,
"text": "Java"
},
{
"code": null,
"e": 46208,
"s": 46200,
"text": "Python3"
},
{
"code": null,
"e": 46211,
"s": 46208,
"text": "C#"
},
{
"code": null,
"e": 46215,
"s": 46211,
"text": "PHP"
},
{
"code": null,
"e": 46226,
"s": 46215,
"text": "Javascript"
},
{
"code": "// C++ implementation of above approach#include <bits/stdc++.h>using namespace std; void printRepeating(int arr[], int size){ int *count = new int[sizeof(int)*(size - 2)]; int i; cout << \" Repeating elements are \"; for(i = 0; i < size; i++) { if(count[arr[i]] == 1) cout << arr[i] << \" \"; else count[arr[i]]++; }} // Driver codeint main(){ int arr[] = {4, 2, 4, 5, 2, 3, 1}; int arr_size = sizeof(arr)/sizeof(arr[0]); printRepeating(arr, arr_size); return 0;} // This is code is contributed by rathbhupendra",
"e": 46809,
"s": 46226,
"text": null
},
{
"code": "#include<stdio.h>#include<stdlib.h> void printRepeating(int arr[], int size){ int *count = (int *)calloc(sizeof(int), (size - 2)); int i; printf(\" Repeating elements are \"); for(i = 0; i < size; i++) { if(count[arr[i]] == 1) printf(\" %d \", arr[i]); else count[arr[i]]++; } } int main(){ int arr[] = {4, 2, 4, 5, 2, 3, 1}; int arr_size = sizeof(arr)/sizeof(arr[0]); printRepeating(arr, arr_size); getchar(); return 0;}",
"e": 47264,
"s": 46809,
"text": null
},
{
"code": "class RepeatElement{ void printRepeating(int arr[], int size) { int count[] = new int[size]; int i; System.out.println(\"Repeated elements are : \"); for (i = 0; i < size; i++) { if (count[arr[i]] == 1) System.out.print(arr[i] + \" \"); else count[arr[i]]++; } } public static void main(String[] args) { RepeatElement repeat = new RepeatElement(); int arr[] = {4, 2, 4, 5, 2, 3, 1}; int arr_size = arr.length; repeat.printRepeating(arr, arr_size); }}",
"e": 47853,
"s": 47264,
"text": null
},
{
"code": "# Python3 code for Find the two repeating# elements in a given array def printRepeating(arr,size) : count = [0] * size print(\" Repeating elements are \",end = \"\") for i in range(0, size) : if(count[arr[i]] == 1) : print(arr[i], end = \" \") else : count[arr[i]] = count[arr[i]] + 1 # Driver codearr = [4, 2, 4, 5, 2, 3, 1]arr_size = len(arr)printRepeating(arr, arr_size) # This code is contributed by Nikita Tiwari.",
"e": 48323,
"s": 47853,
"text": null
},
{
"code": "// C# program to Find the two// repeating elements in a given arrayusing System; class GFG{ static void printRepeating(int []arr, int size) { int []count = new int[size]; int i; Console.Write(\"Repeated elements are: \"); for (i = 0; i < size; i++) { if (count[arr[i]] == 1) Console.Write(arr[i] + \" \"); else count[arr[i]]++; } } // driver code public static void Main() { int []arr = {4, 2, 4, 5, 2, 3, 1}; int arr_size = arr.Length; printRepeating(arr, arr_size); }} //This code is contributed by Sam007",
"e": 49018,
"s": 48323,
"text": null
},
{
"code": "<?php// PHP program to Find the two// repeating elements in a given arrayfunction printRepeating($arr, $size){ $count = array_fill(0, $size, 0); echo \"Repeated elements are \"; for ($i = 0; $i < $size; $i++) { if ($count[$arr[$i]] == 1) echo $arr[$i].\" \"; else $count[$arr[$i]]++; }} // Driver code$arr = array(4, 2, 4, 5, 2, 3, 1);$arr_size = count($arr); printRepeating($arr, $arr_size); // This code is contributed by mits?>",
"e": 49504,
"s": 49018,
"text": null
},
{
"code": "<script> // Javascript program to Find the two // repeating elements in a given array function printRepeating(arr, size) { let count = new Array(size); count.fill(0); let i; document.write(\"Repeating elements are \"); for (i = 0; i < size; i++) { if (count[arr[i]] == 1) document.write(arr[i] + \" \"); else count[arr[i]]++; } } let arr = [4, 2, 4, 5, 2, 3, 1]; let arr_size = arr.length; printRepeating(arr, arr_size); </script>",
"e": 50076,
"s": 49504,
"text": null
},
{
"code": null,
"e": 50105,
"s": 50076,
"text": " Repeating elements are 4 2 "
},
{
"code": null,
"e": 50149,
"s": 50105,
"text": "Time Complexity: O(n) Auxiliary Space: O(n)"
},
{
"code": null,
"e": 50180,
"s": 50149,
"text": "Method 3 (Make two equations) "
},
{
"code": null,
"e": 51235,
"s": 50180,
"text": "Let the numbers which are being repeated are X and Y. We make two equations for X and Y and the simple task left is to solve the two equations. We know the sum of integers from 1 to n is n(n+1)/2 and product is n!. We calculate the sum of input array when this sum is subtracted from n(n+1)/2, we get X + Y because X and Y are the two numbers missing from set [1..n]. Similarly calculate the product of input array, when this product is divided from n!, we get X*Y. Given the sum and product of X and Y, we can find easily out X and Y.Let summation of all numbers in the array be S and product be PX + Y = S – n(n+1)/2 XY = P/n!Using the above two equations, we can find out X and Y. For array = 4 2 4 5 2 3 1, we get S = 21 and P as 960.X + Y = 21 – 15 = 6XY = 960/5! = 8X – Y = sqrt((X+Y)^2 – 4*XY) = sqrt(4) = 2Using below two equations, we easily get X = (6 + 2)/2 and Y = (6-2)/2 X + Y = 6 X – Y = 2Thanks to geek4u for suggesting this method. As pointed by Beginner, there can be an addition and multiplication overflow problem with this approach. "
},
{
"code": null,
"e": 51306,
"s": 51235,
"text": "The methods 3 and 4 use all useful information given in the question :"
},
{
"code": null,
"e": 51310,
"s": 51306,
"text": "C++"
},
{
"code": null,
"e": 51312,
"s": 51310,
"text": "C"
},
{
"code": null,
"e": 51317,
"s": 51312,
"text": "Java"
},
{
"code": null,
"e": 51325,
"s": 51317,
"text": "Python3"
},
{
"code": null,
"e": 51328,
"s": 51325,
"text": "C#"
},
{
"code": null,
"e": 51332,
"s": 51328,
"text": "PHP"
},
{
"code": null,
"e": 51343,
"s": 51332,
"text": "Javascript"
},
{
"code": "#include <bits/stdc++.h>using namespace std; /* function to get factorial of n */int fact(int n); void printRepeating(int arr[], int size){ int S = 0; /* S is for sum of elements in arr[] */ int P = 1; /* P is for product of elements in arr[] */ int x, y; /* x and y are two repeating elements */ int D; /* D is for difference of x and y, i.e., x-y*/ int n = size - 2, i; /* Calculate Sum and Product of all elements in arr[] */ for(i = 0; i < size; i++) { S = S + arr[i]; P = P*arr[i]; } S = S - n*(n+1)/2; /* S is x + y now */ P = P/fact(n); /* P is x*y now */ D = sqrt(S*S - 4*P); /* D is x - y now */ x = (D + S)/2; y = (S - D)/2; cout<<\"The two Repeating elements are \"<<x<<\" & \"<<y;} int fact(int n){ return (n == 0)? 1 : n*fact(n-1);} // Driver codeint main(){ int arr[] = {4, 2, 4, 5, 2, 3, 1}; int arr_size = sizeof(arr)/sizeof(arr[0]); printRepeating(arr, arr_size); return 0;} // This code is contributed by rathbhupendra",
"e": 52399,
"s": 51343,
"text": null
},
{
"code": "#include<stdio.h>#include<stdlib.h>#include<math.h> /* function to get factorial of n */int fact(int n); void printRepeating(int arr[], int size){ int S = 0; /* S is for sum of elements in arr[] */ int P = 1; /* P is for product of elements in arr[] */ int x, y; /* x and y are two repeating elements */ int D; /* D is for difference of x and y, i.e., x-y*/ int n = size - 2, i; /* Calculate Sum and Product of all elements in arr[] */ for(i = 0; i < size; i++) { S = S + arr[i]; P = P*arr[i]; } S = S - n*(n+1)/2; /* S is x + y now */ P = P/fact(n); /* P is x*y now */ D = sqrt(S*S - 4*P); /* D is x - y now */ x = (D + S)/2; y = (S - D)/2; printf(\"The two Repeating elements are %d & %d\", x, y);} int fact(int n){ return (n == 0)? 1 : n*fact(n-1);} int main(){ int arr[] = {4, 2, 4, 5, 2, 3, 1}; int arr_size = sizeof(arr)/sizeof(arr[0]); printRepeating(arr, arr_size); getchar(); return 0;}",
"e": 53370,
"s": 52399,
"text": null
},
{
"code": "class RepeatElement{ void printRepeating(int arr[], int size) { /* S is for sum of elements in arr[] */ int S = 0; /* P is for product of elements in arr[] */ int P = 1; /* x and y are two repeating elements */ int x, y; /* D is for difference of x and y, i.e., x-y*/ int D; int n = size - 2, i; /* Calculate Sum and Product of all elements in arr[] */ for (i = 0; i < size; i++) { S = S + arr[i]; P = P * arr[i]; } /* S is x + y now */ S = S - n * (n + 1) / 2; /* P is x*y now */ P = P / fact(n); /* D is x - y now */ D = (int) Math.sqrt(S * S - 4 * P); x = (D + S) / 2; y = (S - D) / 2; System.out.println(\"The two repeating elements are :\"); System.out.print(x + \" \" + y); } int fact(int n) { return (n == 0) ? 1 : n * fact(n - 1); } public static void main(String[] args) { RepeatElement repeat = new RepeatElement(); int arr[] = {4, 2, 4, 5, 2, 3, 1}; int arr_size = arr.length; repeat.printRepeating(arr, arr_size); }} // This code has been contributed by Mayank Jaiswal",
"e": 54657,
"s": 53370,
"text": null
},
{
"code": "# Python3 code for Find the two repeating# elements in a given arrayimport math def printRepeating(arr, size) : # S is for sum of elements in arr[] S = 0; # P is for product of elements in arr[] P = 1; n = size - 2 # Calculate Sum and Product # of all elements in arr[] for i in range(0, size) : S = S + arr[i] P = P * arr[i] # S is x + y now S = S - n * (n + 1) // 2 # P is x*y now P = P // fact(n) # D is x - y now D = math.sqrt(S * S - 4 * P) x = (D + S) // 2 y = (S - D) // 2 print(\"The two Repeating elements are \", (int)(x),\" & \" ,(int)(y)) def fact(n) : if(n == 0) : return 1 else : return(n * fact(n - 1)) # Driver codearr = [4, 2, 4, 5, 2, 3, 1]arr_size = len(arr)printRepeating(arr, arr_size) # This code is contributed by Nikita Tiwari.",
"e": 55558,
"s": 54657,
"text": null
},
{
"code": "using System; class GFG{ static void printRepeating(int []arr, int size) { /* S is for sum of elements in arr[] */ int S = 0; /* P is for product of elements in arr[] */ int P = 1; /* x and y are two repeating elements */ int x, y; /* D is for difference of x and y, i.e., x-y*/ int D; int n = size - 2, i; /* Calculate Sum and Product of all elements in arr[] */ for (i = 0; i < size; i++) { S = S + arr[i]; P = P * arr[i]; } /* S is x + y now */ S = S - n * (n + 1) / 2; /* P is x*y now */ P = P / fact(n); /* D is x - y now */ D = (int) Math.Sqrt(S * S - 4 * P); x = (D + S) / 2; y = (S - D) / 2; Console.WriteLine(\"The two\" + \" repeating elements are :\"); Console.Write(x + \" \" + y); } static int fact(int n) { return (n == 0) ? 1 : n * fact(n - 1); } // driver code public static void Main() { int []arr = {4, 2, 4, 5, 2, 3, 1}; int arr_size = arr.Length; printRepeating(arr, arr_size); }}// This code is contributed by Sam007",
"e": 56838,
"s": 55558,
"text": null
},
{
"code": "<?php /* function to get factorial of n */function fact($n){ return ($n == 0)? 1 : $n*fact($n-1);} function printRepeating($arr, $size){ $S = 0; /* S is for sum of elements in arr[] */ $P = 1; /* P is for product of elements in arr[] */ $x; $y; /* x and y are two repeating elements */ $D; /* D is for difference of x and y, i.e., x-y*/ $n = $size - 2; /* Calculate Sum and Product of all elements in arr[] */for($i = 0; $i < $size; $i++){ $S = $S + $arr[$i]; $P = $P*$arr[$i];} $S = $S - $n*($n+1)/2; /* S is x + y now */$P = $P/fact($n); /* P is x*y now */ $D = sqrt($S*$S - 4*$P); /* D is x - y now */ $x = ($D + $S)/2;$y = ($S - $D)/2; echo \"The two Repeating elements are \".$x.\" & \".$y;} $arr = array(4, 2, 4, 5, 2, 3, 1);$arr_size = count($arr);printRepeating($arr, $arr_size);?>",
"e": 57656,
"s": 56838,
"text": null
},
{
"code": "<script> function printRepeating(arr , size) { /* S is for sum of elements in arr */ var S = 0; /* P is for product of elements in arr */ var P = 1; /* x and y are two repeating elements */ var x, y; /* D is for difference of x and y, i.e., x-y*/ var D; var n = size - 2, i; /* Calculate Sum and Product of all elements in arr */ for (i = 0; i < size; i++) { S = S + arr[i]; P = P * arr[i]; } /* S is x + y now */ S = S - n * parseInt((n + 1) / 2); /* P is x*y now */ P = parseInt(P / fact(n)); /* D is x - y now */ D = parseInt( Math.sqrt(S * S - 4 * P)); x = parseInt((D + S) / 2); y = parseInt((S - D) / 2); document.write(\"The two repeating elements are : \"); document.write(x + \" & \" + y); } function fact(n) { var ans = false; if(n == 0) return 1; else return(n * fact(n - 1)); } var arr = [4, 2, 4, 5, 2, 3, 1]; var arr_size = arr.length; printRepeating(arr, arr_size); // This code is contributed by 29AjayKumar </script>",
"e": 58909,
"s": 57656,
"text": null
},
{
"code": null,
"e": 58946,
"s": 58909,
"text": "The two Repeating elements are 4 & 2"
},
{
"code": null,
"e": 58991,
"s": 58946,
"text": "Time Complexity: O(n) Auxiliary Space: O(1) "
},
{
"code": null,
"e": 59011,
"s": 58991,
"text": "Method 4 (Use XOR) "
},
{
"code": null,
"e": 59525,
"s": 59011,
"text": "Thanks to neophyte for suggesting this method. The approach used here is similar to method 2 of this post. Let the repeating numbers be X and Y, if we xor all the elements in the array and all integers from 1 to n, then the result is X xor Y. The 1’s in binary representation of X xor Y is corresponding to the different bits between X and Y. Suppose that the kth bit of X xor Y is 1, we can xor all the elements in the array and all integers from 1 to n, whose kth bits are 1. The result will be one of X and Y. "
},
{
"code": null,
"e": 59529,
"s": 59525,
"text": "C++"
},
{
"code": null,
"e": 59531,
"s": 59529,
"text": "C"
},
{
"code": null,
"e": 59536,
"s": 59531,
"text": "Java"
},
{
"code": null,
"e": 59544,
"s": 59536,
"text": "Python3"
},
{
"code": null,
"e": 59547,
"s": 59544,
"text": "C#"
},
{
"code": null,
"e": 59551,
"s": 59547,
"text": "PHP"
},
{
"code": null,
"e": 59562,
"s": 59551,
"text": "Javascript"
},
{
"code": "#include <bits/stdc++.h>using namespace std; void printRepeating(int arr[], int size){ int Xor = arr[0]; /* Will hold Xor of all elements */ int set_bit_no; /* Will have only single set bit of Xor */ int i; int n = size - 2; int x = 0, y = 0; /* Get the Xor of all elements in arr[] and {1, 2 .. n} */ for(i = 1; i < size; i++) Xor ^= arr[i]; for(i = 1; i <= n; i++) Xor ^= i; /* Get the rightmost set bit in set_bit_no */ set_bit_no = Xor & ~(Xor-1); /* Now divide elements in two sets by comparing rightmost set bit of Xor with bit at same position in each element. */ for(i = 0; i < size; i++) { if(arr[i] & set_bit_no) x = x ^ arr[i]; /*Xor of first set in arr[] */ else y = y ^ arr[i]; /*Xor of second set in arr[] */ } for(i = 1; i <= n; i++) { if(i & set_bit_no) x = x ^ i; /*Xor of first set in arr[] and {1, 2, ...n }*/ else y = y ^ i; /*Xor of second set in arr[] and {1, 2, ...n } */ } cout<<\"The two repeating elements are \"<<y<<\" \"<<x;} // Driver codeint main(){ int arr[] = {4, 2, 4, 5, 2, 3, 1}; int arr_size = sizeof(arr)/sizeof(arr[0]); printRepeating(arr, arr_size); return 0;} // This code is contributed by rathbhupendra",
"e": 60870,
"s": 59562,
"text": null
},
{
"code": "void printRepeating(int arr[], int size){ int xor = arr[0]; /* Will hold xor of all elements */ int set_bit_no; /* Will have only single set bit of xor */ int i; int n = size - 2; int x = 0, y = 0; /* Get the xor of all elements in arr[] and {1, 2 .. n} */ for(i = 1; i < size; i++) xor ^= arr[i]; for(i = 1; i <= n; i++) xor ^= i; /* Get the rightmost set bit in set_bit_no */ set_bit_no = xor & ~(xor-1); /* Now divide elements in two sets by comparing rightmost set bit of xor with bit at same position in each element. */ for(i = 0; i < size; i++) { if(arr[i] & set_bit_no) x = x ^ arr[i]; /*XOR of first set in arr[] */ else y = y ^ arr[i]; /*XOR of second set in arr[] */ } for(i = 1; i <= n; i++) { if(i & set_bit_no) x = x ^ i; /*XOR of first set in arr[] and {1, 2, ...n }*/ else y = y ^ i; /*XOR of second set in arr[] and {1, 2, ...n } */ } printf(\"n The two repeating elements are %d & %d \", x, y);} int main(){ int arr[] = {4, 2, 4, 5, 2, 3, 1}; int arr_size = sizeof(arr)/sizeof(arr[0]); printRepeating(arr, arr_size); getchar(); return 0;}",
"e": 62006,
"s": 60870,
"text": null
},
{
"code": "class RepeatElement{ void printRepeating(int arr[], int size) { /* Will hold xor of all elements */ int xor = arr[0]; /* Will have only single set bit of xor */ int set_bit_no; int i; int n = size - 2; int x = 0, y = 0; /* Get the xor of all elements in arr[] and {1, 2 .. n} */ for (i = 1; i < size; i++) xor ^= arr[i]; for (i = 1; i <= n; i++) xor ^= i; /* Get the rightmost set bit in set_bit_no */ set_bit_no = (xor & ~(xor - 1)); /* Now divide elements in two sets by comparing rightmost set bit of xor with bit at same position in each element. */ for (i = 0; i < size; i++) { int a = arr[i] & set_bit_no; if (a != 0) x = x ^ arr[i]; /*XOR of first set in arr[] */ else y = y ^ arr[i]; /*XOR of second set in arr[] */ } for (i = 1; i <= n; i++) { int a = i & set_bit_no; if (a != 0) x = x ^ i; /*XOR of first set in arr[] and {1, 2, ...n }*/ else y = y ^ i; /*XOR of second set in arr[] and {1, 2, ...n } */ } System.out.println(\"The two reppeated elements are :\"); System.out.println(x + \" \" + y); } /* Driver program to test the above function */ public static void main(String[] args) { RepeatElement repeat = new RepeatElement(); int arr[] = {4, 2, 4, 5, 2, 3, 1}; int arr_size = arr.length; repeat.printRepeating(arr, arr_size); }} // This code has been contributed by Mayank Jaiswal",
"e": 63671,
"s": 62006,
"text": null
},
{
"code": "# Python3 code to Find the# two repeating elements# in a given arraydef printRepeating(arr, size): # Will hold xor # of all elements xor = arr[0] n = size - 2 x = 0 y = 0 # Get the xor of all # elements in arr[] # and 1, 2 .. n for i in range(1 , size): xor ^= arr[i] for i in range(1 , n + 1): xor ^= i # Get the rightmost set # bit in set_bit_no set_bit_no = xor & ~(xor-1) # Now divide elements in two # sets by comparing rightmost # set bit of xor with bit at # same position in each element. for i in range(0, size): if(arr[i] & set_bit_no): # XOR of first # set in arr[] x = x ^ arr[i] else: # XOR of second # set in arr[] y = y ^ arr[i] for i in range(1 , n + 1): if(i & set_bit_no): # XOR of first set # in arr[] and # 1, 2, ...n x = x ^ i else: # XOR of second set # in arr[] and # 1, 2, ...n y = y ^ i print(\"The two repeating\", \"elements are\", y, x) # Driver code arr = [4, 2, 4, 5, 2, 3, 1]arr_size = len(arr)printRepeating(arr, arr_size) # This code is contributed# by Smitha",
"e": 65046,
"s": 63671,
"text": null
},
{
"code": "using System; class GFG{ static void printRepeating(int []arr, int size) { /* Will hold xor of all elements */ int xor = arr[0]; /* Will have only single set bit of xor */ int set_bit_no; int i; int n = size - 2; int x = 0, y = 0; /* Get the xor of all elements in arr[] and {1, 2 .. n} */ for (i = 1; i < size; i++) xor ^= arr[i]; for (i = 1; i <= n; i++) xor ^= i; /* Get the rightmost set bit in set_bit_no */ set_bit_no = (xor & ~(xor - 1)); /* Now divide elements in two sets by comparing rightmost set bit of xor with bit at same position in each element. */ for (i = 0; i < size; i++) { int a = arr[i] & set_bit_no; if (a != 0) /* XOR of first set in arr[] */ x = x ^ arr[i]; else /* XOR of second set in arr[] */ y = y ^ arr[i]; } for (i = 1; i <= n; i++) { int a = i & set_bit_no; if (a != 0) /* XOR of first set in arr[] and {1, 2, ...n }*/ x = x ^ i; else /* XOR of second set in arr[] and {1, 2, ...n } */ y = y ^ i; } Console.WriteLine(\"The two\" + \" reppeated elements are :\"); Console.Write(x + \" \" + y); } /* Driver program to test the above function */ public static void Main() { int []arr = {4, 2, 4, 5, 2, 3, 1}; int arr_size = arr.Length; printRepeating(arr, arr_size); }} // This code is contributed by Sam007",
"e": 66823,
"s": 65046,
"text": null
},
{
"code": "<?php// PHP code to Find the// two repeating elements// in a given arrayfunction printRepeating( $arr, $size){ $xor = $arr[0]; /* Will hold xor of all elements */ $set_bit_no; /* Will have only single set bit of xor */ $i; $n = $size - 2; $x = 0; $y = 0; /* Get the xor of all elements in arr[] and {1, 2 .. n} */ for($i = 1; $i < $size; $i++) $xor ^= $arr[$i]; for($i = 1; $i <= $n; $i++) $xor ^= $i; /* Get the rightmost set bit in set_bit_no */ $set_bit_no = $xor & ~($xor-1); /* Now divide elements in two sets by comparing rightmost set bit of xor with bit at same position in each element. */ for($i = 0; $i < $size; $i++) { if($arr[$i] & $set_bit_no) $x = $x ^ $arr[$i]; /*XOR of first set in arr[] */ else $y = $y ^ $arr[$i]; /*XOR of second set in arr[] */ } for($i = 1; $i <= $n; $i++) { if($i & $set_bit_no) /*XOR of first set in arr[] and {1, 2, ...n }*/ $x = $x ^ $i; else /*XOR of second set in arr[] and {1, 2, ...n } */ $y = $y ^ $i; } echo \"n The two repeating elements are \"; echo $y. \" \".$x; } $arr = array(4, 2, 4, 5, 2, 3, 1);$arr_size = count($arr);printRepeating($arr, $arr_size); // This code has been contributed by Rajput-Ji?>",
"e": 68152,
"s": 66823,
"text": null
},
{
"code": "<script> function printRepeating( arr, size){ let Xor = arr[0]; /* Will hold Xor of all elements */ let set_bit_no; /* Will have only single set bit of Xor */ let i; let n = size - 2; let x = 0, y = 0; /* Get the Xor of all elements in arr[] and {1, 2 .. n} */ for(i = 1; i < size; i++) Xor ^= arr[i]; for(i = 1; i <= n; i++) Xor ^= i; /* Get the rightmost set bit in set_bit_no */ set_bit_no = Xor & ~(Xor-1); /* Now divide elements in two sets by comparing rightmost set bit of Xor with bit at same position in each element. */ for(i = 0; i < size; i++) { if(arr[i] & set_bit_no) x = x ^ arr[i]; /*Xor of first set in arr[] */ else y = y ^ arr[i]; /*Xor of second set in arr[] */ } for(i = 1; i <= n; i++) { if(i & set_bit_no) x = x ^ i; /*Xor of first set in arr[] and {1, 2, ...n }*/ else y = y ^ i; /*Xor of second set in arr[] and {1, 2, ...n } */ } document.write(\"The two repeating elements are \"+y+\" \"+x);} // driver code let arr = [4, 2, 4, 5, 2, 3, 1]; let arr_size = arr.length; printRepeating(arr, arr_size); // This code is contributed by jana_sayantan.</script>",
"e": 69404,
"s": 68152,
"text": null
},
{
"code": null,
"e": 69439,
"s": 69404,
"text": "The two repeating elements are 4 2"
},
{
"code": null,
"e": 69535,
"s": 69439,
"text": "Method 5 (Use array elements as index) Thanks to Manish K. Aasawat for suggesting this method. "
},
{
"code": null,
"e": 70396,
"s": 69535,
"text": "Traverse the array. Do following for every index i of A[].\n{\ncheck for sign of A[abs(A[i])] ;\nif positive then\n make it negative by A[abs(A[i])]=-A[abs(A[i])];\nelse // i.e., A[abs(A[i])] is negative\n this element (ith element of list) is a repetition\n}\n\nExample: A[] = {1, 1, 2, 3, 2}\ni=0; \nCheck sign of A[abs(A[0])] which is A[1]. A[1] is positive, so make it negative. \nArray now becomes {1, -1, 2, 3, 2}\n\ni=1; \nCheck sign of A[abs(A[1])] which is A[1]. A[1] is negative, so A[1] is a repetition.\n\ni=2; \nCheck sign of A[abs(A[2])] which is A[2]. A[2] is positive, so make it negative. '\nArray now becomes {1, -1, -2, 3, 2}\n\ni=3; \nCheck sign of A[abs(A[3])] which is A[3]. A[3] is positive, so make it negative. \nArray now becomes {1, -1, -2, -3, 2}\n\ni=4; \nCheck sign of A[abs(A[4])] which is A[2]. A[2] is negative, so A[4] is a repetition."
},
{
"code": null,
"e": 70526,
"s": 70396,
"text": "Note that this method modifies the original array and may not be a recommended method if we are not allowed to modify the array. "
},
{
"code": null,
"e": 70530,
"s": 70526,
"text": "C++"
},
{
"code": null,
"e": 70532,
"s": 70530,
"text": "C"
},
{
"code": null,
"e": 70537,
"s": 70532,
"text": "Java"
},
{
"code": null,
"e": 70545,
"s": 70537,
"text": "Python3"
},
{
"code": null,
"e": 70548,
"s": 70545,
"text": "C#"
},
{
"code": null,
"e": 70552,
"s": 70548,
"text": "PHP"
},
{
"code": null,
"e": 70563,
"s": 70552,
"text": "Javascript"
},
{
"code": "#include <bits/stdc++.h>using namespace std; void printRepeating(int arr[], int size){ int i; cout << \"The repeating elements are\"; for(i = 0; i < size; i++) { if(arr[abs(arr[i])] > 0) arr[abs(arr[i])] = -arr[abs(arr[i])]; else cout<<\" \" << abs(arr[i]) <<\" \"; } } // Driver codeint main(){ int arr[] = {4, 2, 4, 5, 2, 3, 1}; int arr_size = sizeof(arr)/sizeof(arr[0]); printRepeating(arr, arr_size); return 0;} // This code is contributed by rathbhupendra",
"e": 71098,
"s": 70563,
"text": null
},
{
"code": "#include <stdio.h>#include <stdlib.h> void printRepeating(int arr[], int size){ int i; printf(\"\\n The repeating elements are\"); for(i = 0; i < size; i++) { if(arr[abs(arr[i])] > 0) arr[abs(arr[i])] = -arr[abs(arr[i])]; else printf(\" %d \", abs(arr[i])); } } int main(){ int arr[] = {4, 2, 4, 5, 2, 3, 1}; int arr_size = sizeof(arr)/sizeof(arr[0]); printRepeating(arr, arr_size); getchar(); return 0;}",
"e": 71541,
"s": 71098,
"text": null
},
{
"code": "class RepeatElement{ void printRepeating(int arr[], int size) { int i; System.out.println(\"The repeating elements are : \"); for(i = 0; i < size; i++) { int abs_val = Math.abs(arr[i]); if(arr[abs_val] > 0) arr[abs_val] = -arr[abs_val]; else System.out.print(abs_val + \" \"); } } /* Driver program to test the above function */ public static void main(String[] args) { RepeatElement repeat = new RepeatElement(); int arr[] = {4, 2, 4, 5, 2, 3, 1}; int arr_size = arr.length; repeat.printRepeating(arr, arr_size); }} // This code has been contributed by Mayank Jaiswal",
"e": 72266,
"s": 71541,
"text": null
},
{
"code": "# Python3 code for Find the two repeating# elements in a given array def printRepeating(arr, size) : print(\" The repeating elements are\",end=\" \") for i in range(0,size) : if(arr[abs(arr[i])] > 0) : arr[abs(arr[i])] = (-1) * arr[abs(arr[i])] else : print(abs(arr[i]),end = \" \") # Driver codearr = [4, 2, 4, 5, 2, 3, 1]arr_size = len(arr)printRepeating(arr, arr_size) # This code is contributed by Nikita Tiwari.",
"e": 72740,
"s": 72266,
"text": null
},
{
"code": "// C# code for Find the two repeating// elements in a given array using System; class GFG{ static void printRepeating(int []arr, int size) { int i; Console.Write(\"The repeating elements are : \"); for(i = 0; i < size; i++) { int abs_val = Math.Abs(arr[i]); if(arr[abs_val] > 0) arr[abs_val] = -arr[abs_val]; else Console.Write(abs_val + \" \"); } } /* Driver program to test the above function */ public static void Main() { int []arr = {4, 2, 4, 5, 2, 3, 1}; int arr_size = arr.Length; printRepeating(arr, arr_size); }} // This code is contributed by Sam007",
"e": 73457,
"s": 72740,
"text": null
},
{
"code": "<?php function printRepeating($arr, $size){ $i; echo \"The repeating elements are\",\" \"; for($i = 0; $i < $size; $i++){ if($arr[abs($arr[$i])] > 0) $arr[abs($arr[$i])] = -$arr[abs($arr[$i])]; else echo abs($arr[$i]),\" \";} } $arr = array (4, 2, 4, 5, 2, 3, 1); $arr_size = sizeof($arr); printRepeating($arr, $arr_size); #This code is contributed by aj_36?>",
"e": 73861,
"s": 73457,
"text": null
},
{
"code": "<script> function printRepeating(arr , size){ var i; document.write(\"The repeating elements are : \"); for(i = 0; i < size; i++) { var abs_val = Math.abs(arr[i]); if(arr[abs_val] > 0)x arr[abs_val] = -arr[abs_val]; else document.write(abs_val + \" \"); } } /* Driver program to test the above function */ var arr = [4, 2, 4, 5, 2, 3, 1];var arr_size = arr.length;printRepeating(arr, arr_size); // This code is contributed by 29AjayKumar </script>",
"e": 74404,
"s": 73861,
"text": null
},
{
"code": null,
"e": 74437,
"s": 74404,
"text": "The repeating elements are 4 2 "
},
{
"code": null,
"e": 74468,
"s": 74437,
"text": "Method 6 (Similar to method 5)"
},
{
"code": null,
"e": 74518,
"s": 74468,
"text": "Thanks to Vivek Kumar for suggesting this method."
},
{
"code": null,
"e": 74980,
"s": 74518,
"text": "The point is to increment every element at (arr[i]th-1)th index by N-1 (as the elements are present upto N-2 only) and at the same time check if element at that index when divided by (N-1) gives 2. If this is true then it means that the element has appeared twice and we can easily say that this is one of our answers. This is one of the very useful techniques when we want to calculate Frequencies of Limited Range Array Elements (see this post to know more)."
},
{
"code": null,
"e": 75392,
"s": 74980,
"text": "This method works on the fact that the remainder of an element when divided by any number greater than that element will always give that same element. Similarly, as we are incrementing each element at (arr[i]th-1) index by N-1, so when this incremented element is divided by N-1 it will give number of times we have added N-1 to it, hence giving us the occurrence of that index (according to 1-based indexing)."
},
{
"code": null,
"e": 75430,
"s": 75392,
"text": "Below given code applies this method:"
},
{
"code": null,
"e": 75434,
"s": 75430,
"text": "C++"
},
{
"code": null,
"e": 75439,
"s": 75434,
"text": "Java"
},
{
"code": null,
"e": 75447,
"s": 75439,
"text": "Python3"
},
{
"code": null,
"e": 75450,
"s": 75447,
"text": "C#"
},
{
"code": null,
"e": 75461,
"s": 75450,
"text": "Javascript"
},
{
"code": "#include <iostream>using namespace std; void twoRepeated(int arr[], int N){ int m = N - 1; for (int i = 0; i < N; i++) { arr[arr[i] % m - 1] += m; if ((arr[arr[i] % m - 1] / m) == 2) cout << arr[i] % m << \" \"; }}// Driver Codeint main(){ int arr[] = { 4, 2, 4, 5, 2, 3, 1 }; int n = sizeof(arr) / sizeof(arr[0]); cout << \"The two repeating elements are \"; twoRepeated(arr, n); return 0;}// This code is contributed by Kartik Singh Kushwah",
"e": 75950,
"s": 75461,
"text": null
},
{
"code": "import java.io.*; class GFG{ public static void twoRepeated(int arr[], int N){ int m = N - 1; for(int i = 0; i < N; i++) { arr[arr[i] % m - 1] += m; if ((arr[arr[i] % m - 1] / m) == 2) System.out.printf(arr[i] % m + \" \"); }} // Driver codepublic static void main(String[] args){ int arr[] = { 4, 2, 4, 5, 2, 3, 1 }; int n = 7; System.out.printf(\"The two repeating elements are \"); twoRepeated(arr, n);}} // This code is contributed by Potta Lokesh",
"e": 76470,
"s": 75950,
"text": null
},
{
"code": "# Python program for the above approachdef twoRepeated(arr, N): m = N - 1 for i in range(N): arr[arr[i] % m - 1] += m if ((arr[arr[i] % m - 1] // m) == 2): print(arr[i] % m ,end= \" \") # Driver Codearr = [4, 2, 4, 5, 2, 3, 1]n = len(arr)print(\"The two repeating elements are \", end = \"\")twoRepeated(arr, n) # This code is contributed by Shubham Singh",
"e": 76855,
"s": 76470,
"text": null
},
{
"code": "// C# program for the above approachusing System; public class GFG{public static void twoRepeated(int[] arr, int N){ int m = N - 1; for(int i = 0; i < N; i++) { arr[arr[i] % m - 1] += m; if ((arr[arr[i] % m - 1] / m) == 2) Console.Write(arr[i] % m + \" \"); }} // Driver codepublic static void Main(String []args){ int[] arr = { 4, 2, 4, 5, 2, 3, 1 }; int n = 7; Console.Write(\"The two repeating elements are \"); twoRepeated(arr, n);}} // This code is contributed by splevel62.",
"e": 77399,
"s": 76855,
"text": null
},
{
"code": "<script> function twoRepeated(arr, N){ let m = N - 1; for(let i = 0; i < N; i++) { arr[parseInt(arr[i] % m) - 1] += m; if (parseInt(arr[parseInt(arr[i] % m) - 1] / m) == 2) document.write(parseInt(arr[i] % m) + \" \"); }} // Driver Codevar arr = [ 4, 2, 4, 5, 2, 3, 1 ];var n = 7;document.write(\"The two repeating elements are \"); twoRepeated(arr, n); // This code is contributed by Potta Lokesh </script>",
"e": 77840,
"s": 77399,
"text": null
},
{
"code": null,
"e": 77876,
"s": 77840,
"text": "The two repeating elements are 4 2 "
},
{
"code": null,
"e": 78045,
"s": 77876,
"text": "Method 7The point here is to enter the array elements one by one into the unordered set. If a particular element is already present in the set it’s a repeating element."
},
{
"code": null,
"e": 78049,
"s": 78045,
"text": "C++"
},
{
"code": null,
"e": 78054,
"s": 78049,
"text": "Java"
},
{
"code": null,
"e": 78062,
"s": 78054,
"text": "Python3"
},
{
"code": null,
"e": 78065,
"s": 78062,
"text": "C#"
},
{
"code": null,
"e": 78076,
"s": 78065,
"text": "Javascript"
},
{
"code": "// C++ program to Find the two repeating// elements in a given array#include <bits/stdc++.h>using namespace std; void printRepeating(int arr[], int size){ unordered_set<int>s; cout<<\"The two Repeating elements are : \"; for(int i=0;i<size;i++) { if(s.empty()==false && s.find(arr[i])!=s.end()) cout<<arr[i]<<\" \"; s.insert(arr[i]); }} // Driver codeint main(){ int arr[] = {4, 2, 4, 5, 2, 3, 1}; int arr_size = sizeof(arr)/sizeof(arr[0]); printRepeating(arr, arr_size); return 0;} // This code is contributed by nakul amate",
"e": 78647,
"s": 78076,
"text": null
},
{
"code": "// Java program to Find the two repeating// elements in a given arrayimport java.util.*;class GFG{ static void printRepeating(int arr[], int size) { HashSet<Integer>s = new HashSet<>(); System.out.print(\"The two Repeating elements are : \"); for(int i = 0; i < size; i++) { if(!s.isEmpty() && s.contains(arr[i])) System.out.print(arr[i]+\" \"); s.add(arr[i]); } } // Driver code public static void main(String[] args) { int arr[] = {4, 2, 4, 5, 2, 3, 1}; int arr_size = arr.length; printRepeating(arr, arr_size); }} // This code is contributed by Rajput-Ji",
"e": 79252,
"s": 78647,
"text": null
},
{
"code": "# Python3 program to find the two repeating# elements in a given arraydef printRepeating(arr, size): s = set() print(\"The two Repeating elements are : \", end = \"\") for i in range(size): if (len(s) and arr[i] in s): print(arr[i], end = \" \") s.add(arr[i]) # Driver codearr = [ 4, 2, 4, 5, 2, 3, 1 ]arr_size = len(arr)printRepeating(arr, arr_size) # This code is contributed by Shubham Singh",
"e": 79707,
"s": 79252,
"text": null
},
{
"code": "// C# program to Find the two repeating// elements in a given arrayusing System;using System.Collections.Generic; public class GFG{ static void printRepeating(int[] arr, int size) { HashSet<int>s = new HashSet<int>(); Console.Write(\"The two Repeating elements are : \"); for(int i = 0; i < size; i++) { if(s.Count != 0 && s.Contains(arr[i])) Console.Write(arr[i] + \" \"); s.Add(arr[i]); } } // Driver code public static void Main() { int[] arr = {4, 2, 4, 5, 2, 3, 1}; int arr_size = arr.Length; printRepeating(arr, arr_size); }} // This code is contributed by Shubham Singh",
"e": 80335,
"s": 79707,
"text": null
},
{
"code": "<script> function printRepeating(arr, size){ const s = new Set(); document.write(\"The two repeating elements are \"); for(let i = 0; i < size; i++) { if(s.size != 0 && s.has(arr[i])) document.write(arr[i] + \" \"); s.add(arr[i]); }} // Driver Codevar arr = [ 4, 2, 4, 5, 2, 3, 1 ];var arr_size = 7;printRepeating(arr, arr_size); // This code is contributed by Shubham Singh </script>",
"e": 80761,
"s": 80335,
"text": null
},
{
"code": null,
"e": 80801,
"s": 80761,
"text": "The two Repeating elements are : 4 2 "
},
{
"code": null,
"e": 80825,
"s": 80801,
"text": "Time Complexity: O(n) "
},
{
"code": null,
"e": 80849,
"s": 80825,
"text": "Auxiliary Space: O(n) "
},
{
"code": null,
"e": 80969,
"s": 80849,
"text": " Please write comments if you find the above codes/algorithms incorrect, or find better ways to solve the same problem."
},
{
"code": null,
"e": 80975,
"s": 80969,
"text": "jit_t"
},
{
"code": null,
"e": 80996,
"s": 80975,
"text": "Smitha Dinesh Semwal"
},
{
"code": null,
"e": 81009,
"s": 80996,
"text": "Mithun Kumar"
},
{
"code": null,
"e": 81021,
"s": 81009,
"text": "29AjayKumar"
},
{
"code": null,
"e": 81031,
"s": 81021,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 81046,
"s": 81031,
"text": "Shivi_Aggarwal"
},
{
"code": null,
"e": 81060,
"s": 81046,
"text": "rathbhupendra"
},
{
"code": null,
"e": 81071,
"s": 81060,
"text": "nidhi_biet"
},
{
"code": null,
"e": 81081,
"s": 81071,
"text": "imaryan20"
},
{
"code": null,
"e": 81095,
"s": 81081,
"text": "jana_sayantan"
},
{
"code": null,
"e": 81110,
"s": 81095,
"text": "rameshtravel07"
},
{
"code": null,
"e": 81125,
"s": 81110,
"text": "vimlakushwah81"
},
{
"code": null,
"e": 81140,
"s": 81125,
"text": "sujalgupta6100"
},
{
"code": null,
"e": 81154,
"s": 81140,
"text": "lokeshpotta20"
},
{
"code": null,
"e": 81164,
"s": 81154,
"text": "splevel62"
},
{
"code": null,
"e": 81176,
"s": 81164,
"text": "nakul_amate"
},
{
"code": null,
"e": 81191,
"s": 81176,
"text": "SHUBHAMSINGH10"
},
{
"code": null,
"e": 81202,
"s": 81191,
"text": "yaliyunus4"
},
{
"code": null,
"e": 81213,
"s": 81202,
"text": "MakeMyTrip"
},
{
"code": null,
"e": 81220,
"s": 81213,
"text": "Arrays"
},
{
"code": null,
"e": 81231,
"s": 81220,
"text": "MakeMyTrip"
},
{
"code": null,
"e": 81238,
"s": 81231,
"text": "Arrays"
},
{
"code": null,
"e": 81336,
"s": 81238,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 81345,
"s": 81336,
"text": "Comments"
},
{
"code": null,
"e": 81358,
"s": 81345,
"text": "Old Comments"
},
{
"code": null,
"e": 81373,
"s": 81358,
"text": "Arrays in Java"
},
{
"code": null,
"e": 81389,
"s": 81373,
"text": "Arrays in C/C++"
},
{
"code": null,
"e": 81416,
"s": 81389,
"text": "Program for array rotation"
},
{
"code": null,
"e": 81464,
"s": 81416,
"text": "Stack Data Structure (Introduction and Program)"
},
{
"code": null,
"e": 81508,
"s": 81464,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 81554,
"s": 81508,
"text": "Write a program to reverse an array or string"
},
{
"code": null,
"e": 81586,
"s": 81554,
"text": "Largest Sum Contiguous Subarray"
},
{
"code": null,
"e": 81609,
"s": 81586,
"text": "Introduction to Arrays"
}
] |
Overview of Text Similarity Metrics in Python | by Sanket Gupta | Towards Data Science
|
While working on natural language models for search engines, I have frequently asked questions “How similar are these two words?”, “How similar are these two sentences?” , “How similar are these two documents?”. I have already talked about custom word embeddings in a previous post, where word meanings are taken into consideration for word similarity. In this blog post, we will look more into techniques for sentence or document similarity.
There are a few text similarity metrics but we will look at Jaccard Similarity and Cosine Similarity which are the most common ones.
Jaccard similarity or intersection over union is defined as size of intersection divided by size of union of two sets. Let’s take example of two sentences:
Sentence 1: AI is our friend and it has been friendlySentence 2: AI and humans have always been friendly
In order to calculate similarity using Jaccard similarity, we will first perform lemmatization to reduce words to the same root word. In our case, “friend” and “friendly” will both become “friend”, “has” and “have” will both become “has”. Drawing a Venn diagram of the two sentences we get:
For the above two sentences, we get Jaccard similarity of 5/(5+3+2) = 0.5 which is size of intersection of the set divided by total size of set. The code for Jaccard similarity in Python is:
def get_jaccard_sim(str1, str2): a = set(str1.split()) b = set(str2.split()) c = a.intersection(b) return float(len(c)) / (len(a) + len(b) - len(c))
One thing to note here is that since we use sets, “friend” appeared twice in Sentence 1 but it did not affect our calculations — this will change with Cosine Similarity.
Cosine similarity calculates similarity by measuring the cosine of angle between two vectors. This is calculated as:
With cosine similarity, we need to convert sentences into vectors. One way to do that is to use bag of words with either TF (term frequency) or TF-IDF (term frequency- inverse document frequency). The choice of TF or TF-IDF depends on application and is immaterial to how cosine similarity is actually performed — which just needs vectors. TF is good for text similarity in general, but TF-IDF is good for search query relevance.
Another way is to use Word2Vec or our own custom word embeddings to convert words into vectors. I have talked about training our own custom word embeddings in a previous post.
There are two main difference between tf/ tf-idf with bag of words and word embeddings: 1. tf / tf-idf creates one number per word, word embeddings typically creates one vector per word. 2. tf / tf-idf is good for classification documents as a whole, but word embeddings is good for identifying contextual content.
Let’s calculate cosine similarity for these two sentences:
Sentence 1: AI is our friend and it has been friendlySentence 2: AI and humans have always been friendly
Step 1, we will calculate Term Frequency using Bag of Words:
Step 2, The main issue with term frequency counts shown above is that it favors the documents or sentences that are longer. One way to solve this issue is to normalize the term frequencies with the respective magnitudes or L2 norms. Summing up squares of each frequency and taking a square root, L2 norm of Sentence 1 is 3.3166 and Sentence 2 is 2.6458. Dividing above term frequencies with these norms, we get:
Step 3, as we have already normalized the two vectors to have a length of 1, we can calculate the cosine similarity with a dot product: Cosine Similarity = (0.302*0.378) + (0.603*0.378) + (0.302*0.378) + (0.302*0.378) + (0.302*0.378) = 0.684
Therefore, cosine similarity of the two sentences is 0.684 which is different from Jaccard Similarity of the exact same two sentences which was 0.5 (calculated above)
The code for pairwise Cosine Similarity of strings in Python is:
from collections import Counterfrom sklearn.feature_extraction.text import CountVectorizerfrom sklearn.metrics.pairwise import cosine_similaritydef get_cosine_sim(*strs): vectors = [t for t in get_vectors(*strs)] return cosine_similarity(vectors) def get_vectors(*strs): text = [t for t in strs] vectorizer = CountVectorizer(text) vectorizer.fit(text) return vectorizer.transform(text).toarray()
Jaccard similarity takes only unique set of words for each sentence / document while cosine similarity takes total length of the vectors. (these vectors could be made from bag of words term frequency or tf-idf)This means that if you repeat the word “friend” in Sentence 1 several times, cosine similarity changes but Jaccard similarity does not. For ex, if the word “friend” is repeated in the first sentence 50 times, cosine similarity drops to 0.4 but Jaccard similarity remains at 0.5.Jaccard similarity is good for cases where duplication does not matter, cosine similarity is good for cases where duplication matters while analyzing text similarity. For two product descriptions, it will be better to use Jaccard similarity as repetition of a word does not reduce their similarity.
Jaccard similarity takes only unique set of words for each sentence / document while cosine similarity takes total length of the vectors. (these vectors could be made from bag of words term frequency or tf-idf)
This means that if you repeat the word “friend” in Sentence 1 several times, cosine similarity changes but Jaccard similarity does not. For ex, if the word “friend” is repeated in the first sentence 50 times, cosine similarity drops to 0.4 but Jaccard similarity remains at 0.5.
Jaccard similarity is good for cases where duplication does not matter, cosine similarity is good for cases where duplication matters while analyzing text similarity. For two product descriptions, it will be better to use Jaccard similarity as repetition of a word does not reduce their similarity.
If you know more applications for each, please mention in the comments below as it will help others. This concludes my blog on the overview of text similarity metrics. Good luck in your own explorations with text!
One of the best books I have found on the topic of information retrieval is Introduction to Information Retrieval, it is a fantastic book which covers lots of concepts on NLP, information retrieval and search.
Also, check out my PODCAST! I have a podcast called “The Data Life Podcast”. You can hear this wherever you get your podcasts. In this episode you will hear a really interesting conversation with Paul Azunre (author of Manning Book Transfer Learning in NLP) about trends in BERT, Elmo, word embeddings etc.
If you have any questions, drop me a note at my LinkedIn profile. Thanks for reading!
|
[
{
"code": null,
"e": 615,
"s": 172,
"text": "While working on natural language models for search engines, I have frequently asked questions “How similar are these two words?”, “How similar are these two sentences?” , “How similar are these two documents?”. I have already talked about custom word embeddings in a previous post, where word meanings are taken into consideration for word similarity. In this blog post, we will look more into techniques for sentence or document similarity."
},
{
"code": null,
"e": 748,
"s": 615,
"text": "There are a few text similarity metrics but we will look at Jaccard Similarity and Cosine Similarity which are the most common ones."
},
{
"code": null,
"e": 904,
"s": 748,
"text": "Jaccard similarity or intersection over union is defined as size of intersection divided by size of union of two sets. Let’s take example of two sentences:"
},
{
"code": null,
"e": 1009,
"s": 904,
"text": "Sentence 1: AI is our friend and it has been friendlySentence 2: AI and humans have always been friendly"
},
{
"code": null,
"e": 1300,
"s": 1009,
"text": "In order to calculate similarity using Jaccard similarity, we will first perform lemmatization to reduce words to the same root word. In our case, “friend” and “friendly” will both become “friend”, “has” and “have” will both become “has”. Drawing a Venn diagram of the two sentences we get:"
},
{
"code": null,
"e": 1491,
"s": 1300,
"text": "For the above two sentences, we get Jaccard similarity of 5/(5+3+2) = 0.5 which is size of intersection of the set divided by total size of set. The code for Jaccard similarity in Python is:"
},
{
"code": null,
"e": 1654,
"s": 1491,
"text": "def get_jaccard_sim(str1, str2): a = set(str1.split()) b = set(str2.split()) c = a.intersection(b) return float(len(c)) / (len(a) + len(b) - len(c))"
},
{
"code": null,
"e": 1824,
"s": 1654,
"text": "One thing to note here is that since we use sets, “friend” appeared twice in Sentence 1 but it did not affect our calculations — this will change with Cosine Similarity."
},
{
"code": null,
"e": 1941,
"s": 1824,
"text": "Cosine similarity calculates similarity by measuring the cosine of angle between two vectors. This is calculated as:"
},
{
"code": null,
"e": 2371,
"s": 1941,
"text": "With cosine similarity, we need to convert sentences into vectors. One way to do that is to use bag of words with either TF (term frequency) or TF-IDF (term frequency- inverse document frequency). The choice of TF or TF-IDF depends on application and is immaterial to how cosine similarity is actually performed — which just needs vectors. TF is good for text similarity in general, but TF-IDF is good for search query relevance."
},
{
"code": null,
"e": 2547,
"s": 2371,
"text": "Another way is to use Word2Vec or our own custom word embeddings to convert words into vectors. I have talked about training our own custom word embeddings in a previous post."
},
{
"code": null,
"e": 2862,
"s": 2547,
"text": "There are two main difference between tf/ tf-idf with bag of words and word embeddings: 1. tf / tf-idf creates one number per word, word embeddings typically creates one vector per word. 2. tf / tf-idf is good for classification documents as a whole, but word embeddings is good for identifying contextual content."
},
{
"code": null,
"e": 2921,
"s": 2862,
"text": "Let’s calculate cosine similarity for these two sentences:"
},
{
"code": null,
"e": 3026,
"s": 2921,
"text": "Sentence 1: AI is our friend and it has been friendlySentence 2: AI and humans have always been friendly"
},
{
"code": null,
"e": 3087,
"s": 3026,
"text": "Step 1, we will calculate Term Frequency using Bag of Words:"
},
{
"code": null,
"e": 3499,
"s": 3087,
"text": "Step 2, The main issue with term frequency counts shown above is that it favors the documents or sentences that are longer. One way to solve this issue is to normalize the term frequencies with the respective magnitudes or L2 norms. Summing up squares of each frequency and taking a square root, L2 norm of Sentence 1 is 3.3166 and Sentence 2 is 2.6458. Dividing above term frequencies with these norms, we get:"
},
{
"code": null,
"e": 3741,
"s": 3499,
"text": "Step 3, as we have already normalized the two vectors to have a length of 1, we can calculate the cosine similarity with a dot product: Cosine Similarity = (0.302*0.378) + (0.603*0.378) + (0.302*0.378) + (0.302*0.378) + (0.302*0.378) = 0.684"
},
{
"code": null,
"e": 3908,
"s": 3741,
"text": "Therefore, cosine similarity of the two sentences is 0.684 which is different from Jaccard Similarity of the exact same two sentences which was 0.5 (calculated above)"
},
{
"code": null,
"e": 3973,
"s": 3908,
"text": "The code for pairwise Cosine Similarity of strings in Python is:"
},
{
"code": null,
"e": 4391,
"s": 3973,
"text": "from collections import Counterfrom sklearn.feature_extraction.text import CountVectorizerfrom sklearn.metrics.pairwise import cosine_similaritydef get_cosine_sim(*strs): vectors = [t for t in get_vectors(*strs)] return cosine_similarity(vectors) def get_vectors(*strs): text = [t for t in strs] vectorizer = CountVectorizer(text) vectorizer.fit(text) return vectorizer.transform(text).toarray()"
},
{
"code": null,
"e": 5178,
"s": 4391,
"text": "Jaccard similarity takes only unique set of words for each sentence / document while cosine similarity takes total length of the vectors. (these vectors could be made from bag of words term frequency or tf-idf)This means that if you repeat the word “friend” in Sentence 1 several times, cosine similarity changes but Jaccard similarity does not. For ex, if the word “friend” is repeated in the first sentence 50 times, cosine similarity drops to 0.4 but Jaccard similarity remains at 0.5.Jaccard similarity is good for cases where duplication does not matter, cosine similarity is good for cases where duplication matters while analyzing text similarity. For two product descriptions, it will be better to use Jaccard similarity as repetition of a word does not reduce their similarity."
},
{
"code": null,
"e": 5389,
"s": 5178,
"text": "Jaccard similarity takes only unique set of words for each sentence / document while cosine similarity takes total length of the vectors. (these vectors could be made from bag of words term frequency or tf-idf)"
},
{
"code": null,
"e": 5668,
"s": 5389,
"text": "This means that if you repeat the word “friend” in Sentence 1 several times, cosine similarity changes but Jaccard similarity does not. For ex, if the word “friend” is repeated in the first sentence 50 times, cosine similarity drops to 0.4 but Jaccard similarity remains at 0.5."
},
{
"code": null,
"e": 5967,
"s": 5668,
"text": "Jaccard similarity is good for cases where duplication does not matter, cosine similarity is good for cases where duplication matters while analyzing text similarity. For two product descriptions, it will be better to use Jaccard similarity as repetition of a word does not reduce their similarity."
},
{
"code": null,
"e": 6181,
"s": 5967,
"text": "If you know more applications for each, please mention in the comments below as it will help others. This concludes my blog on the overview of text similarity metrics. Good luck in your own explorations with text!"
},
{
"code": null,
"e": 6391,
"s": 6181,
"text": "One of the best books I have found on the topic of information retrieval is Introduction to Information Retrieval, it is a fantastic book which covers lots of concepts on NLP, information retrieval and search."
},
{
"code": null,
"e": 6698,
"s": 6391,
"text": "Also, check out my PODCAST! I have a podcast called “The Data Life Podcast”. You can hear this wherever you get your podcasts. In this episode you will hear a really interesting conversation with Paul Azunre (author of Manning Book Transfer Learning in NLP) about trends in BERT, Elmo, word embeddings etc."
}
] |
C# | Enumeration (or enum) - GeeksforGeeks
|
21 Sep, 2021
Enumeration (or enum) is a value data type in C#. It is mainly used to assign the names or string values to integral constants, that make a program easy to read and maintain. For example, the 4 suits in a deck of playing cards may be 4 enumerators named Club, Diamond, Heart, and Spade, belonging to an enumerated type named Suit. Other examples include natural enumerated types (like the planets, days of the week, colors, directions, etc.). The main objective of enum is to define our own data types(Enumerated Data Types). Enumeration is declared using enum keyword directly inside a namespace, class, or structure.
Syntax:
enum Enum_variable
{
string_1...;
string_2...;
.
.
}
In above syntax, Enum_variable is the name of the enumerator, and string_1 is attached with value 0, string_2 is attached value 1 and so on. Because by default, the first member of an enum has the value 0, and the value of each successive enum member is increased by 1. We can change this default value.
Example 1: Consider the below code for the enum. Here enum with name month is created and its data members are the name of months like jan, feb, mar, apr, may. Now let’s try to print the default integer values of these enums. An explicit cast is required to convert from enum type to an integral type.
C#
// C# program to illustrate the enums// with their default valuesusing System;namespace ConsoleApplication1 { // making an enumerator 'month'enum month{ // following are the data members jan, feb, mar, apr, may } class Program { // Main Method static void Main(string[] args) { // getting the integer values of data members.. Console.WriteLine("The value of jan in month " + "enum is " + (int)month.jan); Console.WriteLine("The value of feb in month " + "enum is " + (int)month.feb); Console.WriteLine("The value of mar in month " + "enum is " + (int)month.mar); Console.WriteLine("The value of apr in month " + "enum is " + (int)month.apr); Console.WriteLine("The value of may in month " + "enum is " + (int)month.may); }}}
The value of jan in month enum is 0
The value of feb in month enum is 1
The value of mar in month enum is 2
The value of apr in month enum is 3
The value of may in month enum is 4
Example 2: In the below code, an enumerator with name shapes is created with string data members as Circle which is by default initialized to value 0 and similarly, Square is assigned value 1 inside the class Perimeter. There is also one member function peri() which takes one parameter as a value to initializes the side/radius. Another parameter is used to judge the shape whether it is circle or square in the form of an integer value(0 or 1). Now in the main() method, an object of the Perimeter class is created. During the call of method peri(), Perimeter.shapes.circle denotes that it is a circle with value 0 and similar is the case for Perimeter.shapes.square with value 1. So inside the method, if the s1 object has value 0 then it is circle and hence its circumference is calculated and same is the case for square perimeter.
C#
// C# program to illustrate the Enumsusing System;namespace ConsoleApplication2 { class Perimeter { // declaring enum public enum shapes { circle, square } public void peri(int val, shapes s1) { // checking for shape to be circle if (s1 == 0) { // Output the circumference Console.WriteLine("Circumference of the circle is " + 2 * 3.14 * val); } else { // else output the perimeter of the square Console.WriteLine("Perimeter of the square is " + 4 * val); } }} class Program { // Main Method static void Main(string[] args) { Perimeter a1 = new Perimeter(); a1.peri(3, Perimeter.shapes.circle); a1.peri(4, Perimeter.shapes.square); }}}
Circumference of the circle is 18.84
Perimeter of the square is 16
Initialization of enum: As discussed above, that the default value of first enum member is set to 0 and it increases by 1 for the further data members of enum. However, the user can also change these default value.
Example:
enum days {
day1 = 1,
day2 = day1 + 1,
day3 = day1 + 2
.
.
}
In above example, day1 is assigned value ‘1’ by the user, day2 will be assigned value ‘2’ and similar is the case with day3 member. So you have to just change the value of first data member of enum, further data members of enums will increase by 1 than the previous one automatically.
Note: Now, if the data member of enum member has not been initialized, then its value is set according to rules stated below:
if it is the first member, then it value is set to 0 otherwise
It set out the value which is obtained by adding 1 to the previous value of enum data member
Example:
enum random {
A,
B,
C = 6;
D
}
Here, A is set to 0 by default, B will be incremented to 1. However, as C is initialized with 6 so the value of D will be 7
Program: To demonstrate the initialization of enum data member with user define values and also some special case of initialization.
C#
// C# program to illustrate the enum// data member Initialisationusing System;namespace ConsoleApplication3 { // enum declarationenum days { // enum data members monday, tuesday, wednesday, thursday, friday, saturday, sunday} // enum declarationenum color { // enum data members Red, Yellow, Blue, // assigning value yellow(1) + 5 Green = Yellow + 5, Brown, // assigning value Green(6) + 3 Black = Green + 3 } class Program { // Main Method static void Main(string[] args) { Console.WriteLine("Demonstrating the difference "+ "between Special Initialisation" + "cases and non-initialisation cases\n\n"); // first of all non-initialized enum // 'days' will be displayed // as mentioned already, the first // member is initialized to 0 // hence the output will numbers // from 0 1 2 3 4 5 6 Console.WriteLine("Value of Monday is " + (int)days.monday); Console.WriteLine("Value of Tuesday is " + (int)days.tuesday); Console.WriteLine("Value of Wednesday is " + (int)days.wednesday); Console.WriteLine("Value of Thursday is " + (int)days.thursday); Console.WriteLine("Value of Friday is " + (int)days.friday); Console.WriteLine("Value of Saturday is " + (int)days.saturday); Console.WriteLine("Value of Sunday is " + (int)days.sunday); // Now the use of special initialisation // cases is demonstrated as expected Red // will be assigned 0 value similarly // yellow will be 1 and blue will be 2 // however, green will be assigned the // value 1+5=6 similarly is the case // with brown and black Console.WriteLine("\n\nColor Enum"); Console.WriteLine("Value of Red Color is " + (int)color.Red); Console.WriteLine("Value of Yellow Color is " + (int)color.Yellow); Console.WriteLine("Value of Blue Color is " + (int)color.Blue); Console.WriteLine("Value of Green Color is " + (int)color.Green); Console.WriteLine("Value of Brown Color is " + (int)color.Brown); Console.WriteLine("Value of Black Color is " + (int)color.Black); }}}
Demonstrating the difference between Special Initialisationcases and non-initialisation cases
Value of Monday is 0
Value of Tuesday is 1
Value of Wednesday is 2
Value of Thursday is 3
Value of Friday is 4
Value of Saturday is 5
Value of Sunday is 6
Color Enum
Value of Red Color is 0
Value of Yellow Color is 1
Value of Blue Color is 2
Value of Green Color is 6
Value of Brown Color is 7
Value of Black Color is 9
Explanation: In above code, we have form two types of enums i.e color and days. In case of days enum, no initialization is done. So as per the rules monday will be assigned 0 and by the increment of 1, the values of tuesday, wednesday and other days will be decided. However, in case of enum color, Red will be assigned 0, Yellow will be given value 1 and so is the case of Blue. But in case of Green, its value will be decided by adding the value of Yellow with 5 which results in value 6. Again, in case of Brown, its value will be 7 and in case of Black, its value will be (7 + 3) which is 10.
Changing the type of Enum’s Data Member: By default the base data type of enumerator in C# is int. However, the user can change it as per convenience like bool, long, double, etc.
Example:
// byte type
enum button : byte {
// OFF will be assigned 0
OFF,
//ON will be assigned 1
ON
// However, if we assign 100 to ON then,
// this will give error as byte cannot hold this
}
Program: To demonstrate the changing of data type of members of enum
C#
// C# program to illustrate the changing// of data type of enum membersusing System;namespace ConsoleApplication4 { // changing the type to byte using :enum Button : byte { // OFF denotes the Button is // switched Off... with value 0 OFF, // ON denotes the Button is // switched on.. with value 1 ON } class Program { // Main Method static void Main(string[] args) { Console.WriteLine("Enter 0 or 1 to know the " + "state of electric switch!"); byte i = Convert.ToByte(Console.ReadLine()); if (i == (byte)Button.OFF) { Console.WriteLine("The electric switch is Off"); } else if (i == (byte)Button.ON) { Console.WriteLine("The electric switch is ON"); } else { Console.WriteLine("byte cannot hold such" + " large value"); } }}}
Input:
1
Output:
Enter 0 or 1 to know the state of electric switch!
The electric switch is ON
rajeev0719singh
sooda367
as5853535
akshaysingh98088
CSharp-Basics
CSharp-data-types
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
C# Dictionary with examples
Difference between Ref and Out keywords in C#
Introduction to .NET Framework
Extension Method in C#
C# | String.IndexOf( ) Method | Set - 1
C# | Abstract Classes
C# | Delegates
Top 50 C# Interview Questions & Answers
Different ways to sort an array in descending order in C#
C# | Replace() Method
|
[
{
"code": null,
"e": 23784,
"s": 23756,
"text": "\n21 Sep, 2021"
},
{
"code": null,
"e": 24403,
"s": 23784,
"text": "Enumeration (or enum) is a value data type in C#. It is mainly used to assign the names or string values to integral constants, that make a program easy to read and maintain. For example, the 4 suits in a deck of playing cards may be 4 enumerators named Club, Diamond, Heart, and Spade, belonging to an enumerated type named Suit. Other examples include natural enumerated types (like the planets, days of the week, colors, directions, etc.). The main objective of enum is to define our own data types(Enumerated Data Types). Enumeration is declared using enum keyword directly inside a namespace, class, or structure."
},
{
"code": null,
"e": 24411,
"s": 24403,
"text": "Syntax:"
},
{
"code": null,
"e": 24484,
"s": 24411,
"text": "enum Enum_variable\n{\n string_1...;\n string_2...;\n .\n .\n}"
},
{
"code": null,
"e": 24789,
"s": 24484,
"text": "In above syntax, Enum_variable is the name of the enumerator, and string_1 is attached with value 0, string_2 is attached value 1 and so on. Because by default, the first member of an enum has the value 0, and the value of each successive enum member is increased by 1. We can change this default value. "
},
{
"code": null,
"e": 25091,
"s": 24789,
"text": "Example 1: Consider the below code for the enum. Here enum with name month is created and its data members are the name of months like jan, feb, mar, apr, may. Now let’s try to print the default integer values of these enums. An explicit cast is required to convert from enum type to an integral type."
},
{
"code": null,
"e": 25094,
"s": 25091,
"text": "C#"
},
{
"code": "// C# program to illustrate the enums// with their default valuesusing System;namespace ConsoleApplication1 { // making an enumerator 'month'enum month{ // following are the data members jan, feb, mar, apr, may } class Program { // Main Method static void Main(string[] args) { // getting the integer values of data members.. Console.WriteLine(\"The value of jan in month \" + \"enum is \" + (int)month.jan); Console.WriteLine(\"The value of feb in month \" + \"enum is \" + (int)month.feb); Console.WriteLine(\"The value of mar in month \" + \"enum is \" + (int)month.mar); Console.WriteLine(\"The value of apr in month \" + \"enum is \" + (int)month.apr); Console.WriteLine(\"The value of may in month \" + \"enum is \" + (int)month.may); }}}",
"e": 26031,
"s": 25094,
"text": null
},
{
"code": null,
"e": 26211,
"s": 26031,
"text": "The value of jan in month enum is 0\nThe value of feb in month enum is 1\nThe value of mar in month enum is 2\nThe value of apr in month enum is 3\nThe value of may in month enum is 4"
},
{
"code": null,
"e": 27050,
"s": 26213,
"text": "Example 2: In the below code, an enumerator with name shapes is created with string data members as Circle which is by default initialized to value 0 and similarly, Square is assigned value 1 inside the class Perimeter. There is also one member function peri() which takes one parameter as a value to initializes the side/radius. Another parameter is used to judge the shape whether it is circle or square in the form of an integer value(0 or 1). Now in the main() method, an object of the Perimeter class is created. During the call of method peri(), Perimeter.shapes.circle denotes that it is a circle with value 0 and similar is the case for Perimeter.shapes.square with value 1. So inside the method, if the s1 object has value 0 then it is circle and hence its circumference is calculated and same is the case for square perimeter."
},
{
"code": null,
"e": 27053,
"s": 27050,
"text": "C#"
},
{
"code": "// C# program to illustrate the Enumsusing System;namespace ConsoleApplication2 { class Perimeter { // declaring enum public enum shapes { circle, square } public void peri(int val, shapes s1) { // checking for shape to be circle if (s1 == 0) { // Output the circumference Console.WriteLine(\"Circumference of the circle is \" + 2 * 3.14 * val); } else { // else output the perimeter of the square Console.WriteLine(\"Perimeter of the square is \" + 4 * val); } }} class Program { // Main Method static void Main(string[] args) { Perimeter a1 = new Perimeter(); a1.peri(3, Perimeter.shapes.circle); a1.peri(4, Perimeter.shapes.square); }}}",
"e": 28000,
"s": 27053,
"text": null
},
{
"code": null,
"e": 28067,
"s": 28000,
"text": "Circumference of the circle is 18.84\nPerimeter of the square is 16"
},
{
"code": null,
"e": 28286,
"s": 28069,
"text": "Initialization of enum: As discussed above, that the default value of first enum member is set to 0 and it increases by 1 for the further data members of enum. However, the user can also change these default value. "
},
{
"code": null,
"e": 28295,
"s": 28286,
"text": "Example:"
},
{
"code": null,
"e": 28390,
"s": 28295,
"text": "enum days {\n\n day1 = 1,\n\n day2 = day1 + 1,\n\n day3 = day1 + 2\n .\n .\n\n}"
},
{
"code": null,
"e": 28675,
"s": 28390,
"text": "In above example, day1 is assigned value ‘1’ by the user, day2 will be assigned value ‘2’ and similar is the case with day3 member. So you have to just change the value of first data member of enum, further data members of enums will increase by 1 than the previous one automatically."
},
{
"code": null,
"e": 28802,
"s": 28675,
"text": "Note: Now, if the data member of enum member has not been initialized, then its value is set according to rules stated below: "
},
{
"code": null,
"e": 28865,
"s": 28802,
"text": "if it is the first member, then it value is set to 0 otherwise"
},
{
"code": null,
"e": 28958,
"s": 28865,
"text": "It set out the value which is obtained by adding 1 to the previous value of enum data member"
},
{
"code": null,
"e": 28967,
"s": 28958,
"text": "Example:"
},
{
"code": null,
"e": 29003,
"s": 28967,
"text": "enum random {\n\nA,\n\nB,\n\nC = 6;\n\nD\n\n}"
},
{
"code": null,
"e": 29127,
"s": 29003,
"text": "Here, A is set to 0 by default, B will be incremented to 1. However, as C is initialized with 6 so the value of D will be 7"
},
{
"code": null,
"e": 29260,
"s": 29127,
"text": "Program: To demonstrate the initialization of enum data member with user define values and also some special case of initialization."
},
{
"code": null,
"e": 29263,
"s": 29260,
"text": "C#"
},
{
"code": "// C# program to illustrate the enum// data member Initialisationusing System;namespace ConsoleApplication3 { // enum declarationenum days { // enum data members monday, tuesday, wednesday, thursday, friday, saturday, sunday} // enum declarationenum color { // enum data members Red, Yellow, Blue, // assigning value yellow(1) + 5 Green = Yellow + 5, Brown, // assigning value Green(6) + 3 Black = Green + 3 } class Program { // Main Method static void Main(string[] args) { Console.WriteLine(\"Demonstrating the difference \"+ \"between Special Initialisation\" + \"cases and non-initialisation cases\\n\\n\"); // first of all non-initialized enum // 'days' will be displayed // as mentioned already, the first // member is initialized to 0 // hence the output will numbers // from 0 1 2 3 4 5 6 Console.WriteLine(\"Value of Monday is \" + (int)days.monday); Console.WriteLine(\"Value of Tuesday is \" + (int)days.tuesday); Console.WriteLine(\"Value of Wednesday is \" + (int)days.wednesday); Console.WriteLine(\"Value of Thursday is \" + (int)days.thursday); Console.WriteLine(\"Value of Friday is \" + (int)days.friday); Console.WriteLine(\"Value of Saturday is \" + (int)days.saturday); Console.WriteLine(\"Value of Sunday is \" + (int)days.sunday); // Now the use of special initialisation // cases is demonstrated as expected Red // will be assigned 0 value similarly // yellow will be 1 and blue will be 2 // however, green will be assigned the // value 1+5=6 similarly is the case // with brown and black Console.WriteLine(\"\\n\\nColor Enum\"); Console.WriteLine(\"Value of Red Color is \" + (int)color.Red); Console.WriteLine(\"Value of Yellow Color is \" + (int)color.Yellow); Console.WriteLine(\"Value of Blue Color is \" + (int)color.Blue); Console.WriteLine(\"Value of Green Color is \" + (int)color.Green); Console.WriteLine(\"Value of Brown Color is \" + (int)color.Brown); Console.WriteLine(\"Value of Black Color is \" + (int)color.Black); }}}",
"e": 31985,
"s": 29263,
"text": null
},
{
"code": null,
"e": 32403,
"s": 31985,
"text": "Demonstrating the difference between Special Initialisationcases and non-initialisation cases\n\n\nValue of Monday is 0\nValue of Tuesday is 1\nValue of Wednesday is 2\nValue of Thursday is 3\nValue of Friday is 4\nValue of Saturday is 5\nValue of Sunday is 6\n\n\nColor Enum\nValue of Red Color is 0\nValue of Yellow Color is 1\nValue of Blue Color is 2\nValue of Green Color is 6\nValue of Brown Color is 7\nValue of Black Color is 9"
},
{
"code": null,
"e": 33000,
"s": 32403,
"text": "Explanation: In above code, we have form two types of enums i.e color and days. In case of days enum, no initialization is done. So as per the rules monday will be assigned 0 and by the increment of 1, the values of tuesday, wednesday and other days will be decided. However, in case of enum color, Red will be assigned 0, Yellow will be given value 1 and so is the case of Blue. But in case of Green, its value will be decided by adding the value of Yellow with 5 which results in value 6. Again, in case of Brown, its value will be 7 and in case of Black, its value will be (7 + 3) which is 10."
},
{
"code": null,
"e": 33181,
"s": 33000,
"text": "Changing the type of Enum’s Data Member: By default the base data type of enumerator in C# is int. However, the user can change it as per convenience like bool, long, double, etc. "
},
{
"code": null,
"e": 33190,
"s": 33181,
"text": "Example:"
},
{
"code": null,
"e": 33379,
"s": 33190,
"text": "// byte type\nenum button : byte {\n\n// OFF will be assigned 0\nOFF,\n\n//ON will be assigned 1\nON\n\n// However, if we assign 100 to ON then, \n// this will give error as byte cannot hold this\n\n}"
},
{
"code": null,
"e": 33448,
"s": 33379,
"text": "Program: To demonstrate the changing of data type of members of enum"
},
{
"code": null,
"e": 33451,
"s": 33448,
"text": "C#"
},
{
"code": "// C# program to illustrate the changing// of data type of enum membersusing System;namespace ConsoleApplication4 { // changing the type to byte using :enum Button : byte { // OFF denotes the Button is // switched Off... with value 0 OFF, // ON denotes the Button is // switched on.. with value 1 ON } class Program { // Main Method static void Main(string[] args) { Console.WriteLine(\"Enter 0 or 1 to know the \" + \"state of electric switch!\"); byte i = Convert.ToByte(Console.ReadLine()); if (i == (byte)Button.OFF) { Console.WriteLine(\"The electric switch is Off\"); } else if (i == (byte)Button.ON) { Console.WriteLine(\"The electric switch is ON\"); } else { Console.WriteLine(\"byte cannot hold such\" + \" large value\"); } }}}",
"e": 34410,
"s": 33451,
"text": null
},
{
"code": null,
"e": 34417,
"s": 34410,
"text": "Input:"
},
{
"code": null,
"e": 34419,
"s": 34417,
"text": "1"
},
{
"code": null,
"e": 34427,
"s": 34419,
"text": "Output:"
},
{
"code": null,
"e": 34504,
"s": 34427,
"text": "Enter 0 or 1 to know the state of electric switch!\nThe electric switch is ON"
},
{
"code": null,
"e": 34520,
"s": 34504,
"text": "rajeev0719singh"
},
{
"code": null,
"e": 34529,
"s": 34520,
"text": "sooda367"
},
{
"code": null,
"e": 34539,
"s": 34529,
"text": "as5853535"
},
{
"code": null,
"e": 34556,
"s": 34539,
"text": "akshaysingh98088"
},
{
"code": null,
"e": 34570,
"s": 34556,
"text": "CSharp-Basics"
},
{
"code": null,
"e": 34588,
"s": 34570,
"text": "CSharp-data-types"
},
{
"code": null,
"e": 34591,
"s": 34588,
"text": "C#"
},
{
"code": null,
"e": 34689,
"s": 34591,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 34698,
"s": 34689,
"text": "Comments"
},
{
"code": null,
"e": 34711,
"s": 34698,
"text": "Old Comments"
},
{
"code": null,
"e": 34739,
"s": 34711,
"text": "C# Dictionary with examples"
},
{
"code": null,
"e": 34785,
"s": 34739,
"text": "Difference between Ref and Out keywords in C#"
},
{
"code": null,
"e": 34816,
"s": 34785,
"text": "Introduction to .NET Framework"
},
{
"code": null,
"e": 34839,
"s": 34816,
"text": "Extension Method in C#"
},
{
"code": null,
"e": 34879,
"s": 34839,
"text": "C# | String.IndexOf( ) Method | Set - 1"
},
{
"code": null,
"e": 34901,
"s": 34879,
"text": "C# | Abstract Classes"
},
{
"code": null,
"e": 34916,
"s": 34901,
"text": "C# | Delegates"
},
{
"code": null,
"e": 34956,
"s": 34916,
"text": "Top 50 C# Interview Questions & Answers"
},
{
"code": null,
"e": 35014,
"s": 34956,
"text": "Different ways to sort an array in descending order in C#"
}
] |
CSS Tutorial
|
CSS is the language we use to style an HTML document.
CSS describes how HTML elements should be displayed.
This tutorial will teach you CSS from basic to advanced.
This CSS tutorial contains hundreds of CSS examples.
With our online editor, you can edit the CSS, and click on a button to view the result.
Click on the "Try it Yourself" button to see how it works.
Learn from over 300 examples! With our editor, you can edit the CSS, and click on a
button to view the result.
Go to CSS Examples!
We recommend reading this tutorial, in the sequence listed in the menu.
If you have a large screen, the menu will always be present on the left.
If you have a small screen, open the menu by clicking the top menu sign ☰.
We have created some responsive W3.CSS templates for you to use.
You are free to modify, save, share, and use them in all your projects.
Free CSS Templates!
Set the color of all <p> elements to red.
<style>
{
red;
}
</style>
Start the Exercise
Test your CSS skills with a quiz.
Start CSS Quiz!
At W3Schools you will find complete CSS references of all properties and selectors with syntax, examples, browser support, and more.
Get certified by completing the CSS course
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:
[email protected]
Your message has been sent to W3Schools.
|
[
{
"code": null,
"e": 54,
"s": 0,
"text": "CSS is the language we use to style an HTML document."
},
{
"code": null,
"e": 107,
"s": 54,
"text": "CSS describes how HTML elements should be displayed."
},
{
"code": null,
"e": 164,
"s": 107,
"text": "This tutorial will teach you CSS from basic to advanced."
},
{
"code": null,
"e": 217,
"s": 164,
"text": "This CSS tutorial contains hundreds of CSS examples."
},
{
"code": null,
"e": 305,
"s": 217,
"text": "With our online editor, you can edit the CSS, and click on a button to view the result."
},
{
"code": null,
"e": 364,
"s": 305,
"text": "Click on the \"Try it Yourself\" button to see how it works."
},
{
"code": null,
"e": 475,
"s": 364,
"text": "Learn from over 300 examples! With our editor, you can edit the CSS, and click on a\nbutton to view the result."
},
{
"code": null,
"e": 495,
"s": 475,
"text": "Go to CSS Examples!"
},
{
"code": null,
"e": 567,
"s": 495,
"text": "We recommend reading this tutorial, in the sequence listed in the menu."
},
{
"code": null,
"e": 640,
"s": 567,
"text": "If you have a large screen, the menu will always be present on the left."
},
{
"code": null,
"e": 715,
"s": 640,
"text": "If you have a small screen, open the menu by clicking the top menu sign ☰."
},
{
"code": null,
"e": 780,
"s": 715,
"text": "We have created some responsive W3.CSS templates for you to use."
},
{
"code": null,
"e": 852,
"s": 780,
"text": "You are free to modify, save, share, and use them in all your projects."
},
{
"code": null,
"e": 872,
"s": 852,
"text": "Free CSS Templates!"
},
{
"code": null,
"e": 914,
"s": 872,
"text": "Set the color of all <p> elements to red."
},
{
"code": null,
"e": 945,
"s": 914,
"text": "<style>\n {\n red;\n}\n</style>\n"
},
{
"code": null,
"e": 964,
"s": 945,
"text": "Start the Exercise"
},
{
"code": null,
"e": 998,
"s": 964,
"text": "Test your CSS skills with a quiz."
},
{
"code": null,
"e": 1014,
"s": 998,
"text": "Start CSS Quiz!"
},
{
"code": null,
"e": 1147,
"s": 1014,
"text": "At W3Schools you will find complete CSS references of all properties and selectors with syntax, examples, browser support, and more."
},
{
"code": null,
"e": 1190,
"s": 1147,
"text": "Get certified by completing the CSS course"
},
{
"code": null,
"e": 1223,
"s": 1190,
"text": "We just launchedW3Schools videos"
},
{
"code": null,
"e": 1265,
"s": 1223,
"text": "Get certifiedby completinga course today!"
},
{
"code": null,
"e": 1372,
"s": 1265,
"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": 1391,
"s": 1372,
"text": "[email protected]"
}
] |
Mask Detection using YOLOv5. Explanation of key concepts followed by... | by Sean Yap | Towards Data Science
|
I recently completed DeepLearningAI’s Convolutional Neural Network course taught by Andrew Ng on Coursera and a portion of the course dwelled into the field of Computer Vision. I was fascinated by the capability of computer vision and how it can be integrated into our daily lives which motivated me to dive deeper into computer vision and initiate projects to enforce my learning.
Before implementing a project, it's best to understand a few fundamental concepts on Object Detection and how it works together. Let's start by defining Object Detection:
Image classification is where an algorithm is applied to an image to predict the class of one object eg: Car. Object localization not only predicts the class of objects but also figures out the location of the object by drawing a bounding box around the object. Object detection involves both classification and localization and detects more than one object & more than one class even.
A standard classification task would involve an image running through a Convnet with multiple layers in which vector features are fed into a softmax unit for example that outputs the predicted class (Object categories that the algorithm is trying to detect i.e cars, trees, pedestrians). Object detection models such as YOLO works by splitting images into a grid of cells where each grid cell is responsible for predicting a bounding box if the centre of the bounding box lies in the cell. It will then output the predicted class, coordinates of the bounding box as shown below:
To learn more about convolutional neural networks, look up Convolutional Neural Networks, Explained by Mayank Mishra. He does a pretty good job at explaining how Convnet works
When the algorithm outputs bounding boxes localizing objects detected, how do you tell if the algorithm is working well? This is where Intersection over Union(IoU) comes into play. Generally, IoU is a measure of overlap between two bounding boxes: algorithm predicted bounding box and ground truth bounding box.
The formula for IoU is the size of the intersection divided by the size of the union of both bounding boxes. The threshold for IoU is around 0.5. IoUs with values ≥ 0.5 are deemed “correct” predictions.
With reference to the bounding box image below, cells labeled 1–33 all predict that the centre of the bounding box lies in their cell.
This will lead to the algorithm detecting the object multiple times instead of just once. This is where Non-max suppression comes in where it ensures the algorithm detects each object only once. As was previously stated, each cell outputs y = (Pc, bx, bγ, bw, bh, c) with Pc being the probability there is an object. What Non-max suppression does is it takes the bounding box with the highest Pc, discards any bounding boxes with Pc ≤ 0.6and “silences” the other bounding boxes with IoU ≥ 0.5.
What if multiple objects lie in the same grid cell? How would the bounding boxes be like? Here’s where the idea of anchor boxes can be used. Looking at the image below, notice how both the person and car midpoints lie within the grid cell. (For simplicity sake I split the image into a 3 by 3 grid)
The current cell output y = (Pc, bx, bγ, bw, bh, c), the cell can only choose one of the two objects detected. But with anchor boxes (usually predefined beforehand using a k-means analysis on the training dataset), the cost label y becomes (Pc, bx, bγ, bw, bh, c, Pc1, bx1, bγ1, bw1, bh1, c, Pc, ....) basically repeated depending on how man anchor boxes are there, with the first output encoded with anchor box 1 and second output encoded with anchor box 2 and so on. Each output unit detects for one object class; anchor box 1 is similar to the car so the output c will be for car, the next output c will be for person as it is encoded to anchor box 2.
Note that each output unit c representing the object class is influenced by high IoU with the object’s ground truth bounding box.
For this project, I will be using the YOLOv5 to train an object detection model. YOLO is an acronym for “You Only Look Once”. A popular architecture due to:
Speed (Base model — 45 frames per second, Fast model — 155 frames per second, 1000x faster than R-CNN, )
The architecture comprises only a single neural network (Can be optimized end to end directly on detection performance)
Able to learn the general representation of objects (Predictions are informed by the global context of image)
Open-source
To learn more about the model visit their repository: Ultralytics YOLOv5 Github repository.
I found this Face Mask Detection dataset on Kaggle, comprising of 853 images with 3 classes: With mask, without mask, and mask worn incorrectly. Each image comes with an XML file in PASCAL VOC format that contains annotations of its bounding boxes. Here’s an example:
<annotation> <folder>images</folder> <filename>maksssksksss4.png</filename> <size> <width>301</width> <height>400</height> <depth>3</depth> </size> <segmented>0</segmented> <object> <name>with_mask</name> <pose>Unspecified</pose> <truncated>0</truncated> <occluded>0</occluded> <difficult>0</difficult> <bndbox> <xmin>70</xmin> <ymin>185</ymin> <xmax>176</xmax> <ymax>321</ymax> </bndbox> </object></annotation>
The key information needed for this project are:
<width>and <height> : Dimension of the image in pixelsThe entirety of <bndbox>: xmin, ymin indicates the location of the top left-hand corner of the bounding box while xmax, ymax indicates the bottom right-hand corner of the bounding box in pixels
<width>and <height> : Dimension of the image in pixels
The entirety of <bndbox>: xmin, ymin indicates the location of the top left-hand corner of the bounding box while xmax, ymax indicates the bottom right-hand corner of the bounding box in pixels
Before training the data with the model, the annotation data in PASCAL VOC XML format have to be changed to YOLO format, with one *.txt file per image with the following specifications: (Also illustrated with example image maksssksksss4.png below)
One row per object
Each row is class x_center y_center width height format.
Box coordinates must be in normalized xywh format (from 0–1). If your boxes are in pixels, divide x_center and width by image width, and y_center and height by image height.
Class numbers are zero-indexed (start from 0).
I wrote a function that extracts the required information from the XML files using the XML.etree library and calculates both x_centre and y_centre. As the annotation data is in image pixels, I normalized the final value to match the requirements.
The outcome would look like this:
It is also required for the directories to be formatted in a particular way as shown below where training and validation images and labels are separated into each independent folder
I wrote another simple function using the Pathlib library.
Do note that the entire formatting mentioned above can be done using Roboflow, a simple, code, and hassle-free alternative. It is my personal preference to manually do it by code
Before training the model, we will need to create a projectdata. yaml file, specifying where the training and validation images are and the number of labels as well as the label names of our training data. The file should be structured as shown:
# specify pathway which the val and training data is at# Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..]path: ../mask_detection/projectdatatrain: images/trainval: images/val# Classesnc: 3names: ['no mask', 'mask worn incorrectly', 'mask on']
To train the model with the custom dataset, I ran train.py in the local terminal with the following arguments:
img: input image size
batch: batch size
epochs: number of epochs
data: path to the projectdata.yaml file
cfg: model to choose among the preexisting in 📁models
weights: initial weights path, defaults to yolov5s.pt
cache: cache images for faster training
I chose the smallest and fastest model yolov5s. I also used the model’s pre-trained weights for transfer learning instead of training new weights all over again, which is time-consuming and impossible to train on a laptop due to high processing power requirements. I use a batch size of ‘1’ and trained the model for 10 epochs.
python mask_detection\yolov5\train.py --img 640 --batch 1 --epochs 10 --data projectdata.yaml--weights yolov5s.pt --cfg mask_detection\yolov5\models\yolov5s.yaml --cache
The command will output the following and start training if all the steps were done correctly. Keep an eye out for [email protected] to see how to model is performing. Once training begins, under the “run” folder, Yolov5 training pipeline inputs both ground truth and prediction results on test images as shown below.
Once the training is completed, the trained model will be saved in your “weights” folder/directory and the validation metrics will be logged onto Tensorboard. (I opted for the data be logged to wandb instead as it was recommended)
Popular challenges and competitions such as:
The PASCAL VOC Challenge (Everingham et al. 2010)
The COCO Object Detection Challenge (Lin et al. 2014)
The Open Images Challenge (Kuznetsova 2018)
All 3 challenges use mean average precision(mAP) as the main metric for evaluating object detectors. What exactly is mAP? First, let's go through some foundational concepts.
Confidence score: Probability that an anchor box contains an object predicted by the classifier
Intersection over Union (IoU): Area of intersection of bounding boxes divided by Area of union of the predicted bounding box
Precision: The number of True Positive(TP) divided by the sum of True Positive(TP) & False Positive(FP)
Recall: The number of True Positive divided by the sum of True Positive(TP) & False Negative (FP)
Both Confidence score and IoU are used to determine whether the predicted detection is TP or FP only if it satisfies the following conditions(Note: Any violation of the latter 2 conditions makes it a FP)
Confidence score > threshold (If < threshold, detection counts as a False Negative (FN))Predicted bounding box has a higher IoU than the thresholdPredicted class matches the class of ground truth
Confidence score > threshold (If < threshold, detection counts as a False Negative (FN))
Predicted bounding box has a higher IoU than the threshold
Predicted class matches the class of ground truth
As the confidence score increases, recall decreases monotonically while precision can go up and down, but for this project, all classes (except mask worn incorrectly) increases.
Although precision-recall metric can be used to evaluate the performance of object detector, it is not easy to compare among different detectors. To view the whole thing for comparison, average precision(AP) which is based on the precision-recall curve, comes into play. By definition, AP is finding the area under the precision-recall curve above. Mean average precision (mAP) is the mean of AP.
Note that there are variations in definitions and implementations of mAP.
In The PASCAL VOC Challenge, AP for one object class is calculated for an IoU threshold of 0.5. So the mAP is the averaged of all object classes.
For The COCO Object Detection challenge, the mAP is averaged over all object categories and 10 IoU thresholds.
Now that the model is trained, it's time for the fun part: running inference on either images or videos! Call detect.py in the local terminal to run inference with the following parameters: (view detect.py parser for full list of parameters)
weights: weights of the trained model
source: input file/folder to run inference on, 0 for webcam
iou-thres: IOU threshold for Non-max suppression, default value: 0.45
python yolov5\detect.py --source vid.mp4 --weights runs\train\exp\weights\best.pt --img 640 --iou-thres 0.5
As you can see, the model is able to detect the presence of face masks!
Far from perfect, the model still has room for improvement
The model is unable to detect incorrectly worn masks which is one of the classes. This is most probably due to the large imbalance of data. Only a small fraction of the data consists of incorrectly worn masks. A possible solution would be to apply data balancing so that the model will be better at identifying incorrectly worn masks.
A larger framework could have been used such as Yolov5x instead of Yolov5s to achieve higher mAP. But a possible drawback would be the extra time taken to train such a large model.
With that, I end my article here! This project has been really fun for me, I enjoyed learning new and interesting concepts especially when in the beginning, learning computer vision seemed like such a daunting task but I am glad to pull through it! Cheers!
LinkedIn Profile: Sean Yap
[1]Joseph Redmon, Santosh Divvala, Ross Girshick, Ali Farhadi, You Only Look Once: Unified, Real-Time Object Detection(2015)
[2]Andrew Ng, Convolutional Neural Network, DeepLearning.AI Coursera
[3]The PASCAL Visual Object Classes (VOC) Challenge, by Mark Everingham, Luc Van Gool, Christopher K. I. Williams, John Winn, and Andrew Zisserman
|
[
{
"code": null,
"e": 553,
"s": 171,
"text": "I recently completed DeepLearningAI’s Convolutional Neural Network course taught by Andrew Ng on Coursera and a portion of the course dwelled into the field of Computer Vision. I was fascinated by the capability of computer vision and how it can be integrated into our daily lives which motivated me to dive deeper into computer vision and initiate projects to enforce my learning."
},
{
"code": null,
"e": 724,
"s": 553,
"text": "Before implementing a project, it's best to understand a few fundamental concepts on Object Detection and how it works together. Let's start by defining Object Detection:"
},
{
"code": null,
"e": 1110,
"s": 724,
"text": "Image classification is where an algorithm is applied to an image to predict the class of one object eg: Car. Object localization not only predicts the class of objects but also figures out the location of the object by drawing a bounding box around the object. Object detection involves both classification and localization and detects more than one object & more than one class even."
},
{
"code": null,
"e": 1689,
"s": 1110,
"text": "A standard classification task would involve an image running through a Convnet with multiple layers in which vector features are fed into a softmax unit for example that outputs the predicted class (Object categories that the algorithm is trying to detect i.e cars, trees, pedestrians). Object detection models such as YOLO works by splitting images into a grid of cells where each grid cell is responsible for predicting a bounding box if the centre of the bounding box lies in the cell. It will then output the predicted class, coordinates of the bounding box as shown below:"
},
{
"code": null,
"e": 1865,
"s": 1689,
"text": "To learn more about convolutional neural networks, look up Convolutional Neural Networks, Explained by Mayank Mishra. He does a pretty good job at explaining how Convnet works"
},
{
"code": null,
"e": 2177,
"s": 1865,
"text": "When the algorithm outputs bounding boxes localizing objects detected, how do you tell if the algorithm is working well? This is where Intersection over Union(IoU) comes into play. Generally, IoU is a measure of overlap between two bounding boxes: algorithm predicted bounding box and ground truth bounding box."
},
{
"code": null,
"e": 2380,
"s": 2177,
"text": "The formula for IoU is the size of the intersection divided by the size of the union of both bounding boxes. The threshold for IoU is around 0.5. IoUs with values ≥ 0.5 are deemed “correct” predictions."
},
{
"code": null,
"e": 2515,
"s": 2380,
"text": "With reference to the bounding box image below, cells labeled 1–33 all predict that the centre of the bounding box lies in their cell."
},
{
"code": null,
"e": 3009,
"s": 2515,
"text": "This will lead to the algorithm detecting the object multiple times instead of just once. This is where Non-max suppression comes in where it ensures the algorithm detects each object only once. As was previously stated, each cell outputs y = (Pc, bx, bγ, bw, bh, c) with Pc being the probability there is an object. What Non-max suppression does is it takes the bounding box with the highest Pc, discards any bounding boxes with Pc ≤ 0.6and “silences” the other bounding boxes with IoU ≥ 0.5."
},
{
"code": null,
"e": 3308,
"s": 3009,
"text": "What if multiple objects lie in the same grid cell? How would the bounding boxes be like? Here’s where the idea of anchor boxes can be used. Looking at the image below, notice how both the person and car midpoints lie within the grid cell. (For simplicity sake I split the image into a 3 by 3 grid)"
},
{
"code": null,
"e": 3963,
"s": 3308,
"text": "The current cell output y = (Pc, bx, bγ, bw, bh, c), the cell can only choose one of the two objects detected. But with anchor boxes (usually predefined beforehand using a k-means analysis on the training dataset), the cost label y becomes (Pc, bx, bγ, bw, bh, c, Pc1, bx1, bγ1, bw1, bh1, c, Pc, ....) basically repeated depending on how man anchor boxes are there, with the first output encoded with anchor box 1 and second output encoded with anchor box 2 and so on. Each output unit detects for one object class; anchor box 1 is similar to the car so the output c will be for car, the next output c will be for person as it is encoded to anchor box 2."
},
{
"code": null,
"e": 4093,
"s": 3963,
"text": "Note that each output unit c representing the object class is influenced by high IoU with the object’s ground truth bounding box."
},
{
"code": null,
"e": 4250,
"s": 4093,
"text": "For this project, I will be using the YOLOv5 to train an object detection model. YOLO is an acronym for “You Only Look Once”. A popular architecture due to:"
},
{
"code": null,
"e": 4355,
"s": 4250,
"text": "Speed (Base model — 45 frames per second, Fast model — 155 frames per second, 1000x faster than R-CNN, )"
},
{
"code": null,
"e": 4475,
"s": 4355,
"text": "The architecture comprises only a single neural network (Can be optimized end to end directly on detection performance)"
},
{
"code": null,
"e": 4585,
"s": 4475,
"text": "Able to learn the general representation of objects (Predictions are informed by the global context of image)"
},
{
"code": null,
"e": 4597,
"s": 4585,
"text": "Open-source"
},
{
"code": null,
"e": 4689,
"s": 4597,
"text": "To learn more about the model visit their repository: Ultralytics YOLOv5 Github repository."
},
{
"code": null,
"e": 4957,
"s": 4689,
"text": "I found this Face Mask Detection dataset on Kaggle, comprising of 853 images with 3 classes: With mask, without mask, and mask worn incorrectly. Each image comes with an XML file in PASCAL VOC format that contains annotations of its bounding boxes. Here’s an example:"
},
{
"code": null,
"e": 5487,
"s": 4957,
"text": "<annotation> <folder>images</folder> <filename>maksssksksss4.png</filename> <size> <width>301</width> <height>400</height> <depth>3</depth> </size> <segmented>0</segmented> <object> <name>with_mask</name> <pose>Unspecified</pose> <truncated>0</truncated> <occluded>0</occluded> <difficult>0</difficult> <bndbox> <xmin>70</xmin> <ymin>185</ymin> <xmax>176</xmax> <ymax>321</ymax> </bndbox> </object></annotation>"
},
{
"code": null,
"e": 5536,
"s": 5487,
"text": "The key information needed for this project are:"
},
{
"code": null,
"e": 5784,
"s": 5536,
"text": "<width>and <height> : Dimension of the image in pixelsThe entirety of <bndbox>: xmin, ymin indicates the location of the top left-hand corner of the bounding box while xmax, ymax indicates the bottom right-hand corner of the bounding box in pixels"
},
{
"code": null,
"e": 5839,
"s": 5784,
"text": "<width>and <height> : Dimension of the image in pixels"
},
{
"code": null,
"e": 6033,
"s": 5839,
"text": "The entirety of <bndbox>: xmin, ymin indicates the location of the top left-hand corner of the bounding box while xmax, ymax indicates the bottom right-hand corner of the bounding box in pixels"
},
{
"code": null,
"e": 6281,
"s": 6033,
"text": "Before training the data with the model, the annotation data in PASCAL VOC XML format have to be changed to YOLO format, with one *.txt file per image with the following specifications: (Also illustrated with example image maksssksksss4.png below)"
},
{
"code": null,
"e": 6300,
"s": 6281,
"text": "One row per object"
},
{
"code": null,
"e": 6357,
"s": 6300,
"text": "Each row is class x_center y_center width height format."
},
{
"code": null,
"e": 6531,
"s": 6357,
"text": "Box coordinates must be in normalized xywh format (from 0–1). If your boxes are in pixels, divide x_center and width by image width, and y_center and height by image height."
},
{
"code": null,
"e": 6578,
"s": 6531,
"text": "Class numbers are zero-indexed (start from 0)."
},
{
"code": null,
"e": 6825,
"s": 6578,
"text": "I wrote a function that extracts the required information from the XML files using the XML.etree library and calculates both x_centre and y_centre. As the annotation data is in image pixels, I normalized the final value to match the requirements."
},
{
"code": null,
"e": 6859,
"s": 6825,
"text": "The outcome would look like this:"
},
{
"code": null,
"e": 7041,
"s": 6859,
"text": "It is also required for the directories to be formatted in a particular way as shown below where training and validation images and labels are separated into each independent folder"
},
{
"code": null,
"e": 7100,
"s": 7041,
"text": "I wrote another simple function using the Pathlib library."
},
{
"code": null,
"e": 7279,
"s": 7100,
"text": "Do note that the entire formatting mentioned above can be done using Roboflow, a simple, code, and hassle-free alternative. It is my personal preference to manually do it by code"
},
{
"code": null,
"e": 7525,
"s": 7279,
"text": "Before training the model, we will need to create a projectdata. yaml file, specifying where the training and validation images are and the number of labels as well as the label names of our training data. The file should be structured as shown:"
},
{
"code": null,
"e": 7838,
"s": 7525,
"text": "# specify pathway which the val and training data is at# Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..]path: ../mask_detection/projectdatatrain: images/trainval: images/val# Classesnc: 3names: ['no mask', 'mask worn incorrectly', 'mask on']"
},
{
"code": null,
"e": 7949,
"s": 7838,
"text": "To train the model with the custom dataset, I ran train.py in the local terminal with the following arguments:"
},
{
"code": null,
"e": 7971,
"s": 7949,
"text": "img: input image size"
},
{
"code": null,
"e": 7989,
"s": 7971,
"text": "batch: batch size"
},
{
"code": null,
"e": 8014,
"s": 7989,
"text": "epochs: number of epochs"
},
{
"code": null,
"e": 8054,
"s": 8014,
"text": "data: path to the projectdata.yaml file"
},
{
"code": null,
"e": 8108,
"s": 8054,
"text": "cfg: model to choose among the preexisting in 📁models"
},
{
"code": null,
"e": 8162,
"s": 8108,
"text": "weights: initial weights path, defaults to yolov5s.pt"
},
{
"code": null,
"e": 8202,
"s": 8162,
"text": "cache: cache images for faster training"
},
{
"code": null,
"e": 8530,
"s": 8202,
"text": "I chose the smallest and fastest model yolov5s. I also used the model’s pre-trained weights for transfer learning instead of training new weights all over again, which is time-consuming and impossible to train on a laptop due to high processing power requirements. I use a batch size of ‘1’ and trained the model for 10 epochs."
},
{
"code": null,
"e": 8700,
"s": 8530,
"text": "python mask_detection\\yolov5\\train.py --img 640 --batch 1 --epochs 10 --data projectdata.yaml--weights yolov5s.pt --cfg mask_detection\\yolov5\\models\\yolov5s.yaml --cache"
},
{
"code": null,
"e": 9007,
"s": 8700,
"text": "The command will output the following and start training if all the steps were done correctly. Keep an eye out for [email protected] to see how to model is performing. Once training begins, under the “run” folder, Yolov5 training pipeline inputs both ground truth and prediction results on test images as shown below."
},
{
"code": null,
"e": 9238,
"s": 9007,
"text": "Once the training is completed, the trained model will be saved in your “weights” folder/directory and the validation metrics will be logged onto Tensorboard. (I opted for the data be logged to wandb instead as it was recommended)"
},
{
"code": null,
"e": 9283,
"s": 9238,
"text": "Popular challenges and competitions such as:"
},
{
"code": null,
"e": 9333,
"s": 9283,
"text": "The PASCAL VOC Challenge (Everingham et al. 2010)"
},
{
"code": null,
"e": 9387,
"s": 9333,
"text": "The COCO Object Detection Challenge (Lin et al. 2014)"
},
{
"code": null,
"e": 9431,
"s": 9387,
"text": "The Open Images Challenge (Kuznetsova 2018)"
},
{
"code": null,
"e": 9605,
"s": 9431,
"text": "All 3 challenges use mean average precision(mAP) as the main metric for evaluating object detectors. What exactly is mAP? First, let's go through some foundational concepts."
},
{
"code": null,
"e": 9701,
"s": 9605,
"text": "Confidence score: Probability that an anchor box contains an object predicted by the classifier"
},
{
"code": null,
"e": 9826,
"s": 9701,
"text": "Intersection over Union (IoU): Area of intersection of bounding boxes divided by Area of union of the predicted bounding box"
},
{
"code": null,
"e": 9930,
"s": 9826,
"text": "Precision: The number of True Positive(TP) divided by the sum of True Positive(TP) & False Positive(FP)"
},
{
"code": null,
"e": 10028,
"s": 9930,
"text": "Recall: The number of True Positive divided by the sum of True Positive(TP) & False Negative (FP)"
},
{
"code": null,
"e": 10232,
"s": 10028,
"text": "Both Confidence score and IoU are used to determine whether the predicted detection is TP or FP only if it satisfies the following conditions(Note: Any violation of the latter 2 conditions makes it a FP)"
},
{
"code": null,
"e": 10428,
"s": 10232,
"text": "Confidence score > threshold (If < threshold, detection counts as a False Negative (FN))Predicted bounding box has a higher IoU than the thresholdPredicted class matches the class of ground truth"
},
{
"code": null,
"e": 10517,
"s": 10428,
"text": "Confidence score > threshold (If < threshold, detection counts as a False Negative (FN))"
},
{
"code": null,
"e": 10576,
"s": 10517,
"text": "Predicted bounding box has a higher IoU than the threshold"
},
{
"code": null,
"e": 10626,
"s": 10576,
"text": "Predicted class matches the class of ground truth"
},
{
"code": null,
"e": 10804,
"s": 10626,
"text": "As the confidence score increases, recall decreases monotonically while precision can go up and down, but for this project, all classes (except mask worn incorrectly) increases."
},
{
"code": null,
"e": 11201,
"s": 10804,
"text": "Although precision-recall metric can be used to evaluate the performance of object detector, it is not easy to compare among different detectors. To view the whole thing for comparison, average precision(AP) which is based on the precision-recall curve, comes into play. By definition, AP is finding the area under the precision-recall curve above. Mean average precision (mAP) is the mean of AP."
},
{
"code": null,
"e": 11275,
"s": 11201,
"text": "Note that there are variations in definitions and implementations of mAP."
},
{
"code": null,
"e": 11421,
"s": 11275,
"text": "In The PASCAL VOC Challenge, AP for one object class is calculated for an IoU threshold of 0.5. So the mAP is the averaged of all object classes."
},
{
"code": null,
"e": 11532,
"s": 11421,
"text": "For The COCO Object Detection challenge, the mAP is averaged over all object categories and 10 IoU thresholds."
},
{
"code": null,
"e": 11774,
"s": 11532,
"text": "Now that the model is trained, it's time for the fun part: running inference on either images or videos! Call detect.py in the local terminal to run inference with the following parameters: (view detect.py parser for full list of parameters)"
},
{
"code": null,
"e": 11812,
"s": 11774,
"text": "weights: weights of the trained model"
},
{
"code": null,
"e": 11872,
"s": 11812,
"text": "source: input file/folder to run inference on, 0 for webcam"
},
{
"code": null,
"e": 11942,
"s": 11872,
"text": "iou-thres: IOU threshold for Non-max suppression, default value: 0.45"
},
{
"code": null,
"e": 12050,
"s": 11942,
"text": "python yolov5\\detect.py --source vid.mp4 --weights runs\\train\\exp\\weights\\best.pt --img 640 --iou-thres 0.5"
},
{
"code": null,
"e": 12122,
"s": 12050,
"text": "As you can see, the model is able to detect the presence of face masks!"
},
{
"code": null,
"e": 12181,
"s": 12122,
"text": "Far from perfect, the model still has room for improvement"
},
{
"code": null,
"e": 12516,
"s": 12181,
"text": "The model is unable to detect incorrectly worn masks which is one of the classes. This is most probably due to the large imbalance of data. Only a small fraction of the data consists of incorrectly worn masks. A possible solution would be to apply data balancing so that the model will be better at identifying incorrectly worn masks."
},
{
"code": null,
"e": 12697,
"s": 12516,
"text": "A larger framework could have been used such as Yolov5x instead of Yolov5s to achieve higher mAP. But a possible drawback would be the extra time taken to train such a large model."
},
{
"code": null,
"e": 12954,
"s": 12697,
"text": "With that, I end my article here! This project has been really fun for me, I enjoyed learning new and interesting concepts especially when in the beginning, learning computer vision seemed like such a daunting task but I am glad to pull through it! Cheers!"
},
{
"code": null,
"e": 12981,
"s": 12954,
"text": "LinkedIn Profile: Sean Yap"
},
{
"code": null,
"e": 13106,
"s": 12981,
"text": "[1]Joseph Redmon, Santosh Divvala, Ross Girshick, Ali Farhadi, You Only Look Once: Unified, Real-Time Object Detection(2015)"
},
{
"code": null,
"e": 13175,
"s": 13106,
"text": "[2]Andrew Ng, Convolutional Neural Network, DeepLearning.AI Coursera"
}
] |
Find the maximum path sum between two leaves of a binary tree
|
23 Jun, 2022
Given a binary tree in which each node element contains a number. Find the maximum possible sum from one leaf node to another.
The maximum sum path may or may not go through root. For example, in the following binary tree, the maximum sum is 27(3 + 6 + 9 + 0 – 1 + 10). Expected time complexity is O(n). If one side of root is empty, then function should return minus infinite (INT_MIN in case of C/C++)
A simple solution is to traverse the tree and do following for every traversed node X.
Find maximum sum from leaf to root in left subtree of X (we can use this post for this and next steps) Find maximum sum from leaf to root in right subtree of X. Add the above two calculated values and X->data and compare the sum with the maximum value obtained so far and update the maximum value. Return the maximum value.
Find maximum sum from leaf to root in left subtree of X (we can use this post for this and next steps)
Find maximum sum from leaf to root in right subtree of X.
Add the above two calculated values and X->data and compare the sum with the maximum value obtained so far and update the maximum value.
Return the maximum value.
The time complexity of above solution is O(n2)
Chapters
descriptions off, selected
captions settings, opens captions settings dialog
captions off, selected
English
default, selected
This is a modal window.
Beginning of dialog window. Escape will cancel and close the window.
End of dialog window.
We can find the maximum sum using single traversal of binary tree. The idea is to maintain two values in recursive calls
(Note: If the tree is right-most or left-most tree then first we have to adjust the tree such that both the right and left are not null. Left-most means if the right of super root of the tree is null and right-most tree means if left of super root of the tree is null.)
Maximum root to leaf path sum for the subtree rooted under current node. The maximum path sum between leaves (desired output).
Maximum root to leaf path sum for the subtree rooted under current node.
The maximum path sum between leaves (desired output).
For every visited node X, we find the maximum root to leaf sum in left and right subtrees of X. We add the two values with X->data, and compare the sum with maximum path sum found so far.
Following is the implementation of the above O(n) solution.
C++
Java
Python3
C#
Javascript
// C++ program to find maximum path//sum between two leaves of a binary tree#include <bits/stdc++.h>using namespace std; // A binary tree nodestruct Node{ int data; struct Node* left, *right;}; // Utility function to allocate memory for a new nodestruct Node* newNode(int data){ struct Node* node = new(struct Node); node->data = data; node->left = node->right = NULL; return (node);} // Utility function to find maximum of two integersint max(int a, int b){ return (a >= b)? a: b; } // A utility function to find the maximum sum between any// two leaves.This function calculates two values:// 1) Maximum path sum between two leaves which is stored// in res.// 2) The maximum root to leaf path sum which is returned.// If one side of root is empty, then it returns INT_MINint maxPathSumUtil(struct Node *root, int &res){ // Base cases if (root==NULL) return 0; if (!root->left && !root->right) return root->data; // Find maximum sum in left and right subtree. Also // find maximum root to leaf sums in left and right // subtrees and store them in ls and rs int ls = maxPathSumUtil(root->left, res); int rs = maxPathSumUtil(root->right, res); // If both left and right children exist if (root->left && root->right) { // Update result if needed res = max(res, ls + rs + root->data); // Return maximum possible value for root being // on one side return max(ls, rs) + root->data; } // If any of the two children is empty, return // root sum for root being on one side return (!root->left)? rs + root->data: ls + root->data;} // The main function which returns sum of the maximum// sum path between two leaves. This function mainly// uses maxPathSumUtil()int maxPathSum(struct Node *root){ int res = INT_MIN; int val = maxPathSumUtil(root, res); //--- for test case --- // 7 // / \ // Null -3 // (case - 1) // value of res will be INT_MIN but the answer is 4 , which is returned by the // function maxPathSumUtil(). if(root->left && root->right) return res; return max(res, val);} // Driver Codeint main(){ struct Node *root = newNode(-15); root->left = newNode(5); root->right = newNode(6); root->left->left = newNode(-8); root->left->right = newNode(1); root->left->left->left = newNode(2); root->left->left->right = newNode(6); root->right->left = newNode(3); root->right->right = newNode(9); root->right->right->right= newNode(0); root->right->right->right->left= newNode(4); root->right->right->right->right= newNode(-1); root->right->right->right->right->left= newNode(10); cout << "Max pathSum of the given binary tree is " << maxPathSum(root); return 0;}
// Java program to find maximum path sum between two leaves// of a binary treeclass Node { int data; Node left, right; Node(int item) { data = item; left = right = null; }} // An object of Res is passed around so that the// same value can be used by multiple recursive calls.class Res { int val;} class BinaryTree { static Node root; Node setTree(Node root){ Node temp = new Node(0); //if tree is left most if(root.right==null){ root.right=temp; } else{ //if tree is right most root.left=temp; } return root; } // A utility function to find the maximum sum between any // two leaves.This function calculates two values: // 1) Maximum path sum between two leaves which is stored // in res. // 2) The maximum root to leaf path sum which is returned. // If one side of root is empty, then it returns INT_MIN int maxPathSumUtil(Node node, Res res) { // Base cases if (node == null) return 0; if (node.left == null && node.right == null) return node.data; // Find maximum sum in left and right subtree. Also // find maximum root to leaf sums in left and right // subtrees and store them in ls and rs int ls = maxPathSumUtil(node.left, res); int rs = maxPathSumUtil(node.right, res); // If both left and right children exist if (node.left != null && node.right != null) { // Update result if needed res.val = Math.max(res.val, ls + rs + node.data); // Return maximum possible value for root being // on one side return Math.max(ls, rs) + node.data; } // If any of the two children is empty, return // root sum for root being on one side return (node.left == null) ? rs + node.data : ls + node.data; } // The main function which returns sum of the maximum // sum path between two leaves. This function mainly // uses maxPathSumUtil() int maxPathSum(Node node) { Res res = new Res(); res.val = Integer.MIN_VALUE; if(root.left==null || root.right==null){ root=setTree(root); } //if tree is left most or right most //call setTree() method to adjust tree first maxPathSumUtil(root, res); return res.val; } //Driver program to test above functions public static void main(String args[]) { BinaryTree tree = new BinaryTree(); tree.root = new Node(-15); tree.root.left = new Node(5); tree.root.right = new Node(6); tree.root.left.left = new Node(-8); tree.root.left.right = new Node(1); tree.root.left.left.left = new Node(2); tree.root.left.left.right = new Node(6); tree.root.right.left = new Node(3); tree.root.right.right = new Node(9); tree.root.right.right.right = new Node(0); tree.root.right.right.right.left = new Node(4); tree.root.right.right.right.right = new Node(-1); tree.root.right.right.right.right.left = new Node(10); System.out.println("Max pathSum of the given binary tree is " + tree.maxPathSum(root)); }} // This code is improved by Rahul Soni
# Python program to find maximumpath sum between two leaves# of a binary tree INT_MIN = -2**32 # A binary tree node class Node: # Constructor to create a new node def __init__(self, data): self.data = data self.left = None self.right = None # Utility function to find maximum sum between any# two leaves. This function calculates two values:# 1) Maximum path sum between two leaves which are stored# in res# 2) The maximum root to leaf path sum which is returned# If one side of root is empty, then it returns INT_MIN def maxPathSumUtil(root, res): # Base Case if root is None: return 0 # Find maximumsum in left and right subtree. Also # find maximum root to leaf sums in left and right # subtrees ans store them in ls and rs ls = maxPathSumUtil(root.left, res) rs = maxPathSumUtil(root.right, res) # If both left and right children exist if root.left is not None and root.right is not None: # update result if needed res[0] = max(res[0], ls + rs + root.data) # Return maximum possible value for root being # on one side return max(ls, rs) + root.data # If any of the two children is empty, return # root sum for root being on one side if root.left is None: return rs + root.data else: return ls + root.data # The main function which returns sum of the maximum# sum path betwee ntwo leaves. THis function mainly# uses maxPathSumUtil() def maxPathSum(root): res = [INT_MIN] maxPathSumUtil(root, res) return res[0] # Driver program to test above functionroot = Node(-15)root.left = Node(5)root.right = Node(6)root.left.left = Node(-8)root.left.right = Node(1)root.left.left.left = Node(2)root.left.left.right = Node(6)root.right.left = Node(3)root.right.right = Node(9)root.right.right.right = Node(0)root.right.right.right.left = Node(4)root.right.right.right.right = Node(-1)root.right.right.right.right.left = Node(10) print ("Max pathSum of the given binary tree is", maxPathSum(root)) # This code is contributed by Nikhil Kumar Singh(nickzuck_007)
using System; // C# program to find maximum path sum between two leaves// of a binary treepublic class Node{ public int data; public Node left, right; public Node(int item) { data = item; left = right = null; }} // An object of Res is passed around so that the// same value can be used by multiple recursive calls.public class Res{ public int val;} public class BinaryTree{ public static Node root; // A utility function to find the maximum sum between any // two leaves.This function calculates two values: // 1) Maximum path sum between two leaves which is stored // in res. // 2) The maximum root to leaf path sum which is returned. // If one side of root is empty, then it returns INT_MIN public virtual int maxPathSumUtil(Node node, Res res) { // Base cases if (node == null) { return 0; } if (node.left == null && node.right == null) { return node.data; } // Find maximum sum in left and right subtree. Also // find maximum root to leaf sums in left and right // subtrees and store them in ls and rs int ls = maxPathSumUtil(node.left, res); int rs = maxPathSumUtil(node.right, res); // If both left and right children exist if (node.left != null && node.right != null) { // Update result if needed res.val = Math.Max(res.val, ls + rs + node.data); // Return maximum possible value for root being // on one side return Math.Max(ls, rs) + node.data; } // If any of the two children is empty, return // root sum for root being on one side return (node.left == null) ? rs + node.data : ls + node.data; } // The main function which returns sum of the maximum // sum path between two leaves. This function mainly // uses maxPathSumUtil() public virtual int maxPathSum(Node node) { Res res = new Res(); res.val = int.MinValue; maxPathSumUtil(root, res); return res.val; } //Driver program to test above functions public static void Main(string[] args) { BinaryTree tree = new BinaryTree(); BinaryTree.root = new Node(-15); BinaryTree.root.left = new Node(5); BinaryTree.root.right = new Node(6); BinaryTree.root.left.left = new Node(-8); BinaryTree.root.left.right = new Node(1); BinaryTree.root.left.left.left = new Node(2); BinaryTree.root.left.left.right = new Node(6); BinaryTree.root.right.left = new Node(3); BinaryTree.root.right.right = new Node(9); BinaryTree.root.right.right.right = new Node(0); BinaryTree.root.right.right.right.left = new Node(4); BinaryTree.root.right.right.right.right = new Node(-1); BinaryTree.root.right.right.right.right.left = new Node(10); Console.WriteLine("Max pathSum of the given binary tree is " + tree.maxPathSum(root)); }} // This code is contributed by Shrikant13
<script>// javascript program to find maximum path sum between two leaves// of a binary treeclass Node { constructor(val) { this.data = val; this.left = null; this.right = null; }} // An object of Res is passed around so that the// same value can be used by multiple recursive calls.class Res { constructor(){ this.val = 0; }} var root; function setTree(root) { var temp = new Node(0); // if tree is left most if (root.right == null) { root.right = temp; } else { // if tree is right most root.left = temp; } return root; } // A utility function to find the maximum sum between any // two leaves.This function calculates two values: // 1) Maximum path sum between two leaves which is stored // in res. // 2) The maximum root to leaf path sum which is returned. // If one side of root is empty, then it returns INT_MIN function maxPathSumUtil(node, res) { // Base cases if (node == null) return 0; if (node.left == null && node.right == null) return node.data; // Find maximum sum in left and right subtree. Also // find maximum root to leaf sums in left and right // subtrees and store them in ls and rs var ls = maxPathSumUtil(node.left, res); var rs = maxPathSumUtil(node.right, res); // If both left and right children exist if (node.left != null && node.right != null) { // Update result if needed res.val = Math.max(res.val, ls + rs + node.data); // Return maximum possible value for root being // on one side return Math.max(ls, rs) + node.data; } // If any of the two children is empty, return // root sum for root being on one side return (node.left == null) ? rs + node.data : ls + node.data; } // The main function which returns sum of the maximum // sum path between two leaves. This function mainly // uses maxPathSumUtil() function maxPathSum(node) { var res = new Res(); res.val = Number.MIN_VALUE; if (root.left == null || root.right == null) { root = setTree(root); } // if tree is left most or right most // call setTree() method to adjust tree first maxPathSumUtil(root, res); return res.val; } // Driver program to test above functions var root = new Node(-15); root.left = new Node(5); root.right = new Node(6); root.left.left = new Node(-8); root.left.right = new Node(1); root.left.left.left = new Node(2); root.left.left.right = new Node(6); root.right.left = new Node(3); root.right.right = new Node(9); root.right.right.right = new Node(0); root.right.right.right.left = new Node(4); root.right.right.right.right = new Node(-1); root.right.right.right.right.left = new Node(10); document.write("Max pathSum of the given binary tree is " + maxPathSum(root)); // This code is contributed by umadevi9616</script>
Max pathSum of the given binary tree is 27
Time complexity: O(n) where n is the number of nodesAuxiliary Space: O(1)
shrikanth13
saumil diwaker
amankharwar
surindertarika1234
rahul989741
anikakapoor
umadevi9616
amartyaghoshgfg
prabormukherjee
hasani
hardikkoriintern
Accolite
Amazon
Directi
Facebook
FactSet
Microsoft
OYO Rooms
Tree
Accolite
Amazon
Microsoft
OYO Rooms
FactSet
Directi
Facebook
Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n23 Jun, 2022"
},
{
"code": null,
"e": 180,
"s": 52,
"text": "Given a binary tree in which each node element contains a number. Find the maximum possible sum from one leaf node to another. "
},
{
"code": null,
"e": 457,
"s": 180,
"text": "The maximum sum path may or may not go through root. For example, in the following binary tree, the maximum sum is 27(3 + 6 + 9 + 0 – 1 + 10). Expected time complexity is O(n). If one side of root is empty, then function should return minus infinite (INT_MIN in case of C/C++)"
},
{
"code": null,
"e": 547,
"s": 459,
"text": "A simple solution is to traverse the tree and do following for every traversed node X. "
},
{
"code": null,
"e": 871,
"s": 547,
"text": "Find maximum sum from leaf to root in left subtree of X (we can use this post for this and next steps) Find maximum sum from leaf to root in right subtree of X. Add the above two calculated values and X->data and compare the sum with the maximum value obtained so far and update the maximum value. Return the maximum value."
},
{
"code": null,
"e": 975,
"s": 871,
"text": "Find maximum sum from leaf to root in left subtree of X (we can use this post for this and next steps) "
},
{
"code": null,
"e": 1034,
"s": 975,
"text": "Find maximum sum from leaf to root in right subtree of X. "
},
{
"code": null,
"e": 1172,
"s": 1034,
"text": "Add the above two calculated values and X->data and compare the sum with the maximum value obtained so far and update the maximum value. "
},
{
"code": null,
"e": 1198,
"s": 1172,
"text": "Return the maximum value."
},
{
"code": null,
"e": 1245,
"s": 1198,
"text": "The time complexity of above solution is O(n2)"
},
{
"code": null,
"e": 1254,
"s": 1245,
"text": "Chapters"
},
{
"code": null,
"e": 1281,
"s": 1254,
"text": "descriptions off, selected"
},
{
"code": null,
"e": 1331,
"s": 1281,
"text": "captions settings, opens captions settings dialog"
},
{
"code": null,
"e": 1354,
"s": 1331,
"text": "captions off, selected"
},
{
"code": null,
"e": 1362,
"s": 1354,
"text": "English"
},
{
"code": null,
"e": 1380,
"s": 1362,
"text": "default, selected"
},
{
"code": null,
"e": 1404,
"s": 1380,
"text": "This is a modal window."
},
{
"code": null,
"e": 1473,
"s": 1404,
"text": "Beginning of dialog window. Escape will cancel and close the window."
},
{
"code": null,
"e": 1495,
"s": 1473,
"text": "End of dialog window."
},
{
"code": null,
"e": 1616,
"s": 1495,
"text": "We can find the maximum sum using single traversal of binary tree. The idea is to maintain two values in recursive calls"
},
{
"code": null,
"e": 1888,
"s": 1616,
"text": "(Note: If the tree is right-most or left-most tree then first we have to adjust the tree such that both the right and left are not null. Left-most means if the right of super root of the tree is null and right-most tree means if left of super root of the tree is null.) "
},
{
"code": null,
"e": 2015,
"s": 1888,
"text": "Maximum root to leaf path sum for the subtree rooted under current node. The maximum path sum between leaves (desired output)."
},
{
"code": null,
"e": 2089,
"s": 2015,
"text": "Maximum root to leaf path sum for the subtree rooted under current node. "
},
{
"code": null,
"e": 2143,
"s": 2089,
"text": "The maximum path sum between leaves (desired output)."
},
{
"code": null,
"e": 2331,
"s": 2143,
"text": "For every visited node X, we find the maximum root to leaf sum in left and right subtrees of X. We add the two values with X->data, and compare the sum with maximum path sum found so far."
},
{
"code": null,
"e": 2391,
"s": 2331,
"text": "Following is the implementation of the above O(n) solution."
},
{
"code": null,
"e": 2395,
"s": 2391,
"text": "C++"
},
{
"code": null,
"e": 2400,
"s": 2395,
"text": "Java"
},
{
"code": null,
"e": 2408,
"s": 2400,
"text": "Python3"
},
{
"code": null,
"e": 2411,
"s": 2408,
"text": "C#"
},
{
"code": null,
"e": 2422,
"s": 2411,
"text": "Javascript"
},
{
"code": "// C++ program to find maximum path//sum between two leaves of a binary tree#include <bits/stdc++.h>using namespace std; // A binary tree nodestruct Node{ int data; struct Node* left, *right;}; // Utility function to allocate memory for a new nodestruct Node* newNode(int data){ struct Node* node = new(struct Node); node->data = data; node->left = node->right = NULL; return (node);} // Utility function to find maximum of two integersint max(int a, int b){ return (a >= b)? a: b; } // A utility function to find the maximum sum between any// two leaves.This function calculates two values:// 1) Maximum path sum between two leaves which is stored// in res.// 2) The maximum root to leaf path sum which is returned.// If one side of root is empty, then it returns INT_MINint maxPathSumUtil(struct Node *root, int &res){ // Base cases if (root==NULL) return 0; if (!root->left && !root->right) return root->data; // Find maximum sum in left and right subtree. Also // find maximum root to leaf sums in left and right // subtrees and store them in ls and rs int ls = maxPathSumUtil(root->left, res); int rs = maxPathSumUtil(root->right, res); // If both left and right children exist if (root->left && root->right) { // Update result if needed res = max(res, ls + rs + root->data); // Return maximum possible value for root being // on one side return max(ls, rs) + root->data; } // If any of the two children is empty, return // root sum for root being on one side return (!root->left)? rs + root->data: ls + root->data;} // The main function which returns sum of the maximum// sum path between two leaves. This function mainly// uses maxPathSumUtil()int maxPathSum(struct Node *root){ int res = INT_MIN; int val = maxPathSumUtil(root, res); //--- for test case --- // 7 // / \\ // Null -3 // (case - 1) // value of res will be INT_MIN but the answer is 4 , which is returned by the // function maxPathSumUtil(). if(root->left && root->right) return res; return max(res, val);} // Driver Codeint main(){ struct Node *root = newNode(-15); root->left = newNode(5); root->right = newNode(6); root->left->left = newNode(-8); root->left->right = newNode(1); root->left->left->left = newNode(2); root->left->left->right = newNode(6); root->right->left = newNode(3); root->right->right = newNode(9); root->right->right->right= newNode(0); root->right->right->right->left= newNode(4); root->right->right->right->right= newNode(-1); root->right->right->right->right->left= newNode(10); cout << \"Max pathSum of the given binary tree is \" << maxPathSum(root); return 0;}",
"e": 5328,
"s": 2422,
"text": null
},
{
"code": "// Java program to find maximum path sum between two leaves// of a binary treeclass Node { int data; Node left, right; Node(int item) { data = item; left = right = null; }} // An object of Res is passed around so that the// same value can be used by multiple recursive calls.class Res { int val;} class BinaryTree { static Node root; Node setTree(Node root){ Node temp = new Node(0); //if tree is left most if(root.right==null){ root.right=temp; } else{ //if tree is right most root.left=temp; } return root; } // A utility function to find the maximum sum between any // two leaves.This function calculates two values: // 1) Maximum path sum between two leaves which is stored // in res. // 2) The maximum root to leaf path sum which is returned. // If one side of root is empty, then it returns INT_MIN int maxPathSumUtil(Node node, Res res) { // Base cases if (node == null) return 0; if (node.left == null && node.right == null) return node.data; // Find maximum sum in left and right subtree. Also // find maximum root to leaf sums in left and right // subtrees and store them in ls and rs int ls = maxPathSumUtil(node.left, res); int rs = maxPathSumUtil(node.right, res); // If both left and right children exist if (node.left != null && node.right != null) { // Update result if needed res.val = Math.max(res.val, ls + rs + node.data); // Return maximum possible value for root being // on one side return Math.max(ls, rs) + node.data; } // If any of the two children is empty, return // root sum for root being on one side return (node.left == null) ? rs + node.data : ls + node.data; } // The main function which returns sum of the maximum // sum path between two leaves. This function mainly // uses maxPathSumUtil() int maxPathSum(Node node) { Res res = new Res(); res.val = Integer.MIN_VALUE; if(root.left==null || root.right==null){ root=setTree(root); } //if tree is left most or right most //call setTree() method to adjust tree first maxPathSumUtil(root, res); return res.val; } //Driver program to test above functions public static void main(String args[]) { BinaryTree tree = new BinaryTree(); tree.root = new Node(-15); tree.root.left = new Node(5); tree.root.right = new Node(6); tree.root.left.left = new Node(-8); tree.root.left.right = new Node(1); tree.root.left.left.left = new Node(2); tree.root.left.left.right = new Node(6); tree.root.right.left = new Node(3); tree.root.right.right = new Node(9); tree.root.right.right.right = new Node(0); tree.root.right.right.right.left = new Node(4); tree.root.right.right.right.right = new Node(-1); tree.root.right.right.right.right.left = new Node(10); System.out.println(\"Max pathSum of the given binary tree is \" + tree.maxPathSum(root)); }} // This code is improved by Rahul Soni",
"e": 8647,
"s": 5328,
"text": null
},
{
"code": "# Python program to find maximumpath sum between two leaves# of a binary tree INT_MIN = -2**32 # A binary tree node class Node: # Constructor to create a new node def __init__(self, data): self.data = data self.left = None self.right = None # Utility function to find maximum sum between any# two leaves. This function calculates two values:# 1) Maximum path sum between two leaves which are stored# in res# 2) The maximum root to leaf path sum which is returned# If one side of root is empty, then it returns INT_MIN def maxPathSumUtil(root, res): # Base Case if root is None: return 0 # Find maximumsum in left and right subtree. Also # find maximum root to leaf sums in left and right # subtrees ans store them in ls and rs ls = maxPathSumUtil(root.left, res) rs = maxPathSumUtil(root.right, res) # If both left and right children exist if root.left is not None and root.right is not None: # update result if needed res[0] = max(res[0], ls + rs + root.data) # Return maximum possible value for root being # on one side return max(ls, rs) + root.data # If any of the two children is empty, return # root sum for root being on one side if root.left is None: return rs + root.data else: return ls + root.data # The main function which returns sum of the maximum# sum path betwee ntwo leaves. THis function mainly# uses maxPathSumUtil() def maxPathSum(root): res = [INT_MIN] maxPathSumUtil(root, res) return res[0] # Driver program to test above functionroot = Node(-15)root.left = Node(5)root.right = Node(6)root.left.left = Node(-8)root.left.right = Node(1)root.left.left.left = Node(2)root.left.left.right = Node(6)root.right.left = Node(3)root.right.right = Node(9)root.right.right.right = Node(0)root.right.right.right.left = Node(4)root.right.right.right.right = Node(-1)root.right.right.right.right.left = Node(10) print (\"Max pathSum of the given binary tree is\", maxPathSum(root)) # This code is contributed by Nikhil Kumar Singh(nickzuck_007)",
"e": 10743,
"s": 8647,
"text": null
},
{
"code": "using System; // C# program to find maximum path sum between two leaves// of a binary treepublic class Node{ public int data; public Node left, right; public Node(int item) { data = item; left = right = null; }} // An object of Res is passed around so that the// same value can be used by multiple recursive calls.public class Res{ public int val;} public class BinaryTree{ public static Node root; // A utility function to find the maximum sum between any // two leaves.This function calculates two values: // 1) Maximum path sum between two leaves which is stored // in res. // 2) The maximum root to leaf path sum which is returned. // If one side of root is empty, then it returns INT_MIN public virtual int maxPathSumUtil(Node node, Res res) { // Base cases if (node == null) { return 0; } if (node.left == null && node.right == null) { return node.data; } // Find maximum sum in left and right subtree. Also // find maximum root to leaf sums in left and right // subtrees and store them in ls and rs int ls = maxPathSumUtil(node.left, res); int rs = maxPathSumUtil(node.right, res); // If both left and right children exist if (node.left != null && node.right != null) { // Update result if needed res.val = Math.Max(res.val, ls + rs + node.data); // Return maximum possible value for root being // on one side return Math.Max(ls, rs) + node.data; } // If any of the two children is empty, return // root sum for root being on one side return (node.left == null) ? rs + node.data : ls + node.data; } // The main function which returns sum of the maximum // sum path between two leaves. This function mainly // uses maxPathSumUtil() public virtual int maxPathSum(Node node) { Res res = new Res(); res.val = int.MinValue; maxPathSumUtil(root, res); return res.val; } //Driver program to test above functions public static void Main(string[] args) { BinaryTree tree = new BinaryTree(); BinaryTree.root = new Node(-15); BinaryTree.root.left = new Node(5); BinaryTree.root.right = new Node(6); BinaryTree.root.left.left = new Node(-8); BinaryTree.root.left.right = new Node(1); BinaryTree.root.left.left.left = new Node(2); BinaryTree.root.left.left.right = new Node(6); BinaryTree.root.right.left = new Node(3); BinaryTree.root.right.right = new Node(9); BinaryTree.root.right.right.right = new Node(0); BinaryTree.root.right.right.right.left = new Node(4); BinaryTree.root.right.right.right.right = new Node(-1); BinaryTree.root.right.right.right.right.left = new Node(10); Console.WriteLine(\"Max pathSum of the given binary tree is \" + tree.maxPathSum(root)); }} // This code is contributed by Shrikant13",
"e": 13804,
"s": 10743,
"text": null
},
{
"code": "<script>// javascript program to find maximum path sum between two leaves// of a binary treeclass Node { constructor(val) { this.data = val; this.left = null; this.right = null; }} // An object of Res is passed around so that the// same value can be used by multiple recursive calls.class Res { constructor(){ this.val = 0; }} var root; function setTree(root) { var temp = new Node(0); // if tree is left most if (root.right == null) { root.right = temp; } else { // if tree is right most root.left = temp; } return root; } // A utility function to find the maximum sum between any // two leaves.This function calculates two values: // 1) Maximum path sum between two leaves which is stored // in res. // 2) The maximum root to leaf path sum which is returned. // If one side of root is empty, then it returns INT_MIN function maxPathSumUtil(node, res) { // Base cases if (node == null) return 0; if (node.left == null && node.right == null) return node.data; // Find maximum sum in left and right subtree. Also // find maximum root to leaf sums in left and right // subtrees and store them in ls and rs var ls = maxPathSumUtil(node.left, res); var rs = maxPathSumUtil(node.right, res); // If both left and right children exist if (node.left != null && node.right != null) { // Update result if needed res.val = Math.max(res.val, ls + rs + node.data); // Return maximum possible value for root being // on one side return Math.max(ls, rs) + node.data; } // If any of the two children is empty, return // root sum for root being on one side return (node.left == null) ? rs + node.data : ls + node.data; } // The main function which returns sum of the maximum // sum path between two leaves. This function mainly // uses maxPathSumUtil() function maxPathSum(node) { var res = new Res(); res.val = Number.MIN_VALUE; if (root.left == null || root.right == null) { root = setTree(root); } // if tree is left most or right most // call setTree() method to adjust tree first maxPathSumUtil(root, res); return res.val; } // Driver program to test above functions var root = new Node(-15); root.left = new Node(5); root.right = new Node(6); root.left.left = new Node(-8); root.left.right = new Node(1); root.left.left.left = new Node(2); root.left.left.right = new Node(6); root.right.left = new Node(3); root.right.right = new Node(9); root.right.right.right = new Node(0); root.right.right.right.left = new Node(4); root.right.right.right.right = new Node(-1); root.right.right.right.right.left = new Node(10); document.write(\"Max pathSum of the given binary tree is \" + maxPathSum(root)); // This code is contributed by umadevi9616</script>",
"e": 16943,
"s": 13804,
"text": null
},
{
"code": null,
"e": 16986,
"s": 16943,
"text": "Max pathSum of the given binary tree is 27"
},
{
"code": null,
"e": 17060,
"s": 16986,
"text": "Time complexity: O(n) where n is the number of nodesAuxiliary Space: O(1)"
},
{
"code": null,
"e": 17072,
"s": 17060,
"text": "shrikanth13"
},
{
"code": null,
"e": 17087,
"s": 17072,
"text": "saumil diwaker"
},
{
"code": null,
"e": 17099,
"s": 17087,
"text": "amankharwar"
},
{
"code": null,
"e": 17118,
"s": 17099,
"text": "surindertarika1234"
},
{
"code": null,
"e": 17130,
"s": 17118,
"text": "rahul989741"
},
{
"code": null,
"e": 17142,
"s": 17130,
"text": "anikakapoor"
},
{
"code": null,
"e": 17154,
"s": 17142,
"text": "umadevi9616"
},
{
"code": null,
"e": 17170,
"s": 17154,
"text": "amartyaghoshgfg"
},
{
"code": null,
"e": 17186,
"s": 17170,
"text": "prabormukherjee"
},
{
"code": null,
"e": 17193,
"s": 17186,
"text": "hasani"
},
{
"code": null,
"e": 17210,
"s": 17193,
"text": "hardikkoriintern"
},
{
"code": null,
"e": 17219,
"s": 17210,
"text": "Accolite"
},
{
"code": null,
"e": 17226,
"s": 17219,
"text": "Amazon"
},
{
"code": null,
"e": 17234,
"s": 17226,
"text": "Directi"
},
{
"code": null,
"e": 17243,
"s": 17234,
"text": "Facebook"
},
{
"code": null,
"e": 17251,
"s": 17243,
"text": "FactSet"
},
{
"code": null,
"e": 17261,
"s": 17251,
"text": "Microsoft"
},
{
"code": null,
"e": 17271,
"s": 17261,
"text": "OYO Rooms"
},
{
"code": null,
"e": 17276,
"s": 17271,
"text": "Tree"
},
{
"code": null,
"e": 17285,
"s": 17276,
"text": "Accolite"
},
{
"code": null,
"e": 17292,
"s": 17285,
"text": "Amazon"
},
{
"code": null,
"e": 17302,
"s": 17292,
"text": "Microsoft"
},
{
"code": null,
"e": 17312,
"s": 17302,
"text": "OYO Rooms"
},
{
"code": null,
"e": 17320,
"s": 17312,
"text": "FactSet"
},
{
"code": null,
"e": 17328,
"s": 17320,
"text": "Directi"
},
{
"code": null,
"e": 17337,
"s": 17328,
"text": "Facebook"
},
{
"code": null,
"e": 17342,
"s": 17337,
"text": "Tree"
}
] |
Get the first 3 rows of a given DataFrame
|
20 Aug, 2020
Let us first create a dataframe and then we will try to get first 3 rows of this dataframe using several methods.
Code: Creating a Dataframe.
Python3
# import pandas libraryimport pandas as pd # dictionaryrecord = { "Name": ["Tom", "Jack", "Lucy", "Bob", "Jerry", "Alice", "Thomas", "Barbie"], "Marks": [9, 19, 20, 17, 11, 18, 5, 8], "Status": ["Fail", "Pass", "Pass", "Pass","Pass", "Pass", "Fail", "Fail"]} # converting record into# pandas dataframedf = pd.DataFrame(record) # printing whole dataframedf
Output:
Output of above code: Dataframe created
Method 1: Using head(n) method.
This method returns top n rows of the dataframe where n is an integer value and it specifies the number of rows to be displayed. The default value of n is 5 therefore, head function without arguments gives the first five rows of the dataframe as an output. So to get first three rows of the dataframe, we can assign the value of n as ‘3’.
Syntax: Dataframe.head(n)
Below is the code for getting first three rows of the dataframe using head() method:
Python3
# import pandas libraryimport pandas as pd # dictionaryrecord = { "Name": ["Tom", "Jack", "Lucy", "Bob", "Jerry", "Alice", "Thomas", "Barbie"], "Marks": [9, 19, 20, 17, 11, 18, 5, 8], "Status": ["Fail", "Pass", "Pass", "Pass","Pass", "Pass", "Fail", "Fail"]} # converting record into# pandas dataframedf = pd.DataFrame(record) # select first 3 rows# from the dataframedf1 = df.head(3) # show the dataframedf1
Output:
Output of above code:- first three rows of the dataframe using head() function
Method 2: Using iloc[ ].
This can be used to slice a dataframe by using the starting index and ending index of the sliced dataframe that we want.
Syntax: dataframe.iloc[statrt_index, end_index+1]
So if we want first three rows, i.e. from index 0 to index 2, we can use the following code:
Python3
# import pandas libraryimport pandas as pd # dictionaryrecord = { "Name": ["Tom", "Jack", "Lucy", "Bob", "Jerry", "Alice", "Thomas", "Barbie"], "Marks": [9, 19, 20, 17, 11, 18, 5, 8], "Status": ["Fail", "Pass", "Pass", "Pass","Pass", "Pass", "Fail", "Fail"]} # converting record into# pandas dataframedf = pd.DataFrame(record) # select first 3 rows# from dataframedf2 = df.iloc[0:3] # show the dataframedf2
Output of above code:- First three rows of the dataframe using iloc[] method
Method 3: Using index of the rows.
iloc[ ] method can also be used by directly stating the indices of the rows we want in the iloc method. Say to get row with indices m and n iloc[ ] can be used as:
Syntax: Dataframe.iloc [ [m,n] ]
Following is the code to get first three rows of the dataframe using this method:
Python
# import pandas libraryimport pandas as pd # dictionaryrecord = { "Name": ["Tom", "Jack", "Lucy", "Bob", "Jerry", "Alice", "Thomas", "Barbie"], "Marks": [9, 19, 20, 17, 11, 18, 5, 8], "Status": ["Fail", "Pass", "Pass", "Pass","Pass", "Pass", "Fail", "Fail"]} # converting record into# pandas dataframedf = pd.DataFrame(record) # select first 3 rows # of the dataframedf3 = df.iloc[[0, 1, 2]] # show the dataframedf3
Output:
Output of the above code:- First three rows of the dataframe using iloc and indices of the desired rows.
Python pandas-dataFrame
Python Pandas-exercise
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n20 Aug, 2020"
},
{
"code": null,
"e": 142,
"s": 28,
"text": "Let us first create a dataframe and then we will try to get first 3 rows of this dataframe using several methods."
},
{
"code": null,
"e": 170,
"s": 142,
"text": "Code: Creating a Dataframe."
},
{
"code": null,
"e": 178,
"s": 170,
"text": "Python3"
},
{
"code": "# import pandas libraryimport pandas as pd # dictionaryrecord = { \"Name\": [\"Tom\", \"Jack\", \"Lucy\", \"Bob\", \"Jerry\", \"Alice\", \"Thomas\", \"Barbie\"], \"Marks\": [9, 19, 20, 17, 11, 18, 5, 8], \"Status\": [\"Fail\", \"Pass\", \"Pass\", \"Pass\",\"Pass\", \"Pass\", \"Fail\", \"Fail\"]} # converting record into# pandas dataframedf = pd.DataFrame(record) # printing whole dataframedf",
"e": 619,
"s": 178,
"text": null
},
{
"code": null,
"e": 627,
"s": 619,
"text": "Output:"
},
{
"code": null,
"e": 667,
"s": 627,
"text": "Output of above code: Dataframe created"
},
{
"code": null,
"e": 699,
"s": 667,
"text": "Method 1: Using head(n) method."
},
{
"code": null,
"e": 1039,
"s": 699,
"text": "This method returns top n rows of the dataframe where n is an integer value and it specifies the number of rows to be displayed. The default value of n is 5 therefore, head function without arguments gives the first five rows of the dataframe as an output. So to get first three rows of the dataframe, we can assign the value of n as ‘3’. "
},
{
"code": null,
"e": 1065,
"s": 1039,
"text": "Syntax: Dataframe.head(n)"
},
{
"code": null,
"e": 1150,
"s": 1065,
"text": "Below is the code for getting first three rows of the dataframe using head() method:"
},
{
"code": null,
"e": 1158,
"s": 1150,
"text": "Python3"
},
{
"code": "# import pandas libraryimport pandas as pd # dictionaryrecord = { \"Name\": [\"Tom\", \"Jack\", \"Lucy\", \"Bob\", \"Jerry\", \"Alice\", \"Thomas\", \"Barbie\"], \"Marks\": [9, 19, 20, 17, 11, 18, 5, 8], \"Status\": [\"Fail\", \"Pass\", \"Pass\", \"Pass\",\"Pass\", \"Pass\", \"Fail\", \"Fail\"]} # converting record into# pandas dataframedf = pd.DataFrame(record) # select first 3 rows# from the dataframedf1 = df.head(3) # show the dataframedf1",
"e": 1653,
"s": 1158,
"text": null
},
{
"code": null,
"e": 1661,
"s": 1653,
"text": "Output:"
},
{
"code": null,
"e": 1740,
"s": 1661,
"text": "Output of above code:- first three rows of the dataframe using head() function"
},
{
"code": null,
"e": 1765,
"s": 1740,
"text": "Method 2: Using iloc[ ]."
},
{
"code": null,
"e": 1886,
"s": 1765,
"text": "This can be used to slice a dataframe by using the starting index and ending index of the sliced dataframe that we want."
},
{
"code": null,
"e": 1936,
"s": 1886,
"text": "Syntax: dataframe.iloc[statrt_index, end_index+1]"
},
{
"code": null,
"e": 2029,
"s": 1936,
"text": "So if we want first three rows, i.e. from index 0 to index 2, we can use the following code:"
},
{
"code": null,
"e": 2037,
"s": 2029,
"text": "Python3"
},
{
"code": "# import pandas libraryimport pandas as pd # dictionaryrecord = { \"Name\": [\"Tom\", \"Jack\", \"Lucy\", \"Bob\", \"Jerry\", \"Alice\", \"Thomas\", \"Barbie\"], \"Marks\": [9, 19, 20, 17, 11, 18, 5, 8], \"Status\": [\"Fail\", \"Pass\", \"Pass\", \"Pass\",\"Pass\", \"Pass\", \"Fail\", \"Fail\"]} # converting record into# pandas dataframedf = pd.DataFrame(record) # select first 3 rows# from dataframedf2 = df.iloc[0:3] # show the dataframedf2",
"e": 2530,
"s": 2037,
"text": null
},
{
"code": null,
"e": 2607,
"s": 2530,
"text": "Output of above code:- First three rows of the dataframe using iloc[] method"
},
{
"code": null,
"e": 2642,
"s": 2607,
"text": "Method 3: Using index of the rows."
},
{
"code": null,
"e": 2807,
"s": 2642,
"text": " iloc[ ] method can also be used by directly stating the indices of the rows we want in the iloc method. Say to get row with indices m and n iloc[ ] can be used as:"
},
{
"code": null,
"e": 2840,
"s": 2807,
"text": "Syntax: Dataframe.iloc [ [m,n] ]"
},
{
"code": null,
"e": 2922,
"s": 2840,
"text": "Following is the code to get first three rows of the dataframe using this method:"
},
{
"code": null,
"e": 2929,
"s": 2922,
"text": "Python"
},
{
"code": "# import pandas libraryimport pandas as pd # dictionaryrecord = { \"Name\": [\"Tom\", \"Jack\", \"Lucy\", \"Bob\", \"Jerry\", \"Alice\", \"Thomas\", \"Barbie\"], \"Marks\": [9, 19, 20, 17, 11, 18, 5, 8], \"Status\": [\"Fail\", \"Pass\", \"Pass\", \"Pass\",\"Pass\", \"Pass\", \"Fail\", \"Fail\"]} # converting record into# pandas dataframedf = pd.DataFrame(record) # select first 3 rows # of the dataframedf3 = df.iloc[[0, 1, 2]] # show the dataframedf3",
"e": 3431,
"s": 2929,
"text": null
},
{
"code": null,
"e": 3439,
"s": 3431,
"text": "Output:"
},
{
"code": null,
"e": 3544,
"s": 3439,
"text": "Output of the above code:- First three rows of the dataframe using iloc and indices of the desired rows."
},
{
"code": null,
"e": 3568,
"s": 3544,
"text": "Python pandas-dataFrame"
},
{
"code": null,
"e": 3591,
"s": 3568,
"text": "Python Pandas-exercise"
},
{
"code": null,
"e": 3605,
"s": 3591,
"text": "Python-pandas"
},
{
"code": null,
"e": 3612,
"s": 3605,
"text": "Python"
}
] |
Bitwise AND of N binary strings
|
04 Jul, 2022
Given an array arr[] of binary strings, the task is to calculate the bitwise AND of all of these strings and print the resultant string.
Examples:
Input: arr[] = {"101", "110110", "111"}
Output: 000100
(000101) & (110110) & (000111) = 000100
Input: arr[] = {"110010101", "111101001"}
Output: 110000001
Approach 1: Similar to Add two bit strings(https://www.geeksforgeeks.org/add-two-bit-strings/) Given an array of N binary strings. We first compute the AND operation of the first two binary strings and then perform this “Result” with third binary string and so on till the last binary string. For Example, string arr[] = {“101”, “110110”, “111”}; Step 1: Result = 101 AND 110110; Step 2: Result = Result(Step1) AND 111; So on..
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ implementation of the above approach #include <bits/stdc++.h>using namespace std; // Helper method: given two unequal sized// bit strings, converts them to// same length by adding leading 0s in the// smaller string. Returns the new lengthint makeEqualLength(string &a, string &b){ int len_a = a.length(); int len_b = b.length(); int num_zeros = abs(len_a-len_b); if (len_a<len_b) { for (int i = 0 ; i<num_zeros; i++) { a = '0' + a; } // Return len_b which is highest. // No need to proceed further! return len_b; } else { for (int i = 0 ; i<num_zeros; i++) { b = '0' + b; } } // Return len_a which is greater or // equal to len_b return len_a;} // The main function that performs AND// operation of two-bit sequences// and returns the resultant stringstring andOperationBitwise(string s1, string s2){ // Make both strings of same length with the // maximum length of s1 & s2. int length = makeEqualLength(s1,s2); // Initialize res as NULL string string res = ""; // We start from left to right as we have // made both strings of same length. for (int i = 0 ; i<length; i++) { // Convert s1[i] and s2[i] to int and perform // bitwise AND operation, append to "res" string res = res + (char)((s1[i] - '0' & s2[i]-'0')+'0'); } return res;} //Driver Codeint main(){ string arr[] = {"101", "110110", "111"}; int n = sizeof(arr)/sizeof(arr[0]); string result; // Check corner case: If there is just one // binary string, then print it and return. if (n<2) { cout<<arr[n-1]<<endl; return 0; } result = arr[0]; for (int i = 1; i<n; i++) { result = andOperationBitwise(result, arr[i]); } cout <<result<<endl;}// This code has been contributed by sharathmaidargi
// Java implementation of the above approachclass GFG { // global fields static String a; static String b; // Helper method: given two unequal sized // bit strings, converts them to // same length by adding leading 0s in the // smaller string. Returns the new length static int makeEqualLength() { int len_a = a.length(); int len_b = b.length(); int num_zeros = Math.abs(len_a - len_b); if (len_a < len_b) { for (int i = 0; i < num_zeros; i++) { a = '0' + a; } // Return len_b which is highest. // No need to proceed further! return len_b; } else { for (int i = 0; i < num_zeros; i++) { b = '0' + b; } } // Return len_a which is greater or // equal to len_b return len_a; } // The main function that performs AND // operation of two-bit sequences // and returns the resultant string static String andOperationBitwise(String s1, String s2) { // Make both strings of same length with the // maximum length of s1 & s2. a = s1; b = s2; int length = makeEqualLength(); s1 = a; s2 = b; // Initialize res as NULL string String res = ""; // We start from left to right as we have // made both strings of same length. for (int i = 0; i < length; i++) { // Convert s1[i] and s2[i] to int and perform // bitwise AND operation, append to "res" string res = res + (char)((s1.charAt(i) - '0' & s2.charAt(i) - '0') + '0'); } return res; } // Driver code public static void main(String[] args) { String arr[] = { "101", "110110", "111" }; int n = arr.length; String result = ""; // Check corner case: If there is just one // binary string, then print it and return. if (n < 2) { System.out.println(arr[n - 1]); } result = arr[0]; for (int i = 1; i < n; i++) { result = andOperationBitwise(result, arr[i]); } System.out.println(result); }} // This code is contributed by phasing17
# Python3 implementation of above approach # this function takes two unequal sized# bit strings, converts them to# same length by adding leading 0s in the# smaller string. Returns the new lengthdef makeEqualLength(a, b): len_a = len(a) len_b = len(b) num_zeros = abs(len_a - len_b) if (len_a < len_b): for i in range(num_zeros): a = '0' + a # Return len_b which is highest. # No need to proceed further! return len_b, a, b else: for i in range(num_zeros): b = '0' + b # Return len_a which is greater or # equal to len_b return len_a, a, b # The main function that performs AND# operation of two-bit sequences# and returns the resultant stringdef andOperationBitwise(s1, s2): # Make both strings of same length # with the maximum length of s1 & s2. length, s1, s2 = makeEqualLength(s1, s2) # Initialize res as NULL string res = "" # We start from left to right as we have # made both strings of same length. for i in range(length): # Convert s1[i] and s2[i] to int # and perform bitwise AND operation, # append to "res" string res = res + str(int(s1[i]) & int(s2[i])) return res # Driver Codearr = ["101", "110110", "111"]n = len(arr)if (n < 2): print(arr[n - 1]) else: result = arr[0] for i in range(n): result = andOperationBitwise(result, arr[i]); print(result) # This code is contributed by# ANKITKUMAR34
// C# implementation of the above approach using System; class GFG { // global fields static string a; static string b; // Helper method: given two unequal sized // bit strings, converts them to // same length by adding leading 0s in the // smaller string. Returns the new length static int makeEqualLength() { int len_a = a.Length; int len_b = b.Length; int num_zeros = Math.Abs(len_a - len_b); if (len_a < len_b) { for (int i = 0; i < num_zeros; i++) { a = '0' + a; } // Return len_b which is highest. // No need to proceed further! return len_b; } else { for (int i = 0; i < num_zeros; i++) { b = '0' + b; } } // Return len_a which is greater or // equal to len_b return len_a; } // The main function that performs AND // operation of two-bit sequences // and returns the resultant string static string andOperationBitwise(string s1, string s2) { // Make both strings of same length with the // maximum length of s1 & s2. a = s1; b = s2; int length = makeEqualLength(); s1 = a; s2 = b; // Initialize res as NULL string string res = ""; // We start from left to right as we have // made both strings of same length. for (int i = 0; i < length; i++) { // Convert s1[i] and s2[i] to int and perform // bitwise AND operation, append to "res" string res = res + (char)((s1[i] - '0' & s2[i] - '0') + '0'); } return res; } // Driver code public static void Main(string[] args) { string[] arr = { "101", "110110", "111" }; int n = arr.Length; string result = ""; // Check corner case: If there is just one // binary string, then print it and return. if (n < 2) { Console.WriteLine(arr[n - 1]); } result = arr[0]; for (int i = 1; i < n; i++) { result = andOperationBitwise(result, arr[i]); } Console.WriteLine(result); }} // This code is contributed by phasing17
<script> // Javascript implementation of the above approach // Helper method: given two unequal sized// bit strings, converts them to// same length by adding leading 0s in the// smaller string. Returns the new lengthlet s1, s2; function makeEqualLength(){ let len_a = s1.length; let len_b = s2.length; let num_zeros = Math.abs(len_a - len_b); if (len_a < len_b) { for(let i = 0; i < num_zeros; i++) { s1 = '0' + s1; } // Return len_b which is highest. // No need to proceed further! return len_b; } else { for(let i = 0; i < num_zeros; i++) { s2 = '0' + s2; } } // Return len_a which is greater or // equal to len_b return len_a;} // The main function that performs AND// operation of two-bit sequences// and returns the resultant stringfunction andOperationBitwise(){ // Make both strings of same length with the // maximum length of s1 & s2. let length = makeEqualLength(); // Initialize res as NULL string let res = ""; // We start from left to right as we have // made both strings of same length. for(let i = 0 ; i<length; i++) { // Convert s1[i] and s2[i] to int // and perform bitwise AND operation, // append to "res" string res = res + String.fromCharCode((s1[i].charCodeAt() - '0'.charCodeAt() & s2[i].charCodeAt() - '0'.charCodeAt()) + '0'.charCodeAt()); } return res;} // Driver codelet arr = [ "101", "110110", "111" ];let n = arr.length;let result; // Check corner case: If there is just one// binary string, then print it and return.if (n < 2){ document.write(arr[n - 1] + "</br>");}result = arr[0];for(let i = 1; i<n; i++){ s1 = result; s2 = arr[i]; result = andOperationBitwise();}document.write(result); // This code is contributed by vaibhavrabadiya3 </script>
000100
Approach 2: Find the size of the smallest and the largest string. We need this to add (largest-smallest) zeroes to our result. For example, if we have 0010 and 11, then AND on these strings will be 0010 (since we can write 11 as 0011). Then perform AND operation on each bit.We can achieve this by only finding if the current bit in any string is 0 or not. If current bit is 0 in any of the given strings, then AND operation on that bit will be 0. If all bits at the current position are 1, then AND operation will be 1.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ implementation of the above approach #include <bits/stdc++.h>using namespace std; // Function to find the bitwise AND of// all the binary stringsstring strBitwiseAND(string* arr, int n){ string res; // To store the largest and the smallest // string's size, We need this to add '0's // in the resultant string int smallest_size = INT_MAX; int largest_size = INT_MIN; // Reverse each string // Since we need to perform AND operation // on bits from Right to Left for (int i = 0; i < n; i++) { reverse(arr[i].begin(), arr[i].end()); // Update the respective length values smallest_size = min(smallest_size, (int)arr[i].size()); largest_size = max(largest_size, (int)arr[i].size()); } // Traverse bits from 0 to smallest string's size for (int i = 0; i < smallest_size; i++) { bool all_ones = true; for (int j = 0; j < n; j++) { // If at this bit position, there is a 0 // in any of the given strings then AND // operation on current bit position // will be 0 if (arr[j][i] == '0') { all_ones = false; break; } } // Add resultant bit to result res += (all_ones ? '1' : '0'); } // Add 0's to the string. for (int i = 0; i < largest_size - smallest_size; i++) res += '0'; // Reverse the string // Since we started from LEFT to RIGHT reverse(res.begin(), res.end()); // Return the resultant string return res;} // Driver codeint main(){ string arr[] = { "101", "110110", "111" }; int n = sizeof(arr) / sizeof(arr[0]); cout << strBitwiseAND(arr, n); return 0;}
// Java implementation of the above approachclass GfG{ // Function to find the bitwise AND of // all the binary strings static String strBitwiseAND(String[] arr, int n) { String res = ""; // To store the largest and the smallest // string's size, We need this to add // '0's in the resultant string int smallest_size = Integer.MAX_VALUE; int largest_size = Integer.MIN_VALUE; // Reverse each string // Since we need to perform AND operation // on bits from Right to Left for (int i = 0; i < n; i++) { StringBuilder temp = new StringBuilder(); temp.append(arr[i]); arr[i] = temp.reverse().toString(); // Update the respective length values smallest_size = Math.min(smallest_size, arr[i].length()); largest_size = Math.max(largest_size, arr[i].length()); } // Traverse bits from 0 to smallest string's size for (int i = 0; i < smallest_size; i++) { boolean all_ones = true; for (int j = 0; j < n; j++) { // If at this bit position, there is a 0 // in any of the given strings then AND // operation on current bit position // will be 0 if (arr[j].charAt(i) == '0') { all_ones = false; break; } } // Add resultant bit to result res += (all_ones ? '1' : '0'); } // Add 0's to the string. for (int i = 0; i < largest_size - smallest_size; i++) res += '0'; // Reverse the string // Since we started from LEFT to RIGHT StringBuilder temp = new StringBuilder(); temp.append(res); res = temp.reverse().toString(); // Return the resultant string return res; } // Driver code public static void main(String []args) { String arr[] = { "101", "110110", "111" }; int n = arr.length; System.out.println(strBitwiseAND(arr, n)); }} // This code is contributed by Rituraj Jain
# Python3 implementation of the above approachimport sys; # Function to find the bitwise AND of# all the binary stringsdef strBitwiseAND(arr, n) : res = "" # To store the largest and the smallest # string's size, We need this to add '0's # in the resultant string smallest_size = sys.maxsize; largest_size = -(sys.maxsize - 1); # Reverse each string # Since we need to perform AND operation # on bits from Right to Left for i in range(n) : arr[i] = arr[i][::-1] ; # Update the respective length values smallest_size = min(smallest_size, len(arr[i])); largest_size = max(largest_size, len(arr[i])); # Traverse bits from 0 to smallest string's size for i in range(smallest_size) : all_ones = True; for j in range(n) : # If at this bit position, there is a 0 # in any of the given strings then AND # operation on current bit position # will be 0 if (arr[j][i] == '0') : all_ones = False; break; # Add resultant bit to result if all_ones : res += '1' ; else : res += '0' ; # Add 0's to the string. for i in range(largest_size - smallest_size) : res += '0'; # Reverse the string # Since we started from LEFT to RIGHT res = res[::-1]; # Return the resultant string return res; # Driver codeif __name__ == "__main__" : arr = [ "101", "110110", "111" ]; n = len(arr) ; print(strBitwiseAND(arr, n)); # This code is contributed by Ryuga
// C# implementation of the above approach:using System; class GfG{ // Function to find the bitwise AND of // all the binary strings static String strBitwiseAND(String[] arr, int n) { String res = ""; // To store the largest and the smallest // string's size, We need this to add // '0's in the resultant string int smallest_size = int.MaxValue; int largest_size = int.MinValue; // Reverse each string // Since we need to perform AND operation // on bits from Right to Left String temp =""; for (int i = 0; i < n; i++) { temp+=arr[i]; arr[i] = reverse(temp); // Update the respective length values smallest_size = Math.Min(smallest_size, arr[i].Length); largest_size = Math.Max(largest_size, arr[i].Length); } // Traverse bits from 0 to smallest string's size for (int i = 0; i < smallest_size; i++) { bool all_ones = true; for (int j = 0; j < n; j++) { // If at this bit position, there is a 0 // in any of the given strings then AND // operation on current bit position // will be 0 if (arr[j][i] == '0') { all_ones = false; break; } } // Add resultant bit to result res += (all_ones ? '1' : '0'); } // Add 0's to the string. for (int i = 0; i < largest_size - smallest_size; i++) res += '0'; // Reverse the string // Since we started from LEFT to RIGHT String temp1 = ""; temp1+=res; res = reverse(temp1); // Return the resultant string return res; } static String reverse(String input) { char[] temparray = input.ToCharArray(); int left, right = 0; right = temparray.Length - 1; for (left = 0; left < right; left++, right--) { // Swap values of left and right char temp = temparray[left]; temparray[left] = temparray[right]; temparray[right] = temp; } return String.Join("",temparray); } // Driver code public static void Main(String []args) { String []arr = { "101", "110110", "111" }; int n = arr.Length; Console.WriteLine(strBitwiseAND(arr, n)); }} // This code has been contributed by 29AjayKumar
<script> // JavaScript implementation of the above approach: // Function to find the bitwise AND of // all the binary strings function strBitwiseAND(arr, n) { let res = ""; // To store the largest and the smallest // string's size, We need this to add // '0's in the resultant string let smallest_size = Number.MAX_VALUE; let largest_size = Number.MIN_VALUE; // Reverse each string // Since we need to perform AND operation // on bits from Right to Left let temp =""; for (let i = 0; i < n; i++) { temp+=arr[i]; arr[i] = reverse(temp); // Update the respective length values smallest_size = Math.min(smallest_size, arr[i].length); largest_size = Math.max(largest_size, arr[i].length); } // Traverse bits from 0 to smallest string's size for (let i = 0; i < smallest_size; i++) { let all_ones = true; for (let j = 0; j < n; j++) { // If at this bit position, there is a 0 // in any of the given strings then AND // operation on current bit position // will be 0 if (arr[j][i] == '0') { all_ones = false; break; } } // Add resultant bit to result res += (all_ones ? '1' : '0'); } // Add 0's to the string. for (let i = 0; i < largest_size - smallest_size; i++) res += '0'; // Reverse the string // Since we started from LEFT to RIGHT let temp1 = ""; temp1+=res; res = reverse(temp1); // Return the resultant string let temparray1 = res; let Temparray = ""; for(let i = 6; i < temparray1.length; i++) { Temparray = Temparray + temparray1[i]; } return Temparray; } function reverse(input) { let temparray = input.split(''); let left, right = 0; right = temparray.length - 1; for (left = 0; left < right; left++, right--) { // Swap values of left and right let temp = temparray[left]; temparray[left] = temparray[right]; temparray[right] = temp; } return temparray.join(""); } let arr = [ "101", "110110", "111" ]; let n = arr.length; document.write(strBitwiseAND(arr, n)); </script>
000100
ankthon
rituraj_jain
29AjayKumar
sharathmaidargi
ANKITKUMAR34
ApurvaRaj
rameshtravel07
vaibhavrabadiya3
ankita_saini
phasing17
binary-string
Bitwise-AND
Marketing
Sorting
Strings
Strings
Sorting
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
HeapSort
std::sort() in C++ STL
Time Complexities of all Sorting Algorithms
Count Inversions in an array | Set 1 (Using Merge Sort)
Merge two sorted arrays
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
Check for Balanced Brackets in an expression (well-formedness) using Stack
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n04 Jul, 2022"
},
{
"code": null,
"e": 189,
"s": 52,
"text": "Given an array arr[] of binary strings, the task is to calculate the bitwise AND of all of these strings and print the resultant string."
},
{
"code": null,
"e": 200,
"s": 189,
"text": "Examples: "
},
{
"code": null,
"e": 356,
"s": 200,
"text": "Input: arr[] = {\"101\", \"110110\", \"111\"}\nOutput: 000100\n(000101) & (110110) & (000111) = 000100\n\nInput: arr[] = {\"110010101\", \"111101001\"}\nOutput: 110000001"
},
{
"code": null,
"e": 785,
"s": 356,
"text": "Approach 1: Similar to Add two bit strings(https://www.geeksforgeeks.org/add-two-bit-strings/) Given an array of N binary strings. We first compute the AND operation of the first two binary strings and then perform this “Result” with third binary string and so on till the last binary string. For Example, string arr[] = {“101”, “110110”, “111”}; Step 1: Result = 101 AND 110110; Step 2: Result = Result(Step1) AND 111; So on.. "
},
{
"code": null,
"e": 838,
"s": 785,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 842,
"s": 838,
"text": "C++"
},
{
"code": null,
"e": 847,
"s": 842,
"text": "Java"
},
{
"code": null,
"e": 855,
"s": 847,
"text": "Python3"
},
{
"code": null,
"e": 858,
"s": 855,
"text": "C#"
},
{
"code": null,
"e": 869,
"s": 858,
"text": "Javascript"
},
{
"code": "// C++ implementation of the above approach #include <bits/stdc++.h>using namespace std; // Helper method: given two unequal sized// bit strings, converts them to// same length by adding leading 0s in the// smaller string. Returns the new lengthint makeEqualLength(string &a, string &b){ int len_a = a.length(); int len_b = b.length(); int num_zeros = abs(len_a-len_b); if (len_a<len_b) { for (int i = 0 ; i<num_zeros; i++) { a = '0' + a; } // Return len_b which is highest. // No need to proceed further! return len_b; } else { for (int i = 0 ; i<num_zeros; i++) { b = '0' + b; } } // Return len_a which is greater or // equal to len_b return len_a;} // The main function that performs AND// operation of two-bit sequences// and returns the resultant stringstring andOperationBitwise(string s1, string s2){ // Make both strings of same length with the // maximum length of s1 & s2. int length = makeEqualLength(s1,s2); // Initialize res as NULL string string res = \"\"; // We start from left to right as we have // made both strings of same length. for (int i = 0 ; i<length; i++) { // Convert s1[i] and s2[i] to int and perform // bitwise AND operation, append to \"res\" string res = res + (char)((s1[i] - '0' & s2[i]-'0')+'0'); } return res;} //Driver Codeint main(){ string arr[] = {\"101\", \"110110\", \"111\"}; int n = sizeof(arr)/sizeof(arr[0]); string result; // Check corner case: If there is just one // binary string, then print it and return. if (n<2) { cout<<arr[n-1]<<endl; return 0; } result = arr[0]; for (int i = 1; i<n; i++) { result = andOperationBitwise(result, arr[i]); } cout <<result<<endl;}// This code has been contributed by sharathmaidargi",
"e": 2786,
"s": 869,
"text": null
},
{
"code": "// Java implementation of the above approachclass GFG { // global fields static String a; static String b; // Helper method: given two unequal sized // bit strings, converts them to // same length by adding leading 0s in the // smaller string. Returns the new length static int makeEqualLength() { int len_a = a.length(); int len_b = b.length(); int num_zeros = Math.abs(len_a - len_b); if (len_a < len_b) { for (int i = 0; i < num_zeros; i++) { a = '0' + a; } // Return len_b which is highest. // No need to proceed further! return len_b; } else { for (int i = 0; i < num_zeros; i++) { b = '0' + b; } } // Return len_a which is greater or // equal to len_b return len_a; } // The main function that performs AND // operation of two-bit sequences // and returns the resultant string static String andOperationBitwise(String s1, String s2) { // Make both strings of same length with the // maximum length of s1 & s2. a = s1; b = s2; int length = makeEqualLength(); s1 = a; s2 = b; // Initialize res as NULL string String res = \"\"; // We start from left to right as we have // made both strings of same length. for (int i = 0; i < length; i++) { // Convert s1[i] and s2[i] to int and perform // bitwise AND operation, append to \"res\" string res = res + (char)((s1.charAt(i) - '0' & s2.charAt(i) - '0') + '0'); } return res; } // Driver code public static void main(String[] args) { String arr[] = { \"101\", \"110110\", \"111\" }; int n = arr.length; String result = \"\"; // Check corner case: If there is just one // binary string, then print it and return. if (n < 2) { System.out.println(arr[n - 1]); } result = arr[0]; for (int i = 1; i < n; i++) { result = andOperationBitwise(result, arr[i]); } System.out.println(result); }} // This code is contributed by phasing17",
"e": 5097,
"s": 2786,
"text": null
},
{
"code": "# Python3 implementation of above approach # this function takes two unequal sized# bit strings, converts them to# same length by adding leading 0s in the# smaller string. Returns the new lengthdef makeEqualLength(a, b): len_a = len(a) len_b = len(b) num_zeros = abs(len_a - len_b) if (len_a < len_b): for i in range(num_zeros): a = '0' + a # Return len_b which is highest. # No need to proceed further! return len_b, a, b else: for i in range(num_zeros): b = '0' + b # Return len_a which is greater or # equal to len_b return len_a, a, b # The main function that performs AND# operation of two-bit sequences# and returns the resultant stringdef andOperationBitwise(s1, s2): # Make both strings of same length # with the maximum length of s1 & s2. length, s1, s2 = makeEqualLength(s1, s2) # Initialize res as NULL string res = \"\" # We start from left to right as we have # made both strings of same length. for i in range(length): # Convert s1[i] and s2[i] to int # and perform bitwise AND operation, # append to \"res\" string res = res + str(int(s1[i]) & int(s2[i])) return res # Driver Codearr = [\"101\", \"110110\", \"111\"]n = len(arr)if (n < 2): print(arr[n - 1]) else: result = arr[0] for i in range(n): result = andOperationBitwise(result, arr[i]); print(result) # This code is contributed by# ANKITKUMAR34",
"e": 6631,
"s": 5097,
"text": null
},
{
"code": "// C# implementation of the above approach using System; class GFG { // global fields static string a; static string b; // Helper method: given two unequal sized // bit strings, converts them to // same length by adding leading 0s in the // smaller string. Returns the new length static int makeEqualLength() { int len_a = a.Length; int len_b = b.Length; int num_zeros = Math.Abs(len_a - len_b); if (len_a < len_b) { for (int i = 0; i < num_zeros; i++) { a = '0' + a; } // Return len_b which is highest. // No need to proceed further! return len_b; } else { for (int i = 0; i < num_zeros; i++) { b = '0' + b; } } // Return len_a which is greater or // equal to len_b return len_a; } // The main function that performs AND // operation of two-bit sequences // and returns the resultant string static string andOperationBitwise(string s1, string s2) { // Make both strings of same length with the // maximum length of s1 & s2. a = s1; b = s2; int length = makeEqualLength(); s1 = a; s2 = b; // Initialize res as NULL string string res = \"\"; // We start from left to right as we have // made both strings of same length. for (int i = 0; i < length; i++) { // Convert s1[i] and s2[i] to int and perform // bitwise AND operation, append to \"res\" string res = res + (char)((s1[i] - '0' & s2[i] - '0') + '0'); } return res; } // Driver code public static void Main(string[] args) { string[] arr = { \"101\", \"110110\", \"111\" }; int n = arr.Length; string result = \"\"; // Check corner case: If there is just one // binary string, then print it and return. if (n < 2) { Console.WriteLine(arr[n - 1]); } result = arr[0]; for (int i = 1; i < n; i++) { result = andOperationBitwise(result, arr[i]); } Console.WriteLine(result); }} // This code is contributed by phasing17",
"e": 8620,
"s": 6631,
"text": null
},
{
"code": "<script> // Javascript implementation of the above approach // Helper method: given two unequal sized// bit strings, converts them to// same length by adding leading 0s in the// smaller string. Returns the new lengthlet s1, s2; function makeEqualLength(){ let len_a = s1.length; let len_b = s2.length; let num_zeros = Math.abs(len_a - len_b); if (len_a < len_b) { for(let i = 0; i < num_zeros; i++) { s1 = '0' + s1; } // Return len_b which is highest. // No need to proceed further! return len_b; } else { for(let i = 0; i < num_zeros; i++) { s2 = '0' + s2; } } // Return len_a which is greater or // equal to len_b return len_a;} // The main function that performs AND// operation of two-bit sequences// and returns the resultant stringfunction andOperationBitwise(){ // Make both strings of same length with the // maximum length of s1 & s2. let length = makeEqualLength(); // Initialize res as NULL string let res = \"\"; // We start from left to right as we have // made both strings of same length. for(let i = 0 ; i<length; i++) { // Convert s1[i] and s2[i] to int // and perform bitwise AND operation, // append to \"res\" string res = res + String.fromCharCode((s1[i].charCodeAt() - '0'.charCodeAt() & s2[i].charCodeAt() - '0'.charCodeAt()) + '0'.charCodeAt()); } return res;} // Driver codelet arr = [ \"101\", \"110110\", \"111\" ];let n = arr.length;let result; // Check corner case: If there is just one// binary string, then print it and return.if (n < 2){ document.write(arr[n - 1] + \"</br>\");}result = arr[0];for(let i = 1; i<n; i++){ s1 = result; s2 = arr[i]; result = andOperationBitwise();}document.write(result); // This code is contributed by vaibhavrabadiya3 </script>",
"e": 10693,
"s": 8620,
"text": null
},
{
"code": null,
"e": 10700,
"s": 10693,
"text": "000100"
},
{
"code": null,
"e": 11223,
"s": 10702,
"text": "Approach 2: Find the size of the smallest and the largest string. We need this to add (largest-smallest) zeroes to our result. For example, if we have 0010 and 11, then AND on these strings will be 0010 (since we can write 11 as 0011). Then perform AND operation on each bit.We can achieve this by only finding if the current bit in any string is 0 or not. If current bit is 0 in any of the given strings, then AND operation on that bit will be 0. If all bits at the current position are 1, then AND operation will be 1."
},
{
"code": null,
"e": 11276,
"s": 11223,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 11280,
"s": 11276,
"text": "C++"
},
{
"code": null,
"e": 11285,
"s": 11280,
"text": "Java"
},
{
"code": null,
"e": 11293,
"s": 11285,
"text": "Python3"
},
{
"code": null,
"e": 11296,
"s": 11293,
"text": "C#"
},
{
"code": null,
"e": 11307,
"s": 11296,
"text": "Javascript"
},
{
"code": "// C++ implementation of the above approach #include <bits/stdc++.h>using namespace std; // Function to find the bitwise AND of// all the binary stringsstring strBitwiseAND(string* arr, int n){ string res; // To store the largest and the smallest // string's size, We need this to add '0's // in the resultant string int smallest_size = INT_MAX; int largest_size = INT_MIN; // Reverse each string // Since we need to perform AND operation // on bits from Right to Left for (int i = 0; i < n; i++) { reverse(arr[i].begin(), arr[i].end()); // Update the respective length values smallest_size = min(smallest_size, (int)arr[i].size()); largest_size = max(largest_size, (int)arr[i].size()); } // Traverse bits from 0 to smallest string's size for (int i = 0; i < smallest_size; i++) { bool all_ones = true; for (int j = 0; j < n; j++) { // If at this bit position, there is a 0 // in any of the given strings then AND // operation on current bit position // will be 0 if (arr[j][i] == '0') { all_ones = false; break; } } // Add resultant bit to result res += (all_ones ? '1' : '0'); } // Add 0's to the string. for (int i = 0; i < largest_size - smallest_size; i++) res += '0'; // Reverse the string // Since we started from LEFT to RIGHT reverse(res.begin(), res.end()); // Return the resultant string return res;} // Driver codeint main(){ string arr[] = { \"101\", \"110110\", \"111\" }; int n = sizeof(arr) / sizeof(arr[0]); cout << strBitwiseAND(arr, n); return 0;}",
"e": 13023,
"s": 11307,
"text": null
},
{
"code": "// Java implementation of the above approachclass GfG{ // Function to find the bitwise AND of // all the binary strings static String strBitwiseAND(String[] arr, int n) { String res = \"\"; // To store the largest and the smallest // string's size, We need this to add // '0's in the resultant string int smallest_size = Integer.MAX_VALUE; int largest_size = Integer.MIN_VALUE; // Reverse each string // Since we need to perform AND operation // on bits from Right to Left for (int i = 0; i < n; i++) { StringBuilder temp = new StringBuilder(); temp.append(arr[i]); arr[i] = temp.reverse().toString(); // Update the respective length values smallest_size = Math.min(smallest_size, arr[i].length()); largest_size = Math.max(largest_size, arr[i].length()); } // Traverse bits from 0 to smallest string's size for (int i = 0; i < smallest_size; i++) { boolean all_ones = true; for (int j = 0; j < n; j++) { // If at this bit position, there is a 0 // in any of the given strings then AND // operation on current bit position // will be 0 if (arr[j].charAt(i) == '0') { all_ones = false; break; } } // Add resultant bit to result res += (all_ones ? '1' : '0'); } // Add 0's to the string. for (int i = 0; i < largest_size - smallest_size; i++) res += '0'; // Reverse the string // Since we started from LEFT to RIGHT StringBuilder temp = new StringBuilder(); temp.append(res); res = temp.reverse().toString(); // Return the resultant string return res; } // Driver code public static void main(String []args) { String arr[] = { \"101\", \"110110\", \"111\" }; int n = arr.length; System.out.println(strBitwiseAND(arr, n)); }} // This code is contributed by Rituraj Jain",
"e": 15274,
"s": 13023,
"text": null
},
{
"code": "# Python3 implementation of the above approachimport sys; # Function to find the bitwise AND of# all the binary stringsdef strBitwiseAND(arr, n) : res = \"\" # To store the largest and the smallest # string's size, We need this to add '0's # in the resultant string smallest_size = sys.maxsize; largest_size = -(sys.maxsize - 1); # Reverse each string # Since we need to perform AND operation # on bits from Right to Left for i in range(n) : arr[i] = arr[i][::-1] ; # Update the respective length values smallest_size = min(smallest_size, len(arr[i])); largest_size = max(largest_size, len(arr[i])); # Traverse bits from 0 to smallest string's size for i in range(smallest_size) : all_ones = True; for j in range(n) : # If at this bit position, there is a 0 # in any of the given strings then AND # operation on current bit position # will be 0 if (arr[j][i] == '0') : all_ones = False; break; # Add resultant bit to result if all_ones : res += '1' ; else : res += '0' ; # Add 0's to the string. for i in range(largest_size - smallest_size) : res += '0'; # Reverse the string # Since we started from LEFT to RIGHT res = res[::-1]; # Return the resultant string return res; # Driver codeif __name__ == \"__main__\" : arr = [ \"101\", \"110110\", \"111\" ]; n = len(arr) ; print(strBitwiseAND(arr, n)); # This code is contributed by Ryuga",
"e": 16923,
"s": 15274,
"text": null
},
{
"code": "// C# implementation of the above approach:using System; class GfG{ // Function to find the bitwise AND of // all the binary strings static String strBitwiseAND(String[] arr, int n) { String res = \"\"; // To store the largest and the smallest // string's size, We need this to add // '0's in the resultant string int smallest_size = int.MaxValue; int largest_size = int.MinValue; // Reverse each string // Since we need to perform AND operation // on bits from Right to Left String temp =\"\"; for (int i = 0; i < n; i++) { temp+=arr[i]; arr[i] = reverse(temp); // Update the respective length values smallest_size = Math.Min(smallest_size, arr[i].Length); largest_size = Math.Max(largest_size, arr[i].Length); } // Traverse bits from 0 to smallest string's size for (int i = 0; i < smallest_size; i++) { bool all_ones = true; for (int j = 0; j < n; j++) { // If at this bit position, there is a 0 // in any of the given strings then AND // operation on current bit position // will be 0 if (arr[j][i] == '0') { all_ones = false; break; } } // Add resultant bit to result res += (all_ones ? '1' : '0'); } // Add 0's to the string. for (int i = 0; i < largest_size - smallest_size; i++) res += '0'; // Reverse the string // Since we started from LEFT to RIGHT String temp1 = \"\"; temp1+=res; res = reverse(temp1); // Return the resultant string return res; } static String reverse(String input) { char[] temparray = input.ToCharArray(); int left, right = 0; right = temparray.Length - 1; for (left = 0; left < right; left++, right--) { // Swap values of left and right char temp = temparray[left]; temparray[left] = temparray[right]; temparray[right] = temp; } return String.Join(\"\",temparray); } // Driver code public static void Main(String []args) { String []arr = { \"101\", \"110110\", \"111\" }; int n = arr.Length; Console.WriteLine(strBitwiseAND(arr, n)); }} // This code has been contributed by 29AjayKumar",
"e": 19542,
"s": 16923,
"text": null
},
{
"code": "<script> // JavaScript implementation of the above approach: // Function to find the bitwise AND of // all the binary strings function strBitwiseAND(arr, n) { let res = \"\"; // To store the largest and the smallest // string's size, We need this to add // '0's in the resultant string let smallest_size = Number.MAX_VALUE; let largest_size = Number.MIN_VALUE; // Reverse each string // Since we need to perform AND operation // on bits from Right to Left let temp =\"\"; for (let i = 0; i < n; i++) { temp+=arr[i]; arr[i] = reverse(temp); // Update the respective length values smallest_size = Math.min(smallest_size, arr[i].length); largest_size = Math.max(largest_size, arr[i].length); } // Traverse bits from 0 to smallest string's size for (let i = 0; i < smallest_size; i++) { let all_ones = true; for (let j = 0; j < n; j++) { // If at this bit position, there is a 0 // in any of the given strings then AND // operation on current bit position // will be 0 if (arr[j][i] == '0') { all_ones = false; break; } } // Add resultant bit to result res += (all_ones ? '1' : '0'); } // Add 0's to the string. for (let i = 0; i < largest_size - smallest_size; i++) res += '0'; // Reverse the string // Since we started from LEFT to RIGHT let temp1 = \"\"; temp1+=res; res = reverse(temp1); // Return the resultant string let temparray1 = res; let Temparray = \"\"; for(let i = 6; i < temparray1.length; i++) { Temparray = Temparray + temparray1[i]; } return Temparray; } function reverse(input) { let temparray = input.split(''); let left, right = 0; right = temparray.length - 1; for (left = 0; left < right; left++, right--) { // Swap values of left and right let temp = temparray[left]; temparray[left] = temparray[right]; temparray[right] = temp; } return temparray.join(\"\"); } let arr = [ \"101\", \"110110\", \"111\" ]; let n = arr.length; document.write(strBitwiseAND(arr, n)); </script>",
"e": 22186,
"s": 19542,
"text": null
},
{
"code": null,
"e": 22193,
"s": 22186,
"text": "000100"
},
{
"code": null,
"e": 22203,
"s": 22195,
"text": "ankthon"
},
{
"code": null,
"e": 22216,
"s": 22203,
"text": "rituraj_jain"
},
{
"code": null,
"e": 22228,
"s": 22216,
"text": "29AjayKumar"
},
{
"code": null,
"e": 22244,
"s": 22228,
"text": "sharathmaidargi"
},
{
"code": null,
"e": 22257,
"s": 22244,
"text": "ANKITKUMAR34"
},
{
"code": null,
"e": 22267,
"s": 22257,
"text": "ApurvaRaj"
},
{
"code": null,
"e": 22282,
"s": 22267,
"text": "rameshtravel07"
},
{
"code": null,
"e": 22299,
"s": 22282,
"text": "vaibhavrabadiya3"
},
{
"code": null,
"e": 22312,
"s": 22299,
"text": "ankita_saini"
},
{
"code": null,
"e": 22322,
"s": 22312,
"text": "phasing17"
},
{
"code": null,
"e": 22336,
"s": 22322,
"text": "binary-string"
},
{
"code": null,
"e": 22348,
"s": 22336,
"text": "Bitwise-AND"
},
{
"code": null,
"e": 22358,
"s": 22348,
"text": "Marketing"
},
{
"code": null,
"e": 22366,
"s": 22358,
"text": "Sorting"
},
{
"code": null,
"e": 22374,
"s": 22366,
"text": "Strings"
},
{
"code": null,
"e": 22382,
"s": 22374,
"text": "Strings"
},
{
"code": null,
"e": 22390,
"s": 22382,
"text": "Sorting"
},
{
"code": null,
"e": 22488,
"s": 22390,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 22497,
"s": 22488,
"text": "HeapSort"
},
{
"code": null,
"e": 22520,
"s": 22497,
"text": "std::sort() in C++ STL"
},
{
"code": null,
"e": 22564,
"s": 22520,
"text": "Time Complexities of all Sorting Algorithms"
},
{
"code": null,
"e": 22620,
"s": 22564,
"text": "Count Inversions in an array | Set 1 (Using Merge Sort)"
},
{
"code": null,
"e": 22644,
"s": 22620,
"text": "Merge two sorted arrays"
},
{
"code": null,
"e": 22690,
"s": 22644,
"text": "Write a program to reverse an array or string"
},
{
"code": null,
"e": 22715,
"s": 22690,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 22775,
"s": 22715,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 22790,
"s": 22775,
"text": "C++ Data Types"
}
] |
Brutespray – Port Scanning and Automated Brute Force Tool
|
23 Sep, 2021
Brute-Forcing is the technique of matching the credentials like Usernames, Passwords, OTPs for unauthenticated access to the target domain. The list of words are been tested against the target to get the exact credentials. All this process is done through automated tools.
Brutespray is an automated tool that is used to perform brute-forcing for every possible way like Credentials Brute-Forcing, FTP brute-forcing, etc. The Brutespray tool is developed in the Python language which comes with tags-based usage and also interactive usage. After Scanning the target from Nmap the results are to be inputted to the tool for performing brute-forcing. This tool supports GNMAP/XML output file to Brute force Nmap open port services with default credentials using Medusa or Use your dictionary to gain access.
Note: Make Sure You have Python Installed on your System, as this is a python-based tool. Click to check the Installation process: Python Installation Steps on Linux
Step 1: Use the following command to install the tool in your Kali Linux operating system.
git clone https://github.com/x90skysn3k/brutespray.git
Step 2: Now use the following command to move into the directory of the tool. You have to move in the directory in order to run the tool.
cd brutespray
Step 3: You are in the directory of the Brutespray. Now you have to install a dependency of the Brutespray using the following command.
sudo pip3 install -r requirements.txt
Step 4: All the dependencies have been installed in your Kali Linux operating system. Now use the following command to run the tool and check the help section.
python3 brutespray.py -h
Example 1: Using Custom Wordlists
python3 brutespray.py –file results.gnmap -U user.txt -P pass.txt –threads 5 –hosts 5
In this example, we are using the custom word-lists to perform Brute-Forcing on the target domain.
Example 2: Brute-Forcing Specific Services
python3 brutespray.py –file results.gnmap –service ftp,ssh,telnet –threads 5 –hosts 5
In this example, we are only going to perform brute-forcing on ftp,ssh and telnet service.
Example 3: Specific Credentials/ Brute-Forcing Username and Password
python3 brutespray.py –file results.gnmap -u admin -p password –threads 5 –hosts 5
In this example, we will be brute-forcing with single or specified credentials.
Example 4: Continue After Success
python3 brutespray.py –file results.gnmap –threads 5 –hosts 5 -c
In this example, we will be continuing over brute-forcing attack after success also.
Example 5: Use Nmap XML Output
python3 brutespray.py --file results.xml --threads 5 --hosts 5
In this example, we will be using the XML file for scanning and brute-forcing.
Example 6: Brutespray Interactive Mode
python3 brutespray.py --file results.xml -i
In this example, we will be using the interactive mode of the tool Brutespray.
Kali-Linux
Linux-Tools
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
tar command in Linux with examples
Conditional Statements | Shell Script
Tail command in Linux with examples
UDP Server-Client implementation in C
Docker - COPY Instruction
scp command in Linux with Examples
Cat command in Linux with examples
echo command in Linux with Examples
touch command in Linux with Examples
chown command in Linux with Examples
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n23 Sep, 2021"
},
{
"code": null,
"e": 302,
"s": 28,
"text": "Brute-Forcing is the technique of matching the credentials like Usernames, Passwords, OTPs for unauthenticated access to the target domain. The list of words are been tested against the target to get the exact credentials. All this process is done through automated tools. "
},
{
"code": null,
"e": 835,
"s": 302,
"text": "Brutespray is an automated tool that is used to perform brute-forcing for every possible way like Credentials Brute-Forcing, FTP brute-forcing, etc. The Brutespray tool is developed in the Python language which comes with tags-based usage and also interactive usage. After Scanning the target from Nmap the results are to be inputted to the tool for performing brute-forcing. This tool supports GNMAP/XML output file to Brute force Nmap open port services with default credentials using Medusa or Use your dictionary to gain access."
},
{
"code": null,
"e": 1001,
"s": 835,
"text": "Note: Make Sure You have Python Installed on your System, as this is a python-based tool. Click to check the Installation process: Python Installation Steps on Linux"
},
{
"code": null,
"e": 1092,
"s": 1001,
"text": "Step 1: Use the following command to install the tool in your Kali Linux operating system."
},
{
"code": null,
"e": 1147,
"s": 1092,
"text": "git clone https://github.com/x90skysn3k/brutespray.git"
},
{
"code": null,
"e": 1285,
"s": 1147,
"text": "Step 2: Now use the following command to move into the directory of the tool. You have to move in the directory in order to run the tool."
},
{
"code": null,
"e": 1299,
"s": 1285,
"text": "cd brutespray"
},
{
"code": null,
"e": 1435,
"s": 1299,
"text": "Step 3: You are in the directory of the Brutespray. Now you have to install a dependency of the Brutespray using the following command."
},
{
"code": null,
"e": 1473,
"s": 1435,
"text": "sudo pip3 install -r requirements.txt"
},
{
"code": null,
"e": 1633,
"s": 1473,
"text": "Step 4: All the dependencies have been installed in your Kali Linux operating system. Now use the following command to run the tool and check the help section."
},
{
"code": null,
"e": 1658,
"s": 1633,
"text": "python3 brutespray.py -h"
},
{
"code": null,
"e": 1692,
"s": 1658,
"text": "Example 1: Using Custom Wordlists"
},
{
"code": null,
"e": 1778,
"s": 1692,
"text": "python3 brutespray.py –file results.gnmap -U user.txt -P pass.txt –threads 5 –hosts 5"
},
{
"code": null,
"e": 1877,
"s": 1778,
"text": "In this example, we are using the custom word-lists to perform Brute-Forcing on the target domain."
},
{
"code": null,
"e": 1920,
"s": 1877,
"text": "Example 2: Brute-Forcing Specific Services"
},
{
"code": null,
"e": 2006,
"s": 1920,
"text": "python3 brutespray.py –file results.gnmap –service ftp,ssh,telnet –threads 5 –hosts 5"
},
{
"code": null,
"e": 2097,
"s": 2006,
"text": "In this example, we are only going to perform brute-forcing on ftp,ssh and telnet service."
},
{
"code": null,
"e": 2166,
"s": 2097,
"text": "Example 3: Specific Credentials/ Brute-Forcing Username and Password"
},
{
"code": null,
"e": 2249,
"s": 2166,
"text": "python3 brutespray.py –file results.gnmap -u admin -p password –threads 5 –hosts 5"
},
{
"code": null,
"e": 2329,
"s": 2249,
"text": "In this example, we will be brute-forcing with single or specified credentials."
},
{
"code": null,
"e": 2363,
"s": 2329,
"text": "Example 4: Continue After Success"
},
{
"code": null,
"e": 2428,
"s": 2363,
"text": "python3 brutespray.py –file results.gnmap –threads 5 –hosts 5 -c"
},
{
"code": null,
"e": 2513,
"s": 2428,
"text": "In this example, we will be continuing over brute-forcing attack after success also."
},
{
"code": null,
"e": 2544,
"s": 2513,
"text": "Example 5: Use Nmap XML Output"
},
{
"code": null,
"e": 2607,
"s": 2544,
"text": "python3 brutespray.py --file results.xml --threads 5 --hosts 5"
},
{
"code": null,
"e": 2686,
"s": 2607,
"text": "In this example, we will be using the XML file for scanning and brute-forcing."
},
{
"code": null,
"e": 2725,
"s": 2686,
"text": "Example 6: Brutespray Interactive Mode"
},
{
"code": null,
"e": 2769,
"s": 2725,
"text": "python3 brutespray.py --file results.xml -i"
},
{
"code": null,
"e": 2848,
"s": 2769,
"text": "In this example, we will be using the interactive mode of the tool Brutespray."
},
{
"code": null,
"e": 2859,
"s": 2848,
"text": "Kali-Linux"
},
{
"code": null,
"e": 2871,
"s": 2859,
"text": "Linux-Tools"
},
{
"code": null,
"e": 2882,
"s": 2871,
"text": "Linux-Unix"
},
{
"code": null,
"e": 2980,
"s": 2882,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3015,
"s": 2980,
"text": "tar command in Linux with examples"
},
{
"code": null,
"e": 3053,
"s": 3015,
"text": "Conditional Statements | Shell Script"
},
{
"code": null,
"e": 3089,
"s": 3053,
"text": "Tail command in Linux with examples"
},
{
"code": null,
"e": 3127,
"s": 3089,
"text": "UDP Server-Client implementation in C"
},
{
"code": null,
"e": 3153,
"s": 3127,
"text": "Docker - COPY Instruction"
},
{
"code": null,
"e": 3188,
"s": 3153,
"text": "scp command in Linux with Examples"
},
{
"code": null,
"e": 3223,
"s": 3188,
"text": "Cat command in Linux with examples"
},
{
"code": null,
"e": 3259,
"s": 3223,
"text": "echo command in Linux with Examples"
},
{
"code": null,
"e": 3296,
"s": 3259,
"text": "touch command in Linux with Examples"
}
] |
Difference between synchronous and asynchronous method of fs module
|
31 Aug, 2021
NodeJS provides us with an inbuilt fs (File System) module for various file handling operations like read a file, write a file, delete a file etc. fs module can be installed using the below statement:
Syntax:
npm install fs --save
Note: The npm in the above command stands for node package manager from where all the dependencies can be installed in NodeJS.
For using the fs module, append the following statement in the code:
const fs = require('fs');
fs module has different operations for file handling such as read files, write files, append files, close files, delete files, etc. All the operations can be performed in a synchronous as well as in an asynchronous approach depending on the user requirements.
1. Synchronous methods: Synchronous functions block the execution of the program until the file operation is performed. These functions are also called blocking functions. The synchronous methods have File Descriptor as the last argument. File Descriptor is a reference to opened files. It is a number or a reference id to the file returned after opening the file using fs.open() method of the fs module. All asynchronous methods can perform synchronously just by appending “Sync” to the function name. Some of the synchronous methods of fs module in NodeJS are:
fs.readFileSync()
fs.renameSync()
fs.writeSync()
fs.writeFileSync()
fs.fsyncSync()
fs.appendFileSync()
fs.statSync()
fs.readdirSync()
fs.existsSync()
Example 1: Synchronous read method
Step 1: Let’s create a JavaScript file named main.js and a text file with the name sample.txt having the following statement:
GeeksForGeeks is a Computer Science portal.
Step 2: Add the following code inside main.js file and execute it:
main.js
var fs = require("fs"); // Synchronous readconsole.log("Synchronous read method:");var data = fs.readFileSync('sample.txt');console.log("Data in the file is - " + data.toString());
Output:
Output of Synchronous Read Method
Example 2: Synchronous append method
Step 1: Let’s create a JavaScript file named main.js and a text file with the name sample.txt having the following statement:
Hello World !
Step 2: Add the following code inside main.js file and execute it:
main.js
var fs = require("fs"); // Synchronous readconsole.log("Synchronous append method:"); var data = "\nGeeksForGeeks is a Computer Science portal."; // Append data to filefs.appendFileSync('sample.txt', data, 'utf8');console.log("Data is appended to file successfully.") data = fs.readFileSync('sample.txt');console.log("Data in the file after appending is - \n" + data.toString());
Output:
Output of Synchronous Append Method
2. Asynchronous methods:
Asynchronous functions do not block the execution of the program and each command is executed after the previous command even if the previous command has not computed the result. The previous command runs in the background and loads the result once it has finished processing. Thus, these functions are called non-blocking functions. They take a callback function as the last parameter. Asynchronous functions are generally preferred over synchronous functions as they do not block the execution of the program whereas synchronous functions block the execution of the program until it has finished processing. Some of the asynchronous methods of fs module in NodeJS are:
fs.readFile()
fs.rename()
fs.write()
fs.writeFile()
fs.fsync()
fs.appendFile()
fs.stat()
fs.readdir()
fs.exists()
Heavy operations which consume time for processing such as querying huge data from a database should be done asynchronously as other operations can still be executed and thus, reducing the time of execution of the program.
Example 1: Asynchronous read method
Step 1: Let’s create a JavaScript file named main.js and a text file with the name sample.txt having the following statement:
GeeksForGeeks is a Computer Science portal.
Step 2: Add the following code inside main.js file and execute it:
main.js
var fs = require("fs"); // Asynchronous readconsole.log("Asynchronous read method:");fs.readFile('sample.txt', function (err, data) { if (err) { return console.error(err); } console.log("Data in the file is - " + data.toString());});
Output:
Output of Asynchronous Read Method
Example 2: Asynchronous append method
Step 1: Let’s create a JavaScript file named main.js and a text file with the name sample.txt having the following statement:
Hello World !
Step 2: Add the following code inside main.js file and execute it:
main.js
var fs = require("fs"); const data = "\nGeeksForGeeks is a Computer Science portal."; // Asynchronously appending data to filefs.appendFile('sample.txt', data, 'utf8', // Callback function function(err) { if (err) throw err; // If no error console.log("Data is appended to file successfully.")}); fs.readFile('sample.txt', function (err, data) { if (err) { return console.error(err); } console.log("Data in the file after appending: \n" + data.toString()); });
Output:
Output of Asynchronous Append Method
Difference between Asynchronous and Synchronous methods:
Synchronous methods
Asynchronous methods
Node.js-fs-module
NodeJS-Questions
Picked
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n31 Aug, 2021"
},
{
"code": null,
"e": 253,
"s": 52,
"text": "NodeJS provides us with an inbuilt fs (File System) module for various file handling operations like read a file, write a file, delete a file etc. fs module can be installed using the below statement:"
},
{
"code": null,
"e": 261,
"s": 253,
"text": "Syntax:"
},
{
"code": null,
"e": 283,
"s": 261,
"text": "npm install fs --save"
},
{
"code": null,
"e": 410,
"s": 283,
"text": "Note: The npm in the above command stands for node package manager from where all the dependencies can be installed in NodeJS."
},
{
"code": null,
"e": 479,
"s": 410,
"text": "For using the fs module, append the following statement in the code:"
},
{
"code": null,
"e": 505,
"s": 479,
"text": "const fs = require('fs');"
},
{
"code": null,
"e": 765,
"s": 505,
"text": "fs module has different operations for file handling such as read files, write files, append files, close files, delete files, etc. All the operations can be performed in a synchronous as well as in an asynchronous approach depending on the user requirements."
},
{
"code": null,
"e": 1328,
"s": 765,
"text": "1. Synchronous methods: Synchronous functions block the execution of the program until the file operation is performed. These functions are also called blocking functions. The synchronous methods have File Descriptor as the last argument. File Descriptor is a reference to opened files. It is a number or a reference id to the file returned after opening the file using fs.open() method of the fs module. All asynchronous methods can perform synchronously just by appending “Sync” to the function name. Some of the synchronous methods of fs module in NodeJS are:"
},
{
"code": null,
"e": 1346,
"s": 1328,
"text": "fs.readFileSync()"
},
{
"code": null,
"e": 1362,
"s": 1346,
"text": "fs.renameSync()"
},
{
"code": null,
"e": 1377,
"s": 1362,
"text": "fs.writeSync()"
},
{
"code": null,
"e": 1396,
"s": 1377,
"text": "fs.writeFileSync()"
},
{
"code": null,
"e": 1411,
"s": 1396,
"text": "fs.fsyncSync()"
},
{
"code": null,
"e": 1431,
"s": 1411,
"text": "fs.appendFileSync()"
},
{
"code": null,
"e": 1445,
"s": 1431,
"text": "fs.statSync()"
},
{
"code": null,
"e": 1462,
"s": 1445,
"text": "fs.readdirSync()"
},
{
"code": null,
"e": 1478,
"s": 1462,
"text": "fs.existsSync()"
},
{
"code": null,
"e": 1513,
"s": 1478,
"text": "Example 1: Synchronous read method"
},
{
"code": null,
"e": 1639,
"s": 1513,
"text": "Step 1: Let’s create a JavaScript file named main.js and a text file with the name sample.txt having the following statement:"
},
{
"code": null,
"e": 1683,
"s": 1639,
"text": "GeeksForGeeks is a Computer Science portal."
},
{
"code": null,
"e": 1750,
"s": 1683,
"text": "Step 2: Add the following code inside main.js file and execute it:"
},
{
"code": null,
"e": 1758,
"s": 1750,
"text": "main.js"
},
{
"code": "var fs = require(\"fs\"); // Synchronous readconsole.log(\"Synchronous read method:\");var data = fs.readFileSync('sample.txt');console.log(\"Data in the file is - \" + data.toString());",
"e": 1940,
"s": 1758,
"text": null
},
{
"code": null,
"e": 1948,
"s": 1940,
"text": "Output:"
},
{
"code": null,
"e": 1982,
"s": 1948,
"text": "Output of Synchronous Read Method"
},
{
"code": null,
"e": 2021,
"s": 1984,
"text": "Example 2: Synchronous append method"
},
{
"code": null,
"e": 2147,
"s": 2021,
"text": "Step 1: Let’s create a JavaScript file named main.js and a text file with the name sample.txt having the following statement:"
},
{
"code": null,
"e": 2161,
"s": 2147,
"text": "Hello World !"
},
{
"code": null,
"e": 2228,
"s": 2161,
"text": "Step 2: Add the following code inside main.js file and execute it:"
},
{
"code": null,
"e": 2236,
"s": 2228,
"text": "main.js"
},
{
"code": "var fs = require(\"fs\"); // Synchronous readconsole.log(\"Synchronous append method:\"); var data = \"\\nGeeksForGeeks is a Computer Science portal.\"; // Append data to filefs.appendFileSync('sample.txt', data, 'utf8');console.log(\"Data is appended to file successfully.\") data = fs.readFileSync('sample.txt');console.log(\"Data in the file after appending is - \\n\" + data.toString());",
"e": 2620,
"s": 2236,
"text": null
},
{
"code": null,
"e": 2628,
"s": 2620,
"text": "Output:"
},
{
"code": null,
"e": 2664,
"s": 2628,
"text": "Output of Synchronous Append Method"
},
{
"code": null,
"e": 2689,
"s": 2664,
"text": "2. Asynchronous methods:"
},
{
"code": null,
"e": 3360,
"s": 2689,
"text": "Asynchronous functions do not block the execution of the program and each command is executed after the previous command even if the previous command has not computed the result. The previous command runs in the background and loads the result once it has finished processing. Thus, these functions are called non-blocking functions. They take a callback function as the last parameter. Asynchronous functions are generally preferred over synchronous functions as they do not block the execution of the program whereas synchronous functions block the execution of the program until it has finished processing. Some of the asynchronous methods of fs module in NodeJS are:"
},
{
"code": null,
"e": 3374,
"s": 3360,
"text": "fs.readFile()"
},
{
"code": null,
"e": 3386,
"s": 3374,
"text": "fs.rename()"
},
{
"code": null,
"e": 3397,
"s": 3386,
"text": "fs.write()"
},
{
"code": null,
"e": 3412,
"s": 3397,
"text": "fs.writeFile()"
},
{
"code": null,
"e": 3423,
"s": 3412,
"text": "fs.fsync()"
},
{
"code": null,
"e": 3439,
"s": 3423,
"text": "fs.appendFile()"
},
{
"code": null,
"e": 3449,
"s": 3439,
"text": "fs.stat()"
},
{
"code": null,
"e": 3462,
"s": 3449,
"text": "fs.readdir()"
},
{
"code": null,
"e": 3474,
"s": 3462,
"text": "fs.exists()"
},
{
"code": null,
"e": 3697,
"s": 3474,
"text": "Heavy operations which consume time for processing such as querying huge data from a database should be done asynchronously as other operations can still be executed and thus, reducing the time of execution of the program."
},
{
"code": null,
"e": 3733,
"s": 3697,
"text": "Example 1: Asynchronous read method"
},
{
"code": null,
"e": 3860,
"s": 3733,
"text": "Step 1: Let’s create a JavaScript file named main.js and a text file with the name sample.txt having the following statement: "
},
{
"code": null,
"e": 3904,
"s": 3860,
"text": "GeeksForGeeks is a Computer Science portal."
},
{
"code": null,
"e": 3971,
"s": 3904,
"text": "Step 2: Add the following code inside main.js file and execute it:"
},
{
"code": null,
"e": 3979,
"s": 3971,
"text": "main.js"
},
{
"code": "var fs = require(\"fs\"); // Asynchronous readconsole.log(\"Asynchronous read method:\");fs.readFile('sample.txt', function (err, data) { if (err) { return console.error(err); } console.log(\"Data in the file is - \" + data.toString());});",
"e": 4227,
"s": 3979,
"text": null
},
{
"code": null,
"e": 4235,
"s": 4227,
"text": "Output:"
},
{
"code": null,
"e": 4270,
"s": 4235,
"text": "Output of Asynchronous Read Method"
},
{
"code": null,
"e": 4308,
"s": 4270,
"text": "Example 2: Asynchronous append method"
},
{
"code": null,
"e": 4434,
"s": 4308,
"text": "Step 1: Let’s create a JavaScript file named main.js and a text file with the name sample.txt having the following statement:"
},
{
"code": null,
"e": 4448,
"s": 4434,
"text": "Hello World !"
},
{
"code": null,
"e": 4515,
"s": 4448,
"text": "Step 2: Add the following code inside main.js file and execute it:"
},
{
"code": null,
"e": 4523,
"s": 4515,
"text": "main.js"
},
{
"code": "var fs = require(\"fs\"); const data = \"\\nGeeksForGeeks is a Computer Science portal.\"; // Asynchronously appending data to filefs.appendFile('sample.txt', data, 'utf8', // Callback function function(err) { if (err) throw err; // If no error console.log(\"Data is appended to file successfully.\")}); fs.readFile('sample.txt', function (err, data) { if (err) { return console.error(err); } console.log(\"Data in the file after appending: \\n\" + data.toString()); });",
"e": 5049,
"s": 4523,
"text": null
},
{
"code": null,
"e": 5057,
"s": 5049,
"text": "Output:"
},
{
"code": null,
"e": 5094,
"s": 5057,
"text": "Output of Asynchronous Append Method"
},
{
"code": null,
"e": 5151,
"s": 5094,
"text": "Difference between Asynchronous and Synchronous methods:"
},
{
"code": null,
"e": 5171,
"s": 5151,
"text": "Synchronous methods"
},
{
"code": null,
"e": 5192,
"s": 5171,
"text": "Asynchronous methods"
},
{
"code": null,
"e": 5210,
"s": 5192,
"text": "Node.js-fs-module"
},
{
"code": null,
"e": 5227,
"s": 5210,
"text": "NodeJS-Questions"
},
{
"code": null,
"e": 5234,
"s": 5227,
"text": "Picked"
},
{
"code": null,
"e": 5242,
"s": 5234,
"text": "Node.js"
},
{
"code": null,
"e": 5259,
"s": 5242,
"text": "Web Technologies"
}
] |
Maximum Bipartite Matching
|
28 Jun, 2022
A matching in a Bipartite Graph is a set of the edges chosen in such a way that no two edges share an endpoint. A maximum matching is a matching of maximum size (maximum number of edges). In a maximum matching, if any edge is added to it, it is no longer a matching. There can be more than one maximum matchings for a given Bipartite Graph.
Why do we care? There are many real world problems that can be formed as Bipartite Matching. For example, consider the following problem:
“There are M job applicants and N jobs. Each applicant has a subset of jobs that he/she is interested in. Each job opening can only accept one applicant and a job applicant can be appointed for only one job. Find an assignment of jobs to applicants in such that as many applicants as possible get jobs.”
We strongly recommend to read the following post first. “Ford-Fulkerson Algorithm for Maximum Flow Problem”Maximum Bipartite Matching and Max Flow Problem :
Maximum Bipartite Matching (MBP) problem can be solved by converting it into a flow network (See this video to know how did we arrive this conclusion). Following are the steps.
1) Build a Flow Network : There must be a source and sink in a flow network. So we add a source and add edges from source to all applicants. Similarly, add edges from all jobs to sink. The capacity of every edge is marked as 1 unit.
2) Find the maximum flow: We use Ford-Fulkerson algorithm to find the maximum flow in the flow network built in step 1. The maximum flow is actually the MBP we are looking for.
How to implement the above approach?
Let us first define input and output forms. Input is in the form of Edmonds matrix which is a 2D array ‘bpGraph[M][N]’ with M rows (for M job applicants) and N columns (for N jobs). The value bpGraph[i][j] is 1 if i’th applicant is interested in j’th job, otherwise 0.
Output is number maximum number of people that can get jobs.
A simple way to implement this is to create a matrix that represents adjacency matrix representation of a directed graph with M+N+2 vertices. Call the fordFulkerson() for the matrix. This implementation requires O((M+N)*(M+N)) extra space.
Extra space can be reduced and code can be simplified using the fact that the graph is bipartite and capacity of every edge is either 0 or 1. The idea is to use DFS traversal to find a job for an applicant (similar to augmenting path in Ford-Fulkerson). We call bpm() for every applicant, bpm() is the DFS based function that tries all possibilities to assign a job to the applicant.
In bpm(), we one by one try all jobs that an applicant ‘u’ is interested in until we find a job, or all jobs are tried without luck. For every job we try, we do following.
If a job is not assigned to anybody, we simply assign it to the applicant and return true. If a job is assigned to somebody else say x, then we recursively check whether x can be assigned some other job. To make sure that x doesn’t get the same job again, we mark the job ‘v’ as seen before we make recursive call for x. If x can get other job, we change the applicant for job ‘v’ and return true. We use an array maxR[0..N-1] that stores the applicants assigned to different jobs.
If bmp() returns true, then it means that there is an augmenting path in flow network and 1 unit of flow is added to the result in maxBPM().
Implementation:
C++
Java
Python3
C#
PHP
Javascript
// A C++ program to find maximal// Bipartite matching.#include <iostream>#include <string.h>using namespace std; // M is number of applicants// and N is number of jobs#define M 6#define N 6 // A DFS based recursive function// that returns true if a matching// for vertex u is possiblebool bpm(bool bpGraph[M][N], int u, bool seen[], int matchR[]){ // Try every job one by one for (int v = 0; v < N; v++) { // If applicant u is interested in // job v and v is not visited if (bpGraph[u][v] && !seen[v]) { // Mark v as visited seen[v] = true; // If job 'v' is not assigned to an // applicant OR previously assigned // applicant for job v (which is matchR[v]) // has an alternate job available. // Since v is marked as visited in // the above line, matchR[v] in the following // recursive call will not get job 'v' again if (matchR[v] < 0 || bpm(bpGraph, matchR[v], seen, matchR)) { matchR[v] = u; return true; } } } return false;} // Returns maximum number// of matching from M to Nint maxBPM(bool bpGraph[M][N]){ // An array to keep track of the // applicants assigned to jobs. // The value of matchR[i] is the // applicant number assigned to job i, // the value -1 indicates nobody is // assigned. int matchR[N]; // Initially all jobs are available memset(matchR, -1, sizeof(matchR)); // Count of jobs assigned to applicants int result = 0; for (int u = 0; u < M; u++) { // Mark all jobs as not seen // for next applicant. bool seen[N]; memset(seen, 0, sizeof(seen)); // Find if the applicant 'u' can get a job if (bpm(bpGraph, u, seen, matchR)) result++; } return result;} // Driver Codeint main(){ // Let us create a bpGraph // shown in the above example bool bpGraph[M][N] = {{0, 1, 1, 0, 0, 0}, {1, 0, 0, 1, 0, 0}, {0, 0, 1, 0, 0, 0}, {0, 0, 1, 1, 0, 0}, {0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 1}}; cout << "Maximum number of applicants that can get job is " << maxBPM(bpGraph); return 0;}
// A Java program to find maximal// Bipartite matching.import java.util.*;import java.lang.*;import java.io.*; class GFG{ // M is number of applicants // and N is number of jobs static final int M = 6; static final int N = 6; // A DFS based recursive function that // returns true if a matching for // vertex u is possible boolean bpm(boolean bpGraph[][], int u, boolean seen[], int matchR[]) { // Try every job one by one for (int v = 0; v < N; v++) { // If applicant u is interested // in job v and v is not visited if (bpGraph[u][v] && !seen[v]) { // Mark v as visited seen[v] = true; // If job 'v' is not assigned to // an applicant OR previously // assigned applicant for job v (which // is matchR[v]) has an alternate job available. // Since v is marked as visited in the // above line, matchR[v] in the following // recursive call will not get job 'v' again if (matchR[v] < 0 || bpm(bpGraph, matchR[v], seen, matchR)) { matchR[v] = u; return true; } } } return false; } // Returns maximum number // of matching from M to N int maxBPM(boolean bpGraph[][]) { // An array to keep track of the // applicants assigned to jobs. // The value of matchR[i] is the // applicant number assigned to job i, // the value -1 indicates nobody is assigned. int matchR[] = new int[N]; // Initially all jobs are available for(int i = 0; i < N; ++i) matchR[i] = -1; // Count of jobs assigned to applicants int result = 0; for (int u = 0; u < M; u++) { // Mark all jobs as not seen // for next applicant. boolean seen[] =new boolean[N] ; for(int i = 0; i < N; ++i) seen[i] = false; // Find if the applicant 'u' can get a job if (bpm(bpGraph, u, seen, matchR)) result++; } return result; } // Driver Code public static void main (String[] args) throws java.lang.Exception { // Let us create a bpGraph shown // in the above example boolean bpGraph[][] = new boolean[][]{ {false, true, true, false, false, false}, {true, false, false, true, false, false}, {false, false, true, false, false, false}, {false, false, true, true, false, false}, {false, false, false, false, false, false}, {false, false, false, false, false, true}}; GFG m = new GFG(); System.out.println( "Maximum number of applicants that can"+ " get job is "+m.maxBPM(bpGraph)); }}
# Python program to find# maximal Bipartite matching. class GFG: def __init__(self,graph): # residual graph self.graph = graph self.ppl = len(graph) self.jobs = len(graph[0]) # A DFS based recursive function # that returns true if a matching # for vertex u is possible def bpm(self, u, matchR, seen): # Try every job one by one for v in range(self.jobs): # If applicant u is interested # in job v and v is not seen if self.graph[u][v] and seen[v] == False: # Mark v as visited seen[v] = True '''If job 'v' is not assigned to an applicant OR previously assigned applicant for job v (which is matchR[v]) has an alternate job available. Since v is marked as visited in the above line, matchR[v] in the following recursive call will not get job 'v' again''' if matchR[v] == -1 or self.bpm(matchR[v], matchR, seen): matchR[v] = u return True return False # Returns maximum number of matching def maxBPM(self): '''An array to keep track of the applicants assigned to jobs. The value of matchR[i] is the applicant number assigned to job i, the value -1 indicates nobody is assigned.''' matchR = [-1] * self.jobs # Count of jobs assigned to applicants result = 0 for i in range(self.ppl): # Mark all jobs as not seen for next applicant. seen = [False] * self.jobs # Find if the applicant 'u' can get a job if self.bpm(i, matchR, seen): result += 1 return result bpGraph =[[0, 1, 1, 0, 0, 0], [1, 0, 0, 1, 0, 0], [0, 0, 1, 0, 0, 0], [0, 0, 1, 1, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 1]] g = GFG(bpGraph) print ("Maximum number of applicants that can get job is %d " % g.maxBPM()) # This code is contributed by Neelam Yadav
// A C# program to find maximal// Bipartite matching.using System; class GFG{ // M is number of applicants // and N is number of jobs static int M = 6; static int N = 6; // A DFS based recursive function // that returns true if a matching // for vertex u is possible bool bpm(bool [,]bpGraph, int u, bool []seen, int []matchR) { // Try every job one by one for (int v = 0; v < N; v++) { // If applicant u is interested // in job v and v is not visited if (bpGraph[u, v] && !seen[v]) { // Mark v as visited seen[v] = true; // If job 'v' is not assigned to // an applicant OR previously assigned // applicant for job v (which is matchR[v]) // has an alternate job available. // Since v is marked as visited in the above // line, matchR[v] in the following recursive // call will not get job 'v' again if (matchR[v] < 0 || bpm(bpGraph, matchR[v], seen, matchR)) { matchR[v] = u; return true; } } } return false; } // Returns maximum number of // matching from M to N int maxBPM(bool [,]bpGraph) { // An array to keep track of the // applicants assigned to jobs. // The value of matchR[i] is the // applicant number assigned to job i, // the value -1 indicates nobody is assigned. int []matchR = new int[N]; // Initially all jobs are available for(int i = 0; i < N; ++i) matchR[i] = -1; // Count of jobs assigned to applicants int result = 0; for (int u = 0; u < M; u++) { // Mark all jobs as not // seen for next applicant. bool []seen = new bool[N] ; for(int i = 0; i < N; ++i) seen[i] = false; // Find if the applicant // 'u' can get a job if (bpm(bpGraph, u, seen, matchR)) result++; } return result; } // Driver Code public static void Main () { // Let us create a bpGraph shown // in the above example bool [,]bpGraph = new bool[,] {{false, true, true, false, false, false}, {true, false, false, true, false, false}, {false, false, true, false, false, false}, {false, false, true, true, false, false}, {false, false, false, false, false, false}, {false, false, false, false, false, true}}; GFG m = new GFG(); Console.Write( "Maximum number of applicants that can"+ " get job is "+m.maxBPM(bpGraph)); }} //This code is contributed by nitin mittal.
<?php// A PHP program to find maximal// Bipartite matching. // M is number of applicants// and N is number of jobs$M = 6;$N = 6; // A DFS based recursive function// that returns true if a matching// for vertex u is possiblefunction bpm($bpGraph, $u, &$seen, &$matchR){ global $N; // Try every job one by one for ($v = 0; $v < $N; $v++) { // If applicant u is interested in // job v and v is not visited if ($bpGraph[$u][$v] && !$seen[$v]) { // Mark v as visited $seen[$v] = true; // If job 'v' is not assigned to an // applicant OR previously assigned // applicant for job v (which is matchR[v]) // has an alternate job available. // Since v is marked as visited in // the above line, matchR[v] in the following // recursive call will not get job 'v' again if ($matchR[$v] < 0 || bpm($bpGraph, $matchR[$v], $seen, $matchR)) { $matchR[$v] = $u; return true; } } } return false;} // Returns maximum number// of matching from M to Nfunction maxBPM($bpGraph){ global $N,$M; // An array to keep track of the // applicants assigned to jobs. // The value of matchR[i] is the // applicant number assigned to job i, // the value -1 indicates nobody is // assigned. $matchR = array_fill(0, $N, -1); // Initially all jobs are available // Count of jobs assigned to applicants $result = 0; for ($u = 0; $u < $M; $u++) { // Mark all jobs as not seen // for next applicant. $seen=array_fill(0, $N, false); // Find if the applicant 'u' can get a job if (bpm($bpGraph, $u, $seen, $matchR)) $result++; } return $result;} // Driver Code // Let us create a bpGraph// shown in the above example$bpGraph = array(array(0, 1, 1, 0, 0, 0), array(1, 0, 0, 1, 0, 0), array(0, 0, 1, 0, 0, 0), array(0, 0, 1, 1, 0, 0), array(0, 0, 0, 0, 0, 0), array(0, 0, 0, 0, 0, 1)); echo "Maximum number of applicants that can get job is ".maxBPM($bpGraph); // This code is contributed by chadan_jnu?>
<script> // A JavaScript program to find maximal // Bipartite matching. // M is number of applicants // and N is number of jobs let M = 6; let N = 6; // A DFS based recursive function that // returns true if a matching for // vertex u is possible function bpm(bpGraph, u, seen, matchR) { // Try every job one by one for (let v = 0; v < N; v++) { // If applicant u is interested // in job v and v is not visited if (bpGraph[u][v] && !seen[v]) { // Mark v as visited seen[v] = true; // If job 'v' is not assigned to // an applicant OR previously // assigned applicant for job v (which // is matchR[v]) has an alternate job available. // Since v is marked as visited in the // above line, matchR[v] in the following // recursive call will not get job 'v' again if (matchR[v] < 0 || bpm(bpGraph, matchR[v], seen, matchR)) { matchR[v] = u; return true; } } } return false; } // Returns maximum number // of matching from M to N function maxBPM(bpGraph) { // An array to keep track of the // applicants assigned to jobs. // The value of matchR[i] is the // applicant number assigned to job i, // the value -1 indicates nobody is assigned. let matchR = new Array(N); // Initially all jobs are available for(let i = 0; i < N; ++i) matchR[i] = -1; // Count of jobs assigned to applicants let result = 0; for (let u = 0; u < M; u++) { // Mark all jobs as not seen // for next applicant. let seen =new Array(N); for(let i = 0; i < N; ++i) seen[i] = false; // Find if the applicant 'u' can get a job if (bpm(bpGraph, u, seen, matchR)) result++; } return result; } // Let us create a bpGraph shown // in the above example let bpGraph = [ [false, true, true, false, false, false], [true, false, false, true, false, false], [false, false, true, false, false, false], [false, false, true, true, false, false], [false, false, false, false, false, false], [false, false, false, false, false, true]]; document.write( "Maximum number of applicants that can"+ " get job is "+ maxBPM(bpGraph)); </script>
Maximum number of applicants that can get job is 5
You may like to see below also: Hopcroft–Karp Algorithm for Maximum Matching | Set 1 (Introduction) Hopcroft–Karp Algorithm for Maximum Matching | Set 2 (Implementation)
nitin mittal
Chandan_Kumar
divyeshrabadiya07
amartyaghoshgfg
hardikkoriintern
sumitgumber28
Graph
Graph
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Dijkstra's shortest path algorithm | Greedy Algo-7
Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2
Detect Cycle in a Directed Graph
Find if there is a path between two vertices in a directed graph
Introduction to Data Structures
What is Data Structure: Types, Classifications and Applications
Bellman–Ford Algorithm | DP-23
Find if there is a path between two vertices in an undirected graph
Minimum number of swaps required to sort an array
Minimum steps to reach target by a Knight | Set 1
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n28 Jun, 2022"
},
{
"code": null,
"e": 394,
"s": 52,
"text": "A matching in a Bipartite Graph is a set of the edges chosen in such a way that no two edges share an endpoint. A maximum matching is a matching of maximum size (maximum number of edges). In a maximum matching, if any edge is added to it, it is no longer a matching. There can be more than one maximum matchings for a given Bipartite Graph. "
},
{
"code": null,
"e": 532,
"s": 394,
"text": "Why do we care? There are many real world problems that can be formed as Bipartite Matching. For example, consider the following problem:"
},
{
"code": null,
"e": 836,
"s": 532,
"text": "“There are M job applicants and N jobs. Each applicant has a subset of jobs that he/she is interested in. Each job opening can only accept one applicant and a job applicant can be appointed for only one job. Find an assignment of jobs to applicants in such that as many applicants as possible get jobs.”"
},
{
"code": null,
"e": 993,
"s": 836,
"text": "We strongly recommend to read the following post first. “Ford-Fulkerson Algorithm for Maximum Flow Problem”Maximum Bipartite Matching and Max Flow Problem :"
},
{
"code": null,
"e": 1171,
"s": 993,
"text": "Maximum Bipartite Matching (MBP) problem can be solved by converting it into a flow network (See this video to know how did we arrive this conclusion). Following are the steps. "
},
{
"code": null,
"e": 1404,
"s": 1171,
"text": "1) Build a Flow Network : There must be a source and sink in a flow network. So we add a source and add edges from source to all applicants. Similarly, add edges from all jobs to sink. The capacity of every edge is marked as 1 unit."
},
{
"code": null,
"e": 1583,
"s": 1406,
"text": "2) Find the maximum flow: We use Ford-Fulkerson algorithm to find the maximum flow in the flow network built in step 1. The maximum flow is actually the MBP we are looking for."
},
{
"code": null,
"e": 1621,
"s": 1583,
"text": "How to implement the above approach? "
},
{
"code": null,
"e": 1891,
"s": 1621,
"text": "Let us first define input and output forms. Input is in the form of Edmonds matrix which is a 2D array ‘bpGraph[M][N]’ with M rows (for M job applicants) and N columns (for N jobs). The value bpGraph[i][j] is 1 if i’th applicant is interested in j’th job, otherwise 0. "
},
{
"code": null,
"e": 1953,
"s": 1891,
"text": "Output is number maximum number of people that can get jobs. "
},
{
"code": null,
"e": 2194,
"s": 1953,
"text": "A simple way to implement this is to create a matrix that represents adjacency matrix representation of a directed graph with M+N+2 vertices. Call the fordFulkerson() for the matrix. This implementation requires O((M+N)*(M+N)) extra space. "
},
{
"code": null,
"e": 2578,
"s": 2194,
"text": "Extra space can be reduced and code can be simplified using the fact that the graph is bipartite and capacity of every edge is either 0 or 1. The idea is to use DFS traversal to find a job for an applicant (similar to augmenting path in Ford-Fulkerson). We call bpm() for every applicant, bpm() is the DFS based function that tries all possibilities to assign a job to the applicant."
},
{
"code": null,
"e": 2751,
"s": 2578,
"text": "In bpm(), we one by one try all jobs that an applicant ‘u’ is interested in until we find a job, or all jobs are tried without luck. For every job we try, we do following. "
},
{
"code": null,
"e": 3233,
"s": 2751,
"text": "If a job is not assigned to anybody, we simply assign it to the applicant and return true. If a job is assigned to somebody else say x, then we recursively check whether x can be assigned some other job. To make sure that x doesn’t get the same job again, we mark the job ‘v’ as seen before we make recursive call for x. If x can get other job, we change the applicant for job ‘v’ and return true. We use an array maxR[0..N-1] that stores the applicants assigned to different jobs."
},
{
"code": null,
"e": 3375,
"s": 3233,
"text": "If bmp() returns true, then it means that there is an augmenting path in flow network and 1 unit of flow is added to the result in maxBPM(). "
},
{
"code": null,
"e": 3391,
"s": 3375,
"text": "Implementation:"
},
{
"code": null,
"e": 3395,
"s": 3391,
"text": "C++"
},
{
"code": null,
"e": 3400,
"s": 3395,
"text": "Java"
},
{
"code": null,
"e": 3408,
"s": 3400,
"text": "Python3"
},
{
"code": null,
"e": 3411,
"s": 3408,
"text": "C#"
},
{
"code": null,
"e": 3415,
"s": 3411,
"text": "PHP"
},
{
"code": null,
"e": 3426,
"s": 3415,
"text": "Javascript"
},
{
"code": "// A C++ program to find maximal// Bipartite matching.#include <iostream>#include <string.h>using namespace std; // M is number of applicants// and N is number of jobs#define M 6#define N 6 // A DFS based recursive function// that returns true if a matching// for vertex u is possiblebool bpm(bool bpGraph[M][N], int u, bool seen[], int matchR[]){ // Try every job one by one for (int v = 0; v < N; v++) { // If applicant u is interested in // job v and v is not visited if (bpGraph[u][v] && !seen[v]) { // Mark v as visited seen[v] = true; // If job 'v' is not assigned to an // applicant OR previously assigned // applicant for job v (which is matchR[v]) // has an alternate job available. // Since v is marked as visited in // the above line, matchR[v] in the following // recursive call will not get job 'v' again if (matchR[v] < 0 || bpm(bpGraph, matchR[v], seen, matchR)) { matchR[v] = u; return true; } } } return false;} // Returns maximum number// of matching from M to Nint maxBPM(bool bpGraph[M][N]){ // An array to keep track of the // applicants assigned to jobs. // The value of matchR[i] is the // applicant number assigned to job i, // the value -1 indicates nobody is // assigned. int matchR[N]; // Initially all jobs are available memset(matchR, -1, sizeof(matchR)); // Count of jobs assigned to applicants int result = 0; for (int u = 0; u < M; u++) { // Mark all jobs as not seen // for next applicant. bool seen[N]; memset(seen, 0, sizeof(seen)); // Find if the applicant 'u' can get a job if (bpm(bpGraph, u, seen, matchR)) result++; } return result;} // Driver Codeint main(){ // Let us create a bpGraph // shown in the above example bool bpGraph[M][N] = {{0, 1, 1, 0, 0, 0}, {1, 0, 0, 1, 0, 0}, {0, 0, 1, 0, 0, 0}, {0, 0, 1, 1, 0, 0}, {0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 1}}; cout << \"Maximum number of applicants that can get job is \" << maxBPM(bpGraph); return 0;}",
"e": 5825,
"s": 3426,
"text": null
},
{
"code": "// A Java program to find maximal// Bipartite matching.import java.util.*;import java.lang.*;import java.io.*; class GFG{ // M is number of applicants // and N is number of jobs static final int M = 6; static final int N = 6; // A DFS based recursive function that // returns true if a matching for // vertex u is possible boolean bpm(boolean bpGraph[][], int u, boolean seen[], int matchR[]) { // Try every job one by one for (int v = 0; v < N; v++) { // If applicant u is interested // in job v and v is not visited if (bpGraph[u][v] && !seen[v]) { // Mark v as visited seen[v] = true; // If job 'v' is not assigned to // an applicant OR previously // assigned applicant for job v (which // is matchR[v]) has an alternate job available. // Since v is marked as visited in the // above line, matchR[v] in the following // recursive call will not get job 'v' again if (matchR[v] < 0 || bpm(bpGraph, matchR[v], seen, matchR)) { matchR[v] = u; return true; } } } return false; } // Returns maximum number // of matching from M to N int maxBPM(boolean bpGraph[][]) { // An array to keep track of the // applicants assigned to jobs. // The value of matchR[i] is the // applicant number assigned to job i, // the value -1 indicates nobody is assigned. int matchR[] = new int[N]; // Initially all jobs are available for(int i = 0; i < N; ++i) matchR[i] = -1; // Count of jobs assigned to applicants int result = 0; for (int u = 0; u < M; u++) { // Mark all jobs as not seen // for next applicant. boolean seen[] =new boolean[N] ; for(int i = 0; i < N; ++i) seen[i] = false; // Find if the applicant 'u' can get a job if (bpm(bpGraph, u, seen, matchR)) result++; } return result; } // Driver Code public static void main (String[] args) throws java.lang.Exception { // Let us create a bpGraph shown // in the above example boolean bpGraph[][] = new boolean[][]{ {false, true, true, false, false, false}, {true, false, false, true, false, false}, {false, false, true, false, false, false}, {false, false, true, true, false, false}, {false, false, false, false, false, false}, {false, false, false, false, false, true}}; GFG m = new GFG(); System.out.println( \"Maximum number of applicants that can\"+ \" get job is \"+m.maxBPM(bpGraph)); }}",
"e": 9142,
"s": 5825,
"text": null
},
{
"code": "# Python program to find# maximal Bipartite matching. class GFG: def __init__(self,graph): # residual graph self.graph = graph self.ppl = len(graph) self.jobs = len(graph[0]) # A DFS based recursive function # that returns true if a matching # for vertex u is possible def bpm(self, u, matchR, seen): # Try every job one by one for v in range(self.jobs): # If applicant u is interested # in job v and v is not seen if self.graph[u][v] and seen[v] == False: # Mark v as visited seen[v] = True '''If job 'v' is not assigned to an applicant OR previously assigned applicant for job v (which is matchR[v]) has an alternate job available. Since v is marked as visited in the above line, matchR[v] in the following recursive call will not get job 'v' again''' if matchR[v] == -1 or self.bpm(matchR[v], matchR, seen): matchR[v] = u return True return False # Returns maximum number of matching def maxBPM(self): '''An array to keep track of the applicants assigned to jobs. The value of matchR[i] is the applicant number assigned to job i, the value -1 indicates nobody is assigned.''' matchR = [-1] * self.jobs # Count of jobs assigned to applicants result = 0 for i in range(self.ppl): # Mark all jobs as not seen for next applicant. seen = [False] * self.jobs # Find if the applicant 'u' can get a job if self.bpm(i, matchR, seen): result += 1 return result bpGraph =[[0, 1, 1, 0, 0, 0], [1, 0, 0, 1, 0, 0], [0, 0, 1, 0, 0, 0], [0, 0, 1, 1, 0, 0], [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 1]] g = GFG(bpGraph) print (\"Maximum number of applicants that can get job is %d \" % g.maxBPM()) # This code is contributed by Neelam Yadav",
"e": 11371,
"s": 9142,
"text": null
},
{
"code": "// A C# program to find maximal// Bipartite matching.using System; class GFG{ // M is number of applicants // and N is number of jobs static int M = 6; static int N = 6; // A DFS based recursive function // that returns true if a matching // for vertex u is possible bool bpm(bool [,]bpGraph, int u, bool []seen, int []matchR) { // Try every job one by one for (int v = 0; v < N; v++) { // If applicant u is interested // in job v and v is not visited if (bpGraph[u, v] && !seen[v]) { // Mark v as visited seen[v] = true; // If job 'v' is not assigned to // an applicant OR previously assigned // applicant for job v (which is matchR[v]) // has an alternate job available. // Since v is marked as visited in the above // line, matchR[v] in the following recursive // call will not get job 'v' again if (matchR[v] < 0 || bpm(bpGraph, matchR[v], seen, matchR)) { matchR[v] = u; return true; } } } return false; } // Returns maximum number of // matching from M to N int maxBPM(bool [,]bpGraph) { // An array to keep track of the // applicants assigned to jobs. // The value of matchR[i] is the // applicant number assigned to job i, // the value -1 indicates nobody is assigned. int []matchR = new int[N]; // Initially all jobs are available for(int i = 0; i < N; ++i) matchR[i] = -1; // Count of jobs assigned to applicants int result = 0; for (int u = 0; u < M; u++) { // Mark all jobs as not // seen for next applicant. bool []seen = new bool[N] ; for(int i = 0; i < N; ++i) seen[i] = false; // Find if the applicant // 'u' can get a job if (bpm(bpGraph, u, seen, matchR)) result++; } return result; } // Driver Code public static void Main () { // Let us create a bpGraph shown // in the above example bool [,]bpGraph = new bool[,] {{false, true, true, false, false, false}, {true, false, false, true, false, false}, {false, false, true, false, false, false}, {false, false, true, true, false, false}, {false, false, false, false, false, false}, {false, false, false, false, false, true}}; GFG m = new GFG(); Console.Write( \"Maximum number of applicants that can\"+ \" get job is \"+m.maxBPM(bpGraph)); }} //This code is contributed by nitin mittal.",
"e": 14535,
"s": 11371,
"text": null
},
{
"code": "<?php// A PHP program to find maximal// Bipartite matching. // M is number of applicants// and N is number of jobs$M = 6;$N = 6; // A DFS based recursive function// that returns true if a matching// for vertex u is possiblefunction bpm($bpGraph, $u, &$seen, &$matchR){ global $N; // Try every job one by one for ($v = 0; $v < $N; $v++) { // If applicant u is interested in // job v and v is not visited if ($bpGraph[$u][$v] && !$seen[$v]) { // Mark v as visited $seen[$v] = true; // If job 'v' is not assigned to an // applicant OR previously assigned // applicant for job v (which is matchR[v]) // has an alternate job available. // Since v is marked as visited in // the above line, matchR[v] in the following // recursive call will not get job 'v' again if ($matchR[$v] < 0 || bpm($bpGraph, $matchR[$v], $seen, $matchR)) { $matchR[$v] = $u; return true; } } } return false;} // Returns maximum number// of matching from M to Nfunction maxBPM($bpGraph){ global $N,$M; // An array to keep track of the // applicants assigned to jobs. // The value of matchR[i] is the // applicant number assigned to job i, // the value -1 indicates nobody is // assigned. $matchR = array_fill(0, $N, -1); // Initially all jobs are available // Count of jobs assigned to applicants $result = 0; for ($u = 0; $u < $M; $u++) { // Mark all jobs as not seen // for next applicant. $seen=array_fill(0, $N, false); // Find if the applicant 'u' can get a job if (bpm($bpGraph, $u, $seen, $matchR)) $result++; } return $result;} // Driver Code // Let us create a bpGraph// shown in the above example$bpGraph = array(array(0, 1, 1, 0, 0, 0), array(1, 0, 0, 1, 0, 0), array(0, 0, 1, 0, 0, 0), array(0, 0, 1, 1, 0, 0), array(0, 0, 0, 0, 0, 0), array(0, 0, 0, 0, 0, 1)); echo \"Maximum number of applicants that can get job is \".maxBPM($bpGraph); // This code is contributed by chadan_jnu?>",
"e": 16847,
"s": 14535,
"text": null
},
{
"code": "<script> // A JavaScript program to find maximal // Bipartite matching. // M is number of applicants // and N is number of jobs let M = 6; let N = 6; // A DFS based recursive function that // returns true if a matching for // vertex u is possible function bpm(bpGraph, u, seen, matchR) { // Try every job one by one for (let v = 0; v < N; v++) { // If applicant u is interested // in job v and v is not visited if (bpGraph[u][v] && !seen[v]) { // Mark v as visited seen[v] = true; // If job 'v' is not assigned to // an applicant OR previously // assigned applicant for job v (which // is matchR[v]) has an alternate job available. // Since v is marked as visited in the // above line, matchR[v] in the following // recursive call will not get job 'v' again if (matchR[v] < 0 || bpm(bpGraph, matchR[v], seen, matchR)) { matchR[v] = u; return true; } } } return false; } // Returns maximum number // of matching from M to N function maxBPM(bpGraph) { // An array to keep track of the // applicants assigned to jobs. // The value of matchR[i] is the // applicant number assigned to job i, // the value -1 indicates nobody is assigned. let matchR = new Array(N); // Initially all jobs are available for(let i = 0; i < N; ++i) matchR[i] = -1; // Count of jobs assigned to applicants let result = 0; for (let u = 0; u < M; u++) { // Mark all jobs as not seen // for next applicant. let seen =new Array(N); for(let i = 0; i < N; ++i) seen[i] = false; // Find if the applicant 'u' can get a job if (bpm(bpGraph, u, seen, matchR)) result++; } return result; } // Let us create a bpGraph shown // in the above example let bpGraph = [ [false, true, true, false, false, false], [true, false, false, true, false, false], [false, false, true, false, false, false], [false, false, true, true, false, false], [false, false, false, false, false, false], [false, false, false, false, false, true]]; document.write( \"Maximum number of applicants that can\"+ \" get job is \"+ maxBPM(bpGraph)); </script>",
"e": 19715,
"s": 16847,
"text": null
},
{
"code": null,
"e": 19766,
"s": 19715,
"text": "Maximum number of applicants that can get job is 5"
},
{
"code": null,
"e": 19936,
"s": 19766,
"text": "You may like to see below also: Hopcroft–Karp Algorithm for Maximum Matching | Set 1 (Introduction) Hopcroft–Karp Algorithm for Maximum Matching | Set 2 (Implementation)"
},
{
"code": null,
"e": 19949,
"s": 19936,
"text": "nitin mittal"
},
{
"code": null,
"e": 19963,
"s": 19949,
"text": "Chandan_Kumar"
},
{
"code": null,
"e": 19981,
"s": 19963,
"text": "divyeshrabadiya07"
},
{
"code": null,
"e": 19997,
"s": 19981,
"text": "amartyaghoshgfg"
},
{
"code": null,
"e": 20014,
"s": 19997,
"text": "hardikkoriintern"
},
{
"code": null,
"e": 20028,
"s": 20014,
"text": "sumitgumber28"
},
{
"code": null,
"e": 20034,
"s": 20028,
"text": "Graph"
},
{
"code": null,
"e": 20040,
"s": 20034,
"text": "Graph"
},
{
"code": null,
"e": 20138,
"s": 20040,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 20189,
"s": 20138,
"text": "Dijkstra's shortest path algorithm | Greedy Algo-7"
},
{
"code": null,
"e": 20247,
"s": 20189,
"text": "Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2"
},
{
"code": null,
"e": 20280,
"s": 20247,
"text": "Detect Cycle in a Directed Graph"
},
{
"code": null,
"e": 20345,
"s": 20280,
"text": "Find if there is a path between two vertices in a directed graph"
},
{
"code": null,
"e": 20377,
"s": 20345,
"text": "Introduction to Data Structures"
},
{
"code": null,
"e": 20441,
"s": 20377,
"text": "What is Data Structure: Types, Classifications and Applications"
},
{
"code": null,
"e": 20472,
"s": 20441,
"text": "Bellman–Ford Algorithm | DP-23"
},
{
"code": null,
"e": 20540,
"s": 20472,
"text": "Find if there is a path between two vertices in an undirected graph"
},
{
"code": null,
"e": 20590,
"s": 20540,
"text": "Minimum number of swaps required to sort an array"
}
] |
Difference between addEventListener and onclick in JavaScript
|
15 Aug, 2021
The addEventListener() and onclick both listen for an event. Both can execute a callback function when a button is clicked. However, they are not the same. In this article, we are going to understand the differences between them.
addEventListener(): The addEventListener() method attaches an event handler to the specified element.
Syntax:
element.addEventListener(event, listener, useCapture);
Parameters:
event: Event can be any valid JavaScript event. Events are used without the “on” prefix like use “click” instead of “onclick” or “mousedown” instead of “onmousedown”.
listener(handler function): It can be a JavaScript function that responds to the event that occurs.
useCapture: (Optional parameter) A Boolean value that specifies whether the event should be executed in the capturing or in the bubbling phase.
Note: The addEventListener() method can have multiple event handlers applied to the same element. It doesn’t overwrite other event handlers.
Example: Below is a JavaScript code to show that multiple events are associated with an element and there is no overwriting.
HTML
<!DOCTYPE html><html> <body> <button id="btn">Click here</button> <h1 id="text1"></h1> <h1 id="text2"></h1> <script> let btn_element = document.getElementById("btn"); btn_element.addEventListener("click", () => { document.getElementById("text1") .innerHTML = "Task 1 is performed"; }) btn_element.addEventListener("click", () => { document.getElementById("text2") .innerHTML = "Task 2 is performed"; }); </script></body> </html>
Output:
onclick: The onclick event attribute works when the user clicks on the button. When the mouse is clicked on the element then the script runs.
Syntax:
In HTML:
<element onclick="myScript">
In JavaScript:
object.onclick = function(){myScript};
The onclick is just a property. Like all object properties, if we write more than one property, it will be overwritten.
Example: Below is a JavaScript code to show that multiple events cannot be associated with an element as there is overwriting
HTML
<!DOCTYPE html><html> <body> <button id="btn">Click here</button> <h1 id="text1"></h1> <h1 id="text2"></h1> <script> let btn_element = document.getElementById("btn"); btn_element.onclick = () => { document.getElementById("text1") .innerHTML = "Task 1 is performed"; }; btn_element.onclick = () => { document.getElementById("text2") .innerHTML = "Task 2 is performed"; }; </script></body> </html>
Output:
Difference between addEventListener and onclick:
addEventListener
onclick
JavaScript-Questions
Difference Between
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
Difference Between Method Overloading and Method Overriding in Java
Similarities and Difference between Java and C++
Difference between Compile-time and Run-time Polymorphism in Java
Difference between Internal and External fragmentation
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
Hide or show elements in HTML using display property
Difference Between PUT and PATCH Request
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n15 Aug, 2021"
},
{
"code": null,
"e": 282,
"s": 52,
"text": "The addEventListener() and onclick both listen for an event. Both can execute a callback function when a button is clicked. However, they are not the same. In this article, we are going to understand the differences between them."
},
{
"code": null,
"e": 384,
"s": 282,
"text": "addEventListener(): The addEventListener() method attaches an event handler to the specified element."
},
{
"code": null,
"e": 392,
"s": 384,
"text": "Syntax:"
},
{
"code": null,
"e": 447,
"s": 392,
"text": "element.addEventListener(event, listener, useCapture);"
},
{
"code": null,
"e": 459,
"s": 447,
"text": "Parameters:"
},
{
"code": null,
"e": 626,
"s": 459,
"text": "event: Event can be any valid JavaScript event. Events are used without the “on” prefix like use “click” instead of “onclick” or “mousedown” instead of “onmousedown”."
},
{
"code": null,
"e": 726,
"s": 626,
"text": "listener(handler function): It can be a JavaScript function that responds to the event that occurs."
},
{
"code": null,
"e": 871,
"s": 726,
"text": "useCapture: (Optional parameter) A Boolean value that specifies whether the event should be executed in the capturing or in the bubbling phase."
},
{
"code": null,
"e": 1013,
"s": 871,
"text": "Note: The addEventListener() method can have multiple event handlers applied to the same element. It doesn’t overwrite other event handlers. "
},
{
"code": null,
"e": 1138,
"s": 1013,
"text": "Example: Below is a JavaScript code to show that multiple events are associated with an element and there is no overwriting."
},
{
"code": null,
"e": 1143,
"s": 1138,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <body> <button id=\"btn\">Click here</button> <h1 id=\"text1\"></h1> <h1 id=\"text2\"></h1> <script> let btn_element = document.getElementById(\"btn\"); btn_element.addEventListener(\"click\", () => { document.getElementById(\"text1\") .innerHTML = \"Task 1 is performed\"; }) btn_element.addEventListener(\"click\", () => { document.getElementById(\"text2\") .innerHTML = \"Task 2 is performed\"; }); </script></body> </html>",
"e": 1682,
"s": 1143,
"text": null
},
{
"code": null,
"e": 1690,
"s": 1682,
"text": "Output:"
},
{
"code": null,
"e": 1832,
"s": 1690,
"text": "onclick: The onclick event attribute works when the user clicks on the button. When the mouse is clicked on the element then the script runs."
},
{
"code": null,
"e": 1840,
"s": 1832,
"text": "Syntax:"
},
{
"code": null,
"e": 1849,
"s": 1840,
"text": "In HTML:"
},
{
"code": null,
"e": 1878,
"s": 1849,
"text": "<element onclick=\"myScript\">"
},
{
"code": null,
"e": 1893,
"s": 1878,
"text": "In JavaScript:"
},
{
"code": null,
"e": 1932,
"s": 1893,
"text": "object.onclick = function(){myScript};"
},
{
"code": null,
"e": 2053,
"s": 1932,
"text": "The onclick is just a property. Like all object properties, if we write more than one property, it will be overwritten. "
},
{
"code": null,
"e": 2179,
"s": 2053,
"text": "Example: Below is a JavaScript code to show that multiple events cannot be associated with an element as there is overwriting"
},
{
"code": null,
"e": 2184,
"s": 2179,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <body> <button id=\"btn\">Click here</button> <h1 id=\"text1\"></h1> <h1 id=\"text2\"></h1> <script> let btn_element = document.getElementById(\"btn\"); btn_element.onclick = () => { document.getElementById(\"text1\") .innerHTML = \"Task 1 is performed\"; }; btn_element.onclick = () => { document.getElementById(\"text2\") .innerHTML = \"Task 2 is performed\"; }; </script></body> </html>",
"e": 2690,
"s": 2184,
"text": null
},
{
"code": null,
"e": 2698,
"s": 2690,
"text": "Output:"
},
{
"code": null,
"e": 2747,
"s": 2698,
"text": "Difference between addEventListener and onclick:"
},
{
"code": null,
"e": 2764,
"s": 2747,
"text": "addEventListener"
},
{
"code": null,
"e": 2772,
"s": 2764,
"text": "onclick"
},
{
"code": null,
"e": 2793,
"s": 2772,
"text": "JavaScript-Questions"
},
{
"code": null,
"e": 2812,
"s": 2793,
"text": "Difference Between"
},
{
"code": null,
"e": 2823,
"s": 2812,
"text": "JavaScript"
},
{
"code": null,
"e": 2840,
"s": 2823,
"text": "Web Technologies"
},
{
"code": null,
"e": 2938,
"s": 2840,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2999,
"s": 2938,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 3067,
"s": 2999,
"text": "Difference Between Method Overloading and Method Overriding in Java"
},
{
"code": null,
"e": 3116,
"s": 3067,
"text": "Similarities and Difference between Java and C++"
},
{
"code": null,
"e": 3182,
"s": 3116,
"text": "Difference between Compile-time and Run-time Polymorphism in Java"
},
{
"code": null,
"e": 3237,
"s": 3182,
"text": "Difference between Internal and External fragmentation"
},
{
"code": null,
"e": 3298,
"s": 3237,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 3370,
"s": 3298,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 3410,
"s": 3370,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 3463,
"s": 3410,
"text": "Hide or show elements in HTML using display property"
}
] |
Spring Boot – Thymeleaf with Example
|
13 Jun, 2022
Thymeleaf is a server-side Java-based template engine for both web and standalone environments, capable of processing HTML, XML, JavaScript, CSS and even plain text. It is more powerful than JPS and responsible for dynamic content rendering on UI. The engine allows a parallel work of the backend and frontend developers on the same view. It can directly access the java object and spring beans and bind them with UI. And it is mostly used with spring MVC when we create any web application. So let’s start with an example to understand how Thymeleaf works with the Spring framework.
Here we are going to perform crud operation on Employee dataset. So for building this we have to add certain dependencies which are listed in bulleted form or also in pom.xml.
Spring Web (Build web, including RESTful, applications using Spring MVC. Uses Apache Tomcat as the default embedded container.)
Spring Data JPA (Persist data in SQL stores with Java Persistence API using Spring Data and Hibernate.)
Spring Boot Devtools (Provides fast application restarts, LiveReload, and configurations for enhanced development experience)
MySQL Driver (MySQL JDBC and R2DBC driver)
Thymeleaf ( server-side Java template engine for both web and standalone environments. Allows HTML to be correctly displayed in browsers and as static prototypes.)
POM.XML
XML
<?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 https:/ /maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.6.2</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>com.example</groupId> <artifactId>thymeleaf</artifactId> <version>0.0.1-SNAPSHOT</version> <name>thymeleaf</name> <description>Demo project for Spring Boot</description> <properties> <java.version>17</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <scope>runtime</scope> <optional>true</optional> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build></project>
application.properties file
spring.jpa.hibernate.ddl-auto=update
spring.datasource.url=jdbc:mysql://localhost:3306/emp
spring.datasource.username=root
spring.datasource.password=root
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQLInnoDBDialect
logging.level.org.hibernate.SQL=DEBUG
logging.level.org.hibernate.type=TRACE
Employee Pojo
This is the simple pojo class which is used to store the data of Employee.
Java
package com.microservice.modal; import javax.persistence.Entity;import javax.persistence.GeneratedValue;import javax.persistence.GenerationType;import javax.persistence.Id; @Entitypublic class Employee { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) private long id; private String name; private String email; public long getId() { return id; } public void setId(long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; }}
Employee Service interface and EmployeeServiceImpl class
Java
package com.microservice.service; import java.util.List; import com.microservice.modal.Employee; public interface EmployeeServices { List<Employee> getAllEmployee(); void save(Employee employee); Employee getById(Long id); void deleteViaId(long id);}
EmployeeServiceImpl class which implements EmployeeSerivce interface methods
Java
package com.microservice.service; import com.microservice.modal.Employee;import com.microservice.repository.EmployeeRepository;import java.util.List;import java.util.Optional;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service; @Servicepublic class EmployeeServiceImpl implements EmployeeServices { @Autowired private EmployeeRepository empRepo; @Override public List<Employee> getAllEmployee() { return empRepo.findAll(); } @Override public void save(Employee employee) { empRepo.save(employee); } @Override public Employee getById(Long id) { Optional<Employee> optional = empRepo.findById(id); Employee employee = null; if (optional.isPresent()) employee = optional.get(); else throw new RuntimeException( "Employee not found for id : " + id); return employee; } @Override public void deleteViaId(long id) { empRepo.deleteById(id); }}
EmployeeRepository Interface
Here we are using JPA for communicating and saving the object into database.
Java
package com.microservice.repository; import org.springframework.data.jpa.repository.JpaRepository;import org.springframework.stereotype.Repository; import com.microservice.modal.Employee; @Repositorypublic interface EmployeeRepository extends JpaRepository<Employee,Long> { }
EmployeeController class
This is the controller class it basically controls the flow of the data. It controls the data flow into model object and updates the view whenever data changes. So here we are mapping our object data with Thymeleaf.
When user type the URL localhost:8080/ on browser than request goes to the viewHomePage() method and in this method we are fetching the list of employee and added it into the modal with key, value pair and return the index.html page. In index.html page the key (allemplist) is identified as a java object and Thymeleaf iterate over the list and generate dynamic content as per the user provided template.
/addNew – when user clicks on Add Employee button than request goes to addNewEmployee() method. And in this method we simply create the empty object of the employee and send it back to newemployee.html so that user can fill the data in this empty object and when user hits on save button than /save mapping runs and get the object of the employee and save that object into database.
/showFormForUpdate/{id} – This mapping is for updating the existing employee data.
/deleteEmployee/{id} – This mapping is for deleting the existing employee data.
Java
package com.microservice.controller; import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Controller;import org.springframework.ui.Model;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.ModelAttribute;import org.springframework.web.bind.annotation.PathVariable;import org.springframework.web.bind.annotation.PostMapping; import com.microservice.modal.Employee;import com.microservice.service.EmployeeServiceImpl; @Controllerpublic class EmployeeController { @Autowired private EmployeeServiceImpl employeeServiceImpl; @GetMapping("/") public String viewHomePage(Model model) { model.addAttribute("allemplist", employeeServiceImpl.getAllEmployee()); return "index"; } @GetMapping("/addnew") public String addNewEmployee(Model model) { Employee employee = new Employee(); model.addAttribute("employee", employee); return "newemployee"; } @PostMapping("/save") public String saveEmployee(@ModelAttribute("employee") Employee employee) { employeeServiceImpl.save(employee); return "redirect:/"; } @GetMapping("/showFormForUpdate/{id}") public String updateForm(@PathVariable(value = "id") long id, Model model) { Employee employee = employeeServiceImpl.getById(id); model.addAttribute("employee", employee); return "update"; } @GetMapping("/deleteEmployee/{id}") public String deleteThroughId(@PathVariable(value = "id") long id) { employeeServiceImpl.deleteViaId(id); return "redirect:/"; }}
index.html
This page is used to displaying the list of employee. Here we are iterating over the allemplist object which is sent by our controller from viewHomePage() method.
HTML
<!DOCTYPE html><html lang="en" xmlns:th="http://www.thymeleaf.org"><head><meta charset="ISO-8859-1"><title>Employee</title><link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous"></head><body><div class="container my-2" align="center"> <h3>Employee List</h3><a th:href="@{/addnew}" class="btn btn-primary btn-sm mb-3" >Add Employee</a> <table style="width:80%" border="1" class = "table table-striped table-responsive-md"> <thead> <tr> <th>Name</th> <th>Email</th> <th>Action</th> </tr> </thead> <tbody> <tr th:each="employee:${allemplist}"> <td th:text="${employee.name}"></td> <td th:text="${employee.email}"></td> <td> <a th:href="@{/showFormForUpdate/{id}(id=${employee.id})}" class="btn btn-primary">Update</a> <a th:href="@{/deleteEmployee/{id}(id=${employee.id})}" class="btn btn-danger">Delete</a> </td> </tr> </tbody></table></div></body></html>
newemployee.html
This page is used to add new employee in the database. Here we simply provide the value in empty fields and click the submit button. Than the data of the employee goes to the saveEmployee() method and save the data into database.
HTML
<!DOCTYPE html><html lang="en" xmlns:th="http://www.thymeleaf.org"><head><meta charset="ISO-8859-1"><title>Employee Management System</title><link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous"></head><body> <div class="container"> <h1>Employee Management System</h1> <hr> <h2>Save Employee</h2> <form action="#" th:action="@{/save}" th:object="${employee}" method="POST"> <input type="text" th:field="*{name}" placeholder="Employee Name" class="form-control mb-4 col-4"> <input type="text" th:field="*{email}" placeholder="Employee Email" class="form-control mb-4 col-4"> <button type="submit" class="btn btn-info col-2">Save Employee</button> </form> <hr> <a th:href="@{/}"> Back to Employee List</a> </div></body></html>
update.html
This page is used to update the data of existing employee.
HTML
<!DOCTYPE html><html lang="en" xmlns:th="http://www.thymeleaf.org"><head><meta charset="ISO-8859-1"><title>Employee Management System</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css"></head><body> <div class="container"> <h1>Employee Management System</h1> <hr> <h2>Update Employee</h2> <form action="#" th:action="@{/save}" th:object="${employee}" method="POST"> <!-- Add hidden form field to handle update --> <input type="hidden" th:field="*{id}" /> <input type="text" th:field="*{Name}" class="form-control mb-4 col-4"> <input type="text" th:field="*{email}" class="form-control mb-4 col-4"> <button type="submit" class="btn btn-info col-2"> Update Employee</button> </form> <hr> <a th:href = "@{/}"> Back to Employee List</a> </div></body></html>
Output:
simmytarika5
surinderdawra388
sumitgumber28
Java-Spring-Boot
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Introduction to Java
Constructors in Java
Exceptions in Java
Generics in Java
Functional Interfaces in Java
Strings in Java
Java Programming Examples
Abstraction in Java
HashSet in Java
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n13 Jun, 2022"
},
{
"code": null,
"e": 637,
"s": 52,
"text": "Thymeleaf is a server-side Java-based template engine for both web and standalone environments, capable of processing HTML, XML, JavaScript, CSS and even plain text. It is more powerful than JPS and responsible for dynamic content rendering on UI. The engine allows a parallel work of the backend and frontend developers on the same view. It can directly access the java object and spring beans and bind them with UI. And it is mostly used with spring MVC when we create any web application. So let’s start with an example to understand how Thymeleaf works with the Spring framework. "
},
{
"code": null,
"e": 814,
"s": 637,
"text": "Here we are going to perform crud operation on Employee dataset. So for building this we have to add certain dependencies which are listed in bulleted form or also in pom.xml. "
},
{
"code": null,
"e": 942,
"s": 814,
"text": "Spring Web (Build web, including RESTful, applications using Spring MVC. Uses Apache Tomcat as the default embedded container.)"
},
{
"code": null,
"e": 1046,
"s": 942,
"text": "Spring Data JPA (Persist data in SQL stores with Java Persistence API using Spring Data and Hibernate.)"
},
{
"code": null,
"e": 1172,
"s": 1046,
"text": "Spring Boot Devtools (Provides fast application restarts, LiveReload, and configurations for enhanced development experience)"
},
{
"code": null,
"e": 1215,
"s": 1172,
"text": "MySQL Driver (MySQL JDBC and R2DBC driver)"
},
{
"code": null,
"e": 1379,
"s": 1215,
"text": "Thymeleaf ( server-side Java template engine for both web and standalone environments. Allows HTML to be correctly displayed in browsers and as static prototypes.)"
},
{
"code": null,
"e": 1387,
"s": 1379,
"text": "POM.XML"
},
{
"code": null,
"e": 1391,
"s": 1387,
"text": "XML"
},
{
"code": "<?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 https:/ /maven.apache.org/xsd/maven-4.0.0.xsd\"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.6.2</version> <relativePath/> <!-- lookup parent from repository --> </parent> <groupId>com.example</groupId> <artifactId>thymeleaf</artifactId> <version>0.0.1-SNAPSHOT</version> <name>thymeleaf</name> <description>Demo project for Spring Boot</description> <properties> <java.version>17</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <scope>runtime</scope> <optional>true</optional> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build></project>",
"e": 3534,
"s": 1391,
"text": null
},
{
"code": null,
"e": 3562,
"s": 3534,
"text": "application.properties file"
},
{
"code": null,
"e": 3875,
"s": 3562,
"text": "spring.jpa.hibernate.ddl-auto=update\nspring.datasource.url=jdbc:mysql://localhost:3306/emp\nspring.datasource.username=root\nspring.datasource.password=root\nspring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQLInnoDBDialect\nlogging.level.org.hibernate.SQL=DEBUG\nlogging.level.org.hibernate.type=TRACE"
},
{
"code": null,
"e": 3889,
"s": 3875,
"text": "Employee Pojo"
},
{
"code": null,
"e": 3965,
"s": 3889,
"text": "This is the simple pojo class which is used to store the data of Employee. "
},
{
"code": null,
"e": 3970,
"s": 3965,
"text": "Java"
},
{
"code": "package com.microservice.modal; import javax.persistence.Entity;import javax.persistence.GeneratedValue;import javax.persistence.GenerationType;import javax.persistence.Id; @Entitypublic class Employee { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) private long id; private String name; private String email; public long getId() { return id; } public void setId(long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; }}",
"e": 4665,
"s": 3970,
"text": null
},
{
"code": null,
"e": 4722,
"s": 4665,
"text": "Employee Service interface and EmployeeServiceImpl class"
},
{
"code": null,
"e": 4727,
"s": 4722,
"text": "Java"
},
{
"code": "package com.microservice.service; import java.util.List; import com.microservice.modal.Employee; public interface EmployeeServices { List<Employee> getAllEmployee(); void save(Employee employee); Employee getById(Long id); void deleteViaId(long id);}",
"e": 4990,
"s": 4727,
"text": null
},
{
"code": null,
"e": 5067,
"s": 4990,
"text": "EmployeeServiceImpl class which implements EmployeeSerivce interface methods"
},
{
"code": null,
"e": 5072,
"s": 5067,
"text": "Java"
},
{
"code": "package com.microservice.service; import com.microservice.modal.Employee;import com.microservice.repository.EmployeeRepository;import java.util.List;import java.util.Optional;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service; @Servicepublic class EmployeeServiceImpl implements EmployeeServices { @Autowired private EmployeeRepository empRepo; @Override public List<Employee> getAllEmployee() { return empRepo.findAll(); } @Override public void save(Employee employee) { empRepo.save(employee); } @Override public Employee getById(Long id) { Optional<Employee> optional = empRepo.findById(id); Employee employee = null; if (optional.isPresent()) employee = optional.get(); else throw new RuntimeException( \"Employee not found for id : \" + id); return employee; } @Override public void deleteViaId(long id) { empRepo.deleteById(id); }}",
"e": 6107,
"s": 5072,
"text": null
},
{
"code": null,
"e": 6136,
"s": 6107,
"text": "EmployeeRepository Interface"
},
{
"code": null,
"e": 6213,
"s": 6136,
"text": "Here we are using JPA for communicating and saving the object into database."
},
{
"code": null,
"e": 6218,
"s": 6213,
"text": "Java"
},
{
"code": "package com.microservice.repository; import org.springframework.data.jpa.repository.JpaRepository;import org.springframework.stereotype.Repository; import com.microservice.modal.Employee; @Repositorypublic interface EmployeeRepository extends JpaRepository<Employee,Long> { }",
"e": 6494,
"s": 6218,
"text": null
},
{
"code": null,
"e": 6519,
"s": 6494,
"text": "EmployeeController class"
},
{
"code": null,
"e": 6736,
"s": 6519,
"text": "This is the controller class it basically controls the flow of the data. It controls the data flow into model object and updates the view whenever data changes. So here we are mapping our object data with Thymeleaf. "
},
{
"code": null,
"e": 7141,
"s": 6736,
"text": "When user type the URL localhost:8080/ on browser than request goes to the viewHomePage() method and in this method we are fetching the list of employee and added it into the modal with key, value pair and return the index.html page. In index.html page the key (allemplist) is identified as a java object and Thymeleaf iterate over the list and generate dynamic content as per the user provided template."
},
{
"code": null,
"e": 7525,
"s": 7141,
"text": "/addNew – when user clicks on Add Employee button than request goes to addNewEmployee() method. And in this method we simply create the empty object of the employee and send it back to newemployee.html so that user can fill the data in this empty object and when user hits on save button than /save mapping runs and get the object of the employee and save that object into database."
},
{
"code": null,
"e": 7608,
"s": 7525,
"text": "/showFormForUpdate/{id} – This mapping is for updating the existing employee data."
},
{
"code": null,
"e": 7688,
"s": 7608,
"text": "/deleteEmployee/{id} – This mapping is for deleting the existing employee data."
},
{
"code": null,
"e": 7693,
"s": 7688,
"text": "Java"
},
{
"code": "package com.microservice.controller; import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Controller;import org.springframework.ui.Model;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.ModelAttribute;import org.springframework.web.bind.annotation.PathVariable;import org.springframework.web.bind.annotation.PostMapping; import com.microservice.modal.Employee;import com.microservice.service.EmployeeServiceImpl; @Controllerpublic class EmployeeController { @Autowired private EmployeeServiceImpl employeeServiceImpl; @GetMapping(\"/\") public String viewHomePage(Model model) { model.addAttribute(\"allemplist\", employeeServiceImpl.getAllEmployee()); return \"index\"; } @GetMapping(\"/addnew\") public String addNewEmployee(Model model) { Employee employee = new Employee(); model.addAttribute(\"employee\", employee); return \"newemployee\"; } @PostMapping(\"/save\") public String saveEmployee(@ModelAttribute(\"employee\") Employee employee) { employeeServiceImpl.save(employee); return \"redirect:/\"; } @GetMapping(\"/showFormForUpdate/{id}\") public String updateForm(@PathVariable(value = \"id\") long id, Model model) { Employee employee = employeeServiceImpl.getById(id); model.addAttribute(\"employee\", employee); return \"update\"; } @GetMapping(\"/deleteEmployee/{id}\") public String deleteThroughId(@PathVariable(value = \"id\") long id) { employeeServiceImpl.deleteViaId(id); return \"redirect:/\"; }}",
"e": 9327,
"s": 7693,
"text": null
},
{
"code": null,
"e": 9338,
"s": 9327,
"text": "index.html"
},
{
"code": null,
"e": 9502,
"s": 9338,
"text": "This page is used to displaying the list of employee. Here we are iterating over the allemplist object which is sent by our controller from viewHomePage() method. "
},
{
"code": null,
"e": 9507,
"s": 9502,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html lang=\"en\" xmlns:th=\"http://www.thymeleaf.org\"><head><meta charset=\"ISO-8859-1\"><title>Employee</title><link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css\" integrity=\"sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO\" crossorigin=\"anonymous\"></head><body><div class=\"container my-2\" align=\"center\"> <h3>Employee List</h3><a th:href=\"@{/addnew}\" class=\"btn btn-primary btn-sm mb-3\" >Add Employee</a> <table style=\"width:80%\" border=\"1\" class = \"table table-striped table-responsive-md\"> <thead> <tr> <th>Name</th> <th>Email</th> <th>Action</th> </tr> </thead> <tbody> <tr th:each=\"employee:${allemplist}\"> <td th:text=\"${employee.name}\"></td> <td th:text=\"${employee.email}\"></td> <td> <a th:href=\"@{/showFormForUpdate/{id}(id=${employee.id})}\" class=\"btn btn-primary\">Update</a> <a th:href=\"@{/deleteEmployee/{id}(id=${employee.id})}\" class=\"btn btn-danger\">Delete</a> </td> </tr> </tbody></table></div></body></html>",
"e": 10627,
"s": 9507,
"text": null
},
{
"code": null,
"e": 10644,
"s": 10627,
"text": "newemployee.html"
},
{
"code": null,
"e": 10875,
"s": 10644,
"text": "This page is used to add new employee in the database. Here we simply provide the value in empty fields and click the submit button. Than the data of the employee goes to the saveEmployee() method and save the data into database. "
},
{
"code": null,
"e": 10880,
"s": 10875,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html lang=\"en\" xmlns:th=\"http://www.thymeleaf.org\"><head><meta charset=\"ISO-8859-1\"><title>Employee Management System</title><link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css\" integrity=\"sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO\" crossorigin=\"anonymous\"></head><body> <div class=\"container\"> <h1>Employee Management System</h1> <hr> <h2>Save Employee</h2> <form action=\"#\" th:action=\"@{/save}\" th:object=\"${employee}\" method=\"POST\"> <input type=\"text\" th:field=\"*{name}\" placeholder=\"Employee Name\" class=\"form-control mb-4 col-4\"> <input type=\"text\" th:field=\"*{email}\" placeholder=\"Employee Email\" class=\"form-control mb-4 col-4\"> <button type=\"submit\" class=\"btn btn-info col-2\">Save Employee</button> </form> <hr> <a th:href=\"@{/}\"> Back to Employee List</a> </div></body></html>",
"e": 11923,
"s": 10880,
"text": null
},
{
"code": null,
"e": 11935,
"s": 11923,
"text": "update.html"
},
{
"code": null,
"e": 11995,
"s": 11935,
"text": "This page is used to update the data of existing employee. "
},
{
"code": null,
"e": 12000,
"s": 11995,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html lang=\"en\" xmlns:th=\"http://www.thymeleaf.org\"><head><meta charset=\"ISO-8859-1\"><title>Employee Management System</title> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css\"></head><body> <div class=\"container\"> <h1>Employee Management System</h1> <hr> <h2>Update Employee</h2> <form action=\"#\" th:action=\"@{/save}\" th:object=\"${employee}\" method=\"POST\"> <!-- Add hidden form field to handle update --> <input type=\"hidden\" th:field=\"*{id}\" /> <input type=\"text\" th:field=\"*{Name}\" class=\"form-control mb-4 col-4\"> <input type=\"text\" th:field=\"*{email}\" class=\"form-control mb-4 col-4\"> <button type=\"submit\" class=\"btn btn-info col-2\"> Update Employee</button> </form> <hr> <a th:href = \"@{/}\"> Back to Employee List</a> </div></body></html>",
"e": 13041,
"s": 12000,
"text": null
},
{
"code": null,
"e": 13049,
"s": 13041,
"text": "Output:"
},
{
"code": null,
"e": 13062,
"s": 13049,
"text": "simmytarika5"
},
{
"code": null,
"e": 13079,
"s": 13062,
"text": "surinderdawra388"
},
{
"code": null,
"e": 13093,
"s": 13079,
"text": "sumitgumber28"
},
{
"code": null,
"e": 13110,
"s": 13093,
"text": "Java-Spring-Boot"
},
{
"code": null,
"e": 13115,
"s": 13110,
"text": "Java"
},
{
"code": null,
"e": 13120,
"s": 13115,
"text": "Java"
},
{
"code": null,
"e": 13218,
"s": 13120,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 13233,
"s": 13218,
"text": "Stream In Java"
},
{
"code": null,
"e": 13254,
"s": 13233,
"text": "Introduction to Java"
},
{
"code": null,
"e": 13275,
"s": 13254,
"text": "Constructors in Java"
},
{
"code": null,
"e": 13294,
"s": 13275,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 13311,
"s": 13294,
"text": "Generics in Java"
},
{
"code": null,
"e": 13341,
"s": 13311,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 13357,
"s": 13341,
"text": "Strings in Java"
},
{
"code": null,
"e": 13383,
"s": 13357,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 13403,
"s": 13383,
"text": "Abstraction in Java"
}
] |
Convert a String to Integer Array in C/C++
|
31 Aug, 2020
Given a string str containing numbers separated with “, “. The task is to convert it into an integer array and find the sum of that array.
Examples:
Input : str = "2, 6, 3, 14"
Output : arr[] = {2, 6, 3, 14}
Sum of the array is = 2 + 6 + 3 + 14 = 25
Input : str = "125, 4, 24, 5543, 111"
Output : arr[] = {125, 4, 24, 5543, 111}
Approach:
Create an empty array with size as string length and initialize all of the elements of array to zero.
Start traversing the string.
Check if the character at the current index in the string is a comma(,). If yes then, increment the index of the array to point to the next element of array.
Else, keep traversing the string until a ‘,’ operator is found and keep converting the characters to number and store at the current array element.To convert characters to number:arr[j] = arr[j] * 10 + (Str[i] – 48)
arr[j] = arr[j] * 10 + (Str[i] – 48)
Below is the implementation of the above idea:
// C++ program to convert a string to// integer array#include <bits/stdc++.h>using namespace std; // Function to convert a string to// integer arrayvoid convertStrtoArr(string str){ // get length of string str int str_length = str.length(); // create an array with size as string // length and initialize with 0 int arr[str_length] = { 0 }; int j = 0, i, sum = 0; // Traverse the string for (i = 0; str[i] != '\0'; i++) { // if str[i] is ', ' then split if (str[i] == ',') continue; if (str[i] == ' '){ // Increment j to point to next // array location j++; } else { // subtract str[i] by 48 to convert it to int // Generate number by multiplying 10 and adding // (int)(str[i]) arr[j] = arr[j] * 10 + (str[i] - 48); } } cout << "arr[] = "; for (i = 0; i <= j; i++) { cout << arr[i] << " "; sum += arr[i]; // sum of array } // print sum of array cout << "\nSum of array is = " << sum << endl;} // Driver codeint main(){ string str = "2, 6, 3, 14"; convertStrtoArr(str); return 0;}
arr[] = 2 6 3 14
Sum of array is = 25
Time Complexity: O(N), where N is the length of the string.
Rudragouda
Akanksha_Rai
number-theory
Traversal
Arrays
Strings
Arrays
number-theory
Strings
Traversal
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n31 Aug, 2020"
},
{
"code": null,
"e": 193,
"s": 54,
"text": "Given a string str containing numbers separated with “, “. The task is to convert it into an integer array and find the sum of that array."
},
{
"code": null,
"e": 203,
"s": 193,
"text": "Examples:"
},
{
"code": null,
"e": 387,
"s": 203,
"text": "Input : str = \"2, 6, 3, 14\"\nOutput : arr[] = {2, 6, 3, 14}\nSum of the array is = 2 + 6 + 3 + 14 = 25\n\nInput : str = \"125, 4, 24, 5543, 111\"\nOutput : arr[] = {125, 4, 24, 5543, 111} \n"
},
{
"code": null,
"e": 397,
"s": 387,
"text": "Approach:"
},
{
"code": null,
"e": 499,
"s": 397,
"text": "Create an empty array with size as string length and initialize all of the elements of array to zero."
},
{
"code": null,
"e": 528,
"s": 499,
"text": "Start traversing the string."
},
{
"code": null,
"e": 686,
"s": 528,
"text": "Check if the character at the current index in the string is a comma(,). If yes then, increment the index of the array to point to the next element of array."
},
{
"code": null,
"e": 902,
"s": 686,
"text": "Else, keep traversing the string until a ‘,’ operator is found and keep converting the characters to number and store at the current array element.To convert characters to number:arr[j] = arr[j] * 10 + (Str[i] – 48)"
},
{
"code": null,
"e": 939,
"s": 902,
"text": "arr[j] = arr[j] * 10 + (Str[i] – 48)"
},
{
"code": null,
"e": 986,
"s": 939,
"text": "Below is the implementation of the above idea:"
},
{
"code": "// C++ program to convert a string to// integer array#include <bits/stdc++.h>using namespace std; // Function to convert a string to// integer arrayvoid convertStrtoArr(string str){ // get length of string str int str_length = str.length(); // create an array with size as string // length and initialize with 0 int arr[str_length] = { 0 }; int j = 0, i, sum = 0; // Traverse the string for (i = 0; str[i] != '\\0'; i++) { // if str[i] is ', ' then split if (str[i] == ',') continue; if (str[i] == ' '){ // Increment j to point to next // array location j++; } else { // subtract str[i] by 48 to convert it to int // Generate number by multiplying 10 and adding // (int)(str[i]) arr[j] = arr[j] * 10 + (str[i] - 48); } } cout << \"arr[] = \"; for (i = 0; i <= j; i++) { cout << arr[i] << \" \"; sum += arr[i]; // sum of array } // print sum of array cout << \"\\nSum of array is = \" << sum << endl;} // Driver codeint main(){ string str = \"2, 6, 3, 14\"; convertStrtoArr(str); return 0;}",
"e": 2182,
"s": 986,
"text": null
},
{
"code": null,
"e": 2222,
"s": 2182,
"text": "arr[] = 2 6 3 14 \nSum of array is = 25\n"
},
{
"code": null,
"e": 2282,
"s": 2222,
"text": "Time Complexity: O(N), where N is the length of the string."
},
{
"code": null,
"e": 2293,
"s": 2282,
"text": "Rudragouda"
},
{
"code": null,
"e": 2306,
"s": 2293,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 2320,
"s": 2306,
"text": "number-theory"
},
{
"code": null,
"e": 2330,
"s": 2320,
"text": "Traversal"
},
{
"code": null,
"e": 2337,
"s": 2330,
"text": "Arrays"
},
{
"code": null,
"e": 2345,
"s": 2337,
"text": "Strings"
},
{
"code": null,
"e": 2352,
"s": 2345,
"text": "Arrays"
},
{
"code": null,
"e": 2366,
"s": 2352,
"text": "number-theory"
},
{
"code": null,
"e": 2374,
"s": 2366,
"text": "Strings"
},
{
"code": null,
"e": 2384,
"s": 2374,
"text": "Traversal"
}
] |
What is entryComponents in angular ngModule ?
|
14 May, 2020
The entryComponent is the component which loads angular by force, that means these components are not referenced in the HTML template. In most of the cases, Angular loads a component when it is explicitly declared in the component template. But this is not the case with entryComponents. The entryComponents are only loaded dynamically and are never referenced in the component template. It refers to the array of components that are not found in HTML, instead are added by the ComponentFactoryResolver.
Firstly, Angular creates a component factory for each of the bootstrap entryComponents by ComponentFactoryResolver class and then, at run-time, it will use the factories to instantiate the components.
abstract class ComponentFactoryResolver {
static NULL: ComponentFactoryResolver
abstract resolveComponentFactory(component: Type): ComponentFactory
}
Types of entry components in Angular:
The bootstrapped root componentRouted component (A component you specify in a route)
The bootstrapped root component
Routed component (A component you specify in a route)
Bootstrapped entryComponent: At the time of application launch or during bootstrap process, the bootstrap component is loaded in DOM (Document Object Model) by Angular.
import { BrowserModule } from '@angular/platform-browser';import { NgModule } from '@angular/core'; import { AppComponent } from './app.component'; @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule ], providers: [], bootstrap: [AppComponent]})export class AppModule { }
The bootstrap component is an entryComponent that provides the entry point to the application. Angular loads AppComponent by default as it is listed in @NgModule.bootstrap.
app.module.ts
Routed entryComponent: This sort of components are declared components and are added as an array inside the declarations section of the app. But, you may need to reference to a component by its class. Router components are not specified explicitly in the HTML of a component but, are registered in routes array. These components are also loaded dynamically and thus Angular needs to know about them.These components are added in two places:
Router
entryComponents
app-routing.module.ts
import { NgModule } from '@angular/core';import { RouterModule, Routes } from '@angular/router';import { ListComponent } from './list/list.component';import { DetailComponent } from './detail/detail.component'; const routes: Routes = [ { path:'', redirectTo:'/contact', pathMatch:'full' }, { path: 'list', component: ListComponent }, { path: 'detail', component: DetailComponent }, { path:'**', redirectTo:'/not-found' }];@NgModule({ imports:[RouterModule.forRoot(routes)], exports:[RouterModule] })export class AppRoutingModule{ }
You don’t need to add the component to entryComponent array explicitly, Angular does that automatically. The compiler adds all the router component to the entryComponent array.
Need of entryComponent Array: Angular only includes those components in the final bundle that has been referenced in the template. This is done to reduce the size of the final package by not including unwanted components. But this would break the final application as all the entryComponents would never be included in the final package (as they have never been referenced). Therefore we need to register these components under entyComponents array fo Angular to include them in the bundle.
AngularJS-Misc
Picked
AngularJS
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Auth Guards in Angular 9/10/11
Routing in Angular 9/10
What is AOT and JIT Compiler in Angular ?
Angular PrimeNG Dropdown Component
How to set focus on input field automatically on page load in AngularJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
Differences between Functional Components and Class Components in React
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n14 May, 2020"
},
{
"code": null,
"e": 532,
"s": 28,
"text": "The entryComponent is the component which loads angular by force, that means these components are not referenced in the HTML template. In most of the cases, Angular loads a component when it is explicitly declared in the component template. But this is not the case with entryComponents. The entryComponents are only loaded dynamically and are never referenced in the component template. It refers to the array of components that are not found in HTML, instead are added by the ComponentFactoryResolver."
},
{
"code": null,
"e": 733,
"s": 532,
"text": "Firstly, Angular creates a component factory for each of the bootstrap entryComponents by ComponentFactoryResolver class and then, at run-time, it will use the factories to instantiate the components."
},
{
"code": null,
"e": 888,
"s": 733,
"text": "abstract class ComponentFactoryResolver {\n static NULL: ComponentFactoryResolver\n abstract resolveComponentFactory(component: Type): ComponentFactory\n}\n"
},
{
"code": null,
"e": 926,
"s": 888,
"text": "Types of entry components in Angular:"
},
{
"code": null,
"e": 1011,
"s": 926,
"text": "The bootstrapped root componentRouted component (A component you specify in a route)"
},
{
"code": null,
"e": 1043,
"s": 1011,
"text": "The bootstrapped root component"
},
{
"code": null,
"e": 1097,
"s": 1043,
"text": "Routed component (A component you specify in a route)"
},
{
"code": null,
"e": 1266,
"s": 1097,
"text": "Bootstrapped entryComponent: At the time of application launch or during bootstrap process, the bootstrap component is loaded in DOM (Document Object Model) by Angular."
},
{
"code": "import { BrowserModule } from '@angular/platform-browser';import { NgModule } from '@angular/core'; import { AppComponent } from './app.component'; @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule ], providers: [], bootstrap: [AppComponent]})export class AppModule { }",
"e": 1569,
"s": 1266,
"text": null
},
{
"code": null,
"e": 1742,
"s": 1569,
"text": "The bootstrap component is an entryComponent that provides the entry point to the application. Angular loads AppComponent by default as it is listed in @NgModule.bootstrap."
},
{
"code": null,
"e": 1756,
"s": 1742,
"text": "app.module.ts"
},
{
"code": null,
"e": 2197,
"s": 1756,
"text": "Routed entryComponent: This sort of components are declared components and are added as an array inside the declarations section of the app. But, you may need to reference to a component by its class. Router components are not specified explicitly in the HTML of a component but, are registered in routes array. These components are also loaded dynamically and thus Angular needs to know about them.These components are added in two places:"
},
{
"code": null,
"e": 2204,
"s": 2197,
"text": "Router"
},
{
"code": null,
"e": 2220,
"s": 2204,
"text": "entryComponents"
},
{
"code": null,
"e": 2242,
"s": 2220,
"text": "app-routing.module.ts"
},
{
"code": "import { NgModule } from '@angular/core';import { RouterModule, Routes } from '@angular/router';import { ListComponent } from './list/list.component';import { DetailComponent } from './detail/detail.component'; const routes: Routes = [ { path:'', redirectTo:'/contact', pathMatch:'full' }, { path: 'list', component: ListComponent }, { path: 'detail', component: DetailComponent }, { path:'**', redirectTo:'/not-found' }];@NgModule({ imports:[RouterModule.forRoot(routes)], exports:[RouterModule] })export class AppRoutingModule{ }",
"e": 2824,
"s": 2242,
"text": null
},
{
"code": null,
"e": 3001,
"s": 2824,
"text": "You don’t need to add the component to entryComponent array explicitly, Angular does that automatically. The compiler adds all the router component to the entryComponent array."
},
{
"code": null,
"e": 3492,
"s": 3001,
"text": "Need of entryComponent Array: Angular only includes those components in the final bundle that has been referenced in the template. This is done to reduce the size of the final package by not including unwanted components. But this would break the final application as all the entryComponents would never be included in the final package (as they have never been referenced). Therefore we need to register these components under entyComponents array fo Angular to include them in the bundle."
},
{
"code": null,
"e": 3507,
"s": 3492,
"text": "AngularJS-Misc"
},
{
"code": null,
"e": 3514,
"s": 3507,
"text": "Picked"
},
{
"code": null,
"e": 3524,
"s": 3514,
"text": "AngularJS"
},
{
"code": null,
"e": 3541,
"s": 3524,
"text": "Web Technologies"
},
{
"code": null,
"e": 3568,
"s": 3541,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 3666,
"s": 3568,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3697,
"s": 3666,
"text": "Auth Guards in Angular 9/10/11"
},
{
"code": null,
"e": 3721,
"s": 3697,
"text": "Routing in Angular 9/10"
},
{
"code": null,
"e": 3763,
"s": 3721,
"text": "What is AOT and JIT Compiler in Angular ?"
},
{
"code": null,
"e": 3798,
"s": 3763,
"text": "Angular PrimeNG Dropdown Component"
},
{
"code": null,
"e": 3872,
"s": 3798,
"text": "How to set focus on input field automatically on page load in AngularJS ?"
},
{
"code": null,
"e": 3934,
"s": 3872,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 3995,
"s": 3934,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 4045,
"s": 3995,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 4088,
"s": 4045,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
Preorder, Postorder and Inorder Traversal of a Binary Tree using a single Stack
|
18 Jan, 2022
Given a binary tree, the task is to print all the nodes of the binary tree in Pre-order, Post-order, and In-order iteratively using only one stack traversal.
Examples:
Input:
Output:Preorder Traversal: 1 2 3Inorder Traversal: 2 1 3Postorder Traversal: 2 3 1
Input:
Output:Preorder traversal: 1 2 4 5 3 6 7Inorder traversal: 4 2 5 1 6 3 7Post-order traversal: 4 5 2 6 7 3 1
Approach: The problem can be solved using only one stack. The idea is to mark each node of the binary tree by assigning a value, called status code with each node such that value 1 represents that the node is currently visiting in preorder traversal, value 2 represents the nodes is currently visiting in inorder traversal and value 3 represents the node is visiting in the postorder traversal.
Initialize a stack < pair < Node*, int>> say S.
Push the root node in the stack with status as 1, i.e {root, 1}.
Initialize three vectors of integers say preorder, inorder, and postorder.
Traverse the stack until the stack is empty and check for the following conditions:If the status of the top node of the stack is 1 then update the status of the top node of the stack to 2 and push the top node in the vector preorder and insert the left child of the top node if it is not NULL in the stack S.If the status of the top node of the stack is 2 then update the status of the top node of the stack to 3 and push the top node in the vector inorder and insert the right child of the top node if it is not NULL in the stack S.If the status of the top node of the stack is 3 then push the top node in vector postorder and then pop the top element.
If the status of the top node of the stack is 1 then update the status of the top node of the stack to 2 and push the top node in the vector preorder and insert the left child of the top node if it is not NULL in the stack S.
If the status of the top node of the stack is 2 then update the status of the top node of the stack to 3 and push the top node in the vector inorder and insert the right child of the top node if it is not NULL in the stack S.
If the status of the top node of the stack is 3 then push the top node in vector postorder and then pop the top element.
Finally, print vectors preorder, inorder, and postorder.
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 the// node of a binary treestruct Node { int data; struct Node *left, *right; Node(int data) { this->data = data; left = right = NULL; }}; // Function to print all nodes of a// binary tree in Preorder, Postorder// and Inorder using only one stackvoid allTraversal(Node* root){ // Stores preorder traversal vector<int> pre; // Stores inorder traversal vector<int> post; // Stores postorder traversal vector<int> in; // Stores the nodes and the order // in which they are currently visited stack<pair<Node*, int> > s; // Push root node of the tree // into the stack s.push(make_pair(root, 1)); // Traverse the stack while // the stack is not empty while (!s.empty()) { // Stores the top // element of the stack pair<Node*, int> p = s.top(); // If the status of top node // of the stack is 1 if (p.second == 1) { // Update the status // of top node s.top().second++; // Insert the current node // into preorder, pre[] pre.push_back(p.first->data); // If left child is not NULL if (p.first->left) { // Insert the left subtree // with status code 1 s.push(make_pair( p.first->left, 1)); } } // If the status of top node // of the stack is 2 else if (p.second == 2) { // Update the status // of top node s.top().second++; // Insert the current node // in inorder, in[] in.push_back(p.first->data); // If right child is not NULL if (p.first->right) { // Insert the right subtree into // the stack with status code 1 s.push(make_pair( p.first->right, 1)); } } // If the status of top node // of the stack is 3 else { // Push the current node // in post[] post.push_back(p.first->data); // Pop the top node s.pop(); } } cout << "Preorder Traversal: "; for (int i = 0; i < pre.size(); i++) { cout << pre[i] << " "; } cout << "\n"; // Printing Inorder cout << "Inorder Traversal: "; for (int i = 0; i < in.size(); i++) { cout << in[i] << " "; } cout << "\n"; // Printing Postorder cout << "Postorder Traversal: "; for (int i = 0; i < post.size(); i++) { cout << post[i] << " "; } cout << "\n";} // Driver Codeint main(){ // Creating the root struct Node* root = new Node(1); root->left = new Node(2); root->right = new Node(3); root->left->left = new Node(4); root->left->right = new Node(5); root->right->left = new Node(6); root->right->right = new Node(7); // Function call allTraversal(root); return 0;}
// Java program for the above approachimport java.util.ArrayList;import java.util.Stack; class GFG{ static class Pair { Node first; int second; public Pair(Node first, int second) { this.first = first; this.second = second; } } // Structure of the // node of a binary tree static class Node { int data; Node left, right; Node(int data) { this.data = data; left = right = null; } }; // Function to print all nodes of a // binary tree in Preorder, Postorder // and Inorder using only one stack static void allTraversal(Node root) { // Stores preorder traversal ArrayList<Integer> pre = new ArrayList<>(); // Stores inorder traversal ArrayList<Integer> in = new ArrayList<>(); // Stores postorder traversal ArrayList<Integer> post = new ArrayList<>(); // Stores the nodes and the order // in which they are currently visited Stack<Pair> s = new Stack<>(); // Push root node of the tree // into the stack s.push(new Pair(root, 1)); // Traverse the stack while // the stack is not empty while (!s.empty()) { // Stores the top // element of the stack Pair p = s.peek(); // If the status of top node // of the stack is 1 if (p.second == 1) { // Update the status // of top node s.peek().second++; // Insert the current node // into preorder, pre[] pre.add(p.first.data); // If left child is not null if (p.first.left != null) { // Insert the left subtree // with status code 1 s.push(new Pair(p.first.left, 1)); } } // If the status of top node // of the stack is 2 else if (p.second == 2) { // Update the status // of top node s.peek().second++; // Insert the current node // in inorder, in[] in.add(p.first.data); // If right child is not null if (p.first.right != null) { // Insert the right subtree into // the stack with status code 1 s.push(new Pair(p.first.right, 1)); } } // If the status of top node // of the stack is 3 else { // Push the current node // in post[] post.add(p.first.data); // Pop the top node s.pop(); } } System.out.print("Preorder Traversal: "); for (int i : pre) { System.out.print(i + " "); } System.out.println(); // Printing Inorder System.out.print("Inorder Traversal: "); for (int i : in) { System.out.print(i + " "); } System.out.println(); // Printing Postorder System.out.print("Postorder Traversal: "); for (int i : post) { System.out.print(i + " "); } System.out.println(); } // Driver Code public static void main(String[] args) { // Creating the root Node root = new Node(1); root.left = new Node(2); root.right = new Node(3); root.left.left = new Node(4); root.left.right = new Node(5); root.right.left = new Node(6); root.right.right = new Node(7); // Function call allTraversal(root); }} // This code is contributed by sanjeev255
# Python3 program for the above approach # Structure of the# node of a binary treeclass Node: def __init__(self, x): self.data = x self.left = None self.right = None # Function to print all nodes of a# binary tree in Preorder, Postorder# and Inorder using only one stackdef allTraversal(root): # Stores preorder traversal pre = [] # Stores inorder traversal post = [] # Stores postorder traversal inn = [] # Stores the nodes and the order # in which they are currently visited s = [] # Push root node of the tree # into the stack s.append([root, 1]) # Traverse the stack while # the stack is not empty while (len(s) > 0): # Stores the top # element of the stack p = s[-1] #del s[-1] # If the status of top node # of the stack is 1 if (p[1] == 1): # Update the status # of top node s[-1][1] += 1 # Insert the current node # into preorder, pre[] pre.append(p[0].data) # If left child is not NULL if (p[0].left): # Insert the left subtree # with status code 1 s.append([p[0].left, 1]) # If the status of top node # of the stack is 2 elif (p[1] == 2): # Update the status # of top node s[-1][1] += 1 # Insert the current node # in inorder, in[] inn.append(p[0].data); # If right child is not NULL if (p[0].right): # Insert the right subtree into # the stack with status code 1 s.append([p[0].right, 1]) # If the status of top node # of the stack is 3 else: # Push the current node # in post[] post.append(p[0].data); # Pop the top node del s[-1] print("Preorder Traversal: ",end=" ") for i in pre: print(i,end=" ") print() # Printing Inorder print("Inorder Traversal: ",end=" ") for i in inn: print(i,end=" ") print() # Printing Postorder print("Postorder Traversal: ",end=" ") for i in post: print(i,end=" ") print() # Driver Codeif __name__ == '__main__': # Creating the root root = Node(1) root.left = Node(2) root.right = Node(3) root.left.left = Node(4) root.left.right = Node(5) root.right.left = Node(6) root.right.right = Node(7) # Function call allTraversal(root) # This code is contributed by mohit kumar 29.
// C# program for the above approachusing System;using System.Collections.Generic;class GFG { // Class containing left and // right child of current // node and key value class Node { public int data; public Node left, right; public Node(int x) { data = x; left = right = null; } } // Function to print all nodes of a // binary tree in Preorder, Postorder // and Inorder using only one stack static void allTraversal(Node root) { // Stores preorder traversal List<int> pre = new List<int>(); // Stores inorder traversal List<int> In = new List<int>(); // Stores postorder traversal List<int> post = new List<int>(); // Stores the nodes and the order // in which they are currently visited Stack<Tuple<Node, int>> s = new Stack<Tuple<Node, int>>(); // Push root node of the tree // into the stack s.Push(new Tuple<Node, int>(root, 1)); // Traverse the stack while // the stack is not empty while (s.Count > 0) { // Stores the top // element of the stack Tuple<Node, int> p = s.Peek(); // If the status of top node // of the stack is 1 if (p.Item2 == 1) { // Update the status // of top node Tuple<Node, int> temp = s.Peek(); temp = new Tuple<Node, int>(temp.Item1, temp.Item2 + 1); s.Pop(); s.Push(temp); // Insert the current node // into preorder, pre[] pre.Add(p.Item1.data); // If left child is not null if (p.Item1.left != null) { // Insert the left subtree // with status code 1 s.Push(new Tuple<Node, int>(p.Item1.left, 1)); } } // If the status of top node // of the stack is 2 else if (p.Item2 == 2) { // Update the status // of top node Tuple<Node, int> temp = s.Peek(); temp = new Tuple<Node, int>(temp.Item1, temp.Item2 + 1); s.Pop(); s.Push(temp); // Insert the current node // in inorder, in[] In.Add(p.Item1.data); // If right child is not null if (p.Item1.right != null) { // Insert the right subtree into // the stack with status code 1 s.Push(new Tuple<Node, int>(p.Item1.right, 1)); } } // If the status of top node // of the stack is 3 else { // Push the current node // in post[] post.Add(p.Item1.data); // Pop the top node s.Pop(); } } Console.Write("Preorder Traversal: "); foreach(int i in pre) { Console.Write(i + " "); } Console.WriteLine(); // Printing Inorder Console.Write("Inorder Traversal: "); foreach(int i in In) { Console.Write(i + " "); } Console.WriteLine(); // Printing Postorder Console.Write("Postorder Traversal: "); foreach(int i in post) { Console.Write(i + " "); } Console.WriteLine(); } static void Main() { // Creating the root Node root = new Node(1); root.left = new Node(2); root.right = new Node(3); root.left.left = new Node(4); root.left.right = new Node(5); root.right.left = new Node(6); root.right.right = new Node(7); // Function call allTraversal(root); }} // This code is contributed by suresh07.
<script> // Javascript program for the above approachclass Pair{ constructor(first, second) { this.first = first; this.second = second; }} // Structure of the// node of a binary treeclass Node{ constructor(data) { this.data = data; this.left = this.right = null; }} // Function to print all nodes of a// binary tree in Preorder, Postorder// and Inorder using only one stackfunction allTraversal(root){ // Stores preorder traversal let pre = []; // Stores inorder traversal let In = []; // Stores postorder traversal let post = []; // Stores the nodes and the order // in which they are currently visited let s = []; // Push root node of the tree // into the stack s.push(new Pair(root, 1)); // Traverse the stack while // the stack is not empty while (s.length != 0) { // Stores the top // element of the stack let p = s[s.length - 1]; // If the status of top node // of the stack is 1 if (p.second == 1) { // Update the status // of top node s[s.length - 1].second++; // Insert the current node // into preorder, pre[] pre.push(p.first.data); // If left child is not null if (p.first.left != null) { // Insert the left subtree // with status code 1 s.push(new Pair(p.first.left, 1)); } } // If the status of top node // of the stack is 2 else if (p.second == 2) { // Update the status // of top node s[s.length - 1].second++; // Insert the current node // in inorder, in[] In.push(p.first.data); // If right child is not null if (p.first.right != null) { // Insert the right subtree into // the stack with status code 1 s.push(new Pair(p.first.right, 1)); } } // If the status of top node // of the stack is 3 else { // Push the current node // in post[] post.push(p.first.data); // Pop the top node s.pop(); } } document.write("Preorder Traversal: "); for(let i = 0; i < pre.length; i++) { document.write(pre[i] + " "); } document.write("<br>"); // Printing Inorder document.write("Inorder Traversal: "); for(let i = 0; i < In.length; i++) { document.write(In[i] + " "); } document.write("<br>"); // Printing Postorder document.write("Postorder Traversal: "); for(let i = 0; i < post.length; i++) { document.write(post[i] + " "); } document.write("<br>");} // Driver Code // Creating the rootlet root = new Node(1);root.left = new Node(2);root.right = new Node(3);root.left.left = new Node(4);root.left.right = new Node(5);root.right.left = new Node(6);root.right.right = new Node(7); // Function callallTraversal(root); // This code is contributed by unknown2108 </script>
Preorder Traversal: 1 2 4 5 3 6 7
Inorder Traversal: 4 2 5 1 6 3 7
Postorder Traversal: 4 5 2 6 7 3 1
Time Complexity: O(N)Auxiliary Space: O(N)
mohit kumar 29
sanjeev2552
unknown2108
suresh07
apurvmundhra
Binary Tree
cpp-stack
Inorder Traversal
PostOrder Traversal
Preorder Traversal
Tree Traversals
Stack
Tree
Stack
Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n18 Jan, 2022"
},
{
"code": null,
"e": 210,
"s": 52,
"text": "Given a binary tree, the task is to print all the nodes of the binary tree in Pre-order, Post-order, and In-order iteratively using only one stack traversal."
},
{
"code": null,
"e": 220,
"s": 210,
"text": "Examples:"
},
{
"code": null,
"e": 227,
"s": 220,
"text": "Input:"
},
{
"code": null,
"e": 310,
"s": 227,
"text": "Output:Preorder Traversal: 1 2 3Inorder Traversal: 2 1 3Postorder Traversal: 2 3 1"
},
{
"code": null,
"e": 317,
"s": 310,
"text": "Input:"
},
{
"code": null,
"e": 425,
"s": 317,
"text": "Output:Preorder traversal: 1 2 4 5 3 6 7Inorder traversal: 4 2 5 1 6 3 7Post-order traversal: 4 5 2 6 7 3 1"
},
{
"code": null,
"e": 820,
"s": 425,
"text": "Approach: The problem can be solved using only one stack. The idea is to mark each node of the binary tree by assigning a value, called status code with each node such that value 1 represents that the node is currently visiting in preorder traversal, value 2 represents the nodes is currently visiting in inorder traversal and value 3 represents the node is visiting in the postorder traversal."
},
{
"code": null,
"e": 868,
"s": 820,
"text": "Initialize a stack < pair < Node*, int>> say S."
},
{
"code": null,
"e": 933,
"s": 868,
"text": "Push the root node in the stack with status as 1, i.e {root, 1}."
},
{
"code": null,
"e": 1008,
"s": 933,
"text": "Initialize three vectors of integers say preorder, inorder, and postorder."
},
{
"code": null,
"e": 1662,
"s": 1008,
"text": "Traverse the stack until the stack is empty and check for the following conditions:If the status of the top node of the stack is 1 then update the status of the top node of the stack to 2 and push the top node in the vector preorder and insert the left child of the top node if it is not NULL in the stack S.If the status of the top node of the stack is 2 then update the status of the top node of the stack to 3 and push the top node in the vector inorder and insert the right child of the top node if it is not NULL in the stack S.If the status of the top node of the stack is 3 then push the top node in vector postorder and then pop the top element."
},
{
"code": null,
"e": 1888,
"s": 1662,
"text": "If the status of the top node of the stack is 1 then update the status of the top node of the stack to 2 and push the top node in the vector preorder and insert the left child of the top node if it is not NULL in the stack S."
},
{
"code": null,
"e": 2114,
"s": 1888,
"text": "If the status of the top node of the stack is 2 then update the status of the top node of the stack to 3 and push the top node in the vector inorder and insert the right child of the top node if it is not NULL in the stack S."
},
{
"code": null,
"e": 2235,
"s": 2114,
"text": "If the status of the top node of the stack is 3 then push the top node in vector postorder and then pop the top element."
},
{
"code": null,
"e": 2292,
"s": 2235,
"text": "Finally, print vectors preorder, inorder, and postorder."
},
{
"code": null,
"e": 2343,
"s": 2292,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 2347,
"s": 2343,
"text": "C++"
},
{
"code": null,
"e": 2352,
"s": 2347,
"text": "Java"
},
{
"code": null,
"e": 2360,
"s": 2352,
"text": "Python3"
},
{
"code": null,
"e": 2363,
"s": 2360,
"text": "C#"
},
{
"code": null,
"e": 2374,
"s": 2363,
"text": "Javascript"
},
{
"code": "// C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Structure of the// node of a binary treestruct Node { int data; struct Node *left, *right; Node(int data) { this->data = data; left = right = NULL; }}; // Function to print all nodes of a// binary tree in Preorder, Postorder// and Inorder using only one stackvoid allTraversal(Node* root){ // Stores preorder traversal vector<int> pre; // Stores inorder traversal vector<int> post; // Stores postorder traversal vector<int> in; // Stores the nodes and the order // in which they are currently visited stack<pair<Node*, int> > s; // Push root node of the tree // into the stack s.push(make_pair(root, 1)); // Traverse the stack while // the stack is not empty while (!s.empty()) { // Stores the top // element of the stack pair<Node*, int> p = s.top(); // If the status of top node // of the stack is 1 if (p.second == 1) { // Update the status // of top node s.top().second++; // Insert the current node // into preorder, pre[] pre.push_back(p.first->data); // If left child is not NULL if (p.first->left) { // Insert the left subtree // with status code 1 s.push(make_pair( p.first->left, 1)); } } // If the status of top node // of the stack is 2 else if (p.second == 2) { // Update the status // of top node s.top().second++; // Insert the current node // in inorder, in[] in.push_back(p.first->data); // If right child is not NULL if (p.first->right) { // Insert the right subtree into // the stack with status code 1 s.push(make_pair( p.first->right, 1)); } } // If the status of top node // of the stack is 3 else { // Push the current node // in post[] post.push_back(p.first->data); // Pop the top node s.pop(); } } cout << \"Preorder Traversal: \"; for (int i = 0; i < pre.size(); i++) { cout << pre[i] << \" \"; } cout << \"\\n\"; // Printing Inorder cout << \"Inorder Traversal: \"; for (int i = 0; i < in.size(); i++) { cout << in[i] << \" \"; } cout << \"\\n\"; // Printing Postorder cout << \"Postorder Traversal: \"; for (int i = 0; i < post.size(); i++) { cout << post[i] << \" \"; } cout << \"\\n\";} // Driver Codeint main(){ // Creating the root struct Node* root = new Node(1); root->left = new Node(2); root->right = new Node(3); root->left->left = new Node(4); root->left->right = new Node(5); root->right->left = new Node(6); root->right->right = new Node(7); // Function call allTraversal(root); return 0;}",
"e": 5457,
"s": 2374,
"text": null
},
{
"code": "// Java program for the above approachimport java.util.ArrayList;import java.util.Stack; class GFG{ static class Pair { Node first; int second; public Pair(Node first, int second) { this.first = first; this.second = second; } } // Structure of the // node of a binary tree static class Node { int data; Node left, right; Node(int data) { this.data = data; left = right = null; } }; // Function to print all nodes of a // binary tree in Preorder, Postorder // and Inorder using only one stack static void allTraversal(Node root) { // Stores preorder traversal ArrayList<Integer> pre = new ArrayList<>(); // Stores inorder traversal ArrayList<Integer> in = new ArrayList<>(); // Stores postorder traversal ArrayList<Integer> post = new ArrayList<>(); // Stores the nodes and the order // in which they are currently visited Stack<Pair> s = new Stack<>(); // Push root node of the tree // into the stack s.push(new Pair(root, 1)); // Traverse the stack while // the stack is not empty while (!s.empty()) { // Stores the top // element of the stack Pair p = s.peek(); // If the status of top node // of the stack is 1 if (p.second == 1) { // Update the status // of top node s.peek().second++; // Insert the current node // into preorder, pre[] pre.add(p.first.data); // If left child is not null if (p.first.left != null) { // Insert the left subtree // with status code 1 s.push(new Pair(p.first.left, 1)); } } // If the status of top node // of the stack is 2 else if (p.second == 2) { // Update the status // of top node s.peek().second++; // Insert the current node // in inorder, in[] in.add(p.first.data); // If right child is not null if (p.first.right != null) { // Insert the right subtree into // the stack with status code 1 s.push(new Pair(p.first.right, 1)); } } // If the status of top node // of the stack is 3 else { // Push the current node // in post[] post.add(p.first.data); // Pop the top node s.pop(); } } System.out.print(\"Preorder Traversal: \"); for (int i : pre) { System.out.print(i + \" \"); } System.out.println(); // Printing Inorder System.out.print(\"Inorder Traversal: \"); for (int i : in) { System.out.print(i + \" \"); } System.out.println(); // Printing Postorder System.out.print(\"Postorder Traversal: \"); for (int i : post) { System.out.print(i + \" \"); } System.out.println(); } // Driver Code public static void main(String[] args) { // Creating the root Node root = new Node(1); root.left = new Node(2); root.right = new Node(3); root.left.left = new Node(4); root.left.right = new Node(5); root.right.left = new Node(6); root.right.right = new Node(7); // Function call allTraversal(root); }} // This code is contributed by sanjeev255",
"e": 9301,
"s": 5457,
"text": null
},
{
"code": "# Python3 program for the above approach # Structure of the# node of a binary treeclass Node: def __init__(self, x): self.data = x self.left = None self.right = None # Function to print all nodes of a# binary tree in Preorder, Postorder# and Inorder using only one stackdef allTraversal(root): # Stores preorder traversal pre = [] # Stores inorder traversal post = [] # Stores postorder traversal inn = [] # Stores the nodes and the order # in which they are currently visited s = [] # Push root node of the tree # into the stack s.append([root, 1]) # Traverse the stack while # the stack is not empty while (len(s) > 0): # Stores the top # element of the stack p = s[-1] #del s[-1] # If the status of top node # of the stack is 1 if (p[1] == 1): # Update the status # of top node s[-1][1] += 1 # Insert the current node # into preorder, pre[] pre.append(p[0].data) # If left child is not NULL if (p[0].left): # Insert the left subtree # with status code 1 s.append([p[0].left, 1]) # If the status of top node # of the stack is 2 elif (p[1] == 2): # Update the status # of top node s[-1][1] += 1 # Insert the current node # in inorder, in[] inn.append(p[0].data); # If right child is not NULL if (p[0].right): # Insert the right subtree into # the stack with status code 1 s.append([p[0].right, 1]) # If the status of top node # of the stack is 3 else: # Push the current node # in post[] post.append(p[0].data); # Pop the top node del s[-1] print(\"Preorder Traversal: \",end=\" \") for i in pre: print(i,end=\" \") print() # Printing Inorder print(\"Inorder Traversal: \",end=\" \") for i in inn: print(i,end=\" \") print() # Printing Postorder print(\"Postorder Traversal: \",end=\" \") for i in post: print(i,end=\" \") print() # Driver Codeif __name__ == '__main__': # Creating the root root = Node(1) root.left = Node(2) root.right = Node(3) root.left.left = Node(4) root.left.right = Node(5) root.right.left = Node(6) root.right.right = Node(7) # Function call allTraversal(root) # This code is contributed by mohit kumar 29.",
"e": 11915,
"s": 9301,
"text": null
},
{
"code": "// C# program for the above approachusing System;using System.Collections.Generic;class GFG { // Class containing left and // right child of current // node and key value class Node { public int data; public Node left, right; public Node(int x) { data = x; left = right = null; } } // Function to print all nodes of a // binary tree in Preorder, Postorder // and Inorder using only one stack static void allTraversal(Node root) { // Stores preorder traversal List<int> pre = new List<int>(); // Stores inorder traversal List<int> In = new List<int>(); // Stores postorder traversal List<int> post = new List<int>(); // Stores the nodes and the order // in which they are currently visited Stack<Tuple<Node, int>> s = new Stack<Tuple<Node, int>>(); // Push root node of the tree // into the stack s.Push(new Tuple<Node, int>(root, 1)); // Traverse the stack while // the stack is not empty while (s.Count > 0) { // Stores the top // element of the stack Tuple<Node, int> p = s.Peek(); // If the status of top node // of the stack is 1 if (p.Item2 == 1) { // Update the status // of top node Tuple<Node, int> temp = s.Peek(); temp = new Tuple<Node, int>(temp.Item1, temp.Item2 + 1); s.Pop(); s.Push(temp); // Insert the current node // into preorder, pre[] pre.Add(p.Item1.data); // If left child is not null if (p.Item1.left != null) { // Insert the left subtree // with status code 1 s.Push(new Tuple<Node, int>(p.Item1.left, 1)); } } // If the status of top node // of the stack is 2 else if (p.Item2 == 2) { // Update the status // of top node Tuple<Node, int> temp = s.Peek(); temp = new Tuple<Node, int>(temp.Item1, temp.Item2 + 1); s.Pop(); s.Push(temp); // Insert the current node // in inorder, in[] In.Add(p.Item1.data); // If right child is not null if (p.Item1.right != null) { // Insert the right subtree into // the stack with status code 1 s.Push(new Tuple<Node, int>(p.Item1.right, 1)); } } // If the status of top node // of the stack is 3 else { // Push the current node // in post[] post.Add(p.Item1.data); // Pop the top node s.Pop(); } } Console.Write(\"Preorder Traversal: \"); foreach(int i in pre) { Console.Write(i + \" \"); } Console.WriteLine(); // Printing Inorder Console.Write(\"Inorder Traversal: \"); foreach(int i in In) { Console.Write(i + \" \"); } Console.WriteLine(); // Printing Postorder Console.Write(\"Postorder Traversal: \"); foreach(int i in post) { Console.Write(i + \" \"); } Console.WriteLine(); } static void Main() { // Creating the root Node root = new Node(1); root.left = new Node(2); root.right = new Node(3); root.left.left = new Node(4); root.left.right = new Node(5); root.right.left = new Node(6); root.right.right = new Node(7); // Function call allTraversal(root); }} // This code is contributed by suresh07.",
"e": 15865,
"s": 11915,
"text": null
},
{
"code": "<script> // Javascript program for the above approachclass Pair{ constructor(first, second) { this.first = first; this.second = second; }} // Structure of the// node of a binary treeclass Node{ constructor(data) { this.data = data; this.left = this.right = null; }} // Function to print all nodes of a// binary tree in Preorder, Postorder// and Inorder using only one stackfunction allTraversal(root){ // Stores preorder traversal let pre = []; // Stores inorder traversal let In = []; // Stores postorder traversal let post = []; // Stores the nodes and the order // in which they are currently visited let s = []; // Push root node of the tree // into the stack s.push(new Pair(root, 1)); // Traverse the stack while // the stack is not empty while (s.length != 0) { // Stores the top // element of the stack let p = s[s.length - 1]; // If the status of top node // of the stack is 1 if (p.second == 1) { // Update the status // of top node s[s.length - 1].second++; // Insert the current node // into preorder, pre[] pre.push(p.first.data); // If left child is not null if (p.first.left != null) { // Insert the left subtree // with status code 1 s.push(new Pair(p.first.left, 1)); } } // If the status of top node // of the stack is 2 else if (p.second == 2) { // Update the status // of top node s[s.length - 1].second++; // Insert the current node // in inorder, in[] In.push(p.first.data); // If right child is not null if (p.first.right != null) { // Insert the right subtree into // the stack with status code 1 s.push(new Pair(p.first.right, 1)); } } // If the status of top node // of the stack is 3 else { // Push the current node // in post[] post.push(p.first.data); // Pop the top node s.pop(); } } document.write(\"Preorder Traversal: \"); for(let i = 0; i < pre.length; i++) { document.write(pre[i] + \" \"); } document.write(\"<br>\"); // Printing Inorder document.write(\"Inorder Traversal: \"); for(let i = 0; i < In.length; i++) { document.write(In[i] + \" \"); } document.write(\"<br>\"); // Printing Postorder document.write(\"Postorder Traversal: \"); for(let i = 0; i < post.length; i++) { document.write(post[i] + \" \"); } document.write(\"<br>\");} // Driver Code // Creating the rootlet root = new Node(1);root.left = new Node(2);root.right = new Node(3);root.left.left = new Node(4);root.left.right = new Node(5);root.right.left = new Node(6);root.right.right = new Node(7); // Function callallTraversal(root); // This code is contributed by unknown2108 </script>",
"e": 19092,
"s": 15865,
"text": null
},
{
"code": null,
"e": 19196,
"s": 19092,
"text": "Preorder Traversal: 1 2 4 5 3 6 7 \nInorder Traversal: 4 2 5 1 6 3 7 \nPostorder Traversal: 4 5 2 6 7 3 1"
},
{
"code": null,
"e": 19241,
"s": 19198,
"text": "Time Complexity: O(N)Auxiliary Space: O(N)"
},
{
"code": null,
"e": 19256,
"s": 19241,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 19268,
"s": 19256,
"text": "sanjeev2552"
},
{
"code": null,
"e": 19280,
"s": 19268,
"text": "unknown2108"
},
{
"code": null,
"e": 19289,
"s": 19280,
"text": "suresh07"
},
{
"code": null,
"e": 19302,
"s": 19289,
"text": "apurvmundhra"
},
{
"code": null,
"e": 19314,
"s": 19302,
"text": "Binary Tree"
},
{
"code": null,
"e": 19324,
"s": 19314,
"text": "cpp-stack"
},
{
"code": null,
"e": 19342,
"s": 19324,
"text": "Inorder Traversal"
},
{
"code": null,
"e": 19362,
"s": 19342,
"text": "PostOrder Traversal"
},
{
"code": null,
"e": 19381,
"s": 19362,
"text": "Preorder Traversal"
},
{
"code": null,
"e": 19397,
"s": 19381,
"text": "Tree Traversals"
},
{
"code": null,
"e": 19403,
"s": 19397,
"text": "Stack"
},
{
"code": null,
"e": 19408,
"s": 19403,
"text": "Tree"
},
{
"code": null,
"e": 19414,
"s": 19408,
"text": "Stack"
},
{
"code": null,
"e": 19419,
"s": 19414,
"text": "Tree"
}
] |
Python – How to Extract all the digits from a String
|
When it is required to extract strings with a digit, a list comprehension and ‘isdigit’ method is used.
Below is a demonstration of the same −
my_string = "python is 12 fun 2 learn"
print("The string is : ")
print(my_string)
my_result = [int(i) for i in my_string.split() if i.isdigit()]
print("The numbers list is :")
print(my_result)
The string is :
python is 12 fun 2 learn
The numbers list is :
[12, 2]
A string is defined and is displayed on the console.
A string is defined and is displayed on the console.
A list comprehension is used to iterate over the string, and every element is checked to see if it is a digit using the ‘isdigit’ function and is converted to an integer.
A list comprehension is used to iterate over the string, and every element is checked to see if it is a digit using the ‘isdigit’ function and is converted to an integer.
These are stored in a list and assigned to a variable.
These are stored in a list and assigned to a variable.
This is the output that is displayed on the console.
This is the output that is displayed on the console.
|
[
{
"code": null,
"e": 1291,
"s": 1187,
"text": "When it is required to extract strings with a digit, a list comprehension and ‘isdigit’ method is used."
},
{
"code": null,
"e": 1330,
"s": 1291,
"text": "Below is a demonstration of the same −"
},
{
"code": null,
"e": 1526,
"s": 1330,
"text": "my_string = \"python is 12 fun 2 learn\"\n\nprint(\"The string is : \")\nprint(my_string)\n\nmy_result = [int(i) for i in my_string.split() if i.isdigit()]\n\nprint(\"The numbers list is :\")\nprint(my_result)"
},
{
"code": null,
"e": 1597,
"s": 1526,
"text": "The string is :\npython is 12 fun 2 learn\nThe numbers list is :\n[12, 2]"
},
{
"code": null,
"e": 1650,
"s": 1597,
"text": "A string is defined and is displayed on the console."
},
{
"code": null,
"e": 1703,
"s": 1650,
"text": "A string is defined and is displayed on the console."
},
{
"code": null,
"e": 1874,
"s": 1703,
"text": "A list comprehension is used to iterate over the string, and every element is checked to see if it is a digit using the ‘isdigit’ function and is converted to an integer."
},
{
"code": null,
"e": 2045,
"s": 1874,
"text": "A list comprehension is used to iterate over the string, and every element is checked to see if it is a digit using the ‘isdigit’ function and is converted to an integer."
},
{
"code": null,
"e": 2100,
"s": 2045,
"text": "These are stored in a list and assigned to a variable."
},
{
"code": null,
"e": 2155,
"s": 2100,
"text": "These are stored in a list and assigned to a variable."
},
{
"code": null,
"e": 2208,
"s": 2155,
"text": "This is the output that is displayed on the console."
},
{
"code": null,
"e": 2261,
"s": 2208,
"text": "This is the output that is displayed on the console."
}
] |
How to display all files in a directory using Node.js ?
|
21 May, 2020
The files present in a directory can be displayed using two approaches in Node.js that are discussed below:
Method 1: Using fs.readdirSync() method: The fs.readdirSync() is a method that is available in the file system module of Node.js. It is used for reading the contents of a directory. It returns an array of file paths, buffers, or fs.Dirent objects.
The returned array of files can be looped through using the forEach() loop and the file names can be displayed from it. This allows one to display all the filenames present in the directory.
The asynchronous variation of the method fs.readdir() can also be used in place of this function that returns a callback with the files instead of the files themselves.
Example:
// Import the filesystem moduleconst fs = require("fs"); let directory_name = "example_dir"; // Function to get current filenames// in directorylet filenames = fs.readdirSync(directory_name); console.log("\nFilenames in directory:");filenames.forEach((file) => { console.log("File:", file);});
Output:
Filenames in directory:
File: file_a.txt
File: file_b.txt
File: file_c.txt
Method 2: Using the fs.opendirSync() method: The fs.opendirSync() method is available in the file system module of Node.js. It can be used to read the contents of a directory. It returns an fs.Dir object that represents the given directory.
The fs.Dir object can be used to access the files in that directory using the readSync() method. This method returns an fs.Dirent object that contains the representation of the directory entry. This object has a name property that can be used to get the file name that this fs.Dirent object refers to. This name can be accessed and displayed to this user. The readSync() method will automatically read the next directory entry and return null when no more entries exist. This can be used to continuously loop through the entries and get all the file names using a while loop.
The asynchronous variation of the method fs.opendir() can also be used in place of this function that returns a callback with the fs.Dir object instead of the object itself.
Example:
// Import the filesystem moduleconst fs = require("fs"); let directory_name = "example_dir"; // Open the directorylet openedDir = fs.opendirSync(directory_name); // Print the pathname of the directoryconsole.log("\nPath of the directory:", openedDir.path); // Get the files present in the directoryconsole.log("Files Present in directory:"); let filesLeft = true;while (filesLeft) { // Read a file as fs.Dirent object let fileDirent = openedDir.readSync(); // If readSync() does not return null // print its filename if (fileDirent != null) console.log("Name:", fileDirent.name); // If the readSync() returns null // stop the loop else filesLeft = false;}
Output:
Path of the directory: example_dir
Files Present in directory:
Name: file_a.txt
Name: file_b.txt
Name: file_c.tx
Node.js-Misc
Picked
Node.js
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to install the previous version of node.js and npm ?
Difference between promise and async await in Node.js
Mongoose | findByIdAndUpdate() Function
JWT Authentication with Node.js
Installation of Node.js on Windows
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
Differences between Functional Components and Class Components in React
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n21 May, 2020"
},
{
"code": null,
"e": 161,
"s": 53,
"text": "The files present in a directory can be displayed using two approaches in Node.js that are discussed below:"
},
{
"code": null,
"e": 409,
"s": 161,
"text": "Method 1: Using fs.readdirSync() method: The fs.readdirSync() is a method that is available in the file system module of Node.js. It is used for reading the contents of a directory. It returns an array of file paths, buffers, or fs.Dirent objects."
},
{
"code": null,
"e": 600,
"s": 409,
"text": "The returned array of files can be looped through using the forEach() loop and the file names can be displayed from it. This allows one to display all the filenames present in the directory."
},
{
"code": null,
"e": 769,
"s": 600,
"text": "The asynchronous variation of the method fs.readdir() can also be used in place of this function that returns a callback with the files instead of the files themselves."
},
{
"code": null,
"e": 778,
"s": 769,
"text": "Example:"
},
{
"code": "// Import the filesystem moduleconst fs = require(\"fs\"); let directory_name = \"example_dir\"; // Function to get current filenames// in directorylet filenames = fs.readdirSync(directory_name); console.log(\"\\nFilenames in directory:\");filenames.forEach((file) => { console.log(\"File:\", file);});",
"e": 1078,
"s": 778,
"text": null
},
{
"code": null,
"e": 1086,
"s": 1078,
"text": "Output:"
},
{
"code": null,
"e": 1162,
"s": 1086,
"text": "Filenames in directory:\nFile: file_a.txt\nFile: file_b.txt\nFile: file_c.txt\n"
},
{
"code": null,
"e": 1403,
"s": 1162,
"text": "Method 2: Using the fs.opendirSync() method: The fs.opendirSync() method is available in the file system module of Node.js. It can be used to read the contents of a directory. It returns an fs.Dir object that represents the given directory."
},
{
"code": null,
"e": 1979,
"s": 1403,
"text": "The fs.Dir object can be used to access the files in that directory using the readSync() method. This method returns an fs.Dirent object that contains the representation of the directory entry. This object has a name property that can be used to get the file name that this fs.Dirent object refers to. This name can be accessed and displayed to this user. The readSync() method will automatically read the next directory entry and return null when no more entries exist. This can be used to continuously loop through the entries and get all the file names using a while loop."
},
{
"code": null,
"e": 2153,
"s": 1979,
"text": "The asynchronous variation of the method fs.opendir() can also be used in place of this function that returns a callback with the fs.Dir object instead of the object itself."
},
{
"code": null,
"e": 2162,
"s": 2153,
"text": "Example:"
},
{
"code": "// Import the filesystem moduleconst fs = require(\"fs\"); let directory_name = \"example_dir\"; // Open the directorylet openedDir = fs.opendirSync(directory_name); // Print the pathname of the directoryconsole.log(\"\\nPath of the directory:\", openedDir.path); // Get the files present in the directoryconsole.log(\"Files Present in directory:\"); let filesLeft = true;while (filesLeft) { // Read a file as fs.Dirent object let fileDirent = openedDir.readSync(); // If readSync() does not return null // print its filename if (fileDirent != null) console.log(\"Name:\", fileDirent.name); // If the readSync() returns null // stop the loop else filesLeft = false;}",
"e": 2838,
"s": 2162,
"text": null
},
{
"code": null,
"e": 2846,
"s": 2838,
"text": "Output:"
},
{
"code": null,
"e": 2960,
"s": 2846,
"text": "Path of the directory: example_dir\nFiles Present in directory:\nName: file_a.txt\nName: file_b.txt\nName: file_c.tx\n"
},
{
"code": null,
"e": 2973,
"s": 2960,
"text": "Node.js-Misc"
},
{
"code": null,
"e": 2980,
"s": 2973,
"text": "Picked"
},
{
"code": null,
"e": 2988,
"s": 2980,
"text": "Node.js"
},
{
"code": null,
"e": 3005,
"s": 2988,
"text": "Web Technologies"
},
{
"code": null,
"e": 3032,
"s": 3005,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 3130,
"s": 3032,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3187,
"s": 3130,
"text": "How to install the previous version of node.js and npm ?"
},
{
"code": null,
"e": 3241,
"s": 3187,
"text": "Difference between promise and async await in Node.js"
},
{
"code": null,
"e": 3281,
"s": 3241,
"text": "Mongoose | findByIdAndUpdate() Function"
},
{
"code": null,
"e": 3313,
"s": 3281,
"text": "JWT Authentication with Node.js"
},
{
"code": null,
"e": 3348,
"s": 3313,
"text": "Installation of Node.js on Windows"
},
{
"code": null,
"e": 3410,
"s": 3348,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 3471,
"s": 3410,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 3521,
"s": 3471,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 3564,
"s": 3521,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
C# | Math.Sqrt() Method
|
08 Nov, 2019
In C#, Math.Sqrt() is a Math class method which is used to calculate the square root of the specified number.Sqrt is a slower computation. It can be cached for a performance boost.Syntax:
public static double Sqrt(double d)
Parameter:
d: Number whose square root is to be calculated and type of this parameter is System.Double.
Return Type: This method returns the square root of d. If d is equal to NaN, NegativeInfinity, or PositiveInfinity, that value is returned. The return type of this method is System.Double.
Examples:
Input : Math.Sqrt(81)
Output : 9
Input : Math.Sqrt(-81)
Output : NaN
Input : Math.Sqrt(0.09)
Output : 0.3
Input : Math.Sqrt(0)
Output : 0
Input : Math.Sqrt(-0)
Output : 0
Below C# programs illustrate the working of Math.Sqrt():
Program 1: When the argument is positive double value then this method returns the square root of a given value.// C# program to illustrate the// Math.Sqrt() methodusing System; class GFG { // Main Method public static void Main() { double x = 81; // Input positive value, Output square root of x Console.Write(Math.Sqrt(x)); }}Output:9
// C# program to illustrate the// Math.Sqrt() methodusing System; class GFG { // Main Method public static void Main() { double x = 81; // Input positive value, Output square root of x Console.Write(Math.Sqrt(x)); }}
9
Program 2: When the argument is Negative, this method will return NaN.// C# program to illustrate the Math.Sqrt() // method when the argument is Negativeusing System; class GFG { // Main method public static void Main() { double x = -81; // Input Negative value, Output square root of x Console.Write(Math.Sqrt(x)); }}Output:NaN
// C# program to illustrate the Math.Sqrt() // method when the argument is Negativeusing System; class GFG { // Main method public static void Main() { double x = -81; // Input Negative value, Output square root of x Console.Write(Math.Sqrt(x)); }}
NaN
Program 3: When the argument is double value with decimal places, then this method will return the square root of a given value.// C# program to illustrate the Math.Sqrt() // method when the argument is double value// with decimal placesusing System; class GFG { // Main Method public static void Main() { double x = 0.09; // Input value with decimal places, // Output square root of x Console.Write(Math.Sqrt(x)); }}Output:0.3
// C# program to illustrate the Math.Sqrt() // method when the argument is double value// with decimal placesusing System; class GFG { // Main Method public static void Main() { double x = 0.09; // Input value with decimal places, // Output square root of x Console.Write(Math.Sqrt(x)); }}
0.3
Program 4: When the argument is positive or negative Zero, then it will return the result as Zero.// C# program to illustrate the Math.Sqrt() // method when the argument is positive // or negative Zerousing System; class GFG { // Main Method public static void Main() { double x = 0; // Input value positive Zero, Output // square root of x Console.WriteLine(Math.Sqrt(x)); double y = -0; // Input value Negative Zero, // Output square root of y Console.Write(Math.Sqrt(y)); }}Output:0
0
// C# program to illustrate the Math.Sqrt() // method when the argument is positive // or negative Zerousing System; class GFG { // Main Method public static void Main() { double x = 0; // Input value positive Zero, Output // square root of x Console.WriteLine(Math.Sqrt(x)); double y = -0; // Input value Negative Zero, // Output square root of y Console.Write(Math.Sqrt(y)); }}
0
0
Note: If the value is too large then its gives the compile time error as error CS1021: Integral constant is too large.
Reference: https://msdn.microsoft.com/en-us/library/system.math.sqrt
Akanksha_Rai
CSharp-Math
CSharp-method
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n08 Nov, 2019"
},
{
"code": null,
"e": 242,
"s": 54,
"text": "In C#, Math.Sqrt() is a Math class method which is used to calculate the square root of the specified number.Sqrt is a slower computation. It can be cached for a performance boost.Syntax:"
},
{
"code": null,
"e": 279,
"s": 242,
"text": "public static double Sqrt(double d)\n"
},
{
"code": null,
"e": 290,
"s": 279,
"text": "Parameter:"
},
{
"code": null,
"e": 383,
"s": 290,
"text": "d: Number whose square root is to be calculated and type of this parameter is System.Double."
},
{
"code": null,
"e": 572,
"s": 383,
"text": "Return Type: This method returns the square root of d. If d is equal to NaN, NegativeInfinity, or PositiveInfinity, that value is returned. The return type of this method is System.Double."
},
{
"code": null,
"e": 582,
"s": 572,
"text": "Examples:"
},
{
"code": null,
"e": 766,
"s": 582,
"text": "Input : Math.Sqrt(81) \nOutput : 9\n\nInput : Math.Sqrt(-81) \nOutput : NaN\n\nInput : Math.Sqrt(0.09) \nOutput : 0.3\n\nInput : Math.Sqrt(0)\nOutput : 0\n\nInput : Math.Sqrt(-0)\nOutput : 0\n"
},
{
"code": null,
"e": 823,
"s": 766,
"text": "Below C# programs illustrate the working of Math.Sqrt():"
},
{
"code": null,
"e": 1199,
"s": 823,
"text": "Program 1: When the argument is positive double value then this method returns the square root of a given value.// C# program to illustrate the// Math.Sqrt() methodusing System; class GFG { // Main Method public static void Main() { double x = 81; // Input positive value, Output square root of x Console.Write(Math.Sqrt(x)); }}Output:9\n"
},
{
"code": "// C# program to illustrate the// Math.Sqrt() methodusing System; class GFG { // Main Method public static void Main() { double x = 81; // Input positive value, Output square root of x Console.Write(Math.Sqrt(x)); }}",
"e": 1454,
"s": 1199,
"text": null
},
{
"code": null,
"e": 1457,
"s": 1454,
"text": "9\n"
},
{
"code": null,
"e": 1825,
"s": 1457,
"text": "Program 2: When the argument is Negative, this method will return NaN.// C# program to illustrate the Math.Sqrt() // method when the argument is Negativeusing System; class GFG { // Main method public static void Main() { double x = -81; // Input Negative value, Output square root of x Console.Write(Math.Sqrt(x)); }}Output:NaN\n"
},
{
"code": "// C# program to illustrate the Math.Sqrt() // method when the argument is Negativeusing System; class GFG { // Main method public static void Main() { double x = -81; // Input Negative value, Output square root of x Console.Write(Math.Sqrt(x)); }}",
"e": 2112,
"s": 1825,
"text": null
},
{
"code": null,
"e": 2117,
"s": 2112,
"text": "NaN\n"
},
{
"code": null,
"e": 2592,
"s": 2117,
"text": "Program 3: When the argument is double value with decimal places, then this method will return the square root of a given value.// C# program to illustrate the Math.Sqrt() // method when the argument is double value// with decimal placesusing System; class GFG { // Main Method public static void Main() { double x = 0.09; // Input value with decimal places, // Output square root of x Console.Write(Math.Sqrt(x)); }}Output:0.3\n"
},
{
"code": "// C# program to illustrate the Math.Sqrt() // method when the argument is double value// with decimal placesusing System; class GFG { // Main Method public static void Main() { double x = 0.09; // Input value with decimal places, // Output square root of x Console.Write(Math.Sqrt(x)); }}",
"e": 2928,
"s": 2592,
"text": null
},
{
"code": null,
"e": 2933,
"s": 2928,
"text": "0.3\n"
},
{
"code": null,
"e": 3497,
"s": 2933,
"text": "Program 4: When the argument is positive or negative Zero, then it will return the result as Zero.// C# program to illustrate the Math.Sqrt() // method when the argument is positive // or negative Zerousing System; class GFG { // Main Method public static void Main() { double x = 0; // Input value positive Zero, Output // square root of x Console.WriteLine(Math.Sqrt(x)); double y = -0; // Input value Negative Zero, // Output square root of y Console.Write(Math.Sqrt(y)); }}Output:0\n0\n"
},
{
"code": "// C# program to illustrate the Math.Sqrt() // method when the argument is positive // or negative Zerousing System; class GFG { // Main Method public static void Main() { double x = 0; // Input value positive Zero, Output // square root of x Console.WriteLine(Math.Sqrt(x)); double y = -0; // Input value Negative Zero, // Output square root of y Console.Write(Math.Sqrt(y)); }}",
"e": 3952,
"s": 3497,
"text": null
},
{
"code": null,
"e": 3957,
"s": 3952,
"text": "0\n0\n"
},
{
"code": null,
"e": 4076,
"s": 3957,
"text": "Note: If the value is too large then its gives the compile time error as error CS1021: Integral constant is too large."
},
{
"code": null,
"e": 4145,
"s": 4076,
"text": "Reference: https://msdn.microsoft.com/en-us/library/system.math.sqrt"
},
{
"code": null,
"e": 4158,
"s": 4145,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 4170,
"s": 4158,
"text": "CSharp-Math"
},
{
"code": null,
"e": 4184,
"s": 4170,
"text": "CSharp-method"
},
{
"code": null,
"e": 4187,
"s": 4184,
"text": "C#"
}
] |
cpp command in Linux with Examples
|
15 May, 2019
cpp is the C language preprocessor, it is automatically used by your C compiler to transform your program before compilation. It is also termed as a macro processor because it is used to give abbreviations for the longer piece of code. It can only be used with C, C++ and Objective-C source code. Using with other programming languages may cause uncertain problems.
Syntax:
cpp [-options] infile outfile
Some Important Options:
-D name : Predefine name as a macro.
-D name=definition : The contents of definition are tokenized and processed as if they are written in program itself.
-U name : Cancel any previous definition of macro.
-undef : Do not predefine any system-specific or GCC-specific macros. The standard predefined macros remain defined.
-I dir : Add the directory dir to the list of directories to be searched for header files.
-Wall : Turns on all optional warnings which are desirable for normal code.
-Wcomments : Warn whenever a comment-start sequence /* appears in a /* comment, or whenever a backslash-newline appears in a // comment.
-Wendif-labels : Warn whenever an #else or an #endif are followed by text.
-w : Suppress all warnings, including those which GNU CPP issues by default.
-M : Instead of outputting the result of preprocessing, output a rule suitable for make describing the dependencies of the main source file.
-MM : Like -M but do not mention header files that are found in system header directories.
-x c
-x c++
-x objective-c
-x assembler-with-cpp : All four above Specify the source language: C, C++, Objective-C, or assembly. This has nothing to do with standards conformance or extensions; it merely selects which base syntax to expect.
Examples: We have created two codes to explain the concept we will refer them as code_a.c and code_b.c.
#include
void main()
{
printf("Hello, World!");
}
code_a.c
#include
void main()
{
printf(out);
}
code_b.c
Using cpp command :It will result into the following output:# 1 "code_a.c"
# 1 ""
# 1 ""
# 1 "/usr/include/stdc-predef.h" 1 3 4
# 1 "" 2
# 1 "code_a.c"
# 1 "/usr/include/stdio.h" 1 3 4
# 27 "/usr/include/stdio.h" 3 4
# 1 "/usr/include/features.h" 1 3 4
# 367 "/usr/include/features.h" 3 4
# 1 "/usr/include/x86_64-linux-gnu/sys/cdefs.h" 1 3 4
# 410 "/usr/include/x86_64-linux-gnu/sys/cdefs.h" 3 4
# 1 "/usr/include/x86_64-linux-gnu/bits/wordsize.h" 1 3 4
# 411 "/usr/include/x86_64-linux-gnu/sys/cdefs.h" 2 3 4
# 368 "/usr/include/features.h" 2 3 4
# 391 "/usr/include/features.h" 3 4
..........
.............
....................
# 2 "code_a.c"
void main()
{
printf("Hello, World!");
}
The output is too large and we actually don’t need it to understand the concept. The thing we understood is that it simply called and replaced the whole piece of code in the header files to the program.
It will result into the following output:
# 1 "code_a.c"
# 1 ""
# 1 ""
# 1 "/usr/include/stdc-predef.h" 1 3 4
# 1 "" 2
# 1 "code_a.c"
# 1 "/usr/include/stdio.h" 1 3 4
# 27 "/usr/include/stdio.h" 3 4
# 1 "/usr/include/features.h" 1 3 4
# 367 "/usr/include/features.h" 3 4
# 1 "/usr/include/x86_64-linux-gnu/sys/cdefs.h" 1 3 4
# 410 "/usr/include/x86_64-linux-gnu/sys/cdefs.h" 3 4
# 1 "/usr/include/x86_64-linux-gnu/bits/wordsize.h" 1 3 4
# 411 "/usr/include/x86_64-linux-gnu/sys/cdefs.h" 2 3 4
# 368 "/usr/include/features.h" 2 3 4
# 391 "/usr/include/features.h" 3 4
..........
.............
....................
# 2 "code_a.c"
void main()
{
printf("Hello, World!");
}
The output is too large and we actually don’t need it to understand the concept. The thing we understood is that it simply called and replaced the whole piece of code in the header files to the program.
using -D option :# 1 "code_b.c"
# 1 ""
# 1 ""
# 1 "/usr/include/stdc-predef.h" 1 3 4
# 1 "" 2
# 1 "code_a.c"
# 1 "/usr/include/stdio.h" 1 3 4
# 27 "/usr/include/stdio.h" 3 4
# 1 "/usr/include/features.h" 1 3 4
# 367 "/usr/include/features.h" 3 4
# 1 "/usr/include/x86_64-linux-gnu/sys/cdefs.h" 1 3 4
# 410 "/usr/include/x86_64-linux-gnu/sys/cdefs.h" 3 4
# 1 "/usr/include/x86_64-linux-gnu/bits/wordsize.h" 1 3 4
# 411 "/usr/include/x86_64-linux-gnu/sys/cdefs.h" 2 3 4
# 368 "/usr/include/features.h" 2 3 4
# 391 "/usr/include/features.h" 3 4
..........
.............
....................
# 2 "code_b.c"
void main()
{
printf("Hello, World!");
}
Observe that it prints the same result. This is because it used the macro we declared on the command line.
# 1 "code_b.c"
# 1 ""
# 1 ""
# 1 "/usr/include/stdc-predef.h" 1 3 4
# 1 "" 2
# 1 "code_a.c"
# 1 "/usr/include/stdio.h" 1 3 4
# 27 "/usr/include/stdio.h" 3 4
# 1 "/usr/include/features.h" 1 3 4
# 367 "/usr/include/features.h" 3 4
# 1 "/usr/include/x86_64-linux-gnu/sys/cdefs.h" 1 3 4
# 410 "/usr/include/x86_64-linux-gnu/sys/cdefs.h" 3 4
# 1 "/usr/include/x86_64-linux-gnu/bits/wordsize.h" 1 3 4
# 411 "/usr/include/x86_64-linux-gnu/sys/cdefs.h" 2 3 4
# 368 "/usr/include/features.h" 2 3 4
# 391 "/usr/include/features.h" 3 4
..........
.............
....................
# 2 "code_b.c"
void main()
{
printf("Hello, World!");
}
Observe that it prints the same result. This is because it used the macro we declared on the command line.
Using -M option:Observed the difference. This is because it only outputs the rules required for make.
Observed the difference. This is because it only outputs the rules required for make.
linux-command
Linux-misc-commands
Picked
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n15 May, 2019"
},
{
"code": null,
"e": 394,
"s": 28,
"text": "cpp is the C language preprocessor, it is automatically used by your C compiler to transform your program before compilation. It is also termed as a macro processor because it is used to give abbreviations for the longer piece of code. It can only be used with C, C++ and Objective-C source code. Using with other programming languages may cause uncertain problems."
},
{
"code": null,
"e": 402,
"s": 394,
"text": "Syntax:"
},
{
"code": null,
"e": 436,
"s": 402,
"text": "cpp [-options] infile outfile\n"
},
{
"code": null,
"e": 460,
"s": 436,
"text": "Some Important Options:"
},
{
"code": null,
"e": 497,
"s": 460,
"text": "-D name : Predefine name as a macro."
},
{
"code": null,
"e": 615,
"s": 497,
"text": "-D name=definition : The contents of definition are tokenized and processed as if they are written in program itself."
},
{
"code": null,
"e": 666,
"s": 615,
"text": "-U name : Cancel any previous definition of macro."
},
{
"code": null,
"e": 783,
"s": 666,
"text": "-undef : Do not predefine any system-specific or GCC-specific macros. The standard predefined macros remain defined."
},
{
"code": null,
"e": 874,
"s": 783,
"text": "-I dir : Add the directory dir to the list of directories to be searched for header files."
},
{
"code": null,
"e": 950,
"s": 874,
"text": "-Wall : Turns on all optional warnings which are desirable for normal code."
},
{
"code": null,
"e": 1087,
"s": 950,
"text": "-Wcomments : Warn whenever a comment-start sequence /* appears in a /* comment, or whenever a backslash-newline appears in a // comment."
},
{
"code": null,
"e": 1162,
"s": 1087,
"text": "-Wendif-labels : Warn whenever an #else or an #endif are followed by text."
},
{
"code": null,
"e": 1239,
"s": 1162,
"text": "-w : Suppress all warnings, including those which GNU CPP issues by default."
},
{
"code": null,
"e": 1380,
"s": 1239,
"text": "-M : Instead of outputting the result of preprocessing, output a rule suitable for make describing the dependencies of the main source file."
},
{
"code": null,
"e": 1471,
"s": 1380,
"text": "-MM : Like -M but do not mention header files that are found in system header directories."
},
{
"code": null,
"e": 1476,
"s": 1471,
"text": "-x c"
},
{
"code": null,
"e": 1483,
"s": 1476,
"text": "-x c++"
},
{
"code": null,
"e": 1498,
"s": 1483,
"text": "-x objective-c"
},
{
"code": null,
"e": 1712,
"s": 1498,
"text": "-x assembler-with-cpp : All four above Specify the source language: C, C++, Objective-C, or assembly. This has nothing to do with standards conformance or extensions; it merely selects which base syntax to expect."
},
{
"code": null,
"e": 1816,
"s": 1712,
"text": "Examples: We have created two codes to explain the concept we will refer them as code_a.c and code_b.c."
},
{
"code": null,
"e": 1879,
"s": 1816,
"text": "#include\nvoid main()\n{\n printf(\"Hello, World!\");\n}\n\ncode_a.c\n"
},
{
"code": null,
"e": 1931,
"s": 1879,
"text": "#include\nvoid main()\n{\n printf(out);\n}\n\ncode_b.c\n"
},
{
"code": null,
"e": 2822,
"s": 1931,
"text": "Using cpp command :It will result into the following output:# 1 \"code_a.c\"\n# 1 \"\"\n# 1 \"\"\n# 1 \"/usr/include/stdc-predef.h\" 1 3 4\n# 1 \"\" 2\n# 1 \"code_a.c\"\n# 1 \"/usr/include/stdio.h\" 1 3 4\n# 27 \"/usr/include/stdio.h\" 3 4\n# 1 \"/usr/include/features.h\" 1 3 4\n# 367 \"/usr/include/features.h\" 3 4\n# 1 \"/usr/include/x86_64-linux-gnu/sys/cdefs.h\" 1 3 4\n# 410 \"/usr/include/x86_64-linux-gnu/sys/cdefs.h\" 3 4\n# 1 \"/usr/include/x86_64-linux-gnu/bits/wordsize.h\" 1 3 4\n# 411 \"/usr/include/x86_64-linux-gnu/sys/cdefs.h\" 2 3 4\n# 368 \"/usr/include/features.h\" 2 3 4\n# 391 \"/usr/include/features.h\" 3 4\n..........\n.............\n....................\n# 2 \"code_a.c\"\nvoid main()\n{\nprintf(\"Hello, World!\");\n\n}\nThe output is too large and we actually don’t need it to understand the concept. The thing we understood is that it simply called and replaced the whole piece of code in the header files to the program."
},
{
"code": null,
"e": 2864,
"s": 2822,
"text": "It will result into the following output:"
},
{
"code": null,
"e": 3493,
"s": 2864,
"text": "# 1 \"code_a.c\"\n# 1 \"\"\n# 1 \"\"\n# 1 \"/usr/include/stdc-predef.h\" 1 3 4\n# 1 \"\" 2\n# 1 \"code_a.c\"\n# 1 \"/usr/include/stdio.h\" 1 3 4\n# 27 \"/usr/include/stdio.h\" 3 4\n# 1 \"/usr/include/features.h\" 1 3 4\n# 367 \"/usr/include/features.h\" 3 4\n# 1 \"/usr/include/x86_64-linux-gnu/sys/cdefs.h\" 1 3 4\n# 410 \"/usr/include/x86_64-linux-gnu/sys/cdefs.h\" 3 4\n# 1 \"/usr/include/x86_64-linux-gnu/bits/wordsize.h\" 1 3 4\n# 411 \"/usr/include/x86_64-linux-gnu/sys/cdefs.h\" 2 3 4\n# 368 \"/usr/include/features.h\" 2 3 4\n# 391 \"/usr/include/features.h\" 3 4\n..........\n.............\n....................\n# 2 \"code_a.c\"\nvoid main()\n{\nprintf(\"Hello, World!\");\n\n}\n"
},
{
"code": null,
"e": 3696,
"s": 3493,
"text": "The output is too large and we actually don’t need it to understand the concept. The thing we understood is that it simply called and replaced the whole piece of code in the header files to the program."
},
{
"code": null,
"e": 4449,
"s": 3696,
"text": "using -D option :# 1 \"code_b.c\"\n# 1 \"\"\n# 1 \"\"\n# 1 \"/usr/include/stdc-predef.h\" 1 3 4\n# 1 \"\" 2\n# 1 \"code_a.c\"\n# 1 \"/usr/include/stdio.h\" 1 3 4\n# 27 \"/usr/include/stdio.h\" 3 4\n# 1 \"/usr/include/features.h\" 1 3 4\n# 367 \"/usr/include/features.h\" 3 4\n# 1 \"/usr/include/x86_64-linux-gnu/sys/cdefs.h\" 1 3 4\n# 410 \"/usr/include/x86_64-linux-gnu/sys/cdefs.h\" 3 4\n# 1 \"/usr/include/x86_64-linux-gnu/bits/wordsize.h\" 1 3 4\n# 411 \"/usr/include/x86_64-linux-gnu/sys/cdefs.h\" 2 3 4\n# 368 \"/usr/include/features.h\" 2 3 4\n# 391 \"/usr/include/features.h\" 3 4\n..........\n.............\n....................\n# 2 \"code_b.c\"\nvoid main()\n{\nprintf(\"Hello, World!\");\n\n}\n\nObserve that it prints the same result. This is because it used the macro we declared on the command line."
},
{
"code": null,
"e": 5079,
"s": 4449,
"text": "# 1 \"code_b.c\"\n# 1 \"\"\n# 1 \"\"\n# 1 \"/usr/include/stdc-predef.h\" 1 3 4\n# 1 \"\" 2\n# 1 \"code_a.c\"\n# 1 \"/usr/include/stdio.h\" 1 3 4\n# 27 \"/usr/include/stdio.h\" 3 4\n# 1 \"/usr/include/features.h\" 1 3 4\n# 367 \"/usr/include/features.h\" 3 4\n# 1 \"/usr/include/x86_64-linux-gnu/sys/cdefs.h\" 1 3 4\n# 410 \"/usr/include/x86_64-linux-gnu/sys/cdefs.h\" 3 4\n# 1 \"/usr/include/x86_64-linux-gnu/bits/wordsize.h\" 1 3 4\n# 411 \"/usr/include/x86_64-linux-gnu/sys/cdefs.h\" 2 3 4\n# 368 \"/usr/include/features.h\" 2 3 4\n# 391 \"/usr/include/features.h\" 3 4\n..........\n.............\n....................\n# 2 \"code_b.c\"\nvoid main()\n{\nprintf(\"Hello, World!\");\n\n}\n\n"
},
{
"code": null,
"e": 5186,
"s": 5079,
"text": "Observe that it prints the same result. This is because it used the macro we declared on the command line."
},
{
"code": null,
"e": 5288,
"s": 5186,
"text": "Using -M option:Observed the difference. This is because it only outputs the rules required for make."
},
{
"code": null,
"e": 5374,
"s": 5288,
"text": "Observed the difference. This is because it only outputs the rules required for make."
},
{
"code": null,
"e": 5388,
"s": 5374,
"text": "linux-command"
},
{
"code": null,
"e": 5408,
"s": 5388,
"text": "Linux-misc-commands"
},
{
"code": null,
"e": 5415,
"s": 5408,
"text": "Picked"
},
{
"code": null,
"e": 5426,
"s": 5415,
"text": "Linux-Unix"
}
] |
Calculate maximum value using ‘+’ or ‘*’ sign between two numbers in a string
|
16 Jun, 2022
Given a string of numbers, the task is to find the maximum value from the string, you can add a ‘+’ or ‘*’ sign between any two numbers.Examples:
Input : 01231
Output :
((((0 + 1) + 2) * 3) + 1) = 10
In above manner, we get the maximum value i.e. 10
Input : 891
Output :73
As 8*9*1 = 72 and 8*9+1 = 73.So, 73 is maximum.
Asked in : Facebook
The task is pretty simple as we can get the maximum value on multiplying all values but the point is to handle the case of 0 and 1 i.e. On multiplying with 0 and 1 we get the lower value as compared to on adding with 0 and 1. So, use ‘*’ sign between any two numbers(except numbers containing 0 and 1) and use ‘+’ if any of the numbers is 0 and 1.
C++
Java
Python3
C#
PHP
Javascript
// C++ program to find maximum value#include <bits/stdc++.h> using namespace std; // Function to calculate the valueint calcMaxValue(string str){ // Store first character as integer // in result int res = str[0] -'0'; // Start traversing the string for (int i = 1; i < str.length(); i++) { // Check if any of the two numbers // is 0 or 1, If yes then add current // element if (str[i] == '0' || str[i] == '1' || res < 2 ) res += (str[i]-'0'); // Else multiply else res *= (str[i]-'0'); } // Return maximum value return res;} // Drivers codeint main(){ string str = "01891"; cout << calcMaxValue(str); return 0;}
// Java program to find maximum value public class GFG{ // Method to calculate the value static int calcMaxValue(String str) { // Store first character as integer // in result int res = str.charAt(0) -'0'; // Start traversing the string for (int i = 1; i < str.length(); i++) { // Check if any of the two numbers // is 0 or 1, If yes then add current // element if (str.charAt(i) == '0' || str.charAt(i) == '1' || res < 2 ) res += (str.charAt(i)-'0'); // Else multiply else res *= (str.charAt(i)-'0'); } // Return maximum value return res; } // Driver Method public static void main(String[] args) { String str = "01891"; System.out.println(calcMaxValue(str)); }}
# Python program to find maximum value # Function to calculate the valuedef calcMaxValue(str): # Store first character as integer # in result res = ord(str[0]) - 48 # Start traversing the string for i in range(1, len(str)): # Check if any of the two numbers # is 0 or 1, If yes then add current # element if(str[i] == '0' or str[i] == '1' or res < 2): res += ord(str[i]) - 48 else: res *= ord(str[i]) - 48 return res # Driver codeif __name__== "__main__": str = "01891"; print(calcMaxValue(str)); # This code is contributed by Sairahul Jella
//C# program to find maximum valueusing System; class GFG{ // Method to calculate the value static int calcMaxValue(String str) { // Store first character as integer // in result int res = str[0] -'0'; // Start traversing the string for (int i = 1; i < str.Length; i++) { // Check if any of the two numbers // is 0 or 1, If yes then add current // element if (str[i] == '0' || str[i] == '1' || res < 2 ) res += (str[i] - '0'); // Else multiply else res *= (str[i] - '0'); } // Return maximum value return res; } // Driver Code static public void Main () { String str = "01891"; Console.Write(calcMaxValue(str)); }} // This code is contributed by jit_t
<?php// PHP program to find// maximum value // Function to calculate// the valuefunction calcMaxValue($str){ // Store first character // as integer in result $res = $str[0] - '0'; // Start traversing // the string for ($i = 1; $i < strlen($str); $i++) { // Check if any of the // two numbers is 0 or // 1, If yes then add // current element if ($str[$i] == '0' || $str[$i] == '1' || $res < 2 ) $res += ($str[$i] - '0'); // Else multiply else $res *= ($str[$i] - '0'); } // Return maximum value return $res;} // Driver code$str = "01891";echo calcMaxValue($str); // This code is contributed by ajit?>
<script> // Javascript program to // find maximum value // Method to calculate the value function calcMaxValue(str) { // Store first character as integer // in result let res = str[0].charCodeAt() - '0'.charCodeAt(); // Start traversing the string for (let i = 1; i < str.length; i++) { // Check if any of the two numbers // is 0 or 1, If yes then add current // element if (str[i] == '0' || str[i] == '1' || res < 2 ) res += (str[i].charCodeAt() - '0'.charCodeAt()); // Else multiply else res *= (str[i].charCodeAt() - '0'.charCodeAt()); } // Return maximum value return res; } let str = "01891"; document.write(calcMaxValue(str)); </script>
Output:
82
Time complexity : O(n) Auxiliary Space : O(1)
Above program consider the case of small inputs i.e. up to which C/C++ can handle the range of maximum value.Reference : https://www.careercup.com/question?id=5745795300065280This article is contributed by Sahil Chhabra. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
jit_t
Imam
MorganNewman
Sairahul Jella
Shivam_k
divyeshrabadiya07
a7977370173
Facebook
Strings
Facebook
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n16 Jun, 2022"
},
{
"code": null,
"e": 200,
"s": 52,
"text": "Given a string of numbers, the task is to find the maximum value from the string, you can add a ‘+’ or ‘*’ sign between any two numbers.Examples: "
},
{
"code": null,
"e": 377,
"s": 200,
"text": "Input : 01231\nOutput : \n((((0 + 1) + 2) * 3) + 1) = 10\nIn above manner, we get the maximum value i.e. 10\n\nInput : 891\nOutput :73\nAs 8*9*1 = 72 and 8*9+1 = 73.So, 73 is maximum."
},
{
"code": null,
"e": 398,
"s": 377,
"text": "Asked in : Facebook "
},
{
"code": null,
"e": 747,
"s": 398,
"text": "The task is pretty simple as we can get the maximum value on multiplying all values but the point is to handle the case of 0 and 1 i.e. On multiplying with 0 and 1 we get the lower value as compared to on adding with 0 and 1. So, use ‘*’ sign between any two numbers(except numbers containing 0 and 1) and use ‘+’ if any of the numbers is 0 and 1. "
},
{
"code": null,
"e": 751,
"s": 747,
"text": "C++"
},
{
"code": null,
"e": 756,
"s": 751,
"text": "Java"
},
{
"code": null,
"e": 764,
"s": 756,
"text": "Python3"
},
{
"code": null,
"e": 767,
"s": 764,
"text": "C#"
},
{
"code": null,
"e": 771,
"s": 767,
"text": "PHP"
},
{
"code": null,
"e": 782,
"s": 771,
"text": "Javascript"
},
{
"code": "// C++ program to find maximum value#include <bits/stdc++.h> using namespace std; // Function to calculate the valueint calcMaxValue(string str){ // Store first character as integer // in result int res = str[0] -'0'; // Start traversing the string for (int i = 1; i < str.length(); i++) { // Check if any of the two numbers // is 0 or 1, If yes then add current // element if (str[i] == '0' || str[i] == '1' || res < 2 ) res += (str[i]-'0'); // Else multiply else res *= (str[i]-'0'); } // Return maximum value return res;} // Drivers codeint main(){ string str = \"01891\"; cout << calcMaxValue(str); return 0;}",
"e": 1508,
"s": 782,
"text": null
},
{
"code": "// Java program to find maximum value public class GFG{ // Method to calculate the value static int calcMaxValue(String str) { // Store first character as integer // in result int res = str.charAt(0) -'0'; // Start traversing the string for (int i = 1; i < str.length(); i++) { // Check if any of the two numbers // is 0 or 1, If yes then add current // element if (str.charAt(i) == '0' || str.charAt(i) == '1' || res < 2 ) res += (str.charAt(i)-'0'); // Else multiply else res *= (str.charAt(i)-'0'); } // Return maximum value return res; } // Driver Method public static void main(String[] args) { String str = \"01891\"; System.out.println(calcMaxValue(str)); }}",
"e": 2407,
"s": 1508,
"text": null
},
{
"code": "# Python program to find maximum value # Function to calculate the valuedef calcMaxValue(str): # Store first character as integer # in result res = ord(str[0]) - 48 # Start traversing the string for i in range(1, len(str)): # Check if any of the two numbers # is 0 or 1, If yes then add current # element if(str[i] == '0' or str[i] == '1' or res < 2): res += ord(str[i]) - 48 else: res *= ord(str[i]) - 48 return res # Driver codeif __name__== \"__main__\": str = \"01891\"; print(calcMaxValue(str)); # This code is contributed by Sairahul Jella",
"e": 3064,
"s": 2407,
"text": null
},
{
"code": "//C# program to find maximum valueusing System; class GFG{ // Method to calculate the value static int calcMaxValue(String str) { // Store first character as integer // in result int res = str[0] -'0'; // Start traversing the string for (int i = 1; i < str.Length; i++) { // Check if any of the two numbers // is 0 or 1, If yes then add current // element if (str[i] == '0' || str[i] == '1' || res < 2 ) res += (str[i] - '0'); // Else multiply else res *= (str[i] - '0'); } // Return maximum value return res; } // Driver Code static public void Main () { String str = \"01891\"; Console.Write(calcMaxValue(str)); }} // This code is contributed by jit_t",
"e": 3953,
"s": 3064,
"text": null
},
{
"code": "<?php// PHP program to find// maximum value // Function to calculate// the valuefunction calcMaxValue($str){ // Store first character // as integer in result $res = $str[0] - '0'; // Start traversing // the string for ($i = 1; $i < strlen($str); $i++) { // Check if any of the // two numbers is 0 or // 1, If yes then add // current element if ($str[$i] == '0' || $str[$i] == '1' || $res < 2 ) $res += ($str[$i] - '0'); // Else multiply else $res *= ($str[$i] - '0'); } // Return maximum value return $res;} // Driver code$str = \"01891\";echo calcMaxValue($str); // This code is contributed by ajit?>",
"e": 4684,
"s": 3953,
"text": null
},
{
"code": "<script> // Javascript program to // find maximum value // Method to calculate the value function calcMaxValue(str) { // Store first character as integer // in result let res = str[0].charCodeAt() - '0'.charCodeAt(); // Start traversing the string for (let i = 1; i < str.length; i++) { // Check if any of the two numbers // is 0 or 1, If yes then add current // element if (str[i] == '0' || str[i] == '1' || res < 2 ) res += (str[i].charCodeAt() - '0'.charCodeAt()); // Else multiply else res *= (str[i].charCodeAt() - '0'.charCodeAt()); } // Return maximum value return res; } let str = \"01891\"; document.write(calcMaxValue(str)); </script>",
"e": 5600,
"s": 4684,
"text": null
},
{
"code": null,
"e": 5610,
"s": 5600,
"text": "Output: "
},
{
"code": null,
"e": 5613,
"s": 5610,
"text": "82"
},
{
"code": null,
"e": 5659,
"s": 5613,
"text": "Time complexity : O(n) Auxiliary Space : O(1)"
},
{
"code": null,
"e": 6256,
"s": 5659,
"text": "Above program consider the case of small inputs i.e. up to which C/C++ can handle the range of maximum value.Reference : https://www.careercup.com/question?id=5745795300065280This article is contributed by Sahil Chhabra. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 6262,
"s": 6256,
"text": "jit_t"
},
{
"code": null,
"e": 6267,
"s": 6262,
"text": "Imam"
},
{
"code": null,
"e": 6280,
"s": 6267,
"text": "MorganNewman"
},
{
"code": null,
"e": 6295,
"s": 6280,
"text": "Sairahul Jella"
},
{
"code": null,
"e": 6304,
"s": 6295,
"text": "Shivam_k"
},
{
"code": null,
"e": 6322,
"s": 6304,
"text": "divyeshrabadiya07"
},
{
"code": null,
"e": 6334,
"s": 6322,
"text": "a7977370173"
},
{
"code": null,
"e": 6343,
"s": 6334,
"text": "Facebook"
},
{
"code": null,
"e": 6351,
"s": 6343,
"text": "Strings"
},
{
"code": null,
"e": 6360,
"s": 6351,
"text": "Facebook"
},
{
"code": null,
"e": 6368,
"s": 6360,
"text": "Strings"
}
] |
Python – Convert 2D list to 3D at K slicing
|
03 Jul, 2020
Sometimes, while working with Python lists, we can have a problem in which we need to convert a 2D list to 3D, at every Kth list. This type of problem is peculiar, but can have application in various data domains. Let’s discuss certain ways in which this task can be performed.
Input : test_list = [[6, 5], [2, 3], [3, 1], [4, 6], [3, 2], [1, 6]] , K = 3Output : [[[6, 5], [2, 3], [3, 1]], [[4, 6], [3, 2], [1, 6]]]
Input : test_list = [[6, 5], [2, 3], [3, 1]] , K = 1Output : [[[6, 5]], [[2, 3]], [[3, 1]]]
Method #1 : Using loopThis is brute way in which this task can be performed. In this, we iterate through each element, and maintain a counter, at every Kth sublist, create a new list and append accordingly.
# Python3 code to demonstrate working of # Convert 2D list to 3D at K slicing# Using loop # initializing listtest_list = [[6, 5], [2, 3], [3, 1], [4, 6], [3, 2], [1, 6]] # printing original listprint("The original list is : " + str(test_list)) # initializing K K = 2 # Convert 2D list to 3D at K slicing# Using loopres = []subl = []cnt = 0for sub in test_list: subl.append(sub) cnt = cnt + 1 if cnt >= K: res.append(subl) subl = [] cnt = 0 # printing result print("Records after conversion : " + str(res))
The original list is : [[6, 5], [2, 3], [3, 1], [4, 6], [3, 2], [1, 6]]
Records after conversion : [[[6, 5], [2, 3]], [[3, 1], [4, 6]], [[3, 2], [1, 6]]]
Method #2 : Using zip() + list comprehensionThe combination of above functions can also be used to solve this problem. In this, we perform task by first chunking the values according to size and then list comprehension along with zip() is used for dimension conversion.
# Python3 code to demonstrate working of # Convert 2D list to 3D at K slicing# Using zip() + list comprehension # initializing listtest_list = [[6, 5], [2, 3], [3, 1], [4, 6], [3, 2], [1, 6]] # printing original listprint("The original list is : " + str(test_list)) # initializing K K = 2 # Convert 2D list to 3D at K slicing# Using zip() + list comprehensiontest_list = iter(test_list)temp = [test_list] * Kres = [list(ele) for ele in zip(*temp)] # printing result print("Records after conversion : " + str(res))
The original list is : [[6, 5], [2, 3], [3, 1], [4, 6], [3, 2], [1, 6]]
Records after conversion : [[[6, 5], [2, 3]], [[3, 1], [4, 6]], [[3, 2], [1, 6]]]
Python list-programs
Python-list-of-lists
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
Python | os.path.join() method
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary
Python Program for Fibonacci numbers
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n03 Jul, 2020"
},
{
"code": null,
"e": 306,
"s": 28,
"text": "Sometimes, while working with Python lists, we can have a problem in which we need to convert a 2D list to 3D, at every Kth list. This type of problem is peculiar, but can have application in various data domains. Let’s discuss certain ways in which this task can be performed."
},
{
"code": null,
"e": 444,
"s": 306,
"text": "Input : test_list = [[6, 5], [2, 3], [3, 1], [4, 6], [3, 2], [1, 6]] , K = 3Output : [[[6, 5], [2, 3], [3, 1]], [[4, 6], [3, 2], [1, 6]]]"
},
{
"code": null,
"e": 536,
"s": 444,
"text": "Input : test_list = [[6, 5], [2, 3], [3, 1]] , K = 1Output : [[[6, 5]], [[2, 3]], [[3, 1]]]"
},
{
"code": null,
"e": 743,
"s": 536,
"text": "Method #1 : Using loopThis is brute way in which this task can be performed. In this, we iterate through each element, and maintain a counter, at every Kth sublist, create a new list and append accordingly."
},
{
"code": "# Python3 code to demonstrate working of # Convert 2D list to 3D at K slicing# Using loop # initializing listtest_list = [[6, 5], [2, 3], [3, 1], [4, 6], [3, 2], [1, 6]] # printing original listprint(\"The original list is : \" + str(test_list)) # initializing K K = 2 # Convert 2D list to 3D at K slicing# Using loopres = []subl = []cnt = 0for sub in test_list: subl.append(sub) cnt = cnt + 1 if cnt >= K: res.append(subl) subl = [] cnt = 0 # printing result print(\"Records after conversion : \" + str(res))",
"e": 1285,
"s": 743,
"text": null
},
{
"code": null,
"e": 1440,
"s": 1285,
"text": "The original list is : [[6, 5], [2, 3], [3, 1], [4, 6], [3, 2], [1, 6]]\nRecords after conversion : [[[6, 5], [2, 3]], [[3, 1], [4, 6]], [[3, 2], [1, 6]]]\n"
},
{
"code": null,
"e": 1712,
"s": 1442,
"text": "Method #2 : Using zip() + list comprehensionThe combination of above functions can also be used to solve this problem. In this, we perform task by first chunking the values according to size and then list comprehension along with zip() is used for dimension conversion."
},
{
"code": "# Python3 code to demonstrate working of # Convert 2D list to 3D at K slicing# Using zip() + list comprehension # initializing listtest_list = [[6, 5], [2, 3], [3, 1], [4, 6], [3, 2], [1, 6]] # printing original listprint(\"The original list is : \" + str(test_list)) # initializing K K = 2 # Convert 2D list to 3D at K slicing# Using zip() + list comprehensiontest_list = iter(test_list)temp = [test_list] * Kres = [list(ele) for ele in zip(*temp)] # printing result print(\"Records after conversion : \" + str(res))",
"e": 2232,
"s": 1712,
"text": null
},
{
"code": null,
"e": 2387,
"s": 2232,
"text": "The original list is : [[6, 5], [2, 3], [3, 1], [4, 6], [3, 2], [1, 6]]\nRecords after conversion : [[[6, 5], [2, 3]], [[3, 1], [4, 6]], [[3, 2], [1, 6]]]\n"
},
{
"code": null,
"e": 2408,
"s": 2387,
"text": "Python list-programs"
},
{
"code": null,
"e": 2429,
"s": 2408,
"text": "Python-list-of-lists"
},
{
"code": null,
"e": 2436,
"s": 2429,
"text": "Python"
},
{
"code": null,
"e": 2452,
"s": 2436,
"text": "Python Programs"
},
{
"code": null,
"e": 2550,
"s": 2452,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2582,
"s": 2550,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2609,
"s": 2582,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2630,
"s": 2609,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 2653,
"s": 2630,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 2684,
"s": 2653,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 2706,
"s": 2684,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 2745,
"s": 2706,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 2783,
"s": 2745,
"text": "Python | Convert a list to dictionary"
},
{
"code": null,
"e": 2832,
"s": 2783,
"text": "Python | Convert string dictionary to dictionary"
}
] |
Multiply two numbers represented as linked lists into a third list
|
11 May, 2022
Given two numbers represented by linked lists, write a function that returns the head of the new linked list that represents the number that is the product of those numbers.
Examples:
Input : 9->4->6
8->4
Output : 7->9->4->6->4
Input : 9->9->9->4->6->9
9->9->8->4->9
Output : 9->9->7->9->5->9->8->0->1->8->1
We have already discussed a solution in below post. Multiply two numbers represented by Linked Lists
The solution discussed above stores result in an integer. Here we store result in a third list so that large numbers can be handled.Remember old school multiplication? we imitate that process. On paper, we take the last digit of a number and multiply with the second number and write the product. Now leave the last column and same way each digit of one number is multiplied with every digit of other number and every time result is written by leaving one last column. then add these columns that forms the number. Now assume these columns as nodes of the resultant linked list. We make resultant linked list in reversed fashion.
Algorithm
Reverse both linked lists
Make a linked list of maximum result size (m + n + 1)
For each node of one list
For each node of second list
a) Multiply nodes
b) Add digit in result LL at corresponding
position
c) Now resultant node itself can be higher
than one digit
d) Make carry for next node
Leave one last column means next time start
From next node in result list
Reverse the resulted linked list
C++
C
Python3
// C++ program to Multiply two numbers// represented as linked lists#include <bits/stdc++.h>using namespace std; // Linked list Nodestruct Node { int data; struct Node* next;}; // Function to create a new Node// with given datastruct Node* newNode(int data){ struct Node* new_node = (struct Node*)malloc(sizeof(struct Node)); new_node->data = data; new_node->next = NULL; return new_node;} // Function to insert a Node at the// beginning of the Linked Listvoid push(struct Node** head_ref, int new_data){ // allocate Node struct Node* new_node = newNode(new_data); // link the old list off the new Node new_node->next = (*head_ref); // move the head to point to the new Node (*head_ref) = new_node;} // Function to reverse the linked list and return// its lengthint reverse(struct Node** head_ref){ struct Node* prev = NULL; struct Node* current = *head_ref; struct Node* next; int len = 0; while (current != NULL) { len++; next = current->next; current->next = prev; prev = current; current = next; } *head_ref = prev; return len;} // Function to make an empty linked list of// given sizestruct Node* make_empty_list(int size){ struct Node* head = NULL; while (size--) push(&head, 0); return head;} // Multiply contents of two linked lists => store// in another list and return its headstruct Node* multiplyTwoLists(struct Node* first, struct Node* second){ // reverse the lists to multiply from end // m and n lengths of linked lists to make // and empty list int m = reverse(&first), n = reverse(&second); // make a list that will contain the result // of multiplication. // m+n+1 can be max size of the list struct Node* result = make_empty_list(m + n + 1); // pointers for traverse linked lists and also // to reverse them after struct Node *second_ptr = second, *result_ptr1 = result, *result_ptr2, *first_ptr; // multiply each Node of second list with first while (second_ptr) { int carry = 0; // each time we start from the next of Node // from which we started last time result_ptr2 = result_ptr1; first_ptr = first; while (first_ptr) { // multiply a first list's digit with a // current second list's digit int mul = first_ptr->data * second_ptr->data + carry; // Assign the product to corresponding Node // of result result_ptr2->data += mul % 10; // now resultant Node itself can have more // than 1 digit carry = mul / 10 + result_ptr2->data / 10; result_ptr2->data = result_ptr2->data % 10; first_ptr = first_ptr->next; result_ptr2 = result_ptr2->next; } // if carry is remaining from last multiplication if (carry > 0) { result_ptr2->data += carry; } result_ptr1 = result_ptr1->next; second_ptr = second_ptr->next; } // reverse the result_list as it was populated // from last Node reverse(&result); reverse(&first); reverse(&second); // remove if there are zeros at starting while (result->data == 0) { struct Node* temp = result; result = result->next; free(temp); } // Return head of multiplication list return result;} // A utility function to print a linked listvoid printList(struct Node* Node){ while (Node != NULL) { cout << Node->data; if (Node->next) cout<<"->"; Node = Node->next; } cout << endl;} // Driver program to test above functionint main(void){ struct Node* first = NULL; struct Node* second = NULL; // create first list 9->9->9->4->6->9 push(&first, 9); push(&first, 6); push(&first, 4); push(&first, 9); push(&first, 9); push(&first, 9); cout<<"First List is: "; printList(first); // create second list 9->9->8->4->9 push(&second, 9); push(&second, 4); push(&second, 8); push(&second, 9); push(&second, 9); cout<<"Second List is: "; printList(second); // Multiply the two lists and see result struct Node* result = multiplyTwoLists(first, second); cout << "Resultant list is: "; printList(result); return 0;} // This code is contributed by SHUBHAMSINGH10
// C program to Multiply two numbers// represented as linked lists#include <stdio.h>#include <stdlib.h> // Linked list Nodestruct Node { int data; struct Node* next;}; // Function to create a new Node// with given datastruct Node* newNode(int data){ struct Node* new_node = (struct Node*)malloc(sizeof(struct Node)); new_node->data = data; new_node->next = NULL; return new_node;} // Function to insert a Node at the// beginning of the Linked Listvoid push(struct Node** head_ref, int new_data){ // allocate Node struct Node* new_node = newNode(new_data); // link the old list off the new Node new_node->next = (*head_ref); // move the head to point to the new Node (*head_ref) = new_node;} // Function to reverse the linked list and return// its lengthint reverse(struct Node** head_ref){ struct Node* prev = NULL; struct Node* current = *head_ref; struct Node* next; int len = 0; while (current != NULL) { len++; next = current->next; current->next = prev; prev = current; current = next; } *head_ref = prev; return len;} // Function to make an empty linked list of// given sizestruct Node* make_empty_list(int size){ struct Node* head = NULL; while (size--) push(&head, 0); return head;} // Multiply contents of two linked lists => store// in another list and return its headstruct Node* multiplyTwoLists(struct Node* first, struct Node* second){ // reverse the lists to multiply from end // m and n lengths of linked lists to make // and empty list int m = reverse(&first), n = reverse(&second); // make a list that will contain the result // of multiplication. // m+n+1 can be max size of the list struct Node* result = make_empty_list(m + n + 1); // pointers for traverse linked lists and also // to reverse them after struct Node *second_ptr = second, *result_ptr1 = result, *result_ptr2, *first_ptr; // multiply each Node of second list with first while (second_ptr) { int carry = 0; // each time we start from the next of Node // from which we started last time result_ptr2 = result_ptr1; first_ptr = first; while (first_ptr) { // multiply a first list's digit with a // current second list's digit int mul = first_ptr->data * second_ptr->data + carry; // Assign the product to corresponding Node // of result result_ptr2->data += mul % 10; // now resultant Node itself can have more // than 1 digit carry = mul / 10 + result_ptr2->data / 10; result_ptr2->data = result_ptr2->data % 10; first_ptr = first_ptr->next; result_ptr2 = result_ptr2->next; } // if carry is remaining from last multiplication if (carry > 0) { result_ptr2->data += carry; } result_ptr1 = result_ptr1->next; second_ptr = second_ptr->next; } // reverse the result_list as it was populated // from last Node reverse(&result); reverse(&first); reverse(&second); // remove if there are zeros at starting while (result->data == 0) { struct Node* temp = result; result = result->next; free(temp); } // Return head of multiplication list return result;} // A utility function to print a linked listvoid printList(struct Node* Node){ while (Node != NULL) { printf("%d", Node->data); if (Node->next) printf("->"); Node = Node->next; } printf("\n");} // Driver program to test above functionint main(void){ struct Node* first = NULL; struct Node* second = NULL; // create first list 9->9->9->4->6->9 push(&first, 9); push(&first, 6); push(&first, 4); push(&first, 9); push(&first, 9); push(&first, 9); printf("First List is: "); printList(first); // create second list 9->9->8->4->9 push(&second, 9); push(&second, 4); push(&second, 8); push(&second, 9); push(&second, 9); printf("Second List is: "); printList(second); // Multiply the two lists and see result struct Node* result = multiplyTwoLists(first, second); printf("Resultant list is: "); printList(result); return 0;}
# Python3 program to multiply two numbers# represented as linked lists # Node classclass Node: # Function to initialize the node object def __init__(self, data): self.data = data self.next = None # Linked List Classclass LinkedList: # Function to initialize the # LinkedList class. def __init__(self): # Initialize head as None self.head = None # This function insert a new node at the # beginning of the linked list def push(self, new_data): # Create a new Node new_node = Node(new_data) # Make next of new Node as head new_node.next = self.head # Move the head to point to new Node self.head = new_node # Method to print the linked list def printList(self): # Object to iterate # the list ptr = self.head # Loop to iterate list while(ptr != None): print(ptr.data, '->', end = '') # Moving the iterating object # to next node ptr = ptr.next print() # Function to reverse the linked# list and return its lengthdef reverse(head_ref): # Initialising prev and current # at None and starting node # respectively. prev = None current = head_ref.head Len = 0 # Loop to reverse the link # of each node in the list while(current != None): Len += 1 Next = current.next current.next = prev prev = current current = Next # Assigning new starting object # to main head object. head_ref.head = prev # Returning the length of # linked list. return Len # Function to define an empty# linked list of given size and# each element as zero.def make_empty_list(size): head = LinkedList() while(size): head.push(0) size -= 1 # Returns the head object. return head # Multiply contents of two linked# list store it in other list and# return its head.def multiplyTwoLists(first, second): # Reverse the list to multiply from # end m and n lengths of linked list # to make and empty list m = reverse(first) n = reverse(second) # Make a list that will contain the # result of multiplication. # m+n+1 can be max size of the list. result = make_empty_list(m + n + 1) # Objects for traverse linked list # and also to reverse them after. second_ptr = second.head result_ptr1 = result.head # Multiply each node of second # list with first. while(second_ptr != None): carry = 0 # Each time we start from next # node from which we started last # time. result_ptr2 = result_ptr1 first_ptr = first.head while(first_ptr != None): # Multiply a first list's digit # with a current second list's digit. mul = ((first_ptr.data) * (second_ptr.data) + carry) # Assign the product to corresponding # node of result. result_ptr2.data += mul % 10 # Now resultant node itself can have # more than one digit. carry = ((mul // 10) + (result_ptr2.data // 10)) result_ptr2.data = result_ptr2.data % 10 first_ptr = first_ptr.next result_ptr2 = result_ptr2.next # If carry is remaining from # last multiplication if(carry > 0): result_ptr2.data += carry result_ptr1 = result_ptr1.next second_ptr = second_ptr.next # Reverse the result_list as it # was populated from last node reverse(result) reverse(first) reverse(second) # Remove starting nodes # containing zeroes. start = result.head while(start.data == 0): result.head = start.next start = start.next # Return the resultant multiplicated # linked list. return result # Driver codeif __name__=='__main__': first = LinkedList() second = LinkedList() # Pushing elements at start of # first linked list. first.push(9) first.push(6) first.push(4) first.push(9) first.push(9) first.push(9) # Printing first linked list print("First list is: ", end = '') first.printList() # Pushing elements at start of # second linked list. second.push(9) second.push(4) second.push(8) second.push(9) second.push(9) # Printing second linked list. print("Second List is: ", end = '') second.printList() # Multiply two linked list and # print the result. result = multiplyTwoLists(first, second) print("Resultant list is: ", end = '') result.printList() # This code is contributed by Amit Mangal
Output:
First List is: 9->9->9->4->6->9
Second List is: 9->9->8->4->9
Resultant list is: 9->9->7->9->5->9->8->0->1->8->1
Note: we can take care of resultant node that can have more than 1 digit outside the loop just traverse the result list and add carry to next digit before reversing.
SHUBHAMSINGH10
amit_mangal_
rajeev0719singh
surinderdawra388
kalrap615
mahinsagotra18
Linked List
Linked List
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
LinkedList in Java
Introduction to Data Structures
What is Data Structure: Types, Classifications and Applications
Linked List vs Array
Implementing a Linked List in Java using Class
Find Length of a Linked List (Iterative and Recursive)
Queue - Linked List Implementation
Function to check if a singly linked list is palindrome
Remove duplicates from an unsorted linked list
Implement a stack using singly linked list
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n11 May, 2022"
},
{
"code": null,
"e": 226,
"s": 52,
"text": "Given two numbers represented by linked lists, write a function that returns the head of the new linked list that represents the number that is the product of those numbers."
},
{
"code": null,
"e": 237,
"s": 226,
"text": "Examples: "
},
{
"code": null,
"e": 380,
"s": 237,
"text": "Input : 9->4->6\n 8->4\nOutput : 7->9->4->6->4\n\nInput : 9->9->9->4->6->9\n 9->9->8->4->9\nOutput : 9->9->7->9->5->9->8->0->1->8->1\n "
},
{
"code": null,
"e": 481,
"s": 380,
"text": "We have already discussed a solution in below post. Multiply two numbers represented by Linked Lists"
},
{
"code": null,
"e": 1112,
"s": 481,
"text": "The solution discussed above stores result in an integer. Here we store result in a third list so that large numbers can be handled.Remember old school multiplication? we imitate that process. On paper, we take the last digit of a number and multiply with the second number and write the product. Now leave the last column and same way each digit of one number is multiplied with every digit of other number and every time result is written by leaving one last column. then add these columns that forms the number. Now assume these columns as nodes of the resultant linked list. We make resultant linked list in reversed fashion. "
},
{
"code": null,
"e": 1124,
"s": 1112,
"text": "Algorithm "
},
{
"code": null,
"e": 1551,
"s": 1124,
"text": "Reverse both linked lists\nMake a linked list of maximum result size (m + n + 1)\nFor each node of one list\n For each node of second list\n a) Multiply nodes\n b) Add digit in result LL at corresponding \n position\n c) Now resultant node itself can be higher\n than one digit\n d) Make carry for next node\n Leave one last column means next time start\nFrom next node in result list\nReverse the resulted linked list"
},
{
"code": null,
"e": 1555,
"s": 1551,
"text": "C++"
},
{
"code": null,
"e": 1557,
"s": 1555,
"text": "C"
},
{
"code": null,
"e": 1565,
"s": 1557,
"text": "Python3"
},
{
"code": "// C++ program to Multiply two numbers// represented as linked lists#include <bits/stdc++.h>using namespace std; // Linked list Nodestruct Node { int data; struct Node* next;}; // Function to create a new Node// with given datastruct Node* newNode(int data){ struct Node* new_node = (struct Node*)malloc(sizeof(struct Node)); new_node->data = data; new_node->next = NULL; return new_node;} // Function to insert a Node at the// beginning of the Linked Listvoid push(struct Node** head_ref, int new_data){ // allocate Node struct Node* new_node = newNode(new_data); // link the old list off the new Node new_node->next = (*head_ref); // move the head to point to the new Node (*head_ref) = new_node;} // Function to reverse the linked list and return// its lengthint reverse(struct Node** head_ref){ struct Node* prev = NULL; struct Node* current = *head_ref; struct Node* next; int len = 0; while (current != NULL) { len++; next = current->next; current->next = prev; prev = current; current = next; } *head_ref = prev; return len;} // Function to make an empty linked list of// given sizestruct Node* make_empty_list(int size){ struct Node* head = NULL; while (size--) push(&head, 0); return head;} // Multiply contents of two linked lists => store// in another list and return its headstruct Node* multiplyTwoLists(struct Node* first, struct Node* second){ // reverse the lists to multiply from end // m and n lengths of linked lists to make // and empty list int m = reverse(&first), n = reverse(&second); // make a list that will contain the result // of multiplication. // m+n+1 can be max size of the list struct Node* result = make_empty_list(m + n + 1); // pointers for traverse linked lists and also // to reverse them after struct Node *second_ptr = second, *result_ptr1 = result, *result_ptr2, *first_ptr; // multiply each Node of second list with first while (second_ptr) { int carry = 0; // each time we start from the next of Node // from which we started last time result_ptr2 = result_ptr1; first_ptr = first; while (first_ptr) { // multiply a first list's digit with a // current second list's digit int mul = first_ptr->data * second_ptr->data + carry; // Assign the product to corresponding Node // of result result_ptr2->data += mul % 10; // now resultant Node itself can have more // than 1 digit carry = mul / 10 + result_ptr2->data / 10; result_ptr2->data = result_ptr2->data % 10; first_ptr = first_ptr->next; result_ptr2 = result_ptr2->next; } // if carry is remaining from last multiplication if (carry > 0) { result_ptr2->data += carry; } result_ptr1 = result_ptr1->next; second_ptr = second_ptr->next; } // reverse the result_list as it was populated // from last Node reverse(&result); reverse(&first); reverse(&second); // remove if there are zeros at starting while (result->data == 0) { struct Node* temp = result; result = result->next; free(temp); } // Return head of multiplication list return result;} // A utility function to print a linked listvoid printList(struct Node* Node){ while (Node != NULL) { cout << Node->data; if (Node->next) cout<<\"->\"; Node = Node->next; } cout << endl;} // Driver program to test above functionint main(void){ struct Node* first = NULL; struct Node* second = NULL; // create first list 9->9->9->4->6->9 push(&first, 9); push(&first, 6); push(&first, 4); push(&first, 9); push(&first, 9); push(&first, 9); cout<<\"First List is: \"; printList(first); // create second list 9->9->8->4->9 push(&second, 9); push(&second, 4); push(&second, 8); push(&second, 9); push(&second, 9); cout<<\"Second List is: \"; printList(second); // Multiply the two lists and see result struct Node* result = multiplyTwoLists(first, second); cout << \"Resultant list is: \"; printList(result); return 0;} // This code is contributed by SHUBHAMSINGH10",
"e": 5979,
"s": 1565,
"text": null
},
{
"code": "// C program to Multiply two numbers// represented as linked lists#include <stdio.h>#include <stdlib.h> // Linked list Nodestruct Node { int data; struct Node* next;}; // Function to create a new Node// with given datastruct Node* newNode(int data){ struct Node* new_node = (struct Node*)malloc(sizeof(struct Node)); new_node->data = data; new_node->next = NULL; return new_node;} // Function to insert a Node at the// beginning of the Linked Listvoid push(struct Node** head_ref, int new_data){ // allocate Node struct Node* new_node = newNode(new_data); // link the old list off the new Node new_node->next = (*head_ref); // move the head to point to the new Node (*head_ref) = new_node;} // Function to reverse the linked list and return// its lengthint reverse(struct Node** head_ref){ struct Node* prev = NULL; struct Node* current = *head_ref; struct Node* next; int len = 0; while (current != NULL) { len++; next = current->next; current->next = prev; prev = current; current = next; } *head_ref = prev; return len;} // Function to make an empty linked list of// given sizestruct Node* make_empty_list(int size){ struct Node* head = NULL; while (size--) push(&head, 0); return head;} // Multiply contents of two linked lists => store// in another list and return its headstruct Node* multiplyTwoLists(struct Node* first, struct Node* second){ // reverse the lists to multiply from end // m and n lengths of linked lists to make // and empty list int m = reverse(&first), n = reverse(&second); // make a list that will contain the result // of multiplication. // m+n+1 can be max size of the list struct Node* result = make_empty_list(m + n + 1); // pointers for traverse linked lists and also // to reverse them after struct Node *second_ptr = second, *result_ptr1 = result, *result_ptr2, *first_ptr; // multiply each Node of second list with first while (second_ptr) { int carry = 0; // each time we start from the next of Node // from which we started last time result_ptr2 = result_ptr1; first_ptr = first; while (first_ptr) { // multiply a first list's digit with a // current second list's digit int mul = first_ptr->data * second_ptr->data + carry; // Assign the product to corresponding Node // of result result_ptr2->data += mul % 10; // now resultant Node itself can have more // than 1 digit carry = mul / 10 + result_ptr2->data / 10; result_ptr2->data = result_ptr2->data % 10; first_ptr = first_ptr->next; result_ptr2 = result_ptr2->next; } // if carry is remaining from last multiplication if (carry > 0) { result_ptr2->data += carry; } result_ptr1 = result_ptr1->next; second_ptr = second_ptr->next; } // reverse the result_list as it was populated // from last Node reverse(&result); reverse(&first); reverse(&second); // remove if there are zeros at starting while (result->data == 0) { struct Node* temp = result; result = result->next; free(temp); } // Return head of multiplication list return result;} // A utility function to print a linked listvoid printList(struct Node* Node){ while (Node != NULL) { printf(\"%d\", Node->data); if (Node->next) printf(\"->\"); Node = Node->next; } printf(\"\\n\");} // Driver program to test above functionint main(void){ struct Node* first = NULL; struct Node* second = NULL; // create first list 9->9->9->4->6->9 push(&first, 9); push(&first, 6); push(&first, 4); push(&first, 9); push(&first, 9); push(&first, 9); printf(\"First List is: \"); printList(first); // create second list 9->9->8->4->9 push(&second, 9); push(&second, 4); push(&second, 8); push(&second, 9); push(&second, 9); printf(\"Second List is: \"); printList(second); // Multiply the two lists and see result struct Node* result = multiplyTwoLists(first, second); printf(\"Resultant list is: \"); printList(result); return 0;}",
"e": 10357,
"s": 5979,
"text": null
},
{
"code": "# Python3 program to multiply two numbers# represented as linked lists # Node classclass Node: # Function to initialize the node object def __init__(self, data): self.data = data self.next = None # Linked List Classclass LinkedList: # Function to initialize the # LinkedList class. def __init__(self): # Initialize head as None self.head = None # This function insert a new node at the # beginning of the linked list def push(self, new_data): # Create a new Node new_node = Node(new_data) # Make next of new Node as head new_node.next = self.head # Move the head to point to new Node self.head = new_node # Method to print the linked list def printList(self): # Object to iterate # the list ptr = self.head # Loop to iterate list while(ptr != None): print(ptr.data, '->', end = '') # Moving the iterating object # to next node ptr = ptr.next print() # Function to reverse the linked# list and return its lengthdef reverse(head_ref): # Initialising prev and current # at None and starting node # respectively. prev = None current = head_ref.head Len = 0 # Loop to reverse the link # of each node in the list while(current != None): Len += 1 Next = current.next current.next = prev prev = current current = Next # Assigning new starting object # to main head object. head_ref.head = prev # Returning the length of # linked list. return Len # Function to define an empty# linked list of given size and# each element as zero.def make_empty_list(size): head = LinkedList() while(size): head.push(0) size -= 1 # Returns the head object. return head # Multiply contents of two linked# list store it in other list and# return its head.def multiplyTwoLists(first, second): # Reverse the list to multiply from # end m and n lengths of linked list # to make and empty list m = reverse(first) n = reverse(second) # Make a list that will contain the # result of multiplication. # m+n+1 can be max size of the list. result = make_empty_list(m + n + 1) # Objects for traverse linked list # and also to reverse them after. second_ptr = second.head result_ptr1 = result.head # Multiply each node of second # list with first. while(second_ptr != None): carry = 0 # Each time we start from next # node from which we started last # time. result_ptr2 = result_ptr1 first_ptr = first.head while(first_ptr != None): # Multiply a first list's digit # with a current second list's digit. mul = ((first_ptr.data) * (second_ptr.data) + carry) # Assign the product to corresponding # node of result. result_ptr2.data += mul % 10 # Now resultant node itself can have # more than one digit. carry = ((mul // 10) + (result_ptr2.data // 10)) result_ptr2.data = result_ptr2.data % 10 first_ptr = first_ptr.next result_ptr2 = result_ptr2.next # If carry is remaining from # last multiplication if(carry > 0): result_ptr2.data += carry result_ptr1 = result_ptr1.next second_ptr = second_ptr.next # Reverse the result_list as it # was populated from last node reverse(result) reverse(first) reverse(second) # Remove starting nodes # containing zeroes. start = result.head while(start.data == 0): result.head = start.next start = start.next # Return the resultant multiplicated # linked list. return result # Driver codeif __name__=='__main__': first = LinkedList() second = LinkedList() # Pushing elements at start of # first linked list. first.push(9) first.push(6) first.push(4) first.push(9) first.push(9) first.push(9) # Printing first linked list print(\"First list is: \", end = '') first.printList() # Pushing elements at start of # second linked list. second.push(9) second.push(4) second.push(8) second.push(9) second.push(9) # Printing second linked list. print(\"Second List is: \", end = '') second.printList() # Multiply two linked list and # print the result. result = multiplyTwoLists(first, second) print(\"Resultant list is: \", end = '') result.printList() # This code is contributed by Amit Mangal",
"e": 15068,
"s": 10357,
"text": null
},
{
"code": null,
"e": 15077,
"s": 15068,
"text": "Output: "
},
{
"code": null,
"e": 15190,
"s": 15077,
"text": "First List is: 9->9->9->4->6->9\nSecond List is: 9->9->8->4->9\nResultant list is: 9->9->7->9->5->9->8->0->1->8->1"
},
{
"code": null,
"e": 15357,
"s": 15190,
"text": "Note: we can take care of resultant node that can have more than 1 digit outside the loop just traverse the result list and add carry to next digit before reversing. "
},
{
"code": null,
"e": 15372,
"s": 15357,
"text": "SHUBHAMSINGH10"
},
{
"code": null,
"e": 15385,
"s": 15372,
"text": "amit_mangal_"
},
{
"code": null,
"e": 15401,
"s": 15385,
"text": "rajeev0719singh"
},
{
"code": null,
"e": 15418,
"s": 15401,
"text": "surinderdawra388"
},
{
"code": null,
"e": 15428,
"s": 15418,
"text": "kalrap615"
},
{
"code": null,
"e": 15443,
"s": 15428,
"text": "mahinsagotra18"
},
{
"code": null,
"e": 15455,
"s": 15443,
"text": "Linked List"
},
{
"code": null,
"e": 15467,
"s": 15455,
"text": "Linked List"
},
{
"code": null,
"e": 15565,
"s": 15467,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 15584,
"s": 15565,
"text": "LinkedList in Java"
},
{
"code": null,
"e": 15616,
"s": 15584,
"text": "Introduction to Data Structures"
},
{
"code": null,
"e": 15680,
"s": 15616,
"text": "What is Data Structure: Types, Classifications and Applications"
},
{
"code": null,
"e": 15701,
"s": 15680,
"text": "Linked List vs Array"
},
{
"code": null,
"e": 15748,
"s": 15701,
"text": "Implementing a Linked List in Java using Class"
},
{
"code": null,
"e": 15803,
"s": 15748,
"text": "Find Length of a Linked List (Iterative and Recursive)"
},
{
"code": null,
"e": 15838,
"s": 15803,
"text": "Queue - Linked List Implementation"
},
{
"code": null,
"e": 15894,
"s": 15838,
"text": "Function to check if a singly linked list is palindrome"
},
{
"code": null,
"e": 15941,
"s": 15894,
"text": "Remove duplicates from an unsorted linked list"
}
] |
How Does OutOfMemory Error Happen and How to Solve it in Android?
|
19 Jun, 2021
Continuing our journey from understanding the OutOfMemory Error from the previous article we now check on the main reasons which cause the OOM Error in Android Studio. Every Android developer must have encountered the OutOfMemoryError, sometimes known as OOM. If you haven’t yet encountered an OOM in your Android application, you will in the near future. Memory leaks cause the OutOfMemoryError in Android. To eliminate the OutOfMemoryError, you must first eliminate memory leaks from your Android application.
The Error!
When you run an application on an Android device, the Android system allocates memory to it in order for it to function. All variables, functions, and activity creation, for example, takes happen alone in that memory.
Example: If the Android System assigns 200MB to your program, for example, your application can only use 200MB at a time. If the amount of space allotted to the program is reduced over time, or if very little space is available, the Garbage Collector (GC) will release the memory held by variables and activities that are no longer in use. As a result, the application will get some space once more.
However, if you build your code in such a way that it contains references to objects that are no longer necessary, the Garbage Collector will be unable to release the unused space, and the application will run out of space. This is referred to as a Memory Leak.
We encounter the OutOfMemoryError in Android due to the phenomenon of Memory Leak in Android because your code is holding references to objects that are no longer required and the Garbage Collector is unable to perform its job, and your application consumes all of the space allocated to it by the Android System and demands more.
OutOfMemoryError in Android can occur for a variety of reasons. The following are some of the most typical causes of Memory Leaks that result in an OutOfMemoryError:
The inner class that isn’t static
Use of getContext() and getApplicationContext() incorrectly()
Application of a static view, context, or activity
Let’s go through each of them One by One:
1. Inner class that isn’t static
If you have a nested class in your application, make it a static class because static classes don’t require an implicit reference to the outer class. If you make the inner class non-static, the outer class will be active till the application is active. If your class uses a lot of memory, this can result in an OutOfMemoryError. As a result, it’s preferable to make the inner class static. In Java, you must manually make the inner class static, whereas, in Kotlin, the inner class is static by default. In Kotlin, you don’t have to worry about static inner classes.
2. Use of getContext() and getApplicationContext() incorrectly()
In our application, we use a lot of third-party libraries, and the majority of them employ the Singleton class. If you need to give some context to a third-party library that is beyond the scope of the current activity, use getApplicationContext() rather than getContext(). Like in the Example below initialize is a static function in the library that uses the context
Java
SomeLibrary{ object companion { initializeGeeksforGeeksLib(Content context) { this.context = context.getApplicationContext() } }}
Some libraries, however, do not utilize the aforementioned notation. So, in that scenario, it will use the current activity’s context, and the current activity’s reference will be retained till the application is alive, which may result in an OutOfMemoryError (as the initialize function is static). As a result, it is preferable to utilize getApplicationContext() directly in your code rather than relying on third-party libraries. These are some of the methods for eliminating OutOfMemoryError from our application. It is preferable to write code that does not result in an OutOfMemoryError. Still, if your project is large and you’re having trouble finding the class that causes OutOfMemoryError, you can utilize Android Studio’s memory profiler to locate the classes that cause OutOfMemoryError.
3. Application of a static view, context, or activity
OutOfMemoryError will occur if you use any static views, contexts, or activities (if your activities are dealing with lots of space). This is because the program will hold the view, context, or activity until the application is alive, and the memory used by these will not be released by the Garbage Collector.
Example: If you’re going to use Bitmap in some project. That project will meet the OutOfMemoryError on your mobile device if you use more than 10 photos with a size of 500KB each. The number of images that can cause an OutOfMemoryError in other situations can be greater than or fewer than 10. You may ascertain the limit by adding photos to the BitmapArray one by one until you get an OOM, which indicates the device’s limit.
Picked
Android
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n19 Jun, 2021"
},
{
"code": null,
"e": 540,
"s": 28,
"text": "Continuing our journey from understanding the OutOfMemory Error from the previous article we now check on the main reasons which cause the OOM Error in Android Studio. Every Android developer must have encountered the OutOfMemoryError, sometimes known as OOM. If you haven’t yet encountered an OOM in your Android application, you will in the near future. Memory leaks cause the OutOfMemoryError in Android. To eliminate the OutOfMemoryError, you must first eliminate memory leaks from your Android application."
},
{
"code": null,
"e": 551,
"s": 540,
"text": "The Error!"
},
{
"code": null,
"e": 769,
"s": 551,
"text": "When you run an application on an Android device, the Android system allocates memory to it in order for it to function. All variables, functions, and activity creation, for example, takes happen alone in that memory."
},
{
"code": null,
"e": 1169,
"s": 769,
"text": "Example: If the Android System assigns 200MB to your program, for example, your application can only use 200MB at a time. If the amount of space allotted to the program is reduced over time, or if very little space is available, the Garbage Collector (GC) will release the memory held by variables and activities that are no longer in use. As a result, the application will get some space once more."
},
{
"code": null,
"e": 1431,
"s": 1169,
"text": "However, if you build your code in such a way that it contains references to objects that are no longer necessary, the Garbage Collector will be unable to release the unused space, and the application will run out of space. This is referred to as a Memory Leak."
},
{
"code": null,
"e": 1762,
"s": 1431,
"text": "We encounter the OutOfMemoryError in Android due to the phenomenon of Memory Leak in Android because your code is holding references to objects that are no longer required and the Garbage Collector is unable to perform its job, and your application consumes all of the space allocated to it by the Android System and demands more."
},
{
"code": null,
"e": 1928,
"s": 1762,
"text": "OutOfMemoryError in Android can occur for a variety of reasons. The following are some of the most typical causes of Memory Leaks that result in an OutOfMemoryError:"
},
{
"code": null,
"e": 1962,
"s": 1928,
"text": "The inner class that isn’t static"
},
{
"code": null,
"e": 2024,
"s": 1962,
"text": "Use of getContext() and getApplicationContext() incorrectly()"
},
{
"code": null,
"e": 2075,
"s": 2024,
"text": "Application of a static view, context, or activity"
},
{
"code": null,
"e": 2117,
"s": 2075,
"text": "Let’s go through each of them One by One:"
},
{
"code": null,
"e": 2150,
"s": 2117,
"text": "1. Inner class that isn’t static"
},
{
"code": null,
"e": 2717,
"s": 2150,
"text": "If you have a nested class in your application, make it a static class because static classes don’t require an implicit reference to the outer class. If you make the inner class non-static, the outer class will be active till the application is active. If your class uses a lot of memory, this can result in an OutOfMemoryError. As a result, it’s preferable to make the inner class static. In Java, you must manually make the inner class static, whereas, in Kotlin, the inner class is static by default. In Kotlin, you don’t have to worry about static inner classes."
},
{
"code": null,
"e": 2782,
"s": 2717,
"text": "2. Use of getContext() and getApplicationContext() incorrectly()"
},
{
"code": null,
"e": 3151,
"s": 2782,
"text": "In our application, we use a lot of third-party libraries, and the majority of them employ the Singleton class. If you need to give some context to a third-party library that is beyond the scope of the current activity, use getApplicationContext() rather than getContext(). Like in the Example below initialize is a static function in the library that uses the context"
},
{
"code": null,
"e": 3156,
"s": 3151,
"text": "Java"
},
{
"code": "SomeLibrary{ object companion { initializeGeeksforGeeksLib(Content context) { this.context = context.getApplicationContext() } }}",
"e": 3327,
"s": 3156,
"text": null
},
{
"code": null,
"e": 4127,
"s": 3327,
"text": "Some libraries, however, do not utilize the aforementioned notation. So, in that scenario, it will use the current activity’s context, and the current activity’s reference will be retained till the application is alive, which may result in an OutOfMemoryError (as the initialize function is static). As a result, it is preferable to utilize getApplicationContext() directly in your code rather than relying on third-party libraries. These are some of the methods for eliminating OutOfMemoryError from our application. It is preferable to write code that does not result in an OutOfMemoryError. Still, if your project is large and you’re having trouble finding the class that causes OutOfMemoryError, you can utilize Android Studio’s memory profiler to locate the classes that cause OutOfMemoryError."
},
{
"code": null,
"e": 4181,
"s": 4127,
"text": "3. Application of a static view, context, or activity"
},
{
"code": null,
"e": 4492,
"s": 4181,
"text": "OutOfMemoryError will occur if you use any static views, contexts, or activities (if your activities are dealing with lots of space). This is because the program will hold the view, context, or activity until the application is alive, and the memory used by these will not be released by the Garbage Collector."
},
{
"code": null,
"e": 4919,
"s": 4492,
"text": "Example: If you’re going to use Bitmap in some project. That project will meet the OutOfMemoryError on your mobile device if you use more than 10 photos with a size of 500KB each. The number of images that can cause an OutOfMemoryError in other situations can be greater than or fewer than 10. You may ascertain the limit by adding photos to the BitmapArray one by one until you get an OOM, which indicates the device’s limit."
},
{
"code": null,
"e": 4926,
"s": 4919,
"text": "Picked"
},
{
"code": null,
"e": 4934,
"s": 4926,
"text": "Android"
},
{
"code": null,
"e": 4942,
"s": 4934,
"text": "Android"
}
] |
Conversion of Java Maps to List
|
28 Oct, 2021
A Map is an object that maps keys to values or is a collection of attribute-value pairs. The list is an ordered collection of objects and the List can contain duplicate values. The Map has two values (a key and value), while a List only has one value (an element). So we can generate two lists as listed:
List of values and
List of keys from a Map.
Let us assume “map” is the instance of Map, henceforth as usual we all know it contains set and value pairs. so they are defined as follows:
map.values() will return a Collection of the map’s values.
map.keySet() will return a set of the map’s keys.
Methods:
Passing sets of keys inside ArrayList constructor parameterPassing collection of map values generated by map.values() method to the ArrayList constructor parameterUsing Streams API (only applicable after JDK 8 and onwards)
Passing sets of keys inside ArrayList constructor parameter
Passing collection of map values generated by map.values() method to the ArrayList constructor parameter
Using Streams API (only applicable after JDK 8 and onwards)
Let us discuss each of them
Methods 1: Passing sets of keys inside ArrayList constructor parameter
Procedure: We can convert Map keys to List of Keys bypassing set of map keys generated by map.keySet() method to the ArrayList constructor parameter as shown below
map.values(); // Now here e will pass sets of keys of our map, so it becomes
map.values(map.keySet()); // Now we just need to store it into List, so creating object
List ListofKeys = new ArrayList(map.keySet()); // Now we are done with conversion.
Syntax: Henceforth it as follows:
List ListofKeys = new ArrayList(map.keySet());
Method 2: List ListofKeys = new ArrayList(map.keySet());
We can convert Map keys to a List of Values by passing a collection of map values generated by map.values() method to ArrayList constructor parameter.
Syntax: Henceforth it is as follows:
List Listofvalues = new ArrayList(map.values());
Example
Java
// Java Program to Convert Map to List // Importing required classesimport java.util.*; class GFG { // Method 1 public static void main(String[] args) { // Creating HashMap HashMap<String, Integer> hs = new HashMap<>(); // Adding elements to hashMap hs.put("Geeks", 1); hs.put("for", 2); hs.put("Geeks", 3); hs.put("Computer", 4); hs.put("Science", 5); hs.put("Portal", 6); // Calling method MapValuesToList obj = new MapValuesToList(hs); // Storing into List List<Integer> mapvaltolist = obj.mapvaltolist(hs); // Printing via for loops for (Integer integerList : mapvaltolist) { // Printing our ArrayList System.out.println(integerList); } } // Method 2 // To convert Map to List public List<String> mapvaltolist(Map<String, Integer> map) { // Using Collection Collection<Integer> val = map.values(); // Creating an ArrayList ArrayList<Integer> al = new ArrayList<>(values); return al; }}
Output:
1
2
3
4
5
6
Method 3: Using Streams API
The stream() method returns a stream of the keys from the Set of the map keys returned by Map.keySet(). The collect() method of the Stream class collects the stream of keys in a List.The Collectors.toCollection(ArrayList::new) passed to the collect() method to collect as new ArrayList. One can also use Stream API to convert map keys and values to respective lists. the syntax is as provided below as follows:
List ListofKeys = map.keyset().stream().collect(Collectors.toCollection(ArrayList::new));
List Listofvalues= map.values().stream().collect(Collectors.toCollection(ArrayList::new));
Note: You can collect elements of Stream in an ArrayList, LinkedList, or any other List implementation.
Implementation:
Given RollNo and Student Name of N students as input. First, we create a Map where Rollno is key because Rollno is unique and Name as Value for Map then convert this map to list of values and keys respectively. Where the generated list of keys contains RollNo of students and list of Values contains Name of Students.
Example
Java
// Java program to Convert Map to List // Importing required classesimport java.util.*;// Importing stream sub-packageimport java.util.stream.*; // Main class// MapToListclass GFG { // Main driver method public static void main(String[] args) { // Scanner class to take input of key-value pairs Scanner sc = new Scanner(System.in); // Creating a Hashmap which maps rollno with student // name Map<String, String> map = new HashMap<String, String>(); // Command for better usability System.out.println("Enter No of Students"); // Taking input to Hashmap // via iterating using for loop int noOfStudents = Integer.parseInt(sc.nextLine()); for (int i = 0; i < noOfStudents; i++) { String input = sc.nextLine(); String[] studentdata = input.split(" "); String rollno = studentdata[0]; String name = studentdata[1]; // Simply inserting received pairs to Map map.put(rollno, name); } // Now first create list of keys and values List<String> ListofKeys = null; List<String> ListofValues = null; // Now converting hashMap to List of keys and values ListofKeys = map.keySet().stream().collect( Collectors.toCollection(ArrayList::new)); ListofValues = map.values().stream().collect( Collectors.toCollection(ArrayList::new)); // lastly printing List of rollno and name of // students System.out.println("List of RollNo of Students"); System.out.println(ListofKeys.toString()); System.out.println("List of Name of Students"); System.out.println(ListofValues.toString()); }}
Output:
solankimayank
surinderdawra388
akshaysingh98088
Java-Collections
java-list
Java-List-Programs
java-map
Java-Map-Programs
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Interfaces in Java
Stream In Java
ArrayList in Java
Collections in Java
Singleton Class in Java
Multidimensional Arrays in Java
Stack Class in Java
Initialize an ArrayList in Java
Introduction to Java
Initializing a List in Java
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n28 Oct, 2021"
},
{
"code": null,
"e": 333,
"s": 28,
"text": "A Map is an object that maps keys to values or is a collection of attribute-value pairs. The list is an ordered collection of objects and the List can contain duplicate values. The Map has two values (a key and value), while a List only has one value (an element). So we can generate two lists as listed:"
},
{
"code": null,
"e": 352,
"s": 333,
"text": "List of values and"
},
{
"code": null,
"e": 377,
"s": 352,
"text": "List of keys from a Map."
},
{
"code": null,
"e": 519,
"s": 377,
"text": "Let us assume “map” is the instance of Map, henceforth as usual we all know it contains set and value pairs. so they are defined as follows: "
},
{
"code": null,
"e": 578,
"s": 519,
"text": "map.values() will return a Collection of the map’s values."
},
{
"code": null,
"e": 628,
"s": 578,
"text": "map.keySet() will return a set of the map’s keys."
},
{
"code": null,
"e": 637,
"s": 628,
"text": "Methods:"
},
{
"code": null,
"e": 860,
"s": 637,
"text": "Passing sets of keys inside ArrayList constructor parameterPassing collection of map values generated by map.values() method to the ArrayList constructor parameterUsing Streams API (only applicable after JDK 8 and onwards)"
},
{
"code": null,
"e": 920,
"s": 860,
"text": "Passing sets of keys inside ArrayList constructor parameter"
},
{
"code": null,
"e": 1025,
"s": 920,
"text": "Passing collection of map values generated by map.values() method to the ArrayList constructor parameter"
},
{
"code": null,
"e": 1085,
"s": 1025,
"text": "Using Streams API (only applicable after JDK 8 and onwards)"
},
{
"code": null,
"e": 1113,
"s": 1085,
"text": "Let us discuss each of them"
},
{
"code": null,
"e": 1184,
"s": 1113,
"text": "Methods 1: Passing sets of keys inside ArrayList constructor parameter"
},
{
"code": null,
"e": 1348,
"s": 1184,
"text": "Procedure: We can convert Map keys to List of Keys bypassing set of map keys generated by map.keySet() method to the ArrayList constructor parameter as shown below"
},
{
"code": null,
"e": 1599,
"s": 1348,
"text": "map.values(); // Now here e will pass sets of keys of our map, so it becomes\nmap.values(map.keySet()); // Now we just need to store it into List, so creating object \nList ListofKeys = new ArrayList(map.keySet()); // Now we are done with conversion. "
},
{
"code": null,
"e": 1633,
"s": 1599,
"text": "Syntax: Henceforth it as follows:"
},
{
"code": null,
"e": 1680,
"s": 1633,
"text": "List ListofKeys = new ArrayList(map.keySet());"
},
{
"code": null,
"e": 1737,
"s": 1680,
"text": "Method 2: List ListofKeys = new ArrayList(map.keySet());"
},
{
"code": null,
"e": 1888,
"s": 1737,
"text": "We can convert Map keys to a List of Values by passing a collection of map values generated by map.values() method to ArrayList constructor parameter."
},
{
"code": null,
"e": 1925,
"s": 1888,
"text": "Syntax: Henceforth it is as follows:"
},
{
"code": null,
"e": 1974,
"s": 1925,
"text": "List Listofvalues = new ArrayList(map.values());"
},
{
"code": null,
"e": 1982,
"s": 1974,
"text": "Example"
},
{
"code": null,
"e": 1987,
"s": 1982,
"text": "Java"
},
{
"code": "// Java Program to Convert Map to List // Importing required classesimport java.util.*; class GFG { // Method 1 public static void main(String[] args) { // Creating HashMap HashMap<String, Integer> hs = new HashMap<>(); // Adding elements to hashMap hs.put(\"Geeks\", 1); hs.put(\"for\", 2); hs.put(\"Geeks\", 3); hs.put(\"Computer\", 4); hs.put(\"Science\", 5); hs.put(\"Portal\", 6); // Calling method MapValuesToList obj = new MapValuesToList(hs); // Storing into List List<Integer> mapvaltolist = obj.mapvaltolist(hs); // Printing via for loops for (Integer integerList : mapvaltolist) { // Printing our ArrayList System.out.println(integerList); } } // Method 2 // To convert Map to List public List<String> mapvaltolist(Map<String, Integer> map) { // Using Collection Collection<Integer> val = map.values(); // Creating an ArrayList ArrayList<Integer> al = new ArrayList<>(values); return al; }}",
"e": 3087,
"s": 1987,
"text": null
},
{
"code": null,
"e": 3095,
"s": 3087,
"text": "Output:"
},
{
"code": null,
"e": 3107,
"s": 3095,
"text": "1\n2\n3\n4\n5\n6"
},
{
"code": null,
"e": 3135,
"s": 3107,
"text": "Method 3: Using Streams API"
},
{
"code": null,
"e": 3546,
"s": 3135,
"text": "The stream() method returns a stream of the keys from the Set of the map keys returned by Map.keySet(). The collect() method of the Stream class collects the stream of keys in a List.The Collectors.toCollection(ArrayList::new) passed to the collect() method to collect as new ArrayList. One can also use Stream API to convert map keys and values to respective lists. the syntax is as provided below as follows:"
},
{
"code": null,
"e": 3636,
"s": 3546,
"text": "List ListofKeys = map.keyset().stream().collect(Collectors.toCollection(ArrayList::new));"
},
{
"code": null,
"e": 3727,
"s": 3636,
"text": "List Listofvalues= map.values().stream().collect(Collectors.toCollection(ArrayList::new));"
},
{
"code": null,
"e": 3831,
"s": 3727,
"text": "Note: You can collect elements of Stream in an ArrayList, LinkedList, or any other List implementation."
},
{
"code": null,
"e": 3847,
"s": 3831,
"text": "Implementation:"
},
{
"code": null,
"e": 4165,
"s": 3847,
"text": "Given RollNo and Student Name of N students as input. First, we create a Map where Rollno is key because Rollno is unique and Name as Value for Map then convert this map to list of values and keys respectively. Where the generated list of keys contains RollNo of students and list of Values contains Name of Students."
},
{
"code": null,
"e": 4173,
"s": 4165,
"text": "Example"
},
{
"code": null,
"e": 4178,
"s": 4173,
"text": "Java"
},
{
"code": "// Java program to Convert Map to List // Importing required classesimport java.util.*;// Importing stream sub-packageimport java.util.stream.*; // Main class// MapToListclass GFG { // Main driver method public static void main(String[] args) { // Scanner class to take input of key-value pairs Scanner sc = new Scanner(System.in); // Creating a Hashmap which maps rollno with student // name Map<String, String> map = new HashMap<String, String>(); // Command for better usability System.out.println(\"Enter No of Students\"); // Taking input to Hashmap // via iterating using for loop int noOfStudents = Integer.parseInt(sc.nextLine()); for (int i = 0; i < noOfStudents; i++) { String input = sc.nextLine(); String[] studentdata = input.split(\" \"); String rollno = studentdata[0]; String name = studentdata[1]; // Simply inserting received pairs to Map map.put(rollno, name); } // Now first create list of keys and values List<String> ListofKeys = null; List<String> ListofValues = null; // Now converting hashMap to List of keys and values ListofKeys = map.keySet().stream().collect( Collectors.toCollection(ArrayList::new)); ListofValues = map.values().stream().collect( Collectors.toCollection(ArrayList::new)); // lastly printing List of rollno and name of // students System.out.println(\"List of RollNo of Students\"); System.out.println(ListofKeys.toString()); System.out.println(\"List of Name of Students\"); System.out.println(ListofValues.toString()); }}",
"e": 5931,
"s": 4178,
"text": null
},
{
"code": null,
"e": 5939,
"s": 5931,
"text": "Output:"
},
{
"code": null,
"e": 5953,
"s": 5939,
"text": "solankimayank"
},
{
"code": null,
"e": 5970,
"s": 5953,
"text": "surinderdawra388"
},
{
"code": null,
"e": 5987,
"s": 5970,
"text": "akshaysingh98088"
},
{
"code": null,
"e": 6004,
"s": 5987,
"text": "Java-Collections"
},
{
"code": null,
"e": 6014,
"s": 6004,
"text": "java-list"
},
{
"code": null,
"e": 6033,
"s": 6014,
"text": "Java-List-Programs"
},
{
"code": null,
"e": 6042,
"s": 6033,
"text": "java-map"
},
{
"code": null,
"e": 6060,
"s": 6042,
"text": "Java-Map-Programs"
},
{
"code": null,
"e": 6065,
"s": 6060,
"text": "Java"
},
{
"code": null,
"e": 6070,
"s": 6065,
"text": "Java"
},
{
"code": null,
"e": 6087,
"s": 6070,
"text": "Java-Collections"
},
{
"code": null,
"e": 6185,
"s": 6087,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 6204,
"s": 6185,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 6219,
"s": 6204,
"text": "Stream In Java"
},
{
"code": null,
"e": 6237,
"s": 6219,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 6257,
"s": 6237,
"text": "Collections in Java"
},
{
"code": null,
"e": 6281,
"s": 6257,
"text": "Singleton Class in Java"
},
{
"code": null,
"e": 6313,
"s": 6281,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 6333,
"s": 6313,
"text": "Stack Class in Java"
},
{
"code": null,
"e": 6365,
"s": 6333,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 6386,
"s": 6365,
"text": "Introduction to Java"
}
] |
Python – Color Inversion using Pillow
|
27 May, 2022
Color Inversion (Image Negative) is the method of inverting pixel values of an image. Image inversion does not depend on the color mode of the image, i.e. inversion works on channel level. When inversion is used on a multi color image (RGB, CMYK etc) then each channel is treated separately, and the final result if formed by calibrating the results of all the channels.We would be using pillow (PIL) library for obtaining negative of an image. To install the library, execute the following command in the command-line:-
pip install pillow
Note: Several Linux distributions tend to have Python and PIL preinstalled into them.In this article, 2 methods have been described for inverting color space of an image. The first one is an inbuilt method using ImageChops.invert() function. In the second one we would be inverting the image by elementwise subtraction of pixel values. Sample Image –
Method #1:Using inbuilt method ImageChops.invert() for Negating color.
Python3
# Importing imagechops for using the invert() methodfrom PIL import Image, ImageChops # Opening the test image, and saving it's objectimg = Image.open('test.jpg') # Passing the image object to invert() inv_img = ImageChops.invert(img) # Displaying the output imageinv_img.show()
Output:
Explanation: Firstly we import the ImageChops module for using invert() method. Then we open the test image (test.jpg), and save it’s image object. Now we passed that image object to ImageDraw.invert() which returns the inverted image. At last, we displayed the color inverted image. Things to keep in mind while using ImageChops.invert():
The input Image should not contain a Alpha channel
The input image should not be of P (Paletted) color mode.
Method #2:The method used for getting the inverse of an image is subtraction of the maximum value/intensity of a pixel by the value of current pixel. The resultant value is guided by the formula –
Where INV is the resultant inverted pixel, I^MAX is the maximum intensity level in a given color mode and I(x, y) is the intensity (pixel value) of image/color channel at a particular pair of coordinates.
Python3
from PIL import Image # numpy for performing batch processing and elementwise# matrix operations efficientlyimport numpy as np # Opening an image, and saving open image objectimg = Image.open(r"sample.jpg") # Creating an numpy array out of the image objectimg_arry = np.array(img) # Maximum intensity value of the color modeI_max = 255 # Subtracting 255 (max value possible in a given image# channel) from each pixel values and storing the resultimg_arry = I_max - img_arry # Creating an image object from the resultant numpy arrayinverted_img = Image.fromarray(img_arry) # Saving the image under the name Image_negative.jpginverted_img.save(r"Image_negative.jpg")
Output:
Explanation: Firstly we import numpy into our code, as numpy allows fast elementwise operations on matrices and offers several arithmetic operations on arrays. Then we open the test image using Image.open(), and store the returned image object in the variable img. Then we create an array (img_arry) from the pixel values obtained from the opened image object (img). This is done so as to allow elementwise subtraction operation offered by the numpy library. Now we subtract 255 from each channel/pixel value, this results in all the pixel values being inverted. Now, we use this resultant matrix to create an new image (inverted_img). Finally we saved the image, under the name of Image_negative.jpg.
It should be ensured that the input image does not contain an alpha channel. This is because when the line img_arry = 255 – img_arry will execute for an image containing alpha channel, it would invert the alpha channel values as well. This would lead to inconsistency in the output image, as we may end up with completely transparent images (which is not a part of color inversion). One way to allow processing RGBA images is firstly converting them to RGB color mode using Image.convert(‘RGB’). Alternatively, we could extract the alpha channel using Image.getdata(band=3) and then later combine it to the final image to get back the original RGBA image. This input image sample.jpg is chosen intentionally of the format .jpg as a JPG/JPEG image format doesn’t support transparency or alpha channels.
Input image should not be of P (paletted) mode. As a paletted image does not contain pixel values at coordinates, but rather index to pixel values belonging to a color map (of varying sizes). Therefore, image inversion would lead to inconsistent results.
The value I_max = 255 is assigned assuming that the maximum intensity achievable in the specific image mode is 255. The value isn’t hardcoded. The value depends on the color mode, and therefore could be less then 255 (ex. 1 in bilevel image) or greater than 255 (ex. 32536 in 16 Bit Unsigned Grayscale mode).
adnanirshad158
anikaseth98
khushboogoyal499
Image-Processing
Python-pil
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": "\n27 May, 2022"
},
{
"code": null,
"e": 551,
"s": 28,
"text": "Color Inversion (Image Negative) is the method of inverting pixel values of an image. Image inversion does not depend on the color mode of the image, i.e. inversion works on channel level. When inversion is used on a multi color image (RGB, CMYK etc) then each channel is treated separately, and the final result if formed by calibrating the results of all the channels.We would be using pillow (PIL) library for obtaining negative of an image. To install the library, execute the following command in the command-line:- "
},
{
"code": null,
"e": 570,
"s": 551,
"text": "pip install pillow"
},
{
"code": null,
"e": 922,
"s": 570,
"text": "Note: Several Linux distributions tend to have Python and PIL preinstalled into them.In this article, 2 methods have been described for inverting color space of an image. The first one is an inbuilt method using ImageChops.invert() function. In the second one we would be inverting the image by elementwise subtraction of pixel values. Sample Image – "
},
{
"code": null,
"e": 994,
"s": 922,
"text": " Method #1:Using inbuilt method ImageChops.invert() for Negating color."
},
{
"code": null,
"e": 1002,
"s": 994,
"text": "Python3"
},
{
"code": "# Importing imagechops for using the invert() methodfrom PIL import Image, ImageChops # Opening the test image, and saving it's objectimg = Image.open('test.jpg') # Passing the image object to invert() inv_img = ImageChops.invert(img) # Displaying the output imageinv_img.show()",
"e": 1281,
"s": 1002,
"text": null
},
{
"code": null,
"e": 1290,
"s": 1281,
"text": "Output: "
},
{
"code": null,
"e": 1631,
"s": 1290,
"text": "Explanation: Firstly we import the ImageChops module for using invert() method. Then we open the test image (test.jpg), and save it’s image object. Now we passed that image object to ImageDraw.invert() which returns the inverted image. At last, we displayed the color inverted image. Things to keep in mind while using ImageChops.invert(): "
},
{
"code": null,
"e": 1684,
"s": 1631,
"text": "The input Image should not contain a Alpha channel "
},
{
"code": null,
"e": 1744,
"s": 1684,
"text": "The input image should not be of P (Paletted) color mode. "
},
{
"code": null,
"e": 1945,
"s": 1744,
"text": " Method #2:The method used for getting the inverse of an image is subtraction of the maximum value/intensity of a pixel by the value of current pixel. The resultant value is guided by the formula – "
},
{
"code": null,
"e": 2151,
"s": 1945,
"text": "Where INV is the resultant inverted pixel, I^MAX is the maximum intensity level in a given color mode and I(x, y) is the intensity (pixel value) of image/color channel at a particular pair of coordinates. "
},
{
"code": null,
"e": 2159,
"s": 2151,
"text": "Python3"
},
{
"code": "from PIL import Image # numpy for performing batch processing and elementwise# matrix operations efficientlyimport numpy as np # Opening an image, and saving open image objectimg = Image.open(r\"sample.jpg\") # Creating an numpy array out of the image objectimg_arry = np.array(img) # Maximum intensity value of the color modeI_max = 255 # Subtracting 255 (max value possible in a given image# channel) from each pixel values and storing the resultimg_arry = I_max - img_arry # Creating an image object from the resultant numpy arrayinverted_img = Image.fromarray(img_arry) # Saving the image under the name Image_negative.jpginverted_img.save(r\"Image_negative.jpg\")",
"e": 2825,
"s": 2159,
"text": null
},
{
"code": null,
"e": 2834,
"s": 2825,
"text": "Output: "
},
{
"code": null,
"e": 3537,
"s": 2834,
"text": "Explanation: Firstly we import numpy into our code, as numpy allows fast elementwise operations on matrices and offers several arithmetic operations on arrays. Then we open the test image using Image.open(), and store the returned image object in the variable img. Then we create an array (img_arry) from the pixel values obtained from the opened image object (img). This is done so as to allow elementwise subtraction operation offered by the numpy library. Now we subtract 255 from each channel/pixel value, this results in all the pixel values being inverted. Now, we use this resultant matrix to create an new image (inverted_img). Finally we saved the image, under the name of Image_negative.jpg. "
},
{
"code": null,
"e": 4341,
"s": 3537,
"text": "It should be ensured that the input image does not contain an alpha channel. This is because when the line img_arry = 255 – img_arry will execute for an image containing alpha channel, it would invert the alpha channel values as well. This would lead to inconsistency in the output image, as we may end up with completely transparent images (which is not a part of color inversion). One way to allow processing RGBA images is firstly converting them to RGB color mode using Image.convert(‘RGB’). Alternatively, we could extract the alpha channel using Image.getdata(band=3) and then later combine it to the final image to get back the original RGBA image. This input image sample.jpg is chosen intentionally of the format .jpg as a JPG/JPEG image format doesn’t support transparency or alpha channels. "
},
{
"code": null,
"e": 4598,
"s": 4341,
"text": "Input image should not be of P (paletted) mode. As a paletted image does not contain pixel values at coordinates, but rather index to pixel values belonging to a color map (of varying sizes). Therefore, image inversion would lead to inconsistent results. "
},
{
"code": null,
"e": 4907,
"s": 4598,
"text": "The value I_max = 255 is assigned assuming that the maximum intensity achievable in the specific image mode is 255. The value isn’t hardcoded. The value depends on the color mode, and therefore could be less then 255 (ex. 1 in bilevel image) or greater than 255 (ex. 32536 in 16 Bit Unsigned Grayscale mode)."
},
{
"code": null,
"e": 4922,
"s": 4907,
"text": "adnanirshad158"
},
{
"code": null,
"e": 4934,
"s": 4922,
"text": "anikaseth98"
},
{
"code": null,
"e": 4951,
"s": 4934,
"text": "khushboogoyal499"
},
{
"code": null,
"e": 4968,
"s": 4951,
"text": "Image-Processing"
},
{
"code": null,
"e": 4979,
"s": 4968,
"text": "Python-pil"
},
{
"code": null,
"e": 4986,
"s": 4979,
"text": "Python"
},
{
"code": null,
"e": 5084,
"s": 4986,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5102,
"s": 5084,
"text": "Python Dictionary"
},
{
"code": null,
"e": 5144,
"s": 5102,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 5166,
"s": 5144,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 5201,
"s": 5166,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 5227,
"s": 5201,
"text": "Python String | replace()"
},
{
"code": null,
"e": 5259,
"s": 5227,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 5288,
"s": 5259,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 5315,
"s": 5288,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 5345,
"s": 5315,
"text": "Iterate over a list in Python"
}
] |
Android - Button Control
|
A Button is a Push-button which can be pressed, or clicked, by the user to perform an action.
Following are the important attributes related to Button control. You can check Android official documentation for complete list of attributes and related methods which you can use to change these attributes are run time.
Inherited from android.widget.TextView Class −
android:autoText
If set, specifies that this TextView has a textual input method and automatically corrects some common spelling errors.
android:drawableBottom
This is the drawable to be drawn below the text.
android:drawableRight
This is the drawable to be drawn to the right of the text.
android:editable
If set, specifies that this TextView has an input method.
android:text
This is the Text to display.
Inherited from android.view.View Class −
android:background
This is a drawable to use as the background.
android:contentDescription
This defines text that briefly describes content of the view.
android:id
This supplies an identifier name for this view.
android:onClick
This is the name of the method in this View's context to invoke when the view is clicked.
android:visibility
This controls the initial visibility of the view.
This example will take you through simple steps to show how to create your own Android application using Linear Layout and Button.
Following is the content of the modified main activity file src/MainActivity.java. This file can include each of the fundamental lifecycle methods.
package com.example.saira_000.myapplication;
import android.content.Intent;
import android.net.Uri;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends ActionBarActivity {
Button b1,b2,b3;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b1=(Button)findViewById(R.id.button);
b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(MainActivity.this,"YOUR MESSAGE",Toast.LENGTH_LONG).show();
}
});
}
}
Following will be the content of res/layout/activity_main.xml file −
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity">
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button Control"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:textSize="30dp" />
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tutorials point"
android:textColor="#ff87ff09"
android:textSize="30dp"
android:layout_below="@+id/textView1"
android:layout_centerHorizontal="true" />
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageButton"
android:src="@drawable/abc"
android:layout_below="@+id/textView2"
android:layout_centerHorizontal="true" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/editText"
android:layout_below="@+id/imageButton"
android:layout_alignRight="@+id/imageButton"
android:layout_alignEnd="@+id/imageButton" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button"
android:id="@+id/button"
android:layout_alignTop="@+id/editText"
android:layout_alignLeft="@+id/textView1"
android:layout_alignStart="@+id/textView1"
android:layout_alignRight="@+id/editText"
android:layout_alignEnd="@+id/editText" />
</RelativeLayout>
Following will be the content of res/values/strings.xml to define these new constants −
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">myapplication</string>
</resources>
Following is the default content of AndroidManifest.xml −
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.saira_000.myapplication" >
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.guidemo4.MainActivity"
android:label="@string/app_name" >
<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 GUIDemo4 application. I assume you had created your AVD while doing environment setup. To run the app from Android Studio, open one of your project's activity files and click Run icon from the toolbar.Android Studio installs the app on your AVD and starts it and if everything is fine with your setup and application, it will display following Emulator window −
The following screen will appear by clicking on Button −
I will recommend to try above example with different attributes of Button in Layout XML file as well at programming time to have different look and feel of the Button. Try to make it editable, change to font color, font family, width, textSize etc and see the result. You can also try above example with multiple Button controls in one activity.
46 Lectures
7.5 hours
Aditya Dua
32 Lectures
3.5 hours
Sharad Kumar
9 Lectures
1 hours
Abhilash Nelson
14 Lectures
1.5 hours
Abhilash Nelson
15 Lectures
1.5 hours
Abhilash Nelson
10 Lectures
1 hours
Abhilash Nelson
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 3701,
"s": 3607,
"text": "A Button is a Push-button which can be pressed, or clicked, by the user to perform an action."
},
{
"code": null,
"e": 3923,
"s": 3701,
"text": "Following are the important attributes related to Button control. You can check Android official documentation for complete list of attributes and related methods which you can use to change these attributes are run time."
},
{
"code": null,
"e": 3970,
"s": 3923,
"text": "Inherited from android.widget.TextView Class −"
},
{
"code": null,
"e": 3987,
"s": 3970,
"text": "android:autoText"
},
{
"code": null,
"e": 4107,
"s": 3987,
"text": "If set, specifies that this TextView has a textual input method and automatically corrects some common spelling errors."
},
{
"code": null,
"e": 4130,
"s": 4107,
"text": "android:drawableBottom"
},
{
"code": null,
"e": 4179,
"s": 4130,
"text": "This is the drawable to be drawn below the text."
},
{
"code": null,
"e": 4201,
"s": 4179,
"text": "android:drawableRight"
},
{
"code": null,
"e": 4260,
"s": 4201,
"text": "This is the drawable to be drawn to the right of the text."
},
{
"code": null,
"e": 4277,
"s": 4260,
"text": "android:editable"
},
{
"code": null,
"e": 4335,
"s": 4277,
"text": "If set, specifies that this TextView has an input method."
},
{
"code": null,
"e": 4348,
"s": 4335,
"text": "android:text"
},
{
"code": null,
"e": 4377,
"s": 4348,
"text": "This is the Text to display."
},
{
"code": null,
"e": 4418,
"s": 4377,
"text": "Inherited from android.view.View Class −"
},
{
"code": null,
"e": 4437,
"s": 4418,
"text": "android:background"
},
{
"code": null,
"e": 4482,
"s": 4437,
"text": "This is a drawable to use as the background."
},
{
"code": null,
"e": 4509,
"s": 4482,
"text": "android:contentDescription"
},
{
"code": null,
"e": 4571,
"s": 4509,
"text": "This defines text that briefly describes content of the view."
},
{
"code": null,
"e": 4582,
"s": 4571,
"text": "android:id"
},
{
"code": null,
"e": 4630,
"s": 4582,
"text": "This supplies an identifier name for this view."
},
{
"code": null,
"e": 4646,
"s": 4630,
"text": "android:onClick"
},
{
"code": null,
"e": 4736,
"s": 4646,
"text": "This is the name of the method in this View's context to invoke when the view is clicked."
},
{
"code": null,
"e": 4755,
"s": 4736,
"text": "android:visibility"
},
{
"code": null,
"e": 4805,
"s": 4755,
"text": "This controls the initial visibility of the view."
},
{
"code": null,
"e": 4936,
"s": 4805,
"text": "This example will take you through simple steps to show how to create your own Android application using Linear Layout and Button."
},
{
"code": null,
"e": 5084,
"s": 4936,
"text": "Following is the content of the modified main activity file src/MainActivity.java. This file can include each of the fundamental lifecycle methods."
},
{
"code": null,
"e": 5920,
"s": 5084,
"text": "package com.example.saira_000.myapplication;\n\nimport android.content.Intent;\nimport android.net.Uri;\nimport android.support.v7.app.ActionBarActivity;\nimport android.os.Bundle;\n\nimport android.view.Menu;\nimport android.view.MenuItem;\nimport android.view.View;\n\nimport android.widget.Button;\nimport android.widget.Toast;\n\npublic class MainActivity extends ActionBarActivity {\n Button b1,b2,b3;\n \n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n \n b1=(Button)findViewById(R.id.button);\n b1.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n Toast.makeText(MainActivity.this,\"YOUR MESSAGE\",Toast.LENGTH_LONG).show();\n }\n });\n }\n}"
},
{
"code": null,
"e": 5989,
"s": 5920,
"text": "Following will be the content of res/layout/activity_main.xml file −"
},
{
"code": null,
"e": 8117,
"s": 5989,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout \n xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\" \n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\" \n android:paddingLeft=\"@dimen/activity_horizontal_margin\"\n android:paddingRight=\"@dimen/activity_horizontal_margin\"\n android:paddingTop=\"@dimen/activity_vertical_margin\"\n android:paddingBottom=\"@dimen/activity_vertical_margin\"\n tools:context=\".MainActivity\">\n \n <TextView\n android:id=\"@+id/textView1\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:text=\"Button Control\"\n android:layout_alignParentTop=\"true\"\n android:layout_centerHorizontal=\"true\"\n android:textSize=\"30dp\" />\n \n <TextView\n android:id=\"@+id/textView2\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:text=\"Tutorials point\"\n android:textColor=\"#ff87ff09\"\n android:textSize=\"30dp\"\n android:layout_below=\"@+id/textView1\"\n android:layout_centerHorizontal=\"true\" />\n \n <ImageButton\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:id=\"@+id/imageButton\"\n android:src=\"@drawable/abc\"\n android:layout_below=\"@+id/textView2\"\n android:layout_centerHorizontal=\"true\" />\n \n <EditText\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:id=\"@+id/editText\"\n android:layout_below=\"@+id/imageButton\"\n android:layout_alignRight=\"@+id/imageButton\"\n android:layout_alignEnd=\"@+id/imageButton\" />\n \n <Button\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:text=\"Button\"\n android:id=\"@+id/button\"\n android:layout_alignTop=\"@+id/editText\"\n android:layout_alignLeft=\"@+id/textView1\"\n android:layout_alignStart=\"@+id/textView1\"\n android:layout_alignRight=\"@+id/editText\"\n android:layout_alignEnd=\"@+id/editText\" />\n \n</RelativeLayout>"
},
{
"code": null,
"e": 8206,
"s": 8117,
"text": "Following will be the content of res/values/strings.xml to define these new constants −"
},
{
"code": null,
"e": 8320,
"s": 8206,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<resources>\n <string name=\"app_name\">myapplication</string>\n</resources>"
},
{
"code": null,
"e": 8379,
"s": 8320,
"text": "Following is the default content of AndroidManifest.xml −"
},
{
"code": null,
"e": 9099,
"s": 8379,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\n package=\"com.example.saira_000.myapplication\" >\n \n <application\n android:allowBackup=\"true\"\n android:icon=\"@drawable/ic_launcher\"\n android:label=\"@string/app_name\"\n android:theme=\"@style/AppTheme\" >\n \n <activity\n android:name=\"com.example.guidemo4.MainActivity\"\n android:label=\"@string/app_name\" >\n \n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n \n </activity>\n \n </application>\n</manifest>"
},
{
"code": null,
"e": 9484,
"s": 9099,
"text": "Let's try to run your GUIDemo4 application. I assume you had created your AVD while doing environment setup. To run the app from Android Studio, open one of your project's activity files and click Run icon from the toolbar.Android Studio installs the app on your AVD and starts it and if everything is fine with your setup and application, it will display following Emulator window −"
},
{
"code": null,
"e": 9541,
"s": 9484,
"text": "The following screen will appear by clicking on Button −"
},
{
"code": null,
"e": 9887,
"s": 9541,
"text": "I will recommend to try above example with different attributes of Button in Layout XML file as well at programming time to have different look and feel of the Button. Try to make it editable, change to font color, font family, width, textSize etc and see the result. You can also try above example with multiple Button controls in one activity."
},
{
"code": null,
"e": 9922,
"s": 9887,
"text": "\n 46 Lectures \n 7.5 hours \n"
},
{
"code": null,
"e": 9934,
"s": 9922,
"text": " Aditya Dua"
},
{
"code": null,
"e": 9969,
"s": 9934,
"text": "\n 32 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 9983,
"s": 9969,
"text": " Sharad Kumar"
},
{
"code": null,
"e": 10015,
"s": 9983,
"text": "\n 9 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 10032,
"s": 10015,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 10067,
"s": 10032,
"text": "\n 14 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 10084,
"s": 10067,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 10119,
"s": 10084,
"text": "\n 15 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 10136,
"s": 10119,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 10169,
"s": 10136,
"text": "\n 10 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 10186,
"s": 10169,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 10193,
"s": 10186,
"text": " Print"
},
{
"code": null,
"e": 10204,
"s": 10193,
"text": " Add Notes"
}
] |
Eigenvalues and Eigenvectors in MATLAB - GeeksforGeeks
|
20 Nov, 2021
Eigenvalues and Eigenvectors are properties of a square matrix.
Let is an N*N matrix, X be a vector of size N*1 and be a scalar.
Then the values X, satisfying the equation are eigenvectors and eigenvalues of matrix A respectively.
A matrix of size N*N possess N eigenvalues
Every eigenvalue corresponds to an eigenvector.
Matlab allows the users to find eigenvalues and eigenvectors of matrix using eig() method. Different syntaxes of eig() method are:
e = eig(A)
[V,D] = eig(A)
[V,D,W] = eig(A)
e = eig(A,B)
Let us discuss the above syntaxes in detail:
It returns the vector of eigenvalues of square matrix A.
Matlab
% Square matrix of size 3*3
A = [0 1 2;
1 0 -1;
2 -1 0];
disp("Matrix");
disp(A);
% Eigenvalues of matrix A
e = eig(A);
disp("Eigenvalues");
disp(e);
Output :
It returns the diagonal matrix D having diagonals as eigenvalues.
It also returns the matrix of right vectors as V.
Normal eigenvectors are termed as right eigenvectors.
V is a collection of N eigenvectors of each N*1 size(A is N*N size) that satisfies A*V = V*D
Matlab
% Square matrix of size 3*3
A = [8 -6 2;
-6 7 -4;
2 -4 3];
disp("Matrix");
disp(A);
% Eigenvalues and right eigenvectors of matrix A
[V,D] = eig(A);
disp("Diagonal matrix of Eigenvalues");
disp(D);
disp("Right eigenvectors")
disp(V);
Output :
Along with the diagonal matrix of eigenvalues D and right eigenvectors V, it also returns the left eigenvectors of matrix A.
A left eigenvector u is a 1*N matrix that satisfies the equation u*A = k*u, where k is a left eigenvalue of matrix A.
W is the collection of N left eigenvectors of A that satisfies W’*A = D*W’.
Matlab
% Square matrix of size 3*3
A = [10 -6 2;
-6 7 -4;
2 -4 3];
disp("Matrix :");
disp(A);
% Eigenvalues and right and left eigenvectors
% of matrix A
[V,D,W] = eig(A);
disp("Diagonal matrix of Eigenvalues :");
disp(D);
disp("Right eigenvectors :")
disp(V);
disp("Left eigenvectors :")
disp(W);
Output :
It returns the generalized eigenvalues of two square matrices A and B of the same size.
A generalized eigenvalue λ and a corresponding eigenvector v satisfy Av=λBv.
Matlab
% Square matrix A and B of size 3*3
A = [10 -6 2;
-6 7 -4;
2 -4 3];
B = [8 6 1;
6 17 2;
-1 4 3];
disp("Matrix A:");
disp(A);
disp("Matrix B:");
disp(B);
% Generalized eigen values
% of matrices A and B
e = eig(A,B);
disp("Generalized eigenvalues :")
disp(e);
Output :
surindertarika1234
Picked
Advanced Computer Subject
MATLAB
Matrix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Copying Files to and from Docker Containers
Principal Component Analysis with Python
Fuzzy Logic | Introduction
Classifying data using Support Vector Machines(SVMs) in Python
How to create a REST API using Java Spring Boot
How to Find Index of Element in Array in MATLAB?
Edge detection using Prewitt, Scharr and Sobel Operator
Image Sharpening Using Laplacian Filter and High Boost Filtering in MATLAB
Simpson's Rule in MATLAB
Installing MATLAB on Linux
|
[
{
"code": null,
"e": 24378,
"s": 24347,
"text": " \n20 Nov, 2021\n"
},
{
"code": null,
"e": 24442,
"s": 24378,
"text": "Eigenvalues and Eigenvectors are properties of a square matrix."
},
{
"code": null,
"e": 24508,
"s": 24442,
"text": "Let is an N*N matrix, X be a vector of size N*1 and be a scalar."
},
{
"code": null,
"e": 24614,
"s": 24508,
"text": "Then the values X, satisfying the equation are eigenvectors and eigenvalues of matrix A respectively."
},
{
"code": null,
"e": 24657,
"s": 24614,
"text": "A matrix of size N*N possess N eigenvalues"
},
{
"code": null,
"e": 24705,
"s": 24657,
"text": "Every eigenvalue corresponds to an eigenvector."
},
{
"code": null,
"e": 24836,
"s": 24705,
"text": "Matlab allows the users to find eigenvalues and eigenvectors of matrix using eig() method. Different syntaxes of eig() method are:"
},
{
"code": null,
"e": 24847,
"s": 24836,
"text": "e = eig(A)"
},
{
"code": null,
"e": 24862,
"s": 24847,
"text": "[V,D] = eig(A)"
},
{
"code": null,
"e": 24879,
"s": 24862,
"text": "[V,D,W] = eig(A)"
},
{
"code": null,
"e": 24892,
"s": 24879,
"text": "e = eig(A,B)"
},
{
"code": null,
"e": 24937,
"s": 24892,
"text": "Let us discuss the above syntaxes in detail:"
},
{
"code": null,
"e": 24994,
"s": 24937,
"text": "It returns the vector of eigenvalues of square matrix A."
},
{
"code": null,
"e": 25001,
"s": 24994,
"text": "Matlab"
},
{
"code": "\n\n\n\n\n\n\n% Square matrix of size 3*3 \nA = [0 1 2; \n 1 0 -1; \n 2 -1 0]; \ndisp(\"Matrix\"); \ndisp(A); \n \n% Eigenvalues of matrix A \ne = eig(A); \ndisp(\"Eigenvalues\"); \ndisp(e);\n\n\n\n\n\n",
"e": 25194,
"s": 25011,
"text": null
},
{
"code": null,
"e": 25203,
"s": 25194,
"text": "Output :"
},
{
"code": null,
"e": 25269,
"s": 25203,
"text": "It returns the diagonal matrix D having diagonals as eigenvalues."
},
{
"code": null,
"e": 25319,
"s": 25269,
"text": "It also returns the matrix of right vectors as V."
},
{
"code": null,
"e": 25373,
"s": 25319,
"text": "Normal eigenvectors are termed as right eigenvectors."
},
{
"code": null,
"e": 25466,
"s": 25373,
"text": "V is a collection of N eigenvectors of each N*1 size(A is N*N size) that satisfies A*V = V*D"
},
{
"code": null,
"e": 25473,
"s": 25466,
"text": "Matlab"
},
{
"code": "\n\n\n\n\n\n\n% Square matrix of size 3*3 \nA = [8 -6 2; \n -6 7 -4; \n 2 -4 3]; \ndisp(\"Matrix\"); \ndisp(A); \n \n% Eigenvalues and right eigenvectors of matrix A \n[V,D] = eig(A); \ndisp(\"Diagonal matrix of Eigenvalues\"); \ndisp(D); \ndisp(\"Right eigenvectors\") \ndisp(V);\n\n\n\n\n\n",
"e": 25752,
"s": 25483,
"text": null
},
{
"code": null,
"e": 25761,
"s": 25752,
"text": "Output :"
},
{
"code": null,
"e": 25886,
"s": 25761,
"text": "Along with the diagonal matrix of eigenvalues D and right eigenvectors V, it also returns the left eigenvectors of matrix A."
},
{
"code": null,
"e": 26004,
"s": 25886,
"text": "A left eigenvector u is a 1*N matrix that satisfies the equation u*A = k*u, where k is a left eigenvalue of matrix A."
},
{
"code": null,
"e": 26080,
"s": 26004,
"text": "W is the collection of N left eigenvectors of A that satisfies W’*A = D*W’."
},
{
"code": null,
"e": 26087,
"s": 26080,
"text": "Matlab"
},
{
"code": "\n\n\n\n\n\n\n% Square matrix of size 3*3 \nA = [10 -6 2; \n -6 7 -4; \n 2 -4 3]; \ndisp(\"Matrix :\"); \ndisp(A); \n \n% Eigenvalues and right and left eigenvectors \n% of matrix A \n[V,D,W] = eig(A); \ndisp(\"Diagonal matrix of Eigenvalues :\"); \ndisp(D); \ndisp(\"Right eigenvectors :\") \ndisp(V); \ndisp(\"Left eigenvectors :\") \ndisp(W);\n\n\n\n\n\n",
"e": 26428,
"s": 26097,
"text": null
},
{
"code": null,
"e": 26437,
"s": 26428,
"text": "Output :"
},
{
"code": null,
"e": 26525,
"s": 26437,
"text": "It returns the generalized eigenvalues of two square matrices A and B of the same size."
},
{
"code": null,
"e": 26602,
"s": 26525,
"text": "A generalized eigenvalue λ and a corresponding eigenvector v satisfy Av=λBv."
},
{
"code": null,
"e": 26609,
"s": 26602,
"text": "Matlab"
},
{
"code": "\n\n\n\n\n\n\n% Square matrix A and B of size 3*3 \nA = [10 -6 2; \n -6 7 -4; \n 2 -4 3]; \nB = [8 6 1; \n 6 17 2; \n -1 4 3]; \n \ndisp(\"Matrix A:\"); \ndisp(A); \ndisp(\"Matrix B:\"); \ndisp(B); \n \n% Generalized eigen values \n% of matrices A and B \ne = eig(A,B); \ndisp(\"Generalized eigenvalues :\") \ndisp(e);\n\n\n\n\n\n",
"e": 26935,
"s": 26619,
"text": null
},
{
"code": null,
"e": 26944,
"s": 26935,
"text": "Output :"
},
{
"code": null,
"e": 26963,
"s": 26944,
"text": "surindertarika1234"
},
{
"code": null,
"e": 26972,
"s": 26963,
"text": "\nPicked\n"
},
{
"code": null,
"e": 27000,
"s": 26972,
"text": "\nAdvanced Computer Subject\n"
},
{
"code": null,
"e": 27009,
"s": 27000,
"text": "\nMATLAB\n"
},
{
"code": null,
"e": 27018,
"s": 27009,
"text": "\nMatrix\n"
},
{
"code": null,
"e": 27223,
"s": 27018,
"text": "Writing code in comment? \n Please use ide.geeksforgeeks.org, \n generate link and share the link here.\n "
},
{
"code": null,
"e": 27267,
"s": 27223,
"text": "Copying Files to and from Docker Containers"
},
{
"code": null,
"e": 27308,
"s": 27267,
"text": "Principal Component Analysis with Python"
},
{
"code": null,
"e": 27335,
"s": 27308,
"text": "Fuzzy Logic | Introduction"
},
{
"code": null,
"e": 27398,
"s": 27335,
"text": "Classifying data using Support Vector Machines(SVMs) in Python"
},
{
"code": null,
"e": 27446,
"s": 27398,
"text": "How to create a REST API using Java Spring Boot"
},
{
"code": null,
"e": 27495,
"s": 27446,
"text": "How to Find Index of Element in Array in MATLAB?"
},
{
"code": null,
"e": 27551,
"s": 27495,
"text": "Edge detection using Prewitt, Scharr and Sobel Operator"
},
{
"code": null,
"e": 27626,
"s": 27551,
"text": "Image Sharpening Using Laplacian Filter and High Boost Filtering in MATLAB"
},
{
"code": null,
"e": 27651,
"s": 27626,
"text": "Simpson's Rule in MATLAB"
}
] |
Introduction of Finite Automata - GeeksforGeeks
|
06 Oct, 2021
Finite Automata(FA) is the simplest machine to recognize patterns. The finite automata or finite state machine is an abstract machine that has five elements or tuples. It has a set of states and rules for moving from one state to another but it depends upon the applied input symbol. Basically, it is an abstract model of a digital computer. The following figure shows some essential features of general automation.
Figure: Features of Finite Automata
The above figure shows the following features of automata:
InputOutputStates of automataState relationOutput relation
Input
Output
States of automata
State relation
Output relation
A Finite Automata consists of the following :
Q : Finite set of states.
Σ : set of Input Symbols.
q : Initial state.
F : set of Final States.
δ : Transition Function.
Formal specification of machine is
{ Q, Σ, q, F, δ }
FA is characterized into two types:
1) Deterministic Finite Automata (DFA) –
DFA consists of 5 tuples {Q, Σ, q, F, δ}.
Q : set of all states.
Σ : set of input symbols. ( Symbols which machine takes as input )
q : Initial state. ( Starting state of a machine )
F : set of final state.
δ : Transition Function, defined as δ : Q X Σ --> Q.
In a DFA, for a particular input character, the machine goes to one state only. A transition function is defined on every state for every input symbol. Also in DFA null (or ε) move is not allowed, i.e., DFA cannot change state without any input character.
For example, below DFA with Σ = {0, 1} accepts all strings ending with 0.
Figure: DFA with Σ = {0, 1}
One important thing to note is, there can be many possible DFAs for a pattern. A DFA with a minimum number of states is generally preferred.
2) Nondeterministic Finite Automata(NFA) NFA is similar to DFA except following additional features:
Null (or ε) move is allowed i.e., it can move forward without reading symbols. Ability to transmit to any number of states for a particular input.
Null (or ε) move is allowed i.e., it can move forward without reading symbols.
Ability to transmit to any number of states for a particular input.
However, these above features don’t add any power to NFA. If we compare both in terms of power, both are equivalent.
Due to the above additional features, NFA has a different transition function, the rest is the same as DFA.
δ: Transition Function
δ: Q X (Σ U ε ) --> 2 ^ Q.
As you can see in the transition function is for any input including null (or ε), NFA can go to any state number of states. For example, below is an NFA for the above problem.
NFA
One important thing to note is, in NFA, if any path for an input string leads to a final state, then the input string is accepted. For example, in the above NFA, there are multiple paths for the input string “00”. Since one of the paths leads to a final state, “00” is accepted by the above NFA.
Some Important Points:
Justification:
In case of DFA
δ : Q X Σ --> Q
In case of NFA
δ : Q X Σ --> 2Q
Now if you observe you’ll find out Q X Σ –> Q is part of Q X Σ –> 2Q.
On the RHS side, Q is the subset of 2Q which indicates Q is contained in 2Q or Q is a part of 2Q, however, the reverse isn’t true. So mathematically, we can conclude that every DFA is NFA but not vice-versa. Yet there is a way to convert an NFA to DFA, so there exists an equivalent DFA for every NFA.
Both NFA and DFA have the same power and each NFA can be translated into a DFA. There can be multiple final states in both DFA and NFA. NFA is more of a theoretical concept. DFA is used in Lexical Analysis in Compiler.
Both NFA and DFA have the same power and each NFA can be translated into a DFA.
There can be multiple final states in both DFA and NFA.
NFA is more of a theoretical concept.
DFA is used in Lexical Analysis in Compiler.
See Quiz on Regular Expression and Finite Automata.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
Abhishek_Rai_96
VaibhavRai3
JanviMahajan14
ssatyanand7
itskawal2000
DhruvinSoni
niharikatanwar61
Theory of Computation & Automata
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between DFA and NFA
Closure properties of Regular languages
Design 101 sequence detector (Mealy machine)
Regular expression to ∈-NFA
Boyer-Moore Majority Voting Algorithm
Conversion of Epsilon-NFA to NFA
CYK Algorithm for Context Free Grammar
Removal of ambiguity (Converting an Ambiguous grammar into Unambiguous grammar)
Introduction To Grammar in Theory of Computation
Removing Direct and Indirect Left Recursion in a Grammar
|
[
{
"code": null,
"e": 29443,
"s": 29415,
"text": "\n06 Oct, 2021"
},
{
"code": null,
"e": 29859,
"s": 29443,
"text": "Finite Automata(FA) is the simplest machine to recognize patterns. The finite automata or finite state machine is an abstract machine that has five elements or tuples. It has a set of states and rules for moving from one state to another but it depends upon the applied input symbol. Basically, it is an abstract model of a digital computer. The following figure shows some essential features of general automation."
},
{
"code": null,
"e": 29895,
"s": 29859,
"text": "Figure: Features of Finite Automata"
},
{
"code": null,
"e": 29954,
"s": 29895,
"text": "The above figure shows the following features of automata:"
},
{
"code": null,
"e": 30014,
"s": 29954,
"text": "InputOutputStates of automataState relationOutput relation "
},
{
"code": null,
"e": 30020,
"s": 30014,
"text": "Input"
},
{
"code": null,
"e": 30027,
"s": 30020,
"text": "Output"
},
{
"code": null,
"e": 30046,
"s": 30027,
"text": "States of automata"
},
{
"code": null,
"e": 30061,
"s": 30046,
"text": "State relation"
},
{
"code": null,
"e": 30078,
"s": 30061,
"text": "Output relation "
},
{
"code": null,
"e": 30125,
"s": 30078,
"text": "A Finite Automata consists of the following : "
},
{
"code": null,
"e": 30246,
"s": 30125,
"text": "Q : Finite set of states.\nΣ : set of Input Symbols.\nq : Initial state.\nF : set of Final States.\nδ : Transition Function."
},
{
"code": null,
"e": 30282,
"s": 30246,
"text": "Formal specification of machine is "
},
{
"code": null,
"e": 30300,
"s": 30282,
"text": "{ Q, Σ, q, F, δ }"
},
{
"code": null,
"e": 30337,
"s": 30300,
"text": "FA is characterized into two types: "
},
{
"code": null,
"e": 30378,
"s": 30337,
"text": "1) Deterministic Finite Automata (DFA) –"
},
{
"code": null,
"e": 30639,
"s": 30378,
"text": "DFA consists of 5 tuples {Q, Σ, q, F, δ}. \nQ : set of all states.\nΣ : set of input symbols. ( Symbols which machine takes as input )\nq : Initial state. ( Starting state of a machine )\nF : set of final state.\nδ : Transition Function, defined as δ : Q X Σ --> Q."
},
{
"code": null,
"e": 30896,
"s": 30639,
"text": "In a DFA, for a particular input character, the machine goes to one state only. A transition function is defined on every state for every input symbol. Also in DFA null (or ε) move is not allowed, i.e., DFA cannot change state without any input character. "
},
{
"code": null,
"e": 30972,
"s": 30896,
"text": "For example, below DFA with Σ = {0, 1} accepts all strings ending with 0. "
},
{
"code": null,
"e": 31002,
"s": 30972,
"text": "Figure: DFA with Σ = {0, 1} "
},
{
"code": null,
"e": 31144,
"s": 31002,
"text": "One important thing to note is, there can be many possible DFAs for a pattern. A DFA with a minimum number of states is generally preferred. "
},
{
"code": null,
"e": 31246,
"s": 31144,
"text": "2) Nondeterministic Finite Automata(NFA) NFA is similar to DFA except following additional features: "
},
{
"code": null,
"e": 31394,
"s": 31246,
"text": "Null (or ε) move is allowed i.e., it can move forward without reading symbols. Ability to transmit to any number of states for a particular input. "
},
{
"code": null,
"e": 31474,
"s": 31394,
"text": "Null (or ε) move is allowed i.e., it can move forward without reading symbols. "
},
{
"code": null,
"e": 31543,
"s": 31474,
"text": "Ability to transmit to any number of states for a particular input. "
},
{
"code": null,
"e": 31661,
"s": 31543,
"text": "However, these above features don’t add any power to NFA. If we compare both in terms of power, both are equivalent. "
},
{
"code": null,
"e": 31770,
"s": 31661,
"text": "Due to the above additional features, NFA has a different transition function, the rest is the same as DFA. "
},
{
"code": null,
"e": 31822,
"s": 31770,
"text": "δ: Transition Function\nδ: Q X (Σ U ε ) --> 2 ^ Q. "
},
{
"code": null,
"e": 32000,
"s": 31822,
"text": "As you can see in the transition function is for any input including null (or ε), NFA can go to any state number of states. For example, below is an NFA for the above problem. "
},
{
"code": null,
"e": 32004,
"s": 32000,
"text": "NFA"
},
{
"code": null,
"e": 32301,
"s": 32004,
"text": "One important thing to note is, in NFA, if any path for an input string leads to a final state, then the input string is accepted. For example, in the above NFA, there are multiple paths for the input string “00”. Since one of the paths leads to a final state, “00” is accepted by the above NFA. "
},
{
"code": null,
"e": 32325,
"s": 32301,
"text": "Some Important Points: "
},
{
"code": null,
"e": 32341,
"s": 32325,
"text": "Justification: "
},
{
"code": null,
"e": 32404,
"s": 32341,
"text": "In case of DFA\nδ : Q X Σ --> Q\nIn case of NFA\nδ : Q X Σ --> 2Q"
},
{
"code": null,
"e": 32474,
"s": 32404,
"text": "Now if you observe you’ll find out Q X Σ –> Q is part of Q X Σ –> 2Q."
},
{
"code": null,
"e": 32778,
"s": 32474,
"text": "On the RHS side, Q is the subset of 2Q which indicates Q is contained in 2Q or Q is a part of 2Q, however, the reverse isn’t true. So mathematically, we can conclude that every DFA is NFA but not vice-versa. Yet there is a way to convert an NFA to DFA, so there exists an equivalent DFA for every NFA. "
},
{
"code": null,
"e": 32999,
"s": 32778,
"text": "Both NFA and DFA have the same power and each NFA can be translated into a DFA. There can be multiple final states in both DFA and NFA. NFA is more of a theoretical concept. DFA is used in Lexical Analysis in Compiler. "
},
{
"code": null,
"e": 33080,
"s": 32999,
"text": "Both NFA and DFA have the same power and each NFA can be translated into a DFA. "
},
{
"code": null,
"e": 33137,
"s": 33080,
"text": "There can be multiple final states in both DFA and NFA. "
},
{
"code": null,
"e": 33176,
"s": 33137,
"text": "NFA is more of a theoretical concept. "
},
{
"code": null,
"e": 33223,
"s": 33176,
"text": "DFA is used in Lexical Analysis in Compiler. "
},
{
"code": null,
"e": 33276,
"s": 33223,
"text": "See Quiz on Regular Expression and Finite Automata. "
},
{
"code": null,
"e": 33401,
"s": 33276,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above "
},
{
"code": null,
"e": 33417,
"s": 33401,
"text": "Abhishek_Rai_96"
},
{
"code": null,
"e": 33429,
"s": 33417,
"text": "VaibhavRai3"
},
{
"code": null,
"e": 33444,
"s": 33429,
"text": "JanviMahajan14"
},
{
"code": null,
"e": 33456,
"s": 33444,
"text": "ssatyanand7"
},
{
"code": null,
"e": 33469,
"s": 33456,
"text": "itskawal2000"
},
{
"code": null,
"e": 33481,
"s": 33469,
"text": "DhruvinSoni"
},
{
"code": null,
"e": 33498,
"s": 33481,
"text": "niharikatanwar61"
},
{
"code": null,
"e": 33531,
"s": 33498,
"text": "Theory of Computation & Automata"
},
{
"code": null,
"e": 33629,
"s": 33531,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 33638,
"s": 33629,
"text": "Comments"
},
{
"code": null,
"e": 33651,
"s": 33638,
"text": "Old Comments"
},
{
"code": null,
"e": 33682,
"s": 33651,
"text": "Difference between DFA and NFA"
},
{
"code": null,
"e": 33722,
"s": 33682,
"text": "Closure properties of Regular languages"
},
{
"code": null,
"e": 33767,
"s": 33722,
"text": "Design 101 sequence detector (Mealy machine)"
},
{
"code": null,
"e": 33795,
"s": 33767,
"text": "Regular expression to ∈-NFA"
},
{
"code": null,
"e": 33833,
"s": 33795,
"text": "Boyer-Moore Majority Voting Algorithm"
},
{
"code": null,
"e": 33866,
"s": 33833,
"text": "Conversion of Epsilon-NFA to NFA"
},
{
"code": null,
"e": 33905,
"s": 33866,
"text": "CYK Algorithm for Context Free Grammar"
},
{
"code": null,
"e": 33985,
"s": 33905,
"text": "Removal of ambiguity (Converting an Ambiguous grammar into Unambiguous grammar)"
},
{
"code": null,
"e": 34034,
"s": 33985,
"text": "Introduction To Grammar in Theory of Computation"
}
] |
How to delete the azure blob (File) using Azure CLI in PowerShell?
|
To delete the Azure blob using Azure CLI, we can use “az storage blob” command with the “delete” parameter. Before running this command, we first need to make sure that the azure account is connected (az login) and the proper subscription is set (az account set).
To work with the azure storage account we need to authenticate to the storage. We can use storage key or the storage connections string. Here, we have shown how to retrieve the connections string.
$storageaccount = 'az204storage05june'
$connectionstring = az storage account show-connection-string -
n $storageaccount -otsv
The below command will delete the azure storage blob named ‘Test1.txt’ from the storage container container1.
az storage blob delete --account-name $storageaccount `
--container-name 'container1' `
--name 'Test1.txt' `
--connection-string $connectionstring --verbose
|
[
{
"code": null,
"e": 1326,
"s": 1062,
"text": "To delete the Azure blob using Azure CLI, we can use “az storage blob” command with the “delete” parameter. Before running this command, we first need to make sure that the azure account is connected (az login) and the proper subscription is set (az account set)."
},
{
"code": null,
"e": 1523,
"s": 1326,
"text": "To work with the azure storage account we need to authenticate to the storage. We can use storage key or the storage connections string. Here, we have shown how to retrieve the connections string."
},
{
"code": null,
"e": 1650,
"s": 1523,
"text": "$storageaccount = 'az204storage05june'\n$connectionstring = az storage account show-connection-string -\nn $storageaccount -otsv"
},
{
"code": null,
"e": 1760,
"s": 1650,
"text": "The below command will delete the azure storage blob named ‘Test1.txt’ from the storage container container1."
},
{
"code": null,
"e": 1926,
"s": 1760,
"text": "az storage blob delete --account-name $storageaccount `\n --container-name 'container1' `\n --name 'Test1.txt' `\n --connection-string $connectionstring --verbose"
}
] |
TypeScript - Objects
|
An object is an instance which contains set of key value pairs. The values can be scalar values or functions or even array of other objects. The syntax is given below −
var object_name = {
key1: “value1”, //scalar value
key2: “value”,
key3: function() {
//functions
},
key4:[“content1”, “content2”] //collection
};
As shown above, an object can contain scalar values, functions and structures like arrays and tuples.
var person = {
firstname:"Tom",
lastname:"Hanks"
};
//access the object values
console.log(person.firstname)
console.log(person.lastname)
On compiling, it will generate the same code in JavaScript.
The output of the above code is as follows −
Tom
Hanks
Let’s say you created an object literal in JavaScript as −
var person = {
firstname:"Tom",
lastname:"Hanks"
};
In case you want to add some value to an object, JavaScript allows you to make the necessary modification. Suppose we need to add a function to the person object later this is the way you can do this.
person.sayHello = function(){ return "hello";}
If you use the same code in Typescript the compiler gives an error. This is because in Typescript, concrete objects should have a type template. Objects in Typescript must be an instance of a particular type.
You can solve this by using a method template in declaration.
var person = {
firstName:"Tom",
lastName:"Hanks",
sayHello:function() { } //Type template
}
person.sayHello = function() {
console.log("hello "+person.firstName)
}
person.sayHello()
On compiling, it will generate the same code in JavaScript.
The output of the above code is as follows −
hello Tom
Objects can also be passed as parameters to function.
var person = {
firstname:"Tom",
lastname:"Hanks"
};
var invokeperson = function(obj: { firstname:string, lastname :string }) {
console.log("first name :"+obj.firstname)
console.log("last name :"+obj.lastname)
}
invokeperson(person)
The example declares an object literal. The function expression is invoked passing person object.
On compiling, it will generate following JavaScript code.
//Generated by typescript 1.8.10
var person = {
firstname: "Tom",
lastname: "Hanks"
};
var invokeperson = function (obj) {
console.log("first name :" + obj.firstname);
console.log("last name :" + obj.lastname);
};
invokeperson(person);
Its output is as follows −
first name :Tom
last name :Hanks
You can create and pass an anonymous object on the fly.
var invokeperson = function(obj:{ firstname:string, lastname :string}) {
console.log("first name :"+obj.firstname)
console.log("last name :"+obj.lastname)
}
invokeperson({firstname:"Sachin",lastname:"Tendulkar"});
On compiling, it will generate following JavaScript code.
//Generated by typescript 1.8.10
var invokeperson = function (obj) {
console.log("first name :" + obj.firstname);
console.log("last name :" + obj.lastname);
};
invokeperson({ firstname: "Sachin", lastname: "Tendulkar" });
invokeperson({ firstname: "Sachin", lastname: "Tendulkar" });
Its output is as follows −
first name :Sachin
last name :Tendulkar
In duck-typing, two objects are considered to be of the same type if both share the same set of properties. Duck-typing verifies the presence of certain properties in the objects, rather than their actual type, to check their suitability. The concept is generally explained by the following phrase −
“When I see a bird that walks like a duck and swims like a duck and quacks like a duck, I call that bird a duck.”
The TypeScript compiler implements the duck-typing system that allows object creation on the fly while keeping type safety. The following example shows how we can pass objects that don’t explicitly implement an interface but contain all of the required members to a function.
interface IPoint {
x:number
y:number
}
function addPoints(p1:IPoint,p2:IPoint):IPoint {
var x = p1.x + p2.x
var y = p1.y + p2.y
return {x:x,y:y}
}
//Valid
var newPoint = addPoints({x:3,y:4},{x:5,y:1})
//Error
var newPoint2 = addPoints({x:1},{x:4,y:3})
45 Lectures
4 hours
Antonio Papa
41 Lectures
7 hours
Haider Malik
60 Lectures
2.5 hours
Skillbakerystudios
77 Lectures
8 hours
Sean Bradley
77 Lectures
3.5 hours
TELCOMA Global
19 Lectures
3 hours
Christopher Frewin
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2217,
"s": 2048,
"text": "An object is an instance which contains set of key value pairs. The values can be scalar values or functions or even array of other objects. The syntax is given below −"
},
{
"code": null,
"e": 2393,
"s": 2217,
"text": "var object_name = { \n key1: “value1”, //scalar value \n key2: “value”, \n key3: function() {\n //functions \n }, \n key4:[“content1”, “content2”] //collection \n};\n"
},
{
"code": null,
"e": 2495,
"s": 2393,
"text": "As shown above, an object can contain scalar values, functions and structures like arrays and tuples."
},
{
"code": null,
"e": 2646,
"s": 2495,
"text": "var person = { \n firstname:\"Tom\", \n lastname:\"Hanks\" \n}; \n//access the object values \nconsole.log(person.firstname) \nconsole.log(person.lastname)\n"
},
{
"code": null,
"e": 2706,
"s": 2646,
"text": "On compiling, it will generate the same code in JavaScript."
},
{
"code": null,
"e": 2751,
"s": 2706,
"text": "The output of the above code is as follows −"
},
{
"code": null,
"e": 2763,
"s": 2751,
"text": "Tom \nHanks\n"
},
{
"code": null,
"e": 2822,
"s": 2763,
"text": "Let’s say you created an object literal in JavaScript as −"
},
{
"code": null,
"e": 2884,
"s": 2822,
"text": "var person = { \n firstname:\"Tom\", \n lastname:\"Hanks\" \n};\n"
},
{
"code": null,
"e": 3085,
"s": 2884,
"text": "In case you want to add some value to an object, JavaScript allows you to make the necessary modification. Suppose we need to add a function to the person object later this is the way you can do this."
},
{
"code": null,
"e": 3133,
"s": 3085,
"text": "person.sayHello = function(){ return \"hello\";}\n"
},
{
"code": null,
"e": 3342,
"s": 3133,
"text": "If you use the same code in Typescript the compiler gives an error. This is because in Typescript, concrete objects should have a type template. Objects in Typescript must be an instance of a particular type."
},
{
"code": null,
"e": 3404,
"s": 3342,
"text": "You can solve this by using a method template in declaration."
},
{
"code": null,
"e": 3609,
"s": 3404,
"text": "var person = {\n firstName:\"Tom\", \n lastName:\"Hanks\", \n sayHello:function() { } //Type template \n} \nperson.sayHello = function() { \n console.log(\"hello \"+person.firstName)\n} \nperson.sayHello()\n"
},
{
"code": null,
"e": 3669,
"s": 3609,
"text": "On compiling, it will generate the same code in JavaScript."
},
{
"code": null,
"e": 3714,
"s": 3669,
"text": "The output of the above code is as follows −"
},
{
"code": null,
"e": 3725,
"s": 3714,
"text": "hello Tom\n"
},
{
"code": null,
"e": 3779,
"s": 3725,
"text": "Objects can also be passed as parameters to function."
},
{
"code": null,
"e": 4032,
"s": 3779,
"text": "var person = { \n firstname:\"Tom\", \n lastname:\"Hanks\" \n}; \nvar invokeperson = function(obj: { firstname:string, lastname :string }) { \n console.log(\"first name :\"+obj.firstname) \n console.log(\"last name :\"+obj.lastname) \n} \ninvokeperson(person)\n"
},
{
"code": null,
"e": 4130,
"s": 4032,
"text": "The example declares an object literal. The function expression is invoked passing person object."
},
{
"code": null,
"e": 4188,
"s": 4130,
"text": "On compiling, it will generate following JavaScript code."
},
{
"code": null,
"e": 4439,
"s": 4188,
"text": "//Generated by typescript 1.8.10\nvar person = {\n firstname: \"Tom\",\n lastname: \"Hanks\"\n};\n\nvar invokeperson = function (obj) {\n console.log(\"first name :\" + obj.firstname);\n console.log(\"last name :\" + obj.lastname);\n};\n\ninvokeperson(person);\n"
},
{
"code": null,
"e": 4466,
"s": 4439,
"text": "Its output is as follows −"
},
{
"code": null,
"e": 4501,
"s": 4466,
"text": "first name :Tom \nlast name :Hanks\n"
},
{
"code": null,
"e": 4557,
"s": 4501,
"text": "You can create and pass an anonymous object on the fly."
},
{
"code": null,
"e": 4782,
"s": 4557,
"text": "var invokeperson = function(obj:{ firstname:string, lastname :string}) { \n console.log(\"first name :\"+obj.firstname) \n console.log(\"last name :\"+obj.lastname) \n} \ninvokeperson({firstname:\"Sachin\",lastname:\"Tendulkar\"});\n"
},
{
"code": null,
"e": 4840,
"s": 4782,
"text": "On compiling, it will generate following JavaScript code."
},
{
"code": null,
"e": 5132,
"s": 4840,
"text": "//Generated by typescript 1.8.10\nvar invokeperson = function (obj) {\n console.log(\"first name :\" + obj.firstname);\n console.log(\"last name :\" + obj.lastname);\n};\n\ninvokeperson({ firstname: \"Sachin\", lastname: \"Tendulkar\" });\ninvokeperson({ firstname: \"Sachin\", lastname: \"Tendulkar\" });\n"
},
{
"code": null,
"e": 5159,
"s": 5132,
"text": "Its output is as follows −"
},
{
"code": null,
"e": 5201,
"s": 5159,
"text": "first name :Sachin \nlast name :Tendulkar\n"
},
{
"code": null,
"e": 5501,
"s": 5201,
"text": "In duck-typing, two objects are considered to be of the same type if both share the same set of properties. Duck-typing verifies the presence of certain properties in the objects, rather than their actual type, to check their suitability. The concept is generally explained by the following phrase −"
},
{
"code": null,
"e": 5615,
"s": 5501,
"text": "“When I see a bird that walks like a duck and swims like a duck and quacks like a duck, I call that bird a duck.”"
},
{
"code": null,
"e": 5891,
"s": 5615,
"text": "The TypeScript compiler implements the duck-typing system that allows object creation on the fly while keeping type safety. The following example shows how we can pass objects that don’t explicitly implement an interface but contain all of the required members to a function."
},
{
"code": null,
"e": 6174,
"s": 5891,
"text": "interface IPoint { \n x:number \n y:number \n} \nfunction addPoints(p1:IPoint,p2:IPoint):IPoint { \n var x = p1.x + p2.x \n var y = p1.y + p2.y \n return {x:x,y:y} \n} \n\n//Valid \nvar newPoint = addPoints({x:3,y:4},{x:5,y:1}) \n\n//Error \nvar newPoint2 = addPoints({x:1},{x:4,y:3})\n"
},
{
"code": null,
"e": 6207,
"s": 6174,
"text": "\n 45 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 6221,
"s": 6207,
"text": " Antonio Papa"
},
{
"code": null,
"e": 6254,
"s": 6221,
"text": "\n 41 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 6268,
"s": 6254,
"text": " Haider Malik"
},
{
"code": null,
"e": 6303,
"s": 6268,
"text": "\n 60 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 6323,
"s": 6303,
"text": " Skillbakerystudios"
},
{
"code": null,
"e": 6356,
"s": 6323,
"text": "\n 77 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 6370,
"s": 6356,
"text": " Sean Bradley"
},
{
"code": null,
"e": 6405,
"s": 6370,
"text": "\n 77 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 6421,
"s": 6405,
"text": " TELCOMA Global"
},
{
"code": null,
"e": 6454,
"s": 6421,
"text": "\n 19 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 6474,
"s": 6454,
"text": " Christopher Frewin"
},
{
"code": null,
"e": 6481,
"s": 6474,
"text": " Print"
},
{
"code": null,
"e": 6492,
"s": 6481,
"text": " Add Notes"
}
] |
NATURALINNERJOIN function
|
Performs an inner join of a table with another table. The tables are joined on common columns (by name) in the two tables. The two tables are to be related by one of these common columns.
If the two tables have no common column names, or if there is no relation between the two tables, an error is returned.
DAX NATURALINNERJOIN function is new in Excel 2016.
NATURALINNERJOIN (<leftJoinTable>, <rightJoinTable>)
leftJoinTable
A table expression defining the table on the left side of the join.
rightJoinTable
A table expression defining the table on the right side of the join.
A table which includes only rows for which the values in the common columns specified are present in both tables. The table returned will have the common columns from the left table and other columns from both the tables.
There is no sort order guarantee for the results.
Columns being joined on must have the same data type in both tables.
Only columns from the same source table are joined on.
Strict comparison semantics are used during join. There is no type coercion.
= SUMX (NATURALINNERJOIN (Salesperson,Sales),[Sales Amount])
53 Lectures
5.5 hours
Abhay Gadiya
24 Lectures
2 hours
Randy Minder
26 Lectures
4.5 hours
Randy Minder
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2189,
"s": 2001,
"text": "Performs an inner join of a table with another table. The tables are joined on common columns (by name) in the two tables. The two tables are to be related by one of these common columns."
},
{
"code": null,
"e": 2309,
"s": 2189,
"text": "If the two tables have no common column names, or if there is no relation between the two tables, an error is returned."
},
{
"code": null,
"e": 2361,
"s": 2309,
"text": "DAX NATURALINNERJOIN function is new in Excel 2016."
},
{
"code": null,
"e": 2415,
"s": 2361,
"text": "NATURALINNERJOIN (<leftJoinTable>, <rightJoinTable>)\n"
},
{
"code": null,
"e": 2429,
"s": 2415,
"text": "leftJoinTable"
},
{
"code": null,
"e": 2497,
"s": 2429,
"text": "A table expression defining the table on the left side of the join."
},
{
"code": null,
"e": 2512,
"s": 2497,
"text": "rightJoinTable"
},
{
"code": null,
"e": 2581,
"s": 2512,
"text": "A table expression defining the table on the right side of the join."
},
{
"code": null,
"e": 2803,
"s": 2581,
"text": "A table which includes only rows for which the values in the common columns specified are present in both tables. The table returned will have the common columns from the left table and other columns from both the tables."
},
{
"code": null,
"e": 2853,
"s": 2803,
"text": "There is no sort order guarantee for the results."
},
{
"code": null,
"e": 2922,
"s": 2853,
"text": "Columns being joined on must have the same data type in both tables."
},
{
"code": null,
"e": 2977,
"s": 2922,
"text": "Only columns from the same source table are joined on."
},
{
"code": null,
"e": 3054,
"s": 2977,
"text": "Strict comparison semantics are used during join. There is no type coercion."
},
{
"code": null,
"e": 3116,
"s": 3054,
"text": "= SUMX (NATURALINNERJOIN (Salesperson,Sales),[Sales Amount]) "
},
{
"code": null,
"e": 3151,
"s": 3116,
"text": "\n 53 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 3165,
"s": 3151,
"text": " Abhay Gadiya"
},
{
"code": null,
"e": 3198,
"s": 3165,
"text": "\n 24 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 3212,
"s": 3198,
"text": " Randy Minder"
},
{
"code": null,
"e": 3247,
"s": 3212,
"text": "\n 26 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 3261,
"s": 3247,
"text": " Randy Minder"
},
{
"code": null,
"e": 3268,
"s": 3261,
"text": " Print"
},
{
"code": null,
"e": 3279,
"s": 3268,
"text": " Add Notes"
}
] |
How to Create a Composite Primary Key in SQL Server? - GeeksforGeeks
|
12 Dec, 2021
In this article, We will learn what is a Composite Primary Key and How will create a Composite Primary Key. As We know a Primary key is the Candidate key that is selected to uniquely identify a row in a table. A And Primary Key does not allow NULL value.
When two or more Columns are together Identify the unique row in a table Known as Composite Primary Key. A composite key is a key that is the combination of more than one attribute or column of a given table. It may be a candidate key or a primary key.
We will implement with the help of an example for better understanding, first of all, we will create a database Name of the Database will Sample. and inside the database, we will Create a Compo.
Step 1: Creating a Database
For database creation, there is query we will use in SQL Platform.
Query:
Create database sample
Step 2: Use Database
For using the database we will use another query in SQL Platform like Mysql.
Query:
Use Sample
Step 3: Table Creation with composite primary
We will use the below query to create a Composite Key.
Query:
CREATE TABLE COMPO
(
EMP_ID INT,
DEPT_ID INT,
EMPNAME VARCHAR(25),
GENDER VARCHAR(6),
SALARY INT -->
//This statement will create a
//composite Primary Key from
PRIMARY KEY (EMP_ID,DEPT_ID)
with the help of Column EMP_ID and DEPT_ID
);
Step 4: After the creation of the table, we can Justify the view and metadata of the table with the help of the below Query. It will return Schema, column, data type, and size and constraints.
Query:
EXEC sp_help COMPO;
Output:
Step 5: INSERTION DATA IN TABLE.
We will use the below SQL query to insert data in Created Table.
Query:
INSERT INTO COMPO
VALUES (101,001,'RAHUL','MALE',22000),
(102,002,'RAJ','MALE',25000),
(103,003,'PRIYANKA','FEMALE',25500),
(102,003,'VIJAY','MALE',25000),
(101,004,'SHWETA','FEMALE',22000),
(104,003,'SATYA','MALE',23000),
(105,005,'VIVEK','MALE',28000);
Step 6: Verifying Inserted data
After Inserting data in the table We can justify or confirm which data we have to insert correctly or not. With the help of the Below Query.
Query:
SELECT * FROM COMPO
Output:
Step 7: As We know Primary Key has a unique value but in the above table, EMP_ID has a Duplicate value. Because it’s alone(EMP_ID) is not a primary Key So that it can contain duplicate values. Similarly, DEPT_ID also has duplicate Value because it is also not a Primary Key. But in the above record, EMP_ID and DEPT_ID are not duplicate. Because it is a Composite Primary key. Here (EMP_ID + DEPT_ID) is uniquely Identifying the row in given above table.
For Finding Unique Value from COMPO, we will Execute like below.
Query:
SELECT EMPNAME,SALARY FROM COMPO WHERE EMP_ID= 102 AND DEPT_ID =6;
Output:
anikaseth98
Picked
SQL-Server
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Update Multiple Columns in Single Update Statement in SQL?
What is Temporary Table in SQL?
SQL Query for Matching Multiple Values in the Same Column
SQL using Python
SQL Query to Insert Multiple Rows
SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter
SQL | Subquery
SQL | SEQUENCES
SQL | DROP, TRUNCATE
SQL Query to Convert VARCHAR to INT
|
[
{
"code": null,
"e": 24188,
"s": 24160,
"text": "\n12 Dec, 2021"
},
{
"code": null,
"e": 24444,
"s": 24188,
"text": "In this article, We will learn what is a Composite Primary Key and How will create a Composite Primary Key. As We know a Primary key is the Candidate key that is selected to uniquely identify a row in a table. A And Primary Key does not allow NULL value. "
},
{
"code": null,
"e": 24697,
"s": 24444,
"text": "When two or more Columns are together Identify the unique row in a table Known as Composite Primary Key. A composite key is a key that is the combination of more than one attribute or column of a given table. It may be a candidate key or a primary key."
},
{
"code": null,
"e": 24893,
"s": 24697,
"text": "We will implement with the help of an example for better understanding, first of all, we will create a database Name of the Database will Sample. and inside the database, we will Create a Compo. "
},
{
"code": null,
"e": 24921,
"s": 24893,
"text": "Step 1: Creating a Database"
},
{
"code": null,
"e": 24989,
"s": 24921,
"text": "For database creation, there is query we will use in SQL Platform. "
},
{
"code": null,
"e": 24996,
"s": 24989,
"text": "Query:"
},
{
"code": null,
"e": 25019,
"s": 24996,
"text": "Create database sample"
},
{
"code": null,
"e": 25040,
"s": 25019,
"text": "Step 2: Use Database"
},
{
"code": null,
"e": 25117,
"s": 25040,
"text": "For using the database we will use another query in SQL Platform like Mysql."
},
{
"code": null,
"e": 25124,
"s": 25117,
"text": "Query:"
},
{
"code": null,
"e": 25136,
"s": 25124,
"text": "Use Sample "
},
{
"code": null,
"e": 25182,
"s": 25136,
"text": "Step 3: Table Creation with composite primary"
},
{
"code": null,
"e": 25237,
"s": 25182,
"text": "We will use the below query to create a Composite Key."
},
{
"code": null,
"e": 25244,
"s": 25237,
"text": "Query:"
},
{
"code": null,
"e": 25498,
"s": 25244,
"text": "CREATE TABLE COMPO\n(\nEMP_ID INT,\nDEPT_ID INT,\nEMPNAME VARCHAR(25),\nGENDER VARCHAR(6),\nSALARY INT --> \n//This statement will create a\n//composite Primary Key from\n PRIMARY KEY (EMP_ID,DEPT_ID)\n with the help of Column EMP_ID and DEPT_ID\n);"
},
{
"code": null,
"e": 25693,
"s": 25498,
"text": "Step 4: After the creation of the table, we can Justify the view and metadata of the table with the help of the below Query. It will return Schema, column, data type, and size and constraints. "
},
{
"code": null,
"e": 25701,
"s": 25693,
"text": "Query: "
},
{
"code": null,
"e": 25721,
"s": 25701,
"text": "EXEC sp_help COMPO;"
},
{
"code": null,
"e": 25729,
"s": 25721,
"text": "Output:"
},
{
"code": null,
"e": 25762,
"s": 25729,
"text": "Step 5: INSERTION DATA IN TABLE."
},
{
"code": null,
"e": 25827,
"s": 25762,
"text": "We will use the below SQL query to insert data in Created Table."
},
{
"code": null,
"e": 25834,
"s": 25827,
"text": "Query:"
},
{
"code": null,
"e": 26090,
"s": 25834,
"text": "INSERT INTO COMPO\nVALUES (101,001,'RAHUL','MALE',22000),\n(102,002,'RAJ','MALE',25000),\n(103,003,'PRIYANKA','FEMALE',25500),\n(102,003,'VIJAY','MALE',25000),\n(101,004,'SHWETA','FEMALE',22000),\n(104,003,'SATYA','MALE',23000),\n(105,005,'VIVEK','MALE',28000); "
},
{
"code": null,
"e": 26122,
"s": 26090,
"text": "Step 6: Verifying Inserted data"
},
{
"code": null,
"e": 26265,
"s": 26122,
"text": "After Inserting data in the table We can justify or confirm which data we have to insert correctly or not. With the help of the Below Query. "
},
{
"code": null,
"e": 26273,
"s": 26265,
"text": "Query: "
},
{
"code": null,
"e": 26294,
"s": 26273,
"text": "SELECT * FROM COMPO"
},
{
"code": null,
"e": 26302,
"s": 26294,
"text": "Output:"
},
{
"code": null,
"e": 26758,
"s": 26302,
"text": "Step 7: As We know Primary Key has a unique value but in the above table, EMP_ID has a Duplicate value. Because it’s alone(EMP_ID) is not a primary Key So that it can contain duplicate values. Similarly, DEPT_ID also has duplicate Value because it is also not a Primary Key. But in the above record, EMP_ID and DEPT_ID are not duplicate. Because it is a Composite Primary key. Here (EMP_ID + DEPT_ID) is uniquely Identifying the row in given above table. "
},
{
"code": null,
"e": 26823,
"s": 26758,
"text": "For Finding Unique Value from COMPO, we will Execute like below."
},
{
"code": null,
"e": 26830,
"s": 26823,
"text": "Query:"
},
{
"code": null,
"e": 26898,
"s": 26830,
"text": "SELECT EMPNAME,SALARY FROM COMPO WHERE EMP_ID= 102 AND DEPT_ID =6; "
},
{
"code": null,
"e": 26906,
"s": 26898,
"text": "Output:"
},
{
"code": null,
"e": 26918,
"s": 26906,
"text": "anikaseth98"
},
{
"code": null,
"e": 26925,
"s": 26918,
"text": "Picked"
},
{
"code": null,
"e": 26936,
"s": 26925,
"text": "SQL-Server"
},
{
"code": null,
"e": 26940,
"s": 26936,
"text": "SQL"
},
{
"code": null,
"e": 26944,
"s": 26940,
"text": "SQL"
},
{
"code": null,
"e": 27042,
"s": 26944,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27051,
"s": 27042,
"text": "Comments"
},
{
"code": null,
"e": 27064,
"s": 27051,
"text": "Old Comments"
},
{
"code": null,
"e": 27130,
"s": 27064,
"text": "How to Update Multiple Columns in Single Update Statement in SQL?"
},
{
"code": null,
"e": 27162,
"s": 27130,
"text": "What is Temporary Table in SQL?"
},
{
"code": null,
"e": 27220,
"s": 27162,
"text": "SQL Query for Matching Multiple Values in the Same Column"
},
{
"code": null,
"e": 27237,
"s": 27220,
"text": "SQL using Python"
},
{
"code": null,
"e": 27271,
"s": 27237,
"text": "SQL Query to Insert Multiple Rows"
},
{
"code": null,
"e": 27349,
"s": 27271,
"text": "SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter"
},
{
"code": null,
"e": 27364,
"s": 27349,
"text": "SQL | Subquery"
},
{
"code": null,
"e": 27380,
"s": 27364,
"text": "SQL | SEQUENCES"
},
{
"code": null,
"e": 27401,
"s": 27380,
"text": "SQL | DROP, TRUNCATE"
}
] |
Tryit Editor v3.7
|
HTML form elements
Tryit: HTML select element
|
[
{
"code": null,
"e": 29,
"s": 10,
"text": "HTML form elements"
}
] |
Playit
|
#myDIV { background-color:lightblue; transform:rotate(10deg);}
|
[] |
Cassandra - Data Model
|
The data model of Cassandra is significantly different from what we normally see in an RDBMS. This chapter provides an overview of how Cassandra stores its data.
Cassandra database is distributed over several machines that operate together. The outermost container is known as the Cluster. For failure handling, every node contains a replica, and in case of a failure, the replica takes charge. Cassandra arranges the nodes in a cluster, in a ring format, and assigns data to them.
Keyspace is the outermost container for data in Cassandra. The basic attributes of a Keyspace in Cassandra are −
Replication factor − It is the number of machines in the cluster that will receive copies of the same data.
Replication factor − It is the number of machines in the cluster that will receive copies of the same data.
Replica placement strategy − It is nothing but the strategy to place replicas in the ring. We have strategies such as simple strategy (rack-aware strategy), old network topology strategy (rack-aware strategy), and network topology strategy (datacenter-shared strategy).
Replica placement strategy − It is nothing but the strategy to place replicas in the ring. We have strategies such as simple strategy (rack-aware strategy), old network topology strategy (rack-aware strategy), and network topology strategy (datacenter-shared strategy).
Column families − Keyspace is a container for a list of one or more column families. A column family, in turn, is a container of a collection of rows. Each row contains ordered columns. Column families represent the structure of your data. Each keyspace has at least one and often many column families.
Column families − Keyspace is a container for a list of one or more column families. A column family, in turn, is a container of a collection of rows. Each row contains ordered columns. Column families represent the structure of your data. Each keyspace has at least one and often many column families.
The syntax of creating a Keyspace is as follows −
CREATE KEYSPACE Keyspace name
WITH replication = {'class': 'SimpleStrategy', 'replication_factor' : 3};
The following illustration shows a schematic view of a Keyspace.
A column family is a container for an ordered collection of rows. Each row, in turn, is an ordered collection of columns. The following table lists the points that differentiate a column family from a table of relational databases.
A Cassandra column family has the following attributes −
keys_cached − It represents the number of locations to keep cached per SSTable.
keys_cached − It represents the number of locations to keep cached per SSTable.
rows_cached − It represents the number of rows whose entire contents will be cached in memory.
rows_cached − It represents the number of rows whose entire contents will be cached in memory.
preload_row_cache − It specifies whether you want to pre-populate the row cache.
preload_row_cache − It specifies whether you want to pre-populate the row cache.
Note − Unlike relational tables where a column family’s schema is not fixed, Cassandra does not force individual rows to have all the columns.
The following figure shows an example of a Cassandra column family.
A column is the basic data structure of Cassandra with three values, namely key
or column name, value, and a time stamp. Given below is the structure of a column.
A super column is a special column, therefore, it is also a key-value pair. But a super column stores a map of sub-columns.
Generally column families are stored on disk in individual files. Therefore, to optimize performance, it is important to keep columns that you are likely to query together in the same column family, and a super column can be helpful here.Given below is the structure of a super column.
The following table lists down the points that differentiate the data model of Cassandra from that of an RDBMS.
27 Lectures
2 hours
Navdeep Kaur
34 Lectures
1.5 hours
Bigdata Engineer
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2449,
"s": 2287,
"text": "The data model of Cassandra is significantly different from what we normally see in an RDBMS. This chapter provides an overview of how Cassandra stores its data."
},
{
"code": null,
"e": 2769,
"s": 2449,
"text": "Cassandra database is distributed over several machines that operate together. The outermost container is known as the Cluster. For failure handling, every node contains a replica, and in case of a failure, the replica takes charge. Cassandra arranges the nodes in a cluster, in a ring format, and assigns data to them."
},
{
"code": null,
"e": 2882,
"s": 2769,
"text": "Keyspace is the outermost container for data in Cassandra. The basic attributes of a Keyspace in Cassandra are −"
},
{
"code": null,
"e": 2990,
"s": 2882,
"text": "Replication factor − It is the number of machines in the cluster that will receive copies of the same data."
},
{
"code": null,
"e": 3098,
"s": 2990,
"text": "Replication factor − It is the number of machines in the cluster that will receive copies of the same data."
},
{
"code": null,
"e": 3368,
"s": 3098,
"text": "Replica placement strategy − It is nothing but the strategy to place replicas in the ring. We have strategies such as simple strategy (rack-aware strategy), old network topology strategy (rack-aware strategy), and network topology strategy (datacenter-shared strategy)."
},
{
"code": null,
"e": 3638,
"s": 3368,
"text": "Replica placement strategy − It is nothing but the strategy to place replicas in the ring. We have strategies such as simple strategy (rack-aware strategy), old network topology strategy (rack-aware strategy), and network topology strategy (datacenter-shared strategy)."
},
{
"code": null,
"e": 3941,
"s": 3638,
"text": "Column families − Keyspace is a container for a list of one or more column families. A column family, in turn, is a container of a collection of rows. Each row contains ordered columns. Column families represent the structure of your data. Each keyspace has at least one and often many column families."
},
{
"code": null,
"e": 4244,
"s": 3941,
"text": "Column families − Keyspace is a container for a list of one or more column families. A column family, in turn, is a container of a collection of rows. Each row contains ordered columns. Column families represent the structure of your data. Each keyspace has at least one and often many column families."
},
{
"code": null,
"e": 4294,
"s": 4244,
"text": "The syntax of creating a Keyspace is as follows −"
},
{
"code": null,
"e": 4399,
"s": 4294,
"text": "CREATE KEYSPACE Keyspace name\nWITH replication = {'class': 'SimpleStrategy', 'replication_factor' : 3};\n"
},
{
"code": null,
"e": 4464,
"s": 4399,
"text": "The following illustration shows a schematic view of a Keyspace."
},
{
"code": null,
"e": 4696,
"s": 4464,
"text": "A column family is a container for an ordered collection of rows. Each row, in turn, is an ordered collection of columns. The following table lists the points that differentiate a column family from a table of relational databases."
},
{
"code": null,
"e": 4753,
"s": 4696,
"text": "A Cassandra column family has the following attributes −"
},
{
"code": null,
"e": 4833,
"s": 4753,
"text": "keys_cached − It represents the number of locations to keep cached per SSTable."
},
{
"code": null,
"e": 4913,
"s": 4833,
"text": "keys_cached − It represents the number of locations to keep cached per SSTable."
},
{
"code": null,
"e": 5008,
"s": 4913,
"text": "rows_cached − It represents the number of rows whose entire contents will be cached in memory."
},
{
"code": null,
"e": 5103,
"s": 5008,
"text": "rows_cached − It represents the number of rows whose entire contents will be cached in memory."
},
{
"code": null,
"e": 5184,
"s": 5103,
"text": "preload_row_cache − It specifies whether you want to pre-populate the row cache."
},
{
"code": null,
"e": 5265,
"s": 5184,
"text": "preload_row_cache − It specifies whether you want to pre-populate the row cache."
},
{
"code": null,
"e": 5408,
"s": 5265,
"text": "Note − Unlike relational tables where a column family’s schema is not fixed, Cassandra does not force individual rows to have all the columns."
},
{
"code": null,
"e": 5476,
"s": 5408,
"text": "The following figure shows an example of a Cassandra column family."
},
{
"code": null,
"e": 5639,
"s": 5476,
"text": "A column is the basic data structure of Cassandra with three values, namely key\nor column name, value, and a time stamp. Given below is the structure of a column."
},
{
"code": null,
"e": 5763,
"s": 5639,
"text": "A super column is a special column, therefore, it is also a key-value pair. But a super column stores a map of sub-columns."
},
{
"code": null,
"e": 6049,
"s": 5763,
"text": "Generally column families are stored on disk in individual files. Therefore, to optimize performance, it is important to keep columns that you are likely to query together in the same column family, and a super column can be helpful here.Given below is the structure of a super column."
},
{
"code": null,
"e": 6161,
"s": 6049,
"text": "The following table lists down the points that differentiate the data model of Cassandra from that of an RDBMS."
},
{
"code": null,
"e": 6194,
"s": 6161,
"text": "\n 27 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 6208,
"s": 6194,
"text": " Navdeep Kaur"
},
{
"code": null,
"e": 6243,
"s": 6208,
"text": "\n 34 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 6261,
"s": 6243,
"text": " Bigdata Engineer"
},
{
"code": null,
"e": 6268,
"s": 6261,
"text": " Print"
},
{
"code": null,
"e": 6279,
"s": 6268,
"text": " Add Notes"
}
] |
How to calculate timestamp difference in hours with MongoDB?
|
To calculate timestamp difference, use aggregate framework. Let us first create a collection with documents −
> db.timestampDifferenceDemo.insertOne({
"MovieBeginningTime": new ISODate("2019-05-12 10:20:30"),
"MovieEndingTime":new ISODate("2019-05-12 12:30:20")
});
{
"acknowledged" : true,
"insertedId" : ObjectId("5cd7ba1f6d78f205348bc644")
}
> db.timestampDifferenceDemo.insertOne({
"MovieBeginningTime": new ISODate("2019-05-12 04:00:00"),
"MovieEndingTime":new ISODate("2019-05-12 07:10:00")
});
{
"acknowledged" : true,
"insertedId" : ObjectId("5cd7ba3b6d78f205348bc645")
}
Following is the query to display all documents from a collection with the help of find() method −
> db.timestampDifferenceDemo.find().pretty();
This will produce the following output −
{
"_id" : ObjectId("5cd7ba1f6d78f205348bc644"),
"MovieBeginningTime" : ISODate("2019-05-12T10:20:30Z"),
"MovieEndingTime" : ISODate("2019-05-12T12:30:20Z")
}
{
"_id" : ObjectId("5cd7ba3b6d78f205348bc645"),
"MovieBeginningTime" : ISODate("2019-05-12T04:00:00Z"),
"MovieEndingTime" : ISODate("2019-05-12T07:10:00Z")
}
Following is the query to calculate timestamp difference in MongoDB (in hours) −
> db.timestampDifferenceDemo.aggregate([
{$project: {
DifferenceInHours: {$divide: [{$subtract: ["$MovieEndingTime", "$MovieBeginningTime"]}, 3600000]}
}}
]);
This will produce the following output −
{ "_id" : ObjectId("5cd7ba1f6d78f205348bc644"), "DifferenceInHours" : 2.1638888888888888 }
{ "_id" : ObjectId("5cd7ba3b6d78f205348bc645"), "DifferenceInHours" : 3.1666666666666665 }
|
[
{
"code": null,
"e": 1172,
"s": 1062,
"text": "To calculate timestamp difference, use aggregate framework. Let us first create a collection with documents −"
},
{
"code": null,
"e": 1666,
"s": 1172,
"text": "> db.timestampDifferenceDemo.insertOne({\n \"MovieBeginningTime\": new ISODate(\"2019-05-12 10:20:30\"),\n \"MovieEndingTime\":new ISODate(\"2019-05-12 12:30:20\")\n});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5cd7ba1f6d78f205348bc644\")\n}\n> db.timestampDifferenceDemo.insertOne({\n \"MovieBeginningTime\": new ISODate(\"2019-05-12 04:00:00\"),\n \"MovieEndingTime\":new ISODate(\"2019-05-12 07:10:00\")\n});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5cd7ba3b6d78f205348bc645\")\n}"
},
{
"code": null,
"e": 1765,
"s": 1666,
"text": "Following is the query to display all documents from a collection with the help of find() method −"
},
{
"code": null,
"e": 1811,
"s": 1765,
"text": "> db.timestampDifferenceDemo.find().pretty();"
},
{
"code": null,
"e": 1852,
"s": 1811,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2186,
"s": 1852,
"text": "{\n \"_id\" : ObjectId(\"5cd7ba1f6d78f205348bc644\"),\n \"MovieBeginningTime\" : ISODate(\"2019-05-12T10:20:30Z\"),\n \"MovieEndingTime\" : ISODate(\"2019-05-12T12:30:20Z\")\n}\n{\n \"_id\" : ObjectId(\"5cd7ba3b6d78f205348bc645\"),\n \"MovieBeginningTime\" : ISODate(\"2019-05-12T04:00:00Z\"),\n \"MovieEndingTime\" : ISODate(\"2019-05-12T07:10:00Z\")\n}"
},
{
"code": null,
"e": 2267,
"s": 2186,
"text": "Following is the query to calculate timestamp difference in MongoDB (in hours) −"
},
{
"code": null,
"e": 2438,
"s": 2267,
"text": "> db.timestampDifferenceDemo.aggregate([\n {$project: {\n DifferenceInHours: {$divide: [{$subtract: [\"$MovieEndingTime\", \"$MovieBeginningTime\"]}, 3600000]}\n }}\n]);"
},
{
"code": null,
"e": 2479,
"s": 2438,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2661,
"s": 2479,
"text": "{ \"_id\" : ObjectId(\"5cd7ba1f6d78f205348bc644\"), \"DifferenceInHours\" : 2.1638888888888888 }\n{ \"_id\" : ObjectId(\"5cd7ba3b6d78f205348bc645\"), \"DifferenceInHours\" : 3.1666666666666665 }"
}
] |
Ruby | Enumerable sort() function - GeeksforGeeks
|
05 Dec, 2019
The sort() of enumerable is an inbuilt method in Ruby returns an array which contains the enum items in a sorted order. The comparisons are done using operator or the optional block. The block must implement a comparison between a and b and return an integer less than 0 when b follows a, 0 when a and b are equivalent, or an integer greater than 0 when a follows b. The result returned is not stable. The order of the element is not stable when the comparison of two elements returns 0.
Syntax: enu.sort { |a, b| block }
Parameters: The function accepts an optional comparison block.
Return Value: It returns the an array.
Example 1:
# Ruby program for sort method in Enumerable # Initialize enu = (1..10) # Printsenu.sort
Output:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Example 2:
# Ruby program for sort method in Enumerable # Initialize enu = [10, 9, 8, 12, 10, 13] # Printsenu.sort {|a, b| a <=> b}
Output:
[8, 9, 10, 10, 12, 13]
Ruby Collections
Ruby Enumerable-class
Ruby-Methods
Ruby
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Include v/s Extend in Ruby
Global Variable in Ruby
Ruby | Hash delete() function
Ruby | Case Statement
Ruby | Enumerator each_with_index function
Ruby | Array select() function
Ruby | Data Types
Ruby | Numeric round() function
Ruby For Beginners
Ruby | Decision Making (if, if-else, if-else-if, ternary) | Set - 1
|
[
{
"code": null,
"e": 23700,
"s": 23672,
"text": "\n05 Dec, 2019"
},
{
"code": null,
"e": 24188,
"s": 23700,
"text": "The sort() of enumerable is an inbuilt method in Ruby returns an array which contains the enum items in a sorted order. The comparisons are done using operator or the optional block. The block must implement a comparison between a and b and return an integer less than 0 when b follows a, 0 when a and b are equivalent, or an integer greater than 0 when a follows b. The result returned is not stable. The order of the element is not stable when the comparison of two elements returns 0."
},
{
"code": null,
"e": 24222,
"s": 24188,
"text": "Syntax: enu.sort { |a, b| block }"
},
{
"code": null,
"e": 24285,
"s": 24222,
"text": "Parameters: The function accepts an optional comparison block."
},
{
"code": null,
"e": 24324,
"s": 24285,
"text": "Return Value: It returns the an array."
},
{
"code": null,
"e": 24335,
"s": 24324,
"text": "Example 1:"
},
{
"code": "# Ruby program for sort method in Enumerable # Initialize enu = (1..10) # Printsenu.sort ",
"e": 24427,
"s": 24335,
"text": null
},
{
"code": null,
"e": 24435,
"s": 24427,
"text": "Output:"
},
{
"code": null,
"e": 24468,
"s": 24435,
"text": "[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\n"
},
{
"code": null,
"e": 24479,
"s": 24468,
"text": "Example 2:"
},
{
"code": "# Ruby program for sort method in Enumerable # Initialize enu = [10, 9, 8, 12, 10, 13] # Printsenu.sort {|a, b| a <=> b}",
"e": 24602,
"s": 24479,
"text": null
},
{
"code": null,
"e": 24610,
"s": 24602,
"text": "Output:"
},
{
"code": null,
"e": 24634,
"s": 24610,
"text": "[8, 9, 10, 10, 12, 13]\n"
},
{
"code": null,
"e": 24651,
"s": 24634,
"text": "Ruby Collections"
},
{
"code": null,
"e": 24673,
"s": 24651,
"text": "Ruby Enumerable-class"
},
{
"code": null,
"e": 24686,
"s": 24673,
"text": "Ruby-Methods"
},
{
"code": null,
"e": 24691,
"s": 24686,
"text": "Ruby"
},
{
"code": null,
"e": 24789,
"s": 24691,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 24816,
"s": 24789,
"text": "Include v/s Extend in Ruby"
},
{
"code": null,
"e": 24840,
"s": 24816,
"text": "Global Variable in Ruby"
},
{
"code": null,
"e": 24870,
"s": 24840,
"text": "Ruby | Hash delete() function"
},
{
"code": null,
"e": 24892,
"s": 24870,
"text": "Ruby | Case Statement"
},
{
"code": null,
"e": 24935,
"s": 24892,
"text": "Ruby | Enumerator each_with_index function"
},
{
"code": null,
"e": 24966,
"s": 24935,
"text": "Ruby | Array select() function"
},
{
"code": null,
"e": 24984,
"s": 24966,
"text": "Ruby | Data Types"
},
{
"code": null,
"e": 25016,
"s": 24984,
"text": "Ruby | Numeric round() function"
},
{
"code": null,
"e": 25035,
"s": 25016,
"text": "Ruby For Beginners"
}
] |
Date class in Java (With Examples) - GeeksforGeeks
|
02 Jan, 2019
The class Date represents a specific instant in time, with millisecond precision. The Date class of java.util package implements Serializable, Cloneable and Comparable interface. It provides constructors and methods to deal with date and time with java.
Constructors
Date() : Creates date object representing current date and time.
Date(long milliseconds) : Creates a date object for the given milliseconds since January 1, 1970, 00:00:00 GMT.
Date(int year, int month, int date)
Date(int year, int month, int date, int hrs, int min)
Date(int year, int month, int date, int hrs, int min, int sec)
Date(String s)Note : The last 4 constructors of the Date class are Deprecated.// Java program to demonstrate constuctors of Dateimport java.util.*; public class Main{ public static void main(String[] args) { Date d1 = new Date(); System.out.println("Current date is " + d1); Date d2 = new Date(2323223232L); System.out.println("Date represented is "+ d2 ); }}Output:Current date is Tue Jul 12 18:35:37 IST 2016
Date represented is Wed Jan 28 02:50:23 IST 1970
Important Methodsboolean after(Date date) : Tests if current date is after the given date.boolean before(Date date) : Tests if current date is before the given date.int compareTo(Date date) : Compares current date with given date. Returns 0 if the argument Date is equal to the Date; a value less than 0 if the Date is before the Date argument; and a value greater than 0 if the Date is after the Date argument.long getTime() : Returns the number of milliseconds since January 1, 1970, 00:00:00 GMT represented by this Date object.void setTime(long time) : Changes the current date and time to given time.// Program to demonstrate methods of Date classimport java.util.*; public class Main{ public static void main(String[] args) { // Creating date Date d1 = new Date(2000, 11, 21); Date d2 = new Date(); // Current date Date d3 = new Date(2010, 1, 3); boolean a = d3.after(d1); System.out.println("Date d3 comes after " + "date d2: " + a); boolean b = d3.before(d2); System.out.println("Date d3 comes before "+ "date d2: " + b); int c = d1.compareTo(d2); System.out.println(c); System.out.println("Miliseconds from Jan 1 "+ "1970 to date d1 is " + d1.getTime()); System.out.println("Before setting "+d2); d2.setTime(204587433443L); System.out.println("After setting "+d2); }}Output:Date d3 comes after date d2: true
Date d3 comes before date d2: false
1
Miliseconds from Jan 1 1970 to date d1 is 60935500800000
Before setting Tue Jul 12 13:13:16 UTC 2016
After setting Fri Jun 25 21:50:33 UTC 1976
This article is contributed by Rahul Agrawal .If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.My Personal Notes
arrow_drop_upSave
Note : The last 4 constructors of the Date class are Deprecated.
// Java program to demonstrate constuctors of Dateimport java.util.*; public class Main{ public static void main(String[] args) { Date d1 = new Date(); System.out.println("Current date is " + d1); Date d2 = new Date(2323223232L); System.out.println("Date represented is "+ d2 ); }}
Output:
Current date is Tue Jul 12 18:35:37 IST 2016
Date represented is Wed Jan 28 02:50:23 IST 1970
Important Methods
boolean after(Date date) : Tests if current date is after the given date.
boolean before(Date date) : Tests if current date is before the given date.
int compareTo(Date date) : Compares current date with given date. Returns 0 if the argument Date is equal to the Date; a value less than 0 if the Date is before the Date argument; and a value greater than 0 if the Date is after the Date argument.
long getTime() : Returns the number of milliseconds since January 1, 1970, 00:00:00 GMT represented by this Date object.
void setTime(long time) : Changes the current date and time to given time.
// Program to demonstrate methods of Date classimport java.util.*; public class Main{ public static void main(String[] args) { // Creating date Date d1 = new Date(2000, 11, 21); Date d2 = new Date(); // Current date Date d3 = new Date(2010, 1, 3); boolean a = d3.after(d1); System.out.println("Date d3 comes after " + "date d2: " + a); boolean b = d3.before(d2); System.out.println("Date d3 comes before "+ "date d2: " + b); int c = d1.compareTo(d2); System.out.println(c); System.out.println("Miliseconds from Jan 1 "+ "1970 to date d1 is " + d1.getTime()); System.out.println("Before setting "+d2); d2.setTime(204587433443L); System.out.println("After setting "+d2); }}
Output:
Date d3 comes after date d2: true
Date d3 comes before date d2: false
1
Miliseconds from Jan 1 1970 to date d1 is 60935500800000
Before setting Tue Jul 12 13:13:16 UTC 2016
After setting Fri Jun 25 21:50:33 UTC 1976
This article is contributed by Rahul Agrawal .If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
date-time-program
Java - util package
Java-Date-Time
Java-util-Date
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Initialize an ArrayList in Java
HashMap in Java with Examples
Interfaces in Java
How to iterate any Map in Java
ArrayList in Java
Object Oriented Programming (OOPs) Concept in Java
Multidimensional Arrays in Java
Stack Class in Java
LinkedList in Java
Overriding in Java
|
[
{
"code": null,
"e": 24402,
"s": 24374,
"text": "\n02 Jan, 2019"
},
{
"code": null,
"e": 24656,
"s": 24402,
"text": "The class Date represents a specific instant in time, with millisecond precision. The Date class of java.util package implements Serializable, Cloneable and Comparable interface. It provides constructors and methods to deal with date and time with java."
},
{
"code": null,
"e": 24669,
"s": 24656,
"text": "Constructors"
},
{
"code": null,
"e": 24734,
"s": 24669,
"text": "Date() : Creates date object representing current date and time."
},
{
"code": null,
"e": 24846,
"s": 24734,
"text": "Date(long milliseconds) : Creates a date object for the given milliseconds since January 1, 1970, 00:00:00 GMT."
},
{
"code": null,
"e": 24882,
"s": 24846,
"text": "Date(int year, int month, int date)"
},
{
"code": null,
"e": 24936,
"s": 24882,
"text": "Date(int year, int month, int date, int hrs, int min)"
},
{
"code": null,
"e": 24999,
"s": 24936,
"text": "Date(int year, int month, int date, int hrs, int min, int sec)"
},
{
"code": null,
"e": 27642,
"s": 24999,
"text": "Date(String s)Note : The last 4 constructors of the Date class are Deprecated.// Java program to demonstrate constuctors of Dateimport java.util.*; public class Main{ public static void main(String[] args) { Date d1 = new Date(); System.out.println(\"Current date is \" + d1); Date d2 = new Date(2323223232L); System.out.println(\"Date represented is \"+ d2 ); }}Output:Current date is Tue Jul 12 18:35:37 IST 2016\nDate represented is Wed Jan 28 02:50:23 IST 1970\nImportant Methodsboolean after(Date date) : Tests if current date is after the given date.boolean before(Date date) : Tests if current date is before the given date.int compareTo(Date date) : Compares current date with given date. Returns 0 if the argument Date is equal to the Date; a value less than 0 if the Date is before the Date argument; and a value greater than 0 if the Date is after the Date argument.long getTime() : Returns the number of milliseconds since January 1, 1970, 00:00:00 GMT represented by this Date object.void setTime(long time) : Changes the current date and time to given time.// Program to demonstrate methods of Date classimport java.util.*; public class Main{ public static void main(String[] args) { // Creating date Date d1 = new Date(2000, 11, 21); Date d2 = new Date(); // Current date Date d3 = new Date(2010, 1, 3); boolean a = d3.after(d1); System.out.println(\"Date d3 comes after \" + \"date d2: \" + a); boolean b = d3.before(d2); System.out.println(\"Date d3 comes before \"+ \"date d2: \" + b); int c = d1.compareTo(d2); System.out.println(c); System.out.println(\"Miliseconds from Jan 1 \"+ \"1970 to date d1 is \" + d1.getTime()); System.out.println(\"Before setting \"+d2); d2.setTime(204587433443L); System.out.println(\"After setting \"+d2); }}Output:Date d3 comes after date d2: true\nDate d3 comes before date d2: false\n1\nMiliseconds from Jan 1 1970 to date d1 is 60935500800000\nBefore setting Tue Jul 12 13:13:16 UTC 2016\nAfter setting Fri Jun 25 21:50:33 UTC 1976\nThis article is contributed by Rahul Agrawal .If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.My Personal Notes\narrow_drop_upSave"
},
{
"code": null,
"e": 27707,
"s": 27642,
"text": "Note : The last 4 constructors of the Date class are Deprecated."
},
{
"code": "// Java program to demonstrate constuctors of Dateimport java.util.*; public class Main{ public static void main(String[] args) { Date d1 = new Date(); System.out.println(\"Current date is \" + d1); Date d2 = new Date(2323223232L); System.out.println(\"Date represented is \"+ d2 ); }}",
"e": 28027,
"s": 27707,
"text": null
},
{
"code": null,
"e": 28035,
"s": 28027,
"text": "Output:"
},
{
"code": null,
"e": 28130,
"s": 28035,
"text": "Current date is Tue Jul 12 18:35:37 IST 2016\nDate represented is Wed Jan 28 02:50:23 IST 1970\n"
},
{
"code": null,
"e": 28148,
"s": 28130,
"text": "Important Methods"
},
{
"code": null,
"e": 28222,
"s": 28148,
"text": "boolean after(Date date) : Tests if current date is after the given date."
},
{
"code": null,
"e": 28298,
"s": 28222,
"text": "boolean before(Date date) : Tests if current date is before the given date."
},
{
"code": null,
"e": 28545,
"s": 28298,
"text": "int compareTo(Date date) : Compares current date with given date. Returns 0 if the argument Date is equal to the Date; a value less than 0 if the Date is before the Date argument; and a value greater than 0 if the Date is after the Date argument."
},
{
"code": null,
"e": 28666,
"s": 28545,
"text": "long getTime() : Returns the number of milliseconds since January 1, 1970, 00:00:00 GMT represented by this Date object."
},
{
"code": null,
"e": 28741,
"s": 28666,
"text": "void setTime(long time) : Changes the current date and time to given time."
},
{
"code": "// Program to demonstrate methods of Date classimport java.util.*; public class Main{ public static void main(String[] args) { // Creating date Date d1 = new Date(2000, 11, 21); Date d2 = new Date(); // Current date Date d3 = new Date(2010, 1, 3); boolean a = d3.after(d1); System.out.println(\"Date d3 comes after \" + \"date d2: \" + a); boolean b = d3.before(d2); System.out.println(\"Date d3 comes before \"+ \"date d2: \" + b); int c = d1.compareTo(d2); System.out.println(c); System.out.println(\"Miliseconds from Jan 1 \"+ \"1970 to date d1 is \" + d1.getTime()); System.out.println(\"Before setting \"+d2); d2.setTime(204587433443L); System.out.println(\"After setting \"+d2); }}",
"e": 29599,
"s": 28741,
"text": null
},
{
"code": null,
"e": 29607,
"s": 29599,
"text": "Output:"
},
{
"code": null,
"e": 29824,
"s": 29607,
"text": "Date d3 comes after date d2: true\nDate d3 comes before date d2: false\n1\nMiliseconds from Jan 1 1970 to date d1 is 60935500800000\nBefore setting Tue Jul 12 13:13:16 UTC 2016\nAfter setting Fri Jun 25 21:50:33 UTC 1976\n"
},
{
"code": null,
"e": 30125,
"s": 29824,
"text": "This article is contributed by Rahul Agrawal .If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 30250,
"s": 30125,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 30268,
"s": 30250,
"text": "date-time-program"
},
{
"code": null,
"e": 30288,
"s": 30268,
"text": "Java - util package"
},
{
"code": null,
"e": 30303,
"s": 30288,
"text": "Java-Date-Time"
},
{
"code": null,
"e": 30318,
"s": 30303,
"text": "Java-util-Date"
},
{
"code": null,
"e": 30323,
"s": 30318,
"text": "Java"
},
{
"code": null,
"e": 30328,
"s": 30323,
"text": "Java"
},
{
"code": null,
"e": 30426,
"s": 30328,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30435,
"s": 30426,
"text": "Comments"
},
{
"code": null,
"e": 30448,
"s": 30435,
"text": "Old Comments"
},
{
"code": null,
"e": 30480,
"s": 30448,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 30510,
"s": 30480,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 30529,
"s": 30510,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 30560,
"s": 30529,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 30578,
"s": 30560,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 30629,
"s": 30578,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 30661,
"s": 30629,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 30681,
"s": 30661,
"text": "Stack Class in Java"
},
{
"code": null,
"e": 30700,
"s": 30681,
"text": "LinkedList in Java"
}
] |
HTML | DOM Input FileUpload required Property - GeeksforGeeks
|
13 Dec, 2021
The Input FileUpload required Property is used to set or return whether a file in the file upload field must be selected/uploaded before submitting a form.This property reflects the HTML required attribute.
Syntax:
Return the required property:fileuploadObject.required
fileuploadObject.required
Set the required property:fileuploadObject.required=true|false
fileuploadObject.required=true|false
Property Values:true: Return ‘true’ when the file upload field is required.false: It is the default value. It return ‘false’ when the file upload field is not required.
Return Value: A Boolean value that displays the status of file upload required field.
Examples-1: Return FileUpload required Property.
<!DOCTYPE html><html> <head> <title> Input FileUpload required Property </title> <style> h1 { color: green; } </style></head> <body> <center> <h1> Geeks for Geeks </h1> <form action="/action_page.php"> <input type="file" id="myFile" required> <br> <input type="submit" value="Submit"> </form> <p id="demo"></p> <button onclick="myFunction()"> Try it </button> <script> function myFunction() { var x = document.getElementById( "myFile").required; document.getElementById("demo").innerHTML = x; } </script> </center></body> </html>
Output:Before:After:
Examples-2: Set FileUpload required Property
<!DOCTYPE html><html> <head> <title> Input FileUpload required Property </title> <style> h1 { color: green; } </style></head> <body> <center> <h1> Geeks for Geeks </h1> <form action="/action_page.php"> <input type="file" id="myFile"> <br> <input type="submit" value="Submit"> </form> <p id="demo"></p> <button onclick="myFunction()"> Try it </button> <script> function myFunction() { var x = document.getElementById( "myFile").required = "true"; document.getElementById("demo").innerHTML = x; } </script> </center></body> </html>
Output:Before:After:Supported Browsers:
Google Chrome
Mozilla Firefox
Edge 10.0
Opera
Apple Safari
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.
hritikbhatnagar2182
HTML-DOM
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": 26164,
"s": 26136,
"text": "\n13 Dec, 2021"
},
{
"code": null,
"e": 26371,
"s": 26164,
"text": "The Input FileUpload required Property is used to set or return whether a file in the file upload field must be selected/uploaded before submitting a form.This property reflects the HTML required attribute."
},
{
"code": null,
"e": 26379,
"s": 26371,
"text": "Syntax:"
},
{
"code": null,
"e": 26434,
"s": 26379,
"text": "Return the required property:fileuploadObject.required"
},
{
"code": null,
"e": 26460,
"s": 26434,
"text": "fileuploadObject.required"
},
{
"code": null,
"e": 26523,
"s": 26460,
"text": "Set the required property:fileuploadObject.required=true|false"
},
{
"code": null,
"e": 26560,
"s": 26523,
"text": "fileuploadObject.required=true|false"
},
{
"code": null,
"e": 26729,
"s": 26560,
"text": "Property Values:true: Return ‘true’ when the file upload field is required.false: It is the default value. It return ‘false’ when the file upload field is not required."
},
{
"code": null,
"e": 26815,
"s": 26729,
"text": "Return Value: A Boolean value that displays the status of file upload required field."
},
{
"code": null,
"e": 26864,
"s": 26815,
"text": "Examples-1: Return FileUpload required Property."
},
{
"code": "<!DOCTYPE html><html> <head> <title> Input FileUpload required Property </title> <style> h1 { color: green; } </style></head> <body> <center> <h1> Geeks for Geeks </h1> <form action=\"/action_page.php\"> <input type=\"file\" id=\"myFile\" required> <br> <input type=\"submit\" value=\"Submit\"> </form> <p id=\"demo\"></p> <button onclick=\"myFunction()\"> Try it </button> <script> function myFunction() { var x = document.getElementById( \"myFile\").required; document.getElementById(\"demo\").innerHTML = x; } </script> </center></body> </html>",
"e": 27707,
"s": 26864,
"text": null
},
{
"code": null,
"e": 27728,
"s": 27707,
"text": "Output:Before:After:"
},
{
"code": null,
"e": 27773,
"s": 27728,
"text": "Examples-2: Set FileUpload required Property"
},
{
"code": "<!DOCTYPE html><html> <head> <title> Input FileUpload required Property </title> <style> h1 { color: green; } </style></head> <body> <center> <h1> Geeks for Geeks </h1> <form action=\"/action_page.php\"> <input type=\"file\" id=\"myFile\"> <br> <input type=\"submit\" value=\"Submit\"> </form> <p id=\"demo\"></p> <button onclick=\"myFunction()\"> Try it </button> <script> function myFunction() { var x = document.getElementById( \"myFile\").required = \"true\"; document.getElementById(\"demo\").innerHTML = x; } </script> </center></body> </html>",
"e": 28613,
"s": 27773,
"text": null
},
{
"code": null,
"e": 28653,
"s": 28613,
"text": "Output:Before:After:Supported Browsers:"
},
{
"code": null,
"e": 28667,
"s": 28653,
"text": "Google Chrome"
},
{
"code": null,
"e": 28683,
"s": 28667,
"text": "Mozilla Firefox"
},
{
"code": null,
"e": 28693,
"s": 28683,
"text": "Edge 10.0"
},
{
"code": null,
"e": 28699,
"s": 28693,
"text": "Opera"
},
{
"code": null,
"e": 28712,
"s": 28699,
"text": "Apple Safari"
},
{
"code": null,
"e": 28849,
"s": 28712,
"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": 28869,
"s": 28849,
"text": "hritikbhatnagar2182"
},
{
"code": null,
"e": 28878,
"s": 28869,
"text": "HTML-DOM"
},
{
"code": null,
"e": 28883,
"s": 28878,
"text": "HTML"
},
{
"code": null,
"e": 28900,
"s": 28883,
"text": "Web Technologies"
},
{
"code": null,
"e": 28905,
"s": 28900,
"text": "HTML"
},
{
"code": null,
"e": 29003,
"s": 28905,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29027,
"s": 29003,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 29068,
"s": 29027,
"text": "HTML Cheat Sheet - A Basic Guide to HTML"
},
{
"code": null,
"e": 29105,
"s": 29068,
"text": "Design a web page using HTML and CSS"
},
{
"code": null,
"e": 29134,
"s": 29105,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 29154,
"s": 29134,
"text": "Angular File Upload"
},
{
"code": null,
"e": 29194,
"s": 29154,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 29227,
"s": 29194,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 29272,
"s": 29227,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 29315,
"s": 29272,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
HashSet retainAll() method in Java with Example
|
24 Dec, 2018
The retainAll() method of java.util.HashSet class is used to retain from this set all of its elements that are contained in the specified collection.
Syntax:
public boolean retainAll(Collection c)
Parameters: This method takes collection c as a parameter containing elements to be retained from this set.
Returns Value: This method returns true if this set changed as a result of the call.
Exception: This method throws NullPointerException if this set contains a null element and the specified collection does not permit null elements (optional), or if the specified collection is null.
Below are the examples to illustrate the retainAll() method.
Example 1:
// Java program to demonstrate// retainAll() method for Integer value import java.util.*; public class GFG1 { public static void main(String[] argv) throws Exception { try { // Creating object of HashSet<Integer> HashSet<Integer> arrset1 = new HashSet<Integer>(); // Populating arrset1 arrset1.add(1); arrset1.add(2); arrset1.add(3); arrset1.add(4); arrset1.add(5); // print arrset1 System.out.println("HashSet before " + "retainAll() operation : " + arrset1); // Creating another object of HashSet<Integer> HashSet<Integer> arrset2 = new HashSet<Integer>(); arrset2.add(1); arrset2.add(2); arrset2.add(3); // print arrset2 System.out.println("Collection Elements" + " to be retained : " + arrset2); // Removing elements from arrset // specified in arrset2 // using retainAll() method arrset1.retainAll(arrset2); // print arrset1 System.out.println("HashSet after " + "retainAll() operation : " + arrset1); } catch (NullPointerException e) { System.out.println("Exception thrown : " + e); } }}
HashSet before retainAll() operation : [1, 2, 3, 4, 5]
Collection Elements to be retained : [1, 2, 3]
HashSet after retainAll() operation : [1, 2, 3]
Example 2: For NullPointerException
// Java program to demonstrate// retainAll() method for Integer value import java.util.*; public class GFG1 { public static void main(String[] argv) throws Exception { try { // Creating object of HashSet<Integer> HashSet<Integer> arrset1 = new HashSet<Integer>(); // Populating arrset1 arrset1.add(1); arrset1.add(2); arrset1.add(3); arrset1.add(4); arrset1.add(5); // print arrset1 System.out.println("HashSet before " + "retainAll() operation : " + arrset1); // Creating another object of HashSet<Integer> HashSet<Integer> arrset2 = null; // print arrset2 System.out.println("Collection Elements" + " to be retained : " + arrset2); System.out.println("\nTrying to pass " + "null as a specified element\n"); // Removing elements from arrset // specified in arrset2 // using retainAll() method arrset1.retainAll(arrset2); // print arrset1 System.out.println("HashSet after " + "retainAll() operation : " + arrset1); } catch (NullPointerException e) { System.out.println("Exception thrown : " + e); } }}
HashSet before retainAll() operation : [1, 2, 3, 4, 5]
Collection Elements to be retained : null
Trying to pass null as a specified element
Exception thrown : java.lang.NullPointerException
Java - util package
Java-Collections
Java-Functions
java-hashset
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n24 Dec, 2018"
},
{
"code": null,
"e": 178,
"s": 28,
"text": "The retainAll() method of java.util.HashSet class is used to retain from this set all of its elements that are contained in the specified collection."
},
{
"code": null,
"e": 186,
"s": 178,
"text": "Syntax:"
},
{
"code": null,
"e": 225,
"s": 186,
"text": "public boolean retainAll(Collection c)"
},
{
"code": null,
"e": 333,
"s": 225,
"text": "Parameters: This method takes collection c as a parameter containing elements to be retained from this set."
},
{
"code": null,
"e": 418,
"s": 333,
"text": "Returns Value: This method returns true if this set changed as a result of the call."
},
{
"code": null,
"e": 616,
"s": 418,
"text": "Exception: This method throws NullPointerException if this set contains a null element and the specified collection does not permit null elements (optional), or if the specified collection is null."
},
{
"code": null,
"e": 677,
"s": 616,
"text": "Below are the examples to illustrate the retainAll() method."
},
{
"code": null,
"e": 688,
"s": 677,
"text": "Example 1:"
},
{
"code": "// Java program to demonstrate// retainAll() method for Integer value import java.util.*; public class GFG1 { public static void main(String[] argv) throws Exception { try { // Creating object of HashSet<Integer> HashSet<Integer> arrset1 = new HashSet<Integer>(); // Populating arrset1 arrset1.add(1); arrset1.add(2); arrset1.add(3); arrset1.add(4); arrset1.add(5); // print arrset1 System.out.println(\"HashSet before \" + \"retainAll() operation : \" + arrset1); // Creating another object of HashSet<Integer> HashSet<Integer> arrset2 = new HashSet<Integer>(); arrset2.add(1); arrset2.add(2); arrset2.add(3); // print arrset2 System.out.println(\"Collection Elements\" + \" to be retained : \" + arrset2); // Removing elements from arrset // specified in arrset2 // using retainAll() method arrset1.retainAll(arrset2); // print arrset1 System.out.println(\"HashSet after \" + \"retainAll() operation : \" + arrset1); } catch (NullPointerException e) { System.out.println(\"Exception thrown : \" + e); } }}",
"e": 2214,
"s": 688,
"text": null
},
{
"code": null,
"e": 2365,
"s": 2214,
"text": "HashSet before retainAll() operation : [1, 2, 3, 4, 5]\nCollection Elements to be retained : [1, 2, 3]\nHashSet after retainAll() operation : [1, 2, 3]\n"
},
{
"code": null,
"e": 2401,
"s": 2365,
"text": "Example 2: For NullPointerException"
},
{
"code": "// Java program to demonstrate// retainAll() method for Integer value import java.util.*; public class GFG1 { public static void main(String[] argv) throws Exception { try { // Creating object of HashSet<Integer> HashSet<Integer> arrset1 = new HashSet<Integer>(); // Populating arrset1 arrset1.add(1); arrset1.add(2); arrset1.add(3); arrset1.add(4); arrset1.add(5); // print arrset1 System.out.println(\"HashSet before \" + \"retainAll() operation : \" + arrset1); // Creating another object of HashSet<Integer> HashSet<Integer> arrset2 = null; // print arrset2 System.out.println(\"Collection Elements\" + \" to be retained : \" + arrset2); System.out.println(\"\\nTrying to pass \" + \"null as a specified element\\n\"); // Removing elements from arrset // specified in arrset2 // using retainAll() method arrset1.retainAll(arrset2); // print arrset1 System.out.println(\"HashSet after \" + \"retainAll() operation : \" + arrset1); } catch (NullPointerException e) { System.out.println(\"Exception thrown : \" + e); } }}",
"e": 3946,
"s": 2401,
"text": null
},
{
"code": null,
"e": 4139,
"s": 3946,
"text": "HashSet before retainAll() operation : [1, 2, 3, 4, 5]\nCollection Elements to be retained : null\n\nTrying to pass null as a specified element\n\nException thrown : java.lang.NullPointerException\n"
},
{
"code": null,
"e": 4159,
"s": 4139,
"text": "Java - util package"
},
{
"code": null,
"e": 4176,
"s": 4159,
"text": "Java-Collections"
},
{
"code": null,
"e": 4191,
"s": 4176,
"text": "Java-Functions"
},
{
"code": null,
"e": 4204,
"s": 4191,
"text": "java-hashset"
},
{
"code": null,
"e": 4209,
"s": 4204,
"text": "Java"
},
{
"code": null,
"e": 4214,
"s": 4209,
"text": "Java"
},
{
"code": null,
"e": 4231,
"s": 4214,
"text": "Java-Collections"
}
] |
LINQ | Sorting Operator | OrderByDescending
|
22 May, 2019
In LINQ, sorting operators are used to rearrange the given sequence in ascending or descending order based on one or more attributes. There are 5 different types of sorting operators are available in LINQ:
OrderByOrderByDescendingThenByThenByDescendingReverse
OrderBy
OrderByDescending
ThenBy
ThenByDescending
Reverse
OrderByDescending operator is used to rearranging the elements of the given sequence in descending order. It does not support query syntax in C# and VB.Net. It only supports method syntax. If you want to rearrange or sort the elements of the given sequence or collection in descending order in query syntax, then use descending keyword as shown in below example.And in method syntax, use OrderByDescending () method to sort the elements of the given sequence or collection. This method is present in both the Queryable and Enumerable class. And the method syntax is supported by both C# and VB.Net languages. As shown in the below examples. The OrderByDescending method sorts the elements of the collection according to a single property, you are not allowed to sort the collection using multiple properties.
Example 1:
// C# program to print the employee// ID in descending orderusing System;using System.Linq;using System.Collections.Generic; // Employee detailspublic class Employee { public int emp_id { get; set; } public string emp_name { get; set; } public string emp_gender { get; set; } public string emp_hire_date { get; set; } public int emp_salary { get; set; }} class GFG { // Main method static public void Main() { List<Employee> emp = new List<Employee>() { new Employee() {emp_id = 209, emp_name = "Anjita", emp_gender = "Female", emp_hire_date = "12/3/2017", emp_salary = 20000}, new Employee() {emp_id = 210, emp_name = "Soniya", emp_gender = "Female", emp_hire_date = "22/4/2018", emp_salary = 30000}, new Employee() {emp_id = 211, emp_name = "Rohit", emp_gender = "Male", emp_hire_date = "3/5/2016", emp_salary = 40000}, new Employee() {emp_id = 212, emp_name = "Supriya", emp_gender = "Female", emp_hire_date = "4/8/2017", emp_salary = 40000}, new Employee() {emp_id = 213, emp_name = "Anil", emp_gender = "Male", emp_hire_date = "12/1/2016", emp_salary = 40000}, new Employee() {emp_id = 214, emp_name = "Anju", emp_gender = "Female", emp_hire_date = "17/6/2015", emp_salary = 50000}, }; // Query to print the ID of the // employees in descending order // Using Descending keyword in // query syntax var res = from e in emp orderby e.emp_id descending select e; foreach(var val in res) { Console.WriteLine("Employee ID: {0}", val.emp_id); } }}
Output:
Employee ID: 214
Employee ID: 213
Employee ID: 212
Employee ID: 211
Employee ID: 210
Employee ID: 209
Example 2:
// C# program to print the employee// name in descending orderusing System;using System.Linq;using System.Collections.Generic; // Employee detailspublic class Employee { public int emp_id { get; set; } public string emp_name { get; set; } public string emp_gender { get; set; } public string emp_hire_date { get; set; } public int emp_salary { get; set; }} class GFG { // Main method static public void Main() { List<Employee> emp = new List<Employee>() { new Employee() {emp_id = 209, emp_name = "Anjita", emp_gender = "Female", emp_hire_date = "12/3/2017", emp_salary = 20000}, new Employee() {emp_id = 210, emp_name = "Soniya", emp_gender = "Female", emp_hire_date = "22/4/2018", emp_salary = 30000}, new Employee() {emp_id = 211, emp_name = "Rohit", emp_gender = "Male", emp_hire_date = "3/5/2016", emp_salary = 40000}, new Employee() {emp_id = 212, emp_name = "Supriya", emp_gender = "Female", emp_hire_date = "4/8/2017", emp_salary = 40000}, new Employee() {emp_id = 213, emp_name = "Anil", emp_gender = "Male", emp_hire_date = "12/1/2016", emp_salary = 40000}, new Employee() {emp_id = 214, emp_name = "Anju", emp_gender = "Female", emp_hire_date = "17/6/2015", emp_salary = 50000}, }; // Query to print the name of the // employees in descending order // Using OrderByDescending method var res = emp.OrderByDescending(e => e.emp_name); foreach(var val in res) { Console.WriteLine("Employee Name: {0}", val.emp_name); } }}
Output:
Employee Name: Supriya
Employee Name: Soniya
Employee Name: Rohit
Employee Name: Anju
Employee Name: Anjita
Employee Name: Anil
CSharp LINQ
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C# Dictionary with examples
C# | Delegates
Introduction to .NET Framework
C# | Multiple inheritance using interfaces
Differences Between .NET Core and .NET Framework
C# | Method Overriding
C# | Data Types
C# | String.IndexOf( ) Method | Set - 1
C# | Constructors
C# | Class and Object
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n22 May, 2019"
},
{
"code": null,
"e": 234,
"s": 28,
"text": "In LINQ, sorting operators are used to rearrange the given sequence in ascending or descending order based on one or more attributes. There are 5 different types of sorting operators are available in LINQ:"
},
{
"code": null,
"e": 288,
"s": 234,
"text": "OrderByOrderByDescendingThenByThenByDescendingReverse"
},
{
"code": null,
"e": 296,
"s": 288,
"text": "OrderBy"
},
{
"code": null,
"e": 314,
"s": 296,
"text": "OrderByDescending"
},
{
"code": null,
"e": 321,
"s": 314,
"text": "ThenBy"
},
{
"code": null,
"e": 338,
"s": 321,
"text": "ThenByDescending"
},
{
"code": null,
"e": 346,
"s": 338,
"text": "Reverse"
},
{
"code": null,
"e": 1155,
"s": 346,
"text": "OrderByDescending operator is used to rearranging the elements of the given sequence in descending order. It does not support query syntax in C# and VB.Net. It only supports method syntax. If you want to rearrange or sort the elements of the given sequence or collection in descending order in query syntax, then use descending keyword as shown in below example.And in method syntax, use OrderByDescending () method to sort the elements of the given sequence or collection. This method is present in both the Queryable and Enumerable class. And the method syntax is supported by both C# and VB.Net languages. As shown in the below examples. The OrderByDescending method sorts the elements of the collection according to a single property, you are not allowed to sort the collection using multiple properties."
},
{
"code": null,
"e": 1166,
"s": 1155,
"text": "Example 1:"
},
{
"code": "// C# program to print the employee// ID in descending orderusing System;using System.Linq;using System.Collections.Generic; // Employee detailspublic class Employee { public int emp_id { get; set; } public string emp_name { get; set; } public string emp_gender { get; set; } public string emp_hire_date { get; set; } public int emp_salary { get; set; }} class GFG { // Main method static public void Main() { List<Employee> emp = new List<Employee>() { new Employee() {emp_id = 209, emp_name = \"Anjita\", emp_gender = \"Female\", emp_hire_date = \"12/3/2017\", emp_salary = 20000}, new Employee() {emp_id = 210, emp_name = \"Soniya\", emp_gender = \"Female\", emp_hire_date = \"22/4/2018\", emp_salary = 30000}, new Employee() {emp_id = 211, emp_name = \"Rohit\", emp_gender = \"Male\", emp_hire_date = \"3/5/2016\", emp_salary = 40000}, new Employee() {emp_id = 212, emp_name = \"Supriya\", emp_gender = \"Female\", emp_hire_date = \"4/8/2017\", emp_salary = 40000}, new Employee() {emp_id = 213, emp_name = \"Anil\", emp_gender = \"Male\", emp_hire_date = \"12/1/2016\", emp_salary = 40000}, new Employee() {emp_id = 214, emp_name = \"Anju\", emp_gender = \"Female\", emp_hire_date = \"17/6/2015\", emp_salary = 50000}, }; // Query to print the ID of the // employees in descending order // Using Descending keyword in // query syntax var res = from e in emp orderby e.emp_id descending select e; foreach(var val in res) { Console.WriteLine(\"Employee ID: {0}\", val.emp_id); } }}",
"e": 3159,
"s": 1166,
"text": null
},
{
"code": null,
"e": 3167,
"s": 3159,
"text": "Output:"
},
{
"code": null,
"e": 3270,
"s": 3167,
"text": "Employee ID: 214\nEmployee ID: 213\nEmployee ID: 212\nEmployee ID: 211\nEmployee ID: 210\nEmployee ID: 209\n"
},
{
"code": null,
"e": 3281,
"s": 3270,
"text": "Example 2:"
},
{
"code": "// C# program to print the employee// name in descending orderusing System;using System.Linq;using System.Collections.Generic; // Employee detailspublic class Employee { public int emp_id { get; set; } public string emp_name { get; set; } public string emp_gender { get; set; } public string emp_hire_date { get; set; } public int emp_salary { get; set; }} class GFG { // Main method static public void Main() { List<Employee> emp = new List<Employee>() { new Employee() {emp_id = 209, emp_name = \"Anjita\", emp_gender = \"Female\", emp_hire_date = \"12/3/2017\", emp_salary = 20000}, new Employee() {emp_id = 210, emp_name = \"Soniya\", emp_gender = \"Female\", emp_hire_date = \"22/4/2018\", emp_salary = 30000}, new Employee() {emp_id = 211, emp_name = \"Rohit\", emp_gender = \"Male\", emp_hire_date = \"3/5/2016\", emp_salary = 40000}, new Employee() {emp_id = 212, emp_name = \"Supriya\", emp_gender = \"Female\", emp_hire_date = \"4/8/2017\", emp_salary = 40000}, new Employee() {emp_id = 213, emp_name = \"Anil\", emp_gender = \"Male\", emp_hire_date = \"12/1/2016\", emp_salary = 40000}, new Employee() {emp_id = 214, emp_name = \"Anju\", emp_gender = \"Female\", emp_hire_date = \"17/6/2015\", emp_salary = 50000}, }; // Query to print the name of the // employees in descending order // Using OrderByDescending method var res = emp.OrderByDescending(e => e.emp_name); foreach(var val in res) { Console.WriteLine(\"Employee Name: {0}\", val.emp_name); } }}",
"e": 5212,
"s": 3281,
"text": null
},
{
"code": null,
"e": 5220,
"s": 5212,
"text": "Output:"
},
{
"code": null,
"e": 5349,
"s": 5220,
"text": "Employee Name: Supriya\nEmployee Name: Soniya\nEmployee Name: Rohit\nEmployee Name: Anju\nEmployee Name: Anjita\nEmployee Name: Anil\n"
},
{
"code": null,
"e": 5361,
"s": 5349,
"text": "CSharp LINQ"
},
{
"code": null,
"e": 5364,
"s": 5361,
"text": "C#"
},
{
"code": null,
"e": 5462,
"s": 5364,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5490,
"s": 5462,
"text": "C# Dictionary with examples"
},
{
"code": null,
"e": 5505,
"s": 5490,
"text": "C# | Delegates"
},
{
"code": null,
"e": 5536,
"s": 5505,
"text": "Introduction to .NET Framework"
},
{
"code": null,
"e": 5579,
"s": 5536,
"text": "C# | Multiple inheritance using interfaces"
},
{
"code": null,
"e": 5628,
"s": 5579,
"text": "Differences Between .NET Core and .NET Framework"
},
{
"code": null,
"e": 5651,
"s": 5628,
"text": "C# | Method Overriding"
},
{
"code": null,
"e": 5667,
"s": 5651,
"text": "C# | Data Types"
},
{
"code": null,
"e": 5707,
"s": 5667,
"text": "C# | String.IndexOf( ) Method | Set - 1"
},
{
"code": null,
"e": 5725,
"s": 5707,
"text": "C# | Constructors"
}
] |
How to add header row to a Pandas Dataframe?
|
17 Jun, 2021
A header necessarily stores the names or headings for each of the columns. It basically helps the user to identify the role of the respective column in the data frame. The top row containing column names is called the header row of the data frame. There are basically two approaches to add a header row in Python in case the original data frame doesn’t have a header.
Method 1: Creating a data frame from CSV file and creating row header
While reading the data and storing it in a data frame, or creating a fresh data frame , column names can be specified by using the names attribute of the read_csv() method. Names attribute contains an array of names for each of the columns of the data frame in order. The length of the array is equivalent to the length of this frame structure.
Python3
# pandas package is requiredimport pandas as pd # converting csv file to data framedata_frame = pd.read_csv("test.txt", sep='\t', names=['Name', 'Age', 'Profession']) # printing data frameprint("Data frame")print(data_frame) # printing row headerprint("Row header")print(list(data_frame.columns))
Output:
We can also specify the header=none as an attribute of the read_csv() method and later on give names to the columns explicitly when desired.
Python3
# pandas package is requiredimport pandas as pd # declaring a data frame with three rowsand three columnsdata_frame = pd.read_csv("test.txt") # printing data frameprint("Original Data frame")print(data_frame) # adding column namesdata_frame_new = pd.read_csv("test.txt", names=['A', 'B', 'C'])print("New Data frame")print(data_frame_new) # printing row headerprint("Row header")print(list(data_frame_new.columns))
Output:
Originally, the rows are numbered by index numbers beginning from 0, in case the CSV file does not have any row header.
Method 2: Creating a data frame and creating row header in Python itself
We can create a data frame of specific number of rows and columns by first creating a multi -dimensional array and then converting it into a data frame by the pandas.DataFrame() method. The columns argument is used to specify the row header or the column names. It contains an array of column values with its length equal to the number of columns in the data frame.
Python3
# pandas package is requiredimport pandas as pd # declaring a data frame with three rowsand three columnsdata = [['Mallika', 23, 'Student'], [ 'Yash', 25, 'Tutor'], ['Abc', 14, 'Clerk']] # creating a pandas data framedata_frame = pd.DataFrame(data, columns=['Name', 'Age', 'Profession']) # printing data frameprint("Data frame")print(data_frame) # printing row headerprint("Row header") print(list(data_frame.columns))
Output:
adnanirshad158
Picked
Python pandas-dataFrame
Python Pandas-exercise
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n17 Jun, 2021"
},
{
"code": null,
"e": 421,
"s": 53,
"text": "A header necessarily stores the names or headings for each of the columns. It basically helps the user to identify the role of the respective column in the data frame. The top row containing column names is called the header row of the data frame. There are basically two approaches to add a header row in Python in case the original data frame doesn’t have a header."
},
{
"code": null,
"e": 491,
"s": 421,
"text": "Method 1: Creating a data frame from CSV file and creating row header"
},
{
"code": null,
"e": 837,
"s": 491,
"text": "While reading the data and storing it in a data frame, or creating a fresh data frame , column names can be specified by using the names attribute of the read_csv() method. Names attribute contains an array of names for each of the columns of the data frame in order. The length of the array is equivalent to the length of this frame structure. "
},
{
"code": null,
"e": 845,
"s": 837,
"text": "Python3"
},
{
"code": "# pandas package is requiredimport pandas as pd # converting csv file to data framedata_frame = pd.read_csv(\"test.txt\", sep='\\t', names=['Name', 'Age', 'Profession']) # printing data frameprint(\"Data frame\")print(data_frame) # printing row headerprint(\"Row header\")print(list(data_frame.columns))",
"e": 1167,
"s": 845,
"text": null
},
{
"code": null,
"e": 1176,
"s": 1167,
"text": " Output:"
},
{
"code": null,
"e": 1318,
"s": 1176,
"text": "We can also specify the header=none as an attribute of the read_csv() method and later on give names to the columns explicitly when desired. "
},
{
"code": null,
"e": 1326,
"s": 1318,
"text": "Python3"
},
{
"code": "# pandas package is requiredimport pandas as pd # declaring a data frame with three rowsand three columnsdata_frame = pd.read_csv(\"test.txt\") # printing data frameprint(\"Original Data frame\")print(data_frame) # adding column namesdata_frame_new = pd.read_csv(\"test.txt\", names=['A', 'B', 'C'])print(\"New Data frame\")print(data_frame_new) # printing row headerprint(\"Row header\")print(list(data_frame_new.columns))",
"e": 1741,
"s": 1326,
"text": null
},
{
"code": null,
"e": 1749,
"s": 1741,
"text": "Output:"
},
{
"code": null,
"e": 1870,
"s": 1749,
"text": "Originally, the rows are numbered by index numbers beginning from 0, in case the CSV file does not have any row header. "
},
{
"code": null,
"e": 1943,
"s": 1870,
"text": "Method 2: Creating a data frame and creating row header in Python itself"
},
{
"code": null,
"e": 2310,
"s": 1943,
"text": "We can create a data frame of specific number of rows and columns by first creating a multi -dimensional array and then converting it into a data frame by the pandas.DataFrame() method. The columns argument is used to specify the row header or the column names. It contains an array of column values with its length equal to the number of columns in the data frame. "
},
{
"code": null,
"e": 2318,
"s": 2310,
"text": "Python3"
},
{
"code": "# pandas package is requiredimport pandas as pd # declaring a data frame with three rowsand three columnsdata = [['Mallika', 23, 'Student'], [ 'Yash', 25, 'Tutor'], ['Abc', 14, 'Clerk']] # creating a pandas data framedata_frame = pd.DataFrame(data, columns=['Name', 'Age', 'Profession']) # printing data frameprint(\"Data frame\")print(data_frame) # printing row headerprint(\"Row header\") print(list(data_frame.columns))",
"e": 2741,
"s": 2318,
"text": null
},
{
"code": null,
"e": 2750,
"s": 2741,
"text": " Output:"
},
{
"code": null,
"e": 2765,
"s": 2750,
"text": "adnanirshad158"
},
{
"code": null,
"e": 2772,
"s": 2765,
"text": "Picked"
},
{
"code": null,
"e": 2796,
"s": 2772,
"text": "Python pandas-dataFrame"
},
{
"code": null,
"e": 2819,
"s": 2796,
"text": "Python Pandas-exercise"
},
{
"code": null,
"e": 2833,
"s": 2819,
"text": "Python-pandas"
},
{
"code": null,
"e": 2840,
"s": 2833,
"text": "Python"
}
] |
Performance of a Network
|
27 Sep, 2021
Performance of a network pertains to the measure of service quality of a network as perceived by the user. There are different ways to measure the performance of a network, depending upon the nature and design of the network. The characteristics that measure the performance of a network are :
Bandwidth
Throughput
Latency (Delay)
Bandwidth – Delay Product
Jitter
BANDWIDTH One of the most essential conditions of a website’s performance is the amount of bandwidth allocated to the network. Bandwidth determines how rapidly the webserver is able to upload the requested information. While there are different factors to consider with respect to a site’s performance, bandwidth is every now and again the restricting element.
Bandwidth is characterized as the measure of data or information that can be transmitted in a fixed measure of time. The term can be used in two different contexts with two distinctive estimating values. In the case of digital devices, the bandwidth is measured in bits per second(bps) or bytes per second. In the case of analogue devices, the bandwidth is measured in cycles per second, or Hertz (Hz).
Bandwidth is only one component of what an individual sees as the speed of a network. People frequently mistake bandwidth with internet speed in light of the fact that internet service providers (ISPs) tend to claim that they have a fast “40Mbps connection” in their advertising campaigns. True internet speed is actually the amount of data you receive every second and that has a lot to do with latency too. “Bandwidth” means “Capacity” and “Speed” means “Transfer rate”.
More bandwidth does not mean more speed. Let us take a case where we have double the width of the tap pipe, but the water rate is still the same as it was when the tap pipe was half the width. Hence, there will be no improvement in speed. When we consider WAN links, we mostly mean bandwidth but when we consider LAN, we mostly mean speed. This is on the grounds that we are generally constrained by expensive cable bandwidth over WAN rather than hardware and interface data transfer rates (or speed) over LAN.
Bandwidth in Hertz: It is the range of frequencies contained in a composite signal or the range of frequencies a channel can pass. For example, let us consider the bandwidth of a subscriber telephone line as 4 kHz.
Bandwidth in Bits per Seconds: It refers to the number of bits per second that a channel, a link, or rather a network can transmit. For example, we can say the bandwidth of a Fast Ethernet network is a maximum of 100 Mbps, which means that the network can send 100 Mbps of data.
Note: There exists an explicit relationship between the bandwidth in hertz and the bandwidth in bits per second. An increase in bandwidth in hertz means an increase in bandwidth in bits per second. The relationship depends upon whether we have baseband transmission or transmission with modulation.
THROUGHPUT Throughput is the number of messages successfully transmitted per unit time. It is controlled by available bandwidth, the available signal-to-noise ratio and hardware limitations. The maximum throughput of a network may be consequently higher than the actual throughput achieved in everyday consumption. The terms ‘throughput’ and ‘bandwidth’ are often thought of as the same, yet they are different. Bandwidth is the potential measurement of a link, whereas throughput is an actual measurement of how fast we can send data.
Throughput is measured by tabulating the amount of data transferred between multiple locations during a specific period of time, usually resulting in the unit of bits per second(bps), which has evolved to bytes per second(Bps), kilobytes per second(KBps), megabytes per second(MBps) and gigabytes per second(GBps). Throughput may be affected by numerous factors, such as the hindrance of the underlying analogue physical medium, the available processing power of the system components, and end-user behaviour. When numerous protocol expenses are taken into account, the use rate of the transferred data can be significantly lower than the maximum achievable throughput.
Let us consider: A highway which has a capacity of moving, say, 200 vehicles at a time. But at a random time, someone notices only, say, 150 vehicles moving through it due to some congestion on the road. As a result, the capacity is likely to be 200 vehicles per unit time and the throughput is 150 vehicles at a time.
Example:
Input:A network with bandwidth of 10 Mbps can pass only an average of 12, 000 frames
per minute where each frame carries an average of 10, 000 bits. What will be the
throughput for this network?
Output: We can calculate the throughput as-
Throughput = (12, 000 x 10, 000) / 60 = 2 Mbps
The throughput is nearly equal to one-fifth of the bandwidth in this case.
For the difference between Bandwidth and Throughput, refer.
LATENCY In a network, during the process of data communication, latency(also known as delay) is defined as the total time taken for a complete message to arrive at the destination, starting with the time when the first bit of the message is sent out from the source and ending with the time when the last bit of the message is delivered at the destination. The network connections where small delays occur are called “Low-Latency-Networks” and the network connections which suffer from long delays are known as “High-Latency-Networks”.
High latency leads to the creation of bottlenecks in any network communication. It stops the data from taking full advantage of the network pipe and conclusively decreases the bandwidth of the communicating network. The effect of the latency on a network’s bandwidth can be temporary or never-ending depending on the source of the delays. Latency is also known as a ping rate and is measured in milliseconds(ms).
In simpler terms: latency may be defined as the time required to successfully send a packet across a network.
It is measured in many ways like round trip, one way, etc.
It might be affected by any component in the chain which is utilized to vehiculate data, like workstations, WAN links, routers, LAN, servers and eventually may be limited for large networks, by the speed of light.
Latency = Propagation Time + Transmission Time + Queuing Time + Processing Delay
Propagation Time: It is the time required for a bit to travel from the source to the destination. Propagation time can be calculated as the ratio between the link length (distance) and the propagation speed over the communicating medium. For example, for an electric signal, propagation time is the time taken for the signal to travel through a wire.
Propagation time = Distance / Propagation speed
Example:
Input: What will be the propagation time when the distance between two points is
12, 000 km? Assuming the propagation speed to be 2.4 * 10^8 m/s in cable.
Output: We can calculate the propagation time as-
Propagation time = (12000 * 10000) / (2.4 * 10^8) = 50 ms
Transmission Time: Transmission time is a time based on how long it takes to send the signal down the transmission line. It consists of time costs for an EM signal to propagate from one side to the other, or costs like the training signals that are usually put on the front of a packet by the sender, which helps the receiver synchronize clocks. The transmission time of a message relies upon the size of the message and the bandwidth of the channel.
Transmission time = Message size / Bandwidth
Example:
Input:What will be the propagation time and the transmission time for a 2.5-kbyte
message when the bandwidth of the network is 1 Gbps? Assuming the distance between
sender and receiver is 12, 000 km and speed of light is 2.4 * 10^8 m/s.
Output: We can calculate the propagation and transmission time as-
Propagation time = (12000 * 10000) / (2.4 * 10^8) = 50 ms
Transmission time = (2560 * 8) / 10^9 = 0.020 ms
Note: Since the message is short and the bandwidth is high, the dominant factor is the
propagation time and not the transmission time(which can be ignored).
Queuing Time: Queuing time is a time based on how long the packet has to sit around in the router. Quite frequently the wire is busy, so we are not able to transmit a packet immediately. The queuing time is usually not a fixed factor, hence it changes with the load thrust in the network. In cases like these, the packet sits waiting, ready to go, in a queue. These delays are predominantly characterized by the measure of traffic on the system. The more the traffic, the more likely a packet is stuck in the queue, just sitting in the memory, waiting.
Processing Delay: Processing delay is the delay based on how long it takes the router to figure out where to send the packet. As soon as the router finds it out, it will queue the packet for transmission. These costs are predominantly based on the complexity of the protocol. The router must decipher enough of the packet to make sense of which queue to put the packet in. Typically the lower-level layers of the stack have simpler protocols. If a router does not know which physical port to send the packet to, it will send it to all the ports, queuing the packet in many queues immediately. Differently, at a higher level, like in IP protocols, the processing may include making an ARP request to find out the physical address of the destination before queuing the packet for transmission. This situation may also be considered as a processing delay.
BANDWIDTH – DELAY PRODUCT Bandwidth and delay are two performance measurements of a link. However, what is significant in data communications is the product of the two, the bandwidth-delay product.
Let us take two hypothetical cases as examples.
Case 1: Assume a link is of bandwidth 1bps and the delay of the link is 5s. Let us find the bandwidth-delay product in this case. From the image, we can say that this product 1 x 5 is the maximum number of bits that can fill the link. There can be close to 5 bits at any time on the link.
Case 2: Assume a link is of bandwidth 3bps. From the image, we can say that there can be a maximum of 3 x 5 = 15 bits on the line. The reason is that, at each second, there are 3 bits on the line and the duration of each bit is 0.33s.
For both examples, the product of bandwidth and delay is the number of bits that can fill the link. This estimation is significant in the event that we have to send data in bursts and wait for the acknowledgement of each burst before sending the following one. To utilize the maximum ability of the link, we have to make the size of our burst twice the product of bandwidth and delay. Also, we need to fill up the full-duplex channel. The sender ought to send a burst of data of (2*bandwidth*delay) bits. The sender at that point waits for the receiver’s acknowledgement for part of the burst before sending another burst. The amount: 2*bandwidth*delay is the number of bits that can be in transition at any time.
JITTER Jitter is another performance issue related to delay. In technical terms, jitter is a “packet delay variance”. It can simply mean that jitter is considered as a problem when different packets of data face different delays in a network and the data at the receiver application is time-sensitive, i.e. audio or video data. Jitter is measured in milliseconds(ms). It is defined as an interference in the normal order of sending data packets. For example: if the delay for the first packet is 10 ms, for the second is 35 ms, and for the third is 50 ms, then the real-time destination application that uses the packets experiences jitter.
Simply, jitter is any deviation in, or displacement of, the signal pulses in a high-frequency digital signal. The deviation can be in connection with the amplitude, the width of the signal pulse or the phase timing. The major causes of jitter are electromagnetic interference(EMI) and crosstalk between signals. Jitter can lead to flickering of a display screen, affects the capability of a processor in a desktop or server to proceed as expected, introducing clicks or other undesired impacts in audio signals, and loss of transmitted data between network devices.
Jitter is negative and causes network congestion and packet loss.
Congestion is like a traffic jam on the highway. In a traffic jam, cars cannot move forward at a reasonable speed. Like the traffic jam, in congestion, all the packets come to a junction at the same time. Nothing can get loaded.
The second negative effect is packet loss. When packets arrive at unexpected intervals, the receiving system is not able to process the information, which leads to missing information also called “packet loss”. This has negative effects on video viewing. If a video becomes pixelated and is skipping, the network is experiencing jitter. The result of the jitter is packet loss. When you are playing a game online, the effect of packet loss can be that a player begins moving around on the screen randomly. Even worse, the game goes from one scene to the next, skipping over part of the gameplay.
In the above image, it can be noticed that the time it takes for packets to be sent is not the same as the time in which he will arrive at the receiver side. One of the packets faces an unexpected delay on its way and is received after the expected time. This is jitter.
A jitter buffer can reduce the effects of jitter, either in a network, on a router or switch, or on a computer. The system at the destination receiving the network packets usually receives them from the buffer and not from the source system directly. Each packet is fed out of the buffer at a regular rate. Another approach to diminish jitter in case of multiple paths for traffic is to selectively route traffic along the most stable paths or to always pick the path that can come closest to the targeted packet delivery rate.
jeevanyasa
Computer Networks
Computer Networks
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n27 Sep, 2021"
},
{
"code": null,
"e": 347,
"s": 52,
"text": "Performance of a network pertains to the measure of service quality of a network as perceived by the user. There are different ways to measure the performance of a network, depending upon the nature and design of the network. The characteristics that measure the performance of a network are : "
},
{
"code": null,
"e": 357,
"s": 347,
"text": "Bandwidth"
},
{
"code": null,
"e": 368,
"s": 357,
"text": "Throughput"
},
{
"code": null,
"e": 384,
"s": 368,
"text": "Latency (Delay)"
},
{
"code": null,
"e": 410,
"s": 384,
"text": "Bandwidth – Delay Product"
},
{
"code": null,
"e": 417,
"s": 410,
"text": "Jitter"
},
{
"code": null,
"e": 779,
"s": 417,
"text": "BANDWIDTH One of the most essential conditions of a website’s performance is the amount of bandwidth allocated to the network. Bandwidth determines how rapidly the webserver is able to upload the requested information. While there are different factors to consider with respect to a site’s performance, bandwidth is every now and again the restricting element. "
},
{
"code": null,
"e": 1183,
"s": 779,
"text": "Bandwidth is characterized as the measure of data or information that can be transmitted in a fixed measure of time. The term can be used in two different contexts with two distinctive estimating values. In the case of digital devices, the bandwidth is measured in bits per second(bps) or bytes per second. In the case of analogue devices, the bandwidth is measured in cycles per second, or Hertz (Hz). "
},
{
"code": null,
"e": 1657,
"s": 1183,
"text": "Bandwidth is only one component of what an individual sees as the speed of a network. People frequently mistake bandwidth with internet speed in light of the fact that internet service providers (ISPs) tend to claim that they have a fast “40Mbps connection” in their advertising campaigns. True internet speed is actually the amount of data you receive every second and that has a lot to do with latency too. “Bandwidth” means “Capacity” and “Speed” means “Transfer rate”. "
},
{
"code": null,
"e": 2169,
"s": 1657,
"text": "More bandwidth does not mean more speed. Let us take a case where we have double the width of the tap pipe, but the water rate is still the same as it was when the tap pipe was half the width. Hence, there will be no improvement in speed. When we consider WAN links, we mostly mean bandwidth but when we consider LAN, we mostly mean speed. This is on the grounds that we are generally constrained by expensive cable bandwidth over WAN rather than hardware and interface data transfer rates (or speed) over LAN. "
},
{
"code": null,
"e": 2385,
"s": 2169,
"text": "Bandwidth in Hertz: It is the range of frequencies contained in a composite signal or the range of frequencies a channel can pass. For example, let us consider the bandwidth of a subscriber telephone line as 4 kHz. "
},
{
"code": null,
"e": 2665,
"s": 2385,
"text": "Bandwidth in Bits per Seconds: It refers to the number of bits per second that a channel, a link, or rather a network can transmit. For example, we can say the bandwidth of a Fast Ethernet network is a maximum of 100 Mbps, which means that the network can send 100 Mbps of data. "
},
{
"code": null,
"e": 2965,
"s": 2665,
"text": "Note: There exists an explicit relationship between the bandwidth in hertz and the bandwidth in bits per second. An increase in bandwidth in hertz means an increase in bandwidth in bits per second. The relationship depends upon whether we have baseband transmission or transmission with modulation. "
},
{
"code": null,
"e": 3502,
"s": 2965,
"text": "THROUGHPUT Throughput is the number of messages successfully transmitted per unit time. It is controlled by available bandwidth, the available signal-to-noise ratio and hardware limitations. The maximum throughput of a network may be consequently higher than the actual throughput achieved in everyday consumption. The terms ‘throughput’ and ‘bandwidth’ are often thought of as the same, yet they are different. Bandwidth is the potential measurement of a link, whereas throughput is an actual measurement of how fast we can send data. "
},
{
"code": null,
"e": 4173,
"s": 3502,
"text": "Throughput is measured by tabulating the amount of data transferred between multiple locations during a specific period of time, usually resulting in the unit of bits per second(bps), which has evolved to bytes per second(Bps), kilobytes per second(KBps), megabytes per second(MBps) and gigabytes per second(GBps). Throughput may be affected by numerous factors, such as the hindrance of the underlying analogue physical medium, the available processing power of the system components, and end-user behaviour. When numerous protocol expenses are taken into account, the use rate of the transferred data can be significantly lower than the maximum achievable throughput. "
},
{
"code": null,
"e": 4493,
"s": 4173,
"text": "Let us consider: A highway which has a capacity of moving, say, 200 vehicles at a time. But at a random time, someone notices only, say, 150 vehicles moving through it due to some congestion on the road. As a result, the capacity is likely to be 200 vehicles per unit time and the throughput is 150 vehicles at a time. "
},
{
"code": null,
"e": 4503,
"s": 4493,
"text": "Example: "
},
{
"code": null,
"e": 4867,
"s": 4503,
"text": "Input:A network with bandwidth of 10 Mbps can pass only an average of 12, 000 frames \nper minute where each frame carries an average of 10, 000 bits. What will be the \nthroughput for this network?\n\nOutput: We can calculate the throughput as-\nThroughput = (12, 000 x 10, 000) / 60 = 2 Mbps\nThe throughput is nearly equal to one-fifth of the bandwidth in this case."
},
{
"code": null,
"e": 4928,
"s": 4867,
"text": "For the difference between Bandwidth and Throughput, refer. "
},
{
"code": null,
"e": 5465,
"s": 4928,
"text": "LATENCY In a network, during the process of data communication, latency(also known as delay) is defined as the total time taken for a complete message to arrive at the destination, starting with the time when the first bit of the message is sent out from the source and ending with the time when the last bit of the message is delivered at the destination. The network connections where small delays occur are called “Low-Latency-Networks” and the network connections which suffer from long delays are known as “High-Latency-Networks”. "
},
{
"code": null,
"e": 5879,
"s": 5465,
"text": "High latency leads to the creation of bottlenecks in any network communication. It stops the data from taking full advantage of the network pipe and conclusively decreases the bandwidth of the communicating network. The effect of the latency on a network’s bandwidth can be temporary or never-ending depending on the source of the delays. Latency is also known as a ping rate and is measured in milliseconds(ms). "
},
{
"code": null,
"e": 5990,
"s": 5879,
"text": "In simpler terms: latency may be defined as the time required to successfully send a packet across a network. "
},
{
"code": null,
"e": 6049,
"s": 5990,
"text": "It is measured in many ways like round trip, one way, etc."
},
{
"code": null,
"e": 6264,
"s": 6049,
"text": "It might be affected by any component in the chain which is utilized to vehiculate data, like workstations, WAN links, routers, LAN, servers and eventually may be limited for large networks, by the speed of light. "
},
{
"code": null,
"e": 6345,
"s": 6264,
"text": "Latency = Propagation Time + Transmission Time + Queuing Time + Processing Delay"
},
{
"code": null,
"e": 6698,
"s": 6345,
"text": "Propagation Time: It is the time required for a bit to travel from the source to the destination. Propagation time can be calculated as the ratio between the link length (distance) and the propagation speed over the communicating medium. For example, for an electric signal, propagation time is the time taken for the signal to travel through a wire. "
},
{
"code": null,
"e": 6746,
"s": 6698,
"text": "Propagation time = Distance / Propagation speed"
},
{
"code": null,
"e": 6757,
"s": 6746,
"text": "Example: "
},
{
"code": null,
"e": 7022,
"s": 6757,
"text": "Input: What will be the propagation time when the distance between two points is\n12, 000 km? Assuming the propagation speed to be 2.4 * 10^8 m/s in cable.\n\nOutput: We can calculate the propagation time as-\nPropagation time = (12000 * 10000) / (2.4 * 10^8) = 50 ms "
},
{
"code": null,
"e": 7475,
"s": 7022,
"text": "Transmission Time: Transmission time is a time based on how long it takes to send the signal down the transmission line. It consists of time costs for an EM signal to propagate from one side to the other, or costs like the training signals that are usually put on the front of a packet by the sender, which helps the receiver synchronize clocks. The transmission time of a message relies upon the size of the message and the bandwidth of the channel. "
},
{
"code": null,
"e": 7520,
"s": 7475,
"text": "Transmission time = Message size / Bandwidth"
},
{
"code": null,
"e": 7531,
"s": 7520,
"text": "Example: "
},
{
"code": null,
"e": 8102,
"s": 7531,
"text": "Input:What will be the propagation time and the transmission time for a 2.5-kbyte \nmessage when the bandwidth of the network is 1 Gbps? Assuming the distance between\nsender and receiver is 12, 000 km and speed of light is 2.4 * 10^8 m/s.\n\nOutput: We can calculate the propagation and transmission time as-\nPropagation time = (12000 * 10000) / (2.4 * 10^8) = 50 ms\nTransmission time = (2560 * 8) / 10^9 = 0.020 ms\n\nNote: Since the message is short and the bandwidth is high, the dominant factor is the\npropagation time and not the transmission time(which can be ignored)."
},
{
"code": null,
"e": 8656,
"s": 8102,
"text": "Queuing Time: Queuing time is a time based on how long the packet has to sit around in the router. Quite frequently the wire is busy, so we are not able to transmit a packet immediately. The queuing time is usually not a fixed factor, hence it changes with the load thrust in the network. In cases like these, the packet sits waiting, ready to go, in a queue. These delays are predominantly characterized by the measure of traffic on the system. The more the traffic, the more likely a packet is stuck in the queue, just sitting in the memory, waiting. "
},
{
"code": null,
"e": 9510,
"s": 8656,
"text": "Processing Delay: Processing delay is the delay based on how long it takes the router to figure out where to send the packet. As soon as the router finds it out, it will queue the packet for transmission. These costs are predominantly based on the complexity of the protocol. The router must decipher enough of the packet to make sense of which queue to put the packet in. Typically the lower-level layers of the stack have simpler protocols. If a router does not know which physical port to send the packet to, it will send it to all the ports, queuing the packet in many queues immediately. Differently, at a higher level, like in IP protocols, the processing may include making an ARP request to find out the physical address of the destination before queuing the packet for transmission. This situation may also be considered as a processing delay. "
},
{
"code": null,
"e": 9709,
"s": 9510,
"text": "BANDWIDTH – DELAY PRODUCT Bandwidth and delay are two performance measurements of a link. However, what is significant in data communications is the product of the two, the bandwidth-delay product. "
},
{
"code": null,
"e": 9758,
"s": 9709,
"text": "Let us take two hypothetical cases as examples. "
},
{
"code": null,
"e": 10048,
"s": 9758,
"text": "Case 1: Assume a link is of bandwidth 1bps and the delay of the link is 5s. Let us find the bandwidth-delay product in this case. From the image, we can say that this product 1 x 5 is the maximum number of bits that can fill the link. There can be close to 5 bits at any time on the link. "
},
{
"code": null,
"e": 10284,
"s": 10048,
"text": "Case 2: Assume a link is of bandwidth 3bps. From the image, we can say that there can be a maximum of 3 x 5 = 15 bits on the line. The reason is that, at each second, there are 3 bits on the line and the duration of each bit is 0.33s. "
},
{
"code": null,
"e": 10999,
"s": 10284,
"text": "For both examples, the product of bandwidth and delay is the number of bits that can fill the link. This estimation is significant in the event that we have to send data in bursts and wait for the acknowledgement of each burst before sending the following one. To utilize the maximum ability of the link, we have to make the size of our burst twice the product of bandwidth and delay. Also, we need to fill up the full-duplex channel. The sender ought to send a burst of data of (2*bandwidth*delay) bits. The sender at that point waits for the receiver’s acknowledgement for part of the burst before sending another burst. The amount: 2*bandwidth*delay is the number of bits that can be in transition at any time. "
},
{
"code": null,
"e": 11641,
"s": 10999,
"text": "JITTER Jitter is another performance issue related to delay. In technical terms, jitter is a “packet delay variance”. It can simply mean that jitter is considered as a problem when different packets of data face different delays in a network and the data at the receiver application is time-sensitive, i.e. audio or video data. Jitter is measured in milliseconds(ms). It is defined as an interference in the normal order of sending data packets. For example: if the delay for the first packet is 10 ms, for the second is 35 ms, and for the third is 50 ms, then the real-time destination application that uses the packets experiences jitter. "
},
{
"code": null,
"e": 12208,
"s": 11641,
"text": "Simply, jitter is any deviation in, or displacement of, the signal pulses in a high-frequency digital signal. The deviation can be in connection with the amplitude, the width of the signal pulse or the phase timing. The major causes of jitter are electromagnetic interference(EMI) and crosstalk between signals. Jitter can lead to flickering of a display screen, affects the capability of a processor in a desktop or server to proceed as expected, introducing clicks or other undesired impacts in audio signals, and loss of transmitted data between network devices. "
},
{
"code": null,
"e": 12276,
"s": 12208,
"text": "Jitter is negative and causes network congestion and packet loss. "
},
{
"code": null,
"e": 12505,
"s": 12276,
"text": "Congestion is like a traffic jam on the highway. In a traffic jam, cars cannot move forward at a reasonable speed. Like the traffic jam, in congestion, all the packets come to a junction at the same time. Nothing can get loaded."
},
{
"code": null,
"e": 13101,
"s": 12505,
"text": "The second negative effect is packet loss. When packets arrive at unexpected intervals, the receiving system is not able to process the information, which leads to missing information also called “packet loss”. This has negative effects on video viewing. If a video becomes pixelated and is skipping, the network is experiencing jitter. The result of the jitter is packet loss. When you are playing a game online, the effect of packet loss can be that a player begins moving around on the screen randomly. Even worse, the game goes from one scene to the next, skipping over part of the gameplay."
},
{
"code": null,
"e": 13373,
"s": 13101,
"text": "In the above image, it can be noticed that the time it takes for packets to be sent is not the same as the time in which he will arrive at the receiver side. One of the packets faces an unexpected delay on its way and is received after the expected time. This is jitter. "
},
{
"code": null,
"e": 13902,
"s": 13373,
"text": "A jitter buffer can reduce the effects of jitter, either in a network, on a router or switch, or on a computer. The system at the destination receiving the network packets usually receives them from the buffer and not from the source system directly. Each packet is fed out of the buffer at a regular rate. Another approach to diminish jitter in case of multiple paths for traffic is to selectively route traffic along the most stable paths or to always pick the path that can come closest to the targeted packet delivery rate. "
},
{
"code": null,
"e": 13913,
"s": 13902,
"text": "jeevanyasa"
},
{
"code": null,
"e": 13931,
"s": 13913,
"text": "Computer Networks"
},
{
"code": null,
"e": 13949,
"s": 13931,
"text": "Computer Networks"
}
] |
Set retainAll() method in Java with Example
|
31 Dec, 2018
The retainAll() method of java.util.Set interface is used to retain from this set all of its elements that are contained in the specified collection.
Syntax:
public boolean retainAll(Collection c)
Parameters: This method takes collection c as a parameter containing elements to be retained from this set.
Return Value: This method returns true if this set changed as a result of the call.
Exception: This method throws NullPointerException if this set contains a null element and the specified collection does not permit null elements (optional), or if the specified collection is null.
Below are the examples to illustrate the retainAll() method.
Example 1:
// Java program to demonstrate// retainAll() method for Integer value import java.util.*; public class GFG1 { public static void main(String[] argv) throws Exception { try { // Creating object of Set Set<Integer> arrset1 = new HashSet<Integer>(); // Populating arrset1 arrset1.add(1); arrset1.add(2); arrset1.add(3); arrset1.add(4); arrset1.add(5); // print arrset1 System.out.println("Set before retainAll() operation : " + arrset1); // Creating another object of Set Set<Integer> arrset2 = new HashSet<Integer>(); arrset2.add(1); arrset2.add(2); arrset2.add(3); // print arrset2 System.out.println("Collection Elements to be retained : " + arrset2); // Removing elements from arrset // specified in arrset2 // using retainAll() method arrset1.retainAll(arrset2); // print arrset1 System.out.println("Set after retainAll() operation : " + arrset1); } catch (NullPointerException e) { System.out.println("Exception thrown : " + e); } }}
Set before retainAll() operation : [1, 2, 3, 4, 5]
Collection Elements to be retained : [1, 2, 3]
Set after retainAll() operation : [1, 2, 3]
Example 2: For NullPointerException.
// Java program to demonstrate// retainAll() method for Integer value import java.util.*; public class GFG1 { public static void main(String[] argv) throws Exception { try { // Creating object of Set<Integer> Set<Integer> arrset1 = new HashSet<Integer>(); // Populating arrset1 arrset1.add(1); arrset1.add(2); arrset1.add(3); arrset1.add(4); arrset1.add(5); // print arrset1 System.out.println("Set before retainAll() operation : " + arrset1); // Creating another object of Set<Integer> Set<Integer> arrset2 = null; // print arrset2 System.out.println("Collection Elements to be retained : " + arrset2); System.out.println("\nTrying to pass " + "null as a specified element\n"); // Removing elements from arrset // specified in arrset2 // using retainAll() method arrset1.retainAll(arrset2); // print arrset1 System.out.println("Set after retainAll() operation : " + arrset1); } catch (NullPointerException e) { System.out.println("Exception thrown : " + e); } }}
Set before retainAll() operation : [1, 2, 3, 4, 5]
Collection Elements to be retained : null
Trying to pass null as a specified element
Exception thrown : java.lang.NullPointerException
Reference: https://docs.oracle.com/javase/7/docs/api/java/util/Set.html#retainAll(java.util.Collection)
Java-Collections
Java-Functions
java-set
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
How to iterate any Map in Java
Interfaces in Java
HashMap in Java with Examples
ArrayList in Java
Collections in Java
Multidimensional Arrays in Java
Singleton Class in Java
Set in Java
Stack Class in Java
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n31 Dec, 2018"
},
{
"code": null,
"e": 204,
"s": 54,
"text": "The retainAll() method of java.util.Set interface is used to retain from this set all of its elements that are contained in the specified collection."
},
{
"code": null,
"e": 212,
"s": 204,
"text": "Syntax:"
},
{
"code": null,
"e": 251,
"s": 212,
"text": "public boolean retainAll(Collection c)"
},
{
"code": null,
"e": 359,
"s": 251,
"text": "Parameters: This method takes collection c as a parameter containing elements to be retained from this set."
},
{
"code": null,
"e": 443,
"s": 359,
"text": "Return Value: This method returns true if this set changed as a result of the call."
},
{
"code": null,
"e": 641,
"s": 443,
"text": "Exception: This method throws NullPointerException if this set contains a null element and the specified collection does not permit null elements (optional), or if the specified collection is null."
},
{
"code": null,
"e": 702,
"s": 641,
"text": "Below are the examples to illustrate the retainAll() method."
},
{
"code": null,
"e": 713,
"s": 702,
"text": "Example 1:"
},
{
"code": "// Java program to demonstrate// retainAll() method for Integer value import java.util.*; public class GFG1 { public static void main(String[] argv) throws Exception { try { // Creating object of Set Set<Integer> arrset1 = new HashSet<Integer>(); // Populating arrset1 arrset1.add(1); arrset1.add(2); arrset1.add(3); arrset1.add(4); arrset1.add(5); // print arrset1 System.out.println(\"Set before retainAll() operation : \" + arrset1); // Creating another object of Set Set<Integer> arrset2 = new HashSet<Integer>(); arrset2.add(1); arrset2.add(2); arrset2.add(3); // print arrset2 System.out.println(\"Collection Elements to be retained : \" + arrset2); // Removing elements from arrset // specified in arrset2 // using retainAll() method arrset1.retainAll(arrset2); // print arrset1 System.out.println(\"Set after retainAll() operation : \" + arrset1); } catch (NullPointerException e) { System.out.println(\"Exception thrown : \" + e); } }}",
"e": 2060,
"s": 713,
"text": null
},
{
"code": null,
"e": 2203,
"s": 2060,
"text": "Set before retainAll() operation : [1, 2, 3, 4, 5]\nCollection Elements to be retained : [1, 2, 3]\nSet after retainAll() operation : [1, 2, 3]\n"
},
{
"code": null,
"e": 2240,
"s": 2203,
"text": "Example 2: For NullPointerException."
},
{
"code": "// Java program to demonstrate// retainAll() method for Integer value import java.util.*; public class GFG1 { public static void main(String[] argv) throws Exception { try { // Creating object of Set<Integer> Set<Integer> arrset1 = new HashSet<Integer>(); // Populating arrset1 arrset1.add(1); arrset1.add(2); arrset1.add(3); arrset1.add(4); arrset1.add(5); // print arrset1 System.out.println(\"Set before retainAll() operation : \" + arrset1); // Creating another object of Set<Integer> Set<Integer> arrset2 = null; // print arrset2 System.out.println(\"Collection Elements to be retained : \" + arrset2); System.out.println(\"\\nTrying to pass \" + \"null as a specified element\\n\"); // Removing elements from arrset // specified in arrset2 // using retainAll() method arrset1.retainAll(arrset2); // print arrset1 System.out.println(\"Set after retainAll() operation : \" + arrset1); } catch (NullPointerException e) { System.out.println(\"Exception thrown : \" + e); } }}",
"e": 3623,
"s": 2240,
"text": null
},
{
"code": null,
"e": 3812,
"s": 3623,
"text": "Set before retainAll() operation : [1, 2, 3, 4, 5]\nCollection Elements to be retained : null\n\nTrying to pass null as a specified element\n\nException thrown : java.lang.NullPointerException\n"
},
{
"code": null,
"e": 3916,
"s": 3812,
"text": "Reference: https://docs.oracle.com/javase/7/docs/api/java/util/Set.html#retainAll(java.util.Collection)"
},
{
"code": null,
"e": 3933,
"s": 3916,
"text": "Java-Collections"
},
{
"code": null,
"e": 3948,
"s": 3933,
"text": "Java-Functions"
},
{
"code": null,
"e": 3957,
"s": 3948,
"text": "java-set"
},
{
"code": null,
"e": 3962,
"s": 3957,
"text": "Java"
},
{
"code": null,
"e": 3967,
"s": 3962,
"text": "Java"
},
{
"code": null,
"e": 3984,
"s": 3967,
"text": "Java-Collections"
},
{
"code": null,
"e": 4082,
"s": 3984,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4133,
"s": 4082,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 4164,
"s": 4133,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 4183,
"s": 4164,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 4213,
"s": 4183,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 4231,
"s": 4213,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 4251,
"s": 4231,
"text": "Collections in Java"
},
{
"code": null,
"e": 4283,
"s": 4251,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 4307,
"s": 4283,
"text": "Singleton Class in Java"
},
{
"code": null,
"e": 4319,
"s": 4307,
"text": "Set in Java"
}
] |
How to remove a key and its value from an associative array in PHP ?
|
20 Sep, 2019
Given an associative array containing array elements and the task is to remove a key and its value from the associative array.
Examples:
Input : array( "name" => "Anand", "roll"=> "1")
Output : Array (
[roll] => 1
)
Input : array( "1" => "Add", "2" => "Multiply", "3" => "Divide")
Output : Array (
[2] => Multiply
[3] => Divide
)
Method 1: Using unset() function: The unset() function is used to unset a key and its value in an associative array.
Syntax:
void unset( $array_name['key_to_be_removed'] )
Program:
<?php // Declare an associative array$arr = array( "1" => "Add", "2" => "Multiply", "3" => "Divide"); // Remove the key 1 and its value// from associative arrayunset($arr['1']); // Display the array elementsprint_r($arr); ?>
Array
(
[2] => Multiply
[3] => Divide
)
Method 2: Using array_diff_key() function: This function is used to get the difference between one or more arrays. This function compares the keys between one or more arrays and returns the difference between them.
Syntax:
array array_diff_key( $array_name, array_flip((array) ['keys_to_be_removed'] )
Program:
<?php // Declare an associative array$arr = array( "1" => "a", "2" => "b", "3" => "c"); // Remove the key 1 and its value// from associative array$result = array_diff_key($arr, array_flip((array) ['1'])); // Display the resultprint_r($result); ?>
Array
(
[2] => b
[3] => c
)
Picked
PHP
PHP Programs
Web Technologies
Web technologies Questions
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to fetch data from localserver database and display on HTML table using PHP ?
Difference between HTTP GET and POST Methods
Different ways for passing data to view in Laravel
PHP | file_exists( ) Function
PHP | Ternary Operator
How to call PHP function on the click of a Button ?
How to fetch data from localserver database and display on HTML table using PHP ?
PHP | Ternary Operator
How to create admin login page using PHP?
How to send an email using PHPMailer ?
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n20 Sep, 2019"
},
{
"code": null,
"e": 155,
"s": 28,
"text": "Given an associative array containing array elements and the task is to remove a key and its value from the associative array."
},
{
"code": null,
"e": 165,
"s": 155,
"text": "Examples:"
},
{
"code": null,
"e": 372,
"s": 165,
"text": "Input : array( \"name\" => \"Anand\", \"roll\"=> \"1\")\nOutput : Array (\n [roll] => 1\n)\n\nInput : array( \"1\" => \"Add\", \"2\" => \"Multiply\", \"3\" => \"Divide\")\nOutput : Array (\n [2] => Multiply\n [3] => Divide\n)\n"
},
{
"code": null,
"e": 489,
"s": 372,
"text": "Method 1: Using unset() function: The unset() function is used to unset a key and its value in an associative array."
},
{
"code": null,
"e": 497,
"s": 489,
"text": "Syntax:"
},
{
"code": null,
"e": 544,
"s": 497,
"text": "void unset( $array_name['key_to_be_removed'] )"
},
{
"code": null,
"e": 553,
"s": 544,
"text": "Program:"
},
{
"code": "<?php // Declare an associative array$arr = array( \"1\" => \"Add\", \"2\" => \"Multiply\", \"3\" => \"Divide\"); // Remove the key 1 and its value// from associative arrayunset($arr['1']); // Display the array elementsprint_r($arr); ?>",
"e": 792,
"s": 553,
"text": null
},
{
"code": null,
"e": 841,
"s": 792,
"text": "Array\n(\n [2] => Multiply\n [3] => Divide\n)\n"
},
{
"code": null,
"e": 1056,
"s": 841,
"text": "Method 2: Using array_diff_key() function: This function is used to get the difference between one or more arrays. This function compares the keys between one or more arrays and returns the difference between them."
},
{
"code": null,
"e": 1064,
"s": 1056,
"text": "Syntax:"
},
{
"code": null,
"e": 1143,
"s": 1064,
"text": "array array_diff_key( $array_name, array_flip((array) ['keys_to_be_removed'] )"
},
{
"code": null,
"e": 1152,
"s": 1143,
"text": "Program:"
},
{
"code": "<?php // Declare an associative array$arr = array( \"1\" => \"a\", \"2\" => \"b\", \"3\" => \"c\"); // Remove the key 1 and its value// from associative array$result = array_diff_key($arr, array_flip((array) ['1'])); // Display the resultprint_r($result); ?>",
"e": 1425,
"s": 1152,
"text": null
},
{
"code": null,
"e": 1462,
"s": 1425,
"text": "Array\n(\n [2] => b\n [3] => c\n)\n"
},
{
"code": null,
"e": 1469,
"s": 1462,
"text": "Picked"
},
{
"code": null,
"e": 1473,
"s": 1469,
"text": "PHP"
},
{
"code": null,
"e": 1486,
"s": 1473,
"text": "PHP Programs"
},
{
"code": null,
"e": 1503,
"s": 1486,
"text": "Web Technologies"
},
{
"code": null,
"e": 1530,
"s": 1503,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 1534,
"s": 1530,
"text": "PHP"
},
{
"code": null,
"e": 1632,
"s": 1534,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1714,
"s": 1632,
"text": "How to fetch data from localserver database and display on HTML table using PHP ?"
},
{
"code": null,
"e": 1759,
"s": 1714,
"text": "Difference between HTTP GET and POST Methods"
},
{
"code": null,
"e": 1810,
"s": 1759,
"text": "Different ways for passing data to view in Laravel"
},
{
"code": null,
"e": 1840,
"s": 1810,
"text": "PHP | file_exists( ) Function"
},
{
"code": null,
"e": 1863,
"s": 1840,
"text": "PHP | Ternary Operator"
},
{
"code": null,
"e": 1915,
"s": 1863,
"text": "How to call PHP function on the click of a Button ?"
},
{
"code": null,
"e": 1997,
"s": 1915,
"text": "How to fetch data from localserver database and display on HTML table using PHP ?"
},
{
"code": null,
"e": 2020,
"s": 1997,
"text": "PHP | Ternary Operator"
},
{
"code": null,
"e": 2062,
"s": 2020,
"text": "How to create admin login page using PHP?"
}
] |
Find the sum of series 3, 7, 13, 21, 31....
|
22 Mar, 2021
Given a number N. The task is to find the sum of below series upto nth term.
3, 7, 13, 21, 31, ....
Examples:
Input : N = 3
Output : 23
Input : N = 25
Output : 5875
Approach:
Subtracting the above two equations, we have:
Below is the implementation of the above approach:
C++
Java
Python 3
C#
PHP
Javascript
// C++ Program to find the sum of given series #include <iostream>#include <math.h> using namespace std; // Function to calculate sumint findSum(int n){ // Return sum return (n * (pow(n, 2) + 3 * n + 5)) / 3;} // Driver codeint main(){ int n = 25; cout << findSum(n); return 0;}
// Java program to find sum of// n terms of the given seriesimport java.util.*; class GFG{static int calculateSum(int n){ // returning the final sum return (n * ((int)Math.pow(n, 2) + 3 * n + 5)) / 3;} // Driver Codepublic static void main(String arr[]){ // number of terms to // find the sum int n = 25; System.out.println(calculateSum(n));}} // This code is contributed// by Surendra_Gangwar
# Python program to find the# sum of given series # Function to calculate sumdef findSum(n): # Return sum return (n*(pow(n, 2)+3 * n + 5))/3 # driver coden = 25 print(int(findSum(n)))
// C# program to find// sum of n terms of// the given seriesusing System; class GFG{static int calculateSum(int n){ // returning the final sum return (n * ((int)Math.Pow(n, 2) + 3 * n + 5)) / 3;} // Driver Codepublic static void Main(){ // number of terms to // find the sum int n = 25; Console.WriteLine(calculateSum(n));}} // This code is contributed// by inder_verma.
<?php// PHP Program to find the// sum of given series // Function to calculate sumfunction findSum($n){ // Return sum return ($n * (pow($n, 2) + 3 * $n + 5)) / 3;} // Driver code$n = 25; echo findSum($n); // This code is contributed// by inder_verma?>
<script> // javascript program to find sum of// n terms of the given series function calculateSum(n){ // returning the final sum return (n * (parseInt(Math.pow(n, 2) + 3 * n + 5)) / 3);} // Driver Code// number of terms to// find the sumvar n = 25;document.write(calculateSum(n)); // This code contributed by shikhasingrajput </script>
5875
Time Complexity : O(1)
SURENDRA_GANGWAR
inderDuMCA
shikhasingrajput
series
series-sum
Mathematical
School Programming
Mathematical
series
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n22 Mar, 2021"
},
{
"code": null,
"e": 132,
"s": 54,
"text": "Given a number N. The task is to find the sum of below series upto nth term. "
},
{
"code": null,
"e": 157,
"s": 132,
"text": "3, 7, 13, 21, 31, .... "
},
{
"code": null,
"e": 169,
"s": 157,
"text": "Examples: "
},
{
"code": null,
"e": 225,
"s": 169,
"text": "Input : N = 3\nOutput : 23\n\nInput : N = 25\nOutput : 5875"
},
{
"code": null,
"e": 237,
"s": 227,
"text": "Approach:"
},
{
"code": null,
"e": 290,
"s": 242,
"text": "Subtracting the above two equations, we have: "
},
{
"code": null,
"e": 342,
"s": 290,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 346,
"s": 342,
"text": "C++"
},
{
"code": null,
"e": 351,
"s": 346,
"text": "Java"
},
{
"code": null,
"e": 360,
"s": 351,
"text": "Python 3"
},
{
"code": null,
"e": 363,
"s": 360,
"text": "C#"
},
{
"code": null,
"e": 367,
"s": 363,
"text": "PHP"
},
{
"code": null,
"e": 378,
"s": 367,
"text": "Javascript"
},
{
"code": "// C++ Program to find the sum of given series #include <iostream>#include <math.h> using namespace std; // Function to calculate sumint findSum(int n){ // Return sum return (n * (pow(n, 2) + 3 * n + 5)) / 3;} // Driver codeint main(){ int n = 25; cout << findSum(n); return 0;}",
"e": 674,
"s": 378,
"text": null
},
{
"code": "// Java program to find sum of// n terms of the given seriesimport java.util.*; class GFG{static int calculateSum(int n){ // returning the final sum return (n * ((int)Math.pow(n, 2) + 3 * n + 5)) / 3;} // Driver Codepublic static void main(String arr[]){ // number of terms to // find the sum int n = 25; System.out.println(calculateSum(n));}} // This code is contributed// by Surendra_Gangwar",
"e": 1116,
"s": 674,
"text": null
},
{
"code": "# Python program to find the# sum of given series # Function to calculate sumdef findSum(n): # Return sum return (n*(pow(n, 2)+3 * n + 5))/3 # driver coden = 25 print(int(findSum(n)))",
"e": 1306,
"s": 1116,
"text": null
},
{
"code": "// C# program to find// sum of n terms of// the given seriesusing System; class GFG{static int calculateSum(int n){ // returning the final sum return (n * ((int)Math.Pow(n, 2) + 3 * n + 5)) / 3;} // Driver Codepublic static void Main(){ // number of terms to // find the sum int n = 25; Console.WriteLine(calculateSum(n));}} // This code is contributed// by inder_verma.",
"e": 1725,
"s": 1306,
"text": null
},
{
"code": "<?php// PHP Program to find the// sum of given series // Function to calculate sumfunction findSum($n){ // Return sum return ($n * (pow($n, 2) + 3 * $n + 5)) / 3;} // Driver code$n = 25; echo findSum($n); // This code is contributed// by inder_verma?>",
"e": 1995,
"s": 1725,
"text": null
},
{
"code": "<script> // javascript program to find sum of// n terms of the given series function calculateSum(n){ // returning the final sum return (n * (parseInt(Math.pow(n, 2) + 3 * n + 5)) / 3);} // Driver Code// number of terms to// find the sumvar n = 25;document.write(calculateSum(n)); // This code contributed by shikhasingrajput </script>",
"e": 2370,
"s": 1995,
"text": null
},
{
"code": null,
"e": 2375,
"s": 2370,
"text": "5875"
},
{
"code": null,
"e": 2401,
"s": 2377,
"text": "Time Complexity : O(1) "
},
{
"code": null,
"e": 2418,
"s": 2401,
"text": "SURENDRA_GANGWAR"
},
{
"code": null,
"e": 2429,
"s": 2418,
"text": "inderDuMCA"
},
{
"code": null,
"e": 2446,
"s": 2429,
"text": "shikhasingrajput"
},
{
"code": null,
"e": 2453,
"s": 2446,
"text": "series"
},
{
"code": null,
"e": 2464,
"s": 2453,
"text": "series-sum"
},
{
"code": null,
"e": 2477,
"s": 2464,
"text": "Mathematical"
},
{
"code": null,
"e": 2496,
"s": 2477,
"text": "School Programming"
},
{
"code": null,
"e": 2509,
"s": 2496,
"text": "Mathematical"
},
{
"code": null,
"e": 2516,
"s": 2509,
"text": "series"
}
] |
How to merge table cells in HTML ?
|
20 Dec, 2020
The purpose of this article is to merge table cells in HTML. It can be done by using the rowspan and colspan attribute in HTML. The rowspan is used to merge or combine the number of cells in a row whereas the colspan is used to merge column cells in a table.
Example 1: In this example, we will merge two table row and make a single row.
HTML
<!DOCTYPE html><html> <head> <style> table, th, td { border: 1px solid black; border-collapse: collapse; padding: 6px; } </style></head> <body style="text-align:center"> <h1 style="color:green;"> GeeksforGeeks </h1> <h2>How to merge table cells in HTML?</h2> <table align="center"> <tr> <th>Name</th> <th>Age</th> </tr> <tr> <td>Akku</td> <!-- This cell will take up space on two rows --> <td rowspan="2">44</td> </tr> <tr> <td>fahad</td> </tr> </table></body> </html>
Output:
Example 2: In this example, we will merge two table column and make a single column.
HTML
<!DOCTYPE html><html> <head> <style> table, th, td { border: 1px solid black; border-collapse: collapse; padding: 6px; text-align: center; } </style></head> <body> <center> <h1 style="color: green;"> GeeksforGeeks </h1> <h2> How to merge table cells in HTML? </h2> <table> <tr> <th>Name</tMh> <th>Marks</th> </tr> <tr> <td>Aman</td> <td>10</td> </tr> <tr> <td>riya</td> <td>18</td> </tr> <!-- The last row --> <tr> <!-- This td will span two columns, that is a single column will take up the space of 2 --> <td colspan="2">Sum: 28</td> </tr> </table> </center></body> </html>
Output:
Supported Browsers:
Google Chrome
Internet Explorer
Firefox
Safari
Opera
CSS-Misc
HTML-Misc
CSS
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Types of CSS (Cascading Style Sheet)
Design a Tribute Page using HTML & CSS
How to set space between the flexbox ?
How to position a div at the bottom of its container using CSS?
How to Upload Image into Database and Display it using PHP ?
REST API (Introduction)
Hide or show elements in HTML using display property
How to set the default value for an HTML <select> element ?
How to set input type date in dd-mm-yyyy format using HTML ?
Types of CSS (Cascading Style Sheet)
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n20 Dec, 2020"
},
{
"code": null,
"e": 290,
"s": 28,
"text": "The purpose of this article is to merge table cells in HTML. It can be done by using the rowspan and colspan attribute in HTML. The rowspan is used to merge or combine the number of cells in a row whereas the colspan is used to merge column cells in a table. "
},
{
"code": null,
"e": 369,
"s": 290,
"text": "Example 1: In this example, we will merge two table row and make a single row."
},
{
"code": null,
"e": 374,
"s": 369,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <style> table, th, td { border: 1px solid black; border-collapse: collapse; padding: 6px; } </style></head> <body style=\"text-align:center\"> <h1 style=\"color:green;\"> GeeksforGeeks </h1> <h2>How to merge table cells in HTML?</h2> <table align=\"center\"> <tr> <th>Name</th> <th>Age</th> </tr> <tr> <td>Akku</td> <!-- This cell will take up space on two rows --> <td rowspan=\"2\">44</td> </tr> <tr> <td>fahad</td> </tr> </table></body> </html>",
"e": 1070,
"s": 374,
"text": null
},
{
"code": null,
"e": 1078,
"s": 1070,
"text": "Output:"
},
{
"code": null,
"e": 1163,
"s": 1078,
"text": "Example 2: In this example, we will merge two table column and make a single column."
},
{
"code": null,
"e": 1168,
"s": 1163,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <style> table, th, td { border: 1px solid black; border-collapse: collapse; padding: 6px; text-align: center; } </style></head> <body> <center> <h1 style=\"color: green;\"> GeeksforGeeks </h1> <h2> How to merge table cells in HTML? </h2> <table> <tr> <th>Name</tMh> <th>Marks</th> </tr> <tr> <td>Aman</td> <td>10</td> </tr> <tr> <td>riya</td> <td>18</td> </tr> <!-- The last row --> <tr> <!-- This td will span two columns, that is a single column will take up the space of 2 --> <td colspan=\"2\">Sum: 28</td> </tr> </table> </center></body> </html>",
"e": 2208,
"s": 1168,
"text": null
},
{
"code": null,
"e": 2216,
"s": 2208,
"text": "Output:"
},
{
"code": null,
"e": 2236,
"s": 2216,
"text": "Supported Browsers:"
},
{
"code": null,
"e": 2250,
"s": 2236,
"text": "Google Chrome"
},
{
"code": null,
"e": 2268,
"s": 2250,
"text": "Internet Explorer"
},
{
"code": null,
"e": 2276,
"s": 2268,
"text": "Firefox"
},
{
"code": null,
"e": 2283,
"s": 2276,
"text": "Safari"
},
{
"code": null,
"e": 2289,
"s": 2283,
"text": "Opera"
},
{
"code": null,
"e": 2298,
"s": 2289,
"text": "CSS-Misc"
},
{
"code": null,
"e": 2308,
"s": 2298,
"text": "HTML-Misc"
},
{
"code": null,
"e": 2312,
"s": 2308,
"text": "CSS"
},
{
"code": null,
"e": 2317,
"s": 2312,
"text": "HTML"
},
{
"code": null,
"e": 2334,
"s": 2317,
"text": "Web Technologies"
},
{
"code": null,
"e": 2339,
"s": 2334,
"text": "HTML"
},
{
"code": null,
"e": 2437,
"s": 2339,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2474,
"s": 2437,
"text": "Types of CSS (Cascading Style Sheet)"
},
{
"code": null,
"e": 2513,
"s": 2474,
"text": "Design a Tribute Page using HTML & CSS"
},
{
"code": null,
"e": 2552,
"s": 2513,
"text": "How to set space between the flexbox ?"
},
{
"code": null,
"e": 2616,
"s": 2552,
"text": "How to position a div at the bottom of its container using CSS?"
},
{
"code": null,
"e": 2677,
"s": 2616,
"text": "How to Upload Image into Database and Display it using PHP ?"
},
{
"code": null,
"e": 2701,
"s": 2677,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 2754,
"s": 2701,
"text": "Hide or show elements in HTML using display property"
},
{
"code": null,
"e": 2814,
"s": 2754,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 2875,
"s": 2814,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
}
] |
Even-odd turn game with two integers
|
13 May, 2022
Given three positive integers X, Y and P. Here P denotes the number of turns. Whenever the turn is odd X is multiplied by 2 and in every even turn Y is multiplied by 2. The task is to find the value of max(X, Y) ÷ min(X, Y) after the complete P turns.Examples :
Input : X = 1, Y = 2, P = 1
Output : 1
As turn is odd, X is multiplied by
2 and becomes 2. Now, X is 2 and Y is also 2.
Therefore, 2 ÷ 2 is 1.
Input : X = 3, Y = 7, p = 2
Output : 2
Here we have 2 turns. In the 1st turn which is odd
X is multiplied by 2. And the values are 6 and 7.
In the next turn which is even Y is multiplied by 2.
Now the final values are 6 and 14. Therefore, 14 ÷ 6 is 2.
Lets play the above game for 8 turns :
| i | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 |
|------|---|----|----|----|----|----|----|-----|-----|
| X(i) | X | 2X | 2X | 4X | 4X | 8X | 8X | 16X | 16X |
| Y(i) | Y | Y | 2Y | 2Y | 4Y | 4Y | 8Y | 8Y | 16Y |
Here we can easily spot a pattern :
if i is even, then X(i) = z * X and Y(i) = z * Y.
if i is odd, then X(i) = 2*z * X and Y(i) = z * Y.
Here z is actually the power of 2. So, we can simply say –
If P is even output will be max(X, Y) ÷ min(X, Y)
else output will be max(2*X, Y) ÷ min(2*X, Y).
Below is the implementation :
C++
C
Java
Python3
C#
PHP
Javascript
// CPP program to find max(X, Y) / min(X, Y)// after P turns#include <bits/stdc++.h>using namespace std; int findValue(int X, int Y, int P){ if (P % 2 == 0) return (max(X, Y) / min(X, Y)); else return (max(2 * X, Y) / min(2 * X, Y));} // Driver codeint main(){ // 1st test case int X = 1, Y = 2, P = 1; cout << findValue(X, Y, P) << endl; // 2nd test case X = 3, Y = 7, P = 2; cout << findValue(X, Y, P) << endl;}
// C program to find max(X, Y) / min(X, Y)// after P turns#include <stdio.h> int findValue(int X, int Y, int P){ int Max = X,Min = X; if(Max < Y) Max = Y; if(Min > Y) Min = Y; int Max2 = 2*X,Min2 = 2*X; if(Max2 < Y) Max2 = Y; if(Min2 > Y) Min2 = Y ; if (P % 2 == 0) return (Max / Min); else return (Max2 / Min2);} // Driver codeint main(){ // 1st test case int X = 1, Y = 2, P = 1; printf("%d\n",findValue(X, Y, P)); // 2nd test case X = 3, Y = 7, P = 2; printf("%d\n",findValue(X, Y, P));} // This code is contributed by kothvvsaakash.
// Java program to find max(X, Y) / min(X, Y)// after P turnsimport java.util.*; class Even_odd{ public static int findValue(int X, int Y, int P) { if (P % 2 == 0) return (Math.max(X, Y) / Math.min(X, Y)); else return (Math.max(2 * X, Y) / Math.min(2 * X, Y)); } public static void main(String[] args) { // 1st test case int X = 1, Y = 2, P = 1; System.out.println(findValue(X, Y, P)); // 2nd test case X = 3; Y = 7; P = 2; System.out.print(findValue(X, Y, P)); }} //This code is contributed by rishabh_jain
# Python3 code to find max(X, Y) / min(X, Y)# after P turns def findValue( X , Y , P ): if P % 2 == 0: return int(max(X, Y) / min(X, Y)) else: return int(max(2 * X, Y) / min(2 * X, Y)) # Driver code# 1st test caseX = 1Y = 2P = 1print(findValue(X, Y, P)) # 2nd test caseX = 3Y = 7P = 2print((findValue(X, Y, P))) # This code is contributed by "Sharad_Bhardwaj".
// C# program to find max(X, Y) / min(X, Y)// after P turnsusing System; class GFG{ public static int findValue(int X, int Y, int P) { if (P % 2 == 0) return (Math.Max(X, Y) / Math.Min(X, Y)); else return (Math.Max(2 * X, Y) / Math.Min(2 * X, Y)); } // Driver code public static void Main() { // 1st test case int X = 1, Y = 2, P = 1; Console.WriteLine(findValue(X, Y, P)); // 2nd test case X = 3; Y = 7; P = 2; Console.WriteLine(findValue(X, Y, P)); }} //This code is contributed by vt_m
<?php// PHP program to find// max(X, Y) / min(X, Y)// after P turns function findValue($X, $Y, $P){ if ($P % 2 == 0) return (int)(max($X, $Y) / min($X, $Y)); else return (int)(max(2 * $X, $Y) / min(2 * $X, $Y));} // Driver code // 1st test case$X = 1;$Y = 2;$P = 1;echo findValue($X, $Y, $P), "\n"; // 2nd test case$X = 3; $Y = 7; $P = 2;echo findValue($X, $Y, $P), "\n"; // This code is contributed by ajit?>
<script> // Javascript program to find max(X, Y) / min(X, Y) // after P turns function findValue(X, Y, P) { if (P % 2 == 0) return parseInt((Math.max(X, Y) / Math.min(X, Y)), 10); else return parseInt((Math.max(2 * X, Y) / Math.min(2 * X, Y)), 10); } // 1st test case let X = 1, Y = 2, P = 1; document.write(findValue(X, Y, P) + "</br>"); // 2nd test case X = 3, Y = 7, P = 2; document.write(findValue(X, Y, P)); // This code is contributed by divyeshrabadiya07.</script>
Output:
1
2
Time Complexity:O(1)
jit_t
gfg_sal_gfg
divyeshrabadiya07
varshagumber28
kothavvsaakash
number-theory
School Programming
Searching
Searching
number-theory
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction To PYTHON
Interfaces in Java
Operator Overloading in C++
Types of Operating Systems
Polymorphism in C++
Binary Search
Maximum and minimum of an array using minimum number of comparisons
Linear Search
K'th Smallest/Largest Element in Unsorted Array | Set 1
Search an element in a sorted and rotated array
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n13 May, 2022"
},
{
"code": null,
"e": 316,
"s": 52,
"text": "Given three positive integers X, Y and P. Here P denotes the number of turns. Whenever the turn is odd X is multiplied by 2 and in every even turn Y is multiplied by 2. The task is to find the value of max(X, Y) ÷ min(X, Y) after the complete P turns.Examples : "
},
{
"code": null,
"e": 714,
"s": 316,
"text": "Input : X = 1, Y = 2, P = 1\nOutput : 1\nAs turn is odd, X is multiplied by\n2 and becomes 2. Now, X is 2 and Y is also 2. \nTherefore, 2 ÷ 2 is 1.\n\nInput : X = 3, Y = 7, p = 2\nOutput : 2\nHere we have 2 turns. In the 1st turn which is odd\nX is multiplied by 2. And the values are 6 and 7. \nIn the next turn which is even Y is multiplied by 2.\nNow the final values are 6 and 14. Therefore, 14 ÷ 6 is 2."
},
{
"code": null,
"e": 757,
"s": 716,
"text": "Lets play the above game for 8 turns : "
},
{
"code": null,
"e": 977,
"s": 757,
"text": "| i | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 |\n|------|---|----|----|----|----|----|----|-----|-----|\n| X(i) | X | 2X | 2X | 4X | 4X | 8X | 8X | 16X | 16X |\n| Y(i) | Y | Y | 2Y | 2Y | 4Y | 4Y | 8Y | 8Y | 16Y |"
},
{
"code": null,
"e": 1015,
"s": 977,
"text": "Here we can easily spot a pattern : "
},
{
"code": null,
"e": 1116,
"s": 1015,
"text": "if i is even, then X(i) = z * X and Y(i) = z * Y.\nif i is odd, then X(i) = 2*z * X and Y(i) = z * Y."
},
{
"code": null,
"e": 1177,
"s": 1116,
"text": "Here z is actually the power of 2. So, we can simply say – "
},
{
"code": null,
"e": 1275,
"s": 1177,
"text": "If P is even output will be max(X, Y) ÷ min(X, Y) \nelse output will be max(2*X, Y) ÷ min(2*X, Y)."
},
{
"code": null,
"e": 1307,
"s": 1275,
"text": "Below is the implementation : "
},
{
"code": null,
"e": 1311,
"s": 1307,
"text": "C++"
},
{
"code": null,
"e": 1313,
"s": 1311,
"text": "C"
},
{
"code": null,
"e": 1318,
"s": 1313,
"text": "Java"
},
{
"code": null,
"e": 1326,
"s": 1318,
"text": "Python3"
},
{
"code": null,
"e": 1329,
"s": 1326,
"text": "C#"
},
{
"code": null,
"e": 1333,
"s": 1329,
"text": "PHP"
},
{
"code": null,
"e": 1344,
"s": 1333,
"text": "Javascript"
},
{
"code": "// CPP program to find max(X, Y) / min(X, Y)// after P turns#include <bits/stdc++.h>using namespace std; int findValue(int X, int Y, int P){ if (P % 2 == 0) return (max(X, Y) / min(X, Y)); else return (max(2 * X, Y) / min(2 * X, Y));} // Driver codeint main(){ // 1st test case int X = 1, Y = 2, P = 1; cout << findValue(X, Y, P) << endl; // 2nd test case X = 3, Y = 7, P = 2; cout << findValue(X, Y, P) << endl;}",
"e": 1798,
"s": 1344,
"text": null
},
{
"code": "// C program to find max(X, Y) / min(X, Y)// after P turns#include <stdio.h> int findValue(int X, int Y, int P){ int Max = X,Min = X; if(Max < Y) Max = Y; if(Min > Y) Min = Y; int Max2 = 2*X,Min2 = 2*X; if(Max2 < Y) Max2 = Y; if(Min2 > Y) Min2 = Y ; if (P % 2 == 0) return (Max / Min); else return (Max2 / Min2);} // Driver codeint main(){ // 1st test case int X = 1, Y = 2, P = 1; printf(\"%d\\n\",findValue(X, Y, P)); // 2nd test case X = 3, Y = 7, P = 2; printf(\"%d\\n\",findValue(X, Y, P));} // This code is contributed by kothvvsaakash.",
"e": 2412,
"s": 1798,
"text": null
},
{
"code": "// Java program to find max(X, Y) / min(X, Y)// after P turnsimport java.util.*; class Even_odd{ public static int findValue(int X, int Y, int P) { if (P % 2 == 0) return (Math.max(X, Y) / Math.min(X, Y)); else return (Math.max(2 * X, Y) / Math.min(2 * X, Y)); } public static void main(String[] args) { // 1st test case int X = 1, Y = 2, P = 1; System.out.println(findValue(X, Y, P)); // 2nd test case X = 3; Y = 7; P = 2; System.out.print(findValue(X, Y, P)); }} //This code is contributed by rishabh_jain",
"e": 3138,
"s": 2412,
"text": null
},
{
"code": "# Python3 code to find max(X, Y) / min(X, Y)# after P turns def findValue( X , Y , P ): if P % 2 == 0: return int(max(X, Y) / min(X, Y)) else: return int(max(2 * X, Y) / min(2 * X, Y)) # Driver code# 1st test caseX = 1Y = 2P = 1print(findValue(X, Y, P)) # 2nd test caseX = 3Y = 7P = 2print((findValue(X, Y, P))) # This code is contributed by \"Sharad_Bhardwaj\".",
"e": 3520,
"s": 3138,
"text": null
},
{
"code": "// C# program to find max(X, Y) / min(X, Y)// after P turnsusing System; class GFG{ public static int findValue(int X, int Y, int P) { if (P % 2 == 0) return (Math.Max(X, Y) / Math.Min(X, Y)); else return (Math.Max(2 * X, Y) / Math.Min(2 * X, Y)); } // Driver code public static void Main() { // 1st test case int X = 1, Y = 2, P = 1; Console.WriteLine(findValue(X, Y, P)); // 2nd test case X = 3; Y = 7; P = 2; Console.WriteLine(findValue(X, Y, P)); }} //This code is contributed by vt_m",
"e": 4214,
"s": 3520,
"text": null
},
{
"code": "<?php// PHP program to find// max(X, Y) / min(X, Y)// after P turns function findValue($X, $Y, $P){ if ($P % 2 == 0) return (int)(max($X, $Y) / min($X, $Y)); else return (int)(max(2 * $X, $Y) / min(2 * $X, $Y));} // Driver code // 1st test case$X = 1;$Y = 2;$P = 1;echo findValue($X, $Y, $P), \"\\n\"; // 2nd test case$X = 3; $Y = 7; $P = 2;echo findValue($X, $Y, $P), \"\\n\"; // This code is contributed by ajit?>",
"e": 4685,
"s": 4214,
"text": null
},
{
"code": "<script> // Javascript program to find max(X, Y) / min(X, Y) // after P turns function findValue(X, Y, P) { if (P % 2 == 0) return parseInt((Math.max(X, Y) / Math.min(X, Y)), 10); else return parseInt((Math.max(2 * X, Y) / Math.min(2 * X, Y)), 10); } // 1st test case let X = 1, Y = 2, P = 1; document.write(findValue(X, Y, P) + \"</br>\"); // 2nd test case X = 3, Y = 7, P = 2; document.write(findValue(X, Y, P)); // This code is contributed by divyeshrabadiya07.</script>",
"e": 5248,
"s": 4685,
"text": null
},
{
"code": null,
"e": 5258,
"s": 5248,
"text": "Output: "
},
{
"code": null,
"e": 5262,
"s": 5258,
"text": "1\n2"
},
{
"code": null,
"e": 5284,
"s": 5262,
"text": "Time Complexity:O(1) "
},
{
"code": null,
"e": 5290,
"s": 5284,
"text": "jit_t"
},
{
"code": null,
"e": 5302,
"s": 5290,
"text": "gfg_sal_gfg"
},
{
"code": null,
"e": 5320,
"s": 5302,
"text": "divyeshrabadiya07"
},
{
"code": null,
"e": 5335,
"s": 5320,
"text": "varshagumber28"
},
{
"code": null,
"e": 5350,
"s": 5335,
"text": "kothavvsaakash"
},
{
"code": null,
"e": 5364,
"s": 5350,
"text": "number-theory"
},
{
"code": null,
"e": 5383,
"s": 5364,
"text": "School Programming"
},
{
"code": null,
"e": 5393,
"s": 5383,
"text": "Searching"
},
{
"code": null,
"e": 5403,
"s": 5393,
"text": "Searching"
},
{
"code": null,
"e": 5417,
"s": 5403,
"text": "number-theory"
},
{
"code": null,
"e": 5515,
"s": 5417,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5538,
"s": 5515,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 5557,
"s": 5538,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 5585,
"s": 5557,
"text": "Operator Overloading in C++"
},
{
"code": null,
"e": 5612,
"s": 5585,
"text": "Types of Operating Systems"
},
{
"code": null,
"e": 5632,
"s": 5612,
"text": "Polymorphism in C++"
},
{
"code": null,
"e": 5646,
"s": 5632,
"text": "Binary Search"
},
{
"code": null,
"e": 5714,
"s": 5646,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 5728,
"s": 5714,
"text": "Linear Search"
},
{
"code": null,
"e": 5784,
"s": 5728,
"text": "K'th Smallest/Largest Element in Unsorted Array | Set 1"
}
] |
Node.js – Base64 Encoding & Decoding
|
The buffer object can be encoded and decoded into Base64 string. The buffer class can be used to encode a string into a series of bytes. The Buffer.from() method takes a string as an input and converts it into Base64.
The converted bytes can be changed again into String. The toString() method is used for converting the Base64 buffer back into the string format.
Buffer.from(string, [encoding])
object.toString(encoding)
The parameters are described below:
string − This input parameter takes input for the string that will be encoded into the base64 format.
encoding − This input parameter takes input for the encoding in which string will be encoded and decoded.
Create a file with the name "base64.js" and copy the following code snippet. After creating the file, use the command "node base64.js" to run this code.
Live Demo
// Base64 Encoding Demo Example
// String data to be encoded
let string = "TutorialsPoint";
// Creating the buffer object with utf8 encoding
let bufferObj = Buffer.from(string, "utf8");
// Encoding into base64
let base64String = bufferObj.toString("base64");
// Printing the base64 encoded string
console.log("The encoded base64 string is:", base64String);
C:\home\node>> node base64.js
The encoded base64 string is: VHV0b3JpYWxzUG9pbnQ=
Live Demo
// Base64 Encoding Demo Example
// Base64 Encoded String
let base64string = "VHV0b3JpYWxzUG9pbnQ=";
// Creating the buffer object with utf8 encoding
let bufferObj = Buffer.from(base64string, "base64");
// Decoding base64 into String
let string = bufferObj.toString("utf8");
// Printing the base64 decoded string
console.log("The Decoded base64 string is:", string);
C:\home\node>> node base64.js
The Decoded base64 string is: TutorialsPoint
|
[
{
"code": null,
"e": 1405,
"s": 1187,
"text": "The buffer object can be encoded and decoded into Base64 string. The buffer class can be used to encode a string into a series of bytes. The Buffer.from() method takes a string as an input and converts it into Base64."
},
{
"code": null,
"e": 1551,
"s": 1405,
"text": "The converted bytes can be changed again into String. The toString() method is used for converting the Base64 buffer back into the string format."
},
{
"code": null,
"e": 1609,
"s": 1551,
"text": "Buffer.from(string, [encoding])\nobject.toString(encoding)"
},
{
"code": null,
"e": 1645,
"s": 1609,
"text": "The parameters are described below:"
},
{
"code": null,
"e": 1747,
"s": 1645,
"text": "string − This input parameter takes input for the string that will be encoded into the base64 format."
},
{
"code": null,
"e": 1853,
"s": 1747,
"text": "encoding − This input parameter takes input for the encoding in which string will be encoded and decoded."
},
{
"code": null,
"e": 2006,
"s": 1853,
"text": "Create a file with the name \"base64.js\" and copy the following code snippet. After creating the file, use the command \"node base64.js\" to run this code."
},
{
"code": null,
"e": 2017,
"s": 2006,
"text": " Live Demo"
},
{
"code": null,
"e": 2378,
"s": 2017,
"text": "// Base64 Encoding Demo Example\n\n// String data to be encoded\nlet string = \"TutorialsPoint\";\n\n// Creating the buffer object with utf8 encoding\nlet bufferObj = Buffer.from(string, \"utf8\");\n\n// Encoding into base64\nlet base64String = bufferObj.toString(\"base64\");\n\n// Printing the base64 encoded string\nconsole.log(\"The encoded base64 string is:\", base64String);"
},
{
"code": null,
"e": 2459,
"s": 2378,
"text": "C:\\home\\node>> node base64.js\nThe encoded base64 string is: VHV0b3JpYWxzUG9pbnQ="
},
{
"code": null,
"e": 2470,
"s": 2459,
"text": " Live Demo"
},
{
"code": null,
"e": 2840,
"s": 2470,
"text": "// Base64 Encoding Demo Example\n\n// Base64 Encoded String\nlet base64string = \"VHV0b3JpYWxzUG9pbnQ=\";\n\n// Creating the buffer object with utf8 encoding\nlet bufferObj = Buffer.from(base64string, \"base64\");\n\n// Decoding base64 into String\nlet string = bufferObj.toString(\"utf8\");\n\n// Printing the base64 decoded string\nconsole.log(\"The Decoded base64 string is:\", string);"
},
{
"code": null,
"e": 2915,
"s": 2840,
"text": "C:\\home\\node>> node base64.js\nThe Decoded base64 string is: TutorialsPoint"
}
] |
Python Bokeh – Plotting a Scatter Plot on a Graph
|
10 Jul, 2020
Bokeh is a Python interactive data visualization. It renders its plots using HTML and JavaScript. It targets modern web browsers for presentation providing elegant, concise construction of novel graphics with high-performance interactivity.
Bokeh can be used to plot a scatter plot on a graph. Plotting squares on a graph can be done using the scatter() method of the plotting module.
Syntax : scatter(parameters)
Parameters :
x : x-coordinates of the center of the glyphs
y : y-coordinates of the center of the glyphs
marker : signifies the type of the glyph
Returns : an object of class GlyphRenderer
Example 1 : In this example we will be using the default values for plotting the graph.
# importing the modulesfrom bokeh.plotting import figure, output_file, show # file to save the modeloutput_file("gfg.html") # instantiating the figure objectgraph = figure(title = "Bokeh Scatter Graph") # the points to be plottedx = [1, 2, 3, 4, 5]y = [1, 2, 3, 4, 5] # plotting the graphgraph.scatter(x, y) # displaying the modelshow(graph)
Output :
Example 2 : In this example we will be plotting multiple scatter points with various other parameters
# importing the modules from bokeh.plotting import figure, output_file, show from bokeh.palettes import magmaimport random # file to save the model output_file("gfg.html") # instantiating the figure object graph = figure(title = "Bokeh Scatter Graph") # name of the x-axis graph.xaxis.axis_label = "x-axis" # name of the y-axis graph.yaxis.axis_label = "y-axis" # points to be plottedx = [n for n in range(256)]y = [random.random() + 1 for n in range(256)]size = 10 # color value of the scatter pointscolor = magma(256) # plotting the graph graph.scatter(x, y, size = size, color = color) # displaying the model show(graph)
Output :
Data Visualization
Python Bokeh-plotting-figure-class
Python-Bokeh
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n10 Jul, 2020"
},
{
"code": null,
"e": 269,
"s": 28,
"text": "Bokeh is a Python interactive data visualization. It renders its plots using HTML and JavaScript. It targets modern web browsers for presentation providing elegant, concise construction of novel graphics with high-performance interactivity."
},
{
"code": null,
"e": 413,
"s": 269,
"text": "Bokeh can be used to plot a scatter plot on a graph. Plotting squares on a graph can be done using the scatter() method of the plotting module."
},
{
"code": null,
"e": 442,
"s": 413,
"text": "Syntax : scatter(parameters)"
},
{
"code": null,
"e": 455,
"s": 442,
"text": "Parameters :"
},
{
"code": null,
"e": 501,
"s": 455,
"text": "x : x-coordinates of the center of the glyphs"
},
{
"code": null,
"e": 547,
"s": 501,
"text": "y : y-coordinates of the center of the glyphs"
},
{
"code": null,
"e": 588,
"s": 547,
"text": "marker : signifies the type of the glyph"
},
{
"code": null,
"e": 631,
"s": 588,
"text": "Returns : an object of class GlyphRenderer"
},
{
"code": null,
"e": 719,
"s": 631,
"text": "Example 1 : In this example we will be using the default values for plotting the graph."
},
{
"code": "# importing the modulesfrom bokeh.plotting import figure, output_file, show # file to save the modeloutput_file(\"gfg.html\") # instantiating the figure objectgraph = figure(title = \"Bokeh Scatter Graph\") # the points to be plottedx = [1, 2, 3, 4, 5]y = [1, 2, 3, 4, 5] # plotting the graphgraph.scatter(x, y) # displaying the modelshow(graph)",
"e": 1089,
"s": 719,
"text": null
},
{
"code": null,
"e": 1098,
"s": 1089,
"text": "Output :"
},
{
"code": null,
"e": 1200,
"s": 1098,
"text": "Example 2 : In this example we will be plotting multiple scatter points with various other parameters"
},
{
"code": "# importing the modules from bokeh.plotting import figure, output_file, show from bokeh.palettes import magmaimport random # file to save the model output_file(\"gfg.html\") # instantiating the figure object graph = figure(title = \"Bokeh Scatter Graph\") # name of the x-axis graph.xaxis.axis_label = \"x-axis\" # name of the y-axis graph.yaxis.axis_label = \"y-axis\" # points to be plottedx = [n for n in range(256)]y = [random.random() + 1 for n in range(256)]size = 10 # color value of the scatter pointscolor = magma(256) # plotting the graph graph.scatter(x, y, size = size, color = color) # displaying the model show(graph)",
"e": 1876,
"s": 1200,
"text": null
},
{
"code": null,
"e": 1885,
"s": 1876,
"text": "Output :"
},
{
"code": null,
"e": 1904,
"s": 1885,
"text": "Data Visualization"
},
{
"code": null,
"e": 1939,
"s": 1904,
"text": "Python Bokeh-plotting-figure-class"
},
{
"code": null,
"e": 1952,
"s": 1939,
"text": "Python-Bokeh"
},
{
"code": null,
"e": 1959,
"s": 1952,
"text": "Python"
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.